org.el: New value for `org-todo-repeat-to-state'
[org-mode.git] / lisp / org.el
blob9975cd9009f5b622a5ff6777cd4960b74f7307d3
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 <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; 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-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp)
188 (defvar org-element-paragraph-separate)
190 ;; load languages based on value of `org-babel-load-languages'
191 (defvar org-babel-load-languages)
193 ;;;###autoload
194 (defun org-babel-do-load-languages (sym value)
195 "Load the languages defined in `org-babel-load-languages'."
196 (set-default sym value)
197 (dolist (pair org-babel-load-languages)
198 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
199 (if active
200 (require (intern (concat "ob-" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-execute:" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-expand-body:" lang)))))))
206 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
207 ;;;###autoload
208 (defun org-babel-load-file (file &optional compile)
209 "Load Emacs Lisp source code blocks in the Org FILE.
210 This function exports the source code using `org-babel-tangle'
211 and then loads the resulting file using `load-file'. With prefix
212 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
213 file to byte-code before it is loaded."
214 (interactive "fFile to load: \nP")
215 (let* ((age (lambda (file)
216 (float-time
217 (time-subtract (current-time)
218 (nth 5 (or (file-attributes (file-truename file))
219 (file-attributes file)))))))
220 (base-name (file-name-sans-extension file))
221 (exported-file (concat base-name ".el")))
222 ;; tangle if the Org file is newer than the elisp file
223 (unless (and (file-exists-p exported-file)
224 (> (funcall age file) (funcall age exported-file)))
225 ;; Tangle-file traversal returns reversed list of tangled files
226 ;; and we want to evaluate the first target.
227 (setq exported-file
228 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
229 (message "%s %s"
230 (if compile
231 (progn (byte-compile-file exported-file 'load)
232 "Compiled and loaded")
233 (progn (load-file exported-file) "Loaded"))
234 exported-file)))
236 (defcustom org-babel-load-languages '((emacs-lisp . t))
237 "Languages which can be evaluated in Org buffers.
238 This list can be used to load support for any of the languages
239 below, note that each language will depend on a different set of
240 system executables and/or Emacs modes. When a language is
241 \"loaded\", then code blocks in that language can be evaluated
242 with `org-babel-execute-src-block' bound by default to C-c
243 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
244 be set to remove code block evaluation from the C-c C-c
245 keybinding. By default only Emacs Lisp (which has no
246 requirements) is loaded."
247 :group 'org-babel
248 :set 'org-babel-do-load-languages
249 :version "24.1"
250 :type '(alist :tag "Babel Languages"
251 :key-type
252 (choice
253 (const :tag "Awk" awk)
254 (const :tag "C" C)
255 (const :tag "R" R)
256 (const :tag "Asymptote" asymptote)
257 (const :tag "Calc" calc)
258 (const :tag "Clojure" clojure)
259 (const :tag "CSS" css)
260 (const :tag "Ditaa" ditaa)
261 (const :tag "Dot" dot)
262 (const :tag "Ebnf2ps" ebnf2ps)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "hledger" hledger)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "Vala" vala))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (eval-and-compile
526 (defconst org-comment-string "COMMENT"
527 "Entries starting with this keyword will never be exported.
528 \\<org-mode-map>
529 An entry can be toggled between COMMENT and normal with
530 `\\[org-toggle-comment]'."))
533 ;;;; LaTeX Environments and Fragments
535 (defconst org-latex-regexps
536 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
537 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
538 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
539 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
541 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
542 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
543 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
544 "Regular expressions for matching embedded LaTeX.")
546 ;;;; Node Property
548 (defconst org-effort-property "Effort"
549 "The property that is being used to keep track of effort estimates.
550 Effort estimates given in this property need to have the format H:MM.")
552 ;;;; Table
554 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
555 "Detect an org-type or table-type table.")
557 (defconst org-table-line-regexp "^[ \t]*|"
558 "Detect an org-type table line.")
560 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
561 "Detect an org-type table line.")
563 (defconst org-table-hline-regexp "^[ \t]*|-"
564 "Detect an org-type table hline.")
566 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
567 "Detect a table-type table hline.")
569 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
570 "Detect the first line outside a table when searching from within it.
571 This works for both table types.")
573 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
574 "Detect a #+TBLFM line.")
576 ;;;; Timestamp
578 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
579 "Regular expression for fast time stamp matching.")
581 (defconst org-ts-regexp-inactive
582 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
583 "Regular expression for fast inactive time stamp matching.")
585 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
586 "Regular expression for fast time stamp matching.")
588 (defconst org-ts-regexp0
589 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.
591 This one does not require the space after the date, so it can be used
592 on a string that terminates immediately after the date.")
594 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
595 "Regular expression matching time strings for analysis.")
597 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
598 "Regular expression matching time stamps, with groups.")
600 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
601 "Regular expression matching time stamps (also [..]), with groups.")
603 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
604 "Regular expression matching a time stamp range.")
606 (defconst org-tr-regexp-both
607 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
608 "Regular expression matching a time stamp range.")
610 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
611 org-ts-regexp "\\)?")
612 "Regular expression matching a time stamp or time stamp range.")
614 (defconst org-tsr-regexp-both
615 (concat org-ts-regexp-both "\\(--?-?"
616 org-ts-regexp-both "\\)?")
617 "Regular expression matching a time stamp or time stamp range.
618 The time stamps may be either active or inactive.")
620 (defconst org-repeat-re
621 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
622 "Regular expression for specifying repeated events.
623 After a match, group 1 contains the repeat expression.")
625 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
626 "Formats for `format-time-string' which are used for time stamps.")
629 ;;; The custom variables
631 (defgroup org nil
632 "Outline-based notes management and organizer."
633 :tag "Org"
634 :group 'outlines
635 :group 'calendar)
637 (defcustom org-mode-hook nil
638 "Mode hook for Org mode, run after the mode was turned on."
639 :group 'org
640 :type 'hook)
642 (defcustom org-load-hook nil
643 "Hook that is run after org.el has been loaded."
644 :group 'org
645 :type 'hook)
647 (defcustom org-log-buffer-setup-hook nil
648 "Hook that is run after an Org log buffer is created."
649 :group 'org
650 :version "24.1"
651 :type 'hook)
653 (defvar org-modules) ; defined below
654 (defvar org-modules-loaded nil
655 "Have the modules been loaded already?")
657 (defun org-load-modules-maybe (&optional force)
658 "Load all extensions listed in `org-modules'."
659 (when (or force (not org-modules-loaded))
660 (dolist (ext org-modules)
661 (condition-case nil (require ext)
662 (error (message "Problems while trying to load feature `%s'" ext))))
663 (setq org-modules-loaded t)))
665 (defun org-set-modules (var value)
666 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (set var value)
668 (when (featurep 'org)
669 (org-load-modules-maybe 'force)
670 (org-element-cache-reset 'all)))
672 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
673 "Modules that should always be loaded together with org.el.
675 If a description starts with <C>, the file is not part of Emacs
676 and loading it will require that you have downloaded and properly
677 installed the Org mode distribution.
679 You can also use this system to load external packages (i.e. neither Org
680 core modules, nor modules from the CONTRIB directory). Just add symbols
681 to the end of the list. If the package is called org-xyz.el, then you need
682 to add the symbol `xyz', and the package must have a call to:
684 (provide \\='org-xyz)
686 For export specific modules, see also `org-export-backends'."
687 :group 'org
688 :set 'org-set-modules
689 :version "24.4"
690 :package-version '(Org . "8.0")
691 :type
692 '(set :greedy t
693 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
694 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
695 (const :tag " crypt: Encryption of subtrees" org-crypt)
696 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
697 (const :tag " docview: Links to doc-view buffers" org-docview)
698 (const :tag " eww: Store link to url of eww" org-eww)
699 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
700 (const :tag " habit: Track your consistency with habits" org-habit)
701 (const :tag " id: Global IDs for identifying entries" org-id)
702 (const :tag " info: Links to Info nodes" org-info)
703 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
704 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
705 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
706 (const :tag " mouse: Additional mouse support" org-mouse)
707 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
708 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
709 (const :tag " tempo: Fast completion for structures" org-tempo)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
923 This can also be configured on a per-file basis by adding one of
924 the following lines anywhere in the buffer:
926 #+STARTUP: fold (or `overview', this is equivalent)
927 #+STARTUP: nofold (or `showall', this is equivalent)
928 #+STARTUP: content
929 #+STARTUP: showeverything
931 Set `org-agenda-inhibit-startup' to a non-nil value if you want
932 to ignore this option when Org opens agenda files for the first
933 time."
934 :group 'org-startup
935 :type '(choice
936 (const :tag "nofold: show all" nil)
937 (const :tag "fold: overview" t)
938 (const :tag "content: all headlines" content)
939 (const :tag "show everything, even drawers" showeverything)))
941 (defcustom org-startup-truncated t
942 "Non-nil means entering Org mode will set `truncate-lines'.
943 This is useful since some lines containing links can be very long and
944 uninteresting. Also tables look terrible when wrapped.
946 The variable `org-startup-truncated' allows to configure
947 truncation for Org mode different to the other modes that use the
948 variable `truncate-lines' and as a shortcut instead of putting
949 the variable `truncate-lines' into the `org-mode-hook'. If one
950 wants to configure truncation for Org mode not statically but
951 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
952 the variable `truncate-lines' has to be used because in such a
953 case it is too late to set the variable `org-startup-truncated'."
954 :group 'org-startup
955 :type 'boolean)
957 (defcustom org-startup-indented nil
958 "Non-nil means turn on `org-indent-mode' on startup.
959 This can also be configured on a per-file basis by adding one of
960 the following lines anywhere in the buffer:
962 #+STARTUP: indent
963 #+STARTUP: noindent"
964 :group 'org-structure
965 :type '(choice
966 (const :tag "Not" nil)
967 (const :tag "Globally (slow on startup in large files)" t)))
969 (defcustom org-use-sub-superscripts t
970 "Non-nil means interpret \"_\" and \"^\" for display.
972 If you want to control how Org exports those characters, see
973 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
974 used to be an alias for `org-export-with-sub-superscripts' in
975 Org <8.0, it is not anymore.
977 When this option is turned on, you can use TeX-like syntax for
978 sub- and superscripts within the buffer. Several characters after
979 \"_\" or \"^\" will be considered as a single item - so grouping
980 with {} is normally not needed. For example, the following things
981 will be parsed as single sub- or superscripts:
983 10^24 or 10^tau several digits will be considered 1 item.
984 10^-12 or 10^-tau a leading sign with digits or a word
985 x^2-y^3 will be read as x^2 - y^3, because items are
986 terminated by almost any nonword/nondigit char.
987 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
989 Still, ambiguity is possible. So when in doubt, use {} to enclose
990 the sub/superscript. If you set this variable to the symbol `{}',
991 the braces are *required* in order to trigger interpretations as
992 sub/superscript. This can be helpful in documents that need \"_\"
993 frequently in plain text."
994 :group 'org-startup
995 :version "24.4"
996 :package-version '(Org . "8.0")
997 :type '(choice
998 (const :tag "Always interpret" t)
999 (const :tag "Only with braces" {})
1000 (const :tag "Never interpret" nil)))
1002 (defcustom org-startup-with-beamer-mode nil
1003 "Non-nil means turn on `org-beamer-mode' on startup.
1004 This can also be configured on a per-file basis by adding one of
1005 the following lines anywhere in the buffer:
1007 #+STARTUP: beamer"
1008 :group 'org-startup
1009 :version "24.1"
1010 :type 'boolean)
1012 (defcustom org-startup-align-all-tables nil
1013 "Non-nil means align all tables when visiting a file.
1014 This can also be configured on a per-file basis by adding one of
1015 the following lines anywhere in the buffer:
1016 #+STARTUP: align
1017 #+STARTUP: noalign"
1018 :group 'org-startup
1019 :type 'boolean)
1021 (defcustom org-startup-shrink-all-tables nil
1022 "Non-nil means shrink all table columns with a width cookie.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: shrink"
1026 :group 'org-startup
1027 :type 'boolean
1028 :version "27.1"
1029 :package-version '(Org . "9.2")
1030 :safe #'booleanp)
1032 (defcustom org-startup-with-inline-images nil
1033 "Non-nil means show inline images when loading a new Org file.
1034 This can also be configured on a per-file basis by adding one of
1035 the following lines anywhere in the buffer:
1036 #+STARTUP: inlineimages
1037 #+STARTUP: noinlineimages"
1038 :group 'org-startup
1039 :version "24.1"
1040 :type 'boolean)
1042 (defcustom org-startup-with-latex-preview nil
1043 "Non-nil means preview LaTeX fragments when loading a new Org file.
1045 This can also be configured on a per-file basis by adding one of
1046 the following lines anywhere in the buffer:
1047 #+STARTUP: latexpreview
1048 #+STARTUP: nolatexpreview"
1049 :group 'org-startup
1050 :version "24.4"
1051 :package-version '(Org . "8.0")
1052 :type 'boolean)
1054 (defcustom org-insert-mode-line-in-empty-file nil
1055 "Non-nil means insert the first line setting Org mode in empty files.
1056 When the function `org-mode' is called interactively in an empty file, this
1057 normally means that the file name does not automatically trigger Org mode.
1058 To ensure that the file will always be in Org mode in the future, a
1059 line enforcing Org mode will be inserted into the buffer, if this option
1060 has been set."
1061 :group 'org-startup
1062 :type 'boolean)
1064 (defcustom org-replace-disputed-keys nil
1065 "Non-nil means use alternative key bindings for some keys.
1066 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1067 These keys are also used by other packages like shift-selection-mode'
1068 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1069 If you want to use Org mode together with one of these other modes,
1070 or more generally if you would like to move some Org mode commands to
1071 other keys, set this variable and configure the keys with the variable
1072 `org-disputed-keys'.
1074 This option is only relevant at load-time of Org mode, and must be set
1075 *before* org.el is loaded. Changing it requires a restart of Emacs to
1076 become effective."
1077 :group 'org-startup
1078 :type 'boolean)
1080 (defcustom org-use-extra-keys nil
1081 "Non-nil means use extra key sequence definitions for certain commands.
1082 This happens automatically if `window-system' is nil. This
1083 variable lets you do the same manually. You must set it before
1084 loading Org."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1090 (defcustom org-disputed-keys
1091 '(([(shift up)] . [(meta p)])
1092 ([(shift down)] . [(meta n)])
1093 ([(shift left)] . [(meta -)])
1094 ([(shift right)] . [(meta +)])
1095 ([(control shift right)] . [(meta shift +)])
1096 ([(control shift left)] . [(meta shift -)]))
1097 "Keys for which Org mode and other modes compete.
1098 This is an alist, cars are the default keys, second element specifies
1099 the alternative to use when `org-replace-disputed-keys' is t.
1101 Keys can be specified in any syntax supported by `define-key'.
1102 The value of this option takes effect only at Org mode startup,
1103 therefore you'll have to restart Emacs to apply it after changing."
1104 :group 'org-startup
1105 :type 'alist)
1107 (defun org-key (key)
1108 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1109 Or return the original if not disputed."
1110 (when org-replace-disputed-keys
1111 (let* ((nkey (key-description key))
1112 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1113 org-disputed-keys)))
1114 (setq key (if x (cdr x) key))))
1115 key)
1117 (defun org-defkey (keymap key def)
1118 "Define a key, possibly translated, as returned by `org-key'."
1119 (define-key keymap (org-key key) def))
1121 (defcustom org-ellipsis nil
1122 "The ellipsis to use in the Org mode outline.
1124 When nil, just use the standard three dots. When a non-empty string,
1125 use that string instead.
1127 The change affects only Org mode (which will then use its own display table).
1128 Changing this requires executing `\\[org-mode]' in a buffer to become
1129 effective."
1130 :group 'org-startup
1131 :type '(choice (const :tag "Default" nil)
1132 (string :tag "String" :value "...#"))
1133 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1135 (defvar org-display-table nil
1136 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1138 (defgroup org-keywords nil
1139 "Keywords in Org mode."
1140 :tag "Org Keywords"
1141 :group 'org)
1143 (defcustom org-closed-keep-when-no-todo nil
1144 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1145 :group 'org-todo
1146 :group 'org-keywords
1147 :version "24.4"
1148 :package-version '(Org . "8.0")
1149 :type 'boolean)
1151 (defgroup org-structure nil
1152 "Options concerning the general structure of Org files."
1153 :tag "Org Structure"
1154 :group 'org)
1156 (defgroup org-reveal-location nil
1157 "Options about how to make context of a location visible."
1158 :tag "Org Reveal Location"
1159 :group 'org-structure)
1161 (defcustom org-show-context-detail '((agenda . local)
1162 (bookmark-jump . lineage)
1163 (isearch . lineage)
1164 (default . ancestors))
1165 "Alist between context and visibility span when revealing a location.
1167 \\<org-mode-map>Some actions may move point into invisible
1168 locations. As a consequence, Org always expose a neighborhood
1169 around point. How much is shown depends on the initial action,
1170 or context. Valid contexts are
1172 agenda when exposing an entry from the agenda
1173 org-goto when using the command `org-goto' (`\\[org-goto]')
1174 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1175 tags-tree when constructing a sparse tree based on tags matches
1176 link-search when exposing search matches associated with a link
1177 mark-goto when exposing the jump goal of a mark
1178 bookmark-jump when exposing a bookmark location
1179 isearch when exiting from an incremental search
1180 default default for all contexts not set explicitly
1182 Allowed visibility spans are
1184 minimal show current headline; if point is not on headline,
1185 also show entry
1187 local show current headline, entry and next headline
1189 ancestors show current headline and its direct ancestors; if
1190 point is not on headline, also show entry
1192 lineage show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and first child
1196 tree show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and all children
1200 canonical show current headline, its direct ancestors along with
1201 their entries and children; if point is not located on
1202 the headline, also show current entry and all children
1204 As special cases, a nil or t value means show all contexts in
1205 `minimal' or `canonical' view, respectively.
1207 Some views can make displayed information very compact, but also
1208 make it harder to edit the location of the match. In such
1209 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1210 more context."
1211 :group 'org-reveal-location
1212 :version "26.1"
1213 :package-version '(Org . "9.0")
1214 :type '(choice
1215 (const :tag "Canonical" t)
1216 (const :tag "Minimal" nil)
1217 (repeat :greedy t :tag "Individual contexts"
1218 (cons
1219 (choice :tag "Context"
1220 (const agenda)
1221 (const org-goto)
1222 (const occur-tree)
1223 (const tags-tree)
1224 (const link-search)
1225 (const mark-goto)
1226 (const bookmark-jump)
1227 (const isearch)
1228 (const default))
1229 (choice :tag "Detail level"
1230 (const minimal)
1231 (const local)
1232 (const ancestors)
1233 (const lineage)
1234 (const tree)
1235 (const canonical))))))
1237 (defcustom org-indirect-buffer-display 'other-window
1238 "How should indirect tree buffers be displayed?
1240 This applies to indirect buffers created with the commands
1241 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1243 Valid values are:
1244 current-window Display in the current window
1245 other-window Just display in another window.
1246 dedicated-frame Create one new frame, and re-use it each time.
1247 new-frame Make a new frame each time. Note that in this case
1248 previously-made indirect buffers are kept, and you need to
1249 kill these buffers yourself."
1250 :group 'org-structure
1251 :group 'org-agenda-windows
1252 :type '(choice
1253 (const :tag "In current window" current-window)
1254 (const :tag "In current frame, other window" other-window)
1255 (const :tag "Each time a new frame" new-frame)
1256 (const :tag "One dedicated frame" dedicated-frame)))
1258 (defcustom org-use-speed-commands nil
1259 "Non-nil means activate single letter commands at beginning of a headline.
1260 This may also be a function to test for appropriate locations where speed
1261 commands should be active.
1263 For example, to activate speed commands when the point is on any
1264 star at the beginning of the headline, you can do this:
1266 (setq org-use-speed-commands
1267 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1268 :group 'org-structure
1269 :type '(choice
1270 (const :tag "Never" nil)
1271 (const :tag "At beginning of headline stars" t)
1272 (function)))
1274 (defcustom org-speed-commands-user nil
1275 "Alist of additional speed commands.
1276 This list will be checked before `org-speed-commands-default'
1277 when the variable `org-use-speed-commands' is non-nil
1278 and when the cursor is at the beginning of a headline.
1279 The car of each entry is a string with a single letter, which must
1280 be assigned to `self-insert-command' in the global map.
1281 The cdr is either a command to be called interactively, a function
1282 to be called, or a form to be evaluated.
1283 An entry that is just a list with a single string will be interpreted
1284 as a descriptive headline that will be added when listing the speed
1285 commands in the Help buffer using the `?' speed command."
1286 :group 'org-structure
1287 :type '(repeat :value ("k" . ignore)
1288 (choice :value ("k" . ignore)
1289 (list :tag "Descriptive Headline" (string :tag "Headline"))
1290 (cons :tag "Letter and Command"
1291 (string :tag "Command letter")
1292 (choice
1293 (function)
1294 (sexp))))))
1296 (defcustom org-bookmark-names-plist
1297 '(:last-capture "org-capture-last-stored"
1298 :last-refile "org-refile-last-stored"
1299 :last-capture-marker "org-capture-last-stored-marker")
1300 "Names for bookmarks automatically set by some Org commands.
1301 This can provide strings as names for a number of bookmarks Org sets
1302 automatically. The following keys are currently implemented:
1303 :last-capture
1304 :last-capture-marker
1305 :last-refile
1306 When a key does not show up in the property list, the corresponding bookmark
1307 is not set."
1308 :group 'org-structure
1309 :type 'plist)
1311 (defgroup org-cycle nil
1312 "Options concerning visibility cycling in Org mode."
1313 :tag "Org Cycle"
1314 :group 'org-structure)
1316 (defcustom org-cycle-skip-children-state-if-no-children t
1317 "Non-nil means skip CHILDREN state in entries that don't have any."
1318 :group 'org-cycle
1319 :type 'boolean)
1321 (defcustom org-cycle-max-level nil
1322 "Maximum level which should still be subject to visibility cycling.
1323 Levels higher than this will, for cycling, be treated as text, not a headline.
1324 When `org-odd-levels-only' is set, a value of N in this variable actually
1325 means 2N-1 stars as the limiting headline.
1326 When nil, cycle all levels.
1327 Note that the limiting level of cycling is also influenced by
1328 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1329 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1330 than its value."
1331 :group 'org-cycle
1332 :type '(choice
1333 (const :tag "No limit" nil)
1334 (integer :tag "Maximum level")))
1336 (defcustom org-hide-block-startup nil
1337 "Non-nil means entering Org mode will fold all blocks.
1338 This can also be set in on a per-file basis with
1340 #+STARTUP: hideblocks
1341 #+STARTUP: showblocks"
1342 :group 'org-startup
1343 :group 'org-cycle
1344 :type 'boolean)
1346 (defcustom org-cycle-global-at-bob nil
1347 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1349 This makes it possible to do global cycling without having to use `S-TAB'
1350 or `\\[universal-argument] TAB'. For this special case to work, the first \
1351 line of the buffer
1352 must not be a headline -- it may be empty or some other text.
1354 When used in this way, `org-cycle-hook' is disabled temporarily to make
1355 sure the cursor stays at the beginning of the buffer.
1357 When this option is nil, don't do anything special at the beginning of
1358 the buffer."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-level-after-item/entry-creation t
1363 "Non-nil means cycle entry level or item indentation in new empty entries.
1365 When the cursor is at the end of an empty headline, i.e., with only stars
1366 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1367 and then all possible ancestor states, before returning to the original state.
1368 This makes data entry extremely fast: M-RET to create a new headline,
1369 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1371 When the cursor is at the end of an empty plain list item, one TAB will
1372 make it a subitem, two or more tabs will back up to make this an item
1373 higher up in the item hierarchy."
1374 :group 'org-cycle
1375 :type 'boolean)
1377 (defcustom org-cycle-emulate-tab t
1378 "Where should `org-cycle' emulate TAB.
1379 nil Never
1380 white Only in completely white lines
1381 whitestart Only at the beginning of lines, before the first non-white char
1382 t Everywhere except in headlines
1383 exc-hl-bol Everywhere except at the start of a headline
1384 If TAB is used in a place where it does not emulate TAB, the current subtree
1385 visibility is cycled."
1386 :group 'org-cycle
1387 :type '(choice (const :tag "Never" nil)
1388 (const :tag "Only in completely white lines" white)
1389 (const :tag "Before first char in a line" whitestart)
1390 (const :tag "Everywhere except in headlines" t)
1391 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1393 (defcustom org-cycle-separator-lines 2
1394 "Number of empty lines needed to keep an empty line between collapsed trees.
1395 If you leave an empty line between the end of a subtree and the following
1396 headline, this empty line is hidden when the subtree is folded.
1397 Org mode will leave (exactly) one empty line visible if the number of
1398 empty lines is equal or larger to the number given in this variable.
1399 So the default 2 means at least 2 empty lines after the end of a subtree
1400 are needed to produce free space between a collapsed subtree and the
1401 following headline.
1403 If the number is negative, and the number of empty lines is at least -N,
1404 all empty lines are shown.
1406 Special case: when 0, never leave empty lines in collapsed view."
1407 :group 'org-cycle
1408 :type 'integer)
1409 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1411 (defcustom org-pre-cycle-hook nil
1412 "Hook that is run before visibility cycling is happening.
1413 The function(s) in this hook must accept a single argument which indicates
1414 the new state that will be set right after running this hook. The
1415 argument is a symbol. Before a global state change, it can have the values
1416 `overview', `content', or `all'. Before a local state change, it can have
1417 the values `folded', `children', or `subtree'."
1418 :group 'org-cycle
1419 :type 'hook)
1421 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1422 org-cycle-hide-drawers
1423 org-cycle-show-empty-lines
1424 org-optimize-window-after-visibility-change)
1425 "Hook that is run after `org-cycle' has changed the buffer visibility.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that was set by the most recent `org-cycle' command. The
1428 argument is a symbol. After a global state change, it can have the values
1429 `overview', `contents', or `all'. After a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook
1433 :version "26.1"
1434 :package-version '(Org . "8.3"))
1436 (defgroup org-edit-structure nil
1437 "Options concerning structure editing in Org mode."
1438 :tag "Org Edit Structure"
1439 :group 'org-structure)
1441 (defcustom org-odd-levels-only nil
1442 "Non-nil means skip even levels and only use odd levels for the outline.
1443 This has the effect that two stars are being added/taken away in
1444 promotion/demotion commands. It also influences how levels are
1445 handled by the exporters.
1446 Changing it requires restart of `font-lock-mode' to become effective
1447 for fontification also in regions already fontified.
1448 You may also set this on a per-file basis by adding one of the following
1449 lines to the buffer:
1451 #+STARTUP: odd
1452 #+STARTUP: oddeven"
1453 :group 'org-edit-structure
1454 :group 'org-appearance
1455 :type 'boolean)
1457 (defcustom org-adapt-indentation t
1458 "Non-nil means adapt indentation to outline node level.
1460 When this variable is set, Org assumes that you write outlines by
1461 indenting text in each node to align with the headline (after the
1462 stars). The following issues are influenced by this variable:
1464 - The indentation is increased by one space in a demotion
1465 command, and decreased by one in a promotion command. However,
1466 in the latter case, if shifting some line in the entry body
1467 would alter document structure (e.g., insert a new headline),
1468 indentation is not changed at all.
1470 - Property drawers and planning information is inserted indented
1471 when this variable is set. When nil, they will not be indented.
1473 - TAB indents a line relative to current level. The lines below
1474 a headline will be indented when this variable is set.
1476 Note that this is all about true indentation, by adding and
1477 removing space characters. See also \"org-indent.el\" which does
1478 level-dependent indentation in a virtual way, i.e. at display
1479 time in Emacs."
1480 :group 'org-edit-structure
1481 :type 'boolean
1482 :safe #'booleanp)
1484 (defcustom org-special-ctrl-a/e nil
1485 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1487 When t, `C-a' will bring back the cursor to the beginning of the
1488 headline text, i.e. after the stars and after a possible TODO
1489 keyword. In an item, this will be the position after bullet and
1490 check-box, if any. When the cursor is already at that position,
1491 another `C-a' will bring it to the beginning of the line.
1493 `C-e' will jump to the end of the headline, ignoring the presence
1494 of tags in the headline. A second `C-e' will then jump to the
1495 true end of the line, after any tags. This also means that, when
1496 this variable is non-nil, `C-e' also will never jump beyond the
1497 end of the heading of a folded section, i.e. not after the
1498 ellipses.
1500 When set to the symbol `reversed', the first `C-a' or `C-e' works
1501 normally, going to the true line boundary first. Only a directly
1502 following, identical keypress will bring the cursor to the
1503 special positions.
1505 This may also be a cons cell where the behavior for `C-a' and
1506 `C-e' is set separately."
1507 :group 'org-edit-structure
1508 :type '(choice
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet and before tags first" t)
1511 (const :tag "reversed: true line boundary first" reversed)
1512 (cons :tag "Set C-a and C-e separately"
1513 (choice :tag "Special C-a"
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet first" t)
1516 (const :tag "reversed: before stars/bullet first" reversed))
1517 (choice :tag "Special C-e"
1518 (const :tag "off" nil)
1519 (const :tag "on: before tags first" t)
1520 (const :tag "reversed: after tags first" reversed)))))
1521 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1523 (defcustom org-special-ctrl-k nil
1524 "Non-nil means `C-k' will behave specially in headlines.
1525 When nil, `C-k' will call the default `kill-line' command.
1526 When t, the following will happen while the cursor is in the headline:
1528 - When the cursor is at the beginning of a headline, kill the entire
1529 line and possible the folded subtree below the line.
1530 - When in the middle of the headline text, kill the headline up to the tags.
1531 - When after the headline text, kill the tags."
1532 :group 'org-edit-structure
1533 :type 'boolean)
1535 (defcustom org-ctrl-k-protect-subtree nil
1536 "Non-nil means, do not delete a hidden subtree with C-k.
1537 When set to the symbol `error', simply throw an error when C-k is
1538 used to kill (part-of) a headline that has hidden text behind it.
1539 Any other non-nil value will result in a query to the user, if it is
1540 OK to kill that hidden subtree. When nil, kill without remorse."
1541 :group 'org-edit-structure
1542 :version "24.1"
1543 :type '(choice
1544 (const :tag "Do not protect hidden subtrees" nil)
1545 (const :tag "Protect hidden subtrees with a security query" t)
1546 (const :tag "Never kill a hidden subtree with C-k" error)))
1548 (defcustom org-special-ctrl-o t
1549 "Non-nil means, make `C-o' insert a row in tables."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-catch-invisible-edits nil
1554 "Check if in invisible region before inserting or deleting a character.
1555 Valid values are:
1557 nil Do not check, so just do invisible edits.
1558 error Throw an error and do nothing.
1559 show Make point visible, and do the requested edit.
1560 show-and-error Make point visible, then throw an error and abort the edit.
1561 smart Make point visible, and do insertion/deletion if it is
1562 adjacent to visible text and the change feels predictable.
1563 Never delete a previously invisible character or add in the
1564 middle or right after an invisible region. Basically, this
1565 allows insertion and backward-delete right before ellipses.
1566 FIXME: maybe in this case we should not even show?"
1567 :group 'org-edit-structure
1568 :version "24.1"
1569 :type '(choice
1570 (const :tag "Do not check" nil)
1571 (const :tag "Throw error when trying to edit" error)
1572 (const :tag "Unhide, but do not do the edit" show-and-error)
1573 (const :tag "Show invisible part and do the edit" show)
1574 (const :tag "Be smart and do the right thing" smart)))
1576 (defcustom org-yank-folded-subtrees t
1577 "Non-nil means when yanking subtrees, fold them.
1578 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1579 it starts with a heading and all other headings in it are either children
1580 or siblings, then fold all the subtrees. However, do this only if no
1581 text after the yank would be swallowed into a folded tree by this action."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-yank-adjusted-subtrees nil
1586 "Non-nil means when yanking subtrees, adjust the level.
1587 With this setting, `org-paste-subtree' is used to insert the subtree, see
1588 this function for details."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-M-RET-may-split-line '((default . t))
1593 "Non-nil means M-RET will split the line at the cursor position.
1594 When nil, it will go to the end of the line before making a
1595 new line.
1596 You may also set this option in a different way for different
1597 contexts. Valid contexts are:
1599 headline when creating a new headline
1600 item when creating a new item
1601 table in a table field
1602 default the value to be used for all contexts not explicitly
1603 customized"
1604 :group 'org-structure
1605 :group 'org-table
1606 :type '(choice
1607 (const :tag "Always" t)
1608 (const :tag "Never" nil)
1609 (repeat :greedy t :tag "Individual contexts"
1610 (cons
1611 (choice :tag "Context"
1612 (const headline)
1613 (const item)
1614 (const table)
1615 (const default))
1616 (boolean)))))
1619 (defcustom org-insert-heading-respect-content nil
1620 "Non-nil means insert new headings after the current subtree.
1621 \\<org-mode-map>
1622 When nil, the new heading is created directly after the current line.
1623 The commands `\\[org-insert-heading-respect-content]' and \
1624 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1625 for the duration of the command."
1626 :group 'org-structure
1627 :type 'boolean)
1629 (defcustom org-blank-before-new-entry '((heading . auto)
1630 (plain-list-item . auto))
1631 "Should `org-insert-heading' leave a blank line before new heading/item?
1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
1633 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1634 which case Org will look at the surrounding headings/items and try to
1635 make an intelligent decision whether to insert a blank line or not."
1636 :group 'org-edit-structure
1637 :type '(list
1638 (cons (const heading)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))
1642 (cons (const plain-list-item)
1643 (choice (const :tag "Never" nil)
1644 (const :tag "Always" t)
1645 (const :tag "Auto" auto)))))
1647 (defcustom org-insert-heading-hook nil
1648 "Hook being run after inserting a new heading."
1649 :group 'org-edit-structure
1650 :type 'hook)
1652 (defcustom org-enable-fixed-width-editor t
1653 "Non-nil means lines starting with \":\" are treated as fixed-width.
1654 This currently only means they are never auto-wrapped.
1655 When nil, such lines will be treated like ordinary lines."
1656 :group 'org-edit-structure
1657 :type 'boolean)
1659 (defgroup org-sparse-trees nil
1660 "Options concerning sparse trees in Org mode."
1661 :tag "Org Sparse Trees"
1662 :group 'org-structure)
1664 (defcustom org-highlight-sparse-tree-matches t
1665 "Non-nil means highlight all matches that define a sparse tree.
1666 The highlights will automatically disappear the next time the buffer is
1667 changed by an edit command."
1668 :group 'org-sparse-trees
1669 :type 'boolean)
1671 (defcustom org-remove-highlights-with-change t
1672 "Non-nil means any change to the buffer will remove temporary highlights.
1673 \\<org-mode-map>\
1674 Such highlights are created by `org-occur' and `org-clock-display'.
1675 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1676 to get rid of the highlights.
1677 The highlights created by `org-toggle-latex-fragment' always need
1678 `\\[org-toggle-latex-fragment]' to be removed."
1679 :group 'org-sparse-trees
1680 :group 'org-time
1681 :type 'boolean)
1683 (defcustom org-occur-case-fold-search t
1684 "Non-nil means `org-occur' should be case-insensitive.
1685 If set to `smart' the search will be case-insensitive only if it
1686 doesn't specify any upper case character."
1687 :group 'org-sparse-trees
1688 :version "26.1"
1689 :type '(choice
1690 (const :tag "Case-sensitive" nil)
1691 (const :tag "Case-insensitive" t)
1692 (const :tag "Case-insensitive for lower case searches only" smart)))
1694 (defcustom org-occur-hook '(org-first-headline-recenter)
1695 "Hook that is run after `org-occur' has constructed a sparse tree.
1696 This can be used to recenter the window to show as much of the structure
1697 as possible."
1698 :group 'org-sparse-trees
1699 :type 'hook)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-self-insert-cluster-for-undo nil
1707 "Non-nil means cluster self-insert commands for undo when possible.
1708 If this is set, then, like in the Emacs command loop, 20 consecutive
1709 characters will be undone together.
1710 This is configurable, because there is some impact on typing performance."
1711 :group 'org-table
1712 :type 'boolean)
1714 (defcustom org-table-tab-recognizes-table.el t
1715 "Non-nil means TAB will automatically notice a table.el table.
1716 When it sees such a table, it moves point into it and - if necessary -
1717 calls `table-recognize-table'."
1718 :group 'org-table-editing
1719 :type 'boolean)
1721 (defgroup org-link nil
1722 "Options concerning links in Org mode."
1723 :tag "Org Link"
1724 :group 'org)
1726 (defvar-local org-link-abbrev-alist-local nil
1727 "Buffer-local version of `org-link-abbrev-alist', which see.
1728 The value of this is taken from the #+LINK lines.")
1730 (defcustom org-link-parameters
1731 '(("doi" :follow org--open-doi-link)
1732 ("elisp" :follow org--open-elisp-link)
1733 ("file" :complete org-file-complete-link)
1734 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1735 ("help" :follow org--open-help-link)
1736 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1737 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1738 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1739 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1740 ("shell" :follow org--open-shell-link))
1741 "An alist of properties that defines all the links in Org mode.
1742 The key in each association is a string of the link type.
1743 Subsequent optional elements make up a p-list of link properties.
1745 :follow - A function that takes the link path as an argument.
1747 :export - A function that takes the link path, description and
1748 export-backend as arguments.
1750 :store - A function responsible for storing the link. See the
1751 function `org-store-link-functions'.
1753 :complete - A function that inserts a link with completion. The
1754 function takes one optional prefix arg.
1756 :face - A face for the link, or a function that returns a face.
1757 The function takes one argument which is the link path. The
1758 default face is `org-link'.
1760 :mouse-face - The mouse-face. The default is `highlight'.
1762 :display - `full' will not fold the link in descriptive
1763 display. Default is `org-link'.
1765 :help-echo - A string or function that takes (window object position)
1766 as arguments and returns a string.
1768 :keymap - A keymap that is active on the link. The default is
1769 `org-mouse-map'.
1771 :htmlize-link - A function for the htmlize-link. Defaults
1772 to (list :uri \"type:path\")
1774 :activate-func - A function to run at the end of font-lock
1775 activation. The function must accept (link-start link-end path bracketp)
1776 as arguments."
1777 :group 'org-link
1778 :type '(alist :tag "Link display parameters"
1779 :value-type plist)
1780 :version "26.1"
1781 :package-version '(Org . "9.1"))
1783 (defun org-link-get-parameter (type key)
1784 "Get TYPE link property for KEY.
1785 TYPE is a string and KEY is a plist keyword."
1786 (plist-get
1787 (cdr (assoc type org-link-parameters))
1788 key))
1790 (defun org-link-set-parameters (type &rest parameters)
1791 "Set link TYPE properties to PARAMETERS.
1792 PARAMETERS should be :key val pairs."
1793 (let ((data (assoc type org-link-parameters)))
1794 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1795 (push (cons type parameters) org-link-parameters)
1796 (org-make-link-regexps)
1797 (org-element-update-syntax))))
1799 (defun org-link-types ()
1800 "Return a list of known link types."
1801 (mapcar #'car org-link-parameters))
1803 (defcustom org-link-abbrev-alist nil
1804 "Alist of link abbreviations.
1805 The car of each element is a string, to be replaced at the start of a link.
1806 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1807 links in Org buffers can have an optional tag after a double colon, e.g.,
1809 [[linkkey:tag][description]]
1811 The `linkkey' must be a single word, starting with a letter, followed
1812 by letters, numbers, `-' or `_'.
1814 If REPLACE is a string, the tag will simply be appended to create the link.
1815 If the string contains \"%s\", the tag will be inserted there. If the string
1816 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1817 at that point (see the function `url-hexify-string'). If the string contains
1818 the specifier \"%(my-function)\", then the custom function `my-function' will
1819 be invoked: this function takes the tag as its only argument and must return
1820 a string.
1822 REPLACE may also be a function that will be called with the tag as the
1823 only argument to create the link, which should be returned as a string.
1825 See the manual for examples."
1826 :group 'org-link
1827 :type '(repeat
1828 (cons
1829 (string :tag "Protocol")
1830 (choice
1831 (string :tag "Format")
1832 (function)))))
1834 (defcustom org-descriptive-links t
1835 "Non-nil means Org will display descriptive links.
1836 E.g. [[http://orgmode.org][Org website]] will be displayed as
1837 \"Org Website\", hiding the link itself and just displaying its
1838 description. When set to nil, Org will display the full links
1839 literally.
1841 You can interactively set the value of this variable by calling
1842 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1843 :group 'org-link
1844 :type 'boolean)
1846 (defcustom org-link-file-path-type 'adaptive
1847 "How the path name in file links should be stored.
1848 Valid values are:
1850 relative Relative to the current directory, i.e. the directory of the file
1851 into which the link is being inserted.
1852 absolute Absolute path, if possible with ~ for home directory.
1853 noabbrev Absolute path, no abbreviation of home directory.
1854 adaptive Use relative path for files in the current directory and sub-
1855 directories of it. For other files, use an absolute path."
1856 :group 'org-link
1857 :type '(choice
1858 (const relative)
1859 (const absolute)
1860 (const noabbrev)
1861 (const adaptive)))
1863 (defvaralias 'org-activate-links 'org-highlight-links)
1864 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1865 "Types of links that should be highlighted in Org files.
1867 This is a list of symbols, each one of them leading to the
1868 highlighting of a certain link type.
1870 You can still open links that are not highlighted.
1872 In principle, it does not hurt to turn on highlighting for all
1873 link types. There may be a small gain when turning off unused
1874 link types. The types are:
1876 bracket The recommended [[link][description]] or [[link]] links with hiding.
1877 angle Links in angular brackets that may contain whitespace like
1878 <bbdb:Carsten Dominik>.
1879 plain Plain links in normal text, no whitespace, like http://google.com.
1880 radio Text that is matched by a radio target, see manual for details.
1881 tag Tag settings in a headline (link to tag search).
1882 date Time stamps (link to calendar).
1883 footnote Footnote labels.
1885 If you set this variable during an Emacs session, use `org-mode-restart'
1886 in the Org buffer so that the change takes effect."
1887 :group 'org-link
1888 :group 'org-appearance
1889 :type '(set :greedy t
1890 (const :tag "Double bracket links" bracket)
1891 (const :tag "Angular bracket links" angle)
1892 (const :tag "Plain text links" plain)
1893 (const :tag "Radio target matches" radio)
1894 (const :tag "Tags" tag)
1895 (const :tag "Timestamps" date)
1896 (const :tag "Footnotes" footnote)))
1898 (defcustom org-make-link-description-function nil
1899 "Function to use for generating link descriptions from links.
1900 This function must take two parameters: the first one is the
1901 link, the second one is the description generated by
1902 `org-insert-link'. The function should return the description to
1903 use."
1904 :group 'org-link
1905 :type '(choice (const nil) (function)))
1907 (defgroup org-link-store nil
1908 "Options concerning storing links in Org mode."
1909 :tag "Org Store Link"
1910 :group 'org-link)
1912 (defcustom org-url-hexify-p t
1913 "When non-nil, hexify URL when creating a link."
1914 :type 'boolean
1915 :version "24.3"
1916 :group 'org-link-store)
1918 (defcustom org-email-link-description-format "Email %c: %.30s"
1919 "Format of the description part of a link to an email or usenet message.
1920 The following %-escapes will be replaced by corresponding information:
1922 %F full \"From\" field
1923 %f name, taken from \"From\" field, address if no name
1924 %T full \"To\" field
1925 %t first name in \"To\" field, address if no name
1926 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1927 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1928 %s subject
1929 %d date
1930 %m message-id.
1932 You may use normal field width specification between the % and the letter.
1933 This is for example useful to limit the length of the subject.
1935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1936 :group 'org-link-store
1937 :type 'string)
1939 (defcustom org-from-is-user-regexp
1940 (let (r1 r2)
1941 (when (and user-mail-address (not (string= user-mail-address "")))
1942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1943 (when (and user-full-name (not (string= user-full-name "")))
1944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1946 "Regexp matched against the \"From:\" header of an email or usenet message.
1947 It should match if the message is from the user him/herself."
1948 :group 'org-link-store
1949 :type 'regexp)
1951 (defcustom org-context-in-file-links t
1952 "Non-nil means file links from `org-store-link' contain context.
1953 \\<org-mode-map>
1954 A search string will be added to the file name with :: as separator
1955 and used to find the context when the link is activated by the command
1956 `org-open-at-point'. When this option is t, the entire active region
1957 will be placed in the search string of the file link. If set to a
1958 positive integer, only the first n lines of context will be stored.
1960 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1961 \\[org-store-link]')
1962 negates this setting for the duration of the command."
1963 :group 'org-link-store
1964 :type '(choice boolean integer))
1966 (defcustom org-keep-stored-link-after-insertion nil
1967 "Non-nil means keep link in list for entire session.
1968 \\<org-mode-map>
1969 The command `org-store-link' adds a link pointing to the current
1970 location to an internal list. These links accumulate during a session.
1971 The command `org-insert-link' can be used to insert links into any
1972 Org file (offering completion for all stored links).
1974 When this option is nil, every link which has been inserted once using
1975 `\\[org-insert-link]' will be removed from the list, to make completing the \
1976 unused
1977 links more efficient."
1978 :group 'org-link-store
1979 :type 'boolean)
1981 (defgroup org-link-follow nil
1982 "Options concerning following links in Org mode."
1983 :tag "Org Follow Link"
1984 :group 'org-link)
1986 (defcustom org-link-translation-function nil
1987 "Function to translate links with different syntax to Org syntax.
1988 This can be used to translate links created for example by the Planner
1989 or emacs-wiki packages to Org syntax.
1990 The function must accept two parameters, a TYPE containing the link
1991 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1992 which is everything after the link protocol. It should return a cons
1993 with possibly modified values of type and path.
1994 Org contains a function for this, so if you set this variable to
1995 `org-translate-link-from-planner', you should be able follow many
1996 links created by planner."
1997 :group 'org-link-follow
1998 :type '(choice (const nil) (function)))
2000 (defcustom org-follow-link-hook nil
2001 "Hook that is run after a link has been followed."
2002 :group 'org-link-follow
2003 :type 'hook)
2005 (defcustom org-tab-follows-link nil
2006 "Non-nil means on links TAB will follow the link.
2007 Needs to be set before org.el is loaded.
2008 This really should not be used, it does not make sense, and the
2009 implementation is bad."
2010 :group 'org-link-follow
2011 :type 'boolean)
2013 (defcustom org-return-follows-link nil
2014 "Non-nil means on links RET will follow the link.
2015 In tables, the special behavior of RET has precedence."
2016 :group 'org-link-follow
2017 :type 'boolean)
2019 (defcustom org-mouse-1-follows-link
2020 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2021 "Non-nil means mouse-1 on a link will follow the link.
2022 A longer mouse click will still set point. Needs to be set
2023 before org.el is loaded."
2024 :group 'org-link-follow
2025 :version "26.1"
2026 :package-version '(Org . "8.3")
2027 :type '(choice
2028 (const :tag "A double click follows the link" double)
2029 (const :tag "Unconditionally follow the link with mouse-1" t)
2030 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2032 (defcustom org-mark-ring-length 4
2033 "Number of different positions to be recorded in the ring.
2034 Changing this requires a restart of Emacs to work correctly."
2035 :group 'org-link-follow
2036 :type 'integer)
2038 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2039 "Non-nil means internal fuzzy links can only match headlines.
2041 When nil, the a fuzzy link may point to a target or a named
2042 construct in the document. When set to the special value
2043 `query-to-create', offer to create a new headline when none
2044 matched.
2046 Spaces and statistics cookies are ignored during heading searches."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type '(choice
2050 (const :tag "Use fuzzy text search" nil)
2051 (const :tag "Match only exact headline" t)
2052 (const :tag "Match exact headline or query to create it"
2053 query-to-create))
2054 :safe #'symbolp)
2056 (defcustom org-link-frame-setup
2057 '((vm . vm-visit-folder-other-frame)
2058 (vm-imap . vm-visit-imap-folder-other-frame)
2059 (gnus . org-gnus-no-new-news)
2060 (file . find-file-other-window)
2061 (wl . wl-other-frame))
2062 "Setup the frame configuration for following links.
2063 When following a link with Emacs, it may often be useful to display
2064 this link in another window or frame. This variable can be used to
2065 set this up for the different types of links.
2066 For VM, use any of
2067 `vm-visit-folder'
2068 `vm-visit-folder-other-window'
2069 `vm-visit-folder-other-frame'
2070 For Gnus, use any of
2071 `gnus'
2072 `gnus-other-frame'
2073 `org-gnus-no-new-news'
2074 For FILE, use any of
2075 `find-file'
2076 `find-file-other-window'
2077 `find-file-other-frame'
2078 For Wanderlust use any of
2079 `wl'
2080 `wl-other-frame'
2081 For the calendar, use the variable `calendar-setup'.
2082 For BBDB, it is currently only possible to display the matches in
2083 another window."
2084 :group 'org-link-follow
2085 :type '(list
2086 (cons (const vm)
2087 (choice
2088 (const vm-visit-folder)
2089 (const vm-visit-folder-other-window)
2090 (const vm-visit-folder-other-frame)))
2091 (cons (const vm-imap)
2092 (choice
2093 (const vm-visit-imap-folder)
2094 (const vm-visit-imap-folder-other-window)
2095 (const vm-visit-imap-folder-other-frame)))
2096 (cons (const gnus)
2097 (choice
2098 (const gnus)
2099 (const gnus-other-frame)
2100 (const org-gnus-no-new-news)))
2101 (cons (const file)
2102 (choice
2103 (const find-file)
2104 (const find-file-other-window)
2105 (const find-file-other-frame)))
2106 (cons (const wl)
2107 (choice
2108 (const wl)
2109 (const wl-other-frame)))))
2111 (defcustom org-display-internal-link-with-indirect-buffer nil
2112 "Non-nil means use indirect buffer to display infile links.
2113 Activating internal links (from one location in a file to another location
2114 in the same file) normally just jumps to the location. When the link is
2115 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2116 is displayed in
2117 another window. When this option is set, the other window actually displays
2118 an indirect buffer clone of the current buffer, to avoid any visibility
2119 changes to the current buffer."
2120 :group 'org-link-follow
2121 :type 'boolean)
2123 (defcustom org-open-non-existing-files nil
2124 "Non-nil means `org-open-file' will open non-existing files.
2125 When nil, an error will be generated.
2126 This variable applies only to external applications because they
2127 might choke on non-existing files. If the link is to a file that
2128 will be opened in Emacs, the variable is ignored."
2129 :group 'org-link-follow
2130 :type 'boolean)
2132 (defcustom org-open-directory-means-index-dot-org nil
2133 "Non-nil means a link to a directory really means to index.org.
2134 When nil, following a directory link will run dired or open a finder/explorer
2135 window on that directory."
2136 :group 'org-link-follow
2137 :type 'boolean)
2139 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2140 "Non-nil means ask for confirmation before executing shell links.
2141 Shell links can be dangerous: just think about a link
2143 [[shell:rm -rf ~/*][Google Search]]
2145 This link would show up in your Org document as \"Google Search\",
2146 but really it would remove your entire home directory.
2147 Therefore we advise against setting this variable to nil.
2148 Just change it to `y-or-n-p' if you want to confirm with a
2149 single keystroke rather than having to type \"yes\"."
2150 :group 'org-link-follow
2151 :type '(choice
2152 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2153 (const :tag "with y-or-n (faster)" y-or-n-p)
2154 (const :tag "no confirmation (dangerous)" nil)))
2155 (put 'org-confirm-shell-link-function
2156 'safe-local-variable
2157 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2159 (defcustom org-confirm-shell-link-not-regexp ""
2160 "A regexp to skip confirmation for shell links."
2161 :group 'org-link-follow
2162 :version "24.1"
2163 :type 'regexp)
2165 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2166 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2167 Elisp links can be dangerous: just think about a link
2169 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2171 This link would show up in your Org document as \"Google Search\",
2172 but really it would remove your entire home directory.
2173 Therefore we advise against setting this variable to nil.
2174 Just change it to `y-or-n-p' if you want to confirm with a
2175 single keystroke rather than having to type \"yes\"."
2176 :group 'org-link-follow
2177 :type '(choice
2178 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2179 (const :tag "with y-or-n (faster)" y-or-n-p)
2180 (const :tag "no confirmation (dangerous)" nil)))
2181 (put 'org-confirm-shell-link-function
2182 'safe-local-variable
2183 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2185 (defcustom org-confirm-elisp-link-not-regexp ""
2186 "A regexp to skip confirmation for Elisp links."
2187 :group 'org-link-follow
2188 :version "24.1"
2189 :type 'regexp)
2191 (defconst org-file-apps-defaults-gnu
2192 '((remote . emacs)
2193 (system . mailcap)
2194 (t . mailcap))
2195 "Default file applications on a UNIX or GNU/Linux system.
2196 See `org-file-apps'.")
2198 (defconst org-file-apps-defaults-macosx
2199 '((remote . emacs)
2200 (system . "open %s")
2201 ("ps.gz" . "gv %s")
2202 ("eps.gz" . "gv %s")
2203 ("dvi" . "xdvi %s")
2204 ("fig" . "xfig %s")
2205 (t . "open %s"))
2206 "Default file applications on a macOS system.
2207 The system \"open\" is known as a default, but we use X11 applications
2208 for some files for which the OS does not have a good default.
2209 See `org-file-apps'.")
2211 (defconst org-file-apps-defaults-windowsnt
2212 (list '(remote . emacs)
2213 (cons 'system (lambda (file _path)
2214 (with-no-warnings (w32-shell-execute "open" file))))
2215 (cons t (lambda (file _path)
2216 (with-no-warnings (w32-shell-execute "open" file)))))
2217 "Default file applications on a Windows NT system.
2218 The system \"open\" is used for most files.
2219 See `org-file-apps'.")
2221 (defcustom org-file-apps
2222 '((auto-mode . emacs)
2223 ("\\.mm\\'" . default)
2224 ("\\.x?html?\\'" . default)
2225 ("\\.pdf\\'" . default))
2226 "External applications for opening `file:path' items in a document.
2227 \\<org-mode-map>\
2229 Org mode uses system defaults for different file types, but
2230 you can use this variable to set the application for a given file
2231 extension. The entries in this list are cons cells where the car identifies
2232 files and the cdr the corresponding command.
2234 Possible values for the file identifier are:
2236 \"string\" A string as a file identifier can be interpreted in different
2237 ways, depending on its contents:
2239 - Alphanumeric characters only:
2240 Match links with this file extension.
2241 Example: (\"pdf\" . \"evince %s\")
2242 to open PDFs with evince.
2244 - Regular expression: Match links where the
2245 filename matches the regexp. If you want to
2246 use groups here, use shy groups.
2248 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2249 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2250 to open *.html and *.xhtml with firefox.
2252 - Regular expression which contains (non-shy) groups:
2253 Match links where the whole link, including \"::\", and
2254 anything after that, matches the regexp.
2255 In a custom command string, %1, %2, etc. are replaced with
2256 the parts of the link that were matched by the groups.
2257 For backwards compatibility, if a command string is given
2258 that does not use any of the group matches, this case is
2259 handled identically to the second one (i.e. match against
2260 file name only).
2261 In a custom function, you can access the group matches with
2262 (match-string n link).
2264 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2265 \"evince -p %1 %s\")
2266 to open [[file:document.pdf::5]] with evince at page 5.
2268 `directory' Matches a directory
2269 `remote' Matches a remote file, accessible through tramp or efs.
2270 Remote files most likely should be visited through Emacs
2271 because external applications cannot handle such paths.
2272 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2273 so all files Emacs knows how to handle. Using this with
2274 command `emacs' will open most files in Emacs. Beware that this
2275 will also open html files inside Emacs, unless you add
2276 (\"html\" . default) to the list as well.
2277 `system' The system command to open files, like `open' on Windows
2278 and macOS, and mailcap under GNU/Linux. This is the command
2279 that will be selected if you call `org-open-at-point' with a
2280 double prefix argument (`\\[universal-argument] \
2281 \\[universal-argument] \\[org-open-at-point]').
2282 t Default for files not matched by any of the other options.
2284 Possible values for the command are:
2286 `emacs' The file will be visited by the current Emacs process.
2287 `default' Use the default application for this file type, which is the
2288 association for t in the list, most likely in the system-specific
2289 part. This can be used to overrule an unwanted setting in the
2290 system-specific variable.
2291 `system' Use the system command for opening files, like \"open\".
2292 This command is specified by the entry whose car is `system'.
2293 Most likely, the system-specific version of this variable
2294 does define this command, but you can overrule/replace it
2295 here.
2296 `mailcap' Use command specified in the mailcaps.
2297 string A command to be executed by a shell; %s will be replaced
2298 by the path to the file.
2299 function A Lisp function, which will be called with two arguments:
2300 the file path and the original link string, without the
2301 \"file:\" prefix.
2303 For more examples, see the system specific constants
2304 `org-file-apps-defaults-macosx'
2305 `org-file-apps-defaults-windowsnt'
2306 `org-file-apps-defaults-gnu'."
2307 :group 'org-link-follow
2308 :type '(repeat
2309 (cons (choice :value ""
2310 (string :tag "Extension")
2311 (const :tag "System command to open files" system)
2312 (const :tag "Default for unrecognized files" t)
2313 (const :tag "Remote file" remote)
2314 (const :tag "Links to a directory" directory)
2315 (const :tag "Any files that have Emacs modes"
2316 auto-mode))
2317 (choice :value ""
2318 (const :tag "Visit with Emacs" emacs)
2319 (const :tag "Use default" default)
2320 (const :tag "Use the system command" system)
2321 (string :tag "Command")
2322 (function :tag "Function")))))
2324 (defcustom org-doi-server-url "http://dx.doi.org/"
2325 "The URL of the DOI server."
2326 :type 'string
2327 :version "24.3"
2328 :group 'org-link-follow)
2330 (defgroup org-refile nil
2331 "Options concerning refiling entries in Org mode."
2332 :tag "Org Refile"
2333 :group 'org)
2335 (defcustom org-directory "~/org"
2336 "Directory with Org files.
2337 This is just a default location to look for Org files. There is no need
2338 at all to put your files into this directory. It is used in the
2339 following situations:
2341 1. When a capture template specifies a target file that is not an
2342 absolute path. The path will then be interpreted relative to
2343 `org-directory'
2344 2. When the value of variable `org-agenda-files' is a single file, any
2345 relative paths in this file will be taken as relative to
2346 `org-directory'."
2347 :group 'org-refile
2348 :group 'org-capture
2349 :type 'directory)
2351 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2352 "Default target for storing notes.
2353 Used as a fall back file for org-capture.el, for templates that
2354 do not specify a target file."
2355 :group 'org-refile
2356 :group 'org-capture
2357 :type 'file)
2359 (defcustom org-reverse-note-order nil
2360 "Non-nil means store new notes at the beginning of a file or entry.
2361 When nil, new notes will be filed to the end of a file or entry.
2362 This can also be a list with cons cells of regular expressions that
2363 are matched against file names, and values."
2364 :group 'org-capture
2365 :group 'org-refile
2366 :type '(choice
2367 (const :tag "Reverse always" t)
2368 (const :tag "Reverse never" nil)
2369 (repeat :tag "By file name regexp"
2370 (cons regexp boolean))))
2372 (defcustom org-log-refile nil
2373 "Information to record when a task is refiled.
2375 Possible values are:
2377 nil Don't add anything
2378 time Add a time stamp to the task
2379 note Prompt for a note and add it with template `org-log-note-headings'
2381 This option can also be set with on a per-file-basis with
2383 #+STARTUP: nologrefile
2384 #+STARTUP: logrefile
2385 #+STARTUP: lognoterefile
2387 You can have local logging settings for a subtree by setting the LOGGING
2388 property to one or more of these keywords.
2390 When bulk-refiling from the agenda, the value `note' is forbidden and
2391 will temporarily be changed to `time'."
2392 :group 'org-refile
2393 :group 'org-progress
2394 :version "24.1"
2395 :type '(choice
2396 (const :tag "No logging" nil)
2397 (const :tag "Record timestamp" time)
2398 (const :tag "Record timestamp with note." note)))
2400 (defcustom org-refile-targets nil
2401 "Targets for refiling entries with `\\[org-refile]'.
2402 This is a list of cons cells. Each cell contains:
2403 - a specification of the files to be considered, either a list of files,
2404 or a symbol whose function or variable value will be used to retrieve
2405 a file name or a list of file names. If you use `org-agenda-files' for
2406 that, all agenda files will be scanned for targets. Nil means consider
2407 headings in the current buffer.
2408 - A specification of how to find candidate refile targets. This may be
2409 any of:
2410 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2411 This tag has to be present in all target headlines, inheritance will
2412 not be considered.
2413 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2414 todo keyword.
2415 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2416 headlines that are refiling targets.
2417 - a cons cell (:level . N). Any headline of level N is considered a target.
2418 Note that, when `org-odd-levels-only' is set, level corresponds to
2419 order in hierarchy, not to the number of stars.
2420 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2421 Note that, when `org-odd-levels-only' is set, level corresponds to
2422 order in hierarchy, not to the number of stars.
2424 Each element of this list generates a set of possible targets.
2425 The union of these sets is presented (with completion) to
2426 the user by `org-refile'.
2428 You can set the variable `org-refile-target-verify-function' to a function
2429 to verify each headline found by the simple criteria above.
2431 When this variable is nil, all top-level headlines in the current buffer
2432 are used, equivalent to the value `((nil . (:level . 1))'."
2433 :group 'org-refile
2434 :type '(repeat
2435 (cons
2436 (choice :value org-agenda-files
2437 (const :tag "All agenda files" org-agenda-files)
2438 (const :tag "Current buffer" nil)
2439 (function) (variable) (file))
2440 (choice :tag "Identify target headline by"
2441 (cons :tag "Specific tag" (const :value :tag) (string))
2442 (cons :tag "TODO keyword" (const :value :todo) (string))
2443 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2444 (cons :tag "Level number" (const :value :level) (integer))
2445 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2447 (defcustom org-refile-target-verify-function nil
2448 "Function to verify if the headline at point should be a refile target.
2449 The function will be called without arguments, with point at the
2450 beginning of the headline. It should return t and leave point
2451 where it is if the headline is a valid target for refiling.
2453 If the target should not be selected, the function must return nil.
2454 In addition to this, it may move point to a place from where the search
2455 should be continued. For example, the function may decide that the entire
2456 subtree of the current entry should be excluded and move point to the end
2457 of the subtree."
2458 :group 'org-refile
2459 :type '(choice
2460 (const nil)
2461 (function)))
2463 (defcustom org-refile-use-cache nil
2464 "Non-nil means cache refile targets to speed up the process.
2465 \\<org-mode-map>\
2466 The cache for a particular file will be updated automatically when
2467 the buffer has been killed, or when any of the marker used for flagging
2468 refile targets no longer points at a live buffer.
2469 If you have added new entries to a buffer that might themselves be targets,
2470 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2471 if you find that easier, \
2472 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2473 \\[org-refile]'."
2474 :group 'org-refile
2475 :version "24.1"
2476 :type 'boolean)
2478 (defcustom org-refile-use-outline-path nil
2479 "Non-nil means provide refile targets as paths.
2480 So a level 3 headline will be available as level1/level2/level3.
2482 When the value is `file', also include the file name (without directory)
2483 into the path. In this case, you can also stop the completion after
2484 the file name, to get entries inserted as top level in the file.
2486 When `full-file-path', include the full file path.
2488 When `buffer-name', use the buffer name."
2489 :group 'org-refile
2490 :type '(choice
2491 (const :tag "Not" nil)
2492 (const :tag "Yes" t)
2493 (const :tag "Start with file name" file)
2494 (const :tag "Start with full file path" full-file-path)
2495 (const :tag "Start with buffer name" buffer-name)))
2497 (defcustom org-outline-path-complete-in-steps t
2498 "Non-nil means complete the outline path in hierarchical steps.
2499 When Org uses the refile interface to select an outline path (see
2500 `org-refile-use-outline-path'), the completion of the path can be
2501 done in a single go, or it can be done in steps down the headline
2502 hierarchy. Going in steps is probably the best if you do not use
2503 a special completion package like `ido' or `icicles'. However,
2504 when using these packages, going in one step can be very fast,
2505 while still showing the whole path to the entry."
2506 :group 'org-refile
2507 :type 'boolean)
2509 (defcustom org-refile-allow-creating-parent-nodes nil
2510 "Non-nil means allow the creation of new nodes as refile targets.
2511 New nodes are then created by adding \"/new node name\" to the completion
2512 of an existing node. When the value of this variable is `confirm',
2513 new node creation must be confirmed by the user (recommended).
2514 When nil, the completion must match an existing entry.
2516 Note that, if the new heading is not seen by the criteria
2517 listed in `org-refile-targets', multiple instances of the same
2518 heading would be created by trying again to file under the new
2519 heading."
2520 :group 'org-refile
2521 :type '(choice
2522 (const :tag "Never" nil)
2523 (const :tag "Always" t)
2524 (const :tag "Prompt for confirmation" confirm)))
2526 (defcustom org-refile-active-region-within-subtree nil
2527 "Non-nil means also refile active region within a subtree.
2529 By default `org-refile' doesn't allow refiling regions if they
2530 don't contain a set of subtrees, but it might be convenient to
2531 do so sometimes: in that case, the first line of the region is
2532 converted to a headline before refiling."
2533 :group 'org-refile
2534 :version "24.1"
2535 :type 'boolean)
2537 (defgroup org-todo nil
2538 "Options concerning TODO items in Org mode."
2539 :tag "Org TODO"
2540 :group 'org)
2542 (defgroup org-progress nil
2543 "Options concerning Progress logging in Org mode."
2544 :tag "Org Progress"
2545 :group 'org-time)
2547 (defvar org-todo-interpretation-widgets
2548 '((:tag "Sequence (cycling hits every state)" sequence)
2549 (:tag "Type (cycling directly to DONE)" type))
2550 "The available interpretation symbols for customizing `org-todo-keywords'.
2551 Interested libraries should add to this list.")
2553 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2554 "List of TODO entry keyword sequences and their interpretation.
2555 \\<org-mode-map>This is a list of sequences.
2557 Each sequence starts with a symbol, either `sequence' or `type',
2558 indicating if the keywords should be interpreted as a sequence of
2559 action steps, or as different types of TODO items. The first
2560 keywords are states requiring action - these states will select a headline
2561 for inclusion into the global TODO list Org produces. If one of the
2562 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2563 signify that no further action is necessary. If \"|\" is not found,
2564 the last keyword is treated as the only DONE state of the sequence.
2566 The command `\\[org-todo]' cycles an entry through these states, and one
2567 additional state where no keyword is present. For details about this
2568 cycling, see the manual.
2570 TODO keywords and interpretation can also be set on a per-file basis with
2571 the special #+SEQ_TODO and #+TYP_TODO lines.
2573 Each keyword can optionally specify a character for fast state selection
2574 \(in combination with the variable `org-use-fast-todo-selection')
2575 and specifiers for state change logging, using the same syntax that
2576 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2577 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2578 indicates to record a time stamp each time this state is selected.
2580 Each keyword may also specify if a timestamp or a note should be
2581 recorded when entering or leaving the state, by adding additional
2582 characters in the parenthesis after the keyword. This looks like this:
2583 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2584 record only the time of the state change. With X and Y being either
2585 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2586 Y when leaving the state if and only if the *target* state does not
2587 define X. You may omit any of the fast-selection key or X or /Y,
2588 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2590 For backward compatibility, this variable may also be just a list
2591 of keywords. In this case the interpretation (sequence or type) will be
2592 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2593 :group 'org-todo
2594 :group 'org-keywords
2595 :type '(choice
2596 (repeat :tag "Old syntax, just keywords"
2597 (string :tag "Keyword"))
2598 (repeat :tag "New syntax"
2599 (cons
2600 (choice
2601 :tag "Interpretation"
2602 ;;Quick and dirty way to see
2603 ;;`org-todo-interpretations'. This takes the
2604 ;;place of item arguments
2605 :convert-widget
2606 (lambda (widget)
2607 (widget-put widget
2608 :args (mapcar
2609 (lambda (x)
2610 (widget-convert
2611 (cons 'const x)))
2612 org-todo-interpretation-widgets))
2613 widget))
2614 (repeat
2615 (string :tag "Keyword"))))))
2617 (defvar-local org-todo-keywords-1 nil
2618 "All TODO and DONE keywords active in a buffer.")
2619 (defvar org-todo-keywords-for-agenda nil)
2620 (defvar org-done-keywords-for-agenda nil)
2621 (defvar org-todo-keyword-alist-for-agenda nil)
2622 (defvar org-tag-alist-for-agenda nil
2623 "Alist of all tags from all agenda files.")
2624 (defvar org-tag-groups-alist-for-agenda nil
2625 "Alist of all groups tags from all current agenda files.")
2626 (defvar-local org-tag-groups-alist nil)
2627 (defvar org-agenda-contributing-files nil)
2628 (defvar-local org-current-tag-alist nil
2629 "Alist of all tag groups in current buffer.
2630 This variable takes into consideration `org-tag-alist',
2631 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2632 (defvar-local org-not-done-keywords nil)
2633 (defvar-local org-done-keywords nil)
2634 (defvar-local org-todo-heads nil)
2635 (defvar-local org-todo-sets nil)
2636 (defvar-local org-todo-log-states nil)
2637 (defvar-local org-todo-kwd-alist nil)
2638 (defvar-local org-todo-key-alist nil)
2639 (defvar-local org-todo-key-trigger nil)
2641 (defcustom org-todo-interpretation 'sequence
2642 "Controls how TODO keywords are interpreted.
2643 This variable is in principle obsolete and is only used for
2644 backward compatibility, if the interpretation of todo keywords is
2645 not given already in `org-todo-keywords'. See that variable for
2646 more information."
2647 :group 'org-todo
2648 :group 'org-keywords
2649 :type '(choice (const sequence)
2650 (const type)))
2652 (defcustom org-use-fast-todo-selection t
2653 "\\<org-mode-map>\
2654 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2655 This variable describes if and under what circumstances the cycling
2656 mechanism for TODO keywords will be replaced by a single-key, direct
2657 selection scheme.
2659 When nil, fast selection is never used.
2661 When the symbol `prefix', it will be used when `org-todo' is called
2662 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2663 in an Org buffer, and
2664 `\\[universal-argument] t' in an agenda buffer.
2666 When t, fast selection is used by default. In this case, the prefix
2667 argument forces cycling instead.
2669 In all cases, the special interface is only used if access keys have
2670 actually been assigned by the user, i.e. if keywords in the configuration
2671 are followed by a letter in parenthesis, like TODO(t)."
2672 :group 'org-todo
2673 :type '(choice
2674 (const :tag "Never" nil)
2675 (const :tag "By default" t)
2676 (const :tag "Only with C-u C-c C-t" prefix)))
2678 (defcustom org-provide-todo-statistics t
2679 "Non-nil means update todo statistics after insert and toggle.
2680 ALL-HEADLINES means update todo statistics by including headlines
2681 with no TODO keyword as well, counting them as not done.
2682 A list of TODO keywords means the same, but skip keywords that are
2683 not in this list.
2684 When set to a list of two lists, the first list contains keywords
2685 to consider as TODO keywords, the second list contains keywords
2686 to consider as DONE keywords.
2688 When this is set, todo statistics is updated in the parent of the
2689 current entry each time a todo state is changed."
2690 :group 'org-todo
2691 :type '(choice
2692 (const :tag "Yes, only for TODO entries" t)
2693 (const :tag "Yes, including all entries" all-headlines)
2694 (repeat :tag "Yes, for TODOs in this list"
2695 (string :tag "TODO keyword"))
2696 (list :tag "Yes, for TODOs and DONEs in these lists"
2697 (repeat (string :tag "TODO keyword"))
2698 (repeat (string :tag "DONE keyword")))
2699 (other :tag "No TODO statistics" nil)))
2701 (defcustom org-hierarchical-todo-statistics t
2702 "Non-nil means TODO statistics covers just direct children.
2703 When nil, all entries in the subtree are considered.
2704 This has only an effect if `org-provide-todo-statistics' is set.
2705 To set this to nil for only a single subtree, use a COOKIE_DATA
2706 property and include the word \"recursive\" into the value."
2707 :group 'org-todo
2708 :type 'boolean)
2710 (defcustom org-after-todo-state-change-hook nil
2711 "Hook which is run after the state of a TODO item was changed.
2712 The new state (a string with a TODO keyword, or nil) is available in the
2713 Lisp variable `org-state'."
2714 :group 'org-todo
2715 :type 'hook)
2717 (defvar org-blocker-hook nil
2718 "Hook for functions that are allowed to block a state change.
2720 Functions in this hook should not modify the buffer.
2721 Each function gets as its single argument a property list,
2722 see `org-trigger-hook' for more information about this list.
2724 If any of the functions in this hook returns nil, the state change
2725 is blocked.")
2727 (defvar org-trigger-hook nil
2728 "Hook for functions that are triggered by a state change.
2730 Each function gets as its single argument a property list with at
2731 least the following elements:
2733 (:type type-of-change :position pos-at-entry-start
2734 :from old-state :to new-state)
2736 Depending on the type, more properties may be present.
2738 This mechanism is currently implemented for:
2740 TODO state changes
2741 ------------------
2742 :type todo-state-change
2743 :from previous state (keyword as a string), or nil, or a symbol
2744 `todo' or `done', to indicate the general type of state.
2745 :to new state, like in :from")
2747 (defcustom org-enforce-todo-dependencies nil
2748 "Non-nil means undone TODO entries will block switching the parent to DONE.
2749 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2750 be blocked if any prior sibling is not yet done.
2751 Finally, if the parent is blocked because of ordered siblings of its own,
2752 the child will also be blocked."
2753 :set (lambda (var val)
2754 (set var val)
2755 (if val
2756 (add-hook 'org-blocker-hook
2757 'org-block-todo-from-children-or-siblings-or-parent)
2758 (remove-hook 'org-blocker-hook
2759 'org-block-todo-from-children-or-siblings-or-parent)))
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-enforce-todo-checkbox-dependencies nil
2764 "Non-nil means unchecked boxes will block switching the parent to DONE.
2765 When this is nil, checkboxes have no influence on switching TODO states.
2766 When non-nil, you first need to check off all check boxes before the TODO
2767 entry can be switched to DONE.
2768 This variable needs to be set before org.el is loaded, and you need to
2769 restart Emacs after a change to make the change effective. The only way
2770 to change is while Emacs is running is through the customize interface."
2771 :set (lambda (var val)
2772 (set var val)
2773 (if val
2774 (add-hook 'org-blocker-hook
2775 'org-block-todo-from-checkboxes)
2776 (remove-hook 'org-blocker-hook
2777 'org-block-todo-from-checkboxes)))
2778 :group 'org-todo
2779 :type 'boolean)
2781 (defcustom org-treat-insert-todo-heading-as-state-change nil
2782 "Non-nil means inserting a TODO heading is treated as state change.
2783 So when the command `\\[org-insert-todo-heading]' is used, state change
2784 logging will apply if appropriate. When nil, the new TODO item will
2785 be inserted directly, and no logging will take place."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2790 "Non-nil means switching TODO states with S-cursor counts as state change.
2791 This is the default behavior. However, setting this to nil allows a
2792 convenient way to select a TODO state and bypass any logging associated
2793 with that."
2794 :group 'org-todo
2795 :type 'boolean)
2797 (defcustom org-todo-state-tags-triggers nil
2798 "Tag changes that should be triggered by TODO state changes.
2799 This is a list. Each entry is
2801 (state-change (tag . flag) .......)
2803 State-change can be a string with a state, and empty string to indicate the
2804 state that has no TODO keyword, or it can be one of the symbols `todo'
2805 or `done', meaning any not-done or done state, respectively."
2806 :group 'org-todo
2807 :group 'org-tags
2808 :type '(repeat
2809 (cons (choice :tag "When changing to"
2810 (const :tag "Not-done state" todo)
2811 (const :tag "Done state" done)
2812 (string :tag "State"))
2813 (repeat
2814 (cons :tag "Tag action"
2815 (string :tag "Tag")
2816 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2818 (defcustom org-log-done nil
2819 "Information to record when a task moves to the DONE state.
2821 Possible values are:
2823 nil Don't add anything, just change the keyword
2824 time Add a time stamp to the task
2825 note Prompt for a note and add it with template `org-log-note-headings'
2827 This option can also be set with on a per-file-basis with
2829 #+STARTUP: nologdone
2830 #+STARTUP: logdone
2831 #+STARTUP: lognotedone
2833 You can have local logging settings for a subtree by setting the LOGGING
2834 property to one or more of these keywords."
2835 :group 'org-todo
2836 :group 'org-progress
2837 :type '(choice
2838 (const :tag "No logging" nil)
2839 (const :tag "Record CLOSED timestamp" time)
2840 (const :tag "Record CLOSED timestamp with note." note)))
2842 ;; Normalize old uses of org-log-done.
2843 (cond
2844 ((eq org-log-done t) (setq org-log-done 'time))
2845 ((and (listp org-log-done) (memq 'done org-log-done))
2846 (setq org-log-done 'note)))
2848 (defcustom org-log-reschedule nil
2849 "Information to record when the scheduling date of a tasks is modified.
2851 Possible values are:
2853 nil Don't add anything, just change the date
2854 time Add a time stamp to the task
2855 note Prompt for a note and add it with template `org-log-note-headings'
2857 This option can also be set with on a per-file-basis with
2859 #+STARTUP: nologreschedule
2860 #+STARTUP: logreschedule
2861 #+STARTUP: lognotereschedule"
2862 :group 'org-todo
2863 :group 'org-progress
2864 :type '(choice
2865 (const :tag "No logging" nil)
2866 (const :tag "Record timestamp" time)
2867 (const :tag "Record timestamp with note." note)))
2869 (defcustom org-log-redeadline nil
2870 "Information to record when the deadline date of a tasks is modified.
2872 Possible values are:
2874 nil Don't add anything, just change the date
2875 time Add a time stamp to the task
2876 note Prompt for a note and add it with template `org-log-note-headings'
2878 This option can also be set with on a per-file-basis with
2880 #+STARTUP: nologredeadline
2881 #+STARTUP: logredeadline
2882 #+STARTUP: lognoteredeadline
2884 You can have local logging settings for a subtree by setting the LOGGING
2885 property to one or more of these keywords."
2886 :group 'org-todo
2887 :group 'org-progress
2888 :type '(choice
2889 (const :tag "No logging" nil)
2890 (const :tag "Record timestamp" time)
2891 (const :tag "Record timestamp with note." note)))
2893 (defcustom org-log-note-clock-out nil
2894 "Non-nil means record a note when clocking out of an item.
2895 This can also be configured on a per-file basis by adding one of
2896 the following lines anywhere in the buffer:
2898 #+STARTUP: lognoteclock-out
2899 #+STARTUP: nolognoteclock-out"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type 'boolean)
2904 (defcustom org-log-done-with-time t
2905 "Non-nil means the CLOSED time stamp will contain date and time.
2906 When nil, only the date will be recorded."
2907 :group 'org-progress
2908 :type 'boolean)
2910 (defcustom org-log-note-headings
2911 '((done . "CLOSING NOTE %t")
2912 (state . "State %-12s from %-12S %t")
2913 (note . "Note taken on %t")
2914 (reschedule . "Rescheduled from %S on %t")
2915 (delschedule . "Not scheduled, was %S on %t")
2916 (redeadline . "New deadline from %S on %t")
2917 (deldeadline . "Removed deadline, was %S on %t")
2918 (refile . "Refiled on %t")
2919 (clock-out . ""))
2920 "Headings for notes added to entries.
2922 The value is an alist, with the car being a symbol indicating the
2923 note context, and the cdr is the heading to be used. The heading
2924 may also be the empty string. The following placeholders can be
2925 used:
2927 %t a time stamp.
2928 %T an active time stamp instead the default inactive one
2929 %d a short-format time stamp.
2930 %D an active short-format time stamp.
2931 %s the new TODO state or time stamp (inactive), in double quotes.
2932 %S the old TODO state or time stamp (inactive), in double quotes.
2933 %u the user name.
2934 %U full user name.
2936 In fact, it is not a good idea to change the `state' entry,
2937 because Agenda Log mode depends on the format of these entries."
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type '(list :greedy t
2941 (cons (const :tag "Heading when closing an item" done) string)
2942 (cons (const :tag
2943 "Heading when changing todo state (todo sequence only)"
2944 state) string)
2945 (cons (const :tag "Heading when just taking a note" note) string)
2946 (cons (const :tag "Heading when rescheduling" reschedule) string)
2947 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2948 (cons (const :tag "Heading when changing deadline" redeadline) string)
2949 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2950 (cons (const :tag "Heading when refiling" refile) string)
2951 (cons (const :tag "Heading when clocking out" clock-out) string)))
2953 (unless (assq 'note org-log-note-headings)
2954 (push '(note . "%t") org-log-note-headings))
2956 (defcustom org-log-into-drawer nil
2957 "Non-nil means insert state change notes and time stamps into a drawer.
2958 When nil, state changes notes will be inserted after the headline and
2959 any scheduling and clock lines, but not inside a drawer.
2961 The value of this variable should be the name of the drawer to use.
2962 LOGBOOK is proposed as the default drawer for this purpose, you can
2963 also set this to a string to define the drawer of your choice.
2965 A value of t is also allowed, representing \"LOGBOOK\".
2967 A value of t or nil can also be set with on a per-file-basis with
2969 #+STARTUP: logdrawer
2970 #+STARTUP: nologdrawer
2972 If this variable is set, `org-log-state-notes-insert-after-drawers'
2973 will be ignored.
2975 You can set the property LOG_INTO_DRAWER to overrule this setting for
2976 a subtree.
2978 Do not check directly this variable in a Lisp program. Call
2979 function `org-log-into-drawer' instead."
2980 :group 'org-todo
2981 :group 'org-progress
2982 :type '(choice
2983 (const :tag "Not into a drawer" nil)
2984 (const :tag "LOGBOOK" t)
2985 (string :tag "Other")))
2987 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2989 (defun org-log-into-drawer ()
2990 "Name of the log drawer, as a string, or nil.
2991 This is the value of `org-log-into-drawer'. However, if the
2992 current entry has or inherits a LOG_INTO_DRAWER property, it will
2993 be used instead of the default value."
2994 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2995 (cond ((equal p "nil") nil)
2996 ((equal p "t") "LOGBOOK")
2997 ((stringp p) p)
2998 (p "LOGBOOK")
2999 ((stringp org-log-into-drawer) org-log-into-drawer)
3000 (org-log-into-drawer "LOGBOOK"))))
3002 (defcustom org-log-state-notes-insert-after-drawers nil
3003 "Non-nil means insert state change notes after any drawers in entry.
3004 Only the drawers that *immediately* follow the headline and the
3005 deadline/scheduled line are skipped.
3006 When nil, insert notes right after the heading and perhaps the line
3007 with deadline/scheduling if present.
3009 This variable will have no effect if `org-log-into-drawer' is
3010 set."
3011 :group 'org-todo
3012 :group 'org-progress
3013 :type 'boolean)
3015 (defcustom org-log-states-order-reversed t
3016 "Non-nil means the latest state note will be directly after heading.
3017 When nil, the state change notes will be ordered according to time.
3019 This option can also be set with on a per-file-basis with
3021 #+STARTUP: logstatesreversed
3022 #+STARTUP: nologstatesreversed"
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-todo-repeat-to-state nil
3028 "The TODO state to which a repeater should return the repeating task.
3029 By default this is the first task of a TODO sequence or the
3030 previous state of a TYPE_TODO set. But you can specify to use
3031 the previous state in a TODO sequence or a string.
3033 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3034 entry, which has precedence over this option."
3035 :group 'org-todo
3036 :version "24.1"
3037 :type '(choice (const :tag "Use the previous TODO state" t)
3038 (const :tag "Use the head of the TODO sequence" nil)
3039 (string :tag "Use a specific TODO state")))
3041 (defcustom org-log-repeat 'time
3042 "Non-nil means record moving through the DONE state when triggering repeat.
3043 An auto-repeating task is immediately switched back to TODO when
3044 marked DONE. If you are not logging state changes (by adding \"@\"
3045 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3046 record a closing note, there will be no record of the task moving
3047 through DONE. This variable forces taking a note anyway.
3049 nil Don't force a record
3050 time Record a time stamp
3051 note Prompt for a note and add it with template `org-log-note-headings'
3053 This option can also be set with on a per-file-basis with
3055 #+STARTUP: nologrepeat
3056 #+STARTUP: logrepeat
3057 #+STARTUP: lognoterepeat
3059 You can have local logging settings for a subtree by setting the LOGGING
3060 property to one or more of these keywords."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type '(choice
3064 (const :tag "Don't force a record" nil)
3065 (const :tag "Force recording the DONE state" time)
3066 (const :tag "Force recording a note with the DONE state" note)))
3069 (defgroup org-priorities nil
3070 "Priorities in Org mode."
3071 :tag "Org Priorities"
3072 :group 'org-todo)
3074 (defcustom org-enable-priority-commands t
3075 "Non-nil means priority commands are active.
3076 When nil, these commands will be disabled, so that you never accidentally
3077 set a priority."
3078 :group 'org-priorities
3079 :type 'boolean)
3081 (defcustom org-highest-priority ?A
3082 "The highest priority of TODO items. A character like ?A, ?B etc.
3083 Must have a smaller ASCII number than `org-lowest-priority'."
3084 :group 'org-priorities
3085 :type 'character)
3087 (defcustom org-lowest-priority ?C
3088 "The lowest priority of TODO items. A character like ?A, ?B etc.
3089 Must have a larger ASCII number than `org-highest-priority'."
3090 :group 'org-priorities
3091 :type 'character)
3093 (defcustom org-default-priority ?B
3094 "The default priority of TODO items.
3095 This is the priority an item gets if no explicit priority is given.
3096 When starting to cycle on an empty priority the first step in the cycle
3097 depends on `org-priority-start-cycle-with-default'. The resulting first
3098 step priority must not exceed the range from `org-highest-priority' to
3099 `org-lowest-priority' which means that `org-default-priority' has to be
3100 in this range exclusive or inclusive the range boundaries. Else the
3101 first step refuses to set the default and the second will fall back
3102 to (depending on the command used) the highest or lowest priority."
3103 :group 'org-priorities
3104 :type 'character)
3106 (defcustom org-priority-start-cycle-with-default t
3107 "Non-nil means start with default priority when starting to cycle.
3108 When this is nil, the first step in the cycle will be (depending on the
3109 command used) one higher or lower than the default priority.
3110 See also `org-default-priority'."
3111 :group 'org-priorities
3112 :type 'boolean)
3114 (defcustom org-get-priority-function nil
3115 "Function to extract the priority from a string.
3116 The string is normally the headline. If this is nil Org computes the
3117 priority from the priority cookie like [#A] in the headline. It returns
3118 an integer, increasing by 1000 for each priority level.
3119 The user can set a different function here, which should take a string
3120 as an argument and return the numeric priority."
3121 :group 'org-priorities
3122 :version "24.1"
3123 :type '(choice
3124 (const nil)
3125 (function)))
3127 (defgroup org-time nil
3128 "Options concerning time stamps and deadlines in Org mode."
3129 :tag "Org Time"
3130 :group 'org)
3132 (defcustom org-time-stamp-rounding-minutes '(0 5)
3133 "Number of minutes to round time stamps to.
3134 \\<org-mode-map>\
3135 These are two values, the first applies when first creating a time stamp.
3136 The second applies when changing it with the commands `S-up' and `S-down'.
3137 When changing the time stamp, this means that it will change in steps
3138 of N minutes, as given by the second value.
3140 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3141 numbers should be factors of 60, so for example 5, 10, 15.
3143 When this is larger than 1, you can still force an exact time stamp by using
3144 a double prefix argument to a time stamp command like \
3145 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3146 and by using a prefix arg to `S-up/down' to specify the exact number
3147 of minutes to shift."
3148 :group 'org-time
3149 :get (lambda (var) ; Make sure both elements are there
3150 (if (integerp (default-value var))
3151 (list (default-value var) 5)
3152 (default-value var)))
3153 :type '(list
3154 (integer :tag "when inserting times")
3155 (integer :tag "when modifying times")))
3157 ;; Normalize old customizations of this variable.
3158 (when (integerp org-time-stamp-rounding-minutes)
3159 (setq org-time-stamp-rounding-minutes
3160 (list org-time-stamp-rounding-minutes
3161 org-time-stamp-rounding-minutes)))
3163 (defcustom org-display-custom-times nil
3164 "Non-nil means overlay custom formats over all time stamps.
3165 The formats are defined through the variable `org-time-stamp-custom-formats'.
3166 To turn this on on a per-file basis, insert anywhere in the file:
3167 #+STARTUP: customtime"
3168 :group 'org-time
3169 :set 'set-default
3170 :type 'sexp)
3171 (make-variable-buffer-local 'org-display-custom-times)
3173 (defcustom org-time-stamp-custom-formats
3174 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3175 "Custom formats for time stamps. See `format-time-string' for the syntax.
3176 These are overlaid over the default ISO format if the variable
3177 `org-display-custom-times' is set. Time like %H:%M should be at the
3178 end of the second format. The custom formats are also honored by export
3179 commands, if custom time display is turned on at the time of export."
3180 :group 'org-time
3181 :type 'sexp)
3183 (defun org-time-stamp-format (&optional long inactive)
3184 "Get the right format for a time string."
3185 (let ((f (if long (cdr org-time-stamp-formats)
3186 (car org-time-stamp-formats))))
3187 (if inactive
3188 (concat "[" (substring f 1 -1) "]")
3189 f)))
3191 (defcustom org-deadline-warning-days 14
3192 "Number of days before expiration during which a deadline becomes active.
3193 This variable governs the display in sparse trees and in the agenda.
3194 When 0 or negative, it means use this number (the absolute value of it)
3195 even if a deadline has a different individual lead time specified.
3197 Custom commands can set this variable in the options section."
3198 :group 'org-time
3199 :group 'org-agenda-daily/weekly
3200 :type 'integer)
3202 (defcustom org-scheduled-delay-days 0
3203 "Number of days before a scheduled item becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 The default value (i.e. 0) means: don't delay scheduled item.
3206 When negative, it means use this number (the absolute value of it)
3207 even if a scheduled item has a different individual delay time
3208 specified.
3210 Custom commands can set this variable in the options section."
3211 :group 'org-time
3212 :group 'org-agenda-daily/weekly
3213 :version "24.4"
3214 :package-version '(Org . "8.0")
3215 :type 'integer)
3217 (defcustom org-read-date-prefer-future t
3218 "Non-nil means assume future for incomplete date input from user.
3219 This affects the following situations:
3220 1. The user gives a month but not a year.
3221 For example, if it is April and you enter \"feb 2\", this will be read
3222 as Feb 2, *next* year. \"May 5\", however, will be this year.
3223 2. The user gives a day, but no month.
3224 For example, if today is the 15th, and you enter \"3\", Org will read
3225 this as the third of *next* month. However, if you enter \"17\",
3226 it will be considered as *this* month.
3228 If you set this variable to the symbol `time', then also the following
3229 will work:
3231 3. If the user gives a time.
3232 If the time is before now, it will be interpreted as tomorrow.
3234 Currently none of this works for ISO week specifications.
3236 When this option is nil, the current day, month and year will always be
3237 used as defaults.
3239 See also `org-agenda-jump-prefer-future'."
3240 :group 'org-time
3241 :type '(choice
3242 (const :tag "Never" nil)
3243 (const :tag "Check month and day" t)
3244 (const :tag "Check month, day, and time" time)))
3246 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3247 "Should the agenda jump command prefer the future for incomplete dates?
3248 The default is to do the same as configured in `org-read-date-prefer-future'.
3249 But you can also set a deviating value here.
3250 This may t or nil, or the symbol `org-read-date-prefer-future'."
3251 :group 'org-agenda
3252 :group 'org-time
3253 :version "24.1"
3254 :type '(choice
3255 (const :tag "Use org-read-date-prefer-future"
3256 org-read-date-prefer-future)
3257 (const :tag "Never" nil)
3258 (const :tag "Always" t)))
3260 (defcustom org-read-date-force-compatible-dates t
3261 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3263 Depending on the system Emacs is running on, certain dates cannot
3264 be represented with the type used internally to represent time.
3265 Dates between 1970-1-1 and 2038-1-1 can always be represented
3266 correctly. Some systems allow for earlier dates, some for later,
3267 some for both. One way to find out it to insert any date into an
3268 Org buffer, putting the cursor on the year and hitting S-up and
3269 S-down to test the range.
3271 When this variable is set to t, the date/time prompt will not let
3272 you specify dates outside the 1970-2037 range, so it is certain that
3273 these dates will work in whatever version of Emacs you are
3274 running, and also that you can move a file from one Emacs implementation
3275 to another. WHenever Org is forcing the year for you, it will display
3276 a message and beep.
3278 When this variable is nil, Org will check if the date is
3279 representable in the specific Emacs implementation you are using.
3280 If not, it will force a year, usually the current year, and beep
3281 to remind you. Currently this setting is not recommended because
3282 the likelihood that you will open your Org files in an Emacs that
3283 has limited date range is not negligible.
3285 A workaround for this problem is to use diary sexp dates for time
3286 stamps outside of this range."
3287 :group 'org-time
3288 :version "24.1"
3289 :type 'boolean)
3291 (defcustom org-read-date-display-live t
3292 "Non-nil means display current interpretation of date prompt live.
3293 This display will be in an overlay, in the minibuffer."
3294 :group 'org-time
3295 :type 'boolean)
3297 (defcustom org-read-date-popup-calendar t
3298 "Non-nil means pop up a calendar when prompting for a date.
3299 In the calendar, the date can be selected with mouse-1. However, the
3300 minibuffer will also be active, and you can simply enter the date as well.
3301 When nil, only the minibuffer will be available."
3302 :group 'org-time
3303 :type 'boolean)
3304 (defvaralias 'org-popup-calendar-for-date-prompt
3305 'org-read-date-popup-calendar)
3307 (defcustom org-extend-today-until 0
3308 "The hour when your day really ends. Must be an integer.
3309 This has influence for the following applications:
3310 - When switching the agenda to \"today\". It it is still earlier than
3311 the time given here, the day recognized as TODAY is actually yesterday.
3312 - When a date is read from the user and it is still before the time given
3313 here, the current date and time will be assumed to be yesterday, 23:59.
3314 Also, timestamps inserted in capture templates follow this rule.
3316 IMPORTANT: This is a feature whose implementation is and likely will
3317 remain incomplete. Really, it is only here because past midnight seems to
3318 be the favorite working time of John Wiegley :-)"
3319 :group 'org-time
3320 :type 'integer)
3322 (defcustom org-use-effective-time nil
3323 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3324 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3325 \"effective time\" of any timestamps between midnight and 8am will be
3326 23:59 of the previous day."
3327 :group 'org-time
3328 :version "24.1"
3329 :type 'boolean)
3331 (defcustom org-use-last-clock-out-time-as-effective-time nil
3332 "When non-nil, use the last clock out time for `org-todo'.
3333 Note that this option has precedence over the combined use of
3334 `org-use-effective-time' and `org-extend-today-until'."
3335 :group 'org-time
3336 :version "24.4"
3337 :package-version '(Org . "8.0")
3338 :type 'boolean)
3340 (defcustom org-edit-timestamp-down-means-later nil
3341 "Non-nil means S-down will increase the time in a time stamp.
3342 When nil, S-up will increase."
3343 :group 'org-time
3344 :type 'boolean)
3346 (defcustom org-calendar-follow-timestamp-change t
3347 "Non-nil means make the calendar window follow timestamp changes.
3348 When a timestamp is modified and the calendar window is visible, it will be
3349 moved to the new date."
3350 :group 'org-time
3351 :type 'boolean)
3353 (defgroup org-tags nil
3354 "Options concerning tags in Org mode."
3355 :tag "Org Tags"
3356 :group 'org)
3358 (defcustom org-tag-alist nil
3359 "Default tags available in Org files.
3361 The value of this variable is an alist. Associations either:
3363 (TAG)
3364 (TAG . SELECT)
3365 (SPECIAL)
3367 where TAG is a tag as a string, SELECT is character, used to
3368 select that tag through the fast tag selection interface, and
3369 SPECIAL is one of the following keywords: `:startgroup',
3370 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3371 `:newline'. These keywords are used to define a hierarchy of
3372 tags. See manual for details.
3374 When this variable is nil, Org mode bases tag input on what is
3375 already in the buffer. The value can be overridden locally by
3376 using a TAGS keyword, e.g.,
3378 #+TAGS: tag1 tag2
3380 See also `org-tag-persistent-alist' to sidestep this behavior."
3381 :group 'org-tags
3382 :type '(repeat
3383 (choice
3384 (cons :tag "Tag with key"
3385 (string :tag "Tag name")
3386 (character :tag "Access char"))
3387 (list :tag "Tag" (string :tag "Tag name"))
3388 (const :tag "Start radio group" (:startgroup))
3389 (const :tag "Start tag group, non distinct" (:startgrouptag))
3390 (const :tag "Group tags delimiter" (:grouptags))
3391 (const :tag "End radio group" (:endgroup))
3392 (const :tag "End tag group, non distinct" (:endgrouptag))
3393 (const :tag "New line" (:newline)))))
3395 (defcustom org-tag-persistent-alist nil
3396 "Tags always available in Org files.
3398 The value of this variable is an alist. Associations either:
3400 (TAG)
3401 (TAG . SELECT)
3402 (SPECIAL)
3404 where TAG is a tag as a string, SELECT is a character, used to
3405 select that tag through the fast tag selection interface, and
3406 SPECIAL is one of the following keywords: `:startgroup',
3407 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3408 `:newline'. These keywords are used to define a hierarchy of
3409 tags. See manual for details.
3411 Unlike to `org-tag-alist', tags defined in this variable do not
3412 depend on a local TAGS keyword. Instead, to disable these tags
3413 on a per-file basis, insert anywhere in the file:
3415 #+STARTUP: noptag"
3416 :group 'org-tags
3417 :type '(repeat
3418 (choice
3419 (cons :tag "Tag with key"
3420 (string :tag "Tag name")
3421 (character :tag "Access char"))
3422 (list :tag "Tag" (string :tag "Tag name"))
3423 (const :tag "Start radio group" (:startgroup))
3424 (const :tag "Start tag group, non distinct" (:startgrouptag))
3425 (const :tag "Group tags delimiter" (:grouptags))
3426 (const :tag "End radio group" (:endgroup))
3427 (const :tag "End tag group, non distinct" (:endgrouptag))
3428 (const :tag "New line" (:newline)))))
3430 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3431 "If non-nil, always offer completion for all tags of all agenda files.
3432 Instead of customizing this variable directly, you might want to
3433 set it locally for capture buffers, because there no list of
3434 tags in that file can be created dynamically (there are none).
3436 (add-hook \\='org-capture-mode-hook
3437 (lambda ()
3438 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3439 :group 'org-tags
3440 :version "24.1"
3441 :type 'boolean)
3443 (defvar org-file-tags nil
3444 "List of tags that can be inherited by all entries in the file.
3445 The tags will be inherited if the variable `org-use-tag-inheritance'
3446 says they should be.
3447 This variable is populated from #+FILETAGS lines.")
3449 (defcustom org-use-fast-tag-selection 'auto
3450 "Non-nil means use fast tag selection scheme.
3451 This is a special interface to select and deselect tags with single keys.
3452 When nil, fast selection is never used.
3453 When the symbol `auto', fast selection is used if and only if selection
3454 characters for tags have been configured, either through the variable
3455 `org-tag-alist' or through a #+TAGS line in the buffer.
3456 When t, fast selection is always used and selection keys are assigned
3457 automatically if necessary."
3458 :group 'org-tags
3459 :type '(choice
3460 (const :tag "Always" t)
3461 (const :tag "Never" nil)
3462 (const :tag "When selection characters are configured" auto)))
3464 (defcustom org-fast-tag-selection-single-key nil
3465 "Non-nil means fast tag selection exits after first change.
3466 When nil, you have to press RET to exit it.
3467 During fast tag selection, you can toggle this flag with `C-c'.
3468 This variable can also have the value `expert'. In this case, the window
3469 displaying the tags menu is not even shown, until you press C-c again."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "No" nil)
3473 (const :tag "Yes" t)
3474 (const :tag "Expert" expert)))
3476 (defvar org-fast-tag-selection-include-todo nil
3477 "Non-nil means fast tags selection interface will also offer TODO states.
3478 This is an undocumented feature, you should not rely on it.")
3480 (defcustom org-tags-column -77
3481 "The column to which tags should be indented in a headline.
3482 If this number is positive, it specifies the column. If it is negative,
3483 it means that the tags should be flushright to that column. For example,
3484 -80 works well for a normal 80 character screen.
3485 When 0, place tags directly after headline text, with only one space in
3486 between."
3487 :group 'org-tags
3488 :type 'integer)
3490 (defcustom org-auto-align-tags t
3491 "Non-nil keeps tags aligned when modifying headlines.
3492 Some operations (i.e. demoting) change the length of a headline and
3493 therefore shift the tags around. With this option turned on, after
3494 each such operation the tags are again aligned to `org-tags-column'."
3495 :group 'org-tags
3496 :type 'boolean)
3498 (defcustom org-use-tag-inheritance t
3499 "Non-nil means tags in levels apply also for sublevels.
3500 When nil, only the tags directly given in a specific line apply there.
3501 This may also be a list of tags that should be inherited, or a regexp that
3502 matches tags that should be inherited. Additional control is possible
3503 with the variable `org-tags-exclude-from-inheritance' which gives an
3504 explicit list of tags to be excluded from inheritance, even if the value of
3505 `org-use-tag-inheritance' would select it for inheritance.
3507 If this option is t, a match early-on in a tree can lead to a large
3508 number of matches in the subtree when constructing the agenda or creating
3509 a sparse tree. If you only want to see the first match in a tree during
3510 a search, check out the variable `org-tags-match-list-sublevels'."
3511 :group 'org-tags
3512 :type '(choice
3513 (const :tag "Not" nil)
3514 (const :tag "Always" t)
3515 (repeat :tag "Specific tags" (string :tag "Tag"))
3516 (regexp :tag "Tags matched by regexp")))
3518 (defcustom org-tags-exclude-from-inheritance nil
3519 "List of tags that should never be inherited.
3520 This is a way to exclude a few tags from inheritance. For way to do
3521 the opposite, to actively allow inheritance for selected tags,
3522 see the variable `org-use-tag-inheritance'."
3523 :group 'org-tags
3524 :type '(repeat (string :tag "Tag")))
3526 (defun org-tag-inherit-p (tag)
3527 "Check if TAG is one that should be inherited."
3528 (cond
3529 ((member tag org-tags-exclude-from-inheritance) nil)
3530 ((eq org-use-tag-inheritance t) t)
3531 ((not org-use-tag-inheritance) nil)
3532 ((stringp org-use-tag-inheritance)
3533 (string-match org-use-tag-inheritance tag))
3534 ((listp org-use-tag-inheritance)
3535 (member tag org-use-tag-inheritance))
3536 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3538 (defcustom org-tags-match-list-sublevels t
3539 "Non-nil means list also sublevels of headlines matching a search.
3540 This variable applies to tags/property searches, and also to stuck
3541 projects because this search is based on a tags match as well.
3543 When set to the symbol `indented', sublevels are indented with
3544 leading dots.
3546 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3547 the sublevels of a headline matching a tag search often also match
3548 the same search. Listing all of them can create very long lists.
3549 Setting this variable to nil causes subtrees of a match to be skipped.
3551 This variable is semi-obsolete and probably should always be true. It
3552 is better to limit inheritance to certain tags using the variables
3553 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3554 :group 'org-tags
3555 :type '(choice
3556 (const :tag "No, don't list them" nil)
3557 (const :tag "Yes, do list them" t)
3558 (const :tag "List them, indented with leading dots" indented)))
3560 (defcustom org-tags-sort-function nil
3561 "When set, tags are sorted using this function as a comparator."
3562 :group 'org-tags
3563 :type '(choice
3564 (const :tag "No sorting" nil)
3565 (const :tag "Alphabetical" string<)
3566 (const :tag "Reverse alphabetical" string>)
3567 (function :tag "Custom function" nil)))
3569 (defvar org-tags-history nil
3570 "History of minibuffer reads for tags.")
3571 (defvar org-last-tags-completion-table nil
3572 "The last used completion table for tags.")
3573 (defvar org-after-tags-change-hook nil
3574 "Hook that is run after the tags in a line have changed.")
3576 (defgroup org-properties nil
3577 "Options concerning properties in Org mode."
3578 :tag "Org Properties"
3579 :group 'org)
3581 (defcustom org-property-format "%-10s %s"
3582 "How property key/value pairs should be formatted by `indent-line'.
3583 When `indent-line' hits a property definition, it will format the line
3584 according to this format, mainly to make sure that the values are
3585 lined-up with respect to each other."
3586 :group 'org-properties
3587 :type 'string)
3589 (defcustom org-properties-postprocess-alist nil
3590 "Alist of properties and functions to adjust inserted values.
3591 Elements of this alist must be of the form
3593 ([string] [function])
3595 where [string] must be a property name and [function] must be a
3596 lambda expression: this lambda expression must take one argument,
3597 the value to adjust, and return the new value as a string.
3599 For example, this element will allow the property \"Remaining\"
3600 to be updated wrt the relation between the \"Effort\" property
3601 and the clock summary:
3603 ((\"Remaining\" (lambda(value)
3604 (let ((clocksum (org-clock-sum-current-item))
3605 (effort (org-duration-to-minutes
3606 (org-entry-get (point) \"Effort\"))))
3607 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3608 :group 'org-properties
3609 :version "24.1"
3610 :type '(alist :key-type (string :tag "Property")
3611 :value-type (function :tag "Function")))
3613 (defcustom org-use-property-inheritance nil
3614 "Non-nil means properties apply also for sublevels.
3616 This setting is chiefly used during property searches. Turning it on can
3617 cause significant overhead when doing a search, which is why it is not
3618 on by default.
3620 When nil, only the properties directly given in the current entry count.
3621 When t, every property is inherited. The value may also be a list of
3622 properties that should have inheritance, or a regular expression matching
3623 properties that should be inherited.
3625 However, note that some special properties use inheritance under special
3626 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3627 and the properties ending in \"_ALL\" when they are used as descriptor
3628 for valid values of a property.
3630 Note for programmers:
3631 When querying an entry with `org-entry-get', you can control if inheritance
3632 should be used. By default, `org-entry-get' looks only at the local
3633 properties. You can request inheritance by setting the inherit argument
3634 to t (to force inheritance) or to `selective' (to respect the setting
3635 in this variable)."
3636 :group 'org-properties
3637 :type '(choice
3638 (const :tag "Not" nil)
3639 (const :tag "Always" t)
3640 (repeat :tag "Specific properties" (string :tag "Property"))
3641 (regexp :tag "Properties matched by regexp")))
3643 (defun org-property-inherit-p (property)
3644 "Return a non-nil value if PROPERTY should be inherited."
3645 (cond
3646 ((eq org-use-property-inheritance t) t)
3647 ((not org-use-property-inheritance) nil)
3648 ((stringp org-use-property-inheritance)
3649 (string-match org-use-property-inheritance property))
3650 ((listp org-use-property-inheritance)
3651 (member-ignore-case property org-use-property-inheritance))
3652 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3654 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3655 "The default column format, if no other format has been defined.
3656 This variable can be set on the per-file basis by inserting a line
3658 #+COLUMNS: %25ITEM ....."
3659 :group 'org-properties
3660 :type 'string)
3662 (defcustom org-columns-ellipses ".."
3663 "The ellipses to be used when a field in column view is truncated.
3664 When this is the empty string, as many characters as possible are shown,
3665 but then there will be no visual indication that the field has been truncated.
3666 When this is a string of length N, the last N characters of a truncated
3667 field are replaced by this string. If the column is narrower than the
3668 ellipses string, only part of the ellipses string will be shown."
3669 :group 'org-properties
3670 :type 'string)
3672 (defconst org-global-properties-fixed
3673 '(("VISIBILITY_ALL" . "folded children content all")
3674 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3675 "List of property/value pairs that can be inherited by any entry.
3677 These are fixed values, for the preset properties. The user variable
3678 that can be used to add to this list is `org-global-properties'.
3680 The entries in this list are cons cells where the car is a property
3681 name and cdr is a string with the value. If the value represents
3682 multiple items like an \"_ALL\" property, separate the items by
3683 spaces.")
3685 (defcustom org-global-properties nil
3686 "List of property/value pairs that can be inherited by any entry.
3688 This list will be combined with the constant `org-global-properties-fixed'.
3690 The entries in this list are cons cells where the car is a property
3691 name and cdr is a string with the value.
3693 You can set buffer-local values for the same purpose in the variable
3694 `org-file-properties' this by adding lines like
3696 #+PROPERTY: NAME VALUE"
3697 :group 'org-properties
3698 :type '(repeat
3699 (cons (string :tag "Property")
3700 (string :tag "Value"))))
3702 (defvar-local org-file-properties nil
3703 "List of property/value pairs that can be inherited by any entry.
3704 Valid for the current buffer.
3705 This variable is populated from #+PROPERTY lines.")
3707 (defgroup org-agenda nil
3708 "Options concerning agenda views in Org mode."
3709 :tag "Org Agenda"
3710 :group 'org)
3712 (defvar-local org-category nil
3713 "Variable used by org files to set a category for agenda display.
3714 Such files should use a file variable to set it, for example
3716 # -*- mode: org; org-category: \"ELisp\"
3718 or contain a special line
3720 #+CATEGORY: ELisp
3722 If the file does not specify a category, then file's base name
3723 is used instead.")
3724 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3726 (defcustom org-agenda-files nil
3727 "The files to be used for agenda display.
3729 If an entry is a directory, all files in that directory that are matched
3730 by `org-agenda-file-regexp' will be part of the file list.
3732 If the value of the variable is not a list but a single file name, then
3733 the list of agenda files is actually stored and maintained in that file,
3734 one agenda file per line. In this file paths can be given relative to
3735 `org-directory'. Tilde expansion and environment variable substitution
3736 are also made.
3738 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3739 and removed with `\\[org-remove-file]'."
3740 :group 'org-agenda
3741 :type '(choice
3742 (repeat :tag "List of files and directories" file)
3743 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3745 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3746 "Regular expression to match files for `org-agenda-files'.
3747 If any element in the list in that variable contains a directory instead
3748 of a normal file, all files in that directory that are matched by this
3749 regular expression will be included."
3750 :group 'org-agenda
3751 :type 'regexp)
3753 (defcustom org-agenda-text-search-extra-files nil
3754 "List of extra files to be searched by text search commands.
3755 These files will be searched in addition to the agenda files by the
3756 commands `org-search-view' (`\\[org-agenda] s') \
3757 and `org-occur-in-agenda-files'.
3758 Note that these files will only be searched for text search commands,
3759 not for the other agenda views like todo lists, tag searches or the weekly
3760 agenda. This variable is intended to list notes and possibly archive files
3761 that should also be searched by these two commands.
3762 In fact, if the first element in the list is the symbol `agenda-archives',
3763 then all archive files of all agenda files will be added to the search
3764 scope."
3765 :group 'org-agenda
3766 :type '(set :greedy t
3767 (const :tag "Agenda Archives" agenda-archives)
3768 (repeat :inline t (file))))
3770 (defvaralias 'org-agenda-multi-occur-extra-files
3771 'org-agenda-text-search-extra-files)
3773 (defcustom org-agenda-skip-unavailable-files nil
3774 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3775 A nil value means to remove them, after a query, from the list."
3776 :group 'org-agenda
3777 :type 'boolean)
3779 (defcustom org-calendar-to-agenda-key [?c]
3780 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3781 The command `org-calendar-goto-agenda' will be bound to this key. The
3782 default is the character `c' because then `c' can be used to switch back and
3783 forth between agenda and calendar."
3784 :group 'org-agenda
3785 :type 'sexp)
3787 (defcustom org-calendar-insert-diary-entry-key [?i]
3788 "The key to be installed in `calendar-mode-map' for adding diary entries.
3789 This option is irrelevant until `org-agenda-diary-file' has been configured
3790 to point to an Org file. When that is the case, the command
3791 `org-agenda-diary-entry' will be bound to the key given here, by default
3792 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3793 if you want to continue doing this, you need to change this to a different
3794 key."
3795 :group 'org-agenda
3796 :type 'sexp)
3798 (defcustom org-agenda-diary-file 'diary-file
3799 "File to which to add new entries with the `i' key in agenda and calendar.
3800 When this is the symbol `diary-file', the functionality in the Emacs
3801 calendar will be used to add entries to the `diary-file'. But when this
3802 points to a file, `org-agenda-diary-entry' will be used instead."
3803 :group 'org-agenda
3804 :type '(choice
3805 (const :tag "The standard Emacs diary file" diary-file)
3806 (file :tag "Special Org file diary entries")))
3808 (eval-after-load "calendar"
3809 '(progn
3810 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3811 'org-calendar-goto-agenda)
3812 (add-hook 'calendar-mode-hook
3813 (lambda ()
3814 (unless (eq org-agenda-diary-file 'diary-file)
3815 (define-key calendar-mode-map
3816 org-calendar-insert-diary-entry-key
3817 'org-agenda-diary-entry))))))
3819 (defgroup org-latex nil
3820 "Options for embedding LaTeX code into Org mode."
3821 :tag "Org LaTeX"
3822 :group 'org)
3824 (defcustom org-format-latex-options
3825 '(:foreground default :background default :scale 1.0
3826 :html-foreground "Black" :html-background "Transparent"
3827 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3828 "Options for creating images from LaTeX fragments.
3829 This is a property list with the following properties:
3830 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3831 `default' means use the foreground of the default face.
3832 `auto' means use the foreground from the text face.
3833 :background the background color, or \"Transparent\".
3834 `default' means use the background of the default face.
3835 `auto' means use the background from the text face.
3836 :scale a scaling factor for the size of the images, to get more pixels
3837 :html-foreground, :html-background, :html-scale
3838 the same numbers for HTML export.
3839 :matchers a list indicating which matchers should be used to
3840 find LaTeX fragments. Valid members of this list are:
3841 \"begin\" find environments
3842 \"$1\" find single characters surrounded by $.$
3843 \"$\" find math expressions surrounded by $...$
3844 \"$$\" find math expressions surrounded by $$....$$
3845 \"\\(\" find math expressions surrounded by \\(...\\)
3846 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3847 :group 'org-latex
3848 :type 'plist)
3850 (defcustom org-format-latex-signal-error t
3851 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3852 When nil, just push out a message."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type 'boolean)
3857 (defcustom org-latex-to-mathml-jar-file nil
3858 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3859 Use this to specify additional executable file say a jar file.
3861 When using MathToWeb as the converter, specify the full-path to
3862 your mathtoweb.jar file."
3863 :group 'org-latex
3864 :version "24.1"
3865 :type '(choice
3866 (const :tag "None" nil)
3867 (file :tag "JAR file" :must-match t)))
3869 (defcustom org-latex-to-mathml-convert-command nil
3870 "Command to convert LaTeX fragments to MathML.
3871 Replace format-specifiers in the command as noted below and use
3872 `shell-command' to convert LaTeX to MathML.
3873 %j: Executable file in fully expanded form as specified by
3874 `org-latex-to-mathml-jar-file'.
3875 %I: Input LaTeX file in fully expanded form.
3876 %i: The latex fragment to be converted.
3877 %o: Output MathML file.
3879 This command is used by `org-create-math-formula'.
3881 When using MathToWeb as the converter, set this option to
3882 \"java -jar %j -unicode -force -df %o %I\".
3884 When using LaTeXML set this option to
3885 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3886 :group 'org-latex
3887 :version "24.1"
3888 :type '(choice
3889 (const :tag "None" nil)
3890 (string :tag "\nShell command")))
3892 (defcustom org-preview-latex-default-process 'dvipng
3893 "The default process to convert LaTeX fragments to image files.
3894 All available processes and theirs documents can be found in
3895 `org-preview-latex-process-alist', which see."
3896 :group 'org-latex
3897 :version "26.1"
3898 :package-version '(Org . "9.0")
3899 :type 'symbol)
3901 (defcustom org-preview-latex-process-alist
3902 '((dvipng
3903 :programs ("latex" "dvipng")
3904 :description "dvi > png"
3905 :message "you need to install the programs: latex and dvipng."
3906 :image-input-type "dvi"
3907 :image-output-type "png"
3908 :image-size-adjust (1.0 . 1.0)
3909 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3910 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3911 (dvisvgm
3912 :programs ("latex" "dvisvgm")
3913 :description "dvi > svg"
3914 :message "you need to install the programs: latex and dvisvgm."
3915 :use-xcolor t
3916 :image-input-type "dvi"
3917 :image-output-type "svg"
3918 :image-size-adjust (1.7 . 1.5)
3919 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3920 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3921 (imagemagick
3922 :programs ("latex" "convert")
3923 :description "pdf > png"
3924 :message "you need to install the programs: latex and imagemagick."
3925 :use-xcolor t
3926 :image-input-type "pdf"
3927 :image-output-type "png"
3928 :image-size-adjust (1.0 . 1.0)
3929 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3930 :image-converter
3931 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3932 "Definitions of external processes for LaTeX previewing.
3933 Org mode can use some external commands to generate TeX snippet's images for
3934 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3935 `org-create-formula-image' how to call them.
3937 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3938 PROPERTIES accepts the following attributes:
3940 :programs list of strings, required programs.
3941 :description string, describe the process.
3942 :message string, message it when required programs cannot be found.
3943 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3944 :image-output-type string, output file type of image converter (e.g., \"png\").
3945 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3946 deal with background and foreground color of image.
3947 Otherwise, dvipng style background and foreground color
3948 format are generated. You may then refer to them in
3949 command options with \"%F\" and \"%B\".
3950 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3951 image size showed in buffer and the cdr element is for
3952 HTML file. This option is only useful for process
3953 developers, users should use variable
3954 `org-format-latex-options' instead.
3955 :post-clean list of strings, files matched are to be cleaned up once
3956 the image is generated. When nil, the files with \".dvi\",
3957 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3958 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3959 be cleaned up.
3960 :latex-header list of strings, the LaTeX header of the snippet file.
3961 When nil, the fallback value is used instead, which is
3962 controlled by `org-format-latex-header',
3963 `org-latex-default-packages-alist' and
3964 `org-latex-packages-alist', which see.
3965 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3966 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3967 replaced with values defined below.
3968 :image-converter list of image converter commands strings. Each of them is
3969 given to the shell and supports any of the following
3970 place-holders defined below.
3972 Place-holders used by `:image-converter' and `:latex-compiler':
3974 %f input file name
3975 %b base name of input file
3976 %o base directory of input file
3977 %O absolute output file name
3979 Place-holders only used by `:image-converter':
3981 %F foreground of image
3982 %B background of image
3983 %D dpi, which is used to adjust image size by some processing commands.
3984 %S the image size scale ratio, which is used to adjust image size by some
3985 processing commands."
3986 :group 'org-latex
3987 :version "26.1"
3988 :package-version '(Org . "9.0")
3989 :type '(alist :tag "LaTeX to image backends"
3990 :value-type (plist)))
3992 (defcustom org-preview-latex-image-directory "ltximg/"
3993 "Path to store latex preview images.
3994 A relative path here creates many directories relative to the
3995 processed org files paths. An absolute path puts all preview
3996 images at the same place."
3997 :group 'org-latex
3998 :version "26.1"
3999 :package-version '(Org . "9.0")
4000 :type 'string)
4002 (defun org-format-latex-mathml-available-p ()
4003 "Return t if `org-latex-to-mathml-convert-command' is usable."
4004 (save-match-data
4005 (when (and (boundp 'org-latex-to-mathml-convert-command)
4006 org-latex-to-mathml-convert-command)
4007 (let ((executable (car (split-string
4008 org-latex-to-mathml-convert-command))))
4009 (when (executable-find executable)
4010 (if (string-match
4011 "%j" org-latex-to-mathml-convert-command)
4012 (file-readable-p org-latex-to-mathml-jar-file)
4013 t))))))
4015 (defcustom org-format-latex-header "\\documentclass{article}
4016 \\usepackage[usenames]{color}
4017 \[PACKAGES]
4018 \[DEFAULT-PACKAGES]
4019 \\pagestyle{empty} % do not remove
4020 % The settings below are copied from fullpage.sty
4021 \\setlength{\\textwidth}{\\paperwidth}
4022 \\addtolength{\\textwidth}{-3cm}
4023 \\setlength{\\oddsidemargin}{1.5cm}
4024 \\addtolength{\\oddsidemargin}{-2.54cm}
4025 \\setlength{\\evensidemargin}{\\oddsidemargin}
4026 \\setlength{\\textheight}{\\paperheight}
4027 \\addtolength{\\textheight}{-\\headheight}
4028 \\addtolength{\\textheight}{-\\headsep}
4029 \\addtolength{\\textheight}{-\\footskip}
4030 \\addtolength{\\textheight}{-3cm}
4031 \\setlength{\\topmargin}{1.5cm}
4032 \\addtolength{\\topmargin}{-2.54cm}"
4033 "The document header used for processing LaTeX fragments.
4034 It is imperative that this header make sure that no page number
4035 appears on the page. The package defined in the variables
4036 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4037 will either replace the placeholder \"[PACKAGES]\" in this
4038 header, or they will be appended."
4039 :group 'org-latex
4040 :type 'string)
4042 (defun org-set-packages-alist (var val)
4043 "Set the packages alist and make sure it has 3 elements per entry."
4044 (set var (mapcar (lambda (x)
4045 (if (and (consp x) (= (length x) 2))
4046 (list (car x) (nth 1 x) t)
4048 val)))
4050 (defun org-get-packages-alist (var)
4051 "Get the packages alist and make sure it has 3 elements per entry."
4052 (mapcar (lambda (x)
4053 (if (and (consp x) (= (length x) 2))
4054 (list (car x) (nth 1 x) t)
4056 (default-value var)))
4058 (defcustom org-latex-default-packages-alist
4059 '(("AUTO" "inputenc" t ("pdflatex"))
4060 ("T1" "fontenc" t ("pdflatex"))
4061 ("" "graphicx" t)
4062 ("" "grffile" t)
4063 ("" "longtable" nil)
4064 ("" "wrapfig" nil)
4065 ("" "rotating" nil)
4066 ("normalem" "ulem" t)
4067 ("" "amsmath" t)
4068 ("" "textcomp" t)
4069 ("" "amssymb" t)
4070 ("" "capt-of" nil)
4071 ("" "hyperref" nil))
4072 "Alist of default packages to be inserted in the header.
4074 Change this only if one of the packages here causes an
4075 incompatibility with another package you are using.
4077 The packages in this list are needed by one part or another of
4078 Org mode to function properly:
4080 - inputenc, fontenc: for basic font and character selection
4081 - graphicx: for including images
4082 - grffile: allow periods and spaces in graphics file names
4083 - longtable: For multipage tables
4084 - wrapfig: for figure placement
4085 - rotating: for sideways figures and tables
4086 - ulem: for underline and strike-through
4087 - amsmath: for subscript and superscript and math environments
4088 - textcomp, amssymb: for various symbols used
4089 for interpreting the entities in `org-entities'. You can skip
4090 some of these packages if you don't use any of their symbols.
4091 - capt-of: for captions outside of floats
4092 - hyperref: for cross references
4094 Therefore you should not modify this variable unless you know
4095 what you are doing. The one reason to change it anyway is that
4096 you might be loading some other package that conflicts with one
4097 of the default packages. Each element is either a cell or
4098 a string.
4100 A cell is of the format
4102 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4104 If SNIPPET-FLAG is non-nil, the package also needs to be included
4105 when compiling LaTeX snippets into images for inclusion into
4106 non-LaTeX output. COMPILERS is a list of compilers that should
4107 include the package, see `org-latex-compiler'. If the document
4108 compiler is not in the list, and the list is non-nil, the package
4109 will not be inserted in the final document.
4111 A string will be inserted as-is in the header of the document."
4112 :group 'org-latex
4113 :group 'org-export-latex
4114 :set 'org-set-packages-alist
4115 :get 'org-get-packages-alist
4116 :version "26.1"
4117 :package-version '(Org . "8.3")
4118 :type '(repeat
4119 (choice
4120 (list :tag "options/package pair"
4121 (string :tag "options")
4122 (string :tag "package")
4123 (boolean :tag "Snippet")
4124 (choice
4125 (const :tag "For all compilers" nil)
4126 (repeat :tag "Allowed compiler" string)))
4127 (string :tag "A line of LaTeX"))))
4129 (defcustom org-latex-packages-alist nil
4130 "Alist of packages to be inserted in every LaTeX header.
4132 These will be inserted after `org-latex-default-packages-alist'.
4133 Each element is either a cell or a string.
4135 A cell is of the format:
4137 (\"options\" \"package\" SNIPPET-FLAG)
4139 SNIPPET-FLAG, when non-nil, indicates that this package is also
4140 needed when turning LaTeX snippets into images for inclusion into
4141 non-LaTeX output.
4143 A string will be inserted as-is in the header of the document.
4145 Make sure that you only list packages here which:
4147 - you want in every file;
4148 - do not conflict with the setup in `org-format-latex-header';
4149 - do not conflict with the default packages in
4150 `org-latex-default-packages-alist'."
4151 :group 'org-latex
4152 :group 'org-export-latex
4153 :set 'org-set-packages-alist
4154 :get 'org-get-packages-alist
4155 :type '(repeat
4156 (choice
4157 (list :tag "options/package pair"
4158 (string :tag "options")
4159 (string :tag "package")
4160 (boolean :tag "Snippet"))
4161 (string :tag "A line of LaTeX"))))
4163 (defgroup org-appearance nil
4164 "Settings for Org mode appearance."
4165 :tag "Org Appearance"
4166 :group 'org)
4168 (defcustom org-level-color-stars-only nil
4169 "Non-nil means fontify only the stars in each headline.
4170 When nil, the entire headline is fontified.
4171 Changing it requires restart of `font-lock-mode' to become effective
4172 also in regions already fontified."
4173 :group 'org-appearance
4174 :type 'boolean)
4176 (defcustom org-hide-leading-stars nil
4177 "Non-nil means hide the first N-1 stars in a headline.
4178 This works by using the face `org-hide' for these stars. This
4179 face is white for a light background, and black for a dark
4180 background. You may have to customize the face `org-hide' to
4181 make this work.
4182 Changing it requires restart of `font-lock-mode' to become effective
4183 also in regions already fontified.
4184 You may also set this on a per-file basis by adding one of the following
4185 lines to the buffer:
4187 #+STARTUP: hidestars
4188 #+STARTUP: showstars"
4189 :group 'org-appearance
4190 :type 'boolean)
4192 (defcustom org-hidden-keywords nil
4193 "List of symbols corresponding to keywords to be hidden the org buffer.
4194 For example, a value \\='(title) for this list will make the document's title
4195 appear in the buffer without the initial #+TITLE: keyword."
4196 :group 'org-appearance
4197 :version "24.1"
4198 :type '(set (const :tag "#+AUTHOR" author)
4199 (const :tag "#+DATE" date)
4200 (const :tag "#+EMAIL" email)
4201 (const :tag "#+TITLE" title)))
4203 (defcustom org-custom-properties nil
4204 "List of properties (as strings) with a special meaning.
4205 The default use of these custom properties is to let the user
4206 hide them with `org-toggle-custom-properties-visibility'."
4207 :group 'org-properties
4208 :group 'org-appearance
4209 :version "24.3"
4210 :type '(repeat (string :tag "Property Name")))
4212 (defcustom org-fontify-done-headline nil
4213 "Non-nil means change the face of a headline if it is marked DONE.
4214 Normally, only the TODO/DONE keyword indicates the state of a headline.
4215 When this is non-nil, the headline after the keyword is set to the
4216 `org-headline-done' as an additional indication."
4217 :group 'org-appearance
4218 :type 'boolean)
4220 (defcustom org-fontify-emphasized-text t
4221 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4222 Changing this variable requires a restart of Emacs to take effect."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-fontify-whole-heading-line nil
4227 "Non-nil means fontify the whole line for headings.
4228 This is useful when setting a background color for the
4229 org-level-* faces."
4230 :group 'org-appearance
4231 :type 'boolean)
4233 (defcustom org-highlight-latex-and-related nil
4234 "Non-nil means highlight LaTeX related syntax in the buffer.
4235 When non nil, the value should be a list containing any of the
4236 following symbols:
4237 `latex' Highlight LaTeX snippets and environments.
4238 `script' Highlight subscript and superscript.
4239 `entities' Highlight entities."
4240 :group 'org-appearance
4241 :version "24.4"
4242 :package-version '(Org . "8.0")
4243 :type '(choice
4244 (const :tag "No highlighting" nil)
4245 (set :greedy t :tag "Highlight"
4246 (const :tag "LaTeX snippets and environments" latex)
4247 (const :tag "Subscript and superscript" script)
4248 (const :tag "Entities" entities))))
4250 (defcustom org-hide-emphasis-markers nil
4251 "Non-nil mean font-lock should hide the emphasis marker characters."
4252 :group 'org-appearance
4253 :type 'boolean)
4255 (defcustom org-hide-macro-markers nil
4256 "Non-nil mean font-lock should hide the brackets marking macro calls."
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-pretty-entities nil
4261 "Non-nil means show entities as UTF8 characters.
4262 When nil, the \\name form remains in the buffer."
4263 :group 'org-appearance
4264 :version "24.1"
4265 :type 'boolean)
4267 (defcustom org-pretty-entities-include-sub-superscripts t
4268 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4269 :group 'org-appearance
4270 :version "24.1"
4271 :type 'boolean)
4273 (defvar org-emph-re nil
4274 "Regular expression for matching emphasis.
4275 After a match, the match groups contain these elements:
4276 0 The match of the full regular expression, including the characters
4277 before and after the proper match
4278 1 The character before the proper match, or empty at beginning of line
4279 2 The proper match, including the leading and trailing markers
4280 3 The leading marker like * or /, indicating the type of highlighting
4281 4 The text between the emphasis markers, not including the markers
4282 5 The character after the match, empty at the end of a line")
4284 (defvar org-verbatim-re nil
4285 "Regular expression for matching verbatim text.")
4287 (defvar org-emphasis-regexp-components) ; defined just below
4288 (defvar org-emphasis-alist) ; defined just below
4289 (defun org-set-emph-re (var val)
4290 "Set variable and compute the emphasis regular expression."
4291 (set var val)
4292 (when (and (boundp 'org-emphasis-alist)
4293 (boundp 'org-emphasis-regexp-components)
4294 org-emphasis-alist org-emphasis-regexp-components)
4295 (pcase-let*
4296 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4297 (body (if (<= nl 0) body
4298 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4299 (template
4300 (format (concat "\\([%s]\\|^\\)" ;before markers
4301 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4302 "\\([%s]\\|$\\)") ;after markers
4303 pre border border body border post)))
4304 (setq org-emph-re (format template "*/_+"))
4305 (setq org-verbatim-re (format template "=~")))))
4307 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4308 ;; set this option proved cumbersome. See this message/thread:
4309 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4310 (defvar org-emphasis-regexp-components
4311 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4312 "Components used to build the regular expression for emphasis.
4313 This is a list with five entries. Terminology: In an emphasis string
4314 like \" *strong word* \", we call the initial space PREMATCH, the final
4315 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4316 and \"trong wor\" is the body. The different components in this variable
4317 specify what is allowed/forbidden in each part:
4319 pre Chars allowed as prematch. Beginning of line will be allowed too.
4320 post Chars allowed as postmatch. End of line will be allowed too.
4321 border The chars *forbidden* as border characters.
4322 body-regexp A regexp like \".\" to match a body character. Don't use
4323 non-shy groups here, and don't allow newline here.
4324 newline The maximum number of newlines allowed in an emphasis exp.
4326 You need to reload Org or to restart Emacs after setting this.")
4328 (defcustom org-emphasis-alist
4329 '(("*" bold)
4330 ("/" italic)
4331 ("_" underline)
4332 ("=" org-verbatim verbatim)
4333 ("~" org-code verbatim)
4334 ("+" (:strike-through t)))
4335 "Alist of characters and faces to emphasize text.
4336 Text starting and ending with a special character will be emphasized,
4337 for example *bold*, _underlined_ and /italic/. This variable sets the
4338 marker characters and the face to be used by font-lock for highlighting
4339 in Org buffers.
4341 You need to reload Org or to restart Emacs after customizing this."
4342 :group 'org-appearance
4343 :set 'org-set-emph-re
4344 :version "24.4"
4345 :package-version '(Org . "8.0")
4346 :type '(repeat
4347 (list
4348 (string :tag "Marker character")
4349 (choice
4350 (face :tag "Font-lock-face")
4351 (plist :tag "Face property list"))
4352 (option (const verbatim)))))
4354 (defvar org-protecting-blocks '("src" "example" "export")
4355 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4356 This is needed for font-lock setup.")
4358 ;;; Functions and variables from their packages
4359 ;; Declared here to avoid compiler warnings
4360 (defvar mark-active)
4362 ;; Various packages
4363 (declare-function calc-eval "calc" (str &optional separator &rest args))
4364 (declare-function calendar-forward-day "cal-move" (arg))
4365 (declare-function calendar-goto-date "cal-move" (date))
4366 (declare-function calendar-goto-today "cal-move" ())
4367 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4368 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4369 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4370 (declare-function cdlatex-tab "ext:cdlatex" ())
4371 (declare-function dired-get-filename
4372 "dired"
4373 (&optional localp no-error-if-not-filep))
4374 (declare-function iswitchb-read-buffer
4375 "iswitchb"
4376 (prompt &optional
4377 default require-match _predicate start matches-set))
4378 (declare-function org-agenda-change-all-lines
4379 "org-agenda"
4380 (newhead hdmarker &optional fixface just-this))
4381 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4382 "org-agenda"
4383 (&optional end))
4384 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4385 (declare-function org-agenda-format-item
4386 "org-agenda"
4387 (extra txt &optional level category tags dotime
4388 remove-re habitp))
4389 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4390 (declare-function org-agenda-save-markers-for-cut-and-paste
4391 "org-agenda"
4392 (beg end))
4393 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4394 (declare-function org-agenda-skip "org-agenda" ())
4395 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4396 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4397 (declare-function org-indent-mode "org-indent" (&optional arg))
4398 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4399 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4400 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4401 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4402 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4403 (declare-function parse-time-string "parse-time" (string))
4405 (defvar align-mode-rules-list)
4406 (defvar calc-embedded-close-formula)
4407 (defvar calc-embedded-open-formula)
4408 (defvar calc-embedded-open-mode)
4409 (defvar font-lock-unfontify-region-function)
4410 (defvar iswitchb-temp-buflist)
4411 (defvar org-agenda-tags-todo-honor-ignore-options)
4412 (defvar remember-data-file)
4413 (defvar texmathp-why)
4415 ;;;###autoload
4416 (defun turn-on-orgtbl ()
4417 "Unconditionally turn on `orgtbl-mode'."
4418 (require 'org-table)
4419 (orgtbl-mode 1))
4421 (defun org-at-table-p (&optional table-type)
4422 "Non-nil if the cursor is inside an Org table.
4423 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4424 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4425 (or (not (derived-mode-p 'org-mode))
4426 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4427 (and e (or table-type
4428 (eq 'org (org-element-property :type e))))))))
4430 (defun org-at-table.el-p ()
4431 "Non-nil when point is at a table.el table."
4432 (and (org-match-line "[ \t]*[|+]")
4433 (let ((element (org-element-at-point)))
4434 (and (eq (org-element-type element) 'table)
4435 (eq (org-element-property :type element) 'table.el)))))
4437 (defun org-at-table-hline-p ()
4438 "Non-nil when point is inside a hline in a table.
4439 Assume point is already in a table."
4440 (org-match-line org-table-hline-regexp))
4442 (defun org-table-map-tables (function &optional quietly)
4443 "Apply FUNCTION to the start of all tables in the buffer."
4444 (org-with-wide-buffer
4445 (goto-char (point-min))
4446 (while (re-search-forward org-table-any-line-regexp nil t)
4447 (unless quietly
4448 (message "Mapping tables: %d%%"
4449 (floor (* 100.0 (point)) (buffer-size))))
4450 (beginning-of-line 1)
4451 (when (and (looking-at org-table-line-regexp)
4452 ;; Exclude tables in src/example/verbatim/clocktable blocks
4453 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4454 (save-excursion (funcall function))
4455 (or (looking-at org-table-line-regexp)
4456 (forward-char 1)))
4457 (re-search-forward org-table-any-border-regexp nil 1)))
4458 (unless quietly (message "Mapping tables: done")))
4460 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4461 (declare-function org-clock-update-mode-line "org-clock" ())
4462 (declare-function org-resolve-clocks "org-clock"
4463 (&optional also-non-dangling-p prompt last-valid))
4465 (defun org-at-TBLFM-p (&optional pos)
4466 "Non-nil when point (or POS) is in #+TBLFM line."
4467 (save-excursion
4468 (goto-char (or pos (point)))
4469 (beginning-of-line)
4470 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4471 (eq (org-element-type (org-element-at-point)) 'table))))
4473 (defvar org-clock-start-time)
4474 (defvar org-clock-marker (make-marker)
4475 "Marker recording the last clock-in.")
4476 (defvar org-clock-hd-marker (make-marker)
4477 "Marker recording the last clock-in, but the headline position.")
4478 (defvar org-clock-heading ""
4479 "The heading of the current clock entry.")
4480 (defun org-clock-is-active ()
4481 "Return the buffer where the clock is currently running.
4482 Return nil if no clock is running."
4483 (marker-buffer org-clock-marker))
4485 (defun org-check-running-clock ()
4486 "Check if the current buffer contains the running clock.
4487 If yes, offer to stop it and to save the buffer with the changes."
4488 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4489 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4490 (buffer-name))))
4491 (org-clock-out)
4492 (when (y-or-n-p "Save changed buffer?")
4493 (save-buffer))))
4495 (defun org-clocktable-try-shift (dir n)
4496 "Check if this line starts a clock table, if yes, shift the time block."
4497 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4498 (org-clocktable-shift dir n)))
4500 ;;;###autoload
4501 (defun org-clock-persistence-insinuate ()
4502 "Set up hooks for clock persistence."
4503 (require 'org-clock)
4504 (add-hook 'org-mode-hook 'org-clock-load)
4505 (add-hook 'kill-emacs-hook 'org-clock-save))
4507 (defgroup org-archive nil
4508 "Options concerning archiving in Org mode."
4509 :tag "Org Archive"
4510 :group 'org-structure)
4512 (defcustom org-archive-location "%s_archive::"
4513 "The location where subtrees should be archived.
4515 The value of this variable is a string, consisting of two parts,
4516 separated by a double-colon. The first part is a filename and
4517 the second part is a headline.
4519 When the filename is omitted, archiving happens in the same file.
4520 %s in the filename will be replaced by the current file
4521 name (without the directory part). Archiving to a different file
4522 is useful to keep archived entries from contributing to the
4523 Org Agenda.
4525 The archived entries will be filed as subtrees of the specified
4526 headline. When the headline is omitted, the subtrees are simply
4527 filed away at the end of the file, as top-level entries. Also in
4528 the heading you can use %s to represent the file name, this can be
4529 useful when using the same archive for a number of different files.
4531 Here are a few examples:
4532 \"%s_archive::\"
4533 If the current file is Projects.org, archive in file
4534 Projects.org_archive, as top-level trees. This is the default.
4536 \"::* Archived Tasks\"
4537 Archive in the current file, under the top-level headline
4538 \"* Archived Tasks\".
4540 \"~/org/archive.org::\"
4541 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4543 \"~/org/archive.org::* From %s\"
4544 Archive in file ~/org/archive.org (absolute path), under headlines
4545 \"From FILENAME\" where file name is the current file name.
4547 \"~/org/datetree.org::datetree/* Finished Tasks\"
4548 The \"datetree/\" string is special, signifying to archive
4549 items to the datetree. Items are placed in either the CLOSED
4550 date of the item, or the current date if there is no CLOSED date.
4551 The heading will be a subentry to the current date. There doesn't
4552 need to be a heading, but there always needs to be a slash after
4553 datetree. For example, to store archived items directly in the
4554 datetree, use \"~/org/datetree.org::datetree/\".
4556 \"basement::** Finished Tasks\"
4557 Archive in file ./basement (relative path), as level 3 trees
4558 below the level 2 heading \"** Finished Tasks\".
4560 You may set this option on a per-file basis by adding to the buffer a
4561 line like
4563 #+ARCHIVE: basement::** Finished Tasks
4565 You may also define it locally for a subtree by setting an ARCHIVE property
4566 in the entry. If such a property is found in an entry, or anywhere up
4567 the hierarchy, it will be used."
4568 :group 'org-archive
4569 :type 'string)
4571 (defcustom org-agenda-skip-archived-trees t
4572 "Non-nil means the agenda will skip any items located in archived trees.
4573 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4574 variable is no longer recommended, you should leave it at the value t.
4575 Instead, use the key `v' to cycle the archives-mode in the agenda."
4576 :group 'org-archive
4577 :group 'org-agenda-skip
4578 :type 'boolean)
4580 (defcustom org-columns-skip-archived-trees t
4581 "Non-nil means ignore archived trees when creating column view."
4582 :group 'org-archive
4583 :group 'org-properties
4584 :type 'boolean)
4586 (defcustom org-cycle-open-archived-trees nil
4587 "Non-nil means `org-cycle' will open archived trees.
4588 An archived tree is a tree marked with the tag ARCHIVE.
4589 When nil, archived trees will stay folded. You can still open them with
4590 normal outline commands like `show-all', but not with the cycling commands."
4591 :group 'org-archive
4592 :group 'org-cycle
4593 :type 'boolean)
4595 (defcustom org-sparse-tree-open-archived-trees nil
4596 "Non-nil means sparse tree construction shows matches in archived trees.
4597 When nil, matches in these trees are highlighted, but the trees are kept in
4598 collapsed state."
4599 :group 'org-archive
4600 :group 'org-sparse-trees
4601 :type 'boolean)
4603 (defcustom org-sparse-tree-default-date-type nil
4604 "The default date type when building a sparse tree.
4605 When this is nil, a date is a scheduled or a deadline timestamp.
4606 Otherwise, these types are allowed:
4608 all: all timestamps
4609 active: only active timestamps (<...>)
4610 inactive: only inactive timestamps ([...])
4611 scheduled: only scheduled timestamps
4612 deadline: only deadline timestamps"
4613 :type '(choice (const :tag "Scheduled or deadline" nil)
4614 (const :tag "All timestamps" all)
4615 (const :tag "Only active timestamps" active)
4616 (const :tag "Only inactive timestamps" inactive)
4617 (const :tag "Only scheduled timestamps" scheduled)
4618 (const :tag "Only deadline timestamps" deadline)
4619 (const :tag "Only closed timestamps" closed))
4620 :version "26.1"
4621 :package-version '(Org . "8.3")
4622 :group 'org-sparse-trees)
4624 (defun org-cycle-hide-archived-subtrees (state)
4625 "Re-hide all archived subtrees after a visibility state change.
4626 STATE should be one of the symbols listed in the docstring of
4627 `org-cycle-hook'."
4628 (when (and (not org-cycle-open-archived-trees)
4629 (not (memq state '(overview folded))))
4630 (save-excursion
4631 (let* ((globalp (memq state '(contents all)))
4632 (beg (if globalp (point-min) (point)))
4633 (end (if globalp (point-max) (org-end-of-subtree t))))
4634 (org-hide-archived-subtrees beg end)
4635 (goto-char beg)
4636 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4637 (message "%s" (substitute-command-keys
4638 "Subtree is archived and stays closed. Use \
4639 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4641 (defun org-force-cycle-archived ()
4642 "Cycle subtree even if it is archived."
4643 (interactive)
4644 (setq this-command 'org-cycle)
4645 (let ((org-cycle-open-archived-trees t))
4646 (call-interactively 'org-cycle)))
4648 (defun org-hide-archived-subtrees (beg end)
4649 "Re-hide all archived subtrees after a visibility state change."
4650 (org-with-wide-buffer
4651 (let ((case-fold-search nil)
4652 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4653 (goto-char beg)
4654 ;; Include headline point is currently on.
4655 (beginning-of-line)
4656 (while (and (< (point) end) (re-search-forward re end t))
4657 (when (member org-archive-tag (org-get-tags))
4658 (org-flag-subtree t)
4659 (org-end-of-subtree t))))))
4661 (declare-function outline-end-of-heading "outline" ())
4662 (declare-function outline-flag-region "outline" (from to flag))
4663 (defun org-flag-subtree (flag)
4664 (save-excursion
4665 (org-back-to-heading t)
4666 (outline-end-of-heading)
4667 (outline-flag-region (point)
4668 (progn (org-end-of-subtree t) (point))
4669 flag)))
4671 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4673 ;; Declare Column View Code
4675 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4676 (declare-function org-columns-compute "org-colview" (property))
4678 ;; Declare ID code
4680 (declare-function org-id-store-link "org-id")
4681 (declare-function org-id-locations-load "org-id")
4682 (declare-function org-id-locations-save "org-id")
4683 (defvar org-id-track-globally)
4685 ;;; Variables for pre-computed regular expressions, all buffer local
4687 (defvar-local org-todo-regexp nil
4688 "Matches any of the TODO state keywords.
4689 Since TODO keywords are case-sensitive, `case-fold-search' is
4690 expected to be bound to nil when matching against this regexp.")
4692 (defvar-local org-not-done-regexp nil
4693 "Matches any of the TODO state keywords except the last one.
4694 Since TODO keywords are case-sensitive, `case-fold-search' is
4695 expected to be bound to nil when matching against this regexp.")
4697 (defvar-local org-not-done-heading-regexp nil
4698 "Matches a TODO headline that is not done.
4699 Since TODO keywords are case-sensitive, `case-fold-search' is
4700 expected to be bound to nil when matching against this regexp.")
4702 (defvar-local org-todo-line-regexp nil
4703 "Matches a headline and puts TODO state into group 2 if present.
4704 Since TODO keywords are case-sensitive, `case-fold-search' is
4705 expected to be bound to nil when matching against this regexp.")
4707 (defvar-local org-complex-heading-regexp nil
4708 "Matches a headline and puts everything into groups:
4710 group 1: Stars
4711 group 2: The TODO keyword, maybe
4712 group 3: Priority cookie
4713 group 4: True headline
4714 group 5: Tags
4716 Since TODO keywords are case-sensitive, `case-fold-search' is
4717 expected to be bound to nil when matching against this regexp.")
4719 (defvar-local org-complex-heading-regexp-format nil
4720 "Printf format to make regexp to match an exact headline.
4721 This regexp will match the headline of any node which has the
4722 exact headline text that is put into the format, but may have any
4723 TODO state, priority and tags.")
4725 (defvar-local org-todo-line-tags-regexp nil
4726 "Matches a headline and puts TODO state into group 2 if present.
4727 Also put tags into group 4 if tags are present.")
4729 (defconst org-plain-time-of-day-regexp
4730 (concat
4731 "\\(\\<[012]?[0-9]"
4732 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4733 "\\(--?"
4734 "\\(\\<[012]?[0-9]"
4735 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4736 "\\)?")
4737 "Regular expression to match a plain time or time range.
4738 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4739 groups carry important information:
4740 0 the full match
4741 1 the first time, range or not
4742 8 the second time, if it is a range.")
4744 (defconst org-plain-time-extension-regexp
4745 (concat
4746 "\\(\\<[012]?[0-9]"
4747 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4748 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4749 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4750 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4751 groups carry important information:
4752 0 the full match
4753 7 hours of duration
4754 9 minutes of duration")
4756 (defconst org-stamp-time-of-day-regexp
4757 (concat
4758 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4759 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4760 "\\(--?"
4761 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4762 "Regular expression to match a timestamp time or time range.
4763 After a match, the following groups carry important information:
4764 0 the full match
4765 1 date plus weekday, for back referencing to make sure both times are on the same day
4766 2 the first time, range or not
4767 4 the second time, if it is a range.")
4769 (defconst org-startup-options
4770 '(("fold" org-startup-folded t)
4771 ("overview" org-startup-folded t)
4772 ("nofold" org-startup-folded nil)
4773 ("showall" org-startup-folded nil)
4774 ("showeverything" org-startup-folded showeverything)
4775 ("content" org-startup-folded content)
4776 ("indent" org-startup-indented t)
4777 ("noindent" org-startup-indented nil)
4778 ("hidestars" org-hide-leading-stars t)
4779 ("showstars" org-hide-leading-stars nil)
4780 ("odd" org-odd-levels-only t)
4781 ("oddeven" org-odd-levels-only nil)
4782 ("align" org-startup-align-all-tables t)
4783 ("noalign" org-startup-align-all-tables nil)
4784 ("shrink" org-startup-shrink-all-tables t)
4785 ("inlineimages" org-startup-with-inline-images t)
4786 ("noinlineimages" org-startup-with-inline-images nil)
4787 ("latexpreview" org-startup-with-latex-preview t)
4788 ("nolatexpreview" org-startup-with-latex-preview nil)
4789 ("customtime" org-display-custom-times t)
4790 ("logdone" org-log-done time)
4791 ("lognotedone" org-log-done note)
4792 ("nologdone" org-log-done nil)
4793 ("lognoteclock-out" org-log-note-clock-out t)
4794 ("nolognoteclock-out" org-log-note-clock-out nil)
4795 ("logrepeat" org-log-repeat state)
4796 ("lognoterepeat" org-log-repeat note)
4797 ("logdrawer" org-log-into-drawer t)
4798 ("nologdrawer" org-log-into-drawer nil)
4799 ("logstatesreversed" org-log-states-order-reversed t)
4800 ("nologstatesreversed" org-log-states-order-reversed nil)
4801 ("nologrepeat" org-log-repeat nil)
4802 ("logreschedule" org-log-reschedule time)
4803 ("lognotereschedule" org-log-reschedule note)
4804 ("nologreschedule" org-log-reschedule nil)
4805 ("logredeadline" org-log-redeadline time)
4806 ("lognoteredeadline" org-log-redeadline note)
4807 ("nologredeadline" org-log-redeadline nil)
4808 ("logrefile" org-log-refile time)
4809 ("lognoterefile" org-log-refile note)
4810 ("nologrefile" org-log-refile nil)
4811 ("fninline" org-footnote-define-inline t)
4812 ("nofninline" org-footnote-define-inline nil)
4813 ("fnlocal" org-footnote-section nil)
4814 ("fnauto" org-footnote-auto-label t)
4815 ("fnprompt" org-footnote-auto-label nil)
4816 ("fnconfirm" org-footnote-auto-label confirm)
4817 ("fnplain" org-footnote-auto-label plain)
4818 ("fnadjust" org-footnote-auto-adjust t)
4819 ("nofnadjust" org-footnote-auto-adjust nil)
4820 ("constcgs" constants-unit-system cgs)
4821 ("constSI" constants-unit-system SI)
4822 ("noptag" org-tag-persistent-alist nil)
4823 ("hideblocks" org-hide-block-startup t)
4824 ("nohideblocks" org-hide-block-startup nil)
4825 ("beamer" org-startup-with-beamer-mode t)
4826 ("entitiespretty" org-pretty-entities t)
4827 ("entitiesplain" org-pretty-entities nil))
4828 "Variable associated with STARTUP options for org-mode.
4829 Each element is a list of three items: the startup options (as written
4830 in the #+STARTUP line), the corresponding variable, and the value to set
4831 this variable to if the option is found. An optional forth element PUSH
4832 means to push this value onto the list in the variable.")
4834 (defcustom org-group-tags t
4835 "When non-nil (the default), use group tags.
4836 This can be turned on/off through `org-toggle-tags-groups'."
4837 :group 'org-tags
4838 :group 'org-startup
4839 :type 'boolean)
4841 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4843 (defun org-toggle-tags-groups ()
4844 "Toggle support for group tags.
4845 Support for group tags is controlled by the option
4846 `org-group-tags', which is non-nil by default."
4847 (interactive)
4848 (setq org-group-tags (not org-group-tags))
4849 (cond ((and (derived-mode-p 'org-agenda-mode)
4850 org-group-tags)
4851 (org-agenda-redo))
4852 ((derived-mode-p 'org-mode)
4853 (let ((org-inhibit-startup t)) (org-mode))))
4854 (message "Groups tags support has been turned %s"
4855 (if org-group-tags "on" "off")))
4857 (defun org-set-regexps-and-options (&optional tags-only)
4858 "Precompute regular expressions used in the current buffer.
4859 When optional argument TAGS-ONLY is non-nil, only compute tags
4860 related expressions."
4861 (when (derived-mode-p 'org-mode)
4862 (let ((alist (org--setup-collect-keywords
4863 (org-make-options-regexp
4864 (append '("FILETAGS" "TAGS" "SETUPFILE")
4865 (and (not tags-only)
4866 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4867 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4868 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4869 ;; Startup options. Get this early since it does change
4870 ;; behavior for other options (e.g., tags).
4871 (let ((startup (cdr (assq 'startup alist))))
4872 (dolist (option startup)
4873 (let ((entry (assoc-string option org-startup-options t)))
4874 (when entry
4875 (let ((var (nth 1 entry))
4876 (val (nth 2 entry)))
4877 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4878 (unless (listp (symbol-value var))
4879 (set (make-local-variable var) nil))
4880 (add-to-list var val)))))))
4881 (setq-local org-file-tags
4882 (mapcar #'org-add-prop-inherited
4883 (cdr (assq 'filetags alist))))
4884 (setq org-current-tag-alist
4885 (append org-tag-persistent-alist
4886 (let ((tags (cdr (assq 'tags alist))))
4887 (if tags (org-tag-string-to-alist tags)
4888 org-tag-alist))))
4889 (setq org-tag-groups-alist
4890 (org-tag-alist-to-groups org-current-tag-alist))
4891 (unless tags-only
4892 ;; File properties.
4893 (setq-local org-file-properties (cdr (assq 'property alist)))
4894 ;; Archive location.
4895 (let ((archive (cdr (assq 'archive alist))))
4896 (when archive (setq-local org-archive-location archive)))
4897 ;; Category.
4898 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4899 (when cat
4900 (setq-local org-category (intern cat))
4901 (setq-local org-file-properties
4902 (org--update-property-plist
4903 "CATEGORY" cat org-file-properties))))
4904 ;; Columns.
4905 (let ((column (cdr (assq 'columns alist))))
4906 (when column (setq-local org-columns-default-format column)))
4907 ;; Constants.
4908 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4909 ;; Link abbreviations.
4910 (let ((links (cdr (assq 'link alist))))
4911 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4912 ;; Priorities.
4913 (let ((priorities (cdr (assq 'priorities alist))))
4914 (when priorities
4915 (setq-local org-highest-priority (nth 0 priorities))
4916 (setq-local org-lowest-priority (nth 1 priorities))
4917 (setq-local org-default-priority (nth 2 priorities))))
4918 ;; Scripts.
4919 (let ((scripts (assq 'scripts alist)))
4920 (when scripts
4921 (setq-local org-use-sub-superscripts (cdr scripts))))
4922 ;; TODO keywords.
4923 (setq-local org-todo-kwd-alist nil)
4924 (setq-local org-todo-key-alist nil)
4925 (setq-local org-todo-key-trigger nil)
4926 (setq-local org-todo-keywords-1 nil)
4927 (setq-local org-done-keywords nil)
4928 (setq-local org-todo-heads nil)
4929 (setq-local org-todo-sets nil)
4930 (setq-local org-todo-log-states nil)
4931 (let ((todo-sequences
4932 (or (nreverse (cdr (assq 'todo alist)))
4933 (let ((d (default-value 'org-todo-keywords)))
4934 (if (not (stringp (car d))) d
4935 ;; XXX: Backward compatibility code.
4936 (list (cons org-todo-interpretation d)))))))
4937 (dolist (sequence todo-sequences)
4938 (let* ((sequence (or (run-hook-with-args-until-success
4939 'org-todo-setup-filter-hook sequence)
4940 sequence))
4941 (sequence-type (car sequence))
4942 (keywords (cdr sequence))
4943 (sep (member "|" keywords))
4944 names alist)
4945 (dolist (k (remove "|" keywords))
4946 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4948 (error "Invalid TODO keyword %s" k))
4949 (let ((name (match-string 1 k))
4950 (key (match-string 2 k))
4951 (log (org-extract-log-state-settings k)))
4952 (push name names)
4953 (push (cons name (and key (string-to-char key))) alist)
4954 (when log (push log org-todo-log-states))))
4955 (let* ((names (nreverse names))
4956 (done (if sep (org-remove-keyword-keys (cdr sep))
4957 (last names)))
4958 (head (car names))
4959 (tail (list sequence-type head (car done) (org-last done))))
4960 (add-to-list 'org-todo-heads head 'append)
4961 (push names org-todo-sets)
4962 (setq org-done-keywords (append org-done-keywords done nil))
4963 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4964 (setq org-todo-key-alist
4965 (append org-todo-key-alist
4966 (and alist
4967 (append '((:startgroup))
4968 (nreverse alist)
4969 '((:endgroup))))))
4970 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4971 (setq org-todo-sets (nreverse org-todo-sets)
4972 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4973 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4974 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4975 ;; Compute the regular expressions and other local variables.
4976 ;; Using `org-outline-regexp-bol' would complicate them much,
4977 ;; because of the fixed white space at the end of that string.
4978 (unless org-done-keywords
4979 (setq org-done-keywords
4980 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4981 (setq org-not-done-keywords
4982 (org-delete-all org-done-keywords
4983 (copy-sequence org-todo-keywords-1))
4984 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4985 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4986 org-not-done-heading-regexp
4987 (format org-heading-keyword-regexp-format org-not-done-regexp)
4988 org-todo-line-regexp
4989 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4990 org-complex-heading-regexp
4991 (concat "^\\(\\*+\\)"
4992 "\\(?: +" org-todo-regexp "\\)?"
4993 "\\(?: +\\(\\[#.\\]\\)\\)?"
4994 "\\(?: +\\(.*?\\)\\)??"
4995 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4996 "[ \t]*$")
4997 org-complex-heading-regexp-format
4998 (concat "^\\(\\*+\\)"
4999 "\\(?: +" org-todo-regexp "\\)?"
5000 "\\(?: +\\(\\[#.\\]\\)\\)?"
5001 "\\(?: +"
5002 ;; Stats cookies can be stuck to body.
5003 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5004 "\\(%s\\)"
5005 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5006 "\\)"
5007 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5008 "[ \t]*$")
5009 org-todo-line-tags-regexp
5010 (concat "^\\(\\*+\\)"
5011 "\\(?: +" org-todo-regexp "\\)?"
5012 "\\(?: +\\(.*?\\)\\)??"
5013 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5014 "[ \t]*$"))
5015 (org-compute-latex-and-related-regexp)))))
5017 (defun org--setup-collect-keywords (regexp &optional files alist)
5018 "Return setup keywords values as an alist.
5020 REGEXP matches a subset of setup keywords. FILES is a list of
5021 file names already visited. It is used to avoid circular setup
5022 files. ALIST, when non-nil, is the alist computed so far.
5024 Return value contains the following keys: `archive', `category',
5025 `columns', `constants', `filetags', `link', `priorities',
5026 `property', `scripts', `startup', `tags' and `todo'."
5027 (org-with-wide-buffer
5028 (goto-char (point-min))
5029 (let ((case-fold-search t))
5030 (while (re-search-forward regexp nil t)
5031 (let ((element (org-element-at-point)))
5032 (when (eq (org-element-type element) 'keyword)
5033 (let ((key (org-element-property :key element))
5034 (value (org-element-property :value element)))
5035 (cond
5036 ((equal key "ARCHIVE")
5037 (when (org-string-nw-p value)
5038 (push (cons 'archive value) alist)))
5039 ((equal key "CATEGORY") (push (cons 'category value) alist))
5040 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5041 ((equal key "CONSTANTS")
5042 (let* ((constants (assq 'constants alist))
5043 (store (cdr constants)))
5044 (dolist (pair (split-string value))
5045 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5046 pair)
5047 (let* ((name (match-string 1 pair))
5048 (value (match-string 2 pair))
5049 (old (assoc name store)))
5050 (if old (setcdr old value)
5051 (push (cons name value) store)))))
5052 (if constants (setcdr constants store)
5053 (push (cons 'constants store) alist))))
5054 ((equal key "FILETAGS")
5055 (when (org-string-nw-p value)
5056 (let ((old (assq 'filetags alist))
5057 (new (apply #'nconc
5058 (mapcar (lambda (x) (org-split-string x ":"))
5059 (split-string value)))))
5060 (if old (setcdr old (append new (cdr old)))
5061 (push (cons 'filetags new) alist)))))
5062 ((equal key "LINK")
5063 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5064 (let ((links (assq 'link alist))
5065 (pair (cons (match-string-no-properties 1 value)
5066 (match-string-no-properties 2 value))))
5067 (if links (push pair (cdr links))
5068 (push (list 'link pair) alist)))))
5069 ((equal key "OPTIONS")
5070 (when (and (org-string-nw-p value)
5071 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5072 (push (cons 'scripts (read (match-string 1 value))) alist)))
5073 ((equal key "PRIORITIES")
5074 (push (cons 'priorities
5075 (let ((prio (split-string value)))
5076 (if (< (length prio) 3) '(?A ?C ?B)
5077 (mapcar #'string-to-char prio))))
5078 alist))
5079 ((equal key "PROPERTY")
5080 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5081 (let* ((property (assq 'property alist))
5082 (value (org--update-property-plist
5083 (match-string-no-properties 1 value)
5084 (match-string-no-properties 2 value)
5085 (cdr property))))
5086 (if property (setcdr property value)
5087 (push (cons 'property value) alist)))))
5088 ((equal key "STARTUP")
5089 (let ((startup (assq 'startup alist)))
5090 (if startup
5091 (setcdr startup
5092 (append (cdr startup) (split-string value)))
5093 (push (cons 'startup (split-string value)) alist))))
5094 ((equal key "TAGS")
5095 (let ((tag-cell (assq 'tags alist)))
5096 (if tag-cell
5097 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5098 (push (cons 'tags value) alist))))
5099 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5100 (let ((todo (assq 'todo alist))
5101 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5102 (split-string value))))
5103 (if todo (push value (cdr todo))
5104 (push (list 'todo value) alist))))
5105 ((equal key "SETUPFILE")
5106 (unless buffer-read-only ; Do not check in Gnus messages.
5107 (let ((f (and (org-string-nw-p value)
5108 (expand-file-name
5109 (org-unbracket-string "\"" "\"" value)))))
5110 (when (and f (file-readable-p f) (not (member f files)))
5111 (with-temp-buffer
5112 (setq default-directory (file-name-directory f))
5113 (insert-file-contents f)
5114 (setq alist
5115 ;; Fake Org mode to benefit from cache
5116 ;; without recurring needlessly.
5117 (let ((major-mode 'org-mode))
5118 (org--setup-collect-keywords
5119 regexp (cons f files) alist)))))))))))))))
5120 alist)
5122 (defun org-tag-string-to-alist (s)
5123 "Return tag alist associated to string S.
5124 S is a value for TAGS keyword or produced with
5125 `org-tag-alist-to-string'. Return value is an alist suitable for
5126 `org-tag-alist' or `org-tag-persistent-alist'."
5127 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5128 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5129 "\\|{.+?}\\)" ; regular expression
5130 "\\(?:(\\(.\\))\\)?\\'"))
5131 alist group-flag)
5132 (dolist (tokens lines (cdr (nreverse alist)))
5133 (push '(:newline) alist)
5134 (while tokens
5135 (let ((token (pop tokens)))
5136 (pcase token
5137 ("{"
5138 (push '(:startgroup) alist)
5139 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5140 ("}"
5141 (push '(:endgroup) alist)
5142 (setq group-flag nil))
5143 ("["
5144 (push '(:startgrouptag) alist)
5145 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5146 ("]"
5147 (push '(:endgrouptag) alist)
5148 (setq group-flag nil))
5149 (":"
5150 (push '(:grouptags) alist))
5151 ((guard (string-match tag-re token))
5152 (let ((tag (match-string 1 token))
5153 (key (and (match-beginning 2)
5154 (string-to-char (match-string 2 token)))))
5155 ;; Push all tags in groups, no matter if they already
5156 ;; appear somewhere else in the list.
5157 (when (or group-flag (not (assoc tag alist)))
5158 (push (cons tag key) alist))))))))))
5160 (defun org-tag-alist-to-string (alist &optional skip-key)
5161 "Return tag string associated to ALIST.
5163 ALIST is an alist, as defined in `org-tag-alist' or
5164 `org-tag-persistent-alist', or produced with
5165 `org-tag-string-to-alist'.
5167 Return value is a string suitable as a value for \"TAGS\"
5168 keyword.
5170 When optional argument SKIP-KEY is non-nil, skip selection keys
5171 next to tags."
5172 (mapconcat (lambda (token)
5173 (pcase token
5174 (`(:startgroup) "{")
5175 (`(:endgroup) "}")
5176 (`(:startgrouptag) "[")
5177 (`(:endgrouptag) "]")
5178 (`(:grouptags) ":")
5179 (`(:newline) "\\n")
5180 ((and
5181 (guard (not skip-key))
5182 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5183 (format "%s(%c)" tag key))
5184 (`(,(and tag (pred stringp)) . ,_) tag)
5185 (_ (user-error "Invalid tag token: %S" token))))
5186 alist
5187 " "))
5189 (defun org-tag-alist-to-groups (alist)
5190 "Return group alist from tag ALIST.
5191 ALIST is an alist, as defined in `org-tag-alist' or
5192 `org-tag-persistent-alist', or produced with
5193 `org-tag-string-to-alist'. Return value is an alist following
5194 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5195 a string, summarizing TAGS, as a list of strings."
5196 (let (groups group-status current-group)
5197 (dolist (token alist (nreverse groups))
5198 (pcase token
5199 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5200 (`(,(or :endgroup :endgrouptag))
5201 (when (eq group-status 'append)
5202 (push (nreverse current-group) groups))
5203 (setq group-status nil))
5204 (`(:grouptags) (setq group-status 'append))
5205 ((and `(,tag . ,_) (guard group-status))
5206 (if (eq group-status 'append) (push tag current-group)
5207 (setq current-group (list tag))))
5208 (_ nil)))))
5210 (defvar org--file-cache (make-hash-table :test #'equal)
5211 "Hash table to store contents of files referenced via a URL.
5212 This is the cache of file URLs read using `org-file-contents'.")
5214 (defun org-reset-file-cache ()
5215 "Reset the cache of files downloaded by `org-file-contents'."
5216 (clrhash org--file-cache))
5218 (defun org-file-url-p (file)
5219 "Non-nil if FILE is a URL."
5220 (require 'ffap)
5221 (string-match-p ffap-url-regexp file))
5223 (defun org-file-contents (file &optional noerror nocache)
5224 "Return the contents of FILE, as a string.
5226 FILE can be a file name or URL.
5228 If FILE is a URL, download the contents. If the URL contents are
5229 already cached in the `org--file-cache' hash table, the download step
5230 is skipped.
5232 If NOERROR is non-nil, ignore the error when unable to read the FILE
5233 from file or URL.
5235 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5236 is available. This option applies only if FILE is a URL."
5237 (let* ((is-url (org-file-url-p file))
5238 (cache (and is-url
5239 (not nocache)
5240 (gethash file org--file-cache))))
5241 (cond
5242 (cache)
5243 (is-url
5244 (with-current-buffer (url-retrieve-synchronously file)
5245 (goto-char (point-min))
5246 ;; Move point to after the url-retrieve header.
5247 (search-forward "\n\n" nil :move)
5248 ;; Search for the success code only in the url-retrieve header.
5249 (if (save-excursion
5250 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5251 ;; Update the cache `org--file-cache' and return contents.
5252 (puthash file
5253 (buffer-substring-no-properties (point) (point-max))
5254 org--file-cache)
5255 (funcall (if noerror #'message #'user-error)
5256 "Unable to fetch file from %S"
5257 file))))
5259 (with-temp-buffer
5260 (condition-case nil
5261 (progn
5262 (insert-file-contents file)
5263 (buffer-string))
5264 (file-error
5265 (funcall (if noerror #'message #'user-error)
5266 "Unable to read file %S"
5267 file))))))))
5269 (defun org-extract-log-state-settings (x)
5270 "Extract the log state setting from a TODO keyword string.
5271 This will extract info from a string like \"WAIT(w@/!)\"."
5272 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5273 (let ((kw (match-string 1 x))
5274 (log1 (and (match-end 3) (match-string 3 x)))
5275 (log2 (and (match-end 4) (match-string 4 x))))
5276 (and (or log1 log2)
5277 (list kw
5278 (and log1 (if (equal log1 "!") 'time 'note))
5279 (and log2 (if (equal log2 "!") 'time 'note)))))))
5281 (defun org-remove-keyword-keys (list)
5282 "Remove a pair of parenthesis at the end of each string in LIST."
5283 (mapcar (lambda (x)
5284 (if (string-match "(.*)$" x)
5285 (substring x 0 (match-beginning 0))
5287 list))
5289 (defun org-assign-fast-keys (alist)
5290 "Assign fast keys to a keyword-key alist.
5291 Respect keys that are already there."
5292 (let (new e (alt ?0))
5293 (while (setq e (pop alist))
5294 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5295 (cdr e)) ;; Key already assigned.
5296 (push e new)
5297 (let ((clist (string-to-list (downcase (car e))))
5298 (used (append new alist)))
5299 (when (= (car clist) ?@)
5300 (pop clist))
5301 (while (and clist (rassoc (car clist) used))
5302 (pop clist))
5303 (unless clist
5304 (while (rassoc alt used)
5305 (cl-incf alt)))
5306 (push (cons (car e) (or (car clist) alt)) new))))
5307 (nreverse new)))
5309 ;;; Some variables used in various places
5311 (defvar org-window-configuration nil
5312 "Used in various places to store a window configuration.")
5313 (defvar org-selected-window nil
5314 "Used in various places to store a window configuration.")
5315 (defvar org-finish-function nil
5316 "Function to be called when `C-c C-c' is used.
5317 This is for getting out of special buffers like capture.")
5318 (defvar org-last-state)
5320 ;; Defined somewhere in this file, but used before definition.
5321 (defvar org-entities) ;; defined in org-entities.el
5322 (defvar org-struct-menu)
5323 (defvar org-org-menu)
5324 (defvar org-tbl-menu)
5326 ;;;; Define the Org mode
5328 ;; We use a before-change function to check if a table might need
5329 ;; an update.
5330 (defvar org-table-may-need-update t
5331 "Indicates that a table might need an update.
5332 This variable is set by `org-before-change-function'.
5333 `org-table-align' sets it back to nil.")
5334 (defun org-before-change-function (_beg _end)
5335 "Every change indicates that a table might need an update."
5336 (setq org-table-may-need-update t))
5337 (defvar org-mode-map)
5338 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5339 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5340 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5341 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5342 (defvar org-table-buffer-is-an nil)
5344 (defvar bidi-paragraph-direction)
5345 (defvar buffer-face-mode-face)
5347 (require 'outline)
5349 ;; Other stuff we need.
5350 (require 'time-date)
5351 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5352 (require 'easymenu)
5353 (autoload 'easy-menu-add "easymenu")
5354 (require 'overlay)
5356 ;; (require 'org-macs) moved higher up in the file before it is first used
5357 (require 'org-entities)
5358 ;; (require 'org-compat) moved higher up in the file before it is first used
5359 (require 'org-faces)
5360 (require 'org-list)
5361 (require 'org-pcomplete)
5362 (require 'org-src)
5363 (require 'org-footnote)
5364 (require 'org-macro)
5366 ;; babel
5367 (require 'ob)
5369 ;;;###autoload
5370 (define-derived-mode org-mode outline-mode "Org"
5371 "Outline-based notes management and organizer, alias
5372 \"Carsten's outline-mode for keeping track of everything.\"
5374 Org mode develops organizational tasks around a NOTES file which
5375 contains information about projects as plain text. Org mode is
5376 implemented on top of Outline mode, which is ideal to keep the content
5377 of large files well structured. It supports ToDo items, deadlines and
5378 time stamps, which magically appear in the diary listing of the Emacs
5379 calendar. Tables are easily created with a built-in table editor.
5380 Plain text URL-like links connect to websites, emails (VM), Usenet
5381 messages (Gnus), BBDB entries, and any files related to the project.
5382 For printing and sharing of notes, an Org file (or a part of it)
5383 can be exported as a structured ASCII or HTML file.
5385 The following commands are available:
5387 \\{org-mode-map}"
5389 ;; Get rid of Outline menus, they are not needed
5390 ;; Need to do this here because define-derived-mode sets up
5391 ;; the keymap so late. Still, it is a waste to call this each time
5392 ;; we switch another buffer into Org mode.
5393 (define-key org-mode-map [menu-bar headings] 'undefined)
5394 (define-key org-mode-map [menu-bar hide] 'undefined)
5395 (define-key org-mode-map [menu-bar show] 'undefined)
5397 (org-load-modules-maybe)
5398 (org-install-agenda-files-menu)
5399 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5400 (add-to-invisibility-spec '(org-hide-block . t))
5401 (setq-local outline-regexp org-outline-regexp)
5402 (setq-local outline-level 'org-outline-level)
5403 (setq bidi-paragraph-direction 'left-to-right)
5404 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5405 (unless org-display-table
5406 (setq org-display-table (make-display-table)))
5407 (set-display-table-slot
5408 org-display-table 4
5409 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5410 org-ellipsis)))
5411 (setq buffer-display-table org-display-table))
5412 (org-set-regexps-and-options)
5413 (org-set-font-lock-defaults)
5414 (when (and org-tag-faces (not org-tags-special-faces-re))
5415 ;; tag faces set outside customize.... force initialization.
5416 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5417 ;; Calc embedded
5418 (setq-local calc-embedded-open-mode "# ")
5419 ;; Modify a few syntax entries
5420 (modify-syntax-entry ?@ "w")
5421 (modify-syntax-entry ?\" "\"")
5422 (modify-syntax-entry ?\\ "_")
5423 (modify-syntax-entry ?~ "_")
5424 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5425 ;; Activate before-change-function
5426 (setq-local org-table-may-need-update t)
5427 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5428 ;; Check for running clock before killing a buffer
5429 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5430 ;; Initialize macros templates.
5431 (org-macro-initialize-templates)
5432 ;; Initialize radio targets.
5433 (org-update-radio-target-regexp)
5434 ;; Indentation.
5435 (setq-local indent-line-function 'org-indent-line)
5436 (setq-local indent-region-function 'org-indent-region)
5437 ;; Filling and auto-filling.
5438 (org-setup-filling)
5439 ;; Comments.
5440 (org-setup-comments-handling)
5441 ;; Initialize cache.
5442 (org-element-cache-reset)
5443 ;; Beginning/end of defun
5444 (setq-local beginning-of-defun-function 'org-backward-element)
5445 (setq-local end-of-defun-function
5446 (lambda ()
5447 (if (not (org-at-heading-p))
5448 (org-forward-element)
5449 (org-forward-element)
5450 (forward-char -1))))
5451 ;; Next error for sparse trees
5452 (setq-local next-error-function 'org-occur-next-match)
5453 ;; Make sure dependence stuff works reliably, even for users who set it
5454 ;; too late :-(
5455 (if org-enforce-todo-dependencies
5456 (add-hook 'org-blocker-hook
5457 'org-block-todo-from-children-or-siblings-or-parent)
5458 (remove-hook 'org-blocker-hook
5459 'org-block-todo-from-children-or-siblings-or-parent))
5460 (if org-enforce-todo-checkbox-dependencies
5461 (add-hook 'org-blocker-hook
5462 'org-block-todo-from-checkboxes)
5463 (remove-hook 'org-blocker-hook
5464 'org-block-todo-from-checkboxes))
5466 ;; Align options lines
5467 (setq-local
5468 align-mode-rules-list
5469 '((org-in-buffer-settings
5470 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5471 (modes . '(org-mode)))))
5473 ;; Imenu
5474 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5476 ;; Make isearch reveal context
5477 (setq-local outline-isearch-open-invisible-function
5478 (lambda (&rest _) (org-show-context 'isearch)))
5480 ;; Setup the pcomplete hooks
5481 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5482 (setq-local pcomplete-command-name-function 'org-command-at-point)
5483 (setq-local pcomplete-default-completion-function 'ignore)
5484 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5485 (setq-local pcomplete-termination-string "")
5486 (setq-local buffer-face-mode-face 'org-default)
5488 ;; If empty file that did not turn on Org mode automatically, make
5489 ;; it to.
5490 (when (and org-insert-mode-line-in-empty-file
5491 (called-interactively-p 'any)
5492 (= (point-min) (point-max)))
5493 (insert "# -*- mode: org -*-\n\n"))
5494 (unless org-inhibit-startup
5495 (org-unmodified
5496 (when org-startup-with-beamer-mode (org-beamer-mode))
5497 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5498 (org-table-map-tables
5499 (cond ((and org-startup-align-all-tables
5500 org-startup-shrink-all-tables)
5501 (lambda () (org-table-align) (org-table-shrink)))
5502 (org-startup-align-all-tables #'org-table-align)
5503 (t #'org-table-shrink))
5505 (when org-startup-with-inline-images (org-display-inline-images))
5506 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5507 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5508 (when org-startup-truncated (setq truncate-lines t))
5509 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5510 (org-refresh-effort-properties)))
5511 ;; Try to set `org-hide' face correctly.
5512 (let ((foreground (org-find-invisible-foreground)))
5513 (when foreground
5514 (set-face-foreground 'org-hide foreground))))
5516 ;; Update `customize-package-emacs-version-alist'
5517 (add-to-list 'customize-package-emacs-version-alist
5518 '(Org ("8.0" . "24.4")
5519 ("8.1" . "24.4")
5520 ("8.2" . "24.4")
5521 ("8.2.7" . "24.4")
5522 ("8.3" . "26.1")
5523 ("9.0" . "26.1")
5524 ("9.1" . "26.1")
5525 ("9.2" . "27.1")))
5527 (defvar org-mode-transpose-word-syntax-table
5528 (let ((st (make-syntax-table text-mode-syntax-table)))
5529 (dolist (c org-emphasis-alist st)
5530 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5532 (when (fboundp 'abbrev-table-put)
5533 (abbrev-table-put org-mode-abbrev-table
5534 :parents (list text-mode-abbrev-table)))
5536 (defun org-find-invisible-foreground ()
5537 (let ((candidates (remove
5538 "unspecified-bg"
5539 (nconc
5540 (list (face-background 'default)
5541 (face-background 'org-default))
5542 (mapcar
5543 (lambda (alist)
5544 (when (boundp alist)
5545 (cdr (assq 'background-color (symbol-value alist)))))
5546 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5547 (list (face-foreground 'org-hide))))))
5548 (car (remove nil candidates))))
5550 (defun org-current-time (&optional rounding-minutes past)
5551 "Current time, possibly rounded to ROUNDING-MINUTES.
5552 When ROUNDING-MINUTES is not an integer, fall back on the car of
5553 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5554 the rounding returns a past time."
5555 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5556 (car org-time-stamp-rounding-minutes)))
5557 (time (decode-time)) res)
5558 (if (< r 1)
5559 (current-time)
5560 (setq res
5561 (apply 'encode-time
5562 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5563 (nthcdr 2 time))))
5564 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5565 (seconds-to-time (- (float-time res) (* r 60)))
5566 res))))
5568 (defun org-today ()
5569 "Return today date, considering `org-extend-today-until'."
5570 (time-to-days
5571 (time-subtract (current-time)
5572 (list 0 (* 3600 org-extend-today-until) 0))))
5574 ;;;; Font-Lock stuff, including the activators
5576 (defvar org-mouse-map (make-sparse-keymap))
5577 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5578 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5579 (when org-mouse-1-follows-link
5580 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5581 (when org-tab-follows-link
5582 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5583 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5585 (require 'font-lock)
5587 (defconst org-non-link-chars "]\t\n\r<>")
5588 (defvar org-link-types-re nil
5589 "Matches a link that has a url-like prefix like \"http:\"")
5590 (defvar org-link-re-with-space nil
5591 "Matches a link with spaces, optional angular brackets around it.")
5592 (defvar org-link-re-with-space2 nil
5593 "Matches a link with spaces, optional angular brackets around it.")
5594 (defvar org-link-re-with-space3 nil
5595 "Matches a link with spaces, only for internal part in bracket links.")
5596 (defvar org-angle-link-re nil
5597 "Matches link with angular brackets, spaces are allowed.")
5598 (defvar org-plain-link-re nil
5599 "Matches plain link, without spaces.")
5600 (defvar org-bracket-link-regexp nil
5601 "Matches a link in double brackets.")
5602 (defvar org-bracket-link-analytic-regexp nil
5603 "Regular expression used to analyze links.
5604 Here is what the match groups contain after a match:
5605 1: http:
5606 2: http
5607 3: path
5608 4: [desc]
5609 5: desc")
5610 (defvar org-bracket-link-analytic-regexp++ nil
5611 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5612 (defvar org-any-link-re nil
5613 "Regular expression matching any link.")
5615 (defconst org-match-sexp-depth 3
5616 "Number of stacked braces for sub/superscript matching.")
5618 (defun org-create-multibrace-regexp (left right n)
5619 "Create a regular expression which will match a balanced sexp.
5620 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5621 as single character strings.
5622 The regexp returned will match the entire expression including the
5623 delimiters. It will also define a single group which contains the
5624 match except for the outermost delimiters. The maximum depth of
5625 stacked delimiters is N. Escaping delimiters is not possible."
5626 (let* ((nothing (concat "[^" left right "]*?"))
5627 (or "\\|")
5628 (re nothing)
5629 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5630 (while (> n 1)
5631 (setq n (1- n)
5632 re (concat re or next)
5633 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5634 (concat left "\\(" re "\\)" right)))
5636 (defconst org-match-substring-regexp
5637 (concat
5638 "\\(\\S-\\)\\([_^]\\)\\("
5639 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5640 "\\|"
5641 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5642 "\\|"
5643 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5644 "The regular expression matching a sub- or superscript.")
5646 (defconst org-match-substring-with-braces-regexp
5647 (concat
5648 "\\(\\S-\\)\\([_^]\\)"
5649 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5650 "The regular expression matching a sub- or superscript, forcing braces.")
5652 (defun org-make-link-regexps ()
5653 "Update the link regular expressions.
5654 This should be called after the variable `org-link-parameters' has changed."
5655 (let ((types-re (regexp-opt (org-link-types) t)))
5656 (setq org-link-types-re
5657 (concat "\\`" types-re ":")
5658 org-link-re-with-space
5659 (concat "<?" types-re ":"
5660 "\\([^" org-non-link-chars " ]"
5661 "[^" org-non-link-chars "]*"
5662 "[^" org-non-link-chars " ]\\)>?")
5663 org-link-re-with-space2
5664 (concat "<?" types-re ":"
5665 "\\([^" org-non-link-chars " ]"
5666 "[^\t\n\r]*"
5667 "[^" org-non-link-chars " ]\\)>?")
5668 org-link-re-with-space3
5669 (concat "<?" types-re ":"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^\t\n\r]*\\)")
5672 org-angle-link-re
5673 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5674 types-re)
5675 org-plain-link-re
5676 (concat
5677 "\\<" types-re ":"
5678 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5679 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5680 org-bracket-link-regexp
5681 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5682 org-bracket-link-analytic-regexp
5683 (concat
5684 "\\[\\["
5685 "\\(" types-re ":\\)?"
5686 "\\([^]]+\\)"
5687 "\\]"
5688 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5689 "\\]")
5690 org-bracket-link-analytic-regexp++
5691 (concat
5692 "\\[\\["
5693 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5694 "\\([^]]+\\)"
5695 "\\]"
5696 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5697 "\\]")
5698 org-any-link-re
5699 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5700 org-angle-link-re "\\)\\|\\("
5701 org-plain-link-re "\\)"))))
5703 (org-make-link-regexps)
5705 (defvar org-emph-face nil)
5707 (defun org-do-emphasis-faces (limit)
5708 "Run through the buffer and emphasize strings."
5709 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5710 (car org-emphasis-regexp-components))))
5711 (catch :exit
5712 (while (re-search-forward quick-re limit t)
5713 (let* ((marker (match-string 2))
5714 (verbatim? (member marker '("~" "="))))
5715 (when (save-excursion
5716 (goto-char (match-beginning 0))
5717 (and
5718 ;; Do not match table hlines.
5719 (not (and (equal marker "+")
5720 (org-match-line
5721 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5722 ;; Do not match headline stars. Do not consider
5723 ;; stars of a headline as closing marker for bold
5724 ;; markup either.
5725 (not (and (equal marker "*")
5726 (save-excursion
5727 (forward-char)
5728 (skip-chars-backward "*")
5729 (looking-at-p org-outline-regexp-bol))))
5730 ;; Match full emphasis markup regexp.
5731 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5732 ;; Do not span over paragraph boundaries.
5733 (not (string-match-p org-element-paragraph-separate
5734 (match-string 2)))
5735 ;; Do not span over cells in table rows.
5736 (not (and (save-match-data (org-match-line "[ \t]*|"))
5737 (string-match-p "|" (match-string 4))))))
5738 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5739 (font-lock-prepend-text-property
5740 (match-beginning 2) (match-end 2) 'face face)
5741 (when verbatim?
5742 (org-remove-flyspell-overlays-in
5743 (match-beginning 0) (match-end 0)))
5744 (add-text-properties (match-beginning 2) (match-end 2)
5745 '(font-lock-multiline t org-emphasis t))
5746 (when org-hide-emphasis-markers
5747 (add-text-properties (match-end 4) (match-beginning 5)
5748 '(invisible org-link))
5749 (add-text-properties (match-beginning 3) (match-end 3)
5750 '(invisible org-link)))
5751 (throw :exit t))))))))
5753 (defun org-emphasize (&optional char)
5754 "Insert or change an emphasis, i.e. a font like bold or italic.
5755 If there is an active region, change that region to a new emphasis.
5756 If there is no region, just insert the marker characters and position
5757 the cursor between them.
5758 CHAR should be the marker character. If it is a space, it means to
5759 remove the emphasis of the selected region.
5760 If CHAR is not given (for example in an interactive call) it will be
5761 prompted for."
5762 (interactive)
5763 (let ((erc org-emphasis-regexp-components)
5764 (string "") beg end move s)
5765 (if (org-region-active-p)
5766 (setq beg (region-beginning)
5767 end (region-end)
5768 string (buffer-substring beg end))
5769 (setq move t))
5771 (unless char
5772 (message "Emphasis marker or tag: [%s]"
5773 (mapconcat #'car org-emphasis-alist ""))
5774 (setq char (read-char-exclusive)))
5775 (if (equal char ?\s)
5776 (setq s ""
5777 move nil)
5778 (unless (assoc (char-to-string char) org-emphasis-alist)
5779 (user-error "No such emphasis marker: \"%c\"" char))
5780 (setq s (char-to-string char)))
5781 (while (and (> (length string) 1)
5782 (equal (substring string 0 1) (substring string -1))
5783 (assoc (substring string 0 1) org-emphasis-alist))
5784 (setq string (substring string 1 -1)))
5785 (setq string (concat s string s))
5786 (when beg (delete-region beg end))
5787 (unless (or (bolp)
5788 (string-match (concat "[" (nth 0 erc) "\n]")
5789 (char-to-string (char-before (point)))))
5790 (insert " "))
5791 (unless (or (eobp)
5792 (string-match (concat "[" (nth 1 erc) "\n]")
5793 (char-to-string (char-after (point)))))
5794 (insert " ") (backward-char 1))
5795 (insert string)
5796 (and move (backward-char 1))))
5798 (defconst org-nonsticky-props
5799 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5801 (defsubst org-rear-nonsticky-at (pos)
5802 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5804 (defun org-activate-links (limit)
5805 "Add link properties to links.
5806 This includes angle, plain, and bracket links."
5807 (catch :exit
5808 (while (re-search-forward org-any-link-re limit t)
5809 (let* ((start (match-beginning 0))
5810 (end (match-end 0))
5811 (style (cond ((eq ?< (char-after start)) 'angle)
5812 ((eq ?\[ (char-after (1+ start))) 'bracket)
5813 (t 'plain))))
5814 (when (and (memq style org-highlight-links)
5815 ;; Do not confuse plain links with tags.
5816 (not (and (eq style 'plain)
5817 (let ((face (get-text-property
5818 (max (1- start) (point-min)) 'face)))
5819 (if (consp face) (memq 'org-tag face)
5820 (eq 'org-tag face))))))
5821 (let* ((link-object (save-excursion
5822 (goto-char start)
5823 (save-match-data (org-element-link-parser))))
5824 (link (org-element-property :raw-link link-object))
5825 (type (org-element-property :type link-object))
5826 (path (org-element-property :path link-object))
5827 (properties ;for link's visible part
5828 (list
5829 'face (pcase (org-link-get-parameter type :face)
5830 ((and (pred functionp) face) (funcall face path))
5831 ((and (pred facep) face) face)
5832 ((and (pred consp) face) face) ;anonymous
5833 (_ 'org-link))
5834 'mouse-face (or (org-link-get-parameter type :mouse-face)
5835 'highlight)
5836 'keymap (or (org-link-get-parameter type :keymap)
5837 org-mouse-map)
5838 'help-echo (pcase (org-link-get-parameter type :help-echo)
5839 ((and (pred stringp) echo) echo)
5840 ((and (pred functionp) echo) echo)
5841 (_ (concat "LINK: " link)))
5842 'htmlize-link (pcase (org-link-get-parameter type
5843 :htmlize-link)
5844 ((and (pred functionp) f) (funcall f))
5845 (_ `(:uri ,link)))
5846 'font-lock-multiline t)))
5847 (org-remove-flyspell-overlays-in start end)
5848 (org-rear-nonsticky-at end)
5849 (if (not (eq 'bracket style))
5850 (add-text-properties start end properties)
5851 ;; Handle invisible parts in bracket links.
5852 (remove-text-properties start end '(invisible nil))
5853 (let ((hidden
5854 (append `(invisible
5855 ,(or (org-link-get-parameter type :display)
5856 'org-link))
5857 properties))
5858 (visible-start (or (match-beginning 4) (match-beginning 2)))
5859 (visible-end (or (match-end 4) (match-end 2))))
5860 (add-text-properties start visible-start hidden)
5861 (add-text-properties visible-start visible-end properties)
5862 (add-text-properties visible-end end hidden)
5863 (org-rear-nonsticky-at visible-start)
5864 (org-rear-nonsticky-at visible-end)))
5865 (let ((f (org-link-get-parameter type :activate-func)))
5866 (when (functionp f)
5867 (funcall f start end path (eq style 'bracket))))
5868 (throw :exit t))))) ;signal success
5869 nil))
5871 (defun org-activate-code (limit)
5872 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5873 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5874 (remove-text-properties (match-beginning 0) (match-end 0)
5875 '(display t invisible t intangible t))
5878 (defcustom org-src-fontify-natively t
5879 "When non-nil, fontify code in code blocks.
5880 See also the `org-block' face."
5881 :type 'boolean
5882 :version "26.1"
5883 :package-version '(Org . "8.3")
5884 :group 'org-appearance
5885 :group 'org-babel)
5887 (defcustom org-allow-promoting-top-level-subtree nil
5888 "When non-nil, allow promoting a top level subtree.
5889 The leading star of the top level headline will be replaced
5890 by a #."
5891 :type 'boolean
5892 :version "24.1"
5893 :group 'org-appearance)
5895 (defun org-fontify-meta-lines-and-blocks (limit)
5896 (condition-case nil
5897 (org-fontify-meta-lines-and-blocks-1 limit)
5898 (error (message "org-mode fontification error in %S at %d"
5899 (current-buffer)
5900 (line-number-at-pos)))))
5902 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5903 "Fontify #+ lines and blocks."
5904 (let ((case-fold-search t))
5905 (when (re-search-forward
5906 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5907 limit t)
5908 (let ((beg (match-beginning 0))
5909 (block-start (match-end 0))
5910 (block-end nil)
5911 (lang (match-string 7))
5912 (beg1 (line-beginning-position 2))
5913 (dc1 (downcase (match-string 2)))
5914 (dc3 (downcase (match-string 3)))
5915 end end1 quoting block-type)
5916 (cond
5917 ((and (match-end 4) (equal dc3 "+begin"))
5918 ;; Truly a block
5919 (setq block-type (downcase (match-string 5))
5920 quoting (member block-type org-protecting-blocks))
5921 (when (re-search-forward
5922 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5923 nil t) ;; on purpose, we look further than LIMIT
5924 (setq end (min (point-max) (match-end 0))
5925 end1 (min (point-max) (1- (match-beginning 0))))
5926 (setq block-end (match-beginning 0))
5927 (when quoting
5928 (org-remove-flyspell-overlays-in beg1 end1)
5929 (remove-text-properties beg end
5930 '(display t invisible t intangible t)))
5931 (add-text-properties
5932 beg end '(font-lock-fontified t font-lock-multiline t))
5933 (add-text-properties beg beg1 '(face org-meta-line))
5934 (org-remove-flyspell-overlays-in beg beg1)
5935 (add-text-properties ; For end_src
5936 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5937 (org-remove-flyspell-overlays-in end1 end)
5938 (cond
5939 ((and lang (not (string= lang "")) org-src-fontify-natively)
5940 (org-src-font-lock-fontify-block lang block-start block-end)
5941 (add-text-properties beg1 block-end '(src-block t)))
5942 (quoting
5943 (add-text-properties beg1 (min (point-max) (1+ end1))
5944 (list 'face
5945 (list :inherit
5946 (let ((face-name
5947 (intern (format "org-block-%s" lang))))
5948 (append (and (facep face-name) (list face-name))
5949 '(org-block))))))) ; end of source block
5950 ((not org-fontify-quote-and-verse-blocks))
5951 ((string= block-type "quote")
5952 (add-face-text-property
5953 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5954 ((string= block-type "verse")
5955 (add-face-text-property
5956 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5957 (add-text-properties beg beg1 '(face org-block-begin-line))
5958 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5959 '(face org-block-end-line))
5961 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5962 (org-remove-flyspell-overlays-in
5963 (match-beginning 0)
5964 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5965 (add-text-properties
5966 beg (match-end 3)
5967 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5968 '(font-lock-fontified t invisible t)
5969 '(font-lock-fontified t face org-document-info-keyword)))
5970 (add-text-properties
5971 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5972 (if (string-equal dc1 "+title:")
5973 '(font-lock-fontified t face org-document-title)
5974 '(font-lock-fontified t face org-document-info))))
5975 ((string-prefix-p "+caption" dc1)
5976 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5977 (remove-text-properties (match-beginning 0) (match-end 0)
5978 '(display t invisible t intangible t))
5979 ;; Handle short captions.
5980 (save-excursion
5981 (beginning-of-line)
5982 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5983 (add-text-properties (line-beginning-position) (match-end 1)
5984 '(font-lock-fontified t face org-meta-line))
5985 (add-text-properties (match-end 0) (line-end-position)
5986 '(font-lock-fontified t face org-block))
5988 ((member dc3 '(" " ""))
5989 (org-remove-flyspell-overlays-in beg (match-end 0))
5990 (add-text-properties
5991 beg (match-end 0)
5992 '(font-lock-fontified t face font-lock-comment-face)))
5993 (t ;; just any other in-buffer setting, but not indented
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (remove-text-properties (match-beginning 0) (match-end 0)
5996 '(display t invisible t intangible t))
5997 (add-text-properties beg (match-end 0)
5998 '(font-lock-fontified t face org-meta-line))
5999 t))))))
6001 (defun org-fontify-drawers (limit)
6002 "Fontify drawers."
6003 (when (re-search-forward org-drawer-regexp limit t)
6004 (add-text-properties
6005 (match-beginning 0) (match-end 0)
6006 '(font-lock-fontified t face org-special-keyword))
6007 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (defun org-fontify-macros (limit)
6011 "Fontify macros."
6012 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6013 (add-text-properties
6014 (match-beginning 0) (match-end 0)
6015 '(font-lock-fontified t face org-macro))
6016 (when org-hide-macro-markers
6017 (add-text-properties (match-end 2) (match-beginning 2)
6018 '(invisible t))
6019 (add-text-properties (match-beginning 1) (match-end 1)
6020 '(invisible t)))
6021 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6024 (defun org-activate-footnote-links (limit)
6025 "Add text properties for footnotes."
6026 (let ((fn (org-footnote-next-reference-or-definition limit)))
6027 (when fn
6028 (let* ((beg (nth 1 fn))
6029 (end (nth 2 fn))
6030 (label (car fn))
6031 (referencep (/= (line-beginning-position) beg)))
6032 (when (and referencep (nth 3 fn))
6033 (save-excursion
6034 (goto-char beg)
6035 (search-forward (or label "fn:"))
6036 (org-remove-flyspell-overlays-in beg (match-end 0))))
6037 (add-text-properties beg end
6038 (list 'mouse-face 'highlight
6039 'keymap org-mouse-map
6040 'help-echo
6041 (if referencep "Footnote reference"
6042 "Footnote definition")
6043 'font-lock-fontified t
6044 'font-lock-multiline t
6045 'face 'org-footnote))))))
6047 (defun org-activate-dates (limit)
6048 "Add text properties for dates."
6049 (when (and (re-search-forward org-tsr-regexp-both limit t)
6050 (not (equal (char-before (match-beginning 0)) 91)))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (add-text-properties (match-beginning 0) (match-end 0)
6053 (list 'mouse-face 'highlight
6054 'keymap org-mouse-map))
6055 (org-rear-nonsticky-at (match-end 0))
6056 (when org-display-custom-times
6057 ;; If it's a date range, activate custom time for second date.
6058 (when (match-end 3)
6059 (org-display-custom-time (match-beginning 3) (match-end 3)))
6060 (org-display-custom-time (match-beginning 1) (match-end 1)))
6063 (defvar-local org-target-link-regexp nil
6064 "Regular expression matching radio targets in plain text.")
6066 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6067 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6068 border border border))
6069 "Regular expression matching a link target.")
6071 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6072 "Regular expression matching a radio target.")
6074 (defconst org-any-target-regexp
6075 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6076 "Regular expression matching any target.")
6078 (defun org-activate-target-links (limit)
6079 "Add text properties for target matches."
6080 (when org-target-link-regexp
6081 (let ((case-fold-search t))
6082 (when (re-search-forward org-target-link-regexp limit t)
6083 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6084 (add-text-properties (match-beginning 1) (match-end 1)
6085 (list 'mouse-face 'highlight
6086 'keymap org-mouse-map
6087 'help-echo "Radio target link"
6088 'org-linked-text t))
6089 (org-rear-nonsticky-at (match-end 1))
6090 t))))
6092 (defun org-update-radio-target-regexp ()
6093 "Find all radio targets in this file and update the regular expression.
6094 Also refresh fontification if needed."
6095 (interactive)
6096 (let ((old-regexp org-target-link-regexp)
6097 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6098 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6099 (targets
6100 (org-with-wide-buffer
6101 (goto-char (point-min))
6102 (let (rtn)
6103 (while (re-search-forward org-radio-target-regexp nil t)
6104 ;; Make sure point is really within the object.
6105 (backward-char)
6106 (let ((obj (org-element-context)))
6107 (when (eq (org-element-type obj) 'radio-target)
6108 (cl-pushnew (org-element-property :value obj) rtn
6109 :test #'equal))))
6110 rtn))))
6111 (setq org-target-link-regexp
6112 (and targets
6113 (concat before-re
6114 (mapconcat
6115 (lambda (x)
6116 (replace-regexp-in-string
6117 " +" "\\s-+" (regexp-quote x) t t))
6118 targets
6119 "\\|")
6120 after-re)))
6121 (unless (equal old-regexp org-target-link-regexp)
6122 ;; Clean-up cache.
6123 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6124 ((not org-target-link-regexp) old-regexp)
6126 (concat before-re
6127 (mapconcat
6128 (lambda (re)
6129 (substring re (length before-re)
6130 (- (length after-re))))
6131 (list old-regexp org-target-link-regexp)
6132 "\\|")
6133 after-re)))))
6134 (org-with-wide-buffer
6135 (goto-char (point-min))
6136 (while (re-search-forward regexp nil t)
6137 (org-element-cache-refresh (match-beginning 1)))))
6138 ;; Re fontify buffer.
6139 (when (memq 'radio org-highlight-links)
6140 (org-restart-font-lock)))))
6142 (defvar org-latex-and-related-regexp nil
6143 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6145 (defun org-compute-latex-and-related-regexp ()
6146 "Compute regular expression for LaTeX, entities and sub/superscript.
6147 Result depends on variable `org-highlight-latex-and-related'."
6148 (setq-local
6149 org-latex-and-related-regexp
6150 (let* ((re-sub
6151 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6152 ((eq org-use-sub-superscripts '{})
6153 (list org-match-substring-with-braces-regexp))
6154 (org-use-sub-superscripts (list org-match-substring-regexp))))
6155 (re-latex
6156 (when (memq 'latex org-highlight-latex-and-related)
6157 (let ((matchers (plist-get org-format-latex-options :matchers)))
6158 (delq nil
6159 (mapcar (lambda (x)
6160 (and (member (car x) matchers) (nth 1 x)))
6161 org-latex-regexps)))))
6162 (re-entities
6163 (when (memq 'entities org-highlight-latex-and-related)
6164 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6165 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6167 (defun org-do-latex-and-related (limit)
6168 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6169 LIMIT bounds the search for syntax to highlight. Stop at first
6170 highlighted object, if any. Return t if some highlighting was
6171 done, nil otherwise."
6172 (when (org-string-nw-p org-latex-and-related-regexp)
6173 (catch 'found
6174 (while (re-search-forward org-latex-and-related-regexp limit t)
6175 (unless
6176 (cl-some
6177 (lambda (f)
6178 (memq f '(org-code org-verbatim underline org-special-keyword)))
6179 (save-excursion
6180 (goto-char (1+ (match-beginning 0)))
6181 (face-at-point nil t)))
6182 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6183 '(?_ ?^))
6185 0)))
6186 (font-lock-prepend-text-property
6187 (+ offset (match-beginning 0)) (match-end 0)
6188 'face 'org-latex-and-related)
6189 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6190 '(font-lock-multiline t)))
6191 (throw 'found t)))
6192 nil)))
6194 (defun org-restart-font-lock ()
6195 "Restart `font-lock-mode', to force refontification."
6196 (when (and (boundp 'font-lock-mode) font-lock-mode)
6197 (font-lock-mode -1)
6198 (font-lock-mode 1)))
6200 (defun org-activate-tags (limit)
6201 (when (re-search-forward
6202 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6203 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6204 (add-text-properties (match-beginning 1) (match-end 1)
6205 (list 'mouse-face 'highlight
6206 'keymap org-mouse-map))
6207 (org-rear-nonsticky-at (match-end 1))
6210 (defun org-outline-level ()
6211 "Compute the outline level of the heading at point.
6213 If this is called at a normal headline, the level is the number
6214 of stars. Use `org-reduced-level' to remove the effect of
6215 `org-odd-levels'. Unlike to `org-current-level', this function
6216 takes into consideration inlinetasks."
6217 (org-with-wide-buffer
6218 (end-of-line)
6219 (if (re-search-backward org-outline-regexp-bol nil t)
6220 (1- (- (match-end 0) (match-beginning 0)))
6221 0)))
6223 (defvar org-font-lock-keywords nil)
6225 (defsubst org-re-property (property &optional literal allow-null value)
6226 "Return a regexp matching a PROPERTY line.
6228 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6229 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6230 non-nil, match properties even without a value.
6232 Match group 3 is set to the value when it exists. If there is no
6233 value and ALLOW-NULL is non-nil, it is set to the empty string.
6235 With optional argument VALUE, match only property lines with
6236 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6237 unless LITERAL is non-nil."
6238 (concat
6239 "^\\(?4:[ \t]*\\)"
6240 (format "\\(?1::\\(?2:%s\\):\\)"
6241 (if literal property (regexp-quote property)))
6242 (cond (value
6243 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6244 (if literal value (regexp-quote value))))
6245 (allow-null
6246 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6248 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6250 (defconst org-property-re
6251 (org-re-property "\\S-+" 'literal t)
6252 "Regular expression matching a property line.
6253 There are four matching groups:
6254 1: :PROPKEY: including the leading and trailing colon,
6255 2: PROPKEY without the leading and trailing colon,
6256 3: PROPVAL without leading or trailing spaces,
6257 4: the indentation of the current line,
6258 5: trailing whitespace.")
6260 (defvar org-font-lock-hook nil
6261 "Functions to be called for special font lock stuff.")
6263 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6265 (defvar org-font-lock-set-keywords-hook nil
6266 "Functions that can manipulate `org-font-lock-extra-keywords'.
6267 This is called after `org-font-lock-extra-keywords' is defined, but before
6268 it is installed to be used by font lock. This can be useful if something
6269 needs to be inserted at a specific position in the font-lock sequence.")
6271 (defun org-font-lock-hook (limit)
6272 "Run `org-font-lock-hook' within LIMIT."
6273 (run-hook-with-args 'org-font-lock-hook limit))
6275 (defun org-set-font-lock-defaults ()
6276 "Set font lock defaults for the current buffer."
6277 (let* ((em org-fontify-emphasized-text)
6278 (lk org-highlight-links)
6279 (org-font-lock-extra-keywords
6280 (list
6281 ;; Call the hook
6282 '(org-font-lock-hook)
6283 ;; Headlines
6284 `(,(if org-fontify-whole-heading-line
6285 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6286 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6287 (1 (org-get-level-face 1))
6288 (2 (org-get-level-face 2))
6289 (3 (org-get-level-face 3)))
6290 ;; Table lines
6291 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6292 (1 'org-table t))
6293 ;; Table internals
6294 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6295 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6296 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6297 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6298 ;; Drawers
6299 '(org-fontify-drawers)
6300 ;; Properties
6301 (list org-property-re
6302 '(1 'org-special-keyword t)
6303 '(3 'org-property-value t))
6304 ;; Link related fontification.
6305 '(org-activate-links)
6306 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6307 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6308 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6309 (when (memq 'footnote lk) '(org-activate-footnote-links))
6310 ;; Targets.
6311 (list org-any-target-regexp '(0 'org-target t))
6312 ;; Diary sexps.
6313 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6314 ;; Macro
6315 '(org-fontify-macros)
6316 ;; TODO keyword
6317 (list (format org-heading-keyword-regexp-format
6318 org-todo-regexp)
6319 '(2 (org-get-todo-face 2) t))
6320 ;; DONE
6321 (if org-fontify-done-headline
6322 (list (format org-heading-keyword-regexp-format
6323 (concat
6324 "\\(?:"
6325 (mapconcat 'regexp-quote org-done-keywords "\\|")
6326 "\\)"))
6327 '(2 'org-headline-done t))
6328 nil)
6329 ;; Priorities
6330 '(org-font-lock-add-priority-faces)
6331 ;; Tags
6332 '(org-font-lock-add-tag-faces)
6333 ;; Tags groups
6334 (when (and org-group-tags org-tag-groups-alist)
6335 (list (concat org-outline-regexp-bol ".+\\(:"
6336 (regexp-opt (mapcar 'car org-tag-groups-alist))
6337 ":\\).*$")
6338 '(1 'org-tag-group prepend)))
6339 ;; Special keywords
6340 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6341 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6343 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6344 ;; Emphasis
6345 (when em '(org-do-emphasis-faces))
6346 ;; Checkboxes
6347 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6348 1 'org-checkbox prepend)
6349 (when (cdr (assq 'checkbox org-list-automatic-rules))
6350 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6351 (0 (org-get-checkbox-statistics-face) t)))
6352 ;; Description list items
6353 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6354 1 'org-list-dt prepend)
6355 ;; ARCHIVEd headings
6356 (list (concat
6357 org-outline-regexp-bol
6358 "\\(.*:" org-archive-tag ":.*\\)")
6359 '(1 'org-archived prepend))
6360 ;; Specials
6361 '(org-do-latex-and-related)
6362 '(org-fontify-entities)
6363 '(org-raise-scripts)
6364 ;; Code
6365 '(org-activate-code (1 'org-code t))
6366 ;; COMMENT
6367 (list (format
6368 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6369 org-todo-regexp
6370 org-comment-string)
6371 '(9 'org-special-keyword t))
6372 ;; Blocks and meta lines
6373 '(org-fontify-meta-lines-and-blocks))))
6374 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6375 (run-hooks 'org-font-lock-set-keywords-hook)
6376 ;; Now set the full font-lock-keywords
6377 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6378 (setq-local font-lock-defaults
6379 '(org-font-lock-keywords t nil nil backward-paragraph))
6380 (kill-local-variable 'font-lock-keywords)
6381 nil))
6383 (defun org-toggle-pretty-entities ()
6384 "Toggle the composition display of entities as UTF8 characters."
6385 (interactive)
6386 (setq-local org-pretty-entities (not org-pretty-entities))
6387 (org-restart-font-lock)
6388 (if org-pretty-entities
6389 (message "Entities are now displayed as UTF8 characters")
6390 (save-restriction
6391 (widen)
6392 (decompose-region (point-min) (point-max))
6393 (message "Entities are now displayed as plain text"))))
6395 (defvar-local org-custom-properties-overlays nil
6396 "List of overlays used for custom properties.")
6398 (defun org-toggle-custom-properties-visibility ()
6399 "Display or hide properties in `org-custom-properties'."
6400 (interactive)
6401 (if org-custom-properties-overlays
6402 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6403 (setq org-custom-properties-overlays nil))
6404 (when org-custom-properties
6405 (org-with-wide-buffer
6406 (goto-char (point-min))
6407 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6408 (while (re-search-forward regexp nil t)
6409 (let ((end (cdr (save-match-data (org-get-property-block)))))
6410 (when (and end (< (point) end))
6411 ;; Hide first custom property in current drawer.
6412 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6413 (overlay-put o 'invisible t)
6414 (overlay-put o 'org-custom-property t)
6415 (push o org-custom-properties-overlays))
6416 ;; Hide additional custom properties in the same drawer.
6417 (while (re-search-forward regexp end t)
6418 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6419 (overlay-put o 'invisible t)
6420 (overlay-put o 'org-custom-property t)
6421 (push o org-custom-properties-overlays)))))
6422 ;; Each entry is limited to a single property drawer.
6423 (outline-next-heading)))))))
6425 (defun org-fontify-entities (limit)
6426 "Find an entity to fontify."
6427 (let (ee)
6428 (when org-pretty-entities
6429 (catch 'match
6430 ;; "\_ "-family is left out on purpose. Only the first one,
6431 ;; i.e., "\_ ", could be fontified anyway, and it would be
6432 ;; confusing when adding a second white space character.
6433 (while (re-search-forward
6434 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6435 limit t)
6436 (when (and (not (org-at-comment-p))
6437 (setq ee (org-entity-get (match-string 1)))
6438 (= (length (nth 6 ee)) 1))
6439 (let* ((end (if (equal (match-string 2) "{}")
6440 (match-end 2)
6441 (match-end 1))))
6442 (add-text-properties
6443 (match-beginning 0) end
6444 (list 'font-lock-fontified t))
6445 (compose-region (match-beginning 0) end
6446 (nth 6 ee) nil)
6447 (backward-char 1)
6448 (throw 'match t))))
6449 nil))))
6451 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6452 "Fontify string S like in Org mode."
6453 (with-temp-buffer
6454 (insert s)
6455 (let ((org-odd-levels-only odd-levels))
6456 (org-mode)
6457 (org-font-lock-ensure)
6458 (buffer-string))))
6460 (defvar org-m nil)
6461 (defvar org-l nil)
6462 (defvar org-f nil)
6463 (defun org-get-level-face (n)
6464 "Get the right face for match N in font-lock matching of headlines."
6465 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6466 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6467 (if org-cycle-level-faces
6468 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6469 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6470 (cond
6471 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6472 ((eq n 2) org-f)
6473 (t (unless org-level-color-stars-only org-f))))
6475 (defun org-face-from-face-or-color (context inherit face-or-color)
6476 "Create a face list that inherits INHERIT, but sets the foreground color.
6477 When FACE-OR-COLOR is not a string, just return it."
6478 (if (stringp face-or-color)
6479 (list :inherit inherit
6480 (cdr (assoc context org-faces-easy-properties))
6481 face-or-color)
6482 face-or-color))
6484 (defun org-get-todo-face (kwd)
6485 "Get the right face for a TODO keyword KWD.
6486 If KWD is a number, get the corresponding match group."
6487 (when (numberp kwd) (setq kwd (match-string kwd)))
6488 (or (org-face-from-face-or-color
6489 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6490 (and (member kwd org-done-keywords) 'org-done)
6491 'org-todo))
6493 (defun org-get-priority-face (priority)
6494 "Get the right face for PRIORITY.
6495 PRIORITY is a character."
6496 (or (org-face-from-face-or-color
6497 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6498 'org-priority))
6500 (defun org-get-tag-face (tag)
6501 "Get the right face for TAG.
6502 If TAG is a number, get the corresponding match group."
6503 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6504 (or (org-face-from-face-or-color
6505 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6506 'org-tag)))
6508 (defun org-font-lock-add-priority-faces (limit)
6509 "Add the special priority faces."
6510 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6511 (add-text-properties
6512 (match-beginning 1) (match-end 1)
6513 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6514 'font-lock-fontified t))))
6516 (defun org-font-lock-add-tag-faces (limit)
6517 "Add the special tag faces."
6518 (when (and org-tag-faces org-tags-special-faces-re)
6519 (while (re-search-forward org-tags-special-faces-re limit t)
6520 (add-text-properties (match-beginning 1) (match-end 1)
6521 (list 'face (org-get-tag-face 1)
6522 'font-lock-fontified t))
6523 (backward-char 1))))
6525 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6526 "Remove fontification and activation overlays from links."
6527 (font-lock-default-unfontify-region beg end)
6528 (let* ((buffer-undo-list t)
6529 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6530 (inhibit-modification-hooks t)
6531 deactivate-mark buffer-file-name buffer-file-truename)
6532 (decompose-region beg end)
6533 (remove-text-properties beg end
6534 '(mouse-face t keymap t org-linked-text t
6535 invisible t intangible t
6536 org-emphasis t))
6537 (org-remove-font-lock-display-properties beg end)))
6539 (defconst org-script-display '(((raise -0.3) (height 0.7))
6540 ((raise 0.3) (height 0.7))
6541 ((raise -0.5))
6542 ((raise 0.5)))
6543 "Display properties for showing superscripts and subscripts.")
6545 (defun org-remove-font-lock-display-properties (beg end)
6546 "Remove specific display properties that have been added by font lock.
6547 The will remove the raise properties that are used to show superscripts
6548 and subscripts."
6549 (let (next prop)
6550 (while (< beg end)
6551 (setq next (next-single-property-change beg 'display nil end)
6552 prop (get-text-property beg 'display))
6553 (when (member prop org-script-display)
6554 (put-text-property beg next 'display nil))
6555 (setq beg next))))
6557 (defun org-raise-scripts (limit)
6558 "Add raise properties to sub/superscripts."
6559 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6560 (re-search-forward
6561 (if (eq org-use-sub-superscripts t)
6562 org-match-substring-regexp
6563 org-match-substring-with-braces-regexp)
6564 limit t))
6565 (let* ((pos (point)) table-p comment-p
6566 (mpos (match-beginning 3))
6567 (emph-p (get-text-property mpos 'org-emphasis))
6568 (link-p (get-text-property mpos 'mouse-face))
6569 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6570 (goto-char (point-at-bol))
6571 (setq table-p (looking-at-p org-table-dataline-regexp)
6572 comment-p (looking-at-p "^[ \t]*#[ +]"))
6573 (goto-char pos)
6574 ;; Handle a_b^c
6575 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6576 (unless (or comment-p emph-p link-p keyw-p)
6577 (put-text-property (match-beginning 3) (match-end 0)
6578 'display
6579 (if (equal (char-after (match-beginning 2)) ?^)
6580 (nth (if table-p 3 1) org-script-display)
6581 (nth (if table-p 2 0) org-script-display)))
6582 (add-text-properties (match-beginning 2) (match-end 2)
6583 (list 'invisible t))
6584 (when (and (eq (char-after (match-beginning 3)) ?{)
6585 (eq (char-before (match-end 3)) ?}))
6586 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6587 (list 'invisible t))
6588 (add-text-properties (1- (match-end 3)) (match-end 3)
6589 (list 'invisible t))))
6590 t)))
6592 ;;;; Visibility cycling, including org-goto and indirect buffer
6594 ;;; Cycling
6596 (defvar-local org-cycle-global-status nil)
6597 (put 'org-cycle-global-status 'org-state t)
6598 (defvar-local org-cycle-subtree-status nil)
6599 (put 'org-cycle-subtree-status 'org-state t)
6601 (defvar org-inlinetask-min-level)
6603 ;;;###autoload
6604 (defun org-cycle (&optional arg)
6605 "TAB-action and visibility cycling for Org mode.
6607 This is the command invoked in Org mode by the `TAB' key. Its main
6608 purpose is outline visibility cycling, but it also invokes other actions
6609 in special contexts.
6611 When this function is called with a `\\[universal-argument]' prefix, rotate \
6612 the entire
6613 buffer through 3 states (global cycling)
6614 1. OVERVIEW: Show only top-level headlines.
6615 2. CONTENTS: Show all headlines of all levels, but no body text.
6616 3. SHOW ALL: Show everything.
6618 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6619 switch to the startup visibility,
6620 determined by the variable `org-startup-folded', and by any VISIBILITY
6621 properties in the buffer.
6623 With a `\\[universal-argument] \\[universal-argument] \
6624 \\[universal-argument]' prefix argument, show the entire buffer, including
6625 any drawers.
6627 When inside a table, re-align the table and move to the next field.
6629 When point is at the beginning of a headline, rotate the subtree started
6630 by this line through 3 different states (local cycling)
6631 1. FOLDED: Only the main headline is shown.
6632 2. CHILDREN: The main headline and the direct children are shown.
6633 From this state, you can move to one of the children
6634 and zoom in further.
6635 3. SUBTREE: Show the entire subtree, including body text.
6636 If there is no subtree, switch directly from CHILDREN to FOLDED.
6638 When point is at the beginning of an empty headline and the variable
6639 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6640 of the headline by demoting and promoting it to likely levels. This
6641 speeds up creation document structure by pressing `TAB' once or several
6642 times right after creating a new headline.
6644 When there is a numeric prefix, go up to a heading with level ARG, do
6645 a `show-subtree' and return to the previous cursor position. If ARG
6646 is negative, go up that many levels.
6648 When point is not at the beginning of a headline, execute the global
6649 binding for `TAB', which is re-indenting the line. See the option
6650 `org-cycle-emulate-tab' for details.
6652 As a special case, if point is at the beginning of the buffer and there is
6653 no headline in line 1, this function will act as if called with prefix arg
6654 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6655 prefix arg, but only
6656 if the variable `org-cycle-global-at-bob' is t."
6657 (interactive "P")
6658 (org-load-modules-maybe)
6659 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6660 (and org-cycle-level-after-item/entry-creation
6661 (or (org-cycle-level)
6662 (org-cycle-item-indentation))))
6663 (let* ((limit-level
6664 (or org-cycle-max-level
6665 (and (boundp 'org-inlinetask-min-level)
6666 org-inlinetask-min-level
6667 (1- org-inlinetask-min-level))))
6668 (nstars (and limit-level
6669 (if org-odd-levels-only
6670 (and limit-level (1- (* limit-level 2)))
6671 limit-level)))
6672 (org-outline-regexp
6673 (if (not (derived-mode-p 'org-mode))
6674 outline-regexp
6675 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6676 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6677 (not (looking-at org-outline-regexp))))
6678 (org-cycle-hook
6679 (if bob-special
6680 (delq 'org-optimize-window-after-visibility-change
6681 (copy-sequence org-cycle-hook))
6682 org-cycle-hook))
6683 (pos (point)))
6685 (cond
6687 ((equal arg '(16))
6688 (setq last-command 'dummy)
6689 (org-set-startup-visibility)
6690 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6692 ((equal arg '(64))
6693 (outline-show-all)
6694 (org-unlogged-message "Entire buffer visible, including drawers"))
6696 ((equal arg '(4)) (org-cycle-internal-global))
6698 ;; Try hiding block at point.
6699 ((org-hide-block-toggle-maybe))
6701 ;; Try cdlatex TAB completion
6702 ((org-try-cdlatex-tab))
6704 ;; Table: enter it or move to the next field.
6705 ((org-at-table-p 'any)
6706 (if (org-at-table.el-p)
6707 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6708 Use `\\[org-edit-special]' to edit table.el tables"))
6709 (if arg (org-table-edit-field t)
6710 (org-table-justify-field-maybe)
6711 (call-interactively 'org-table-next-field))))
6713 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6715 ;; Global cycling: delegate to `org-cycle-internal-global'.
6716 (bob-special (org-cycle-internal-global))
6718 ;; Drawers: delegate to `org-flag-drawer'.
6719 ((save-excursion
6720 (beginning-of-line 1)
6721 (looking-at org-drawer-regexp))
6722 (org-flag-drawer ; toggle block visibility
6723 (not (get-char-property (match-end 0) 'invisible))))
6725 ;; Show-subtree, ARG levels up from here.
6726 ((integerp arg)
6727 (save-excursion
6728 (org-back-to-heading)
6729 (outline-up-heading (if (< arg 0) (- arg)
6730 (- (funcall outline-level) arg)))
6731 (org-show-subtree)))
6733 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6734 ((and (featurep 'org-inlinetask)
6735 (org-inlinetask-at-task-p)
6736 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6737 (org-inlinetask-toggle-visibility))
6739 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6740 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6741 (save-excursion (move-beginning-of-line 1)
6742 (looking-at org-outline-regexp)))
6743 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6744 (org-cycle-internal-local))
6746 ;; From there: TAB emulation and template completion.
6747 (buffer-read-only (org-back-to-heading))
6749 ((run-hook-with-args-until-success
6750 'org-tab-after-check-for-cycling-hook))
6752 ((run-hook-with-args-until-success
6753 'org-tab-before-tab-emulation-hook))
6755 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6756 (or (not (bolp))
6757 (not (looking-at org-outline-regexp))))
6758 (call-interactively (global-key-binding "\t")))
6760 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6761 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6762 (or (and (eq org-cycle-emulate-tab 'white)
6763 (= (match-end 0) (point-at-eol)))
6764 (and (eq org-cycle-emulate-tab 'whitestart)
6765 (>= (match-end 0) pos))))
6767 (eq org-cycle-emulate-tab t))
6768 (call-interactively (global-key-binding "\t")))
6770 (t (save-excursion
6771 (org-back-to-heading)
6772 (org-cycle)))))))
6774 (defun org-cycle-internal-global ()
6775 "Do the global cycling action."
6776 ;; Hack to avoid display of messages for .org attachments in Gnus
6777 (let ((ga (string-match "\\*fontification" (buffer-name))))
6778 (cond
6779 ((and (eq last-command this-command)
6780 (eq org-cycle-global-status 'overview))
6781 ;; We just created the overview - now do table of contents
6782 ;; This can be slow in very large buffers, so indicate action
6783 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6784 (unless ga (org-unlogged-message "CONTENTS..."))
6785 (org-content)
6786 (unless ga (org-unlogged-message "CONTENTS...done"))
6787 (setq org-cycle-global-status 'contents)
6788 (run-hook-with-args 'org-cycle-hook 'contents))
6790 ((and (eq last-command this-command)
6791 (eq org-cycle-global-status 'contents))
6792 ;; We just showed the table of contents - now show everything
6793 (run-hook-with-args 'org-pre-cycle-hook 'all)
6794 (outline-show-all)
6795 (unless ga (org-unlogged-message "SHOW ALL"))
6796 (setq org-cycle-global-status 'all)
6797 (run-hook-with-args 'org-cycle-hook 'all))
6800 ;; Default action: go to overview
6801 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6802 (org-overview)
6803 (unless ga (org-unlogged-message "OVERVIEW"))
6804 (setq org-cycle-global-status 'overview)
6805 (run-hook-with-args 'org-cycle-hook 'overview)))))
6807 (defvar org-called-with-limited-levels nil
6808 "Non-nil when `org-with-limited-levels' is currently active.")
6810 (defun org-cycle-internal-local ()
6811 "Do the local cycling action."
6812 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6813 ;; First, determine end of headline (EOH), end of subtree or item
6814 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6815 (save-excursion
6816 (if (org-at-item-p)
6817 (progn
6818 (beginning-of-line)
6819 (setq struct (org-list-struct))
6820 (setq eoh (point-at-eol))
6821 (setq eos (org-list-get-item-end-before-blank (point) struct))
6822 (setq has-children (org-list-has-child-p (point) struct)))
6823 (org-back-to-heading)
6824 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6825 (setq eos (save-excursion (org-end-of-subtree t t)
6826 (when (bolp) (backward-char)) (point)))
6827 (setq has-children
6828 (or (save-excursion
6829 (let ((level (funcall outline-level)))
6830 (outline-next-heading)
6831 (and (org-at-heading-p t)
6832 (> (funcall outline-level) level))))
6833 (save-excursion
6834 (org-list-search-forward (org-item-beginning-re) eos t)))))
6835 ;; Determine end invisible part of buffer (EOL)
6836 (beginning-of-line 2)
6837 (while (and (not (eobp)) ;This is like `next-line'.
6838 (get-char-property (1- (point)) 'invisible))
6839 (goto-char (next-single-char-property-change (point) 'invisible))
6840 (and (eolp) (beginning-of-line 2)))
6841 (setq eol (point)))
6842 ;; Find out what to do next and set `this-command'
6843 (cond
6844 ((= eos eoh)
6845 ;; Nothing is hidden behind this heading
6846 (unless (org-before-first-heading-p)
6847 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6848 (org-unlogged-message "EMPTY ENTRY")
6849 (setq org-cycle-subtree-status nil)
6850 (save-excursion
6851 (goto-char eos)
6852 (outline-next-heading)
6853 (when (org-invisible-p) (org-flag-heading nil))))
6854 ((and (or (>= eol eos)
6855 (not (string-match "\\S-" (buffer-substring eol eos))))
6856 (or has-children
6857 (not (setq children-skipped
6858 org-cycle-skip-children-state-if-no-children))))
6859 ;; Entire subtree is hidden in one line: children view
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-pre-cycle-hook 'children))
6862 (if (org-at-item-p)
6863 (org-list-set-item-visibility (point-at-bol) struct 'children)
6864 (org-show-entry)
6865 (org-with-limited-levels (org-show-children))
6866 (org-show-set-visibility 'canonical)
6867 ;; FIXME: This slows down the func way too much.
6868 ;; How keep drawers hidden in subtree anyway?
6869 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6870 ;; (org-cycle-hide-drawers 'subtree))
6872 ;; Fold every list in subtree to top-level items.
6873 (when (eq org-cycle-include-plain-lists 'integrate)
6874 (save-excursion
6875 (org-back-to-heading)
6876 (while (org-list-search-forward (org-item-beginning-re) eos t)
6877 (beginning-of-line 1)
6878 (let* ((struct (org-list-struct))
6879 (prevs (org-list-prevs-alist struct))
6880 (end (org-list-get-bottom-point struct)))
6881 (dolist (e (org-list-get-all-items (point) struct prevs))
6882 (org-list-set-item-visibility e struct 'folded))
6883 (goto-char (if (< end eos) end eos)))))))
6884 (org-unlogged-message "CHILDREN")
6885 (save-excursion
6886 (goto-char eos)
6887 (outline-next-heading)
6888 (when (org-invisible-p) (org-flag-heading nil)))
6889 (setq org-cycle-subtree-status 'children)
6890 (unless (org-before-first-heading-p)
6891 (run-hook-with-args 'org-cycle-hook 'children)))
6892 ((or children-skipped
6893 (and (eq last-command this-command)
6894 (eq org-cycle-subtree-status 'children)))
6895 ;; We just showed the children, or no children are there,
6896 ;; now show everything.
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6899 (outline-flag-region eoh eos nil)
6900 (org-unlogged-message
6901 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6902 (setq org-cycle-subtree-status 'subtree)
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-cycle-hook 'subtree)))
6906 ;; Default action: hide the subtree.
6907 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6908 (outline-flag-region eoh eos t)
6909 (org-unlogged-message "FOLDED")
6910 (setq org-cycle-subtree-status 'folded)
6911 (unless (org-before-first-heading-p)
6912 (run-hook-with-args 'org-cycle-hook 'folded))))))
6914 ;;;###autoload
6915 (defun org-global-cycle (&optional arg)
6916 "Cycle the global visibility. For details see `org-cycle'.
6917 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6918 With a numeric prefix, show all headlines up to that level."
6919 (interactive "P")
6920 (let ((org-cycle-include-plain-lists
6921 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6922 (cond
6923 ((integerp arg)
6924 (outline-show-all)
6925 (outline-hide-sublevels arg)
6926 (setq org-cycle-global-status 'contents))
6927 ((equal arg '(4))
6928 (org-set-startup-visibility)
6929 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6931 (org-cycle '(4))))))
6933 (defun org-set-startup-visibility ()
6934 "Set the visibility required by startup options and properties."
6935 (cond
6936 ((eq org-startup-folded t)
6937 (org-overview))
6938 ((eq org-startup-folded 'content)
6939 (org-content))
6940 ((or (eq org-startup-folded 'showeverything)
6941 (eq org-startup-folded nil))
6942 (outline-show-all)))
6943 (unless (eq org-startup-folded 'showeverything)
6944 (when org-hide-block-startup (org-hide-block-all))
6945 (org-set-visibility-according-to-property 'no-cleanup)
6946 (org-cycle-hide-archived-subtrees 'all)
6947 (org-cycle-hide-drawers 'all)
6948 (org-cycle-show-empty-lines t)))
6950 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6951 "Switch subtree visibilities according to :VISIBILITY: property."
6952 (interactive)
6953 (org-with-wide-buffer
6954 (goto-char (point-min))
6955 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6956 (if (not (org-at-property-p)) (outline-next-heading)
6957 (let ((state (match-string 3)))
6958 (save-excursion
6959 (org-back-to-heading t)
6960 (outline-hide-subtree)
6961 (org-reveal)
6962 (cond
6963 ((equal state "folded")
6964 (outline-hide-subtree))
6965 ((equal state "children")
6966 (org-show-hidden-entry)
6967 (org-show-children))
6968 ((equal state "content")
6969 (save-excursion
6970 (save-restriction
6971 (org-narrow-to-subtree)
6972 (org-content))))
6973 ((member state '("all" "showall"))
6974 (outline-show-subtree)))))))
6975 (unless no-cleanup
6976 (org-cycle-hide-archived-subtrees 'all)
6977 (org-cycle-hide-drawers 'all)
6978 (org-cycle-show-empty-lines 'all))))
6980 ;; This function uses outline-regexp instead of the more fundamental
6981 ;; org-outline-regexp so that org-cycle-global works outside of Org
6982 ;; buffers, where outline-regexp is needed.
6983 (defun org-overview ()
6984 "Switch to overview mode, showing only top-level headlines.
6985 This shows all headlines with a level equal or greater than the level
6986 of the first headline in the buffer. This is important, because if the
6987 first headline is not level one, then (hide-sublevels 1) gives confusing
6988 results."
6989 (interactive)
6990 (save-excursion
6991 (let ((level
6992 (save-excursion
6993 (goto-char (point-min))
6994 (when (re-search-forward (concat "^" outline-regexp) nil t)
6995 (goto-char (match-beginning 0))
6996 (funcall outline-level)))))
6997 (and level (outline-hide-sublevels level)))))
6999 (defun org-content (&optional arg)
7000 "Show all headlines in the buffer, like a table of contents.
7001 With numerical argument N, show content up to level N."
7002 (interactive "P")
7003 (org-overview)
7004 (save-excursion
7005 ;; Visit all headings and show their offspring
7006 (and (integerp arg) (org-overview))
7007 (goto-char (point-max))
7008 (catch 'exit
7009 (while (and (progn (condition-case nil
7010 (outline-previous-visible-heading 1)
7011 (error (goto-char (point-min))))
7013 (looking-at org-outline-regexp))
7014 (if (integerp arg)
7015 (org-show-children (1- arg))
7016 (outline-show-branches))
7017 (when (bobp) (throw 'exit nil))))))
7019 (defun org-optimize-window-after-visibility-change (state)
7020 "Adjust the window after a change in outline visibility.
7021 This function is the default value of the hook `org-cycle-hook'."
7022 (when (get-buffer-window (current-buffer))
7023 (cond
7024 ((eq state 'content) nil)
7025 ((eq state 'all) nil)
7026 ((eq state 'folded) nil)
7027 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7028 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7030 (defun org-remove-empty-overlays-at (pos)
7031 "Remove outline overlays that do not contain non-white stuff."
7032 (dolist (o (overlays-at pos))
7033 (and (eq 'outline (overlay-get o 'invisible))
7034 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7035 (overlay-end o))))
7036 (delete-overlay o))))
7038 (defun org-clean-visibility-after-subtree-move ()
7039 "Fix visibility issues after moving a subtree."
7040 ;; First, find a reasonable region to look at:
7041 ;; Start two siblings above, end three below
7042 (let* ((beg (save-excursion
7043 (and (org-get-last-sibling)
7044 (org-get-last-sibling))
7045 (point)))
7046 (end (save-excursion
7047 (and (org-get-next-sibling)
7048 (org-get-next-sibling)
7049 (org-get-next-sibling))
7050 (if (org-at-heading-p)
7051 (point-at-eol)
7052 (point))))
7053 (level (looking-at "\\*+"))
7054 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7055 (save-excursion
7056 (save-restriction
7057 (narrow-to-region beg end)
7058 (when re
7059 ;; Properly fold already folded siblings
7060 (goto-char (point-min))
7061 (while (re-search-forward re nil t)
7062 (when (and (not (org-invisible-p))
7063 (save-excursion
7064 (goto-char (point-at-eol)) (org-invisible-p)))
7065 (outline-hide-entry))))
7066 (org-cycle-show-empty-lines 'overview)
7067 (org-cycle-hide-drawers 'overview)))))
7069 (defun org-cycle-show-empty-lines (state)
7070 "Show empty lines above all visible headlines.
7071 The region to be covered depends on STATE when called through
7072 `org-cycle-hook'. Lisp program can use t for STATE to get the
7073 entire buffer covered. Note that an empty line is only shown if there
7074 are at least `org-cycle-separator-lines' empty lines before the headline."
7075 (when (/= org-cycle-separator-lines 0)
7076 (save-excursion
7077 (let* ((n (abs org-cycle-separator-lines))
7078 (re (cond
7079 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7080 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7081 (t (let ((ns (number-to-string (- n 2))))
7082 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7083 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7084 beg end)
7085 (cond
7086 ((memq state '(overview contents t))
7087 (setq beg (point-min) end (point-max)))
7088 ((memq state '(children folded))
7089 (setq beg (point)
7090 end (progn (org-end-of-subtree t t)
7091 (line-beginning-position 2)))))
7092 (when beg
7093 (goto-char beg)
7094 (while (re-search-forward re end t)
7095 (unless (get-char-property (match-end 1) 'invisible)
7096 (let ((e (match-end 1))
7097 (b (if (>= org-cycle-separator-lines 0)
7098 (match-beginning 1)
7099 (save-excursion
7100 (goto-char (match-beginning 0))
7101 (skip-chars-backward " \t\n")
7102 (line-end-position)))))
7103 (outline-flag-region b e nil))))))))
7104 ;; Never hide empty lines at the end of the file.
7105 (save-excursion
7106 (goto-char (point-max))
7107 (outline-previous-heading)
7108 (outline-end-of-heading)
7109 (when (and (looking-at "[ \t\n]+")
7110 (= (match-end 0) (point-max)))
7111 (outline-flag-region (point) (match-end 0) nil))))
7113 (defun org-show-empty-lines-in-parent ()
7114 "Move to the parent and re-show empty lines before visible headlines."
7115 (save-excursion
7116 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7117 (org-cycle-show-empty-lines context))))
7119 (defun org-files-list ()
7120 "Return `org-agenda-files' list, plus all open Org files.
7121 This is useful for operations that need to scan all of a user's
7122 open and agenda-wise Org files."
7123 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7124 (dolist (buf (buffer-list))
7125 (with-current-buffer buf
7126 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7127 (cl-pushnew (expand-file-name (buffer-file-name)) files
7128 :test #'equal))))
7129 files))
7131 (defsubst org-entry-beginning-position ()
7132 "Return the beginning position of the current entry."
7133 (save-excursion (org-back-to-heading t) (point)))
7135 (defsubst org-entry-end-position ()
7136 "Return the end position of the current entry."
7137 (save-excursion (outline-next-heading) (point)))
7139 (defun org-cycle-hide-drawers (state &optional exceptions)
7140 "Re-hide all drawers after a visibility state change.
7141 STATE should be one of the symbols listed in the docstring of
7142 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7143 a list of strings specifying which drawers should not be hidden."
7144 (when (and (derived-mode-p 'org-mode)
7145 (not (memq state '(overview folded contents))))
7146 (save-excursion
7147 (let* ((globalp (eq state 'all))
7148 (beg (if globalp (point-min) (point)))
7149 (end (if globalp (point-max)
7150 (if (eq state 'children)
7151 (save-excursion (outline-next-heading) (point))
7152 (org-end-of-subtree t)))))
7153 (goto-char beg)
7154 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7155 (unless (member-ignore-case (match-string 1) exceptions)
7156 (let ((drawer (org-element-at-point)))
7157 (when (memq (org-element-type drawer) '(drawer property-drawer))
7158 (org-flag-drawer t drawer)
7159 ;; Make sure to skip drawer entirely or we might flag
7160 ;; it another time when matching its ending line with
7161 ;; `org-drawer-regexp'.
7162 (goto-char (org-element-property :end drawer))))))))))
7164 (defun org-flag-drawer (flag &optional element)
7165 "When FLAG is non-nil, hide the drawer we are at.
7166 Otherwise make it visible. When optional argument ELEMENT is
7167 a parsed drawer, as returned by `org-element-at-point', hide or
7168 show that drawer instead."
7169 (let ((drawer (or element
7170 (and (save-excursion
7171 (beginning-of-line)
7172 (looking-at-p org-drawer-regexp))
7173 (org-element-at-point)))))
7174 (when (memq (org-element-type drawer) '(drawer property-drawer))
7175 (let ((post (org-element-property :post-affiliated drawer)))
7176 (save-excursion
7177 (outline-flag-region
7178 (progn (goto-char post) (line-end-position))
7179 (progn (goto-char (org-element-property :end drawer))
7180 (skip-chars-backward " \r\t\n")
7181 (line-end-position))
7182 flag))
7183 ;; When the drawer is hidden away, make sure point lies in
7184 ;; a visible part of the buffer.
7185 (when (and flag (> (line-beginning-position) post))
7186 (goto-char post))))))
7188 (defun org-subtree-end-visible-p ()
7189 "Is the end of the current subtree visible?"
7190 (pos-visible-in-window-p
7191 (save-excursion (org-end-of-subtree t) (point))))
7193 (defun org-first-headline-recenter ()
7194 "Move cursor to the first headline and recenter the headline."
7195 (let ((window (get-buffer-window)))
7196 (when window
7197 (goto-char (point-min))
7198 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7199 (set-window-start window (line-beginning-position))))))
7201 ;;; Saving and restoring visibility
7203 (defun org-outline-overlay-data (&optional use-markers)
7204 "Return a list of the locations of all outline overlays.
7205 These are overlays with the `invisible' property value `outline'.
7206 The return value is a list of cons cells, with start and stop
7207 positions for each overlay.
7208 If USE-MARKERS is set, return the positions as markers."
7209 (let (beg end)
7210 (org-with-wide-buffer
7211 (delq nil
7212 (mapcar (lambda (o)
7213 (when (eq (overlay-get o 'invisible) 'outline)
7214 (setq beg (overlay-start o)
7215 end (overlay-end o))
7216 (and beg end (> end beg)
7217 (if use-markers
7218 (cons (copy-marker beg)
7219 (copy-marker end t))
7220 (cons beg end)))))
7221 (overlays-in (point-min) (point-max)))))))
7223 (defun org-set-outline-overlay-data (data)
7224 "Create visibility overlays for all positions in DATA.
7225 DATA should have been made by `org-outline-overlay-data'."
7226 (org-with-wide-buffer
7227 (outline-show-all)
7228 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7230 ;;; Folding of blocks
7232 (defvar-local org-hide-block-overlays nil
7233 "Overlays hiding blocks.")
7235 (defun org-block-map (function &optional start end)
7236 "Call FUNCTION at the head of all source blocks in the current buffer.
7237 Optional arguments START and END can be used to limit the range."
7238 (let ((start (or start (point-min)))
7239 (end (or end (point-max))))
7240 (save-excursion
7241 (goto-char start)
7242 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7243 (save-excursion
7244 (save-match-data
7245 (goto-char (match-beginning 0))
7246 (funcall function)))))))
7248 (defun org-hide-block-toggle-all ()
7249 "Toggle the visibility of all blocks in the current buffer."
7250 (org-block-map 'org-hide-block-toggle))
7252 (defun org-hide-block-all ()
7253 "Fold all blocks in the current buffer."
7254 (interactive)
7255 (org-show-block-all)
7256 (org-block-map 'org-hide-block-toggle-maybe))
7258 (defun org-show-block-all ()
7259 "Unfold all blocks in the current buffer."
7260 (interactive)
7261 (mapc #'delete-overlay org-hide-block-overlays)
7262 (setq org-hide-block-overlays nil))
7264 (defun org-hide-block-toggle-maybe ()
7265 "Toggle visibility of block at point.
7266 Unlike to `org-hide-block-toggle', this function does not throw
7267 an error. Return a non-nil value when toggling is successful."
7268 (interactive)
7269 (ignore-errors (org-hide-block-toggle)))
7271 (defun org-hide-block-toggle (&optional force)
7272 "Toggle the visibility of the current block.
7273 When optional argument FORCE is `off', make block visible. If it
7274 is non-nil, hide it unconditionally. Throw an error when not at
7275 a block. Return a non-nil value when toggling is successful."
7276 (interactive)
7277 (let ((element (org-element-at-point)))
7278 (unless (memq (org-element-type element)
7279 '(center-block comment-block dynamic-block example-block
7280 export-block quote-block special-block
7281 src-block verse-block))
7282 (user-error "Not at a block"))
7283 (let* ((start (save-excursion
7284 (goto-char (org-element-property :post-affiliated element))
7285 (line-end-position)))
7286 (end (save-excursion
7287 (goto-char (org-element-property :end element))
7288 (skip-chars-backward " \r\t\n")
7289 (line-end-position)))
7290 (overlays (overlays-at start)))
7291 (cond
7292 ;; Do nothing when not before or at the block opening line or
7293 ;; at the block closing line.
7294 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7295 ((and (not (eq force 'off))
7296 (not (memq t (mapcar
7297 (lambda (o)
7298 (eq (overlay-get o 'invisible) 'org-hide-block))
7299 overlays))))
7300 (let ((ov (make-overlay start end)))
7301 (overlay-put ov 'invisible 'org-hide-block)
7302 ;; Make the block accessible to `isearch'.
7303 (overlay-put
7304 ov 'isearch-open-invisible
7305 (lambda (ov)
7306 (when (memq ov org-hide-block-overlays)
7307 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7308 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7309 (delete-overlay ov))))
7310 (push ov org-hide-block-overlays)
7311 ;; When the block is hidden away, make sure point is left in
7312 ;; a visible part of the buffer.
7313 (when (> (line-beginning-position) start)
7314 (goto-char start)
7315 (beginning-of-line))
7316 ;; Signal successful toggling.
7318 ((or (not force) (eq force 'off))
7319 (dolist (ov overlays t)
7320 (when (memq ov org-hide-block-overlays)
7321 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7322 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7323 (delete-overlay ov))))))))
7325 ;; Remove overlays when changing major mode
7326 (add-hook 'org-mode-hook
7327 (lambda () (add-hook 'change-major-mode-hook
7328 'org-show-block-all 'append 'local)))
7330 ;;; Indirect buffer display of subtrees
7332 (defvar org-indirect-dedicated-frame nil
7333 "This is the frame being used for indirect tree display.")
7334 (defvar org-last-indirect-buffer nil)
7336 (defun org-tree-to-indirect-buffer (&optional arg)
7337 "Create indirect buffer and narrow it to current subtree.
7339 With a numerical prefix ARG, go up to this level and then take that tree.
7340 If ARG is negative, go up that many levels.
7342 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7343 indirect buffer previously made with this command, to avoid proliferation of
7344 indirect buffers. However, when you call the command with a \
7345 `\\[universal-argument]' prefix, or
7346 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7347 so that you can work with several indirect buffers at the same time. If
7348 `org-indirect-buffer-display' is `dedicated-frame', the \
7349 `\\[universal-argument]' prefix also
7350 requests that a new frame be made for the new buffer, so that the dedicated
7351 frame is not changed."
7352 (interactive "P")
7353 (let ((cbuf (current-buffer))
7354 (cwin (selected-window))
7355 (pos (point))
7356 beg end level heading ibuf)
7357 (save-excursion
7358 (org-back-to-heading t)
7359 (when (numberp arg)
7360 (setq level (org-outline-level))
7361 (when (< arg 0) (setq arg (+ level arg)))
7362 (while (> (setq level (org-outline-level)) arg)
7363 (org-up-heading-safe)))
7364 (setq beg (point)
7365 heading (org-get-heading 'no-tags))
7366 (org-end-of-subtree t t)
7367 (when (org-at-heading-p) (backward-char 1))
7368 (setq end (point)))
7369 (when (and (buffer-live-p org-last-indirect-buffer)
7370 (not (eq org-indirect-buffer-display 'new-frame))
7371 (not arg))
7372 (kill-buffer org-last-indirect-buffer))
7373 (setq ibuf (org-get-indirect-buffer cbuf heading)
7374 org-last-indirect-buffer ibuf)
7375 (cond
7376 ((or (eq org-indirect-buffer-display 'new-frame)
7377 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7378 (select-frame (make-frame))
7379 (delete-other-windows)
7380 (pop-to-buffer-same-window ibuf)
7381 (org-set-frame-title heading))
7382 ((eq org-indirect-buffer-display 'dedicated-frame)
7383 (raise-frame
7384 (select-frame (or (and org-indirect-dedicated-frame
7385 (frame-live-p org-indirect-dedicated-frame)
7386 org-indirect-dedicated-frame)
7387 (setq org-indirect-dedicated-frame (make-frame)))))
7388 (delete-other-windows)
7389 (pop-to-buffer-same-window ibuf)
7390 (org-set-frame-title (concat "Indirect: " heading)))
7391 ((eq org-indirect-buffer-display 'current-window)
7392 (pop-to-buffer-same-window ibuf))
7393 ((eq org-indirect-buffer-display 'other-window)
7394 (pop-to-buffer ibuf))
7395 (t (error "Invalid value")))
7396 (narrow-to-region beg end)
7397 (outline-show-all)
7398 (goto-char pos)
7399 (run-hook-with-args 'org-cycle-hook 'all)
7400 (and (window-live-p cwin) (select-window cwin))))
7402 (defun org-get-indirect-buffer (&optional buffer heading)
7403 (setq buffer (or buffer (current-buffer)))
7404 (let ((n 1) (base (buffer-name buffer)) bname)
7405 (while (buffer-live-p
7406 (get-buffer
7407 (setq bname
7408 (concat base "-"
7409 (if heading (concat heading "-" (number-to-string n))
7410 (number-to-string n))))))
7411 (setq n (1+ n)))
7412 (condition-case nil
7413 (make-indirect-buffer buffer bname 'clone)
7414 (error (make-indirect-buffer buffer bname)))))
7416 (defun org-set-frame-title (title)
7417 "Set the title of the current frame to the string TITLE."
7418 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7420 ;;;; Structure editing
7422 ;;; Inserting headlines
7424 (defun org--line-empty-p (n)
7425 "Is the Nth next line empty?
7427 Counts the current line as N = 1 and the previous line as N = 0;
7428 see `beginning-of-line'."
7429 (save-excursion
7430 (and (not (bobp))
7431 (or (beginning-of-line n) t)
7432 (save-match-data
7433 (looking-at "[ \t]*$")))))
7435 (defun org-previous-line-empty-p ()
7436 "Is the previous line a blank line?
7437 When NEXT is non-nil, check the next line instead."
7438 (org--line-empty-p 0))
7440 (defun org-next-line-empty-p ()
7441 "Is the previous line a blank line?
7442 When NEXT is non-nil, check the next line instead."
7443 (org--line-empty-p 2))
7445 (defun org--blank-before-heading-p (&optional parent)
7446 "Non-nil when an empty line should precede a new heading here.
7447 When optional argument PARENT is non-nil, consider parent
7448 headline instead of current one."
7449 (pcase (assq 'heading org-blank-before-new-entry)
7450 (`(heading . auto)
7451 (save-excursion
7452 (org-with-limited-levels
7453 (unless (and (org-before-first-heading-p)
7454 (not (outline-next-heading)))
7455 (org-back-to-heading t)
7456 (when parent (org-up-heading-safe))
7457 (cond ((not (bobp))
7458 (org-previous-line-empty-p))
7459 ((outline-next-heading)
7460 (org-previous-line-empty-p))
7461 ;; Ignore trailing spaces on last buffer line.
7462 ((progn (skip-chars-backward " \t") (bolp))
7463 (org-previous-line-empty-p))
7464 (t nil))))))
7465 (`(heading . ,value) value)
7466 (_ nil)))
7468 (defun org-insert-heading (&optional arg invisible-ok top)
7469 "Insert a new heading or an item with the same depth at point.
7471 If point is at the beginning of a heading, insert a new heading
7472 or a new headline above the current one. When at the beginning
7473 of a regular line of text, turn it into a heading.
7475 If point is in the middle of a line, split it and create a new
7476 headline with the text in the current line after point (see
7477 `org-M-RET-may-split-line' on how to modify this behavior). As
7478 a special case, on a headline, splitting can only happen on the
7479 title itself. E.g., this excludes breaking stars or tags.
7481 With a `\\[universal-argument]' prefix, set \
7482 `org-insert-heading-respect-content' to
7483 a non-nil value for the duration of the command. This forces the
7484 insertion of a heading after the current subtree, independently
7485 on the location of point.
7487 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7488 insert the heading at the end of the tree
7489 above the current heading. For example, if point is within a
7490 2nd-level heading, then it will insert a 2nd-level heading at
7491 the end of the 1st-level parent subtree.
7493 When INVISIBLE-OK is set, stop at invisible headlines when going
7494 back. This is important for non-interactive uses of the
7495 command.
7497 When optional argument TOP is non-nil, insert a level 1 heading,
7498 unconditionally."
7499 (interactive "P")
7500 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7501 (level (org-current-level))
7502 (stars (make-string (if (and level (not top)) level 1) ?*)))
7503 (cond
7504 ((or org-insert-heading-respect-content
7505 (member arg '((4) (16)))
7506 (and (not invisible-ok)
7507 (invisible-p (max (1- (point)) (point-min)))))
7508 ;; Position point at the location of insertion.
7509 (if (not level) ;before first headline
7510 (org-with-limited-levels (outline-next-heading))
7511 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7512 ;; is nil.
7513 (org-with-limited-levels (org-back-to-heading invisible-ok))
7514 (cond ((equal arg '(16))
7515 (org-up-heading-safe)
7516 (org-end-of-subtree t t))
7518 (org-end-of-subtree t t))))
7519 (unless (bolp) (insert "\n")) ;ensure final newline
7520 (unless (and blank? (org-previous-line-empty-p))
7521 (org-N-empty-lines-before-current (if blank? 1 0)))
7522 (insert stars " \n")
7523 (forward-char -1))
7524 ;; At a headline...
7525 ((org-at-heading-p)
7526 (cond ((bolp)
7527 (when blank? (save-excursion (insert "\n")))
7528 (save-excursion (insert stars " \n"))
7529 (unless (and blank? (org-previous-line-empty-p))
7530 (org-N-empty-lines-before-current (if blank? 1 0)))
7531 (end-of-line))
7532 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7533 (org-match-line org-complex-heading-regexp)
7534 (org-pos-in-match-range (point) 4))
7535 ;; Grab the text that should moved to the new headline.
7536 ;; Preserve tags.
7537 (let ((split (delete-and-extract-region (point) (match-end 4))))
7538 (if (looking-at "[ \t]*$") (replace-match "")
7539 (org-set-tags nil t))
7540 (end-of-line)
7541 (when blank? (insert "\n"))
7542 (insert "\n" stars " ")
7543 (when (org-string-nw-p split) (insert split))
7544 (when (eobp) (save-excursion (insert "\n")))))
7546 (end-of-line)
7547 (when blank? (insert "\n"))
7548 (insert "\n" stars " ")
7549 (when (eobp) (save-excursion (insert "\n"))))))
7550 ;; On regular text, turn line into a headline or split, if
7551 ;; appropriate.
7552 ((bolp)
7553 (insert stars " ")
7554 (unless (and blank? (org-previous-line-empty-p))
7555 (org-N-empty-lines-before-current (if blank? 1 0))))
7557 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7558 (end-of-line))
7559 (insert "\n" stars " ")
7560 (unless (and blank? (org-previous-line-empty-p))
7561 (org-N-empty-lines-before-current (if blank? 1 0))))))
7562 (run-hooks 'org-insert-heading-hook))
7564 (defun org-N-empty-lines-before-current (n)
7565 "Make the number of empty lines before current exactly N.
7566 So this will delete or add empty lines."
7567 (let ((column (current-column)))
7568 (beginning-of-line)
7569 (unless (bobp)
7570 (let ((start (save-excursion
7571 (skip-chars-backward " \r\t\n")
7572 (line-end-position))))
7573 (delete-region start (line-end-position 0))))
7574 (insert (make-string n ?\n))
7575 (move-to-column column)))
7577 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7578 "Return the heading of the current entry, without the stars.
7579 When NO-TAGS is non-nil, don't include tags.
7580 When NO-TODO is non-nil, don't include TODO keywords.
7581 When NO-PRIORITY is non-nil, don't include priority cookie.
7582 When NO-COMMENT is non-nil, don't include COMMENT string."
7583 (save-excursion
7584 (org-back-to-heading t)
7585 (let ((case-fold-search nil))
7586 (looking-at org-complex-heading-regexp)
7587 (let ((todo (and (not no-todo) (match-string 2)))
7588 (priority (and (not no-priority) (match-string 3)))
7589 (headline (pcase (match-string 4)
7590 (`nil "")
7591 ((and (guard no-comment) h)
7592 (replace-regexp-in-string
7593 (eval-when-compile
7594 (format "\\`%s[ \t]+" org-comment-string))
7595 "" h))
7596 (h h)))
7597 (tags (and (not no-tags) (match-string 5))))
7598 (mapconcat #'identity
7599 (delq nil (list todo priority headline tags))
7600 " ")))))
7602 (defvar orgstruct-mode) ; defined below
7604 (defun org-heading-components ()
7605 "Return the components of the current heading.
7606 This is a list with the following elements:
7607 - the level as an integer
7608 - the reduced level, different if `org-odd-levels-only' is set.
7609 - the TODO keyword, or nil
7610 - the priority character, like ?A, or nil if no priority is given
7611 - the headline text itself, or the tags string if no headline text
7612 - the tags string, or nil."
7613 (save-excursion
7614 (org-back-to-heading t)
7615 (when (let (case-fold-search)
7616 (looking-at
7617 (if orgstruct-mode
7618 org-heading-regexp
7619 org-complex-heading-regexp)))
7620 (if orgstruct-mode
7621 (list (length (match-string 1))
7622 (org-reduced-level (length (match-string 1)))
7625 (match-string 2)
7626 nil)
7627 (list (length (match-string 1))
7628 (org-reduced-level (length (match-string 1)))
7629 (match-string-no-properties 2)
7630 (and (match-end 3) (aref (match-string 3) 2))
7631 (match-string-no-properties 4)
7632 (match-string-no-properties 5))))))
7634 (defun org-get-entry ()
7635 "Get the entry text, after heading, entire subtree."
7636 (save-excursion
7637 (org-back-to-heading t)
7638 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7640 (defun org-edit-headline (&optional heading)
7641 "Edit the current headline.
7642 Set it to HEADING when provided."
7643 (interactive)
7644 (org-with-wide-buffer
7645 (org-back-to-heading t)
7646 (let ((case-fold-search nil))
7647 (when (looking-at org-complex-heading-regexp)
7648 (let* ((old (match-string-no-properties 4))
7649 (new (save-match-data
7650 (org-trim (or heading (read-string "Edit: " old))))))
7651 (unless (equal old new)
7652 (if old (replace-match new t t nil 4)
7653 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7654 (insert " " new))
7655 (org-set-tags nil t)
7656 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7658 (defun org-insert-heading-after-current ()
7659 "Insert a new heading with same level as current, after current subtree."
7660 (interactive)
7661 (org-back-to-heading)
7662 (org-insert-heading)
7663 (org-move-subtree-down)
7664 (end-of-line 1))
7666 (defun org-insert-heading-respect-content (&optional invisible-ok)
7667 "Insert heading with `org-insert-heading-respect-content' set to t."
7668 (interactive)
7669 (org-insert-heading '(4) invisible-ok))
7671 (defun org-insert-todo-heading-respect-content (&optional force-state)
7672 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7673 (interactive)
7674 (org-insert-todo-heading force-state '(4)))
7676 (defun org-insert-todo-heading (arg &optional force-heading)
7677 "Insert a new heading with the same level and TODO state as current heading.
7679 If the heading has no TODO state, or if the state is DONE, use
7680 the first state (TODO by default). Also with one prefix arg,
7681 force first state. With two prefix args, force inserting at the
7682 end of the parent subtree.
7684 When called at a plain list item, insert a new item with an
7685 unchecked check box."
7686 (interactive "P")
7687 (when (or force-heading (not (org-insert-item 'checkbox)))
7688 (org-insert-heading (or (and (equal arg '(16)) '(16))
7689 force-heading))
7690 (save-excursion
7691 (org-forward-heading-same-level -1)
7692 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7693 (let* ((new-mark-x
7694 (if (or (equal arg '(4))
7695 (not (match-beginning 2))
7696 (member (match-string 2) org-done-keywords))
7697 (car org-todo-keywords-1)
7698 (match-string 2)))
7699 (new-mark
7701 (run-hook-with-args-until-success
7702 'org-todo-get-default-hook new-mark-x nil)
7703 new-mark-x)))
7704 (beginning-of-line 1)
7705 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7706 (if org-treat-insert-todo-heading-as-state-change
7707 (org-todo new-mark)
7708 (insert new-mark " "))))
7709 (when org-provide-todo-statistics
7710 (org-update-parent-todo-statistics))))
7712 (defun org-insert-subheading (arg)
7713 "Insert a new subheading and demote it.
7714 Works for outline headings and for plain lists alike."
7715 (interactive "P")
7716 (org-insert-heading arg)
7717 (cond
7718 ((org-at-heading-p) (org-do-demote))
7719 ((org-at-item-p) (org-indent-item))))
7721 (defun org-insert-todo-subheading (arg)
7722 "Insert a new subheading with TODO keyword or checkbox and demote it.
7723 Works for outline headings and for plain lists alike."
7724 (interactive "P")
7725 (org-insert-todo-heading arg)
7726 (cond
7727 ((org-at-heading-p) (org-do-demote))
7728 ((org-at-item-p) (org-indent-item))))
7730 ;;; Promotion and Demotion
7732 (defvar org-after-demote-entry-hook nil
7733 "Hook run after an entry has been demoted.
7734 The cursor will be at the beginning of the entry.
7735 When a subtree is being demoted, the hook will be called for each node.")
7737 (defvar org-after-promote-entry-hook nil
7738 "Hook run after an entry has been promoted.
7739 The cursor will be at the beginning of the entry.
7740 When a subtree is being promoted, the hook will be called for each node.")
7742 (defun org-promote-subtree ()
7743 "Promote the entire subtree.
7744 See also `org-promote'."
7745 (interactive)
7746 (save-excursion
7747 (org-with-limited-levels (org-map-tree 'org-promote)))
7748 (org-fix-position-after-promote))
7750 (defun org-demote-subtree ()
7751 "Demote the entire subtree.
7752 See `org-demote' and `org-promote'."
7753 (interactive)
7754 (save-excursion
7755 (org-with-limited-levels (org-map-tree 'org-demote)))
7756 (org-fix-position-after-promote))
7758 (defun org-do-promote ()
7759 "Promote the current heading higher up the tree.
7760 If the region is active in `transient-mark-mode', promote all
7761 headings in the region."
7762 (interactive)
7763 (save-excursion
7764 (if (org-region-active-p)
7765 (org-map-region 'org-promote (region-beginning) (region-end))
7766 (org-promote)))
7767 (org-fix-position-after-promote))
7769 (defun org-do-demote ()
7770 "Demote the current heading lower down the tree.
7771 If the region is active in `transient-mark-mode', demote all
7772 headings in the region."
7773 (interactive)
7774 (save-excursion
7775 (if (org-region-active-p)
7776 (org-map-region 'org-demote (region-beginning) (region-end))
7777 (org-demote)))
7778 (org-fix-position-after-promote))
7780 (defun org-fix-position-after-promote ()
7781 "Fix cursor position and indentation after demoting/promoting."
7782 (let ((pos (point)))
7783 (when (save-excursion
7784 (beginning-of-line)
7785 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7786 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7787 (cond ((eobp) (insert " "))
7788 ((eolp) (insert " "))
7789 ((equal (char-after) ?\s) (forward-char 1))))))
7791 (defun org-current-level ()
7792 "Return the level of the current entry, or nil if before the first headline.
7793 The level is the number of stars at the beginning of the
7794 headline. Use `org-reduced-level' to remove the effect of
7795 `org-odd-levels'. Unlike to `org-outline-level', this function
7796 ignores inlinetasks."
7797 (let ((level (org-with-limited-levels (org-outline-level))))
7798 (and (> level 0) level)))
7800 (defun org-get-previous-line-level ()
7801 "Return the outline depth of the last headline before the current line.
7802 Returns 0 for the first headline in the buffer, and nil if before the
7803 first headline."
7804 (and (org-current-level)
7805 (or (and (/= (line-beginning-position) (point-min))
7806 (save-excursion (beginning-of-line 0) (org-current-level)))
7807 0)))
7809 (defun org-reduced-level (l)
7810 "Compute the effective level of a heading.
7811 This takes into account the setting of `org-odd-levels-only'."
7812 (cond
7813 ((zerop l) 0)
7814 (org-odd-levels-only (1+ (floor (/ l 2))))
7815 (t l)))
7817 (defun org-level-increment ()
7818 "Return the number of stars that will be added or removed at a
7819 time to headlines when structure editing, based on the value of
7820 `org-odd-levels-only'."
7821 (if org-odd-levels-only 2 1))
7823 (defun org-get-valid-level (level &optional change)
7824 "Rectify a level change under the influence of `org-odd-levels-only'.
7825 LEVEL is a current level, CHANGE is by how much the level should
7826 be modified. Even if CHANGE is nil, LEVEL may be returned
7827 modified because even level numbers will become the next higher
7828 odd number. Returns values greater than 0."
7829 (if org-odd-levels-only
7830 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7831 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7832 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7833 (max 1 (+ level (or change 0)))))
7835 (defun org-promote ()
7836 "Promote the current heading higher up the tree."
7837 (org-with-wide-buffer
7838 (org-back-to-heading t)
7839 (let* ((after-change-functions (remq 'flyspell-after-change-function
7840 after-change-functions))
7841 (level (save-match-data (funcall outline-level)))
7842 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7843 (diff (abs (- level (length up-head) -1))))
7844 (cond
7845 ((and (= level 1) org-allow-promoting-top-level-subtree)
7846 (replace-match "# " nil t))
7847 ((= level 1)
7848 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7849 (t (replace-match up-head nil t)))
7850 (unless (= level 1)
7851 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7852 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7853 (run-hooks 'org-after-promote-entry-hook))))
7855 (defun org-demote ()
7856 "Demote the current heading lower down the tree."
7857 (org-with-wide-buffer
7858 (org-back-to-heading t)
7859 (let* ((after-change-functions (remq 'flyspell-after-change-function
7860 after-change-functions))
7861 (level (save-match-data (funcall outline-level)))
7862 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7863 (diff (abs (- level (length down-head) -1))))
7864 (replace-match down-head nil t)
7865 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7866 (when org-adapt-indentation (org-fixup-indentation diff))
7867 (run-hooks 'org-after-demote-entry-hook))))
7869 (defun org-cycle-level ()
7870 "Cycle the level of an empty headline through possible states.
7871 This goes first to child, then to parent, level, then up the hierarchy.
7872 After top level, it switches back to sibling level."
7873 (interactive)
7874 (let ((org-adapt-indentation nil))
7875 (when (org-point-at-end-of-empty-headline)
7876 (setq this-command 'org-cycle-level) ; Only needed for caching
7877 (let ((cur-level (org-current-level))
7878 (prev-level (org-get-previous-line-level)))
7879 (cond
7880 ;; If first headline in file, promote to top-level.
7881 ((= prev-level 0)
7882 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7883 do (org-do-promote)))
7884 ;; If same level as prev, demote one.
7885 ((= prev-level cur-level)
7886 (org-do-demote))
7887 ;; If parent is top-level, promote to top level if not already.
7888 ((= prev-level 1)
7889 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7890 do (org-do-promote)))
7891 ;; If top-level, return to prev-level.
7892 ((= cur-level 1)
7893 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7894 do (org-do-demote)))
7895 ;; If less than prev-level, promote one.
7896 ((< cur-level prev-level)
7897 (org-do-promote))
7898 ;; If deeper than prev-level, promote until higher than
7899 ;; prev-level.
7900 ((> cur-level prev-level)
7901 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7902 do (org-do-promote))))
7903 t))))
7905 (defun org-map-tree (fun)
7906 "Call FUN for every heading underneath the current one."
7907 (org-back-to-heading t)
7908 (let ((level (funcall outline-level)))
7909 (save-excursion
7910 (funcall fun)
7911 (while (and (progn
7912 (outline-next-heading)
7913 (> (funcall outline-level) level))
7914 (not (eobp)))
7915 (funcall fun)))))
7917 (defun org-map-region (fun beg end)
7918 "Call FUN for every heading between BEG and END."
7919 (let ((org-ignore-region t))
7920 (save-excursion
7921 (setq end (copy-marker end))
7922 (goto-char beg)
7923 (when (and (re-search-forward org-outline-regexp-bol nil t)
7924 (< (point) end))
7925 (funcall fun))
7926 (while (and (progn
7927 (outline-next-heading)
7928 (< (point) end))
7929 (not (eobp)))
7930 (funcall fun)))))
7932 (defun org-fixup-indentation (diff)
7933 "Change the indentation in the current entry by DIFF.
7935 DIFF is an integer. Indentation is done according to the
7936 following rules:
7938 - Planning information and property drawers are always indented
7939 according to the new level of the headline;
7941 - Footnote definitions and their contents are ignored;
7943 - Inlinetasks' boundaries are not shifted;
7945 - Empty lines are ignored;
7947 - Other lines' indentation are shifted by DIFF columns, unless
7948 it would introduce a structural change in the document, in
7949 which case no shifting is done at all.
7951 Assume point is at a heading or an inlinetask beginning."
7952 (org-with-wide-buffer
7953 (narrow-to-region (line-beginning-position)
7954 (save-excursion
7955 (if (org-with-limited-levels (org-at-heading-p))
7956 (org-with-limited-levels (outline-next-heading))
7957 (org-inlinetask-goto-end))
7958 (point)))
7959 (forward-line)
7960 ;; Indent properly planning info and property drawer.
7961 (when (looking-at-p org-planning-line-re)
7962 (org-indent-line)
7963 (forward-line))
7964 (when (looking-at org-property-drawer-re)
7965 (goto-char (match-end 0))
7966 (forward-line)
7967 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7968 (catch 'no-shift
7969 (when (zerop diff) (throw 'no-shift nil))
7970 ;; If DIFF is negative, first check if a shift is possible at all
7971 ;; (e.g., it doesn't break structure). This can only happen if
7972 ;; some contents are not properly indented.
7973 (let ((case-fold-search t))
7974 (when (< diff 0)
7975 (let ((diff (- diff))
7976 (forbidden-re (concat org-outline-regexp
7977 "\\|"
7978 (substring org-footnote-definition-re 1))))
7979 (save-excursion
7980 (while (not (eobp))
7981 (cond
7982 ((looking-at-p "[ \t]*$") (forward-line))
7983 ((and (looking-at-p org-footnote-definition-re)
7984 (let ((e (org-element-at-point)))
7985 (and (eq (org-element-type e) 'footnote-definition)
7986 (goto-char (org-element-property :end e))))))
7987 ((looking-at-p org-outline-regexp) (forward-line))
7988 ;; Give up if shifting would move before column 0 or
7989 ;; if it would introduce a headline or a footnote
7990 ;; definition.
7992 (skip-chars-forward " \t")
7993 (let ((ind (current-column)))
7994 (when (or (< ind diff)
7995 (and (= ind diff) (looking-at-p forbidden-re)))
7996 (throw 'no-shift nil)))
7997 ;; Ignore contents of example blocks and source
7998 ;; blocks if their indentation is meant to be
7999 ;; preserved. Jump to block's closing line.
8000 (beginning-of-line)
8001 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8002 (let ((e (org-element-at-point)))
8003 (and (memq (org-element-type e)
8004 '(example-block src-block))
8005 (or org-src-preserve-indentation
8006 (org-element-property :preserve-indent e))
8007 (goto-char (org-element-property :end e))
8008 (progn (skip-chars-backward " \r\t\n")
8009 (beginning-of-line)
8010 t))))
8011 (forward-line))))))))
8012 ;; Shift lines but footnote definitions, inlinetasks boundaries
8013 ;; by DIFF. Also skip contents of source or example blocks
8014 ;; when indentation is meant to be preserved.
8015 (while (not (eobp))
8016 (cond
8017 ((and (looking-at-p org-footnote-definition-re)
8018 (let ((e (org-element-at-point)))
8019 (and (eq (org-element-type e) 'footnote-definition)
8020 (goto-char (org-element-property :end e))))))
8021 ((looking-at-p org-outline-regexp) (forward-line))
8022 ((looking-at-p "[ \t]*$") (forward-line))
8024 (indent-line-to (+ (org-get-indentation) diff))
8025 (beginning-of-line)
8026 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8027 (let ((e (org-element-at-point)))
8028 (and (memq (org-element-type e)
8029 '(example-block src-block))
8030 (or org-src-preserve-indentation
8031 (org-element-property :preserve-indent e))
8032 (goto-char (org-element-property :end e))
8033 (progn (skip-chars-backward " \r\t\n")
8034 (beginning-of-line)
8035 t))))
8036 (forward-line)))))))))
8038 (defun org-convert-to-odd-levels ()
8039 "Convert an Org file with all levels allowed to one with odd levels.
8040 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8041 level 5 etc."
8042 (interactive)
8043 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8044 (let ((outline-level 'org-outline-level)
8045 (org-odd-levels-only nil) n)
8046 (save-excursion
8047 (goto-char (point-min))
8048 (while (re-search-forward "^\\*\\*+ " nil t)
8049 (setq n (- (length (match-string 0)) 2))
8050 (while (>= (setq n (1- n)) 0)
8051 (org-demote))
8052 (end-of-line 1))))))
8054 (defun org-convert-to-oddeven-levels ()
8055 "Convert an Org file with only odd levels to one with odd/even levels.
8056 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8057 file contains a section with an even level, conversion would
8058 destroy the structure of the file. An error is signaled in this
8059 case."
8060 (interactive)
8061 (goto-char (point-min))
8062 ;; First check if there are no even levels
8063 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8064 (org-show-set-visibility 'canonical)
8065 (error "Not all levels are odd in this file. Conversion not possible"))
8066 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8067 (let ((outline-regexp org-outline-regexp)
8068 (outline-level 'org-outline-level)
8069 (org-odd-levels-only nil) n)
8070 (save-excursion
8071 (goto-char (point-min))
8072 (while (re-search-forward "^\\*\\*+ " nil t)
8073 (setq n (/ (1- (length (match-string 0))) 2))
8074 (while (>= (setq n (1- n)) 0)
8075 (org-promote))
8076 (end-of-line 1))))))
8078 (defun org-tr-level (n)
8079 "Make N odd if required."
8080 (if org-odd-levels-only (1+ (/ n 2)) n))
8082 ;;; Vertical tree motion, cutting and pasting of subtrees
8084 (defun org-move-subtree-up (&optional arg)
8085 "Move the current subtree up past ARG headlines of the same level."
8086 (interactive "p")
8087 (org-move-subtree-down (- (prefix-numeric-value arg))))
8089 (defun org-move-subtree-down (&optional arg)
8090 "Move the current subtree down past ARG headlines of the same level."
8091 (interactive "p")
8092 (setq arg (prefix-numeric-value arg))
8093 (org-preserve-local-variables
8094 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8095 'org-get-last-sibling))
8096 (ins-point (make-marker))
8097 (cnt (abs arg))
8098 (col (current-column))
8099 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8100 ;; Select the tree
8101 (org-back-to-heading)
8102 (setq beg0 (point))
8103 (save-excursion
8104 (setq ne-beg (org-back-over-empty-lines))
8105 (setq beg (point)))
8106 (save-match-data
8107 (save-excursion (outline-end-of-heading)
8108 (setq folded (org-invisible-p)))
8109 (progn (org-end-of-subtree nil t)
8110 (unless (eobp) (backward-char))))
8111 (outline-next-heading)
8112 (setq ne-end (org-back-over-empty-lines))
8113 (setq end (point))
8114 (goto-char beg0)
8115 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8116 ;; include less whitespace
8117 (save-excursion
8118 (goto-char beg)
8119 (forward-line (- ne-beg ne-end))
8120 (setq beg (point))))
8121 ;; Find insertion point, with error handling
8122 (while (> cnt 0)
8123 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8124 (progn (goto-char beg0)
8125 (user-error "Cannot move past superior level or buffer limit")))
8126 (setq cnt (1- cnt)))
8127 (when (> arg 0)
8128 ;; Moving forward - still need to move over subtree
8129 (org-end-of-subtree t t)
8130 (save-excursion
8131 (org-back-over-empty-lines)
8132 (unless (bolp) (insert "\n"))))
8133 (setq ne-ins (org-back-over-empty-lines))
8134 (move-marker ins-point (point))
8135 (setq txt (buffer-substring beg end))
8136 (org-save-markers-in-region beg end)
8137 (delete-region beg end)
8138 (org-remove-empty-overlays-at beg)
8139 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8140 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8141 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8142 (let ((bbb (point)))
8143 (insert-before-markers txt)
8144 (org-reinstall-markers-in-region bbb)
8145 (move-marker ins-point bbb))
8146 (or (bolp) (insert "\n"))
8147 (setq ins-end (point))
8148 (goto-char ins-point)
8149 (org-skip-whitespace)
8150 (when (and (< arg 0)
8151 (org-first-sibling-p)
8152 (> ne-ins ne-beg))
8153 ;; Move whitespace back to beginning.
8154 (save-excursion
8155 (goto-char ins-end)
8156 (let ((kill-whole-line t))
8157 (kill-line (- ne-ins ne-beg)) (point)))
8158 (insert (make-string (- ne-ins ne-beg) ?\n)))
8159 (move-marker ins-point nil)
8160 (if folded
8161 (outline-hide-subtree)
8162 (org-show-entry)
8163 (org-show-children)
8164 (org-cycle-hide-drawers 'children))
8165 (org-clean-visibility-after-subtree-move)
8166 ;; Move back to the initial column we were at.
8167 (move-to-column col))))
8169 (defvar org-subtree-clip ""
8170 "Clipboard for cut and paste of subtrees.
8171 This is actually only a copy of the kill, because we use the normal kill
8172 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8174 (defvar org-subtree-clip-folded nil
8175 "Was the last copied subtree folded?
8176 This is used to fold the tree back after pasting.")
8178 (defun org-cut-subtree (&optional n)
8179 "Cut the current subtree into the clipboard.
8180 With prefix arg N, cut this many sequential subtrees.
8181 This is a short-hand for marking the subtree and then cutting it."
8182 (interactive "p")
8183 (org-copy-subtree n 'cut))
8185 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8186 "Copy the current subtree it in the clipboard.
8187 With prefix arg N, copy this many sequential subtrees.
8188 This is a short-hand for marking the subtree and then copying it.
8189 If CUT is non-nil, actually cut the subtree.
8190 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8191 of some markers in the region, even if CUT is non-nil. This is
8192 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8193 (interactive "p")
8194 (org-preserve-local-variables
8195 (let (beg end folded (beg0 (point)))
8196 (if (called-interactively-p 'any)
8197 (org-back-to-heading nil) ; take what looks like a subtree
8198 (org-back-to-heading t)) ; take what is really there
8199 (setq beg (point))
8200 (skip-chars-forward " \t\r\n")
8201 (save-match-data
8202 (if nosubtrees
8203 (outline-next-heading)
8204 (save-excursion (outline-end-of-heading)
8205 (setq folded (org-invisible-p)))
8206 (ignore-errors (org-forward-heading-same-level (1- n) t))
8207 (org-end-of-subtree t t)))
8208 ;; Include the end of an inlinetask
8209 (when (and (featurep 'org-inlinetask)
8210 (looking-at-p (concat (org-inlinetask-outline-regexp)
8211 "END[ \t]*$")))
8212 (end-of-line))
8213 (setq end (point))
8214 (goto-char beg0)
8215 (when (> end beg)
8216 (setq org-subtree-clip-folded folded)
8217 (when (or cut force-store-markers)
8218 (org-save-markers-in-region beg end))
8219 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8220 (setq org-subtree-clip (current-kill 0))
8221 (message "%s: Subtree(s) with %d characters"
8222 (if cut "Cut" "Copied")
8223 (length org-subtree-clip))))))
8225 (defun org-paste-subtree (&optional level tree for-yank remove)
8226 "Paste the clipboard as a subtree, with modification of headline level.
8227 The entire subtree is promoted or demoted in order to match a new headline
8228 level.
8230 If the cursor is at the beginning of a headline, the same level as
8231 that headline is used to paste the tree.
8233 If not, the new level is derived from the *visible* headings
8234 before and after the insertion point, and taken to be the inferior headline
8235 level of the two. So if the previous visible heading is level 3 and the
8236 next is level 4 (or vice versa), level 4 will be used for insertion.
8237 This makes sure that the subtree remains an independent subtree and does
8238 not swallow low level entries.
8240 You can also force a different level, either by using a numeric prefix
8241 argument, or by inserting the heading marker by hand. For example, if the
8242 cursor is after \"*****\", then the tree will be shifted to level 5.
8244 If optional TREE is given, use this text instead of the kill ring.
8246 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8247 move back over whitespace before inserting, and move point to the end of
8248 the inserted text when done.
8250 When REMOVE is non-nil, remove the subtree from the clipboard."
8251 (interactive "P")
8252 (setq tree (or tree (and kill-ring (current-kill 0))))
8253 (unless (org-kill-is-subtree-p tree)
8254 (user-error "%s"
8255 (substitute-command-keys
8256 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8257 (org-with-limited-levels
8258 (let* ((visp (not (org-invisible-p)))
8259 (txt tree)
8260 (^re_ "\\(\\*+\\)[ \t]*")
8261 (old-level (if (string-match org-outline-regexp-bol txt)
8262 (- (match-end 0) (match-beginning 0) 1)
8263 -1))
8264 (force-level (cond (level (prefix-numeric-value level))
8265 ((and (looking-at "[ \t]*$")
8266 (string-match
8267 "^\\*+$" (buffer-substring
8268 (point-at-bol) (point))))
8269 (- (match-end 0) (match-beginning 0)))
8270 ((and (bolp)
8271 (looking-at org-outline-regexp))
8272 (- (match-end 0) (point) 1))))
8273 (previous-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (outline-previous-visible-heading 1)
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (next-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (or (looking-at org-outline-regexp)
8285 (outline-next-visible-heading 1))
8286 (if (looking-at ^re_)
8287 (- (match-end 0) (match-beginning 0) 1)
8289 (error 1))))
8290 (new-level (or force-level (max previous-level next-level)))
8291 (shift (if (or (= old-level -1)
8292 (= new-level -1)
8293 (= old-level new-level))
8295 (- new-level old-level)))
8296 (delta (if (> shift 0) -1 1))
8297 (func (if (> shift 0) 'org-demote 'org-promote))
8298 (org-odd-levels-only nil)
8299 beg end newend)
8300 ;; Remove the forced level indicator
8301 (when force-level
8302 (delete-region (point-at-bol) (point)))
8303 ;; Paste
8304 (beginning-of-line (if (bolp) 1 2))
8305 (setq beg (point))
8306 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8307 (insert-before-markers txt)
8308 (unless (string-suffix-p "\n" txt) (insert "\n"))
8309 (setq newend (point))
8310 (org-reinstall-markers-in-region beg)
8311 (setq end (point))
8312 (goto-char beg)
8313 (skip-chars-forward " \t\n\r")
8314 (setq beg (point))
8315 (when (and (org-invisible-p) visp)
8316 (save-excursion (outline-show-heading)))
8317 ;; Shift if necessary
8318 (unless (= shift 0)
8319 (save-restriction
8320 (narrow-to-region beg end)
8321 (while (not (= shift 0))
8322 (org-map-region func (point-min) (point-max))
8323 (setq shift (+ delta shift)))
8324 (goto-char (point-min))
8325 (setq newend (point-max))))
8326 (when (or (called-interactively-p 'interactive) for-yank)
8327 (message "Clipboard pasted as level %d subtree" new-level))
8328 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8329 kill-ring
8330 (eq org-subtree-clip (current-kill 0))
8331 org-subtree-clip-folded)
8332 ;; The tree was folded before it was killed/copied
8333 (outline-hide-subtree))
8334 (and for-yank (goto-char newend))
8335 (and remove (setq kill-ring (cdr kill-ring))))))
8337 (defun org-kill-is-subtree-p (&optional txt)
8338 "Check if the current kill is an outline subtree, or a set of trees.
8339 Returns nil if kill does not start with a headline, or if the first
8340 headline level is not the largest headline level in the tree.
8341 So this will actually accept several entries of equal levels as well,
8342 which is OK for `org-paste-subtree'.
8343 If optional TXT is given, check this string instead of the current kill."
8344 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8345 (re (org-get-limited-outline-regexp))
8346 (^re (concat "^" re))
8347 (start-level (and kill
8348 (string-match
8349 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8350 kill)
8351 (- (match-end 2) (match-beginning 2) 1)))
8352 (start (1+ (or (match-beginning 2) -1))))
8353 (if (not start-level)
8354 (progn
8355 nil) ;; does not even start with a heading
8356 (catch 'exit
8357 (while (setq start (string-match ^re kill (1+ start)))
8358 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8359 (throw 'exit nil)))
8360 t))))
8362 (defvar org-markers-to-move nil
8363 "Markers that should be moved with a cut-and-paste operation.
8364 Those markers are stored together with their positions relative to
8365 the start of the region.")
8367 (defun org-save-markers-in-region (beg end)
8368 "Check markers in region.
8369 If these markers are between BEG and END, record their position relative
8370 to BEG, so that after moving the block of text, we can put the markers back
8371 into place.
8372 This function gets called just before an entry or tree gets cut from the
8373 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8374 called immediately, to move the markers with the entries."
8375 (setq org-markers-to-move nil)
8376 (when (featurep 'org-clock)
8377 (org-clock-save-markers-for-cut-and-paste beg end))
8378 (when (featurep 'org-agenda)
8379 (org-agenda-save-markers-for-cut-and-paste beg end)))
8381 (defun org-check-and-save-marker (marker beg end)
8382 "Check if MARKER is between BEG and END.
8383 If yes, remember the marker and the distance to BEG."
8384 (when (and (marker-buffer marker)
8385 (equal (marker-buffer marker) (current-buffer))
8386 (>= marker beg) (< marker end))
8387 (push (cons marker (- marker beg)) org-markers-to-move)))
8389 (defun org-reinstall-markers-in-region (beg)
8390 "Move all remembered markers to their position relative to BEG."
8391 (dolist (x org-markers-to-move)
8392 (move-marker (car x) (+ beg (cdr x))))
8393 (setq org-markers-to-move nil))
8395 (defun org-narrow-to-subtree ()
8396 "Narrow buffer to the current subtree."
8397 (interactive)
8398 (save-excursion
8399 (save-match-data
8400 (org-with-limited-levels
8401 (narrow-to-region
8402 (progn (org-back-to-heading t) (point))
8403 (progn (org-end-of-subtree t t)
8404 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8405 (point)))))))
8407 (defun org-narrow-to-block ()
8408 "Narrow buffer to the current block."
8409 (interactive)
8410 (let* ((case-fold-search t)
8411 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8412 "^[ \t]*#\\+end_.*")))
8413 (if blockp
8414 (narrow-to-region (car blockp) (cdr blockp))
8415 (user-error "Not in a block"))))
8417 (defun org-clone-subtree-with-time-shift (n &optional shift)
8418 "Clone the task (subtree) at point N times.
8419 The clones will be inserted as siblings.
8421 In interactive use, the user will be prompted for the number of
8422 clones to be produced. If the entry has a timestamp, the user
8423 will also be prompted for a time shift, which may be a repeater
8424 as used in time stamps, for example `+3d'. To disable this,
8425 you can call the function with a universal prefix argument.
8427 When a valid repeater is given and the entry contains any time
8428 stamps, the clones will become a sequence in time, with time
8429 stamps in the subtree shifted for each clone produced. If SHIFT
8430 is nil or the empty string, time stamps will be left alone. The
8431 ID property of the original subtree is removed.
8433 In each clone, all the CLOCK entries will be removed. This
8434 prevents Org from considering that the clocked times overlap.
8436 If the original subtree did contain time stamps with a repeater,
8437 the following will happen:
8438 - the repeater will be removed in each clone
8439 - an additional clone will be produced, with the current, unshifted
8440 date(s) in the entry.
8441 - the original entry will be placed *after* all the clones, with
8442 repeater intact.
8443 - the start days in the repeater in the original entry will be shifted
8444 to past the last clone.
8445 In this way you can spell out a number of instances of a repeating task,
8446 and still retain the repeater to cover future instances of the task.
8448 As described above, N+1 clones are produced when the original
8449 subtree has a repeater. Setting N to 0, then, can be used to
8450 remove the repeater from a subtree and create a shifted clone
8451 with the original repeater."
8452 (interactive "nNumber of clones to produce: ")
8453 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8454 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8455 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8456 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8457 (shift
8458 (or shift
8459 (if (and (not (equal current-prefix-arg '(4)))
8460 (save-excursion
8461 (goto-char beg)
8462 (re-search-forward org-ts-regexp-both end-of-tree t)))
8463 (read-from-minibuffer
8464 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8465 ""))) ;No time shift
8466 (doshift
8467 (and (org-string-nw-p shift)
8468 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8469 shift)
8470 (user-error "Invalid shift specification %s" shift)))))
8471 (goto-char end-of-tree)
8472 (unless (bolp) (insert "\n"))
8473 (let* ((end (point))
8474 (template (buffer-substring beg end))
8475 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8476 (shift-what (pcase (and doshift (match-string 2 shift))
8477 (`nil nil)
8478 ("d" 'day)
8479 ("w" (setq shift-n (* 7 shift-n)) 'day)
8480 ("m" 'month)
8481 ("y" 'year)
8482 (_ (error "Unsupported time unit"))))
8483 (nmin 1)
8484 (nmax n)
8485 (n-no-remove -1)
8486 (idprop (org-entry-get nil "ID")))
8487 (when (and doshift
8488 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8489 template))
8490 (delete-region beg end)
8491 (setq end beg)
8492 (setq nmin 0)
8493 (setq nmax (1+ nmax))
8494 (setq n-no-remove nmax))
8495 (goto-char end)
8496 (cl-loop for n from nmin to nmax do
8497 (insert
8498 ;; Prepare clone.
8499 (with-temp-buffer
8500 (insert template)
8501 (org-mode)
8502 (goto-char (point-min))
8503 (org-show-subtree)
8504 (and idprop (if org-clone-delete-id
8505 (org-entry-delete nil "ID")
8506 (org-id-get-create t)))
8507 (unless (= n 0)
8508 (while (re-search-forward org-clock-line-re nil t)
8509 (delete-region (line-beginning-position)
8510 (line-beginning-position 2)))
8511 (goto-char (point-min))
8512 (while (re-search-forward org-drawer-regexp nil t)
8513 (org-remove-empty-drawer-at (point))))
8514 (goto-char (point-min))
8515 (when doshift
8516 (while (re-search-forward org-ts-regexp-both nil t)
8517 (org-timestamp-change (* n shift-n) shift-what))
8518 (unless (= n n-no-remove)
8519 (goto-char (point-min))
8520 (while (re-search-forward org-ts-regexp nil t)
8521 (save-excursion
8522 (goto-char (match-beginning 0))
8523 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8524 (delete-region (match-beginning 1) (match-end 1)))))))
8525 (buffer-string)))))
8526 (goto-char beg)))
8528 ;;; Outline Sorting
8530 (defun org-sort (&optional with-case)
8531 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8532 Optional argument WITH-CASE means sort case-sensitively."
8533 (interactive "P")
8534 (org-call-with-arg
8535 (cond ((org-at-table-p) #'org-table-sort-lines)
8536 ((org-at-item-p) #'org-sort-list)
8537 (t #'org-sort-entries))
8538 with-case))
8540 (defun org-sort-remove-invisible (s)
8541 "Remove invisible part of links and emphasis markers from string S."
8542 (remove-text-properties 0 (length s) org-rm-props s)
8543 (replace-regexp-in-string
8544 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8545 (replace-regexp-in-string
8546 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8547 (org-link-display-format s)
8548 t t) t t))
8550 (defvar org-priority-regexp) ; defined later in the file
8552 (defvar org-after-sorting-entries-or-items-hook nil
8553 "Hook that is run after a bunch of entries or items have been sorted.
8554 When children are sorted, the cursor is in the parent line when this
8555 hook gets called. When a region or a plain list is sorted, the cursor
8556 will be in the first entry of the sorted region/list.")
8558 (defun org-sort-entries
8559 (&optional with-case sorting-type getkey-func compare-func property
8560 interactive?)
8561 "Sort entries on a certain level of an outline tree.
8562 If there is an active region, the entries in the region are sorted.
8563 Else, if the cursor is before the first entry, sort the top-level items.
8564 Else, the children of the entry at point are sorted.
8566 Sorting can be alphabetically, numerically, by date/time as given by
8567 a time stamp, by a property, by priority order, or by a custom function.
8569 The command prompts for the sorting type unless it has been given to the
8570 function through the SORTING-TYPE argument, which needs to be a character,
8571 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8572 the precise meaning of each character:
8574 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8575 c By creation time, which is assumed to be the first inactive time stamp
8576 at the beginning of a line.
8577 d By deadline date/time.
8578 k By clocking time.
8579 n Numerically, by converting the beginning of the entry/item to a number.
8580 o By order of TODO keywords.
8581 p By priority according to the cookie.
8582 r By the value of a property.
8583 s By scheduled date/time.
8584 t By date/time, either the first active time stamp in the entry, or, if
8585 none exist, by the first inactive one.
8587 Capital letters will reverse the sort order.
8589 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8590 called with point at the beginning of the record. It must return a
8591 value that is compatible with COMPARE-FUNC, the function used to
8592 compare entries.
8594 Comparing entries ignores case by default. However, with an optional argument
8595 WITH-CASE, the sorting considers case as well.
8597 Sorting is done against the visible part of the headlines, it ignores hidden
8598 links.
8600 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8602 A non-nil value for INTERACTIVE? is used to signal that this
8603 function is being called interactively."
8604 (interactive (list current-prefix-arg nil nil nil nil t))
8605 (let ((case-func (if with-case 'identity 'downcase))
8606 start beg end stars re re2
8607 txt what tmp)
8608 ;; Find beginning and end of region to sort
8609 (cond
8610 ((org-region-active-p)
8611 ;; we will sort the region
8612 (setq end (region-end)
8613 what "region")
8614 (goto-char (region-beginning))
8615 (unless (org-at-heading-p) (outline-next-heading))
8616 (setq start (point)))
8617 ((or (org-at-heading-p)
8618 (ignore-errors (progn (org-back-to-heading) t)))
8619 ;; we will sort the children of the current headline
8620 (org-back-to-heading)
8621 (setq start (point)
8622 end (progn (org-end-of-subtree t t)
8623 (or (bolp) (insert "\n"))
8624 (when (>= (org-back-over-empty-lines) 1)
8625 (forward-line 1))
8626 (point))
8627 what "children")
8628 (goto-char start)
8629 (outline-show-subtree)
8630 (outline-next-heading))
8632 ;; we will sort the top-level entries in this file
8633 (goto-char (point-min))
8634 (or (org-at-heading-p) (outline-next-heading))
8635 (setq start (point))
8636 (goto-char (point-max))
8637 (beginning-of-line 1)
8638 (when (looking-at ".*?\\S-")
8639 ;; File ends in a non-white line
8640 (end-of-line 1)
8641 (insert "\n"))
8642 (setq end (point-max))
8643 (setq what "top-level")
8644 (goto-char start)
8645 (outline-show-all)))
8647 (setq beg (point))
8648 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8650 (looking-at "\\(\\*+\\)")
8651 (setq stars (match-string 1)
8652 re (concat "^" (regexp-quote stars) " +")
8653 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8654 txt (buffer-substring beg end))
8655 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8656 (when (and (not (equal stars "*")) (string-match re2 txt))
8657 (user-error "Region to sort contains a level above the first entry"))
8659 (unless sorting-type
8660 (message
8661 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8662 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8663 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8664 what)
8665 (setq sorting-type (read-char-exclusive)))
8667 (unless getkey-func
8668 (and (= (downcase sorting-type) ?f)
8669 (setq getkey-func
8670 (or (and interactive?
8671 (org-read-function
8672 "Function for extracting keys: "))
8673 (error "Missing key extractor")))))
8675 (and (= (downcase sorting-type) ?r)
8676 (not property)
8677 (setq property
8678 (completing-read "Property: "
8679 (mapcar #'list (org-buffer-property-keys t))
8680 nil t)))
8682 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8683 (message "Sorting entries...")
8685 (save-restriction
8686 (narrow-to-region start end)
8687 (let ((restore-clock?
8688 ;; The clock marker is lost when using `sort-subr'; mark
8689 ;; the clock with temporary `:org-clock-marker-backup'
8690 ;; text property.
8691 (when (and (eq (org-clock-is-active) (current-buffer))
8692 (<= start (marker-position org-clock-marker))
8693 (>= end (marker-position org-clock-marker)))
8694 (org-with-silent-modifications
8695 (put-text-property (1- org-clock-marker) org-clock-marker
8696 :org-clock-marker-backup t))
8698 (dcst (downcase sorting-type))
8699 (case-fold-search nil)
8700 (now (current-time)))
8701 (org-preserve-local-variables
8702 (sort-subr
8703 (/= dcst sorting-type)
8704 ;; This function moves to the beginning character of the
8705 ;; "record" to be sorted.
8706 (lambda nil
8707 (if (re-search-forward re nil t)
8708 (goto-char (match-beginning 0))
8709 (goto-char (point-max))))
8710 ;; This function moves to the last character of the "record" being
8711 ;; sorted.
8712 (lambda nil
8713 (save-match-data
8714 (condition-case nil
8715 (outline-forward-same-level 1)
8716 (error
8717 (goto-char (point-max))))))
8718 ;; This function returns the value that gets sorted against.
8719 (lambda ()
8720 (cond
8721 ((= dcst ?n)
8722 (if (looking-at org-complex-heading-regexp)
8723 (string-to-number
8724 (org-sort-remove-invisible (match-string 4)))
8725 nil))
8726 ((= dcst ?a)
8727 (if (looking-at org-complex-heading-regexp)
8728 (funcall case-func
8729 (org-sort-remove-invisible (match-string 4)))
8730 nil))
8731 ((= dcst ?k)
8732 (or (get-text-property (point) :org-clock-minutes) 0))
8733 ((= dcst ?t)
8734 (let ((end (save-excursion (outline-next-heading) (point))))
8735 (if (or (re-search-forward org-ts-regexp end t)
8736 (re-search-forward org-ts-regexp-both end t))
8737 (org-time-string-to-seconds (match-string 0))
8738 (float-time now))))
8739 ((= dcst ?c)
8740 (let ((end (save-excursion (outline-next-heading) (point))))
8741 (if (re-search-forward
8742 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8743 end t)
8744 (org-time-string-to-seconds (match-string 0))
8745 (float-time now))))
8746 ((= dcst ?s)
8747 (let ((end (save-excursion (outline-next-heading) (point))))
8748 (if (re-search-forward org-scheduled-time-regexp end t)
8749 (org-time-string-to-seconds (match-string 1))
8750 (float-time now))))
8751 ((= dcst ?d)
8752 (let ((end (save-excursion (outline-next-heading) (point))))
8753 (if (re-search-forward org-deadline-time-regexp end t)
8754 (org-time-string-to-seconds (match-string 1))
8755 (float-time now))))
8756 ((= dcst ?p)
8757 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8758 (string-to-char (match-string 2))
8759 org-default-priority))
8760 ((= dcst ?r)
8761 (or (org-entry-get nil property) ""))
8762 ((= dcst ?o)
8763 (when (looking-at org-complex-heading-regexp)
8764 (let* ((m (match-string 2))
8765 (s (if (member m org-done-keywords) '- '+)))
8766 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8767 ((= dcst ?f)
8768 (if getkey-func
8769 (progn
8770 (setq tmp (funcall getkey-func))
8771 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8772 tmp)
8773 (error "Invalid key function `%s'" getkey-func)))
8774 (t (error "Invalid sorting type `%c'" sorting-type))))
8776 (cond
8777 ((= dcst ?a) 'string<)
8778 ((= dcst ?f)
8779 (or compare-func
8780 (and interactive?
8781 (org-read-function
8782 (concat "Function for comparing keys "
8783 "(empty for default `sort-subr' predicate): ")
8784 'allow-empty))))
8785 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8786 (when restore-clock?
8787 (move-marker org-clock-marker
8788 (1+ (next-single-property-change
8789 start :org-clock-marker-backup)))
8790 (remove-text-properties (1- org-clock-marker) org-clock-marker
8791 '(:org-clock-marker-backup t)))))
8792 (run-hooks 'org-after-sorting-entries-or-items-hook)
8793 (message "Sorting entries...done")))
8795 ;;; The orgstruct minor mode
8797 ;; Define a minor mode which can be used in other modes in order to
8798 ;; integrate the Org mode structure editing commands.
8800 ;; This is really a hack, because the Org mode structure commands use
8801 ;; keys which normally belong to the major mode. Here is how it
8802 ;; works: The minor mode defines all the keys necessary to operate the
8803 ;; structure commands, but wraps the commands into a function which
8804 ;; tests if the cursor is currently at a headline or a plain list
8805 ;; item. If that is the case, the structure command is used,
8806 ;; temporarily setting many Org mode variables like regular
8807 ;; expressions for filling etc. However, when any of those keys is
8808 ;; used at a different location, function uses `key-binding' to look
8809 ;; up if the key has an associated command in another currently active
8810 ;; keymap (minor modes, major mode, global), and executes that
8811 ;; command. There might be problems if any of the keys is otherwise
8812 ;; used as a prefix key.
8814 (defcustom orgstruct-heading-prefix-regexp ""
8815 "Regexp that matches the custom prefix of Org headlines in
8816 orgstruct(++)-mode."
8817 :group 'org
8818 :version "26.1"
8819 :package-version '(Org . "8.3")
8820 :type 'regexp)
8821 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8823 (defcustom orgstruct-setup-hook nil
8824 "Hook run after orgstruct-mode-map is filled."
8825 :group 'org
8826 :version "24.4"
8827 :package-version '(Org . "8.0")
8828 :type 'hook)
8830 (defvar orgstruct-initialized nil)
8832 (defvar org-local-vars nil
8833 "List of local variables, for use by `orgstruct-mode'.")
8835 ;;;###autoload
8836 (define-minor-mode orgstruct-mode
8837 "Toggle the minor mode `orgstruct-mode'.
8838 This mode is for using Org mode structure commands in other
8839 modes. The following keys behave as if Org mode were active, if
8840 the cursor is on a headline, or on a plain list item (both as
8841 defined by Org mode)."
8842 nil " OrgStruct" (make-sparse-keymap)
8843 (funcall (if orgstruct-mode
8844 'add-to-invisibility-spec
8845 'remove-from-invisibility-spec)
8846 '(outline . t))
8847 (when orgstruct-mode
8848 (org-load-modules-maybe)
8849 (unless orgstruct-initialized
8850 (orgstruct-setup)
8851 (setq orgstruct-initialized t))))
8853 ;;;###autoload
8854 (defun turn-on-orgstruct ()
8855 "Unconditionally turn on `orgstruct-mode'."
8856 (orgstruct-mode 1))
8858 (defvar-local orgstruct-is-++ nil
8859 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8860 (defvar-local org-fb-vars nil)
8861 (defun orgstruct++-mode (&optional arg)
8862 "Toggle `orgstruct-mode', the enhanced version of it.
8863 In addition to setting orgstruct-mode, this also exports all
8864 indentation and autofilling variables from Org mode into the
8865 buffer. It will also recognize item context in multiline items."
8866 (interactive "P")
8867 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8868 (if (< arg 1)
8869 (progn (orgstruct-mode -1)
8870 (dolist (v org-fb-vars)
8871 (set (make-local-variable (car v))
8872 (if (eq (car-safe (cadr v)) 'quote)
8873 (cl-cadadr v)
8874 (nth 1 v)))))
8875 (orgstruct-mode 1)
8876 (setq org-fb-vars nil)
8877 (unless org-local-vars
8878 (setq org-local-vars (org-get-local-variables)))
8879 (let (var val)
8880 (dolist (x org-local-vars)
8881 (when (string-match
8882 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8883 \\|fill-prefix\\|indent-\\)"
8884 (symbol-name (car x)))
8885 (setq var (car x) val (nth 1 x))
8886 (push (list var `(quote ,(eval var))) org-fb-vars)
8887 (set (make-local-variable var)
8888 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8889 (setq-local orgstruct-is-++ t))))
8891 ;;;###autoload
8892 (defun turn-on-orgstruct++ ()
8893 "Unconditionally turn on `orgstruct++-mode'."
8894 (orgstruct++-mode 1))
8896 (defun orgstruct-error ()
8897 "Error when there is no default binding for a structure key."
8898 (interactive)
8899 (funcall (if (fboundp 'user-error)
8900 'user-error
8901 'error)
8902 "This key has no function outside structure elements"))
8904 (defun orgstruct-setup ()
8905 "Setup orgstruct keymap."
8906 (dolist (cell '((org-demote . t)
8907 (org-metaleft . t)
8908 (org-metaright . t)
8909 (org-promote . t)
8910 (org-shiftmetaleft . t)
8911 (org-shiftmetaright . t)
8912 org-backward-element
8913 org-backward-heading-same-level
8914 org-ctrl-c-ret
8915 org-ctrl-c-minus
8916 org-ctrl-c-star
8917 org-cycle
8918 org-force-cycle-archived
8919 org-forward-heading-same-level
8920 org-insert-heading
8921 org-insert-heading-respect-content
8922 org-kill-note-or-show-branches
8923 org-mark-subtree
8924 org-meta-return
8925 org-metadown
8926 org-metaup
8927 org-narrow-to-subtree
8928 org-promote-subtree
8929 org-reveal
8930 org-shiftdown
8931 org-shiftleft
8932 org-shiftmetadown
8933 org-shiftmetaup
8934 org-shiftright
8935 org-shifttab
8936 org-shifttab
8937 org-shiftup
8938 org-show-children
8939 org-show-subtree
8940 org-sort
8941 org-up-element
8942 outline-demote
8943 outline-next-visible-heading
8944 outline-previous-visible-heading
8945 outline-promote
8946 outline-up-heading))
8947 (let ((f (or (car-safe cell) cell))
8948 (disable-when-heading-prefix (cdr-safe cell)))
8949 (when (fboundp f)
8950 (let ((new-bindings))
8951 (dolist (binding (nconc (where-is-internal f org-mode-map)
8952 (where-is-internal f outline-mode-map)))
8953 (push binding new-bindings)
8954 ;; TODO use local-function-key-map
8955 (dolist (rep '(("<tab>" . "TAB")
8956 ("<return>" . "RET")
8957 ("<escape>" . "ESC")
8958 ("<delete>" . "DEL")))
8959 (setq binding (read-kbd-macro
8960 (let ((case-fold-search))
8961 (replace-regexp-in-string
8962 (regexp-quote (cdr rep))
8963 (car rep)
8964 (key-description binding)))))
8965 (cl-pushnew binding new-bindings :test 'equal)))
8966 (dolist (binding new-bindings)
8967 (let ((key (lookup-key orgstruct-mode-map binding)))
8968 (when (or (not key) (numberp key))
8969 (ignore-errors
8970 (org-defkey orgstruct-mode-map
8971 binding
8972 (orgstruct-make-binding
8973 f binding disable-when-heading-prefix))))))))))
8974 (run-hooks 'orgstruct-setup-hook))
8976 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8977 "Create a function for binding in the structure minor mode.
8978 FUN is the command to call inside a table. KEY is the key that
8979 should be checked in for a command to execute outside of tables.
8980 Non-nil `disable-when-heading-prefix' means to disable the command
8981 if `orgstruct-heading-prefix-regexp' is not empty."
8982 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8983 (let ((nname name)
8984 (i 0))
8985 (while (fboundp (intern nname))
8986 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8987 (setq name (intern nname)))
8988 (eval
8989 (let ((bindings '((org-heading-regexp
8990 (concat "^"
8991 orgstruct-heading-prefix-regexp
8992 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8993 (org-outline-regexp
8994 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8995 (org-outline-regexp-bol
8996 (concat "^" org-outline-regexp))
8997 (outline-regexp org-outline-regexp)
8998 (outline-heading-end-regexp "\n")
8999 (outline-level 'org-outline-level)
9000 (outline-heading-alist))))
9001 `(defun ,name (arg)
9002 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9003 "Outside of structure, run the binding of `"
9004 (key-description key) "'."
9005 (when disable-when-heading-prefix
9006 (concat
9007 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9008 "back to the default binding due to limitations of Org's implementation of\n"
9009 "`" (symbol-name fun) "'.")))
9010 (interactive "p")
9011 (let* ((disable
9012 ,(and disable-when-heading-prefix
9013 '(not (string= orgstruct-heading-prefix-regexp ""))))
9014 (fallback
9015 (or disable
9016 (not
9017 (let* ,bindings
9018 (org-context-p 'headline 'item
9019 ,(when (memq fun
9020 '(org-insert-heading
9021 org-insert-heading-respect-content
9022 org-meta-return))
9023 '(when orgstruct-is-++
9024 'item-body))))))))
9025 (if fallback
9026 (let* ((orgstruct-mode)
9027 (binding
9028 (let ((key ,key))
9029 (catch 'exit
9030 (dolist
9031 (rep
9032 '(nil
9033 ("<\\([^>]*\\)tab>" . "\\1TAB")
9034 ("<\\([^>]*\\)return>" . "\\1RET")
9035 ("<\\([^>]*\\)escape>" . "\\1ESC")
9036 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9037 nil)
9038 (when rep
9039 (setq key (read-kbd-macro
9040 (let ((case-fold-search))
9041 (replace-regexp-in-string
9042 (car rep)
9043 (cdr rep)
9044 (key-description key))))))
9045 (when (key-binding key)
9046 (throw 'exit (key-binding key))))))))
9047 (if (keymapp binding)
9048 (org-set-transient-map binding)
9049 (let ((func (or binding
9050 (unless disable
9051 'orgstruct-error))))
9052 (when func
9053 (call-interactively func)))))
9054 (org-run-like-in-org-mode
9055 (lambda ()
9056 (interactive)
9057 (let* ,bindings
9058 (call-interactively ',fun)))))))))
9059 name))
9061 (defun org-contextualize-keys (alist contexts)
9062 "Return valid elements in ALIST depending on CONTEXTS.
9064 `org-agenda-custom-commands' or `org-capture-templates' are the
9065 values used for ALIST, and `org-agenda-custom-commands-contexts'
9066 or `org-capture-templates-contexts' are the associated contexts
9067 definitions."
9068 (let ((contexts
9069 ;; normalize contexts
9070 (mapcar
9071 (lambda(c) (cond ((listp (cadr c))
9072 (list (car c) (car c) (nth 1 c)))
9073 ((string= "" (cadr c))
9074 (list (car c) (car c) (nth 2 c)))
9075 (t c)))
9076 contexts))
9077 (a alist) r s)
9078 ;; loop over all commands or templates
9079 (dolist (c a)
9080 (let (vrules repl)
9081 (cond
9082 ((not (assoc (car c) contexts))
9083 (push c r))
9084 ((and (assoc (car c) contexts)
9085 (setq vrules (org-contextualize-validate-key
9086 (car c) contexts)))
9087 (mapc (lambda (vr)
9088 (unless (equal (car vr) (cadr vr))
9089 (setq repl vr)))
9090 vrules)
9091 (if (not repl) (push c r)
9092 (push (cadr repl) s)
9093 (push
9094 (cons (car c)
9095 (cdr (or (assoc (cadr repl) alist)
9096 (error "Undefined key `%s' as contextual replacement for `%s'"
9097 (cadr repl) (car c)))))
9098 r))))))
9099 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9100 (delq
9102 (delete-dups
9103 (mapcar (lambda (x)
9104 (let ((tpl (car x)))
9105 (unless (delq
9107 (mapcar (lambda (y)
9108 (equal y tpl))
9110 x)))
9111 (reverse r))))))
9113 (defun org-contextualize-validate-key (key contexts)
9114 "Check CONTEXTS for agenda or capture KEY."
9115 (let (res)
9116 (dolist (r contexts)
9117 (dolist (rr (car (last r)))
9118 (when
9119 (and (equal key (car r))
9120 (if (functionp rr) (funcall rr)
9121 (or (and (eq (car rr) 'in-file)
9122 (buffer-file-name)
9123 (string-match (cdr rr) (buffer-file-name)))
9124 (and (eq (car rr) 'in-mode)
9125 (string-match (cdr rr) (symbol-name major-mode)))
9126 (and (eq (car rr) 'in-buffer)
9127 (string-match (cdr rr) (buffer-name)))
9128 (when (and (eq (car rr) 'not-in-file)
9129 (buffer-file-name))
9130 (not (string-match (cdr rr) (buffer-file-name))))
9131 (when (eq (car rr) 'not-in-mode)
9132 (not (string-match (cdr rr) (symbol-name major-mode))))
9133 (when (eq (car rr) 'not-in-buffer)
9134 (not (string-match (cdr rr) (buffer-name)))))))
9135 (push r res))))
9136 (delete-dups (delq nil res))))
9138 (defun org-context-p (&rest contexts)
9139 "Check if local context is any of CONTEXTS.
9140 Possible values in the list of contexts are `table', `headline', and `item'."
9141 (let ((pos (point)))
9142 (goto-char (point-at-bol))
9143 (prog1 (or (and (memq 'table contexts)
9144 (looking-at "[ \t]*|"))
9145 (and (memq 'headline contexts)
9146 (looking-at org-outline-regexp))
9147 (and (memq 'item contexts)
9148 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9149 (and (memq 'item-body contexts)
9150 (org-in-item-p)))
9151 (goto-char pos))))
9153 ;;;###autoload
9154 (defun org-run-like-in-org-mode (cmd)
9155 "Run a command, pretending that the current buffer is in Org mode.
9156 This will temporarily bind local variables that are typically bound in
9157 Org mode to the values they have in Org mode, and then interactively
9158 call CMD."
9159 (org-load-modules-maybe)
9160 (unless org-local-vars
9161 (setq org-local-vars (org-get-local-variables)))
9162 (let (binds)
9163 (dolist (var org-local-vars)
9164 (when (or (not (boundp (car var)))
9165 (eq (symbol-value (car var))
9166 (default-value (car var))))
9167 (push (list (car var) `(quote ,(cadr var))) binds)))
9168 (eval `(let ,binds
9169 (call-interactively (quote ,cmd))))))
9171 (defun org-get-category (&optional pos force-refresh)
9172 "Get the category applying to position POS."
9173 (save-match-data
9174 (when force-refresh (org-refresh-category-properties))
9175 (let ((pos (or pos (point))))
9176 (or (get-text-property pos 'org-category)
9177 (progn (org-refresh-category-properties)
9178 (get-text-property pos 'org-category))))))
9180 ;;; Refresh properties
9182 (defun org-refresh-properties (dprop tprop)
9183 "Refresh buffer text properties.
9184 DPROP is the drawer property and TPROP is either the
9185 corresponding text property to set, or an alist with each element
9186 being a text property (as a symbol) and a function to apply to
9187 the value of the drawer property."
9188 (let* ((case-fold-search t)
9189 (inhibit-read-only t)
9190 (inherit? (org-property-inherit-p dprop))
9191 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9192 (global (and inherit? (org--property-global-value dprop nil))))
9193 (org-with-silent-modifications
9194 (org-with-point-at 1
9195 ;; Set global values (e.g., values defined through
9196 ;; "#+PROPERTY:" keywords) to the whole buffer.
9197 (when global (put-text-property (point-min) (point-max) tprop global))
9198 ;; Set local values.
9199 (while (re-search-forward property-re nil t)
9200 (when (org-at-property-p)
9201 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9202 (outline-next-heading))))))
9204 (defun org-refresh-property (tprop p &optional inherit)
9205 "Refresh the buffer text property TPROP from the drawer property P.
9206 The refresh happens only for the current headline, or the whole
9207 sub-tree if optional argument INHERIT is non-nil."
9208 (unless (org-before-first-heading-p)
9209 (save-excursion
9210 (org-back-to-heading t)
9211 (let ((start (point))
9212 (end (save-excursion
9213 (if inherit (org-end-of-subtree t t)
9214 (or (outline-next-heading) (point-max))))))
9215 (if (symbolp tprop)
9216 ;; TPROP is a text property symbol.
9217 (put-text-property start end tprop p)
9218 ;; TPROP is an alist with (property . function) elements.
9219 (pcase-dolist (`(,prop . ,f) tprop)
9220 (put-text-property start end prop (funcall f p))))))))
9222 (defun org-refresh-category-properties ()
9223 "Refresh category text properties in the buffer."
9224 (let ((case-fold-search t)
9225 (inhibit-read-only t)
9226 (default-category
9227 (cond ((null org-category)
9228 (if buffer-file-name
9229 (file-name-sans-extension
9230 (file-name-nondirectory buffer-file-name))
9231 "???"))
9232 ((symbolp org-category) (symbol-name org-category))
9233 (t org-category))))
9234 (org-with-silent-modifications
9235 (org-with-wide-buffer
9236 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9237 ;; This is the default category for the buffer. If none is
9238 ;; found, fall-back to `org-category' or buffer file name.
9239 (put-text-property
9240 (point-min) (point-max)
9241 'org-category
9242 (catch 'buffer-category
9243 (goto-char (point-max))
9244 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9245 (let ((element (org-element-at-point)))
9246 (when (eq (org-element-type element) 'keyword)
9247 (throw 'buffer-category
9248 (org-element-property :value element)))))
9249 default-category))
9250 ;; Set sub-tree specific categories.
9251 (goto-char (point-min))
9252 (let ((regexp (org-re-property "CATEGORY")))
9253 (while (re-search-forward regexp nil t)
9254 (let ((value (match-string-no-properties 3)))
9255 (when (org-at-property-p)
9256 (put-text-property
9257 (save-excursion (org-back-to-heading t) (point))
9258 (save-excursion (org-end-of-subtree t t) (point))
9259 'org-category
9260 value)))))))))
9262 (defun org-refresh-stats-properties ()
9263 "Refresh stats text properties in the buffer."
9264 (org-with-silent-modifications
9265 (org-with-point-at 1
9266 (let ((regexp (concat org-outline-regexp-bol
9267 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9268 (while (re-search-forward regexp nil t)
9269 (let* ((numerator (string-to-number (match-string 1)))
9270 (denominator (and (match-end 2)
9271 (string-to-number (match-string 2))))
9272 (stats (cond ((not denominator) numerator) ;percent
9273 ((= denominator 0) 0)
9274 (t (/ (* numerator 100) denominator)))))
9275 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9276 'org-stats stats)))))))
9278 (defun org-refresh-effort-properties ()
9279 "Refresh effort properties"
9280 (org-refresh-properties
9281 org-effort-property
9282 '((effort . identity)
9283 (effort-minutes . org-duration-to-minutes))))
9285 ;;;; Link Stuff
9287 ;;; Link abbreviations
9289 (defun org-link-expand-abbrev (link)
9290 "Apply replacements as defined in `org-link-abbrev-alist'."
9291 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9292 (let* ((key (match-string 1 link))
9293 (as (or (assoc key org-link-abbrev-alist-local)
9294 (assoc key org-link-abbrev-alist)))
9295 (tag (and (match-end 2) (match-string 3 link)))
9296 rpl)
9297 (if (not as)
9298 link
9299 (setq rpl (cdr as))
9300 (cond
9301 ((symbolp rpl) (funcall rpl tag))
9302 ((string-match "%(\\([^)]+\\))" rpl)
9303 (replace-match
9304 (save-match-data
9305 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9306 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9307 ((string-match "%h" rpl)
9308 (replace-match (url-hexify-string (or tag "")) t t rpl))
9309 (t (concat rpl tag)))))
9310 link))
9312 ;;; Storing and inserting links
9314 (defvar org-insert-link-history nil
9315 "Minibuffer history for links inserted with `org-insert-link'.")
9317 (defvar org-stored-links nil
9318 "Contains the links stored with `org-store-link'.")
9320 (defvar org-store-link-plist nil
9321 "Plist with info about the most recently link created with `org-store-link'.")
9323 (defun org-store-link-functions ()
9324 "Return a list of functions that are called to create and store a link.
9325 The functions defined in the :store property of
9326 `org-link-parameters'.
9328 Each function will be called in turn until one returns a non-nil
9329 value. Each function should check if it is responsible for
9330 creating this link (for example by looking at the major mode).
9331 If not, it must exit and return nil. If yes, it should return
9332 a non-nil value after calling `org-store-link-props' with a list
9333 of properties and values. Special properties are:
9335 :type The link prefix, like \"http\". This must be given.
9336 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9337 This is obligatory as well.
9338 :description Optional default description for the second pair
9339 of brackets in an Org mode link. The user can still change
9340 this when inserting this link into an Org mode buffer.
9342 In addition to these, any additional properties can be specified
9343 and then used in capture templates."
9344 (cl-loop for link in org-link-parameters
9345 with store-func
9346 do (setq store-func (org-link-get-parameter (car link) :store))
9347 if store-func
9348 collect store-func))
9350 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9351 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9353 ;;;###autoload
9354 (defun org-store-link (arg)
9355 "Store an org-link to the current location.
9356 \\<org-mode-map>
9357 This link is added to `org-stored-links' and can later be inserted
9358 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9360 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9361 A single
9362 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9363 `org-gnus-prefer-web-links' for links to Usenet articles.
9365 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9366 skipping storing functions that are not
9367 part of Org core.
9369 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9370 prefix ARG forces storing a link for each line in the
9371 active region."
9372 (interactive "P")
9373 (org-load-modules-maybe)
9374 (if (and (equal arg '(64)) (org-region-active-p))
9375 (save-excursion
9376 (let ((end (region-end)))
9377 (goto-char (region-beginning))
9378 (set-mark (point))
9379 (while (< (point-at-eol) end)
9380 (move-end-of-line 1) (activate-mark)
9381 (let (current-prefix-arg)
9382 (call-interactively 'org-store-link))
9383 (move-beginning-of-line 2)
9384 (set-mark (point)))))
9385 (setq org-store-link-plist nil)
9386 (let (link cpltxt desc description search txt custom-id agenda-link)
9387 (cond
9388 ;; Store a link using an external link type, if any function is
9389 ;; available. If more than one can generate a link from current
9390 ;; location, ask which one to use.
9391 ((and (not (equal arg '(16)))
9392 (let ((results-alist nil))
9393 (dolist (f (org-store-link-functions))
9394 (when (funcall f)
9395 ;; XXX: return value is not link's plist, so we
9396 ;; store the new value before it is modified. It
9397 ;; would be cleaner to ask store link functions to
9398 ;; return the plist instead.
9399 (push (cons f (copy-sequence org-store-link-plist))
9400 results-alist)))
9401 (pcase results-alist
9402 (`nil nil)
9403 (`((,_ . ,_)) t) ;single choice: nothing to do
9404 (`((,name . ,_) . ,_)
9405 ;; Reinstate link plist associated to the chosen
9406 ;; function.
9407 (apply #'org-store-link-props
9408 (cdr (assoc-string
9409 (completing-read
9410 "Which function for creating the link? "
9411 (mapcar #'car results-alist) nil t name)
9412 results-alist)))
9413 t))))
9414 (setq link (plist-get org-store-link-plist :link))
9415 (setq desc (or (plist-get org-store-link-plist :description)
9416 link)))
9418 ;; Store a link from a source code buffer.
9419 ((org-src-edit-buffer-p)
9420 (let ((coderef-format (org-src-coderef-format)))
9421 (cond ((save-excursion
9422 (beginning-of-line)
9423 (looking-at (org-src-coderef-regexp coderef-format)))
9424 (setq link (format "(%s)" (match-string-no-properties 3))))
9425 ((called-interactively-p 'any)
9426 (let ((label (read-string "Code line label: ")))
9427 (end-of-line)
9428 (setq link (format coderef-format label))
9429 (let ((gc (- 79 (length link))))
9430 (if (< (current-column) gc)
9431 (org-move-to-column gc t)
9432 (insert " ")))
9433 (insert link)
9434 (setq link (concat "(" label ")"))
9435 (setq desc nil)))
9436 (t (setq link nil)))))
9438 ;; We are in the agenda, link to referenced location
9439 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9440 (let ((m (or (get-text-property (point) 'org-hd-marker)
9441 (get-text-property (point) 'org-marker))))
9442 (when m
9443 (org-with-point-at m
9444 (setq agenda-link
9445 (if (called-interactively-p 'any)
9446 (call-interactively 'org-store-link)
9447 (org-store-link nil)))))))
9449 ((eq major-mode 'calendar-mode)
9450 (let ((cd (calendar-cursor-to-date)))
9451 (setq link
9452 (format-time-string
9453 (car org-time-stamp-formats)
9454 (apply 'encode-time
9455 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9456 nil nil nil))))
9457 (org-store-link-props :type "calendar" :date cd)))
9459 ((eq major-mode 'help-mode)
9460 (setq link (concat "help:" (save-excursion
9461 (goto-char (point-min))
9462 (looking-at "^[^ ]+")
9463 (match-string 0))))
9464 (org-store-link-props :type "help"))
9466 ((eq major-mode 'w3-mode)
9467 (setq cpltxt (if (and (buffer-name)
9468 (not (string-match "Untitled" (buffer-name))))
9469 (buffer-name)
9470 (url-view-url t))
9471 link (url-view-url t))
9472 (org-store-link-props :type "w3" :url (url-view-url t)))
9474 ((eq major-mode 'image-mode)
9475 (setq cpltxt (concat "file:"
9476 (abbreviate-file-name buffer-file-name))
9477 link cpltxt)
9478 (org-store-link-props :type "image" :file buffer-file-name))
9480 ;; In dired, store a link to the file of the current line
9481 ((derived-mode-p 'dired-mode)
9482 (let ((file (dired-get-filename nil t)))
9483 (setq file (if file
9484 (abbreviate-file-name
9485 (expand-file-name (dired-get-filename nil t)))
9486 ;; otherwise, no file so use current directory.
9487 default-directory))
9488 (setq cpltxt (concat "file:" file)
9489 link cpltxt)))
9491 ((setq search (run-hook-with-args-until-success
9492 'org-create-file-search-functions))
9493 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9494 "::" search))
9495 (setq cpltxt (or description link)))
9497 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9498 (org-with-limited-levels
9499 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9500 (cond
9501 ;; Store a link using the target at point
9502 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9503 (setq cpltxt
9504 (concat "file:"
9505 (abbreviate-file-name
9506 (buffer-file-name (buffer-base-buffer)))
9507 "::" (match-string 1))
9508 link cpltxt))
9509 ((and (featurep 'org-id)
9510 (or (eq org-id-link-to-org-use-id t)
9511 (and (called-interactively-p 'any)
9512 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9513 (and (eq org-id-link-to-org-use-id
9514 'create-if-interactive-and-no-custom-id)
9515 (not custom-id))))
9516 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9517 ;; Store a link using the ID at point
9518 (setq link (condition-case nil
9519 (prog1 (org-id-store-link)
9520 (setq desc (or (plist-get org-store-link-plist
9521 :description)
9522 "")))
9523 (error
9524 ;; Probably before first headline, link only to file
9525 (concat "file:"
9526 (abbreviate-file-name
9527 (buffer-file-name (buffer-base-buffer))))))))
9529 ;; Just link to current headline
9530 (setq cpltxt (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))))
9533 ;; Add a context search string
9534 (when (org-xor org-context-in-file-links
9535 (equal arg '(4)))
9536 (let* ((element (org-element-at-point))
9537 (name (org-element-property :name element)))
9538 (setq txt (cond
9539 ((org-at-heading-p) nil)
9540 (name)
9541 ((org-region-active-p)
9542 (buffer-substring (region-beginning) (region-end)))))
9543 (when (or (null txt) (string-match "\\S-" txt))
9544 (setq cpltxt
9545 (concat cpltxt "::"
9546 (condition-case nil
9547 (org-make-org-heading-search-string txt)
9548 (error "")))
9549 desc (or name
9550 (nth 4 (ignore-errors (org-heading-components)))
9551 "NONE")))))
9552 (when (string-match "::\\'" cpltxt)
9553 (setq cpltxt (substring cpltxt 0 -2)))
9554 (setq link cpltxt)))))
9556 ((buffer-file-name (buffer-base-buffer))
9557 ;; Just link to this file here.
9558 (setq cpltxt (concat "file:"
9559 (abbreviate-file-name
9560 (buffer-file-name (buffer-base-buffer)))))
9561 ;; Add a context string.
9562 (when (org-xor org-context-in-file-links
9563 (equal arg '(4)))
9564 (setq txt (if (org-region-active-p)
9565 (buffer-substring (region-beginning) (region-end))
9566 (buffer-substring (point-at-bol) (point-at-eol))))
9567 ;; Only use search option if there is some text.
9568 (when (string-match "\\S-" txt)
9569 (setq cpltxt
9570 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9571 desc "NONE")))
9572 (setq link cpltxt))
9574 ((called-interactively-p 'interactive)
9575 (user-error "No method for storing a link from this buffer"))
9577 (t (setq link nil)))
9579 ;; We're done setting link and desc, clean up
9580 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9581 (setq link (or link cpltxt)
9582 desc (or desc cpltxt))
9583 (cond ((not desc))
9584 ((equal desc "NONE") (setq desc nil))
9585 (t (setq desc
9586 (replace-regexp-in-string
9587 org-bracket-link-analytic-regexp
9588 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9589 desc))))
9590 ;; Return the link
9591 (if (not (and (or (called-interactively-p 'any)
9592 executing-kbd-macro)
9593 link))
9594 (or agenda-link (and link (org-make-link-string link desc)))
9595 (push (list link desc) org-stored-links)
9596 (message "Stored: %s" (or desc link))
9597 (when custom-id
9598 (setq link (concat "file:" (abbreviate-file-name
9599 (buffer-file-name)) "::#" custom-id))
9600 (push (list link desc) org-stored-links))
9601 (car org-stored-links)))))
9603 (defun org-store-link-props (&rest plist)
9604 "Store link properties.
9605 The properties are pre-processed by extracting names, addresses
9606 and dates."
9607 (let ((x (plist-get plist :from)))
9608 (when x
9609 (let ((adr (mail-extract-address-components x)))
9610 (setq plist (plist-put plist :fromname (car adr)))
9611 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9612 (let ((x (plist-get plist :to)))
9613 (when x
9614 (let ((adr (mail-extract-address-components x)))
9615 (setq plist (plist-put plist :toname (car adr)))
9616 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9617 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9618 (when x
9619 (setq plist (plist-put plist :date-timestamp
9620 (format-time-string
9621 (org-time-stamp-format t) x)))
9622 (setq plist (plist-put plist :date-timestamp-inactive
9623 (format-time-string
9624 (org-time-stamp-format t t) x)))))
9625 (let ((from (plist-get plist :from))
9626 (to (plist-get plist :to)))
9627 (when (and from to org-from-is-user-regexp)
9628 (setq plist
9629 (plist-put plist :fromto
9630 (if (string-match org-from-is-user-regexp from)
9631 (concat "to %t")
9632 (concat "from %f"))))))
9633 (setq org-store-link-plist plist))
9635 (defun org-add-link-props (&rest plist)
9636 "Add these properties to the link property list."
9637 (let (key value)
9638 (while plist
9639 (setq key (pop plist) value (pop plist))
9640 (setq org-store-link-plist
9641 (plist-put org-store-link-plist key value)))))
9643 (defun org-email-link-description (&optional fmt)
9644 "Return the description part of an email link.
9645 This takes information from `org-store-link-plist' and formats it
9646 according to FMT (default from `org-email-link-description-format')."
9647 (setq fmt (or fmt org-email-link-description-format))
9648 (let* ((p org-store-link-plist)
9649 (to (plist-get p :toaddress))
9650 (from (plist-get p :fromaddress))
9651 (table
9652 (list
9653 (cons "%c" (plist-get p :fromto))
9654 (cons "%F" (plist-get p :from))
9655 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9656 (cons "%T" (plist-get p :to))
9657 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9658 (cons "%s" (plist-get p :subject))
9659 (cons "%d" (plist-get p :date))
9660 (cons "%m" (plist-get p :message-id)))))
9661 (when (string-match "%c" fmt)
9662 ;; Check if the user wrote this message
9663 (if (and org-from-is-user-regexp from to
9664 (save-match-data (string-match org-from-is-user-regexp from)))
9665 (setq fmt (replace-match "to %t" t t fmt))
9666 (setq fmt (replace-match "from %f" t t fmt))))
9667 (org-replace-escapes fmt table)))
9669 (defun org-make-org-heading-search-string (&optional string)
9670 "Make search string for the current headline or STRING."
9671 (let ((s (or string
9672 (and (derived-mode-p 'org-mode)
9673 (save-excursion
9674 (org-back-to-heading t)
9675 (org-element-property :raw-value (org-element-at-point))))))
9676 (lines org-context-in-file-links))
9677 (unless string (setq s (concat "*" s))) ;Add * for headlines
9678 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9679 (when (and string (integerp lines) (> lines 0))
9680 (let ((slines (org-split-string s "\n")))
9681 (when (< lines (length slines))
9682 (setq s (mapconcat
9683 'identity
9684 (reverse (nthcdr (- (length slines) lines)
9685 (reverse slines))) "\n")))))
9686 (mapconcat #'identity (split-string s) " ")))
9688 (defconst org-link-escape-chars
9689 ;;%20 %5B %5D %25
9690 '(?\s ?\[ ?\] ?%)
9691 "List of characters that should be escaped in a link when stored to Org.
9692 This is the list that is used for internal purposes.")
9694 (defun org-make-link-string (link &optional description)
9695 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9696 (unless (org-string-nw-p link) (error "Empty link"))
9697 (let ((uri (cond ((string-match org-link-types-re link)
9698 (concat (match-string 1 link)
9699 (org-link-escape (substring link (match-end 1)))))
9700 ((or (file-name-absolute-p link)
9701 (string-match-p "\\`\\.\\.?/" link))
9702 (org-link-escape link))
9703 ;; For readability, do not encode space characters
9704 ;; in fuzzy links.
9705 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9706 (description
9707 (and (org-string-nw-p description)
9708 ;; Remove brackets from description, as they are fatal.
9709 (replace-regexp-in-string
9710 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9711 (org-trim description)))))
9712 (format "[[%s]%s]"
9714 (if description (format "[%s]" description) ""))))
9716 (defun org-link-escape (text &optional table merge)
9717 "Return percent escaped representation of TEXT.
9718 TEXT is a string with the text to escape.
9719 Optional argument TABLE is a list with characters that should be
9720 escaped. When nil, `org-link-escape-chars' is used.
9721 If optional argument MERGE is set, merge TABLE into
9722 `org-link-escape-chars'."
9723 (let ((characters-to-encode
9724 (cond ((null table) org-link-escape-chars)
9725 (merge (append org-link-escape-chars table))
9726 (t table))))
9727 (mapconcat
9728 (lambda (c)
9729 (if (or (memq c characters-to-encode)
9730 (and org-url-hexify-p (or (< c 32) (> c 126))))
9731 (mapconcat (lambda (e) (format "%%%.2X" e))
9732 (or (encode-coding-char c 'utf-8)
9733 (error "Unable to percent escape character: %c" c))
9735 (char-to-string c)))
9736 text "")))
9738 (defun org-link-unescape (str)
9739 "Unhex hexified Unicode parts in string STR.
9740 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9741 reciprocal of `org-link-escape', which see."
9742 (if (org-string-nw-p str)
9743 (replace-regexp-in-string
9744 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9745 str))
9747 (defun org-link-unescape-compound (hex)
9748 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9749 Note: this function also decodes single byte encodings like
9750 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9751 (save-match-data
9752 (let* ((bytes (cdr (split-string hex "%")))
9753 (ret "")
9754 (eat 0)
9755 (sum 0))
9756 (while bytes
9757 (let* ((val (string-to-number (pop bytes) 16))
9758 (shift-xor
9759 (if (= 0 eat)
9760 (cond
9761 ((>= val 252) (cons 6 252))
9762 ((>= val 248) (cons 5 248))
9763 ((>= val 240) (cons 4 240))
9764 ((>= val 224) (cons 3 224))
9765 ((>= val 192) (cons 2 192))
9766 (t (cons 0 0)))
9767 (cons 6 128))))
9768 (when (>= val 192) (setq eat (car shift-xor)))
9769 (setq val (logxor val (cdr shift-xor)))
9770 (setq sum (+ (lsh sum (car shift-xor)) val))
9771 (when (> eat 0) (setq eat (- eat 1)))
9772 (cond
9773 ((= 0 eat) ;multi byte
9774 (setq ret (concat ret (char-to-string sum)))
9775 (setq sum 0))
9776 ((not bytes) ; single byte(s)
9777 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9778 ret)))
9780 (defun org-link-unescape-single-byte-sequence (hex)
9781 "Unhexify hex-encoded single byte character sequences."
9782 (mapconcat (lambda (byte)
9783 (char-to-string (string-to-number byte 16)))
9784 (cdr (split-string hex "%")) ""))
9786 (defun org-fixup-message-id-for-http (s)
9787 "Replace special characters in a message id, so it can be used in an http query."
9788 (when (string-match "%" s)
9789 (setq s (mapconcat (lambda (c)
9790 (if (eq c ?%)
9791 "%25"
9792 (char-to-string c)))
9793 s "")))
9794 (while (string-match "<" s)
9795 (setq s (replace-match "%3C" t t s)))
9796 (while (string-match ">" s)
9797 (setq s (replace-match "%3E" t t s)))
9798 (while (string-match "@" s)
9799 (setq s (replace-match "%40" t t s)))
9802 (defun org-link-prettify (link)
9803 "Return a human-readable representation of LINK.
9804 The car of LINK must be a raw link.
9805 The cdr of LINK must be either a link description or nil."
9806 (let ((desc (or (cadr link) "<no description>")))
9807 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9808 "<" (car link) ">")))
9810 ;;;###autoload
9811 (defun org-insert-link-global ()
9812 "Insert a link like Org mode does.
9813 This command can be called in any mode to insert a link in Org syntax."
9814 (interactive)
9815 (org-load-modules-maybe)
9816 (org-run-like-in-org-mode 'org-insert-link))
9818 (defun org-insert-all-links (arg &optional pre post)
9819 "Insert all links in `org-stored-links'.
9820 When a universal prefix, do not delete the links from `org-stored-links'.
9821 When `ARG' is a number, insert the last N link(s).
9822 `PRE' and `POST' are optional arguments to define a string to
9823 prepend or to append."
9824 (interactive "P")
9825 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9826 (links (copy-sequence org-stored-links))
9827 (pr (or pre "- "))
9828 (po (or post "\n"))
9829 (cnt 1) l)
9830 (if (null org-stored-links)
9831 (message "No link to insert")
9832 (while (and (or (listp arg) (>= arg cnt))
9833 (setq l (if (listp arg)
9834 (pop links)
9835 (pop org-stored-links))))
9836 (setq cnt (1+ cnt))
9837 (insert pr)
9838 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9839 (insert po)))))
9841 (defun org-insert-last-stored-link (arg)
9842 "Insert the last link stored in `org-stored-links'."
9843 (interactive "p")
9844 (org-insert-all-links arg "" "\n"))
9846 (defun org-link-fontify-links-to-this-file ()
9847 "Fontify links to the current file in `org-stored-links'."
9848 (let ((f (buffer-file-name)) a b)
9849 (setq a (mapcar (lambda(l)
9850 (let ((ll (car l)))
9851 (when (and (string-match "^file:\\(.+\\)::" ll)
9852 (equal f (expand-file-name (match-string 1 ll))))
9853 ll)))
9854 org-stored-links))
9855 (when (featurep 'org-id)
9856 (setq b (mapcar (lambda(l)
9857 (let ((ll (car l)))
9858 (when (and (string-match "^id:\\(.+\\)$" ll)
9859 (equal f (expand-file-name
9860 (or (org-id-find-id-file
9861 (match-string 1 ll)) ""))))
9862 ll)))
9863 org-stored-links)))
9864 (mapcar (lambda(l)
9865 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9866 (delq nil (append a b)))))
9868 (defvar org--links-history nil)
9869 (defun org-insert-link (&optional complete-file link-location default-description)
9870 "Insert a link. At the prompt, enter the link.
9872 Completion can be used to insert any of the link protocol prefixes in use.
9874 The history can be used to select a link previously stored with
9875 `org-store-link'. When the empty string is entered (i.e. if you just
9876 press `RET' at the prompt), the link defaults to the most recently
9877 stored link. As `SPC' triggers completion in the minibuffer, you need to
9878 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9880 You will also be prompted for a description, and if one is given, it will
9881 be displayed in the buffer instead of the link.
9883 If there is already a link at point, this command will allow you to edit
9884 link and description parts.
9886 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9887 file name can be
9888 selected using completion. The path to the file will be relative to the
9889 current directory if the file is in the current directory or a subdirectory.
9890 Otherwise, the link will be the absolute path as completed in the minibuffer
9891 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9892 option `org-link-file-path-type'.
9894 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9895 absolute path even if the file is in
9896 the current directory or below.
9898 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9899 prefix negates `org-keep-stored-link-after-insertion'.
9901 If the LINK-LOCATION parameter is non-nil, this value will be used as
9902 the link location instead of reading one interactively.
9904 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9905 be used as the default description. Otherwise, if
9906 `org-make-link-description-function' is non-nil, this function
9907 will be called with the link target, and the result will be the
9908 default link description."
9909 (interactive "P")
9910 (let* ((wcf (current-window-configuration))
9911 (origbuf (current-buffer))
9912 (region (when (org-region-active-p)
9913 (buffer-substring (region-beginning) (region-end))))
9914 (remove (and region (list (region-beginning) (region-end))))
9915 (desc region)
9916 (link link-location)
9917 (abbrevs org-link-abbrev-alist-local)
9918 entry all-prefixes auto-desc)
9919 (cond
9920 (link-location) ; specified by arg, just use it.
9921 ((org-in-regexp org-bracket-link-regexp 1)
9922 ;; We do have a link at point, and we are going to edit it.
9923 (setq remove (list (match-beginning 0) (match-end 0)))
9924 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9925 (setq link (read-string "Link: "
9926 (org-link-unescape
9927 (match-string-no-properties 1)))))
9928 ((or (org-in-regexp org-angle-link-re)
9929 (org-in-regexp org-plain-link-re))
9930 ;; Convert to bracket link
9931 (setq remove (list (match-beginning 0) (match-end 0))
9932 link (read-string "Link: "
9933 (org-unbracket-string "<" ">" (match-string 0)))))
9934 ((member complete-file '((4) (16)))
9935 ;; Completing read for file names.
9936 (setq link (org-file-complete-link complete-file)))
9938 ;; Read link, with completion for stored links.
9939 (org-link-fontify-links-to-this-file)
9940 (org-switch-to-buffer-other-window "*Org Links*")
9941 (with-current-buffer "*Org Links*"
9942 (erase-buffer)
9943 (insert "Insert a link.
9944 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9945 (when org-stored-links
9946 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9947 (insert (mapconcat 'org-link-prettify
9948 (reverse org-stored-links) "\n")))
9949 (goto-char (point-min)))
9950 (let ((cw (selected-window)))
9951 (select-window (get-buffer-window "*Org Links*" 'visible))
9952 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9953 (unless (pos-visible-in-window-p (point-max))
9954 (org-fit-window-to-buffer))
9955 (and (window-live-p cw) (select-window cw)))
9956 (setq all-prefixes (append (mapcar 'car abbrevs)
9957 (mapcar 'car org-link-abbrev-alist)
9958 (org-link-types)))
9959 (unwind-protect
9960 ;; Fake a link history, containing the stored links.
9961 (let ((org--links-history
9962 (append (mapcar #'car org-stored-links)
9963 org-insert-link-history)))
9964 (setq link
9965 (org-completing-read
9966 "Link: "
9967 (append
9968 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9969 (mapcar #'car org-stored-links))
9970 nil nil nil
9971 'org--links-history
9972 (caar org-stored-links)))
9973 (unless (org-string-nw-p link) (user-error "No link selected"))
9974 (dolist (l org-stored-links)
9975 (when (equal link (cadr l))
9976 (setq link (car l))
9977 (setq auto-desc t)))
9978 (when (or (member link all-prefixes)
9979 (and (equal ":" (substring link -1))
9980 (member (substring link 0 -1) all-prefixes)
9981 (setq link (substring link 0 -1))))
9982 (setq link (with-current-buffer origbuf
9983 (org-link-try-special-completion link)))))
9984 (set-window-configuration wcf)
9985 (kill-buffer "*Org Links*"))
9986 (setq entry (assoc link org-stored-links))
9987 (or entry (push link org-insert-link-history))
9988 (setq desc (or desc (nth 1 entry)))))
9990 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9991 (not org-keep-stored-link-after-insertion))
9992 (setq org-stored-links (delq (assoc link org-stored-links)
9993 org-stored-links)))
9995 (when (and (string-match org-plain-link-re link)
9996 (not (string-match org-ts-regexp link)))
9997 ;; URL-like link, normalize the use of angular brackets.
9998 (setq link (org-unbracket-string "<" ">" link)))
10000 ;; Check if we are linking to the current file with a search
10001 ;; option If yes, simplify the link by using only the search
10002 ;; option.
10003 (when (and buffer-file-name
10004 (let ((case-fold-search nil))
10005 (string-match "\\`file:\\(.+?\\)::" link)))
10006 (let ((path (match-string-no-properties 1 link))
10007 (search (substring-no-properties link (match-end 0))))
10008 (save-match-data
10009 (when (equal (file-truename buffer-file-name) (file-truename path))
10010 ;; We are linking to this same file, with a search option
10011 (setq link search)))))
10013 ;; Check if we can/should use a relative path. If yes, simplify
10014 ;; the link.
10015 (let ((case-fold-search nil))
10016 (when (string-match "\\`\\(file\\|docview\\):" link)
10017 (let* ((type (match-string-no-properties 0 link))
10018 (path-start (match-end 0))
10019 (search (and (string-match "::\\(.*\\)\\'" link)
10020 (match-string 1 link)))
10021 (path
10022 (if search
10023 (substring-no-properties
10024 link path-start (match-beginning 0))
10025 (substring-no-properties link (match-end 0))))
10026 (origpath path))
10027 (cond
10028 ((or (eq org-link-file-path-type 'absolute)
10029 (equal complete-file '(16)))
10030 (setq path (abbreviate-file-name (expand-file-name path))))
10031 ((eq org-link-file-path-type 'noabbrev)
10032 (setq path (expand-file-name path)))
10033 ((eq org-link-file-path-type 'relative)
10034 (setq path (file-relative-name path)))
10036 (save-match-data
10037 (if (string-match (concat "^" (regexp-quote
10038 (expand-file-name
10039 (file-name-as-directory
10040 default-directory))))
10041 (expand-file-name path))
10042 ;; We are linking a file with relative path name.
10043 (setq path (substring (expand-file-name path)
10044 (match-end 0)))
10045 (setq path (abbreviate-file-name (expand-file-name path)))))))
10046 (setq link (concat type path (and search (concat "::" search))))
10047 (when (equal desc origpath)
10048 (setq desc path)))))
10050 (unless auto-desc
10051 (let ((initial-input
10052 (cond
10053 (default-description)
10054 ((not org-make-link-description-function) desc)
10055 (t (condition-case nil
10056 (funcall org-make-link-description-function link desc)
10057 (error
10058 (message "Can't get link description from `%s'"
10059 (symbol-name org-make-link-description-function))
10060 (sit-for 2)
10061 nil))))))
10062 (setq desc (read-string "Description: " initial-input))))
10064 (unless (string-match "\\S-" desc) (setq desc nil))
10065 (when remove (apply 'delete-region remove))
10066 (insert (org-make-link-string link desc))
10067 ;; Redisplay so as the new link has proper invisible characters.
10068 (sit-for 0)))
10070 (defun org-link-try-special-completion (type)
10071 "If there is completion support for link type TYPE, offer it."
10072 (let ((fun (org-link-get-parameter type :complete)))
10073 (if (functionp fun)
10074 (funcall fun)
10075 (read-string "Link (no completion support): " (concat type ":")))))
10077 (defun org-file-complete-link (&optional arg)
10078 "Create a file link using completion."
10079 (let ((file (read-file-name "File: "))
10080 (pwd (file-name-as-directory (expand-file-name ".")))
10081 (pwd1 (file-name-as-directory (abbreviate-file-name
10082 (expand-file-name ".")))))
10083 (cond ((equal arg '(16))
10084 (concat "file:"
10085 (abbreviate-file-name (expand-file-name file))))
10086 ((string-match
10087 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10088 (concat "file:" (match-string 1 file)))
10089 ((string-match
10090 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10091 (expand-file-name file))
10092 (concat "file:"
10093 (match-string 1 (expand-file-name file))))
10094 (t (concat "file:" file)))))
10097 ;;; Opening/following a link
10099 (defvar org-link-search-failed nil)
10101 (defvar org-open-link-functions nil
10102 "Hook for functions finding a plain text link.
10103 These functions must take a single argument, the link content.
10104 They will be called for links that look like [[link text][description]]
10105 when LINK TEXT does not have a protocol like \"http:\" and does not look
10106 like a filename (e.g. \"./blue.png\").
10108 These functions will be called *before* Org attempts to resolve the
10109 link by doing text searches in the current buffer - so if you want a
10110 link \"[[target]]\" to still find \"<<target>>\", your function should
10111 handle this as a special case.
10113 When the function does handle the link, it must return a non-nil value.
10114 If it decides that it is not responsible for this link, it must return
10115 nil to indicate that that Org can continue with other options like
10116 exact and fuzzy text search.")
10118 (defun org-next-link (&optional search-backward)
10119 "Move forward to the next link.
10120 If the link is in hidden text, expose it."
10121 (interactive "P")
10122 (when (and org-link-search-failed (eq this-command last-command))
10123 (goto-char (point-min))
10124 (message "Link search wrapped back to beginning of buffer"))
10125 (setq org-link-search-failed nil)
10126 (let* ((pos (point))
10127 (ct (org-context))
10128 (a (assq :link ct))
10129 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10130 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10131 ((looking-at org-any-link-re)
10132 ;; Don't stay stuck at link without an org-link face
10133 (forward-char (if search-backward -1 1))))
10134 (if (funcall srch-fun org-any-link-re nil t)
10135 (progn
10136 (goto-char (match-beginning 0))
10137 (when (org-invisible-p) (org-show-context)))
10138 (goto-char pos)
10139 (setq org-link-search-failed t)
10140 (message "No further link found"))))
10142 (defun org-previous-link ()
10143 "Move backward to the previous link.
10144 If the link is in hidden text, expose it."
10145 (interactive)
10146 (funcall 'org-next-link t))
10148 (defun org-translate-link (s)
10149 "Translate a link string if a translation function has been defined."
10150 (with-temp-buffer
10151 (insert (org-trim s))
10152 (org-trim (org-element-interpret-data (org-element-context)))))
10154 (defun org-translate-link-from-planner (type path)
10155 "Translate a link from Emacs Planner syntax so that Org can follow it.
10156 This is still an experimental function, your mileage may vary."
10157 (cond
10158 ((member type '("http" "https" "news" "ftp"))
10159 ;; standard Internet links are the same.
10160 nil)
10161 ((and (equal type "irc") (string-match "^//" path))
10162 ;; Planner has two / at the beginning of an irc link, we have 1.
10163 ;; We should have zero, actually....
10164 (setq path (substring path 1)))
10165 ((and (equal type "lisp") (string-match "^/" path))
10166 ;; Planner has a slash, we do not.
10167 (setq type "elisp" path (substring path 1)))
10168 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10169 ;; A typical message link. Planner has the id after the final slash,
10170 ;; we separate it with a hash mark
10171 (setq path (concat (match-string 1 path) "#"
10172 (org-unbracket-string "<" ">" (match-string 2 path))))))
10173 (cons type path))
10175 (defun org-find-file-at-mouse (ev)
10176 "Open file link or URL at mouse."
10177 (interactive "e")
10178 (mouse-set-point ev)
10179 (org-open-at-point 'in-emacs))
10181 (defun org-open-at-mouse (ev)
10182 "Open file link or URL at mouse.
10183 See the docstring of `org-open-file' for details."
10184 (interactive "e")
10185 (mouse-set-point ev)
10186 (when (eq major-mode 'org-agenda-mode)
10187 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10188 (org-open-at-point))
10190 (defvar org-window-config-before-follow-link nil
10191 "The window configuration before following a link.
10192 This is saved in case the need arises to restore it.")
10194 ;;;###autoload
10195 (defun org-open-at-point-global ()
10196 "Follow a link or time-stamp like Org mode does.
10197 This command can be called in any mode to follow an external link
10198 or a time-stamp that has Org mode syntax. Its behavior is
10199 undefined when called on internal links (e.g., fuzzy links).
10200 Raise an error when there is nothing to follow. "
10201 (interactive)
10202 (cond ((org-in-regexp org-any-link-re)
10203 (org-open-link-from-string (match-string-no-properties 0)))
10204 ((or (org-in-regexp org-ts-regexp-both nil t)
10205 (org-in-regexp org-tsr-regexp-both nil t))
10206 (org-follow-timestamp-link))
10207 (t (user-error "No link found"))))
10209 ;;;###autoload
10210 (defun org-open-link-from-string (s &optional arg reference-buffer)
10211 "Open a link in the string S, as if it was in Org mode."
10212 (interactive "sLink: \nP")
10213 (let ((reference-buffer (or reference-buffer (current-buffer))))
10214 (with-temp-buffer
10215 (let ((org-inhibit-startup (not reference-buffer)))
10216 (org-mode)
10217 (insert s)
10218 (goto-char (point-min))
10219 (when reference-buffer
10220 (setq org-link-abbrev-alist-local
10221 (with-current-buffer reference-buffer
10222 org-link-abbrev-alist-local)))
10223 (org-open-at-point arg reference-buffer)))))
10225 (defvar org-open-at-point-functions nil
10226 "Hook that is run when following a link at point.
10228 Functions in this hook must return t if they identify and follow
10229 a link at point. If they don't find anything interesting at point,
10230 they must return nil.")
10232 (defvar org-link-search-inhibit-query nil)
10233 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10234 (defun org--open-doi-link (path)
10235 "Open a \"doi\" type link.
10236 PATH is a the path to search for, as a string."
10237 (browse-url (url-encode-url (concat org-doi-server-url path))))
10239 (defun org--open-elisp-link (path)
10240 "Open a \"elisp\" type link.
10241 PATH is the sexp to evaluate, as a string."
10242 (let ((cmd path))
10243 (if (or (and (org-string-nw-p
10244 org-confirm-elisp-link-not-regexp)
10245 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10246 (not org-confirm-elisp-link-function)
10247 (funcall org-confirm-elisp-link-function
10248 (format "Execute \"%s\" as elisp? "
10249 (org-add-props cmd nil 'face 'org-warning))))
10250 (message "%s => %s" cmd
10251 (if (eq (string-to-char cmd) ?\()
10252 (eval (read cmd))
10253 (call-interactively (read cmd))))
10254 (user-error "Abort"))))
10256 (defun org--open-help-link (path)
10257 "Open a \"help\" type link.
10258 PATH is a symbol name, as a string."
10259 (pcase (intern path)
10260 ((and (pred fboundp) variable) (describe-function variable))
10261 ((and (pred boundp) function) (describe-variable function))
10262 (name (user-error "Unknown function or variable: %s" name))))
10264 (defun org--open-shell-link (path)
10265 "Open a \"shell\" type link.
10266 PATH is the command to execute, as a string."
10267 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10268 (cmd path))
10269 (if (or (and (org-string-nw-p
10270 org-confirm-shell-link-not-regexp)
10271 (string-match
10272 org-confirm-shell-link-not-regexp cmd))
10273 (not org-confirm-shell-link-function)
10274 (funcall org-confirm-shell-link-function
10275 (format "Execute \"%s\" in shell? "
10276 (org-add-props cmd nil
10277 'face 'org-warning))))
10278 (progn
10279 (message "Executing %s" cmd)
10280 (shell-command cmd buf)
10281 (when (featurep 'midnight)
10282 (setq clean-buffer-list-kill-buffer-names
10283 (cons (buffer-name buf)
10284 clean-buffer-list-kill-buffer-names))))
10285 (user-error "Abort"))))
10287 (defun org-open-at-point (&optional arg reference-buffer)
10288 "Open link, timestamp, footnote or tags at point.
10290 When point is on a link, follow it. Normally, files will be
10291 opened by an appropriate application. If the optional prefix
10292 argument ARG is non-nil, Emacs will visit the file. With
10293 a double prefix argument, try to open outside of Emacs, in the
10294 application the system uses for this file type.
10296 When point is on a timestamp, open the agenda at the day
10297 specified.
10299 When point is a footnote definition, move to the first reference
10300 found. If it is on a reference, move to the associated
10301 definition.
10303 When point is on a headline, display a list of every link in the
10304 entry, so it is possible to pick one, or all, of them. If point
10305 is on a tag, call `org-tags-view' instead.
10307 When optional argument REFERENCE-BUFFER is non-nil, it should
10308 specify a buffer from where the link search should happen. This
10309 is used internally by `org-open-link-from-string'.
10311 On top of syntactically correct links, this function will also
10312 try to open links and time-stamps in comments, example
10313 blocks... i.e., whenever point is on something looking like
10314 a timestamp or a link."
10315 (interactive "P")
10316 ;; On a code block, open block's results.
10317 (unless (call-interactively 'org-babel-open-src-block-result)
10318 (org-load-modules-maybe)
10319 (setq org-window-config-before-follow-link (current-window-configuration))
10320 (org-remove-occur-highlights nil nil t)
10321 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10322 (let* ((context
10323 ;; Only consider supported types, even if they are not
10324 ;; the closest one.
10325 (org-element-lineage
10326 (org-element-context)
10327 '(clock footnote-definition footnote-reference headline
10328 inlinetask link timestamp)
10330 (type (org-element-type context))
10331 (value (org-element-property :value context)))
10332 (cond
10333 ;; On a headline or an inlinetask, but not on a timestamp,
10334 ;; a link, a footnote reference.
10335 ((memq type '(headline inlinetask))
10336 (org-match-line org-complex-heading-regexp)
10337 (if (and (match-beginning 5)
10338 (>= (point) (match-beginning 5))
10339 (< (point) (match-end 5)))
10340 ;; On tags.
10341 (org-tags-view arg (substring (match-string 5) 0 -1))
10342 ;; Not on tags.
10343 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10344 (`(nil . ,_)
10345 (require 'org-attach)
10346 (org-attach-reveal 'if-exists))
10347 (`(,links . ,links-end)
10348 (dolist (link (if (stringp links) (list links) links))
10349 (search-forward link nil links-end)
10350 (goto-char (match-beginning 0))
10351 (org-open-at-point))))))
10352 ;; On a footnote reference or at definition's label.
10353 ((or (eq type 'footnote-reference)
10354 (and (eq type 'footnote-definition)
10355 (save-excursion
10356 ;; Do not validate action when point is on the
10357 ;; spaces right after the footnote label, in
10358 ;; order to be on par with behaviour on links.
10359 (skip-chars-forward " \t")
10360 (let ((begin
10361 (org-element-property :contents-begin context)))
10362 (if begin (< (point) begin)
10363 (= (org-element-property :post-affiliated context)
10364 (line-beginning-position)))))))
10365 (org-footnote-action))
10366 ;; No valid context. Ignore catch-all types like `headline'.
10367 ;; If point is on something looking like a link or
10368 ;; a time-stamp, try opening it. It may be useful in
10369 ;; comments, example blocks...
10370 ((memq type '(footnote-definition headline inlinetask nil))
10371 (call-interactively #'org-open-at-point-global))
10372 ;; On a clock line, make sure point is on the timestamp
10373 ;; before opening it.
10374 ((and (eq type 'clock)
10375 value
10376 (>= (point) (org-element-property :begin value))
10377 (<= (point) (org-element-property :end value)))
10378 (org-follow-timestamp-link))
10379 ;; Do nothing on white spaces after an object.
10380 ((>= (point)
10381 (save-excursion
10382 (goto-char (org-element-property :end context))
10383 (skip-chars-backward " \t")
10384 (point)))
10385 (user-error "No link found"))
10386 ((eq type 'timestamp) (org-follow-timestamp-link))
10387 ((eq type 'link)
10388 (let ((type (org-element-property :type context))
10389 (path (org-link-unescape (org-element-property :path context))))
10390 ;; Switch back to REFERENCE-BUFFER needed when called in
10391 ;; a temporary buffer through `org-open-link-from-string'.
10392 (with-current-buffer (or reference-buffer (current-buffer))
10393 (cond
10394 ((equal type "file")
10395 (if (string-match "[*?{]" (file-name-nondirectory path))
10396 (dired path)
10397 ;; Look into `org-link-parameters' in order to find
10398 ;; a DEDICATED-FUNCTION to open file. The function
10399 ;; will be applied on raw link instead of parsed
10400 ;; link due to the limitation in `org-add-link-type'
10401 ;; ("open" function called with a single argument).
10402 ;; If no such function is found, fallback to
10403 ;; `org-open-file'.
10404 (let* ((option (org-element-property :search-option context))
10405 (app (org-element-property :application context))
10406 (dedicated-function
10407 (org-link-get-parameter
10408 (if app (concat type "+" app) type)
10409 :follow)))
10410 (if dedicated-function
10411 (funcall dedicated-function
10412 (concat path
10413 (and option (concat "::" option))))
10414 (apply #'org-open-file
10415 path
10416 (cond (arg)
10417 ((equal app "emacs") 'emacs)
10418 ((equal app "sys") 'system))
10419 (cond ((not option) nil)
10420 ((string-match-p "\\`[0-9]+\\'" option)
10421 (list (string-to-number option)))
10422 (t (list nil
10423 (org-link-unescape option)))))))))
10424 ((functionp (org-link-get-parameter type :follow))
10425 (funcall (org-link-get-parameter type :follow) path))
10426 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10427 (unless (run-hook-with-args-until-success
10428 'org-open-link-functions path)
10429 (if (not arg) (org-mark-ring-push)
10430 (switch-to-buffer-other-window
10431 (org-get-buffer-for-internal-link (current-buffer))))
10432 (let ((destination
10433 (org-with-wide-buffer
10434 (if (equal type "radio")
10435 (org-search-radio-target
10436 (org-element-property :path context))
10437 (org-link-search
10438 (if (member type '("custom-id" "coderef"))
10439 (org-element-property :raw-link context)
10440 path)
10441 ;; Prevent fuzzy links from matching
10442 ;; themselves.
10443 (and (equal type "fuzzy")
10444 (+ 2 (org-element-property :begin context)))))
10445 (point))))
10446 (unless (and (<= (point-min) destination)
10447 (>= (point-max) destination))
10448 (widen))
10449 (goto-char destination))))
10450 (t (browse-url-at-point))))))
10451 (t (user-error "No link found")))))
10452 (run-hook-with-args 'org-follow-link-hook)))
10454 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10455 "Offer links in the current entry and return the selected link.
10456 If there is only one link, return it.
10457 If NTH is an integer, return the NTH link found.
10458 If ZERO is a string, check also this string for a link, and if
10459 there is one, return it."
10460 (with-current-buffer buffer
10461 (org-with-wide-buffer
10462 (goto-char marker)
10463 (let ((cnt ?0)
10464 have-zero end links link c)
10465 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10466 (push (match-string 0 zero) links)
10467 (setq cnt (1- cnt) have-zero t))
10468 (save-excursion
10469 (org-back-to-heading t)
10470 (setq end (save-excursion (outline-next-heading) (point)))
10471 (while (re-search-forward org-any-link-re end t)
10472 (push (match-string 0) links))
10473 (setq links (org-uniquify (reverse links))))
10474 (cond
10475 ((null links)
10476 (message "No links"))
10477 ((equal (length links) 1)
10478 (setq link (car links)))
10479 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10480 (setq link (nth (if have-zero nth (1- nth)) links)))
10481 (t ; we have to select a link
10482 (save-excursion
10483 (save-window-excursion
10484 (delete-other-windows)
10485 (with-output-to-temp-buffer "*Select Link*"
10486 (dolist (l links)
10487 (cond
10488 ((not (string-match org-bracket-link-regexp l))
10489 (princ (format "[%c] %s\n" (cl-incf cnt)
10490 (org-unbracket-string "<" ">" l))))
10491 ((match-end 3)
10492 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10493 (match-string 3 l) (match-string 1 l))))
10494 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10495 (match-string 1 l)))))))
10496 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10497 (message "Select link to open, RET to open all:")
10498 (setq c (read-char-exclusive))
10499 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10500 (when (equal c ?q) (user-error "Abort"))
10501 (if (equal c ?\C-m)
10502 (setq link links)
10503 (setq nth (- c ?0))
10504 (when have-zero (setq nth (1+ nth)))
10505 (unless (and (integerp nth) (>= (length links) nth))
10506 (user-error "Invalid link selection"))
10507 (setq link (nth (1- nth) links)))))
10508 (cons link end)))))
10510 ;; TODO: These functions are deprecated since `org-open-at-point'
10511 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10512 (defun org-open-file-with-system (path)
10513 "Open file at PATH using the system way of opening it."
10514 (org-open-file path 'system))
10515 (defun org-open-file-with-emacs (path)
10516 "Open file at PATH in Emacs."
10517 (org-open-file path 'emacs))
10520 ;;; File search
10522 (defvar org-create-file-search-functions nil
10523 "List of functions to construct the right search string for a file link.
10524 These functions are called in turn with point at the location to
10525 which the link should point.
10527 A function in the hook should first test if it would like to
10528 handle this file type, for example by checking the `major-mode'
10529 or the file extension. If it decides not to handle this file, it
10530 should just return nil to give other functions a chance. If it
10531 does handle the file, it must return the search string to be used
10532 when following the link. The search string will be part of the
10533 file link, given after a double colon, and `org-open-at-point'
10534 will automatically search for it. If special measures must be
10535 taken to make the search successful, another function should be
10536 added to the companion hook `org-execute-file-search-functions',
10537 which see.
10539 A function in this hook may also use `setq' to set the variable
10540 `description' to provide a suggestion for the descriptive text to
10541 be used for this link when it gets inserted into an Org buffer
10542 with \\[org-insert-link].")
10544 (defvar org-execute-file-search-functions nil
10545 "List of functions to execute a file search triggered by a link.
10547 Functions added to this hook must accept a single argument, the
10548 search string that was part of the file link, the part after the
10549 double colon. The function must first check if it would like to
10550 handle this search, for example by checking the `major-mode' or
10551 the file extension. If it decides not to handle this search, it
10552 should just return nil to give other functions a chance. If it
10553 does handle the search, it must return a non-nil value to keep
10554 other functions from trying.
10556 Each function can access the current prefix argument through the
10557 variable `current-prefix-arg'. Note that a single prefix is used
10558 to force opening a link in Emacs, so it may be good to only use a
10559 numeric or double prefix to guide the search function.
10561 In case this is needed, a function in this hook can also restore
10562 the window configuration before `org-open-at-point' was called using:
10564 (set-window-configuration org-window-config-before-follow-link)")
10566 (defun org-search-radio-target (target)
10567 "Search a radio target matching TARGET in current buffer.
10568 White spaces are not significant."
10569 (let ((re (format "<<<%s>>>"
10570 (mapconcat #'regexp-quote
10571 (split-string target)
10572 "[ \t]+\\(?:\n[ \t]*\\)?")))
10573 (origin (point)))
10574 (goto-char (point-min))
10575 (catch :radio-match
10576 (while (re-search-forward re nil t)
10577 (backward-char)
10578 (let ((object (org-element-context)))
10579 (when (eq (org-element-type object) 'radio-target)
10580 (goto-char (org-element-property :begin object))
10581 (org-show-context 'link-search)
10582 (throw :radio-match nil))))
10583 (goto-char origin)
10584 (user-error "No match for radio target: %s" target))))
10586 (defun org-link-search (s &optional avoid-pos stealth)
10587 "Search for a search string S.
10589 If S starts with \"#\", it triggers a custom ID search.
10591 If S is enclosed within parenthesis, it initiates a coderef
10592 search.
10594 If S is surrounded by forward slashes, it is interpreted as
10595 a regular expression. In Org mode files, this will create an
10596 `org-occur' sparse tree. In ordinary files, `occur' will be used
10597 to list matches. If the current buffer is in `dired-mode', grep
10598 will be used to search in all files.
10600 When AVOID-POS is given, ignore matches near that position.
10602 When optional argument STEALTH is non-nil, do not modify
10603 visibility around point, thus ignoring `org-show-context-detail'
10604 variable.
10606 Search is case-insensitive and ignores white spaces. Return type
10607 of matched result, which is either `dedicated' or `fuzzy'."
10608 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10609 (let* ((case-fold-search t)
10610 (origin (point))
10611 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10612 (starred (eq (string-to-char normalized) ?*))
10613 (words (split-string (if starred (substring s 1) s)))
10614 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10615 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10616 type)
10617 (cond
10618 ;; Check if there are any special search functions.
10619 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10620 ((eq (string-to-char s) ?#)
10621 ;; Look for a custom ID S if S starts with "#".
10622 (let* ((id (substring normalized 1))
10623 (match (org-find-property "CUSTOM_ID" id)))
10624 (if match (progn (goto-char match) (setf type 'dedicated))
10625 (error "No match for custom ID: %s" id))))
10626 ((string-match "\\`(\\(.*\\))\\'" normalized)
10627 ;; Look for coderef targets if S is enclosed within parenthesis.
10628 (let ((coderef (match-string-no-properties 1 normalized))
10629 (re (substring s-single-re 1 -1)))
10630 (goto-char (point-min))
10631 (catch :coderef-match
10632 (while (re-search-forward re nil t)
10633 (let ((element (org-element-at-point)))
10634 (when (and (memq (org-element-type element)
10635 '(example-block src-block))
10636 ;; Build proper regexp according to current
10637 ;; block's label format.
10638 (let ((label-fmt
10639 (regexp-quote
10640 (or (org-element-property :label-fmt element)
10641 org-coderef-label-format))))
10642 (save-excursion
10643 (beginning-of-line)
10644 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10645 (format label-fmt coderef))))))
10646 (setq type 'dedicated)
10647 (goto-char (match-beginning 1))
10648 (throw :coderef-match nil))))
10649 (goto-char origin)
10650 (error "No match for coderef: %s" coderef))))
10651 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10652 ;; Look for a regular expression.
10653 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10654 (match-string 1 s)))
10655 ;; From here, we handle fuzzy links.
10657 ;; Look for targets, only if not in a headline search.
10658 ((and (not starred)
10659 (let ((target (format "<<%s>>" s-multi-re)))
10660 (catch :target-match
10661 (goto-char (point-min))
10662 (while (re-search-forward target nil t)
10663 (backward-char)
10664 (let ((context (org-element-context)))
10665 (when (eq (org-element-type context) 'target)
10666 (setq type 'dedicated)
10667 (goto-char (org-element-property :begin context))
10668 (throw :target-match t))))
10669 nil))))
10670 ;; Look for elements named after S, only if not in a headline
10671 ;; search.
10672 ((and (not starred)
10673 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10674 (catch :name-match
10675 (goto-char (point-min))
10676 (while (re-search-forward name nil t)
10677 (let ((element (org-element-at-point)))
10678 (when (equal words
10679 (split-string
10680 (org-element-property :name element)))
10681 (setq type 'dedicated)
10682 (beginning-of-line)
10683 (throw :name-match t))))
10684 nil))))
10685 ;; Regular text search. Prefer headlines in Org mode buffers.
10686 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10687 ;; statistics cookies and tags.
10688 ((and (derived-mode-p 'org-mode)
10689 (let ((title-re
10690 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10691 org-outline-regexp-bol
10692 org-comment-string
10693 (mapconcat #'regexp-quote words ".+")))
10694 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10695 (comment-re (eval-when-compile
10696 (format "\\`%s[ \t]+" org-comment-string))))
10697 (goto-char (point-min))
10698 (catch :found
10699 (while (re-search-forward title-re nil t)
10700 (when (equal words
10701 (split-string
10702 (replace-regexp-in-string
10703 cookie-re ""
10704 (replace-regexp-in-string
10705 comment-re "" (org-get-heading t t t)))))
10706 (throw :found t)))
10707 nil)))
10708 (beginning-of-line)
10709 (setq type 'dedicated))
10710 ;; Offer to create non-existent headline depending on
10711 ;; `org-link-search-must-match-exact-headline'.
10712 ((and (derived-mode-p 'org-mode)
10713 (not org-link-search-inhibit-query)
10714 (eq org-link-search-must-match-exact-headline 'query-to-create)
10715 (yes-or-no-p "No match - create this as a new heading? "))
10716 (goto-char (point-max))
10717 (unless (bolp) (newline))
10718 (org-insert-heading nil t t)
10719 (insert s "\n")
10720 (beginning-of-line 0))
10721 ;; Only headlines are looked after. No need to process
10722 ;; further: throw an error.
10723 ((and (derived-mode-p 'org-mode)
10724 (or starred org-link-search-must-match-exact-headline))
10725 (goto-char origin)
10726 (error "No match for fuzzy expression: %s" normalized))
10727 ;; Regular text search.
10728 ((catch :fuzzy-match
10729 (goto-char (point-min))
10730 (while (re-search-forward s-multi-re nil t)
10731 ;; Skip match if it contains AVOID-POS or it is included in
10732 ;; a link with a description but outside the description.
10733 (unless (or (and avoid-pos
10734 (<= (match-beginning 0) avoid-pos)
10735 (> (match-end 0) avoid-pos))
10736 (and (save-match-data
10737 (org-in-regexp org-bracket-link-regexp))
10738 (match-beginning 3)
10739 (or (> (match-beginning 3) (point))
10740 (<= (match-end 3) (point)))
10741 (org-element-lineage
10742 (save-match-data (org-element-context))
10743 '(link) t)))
10744 (goto-char (match-beginning 0))
10745 (setq type 'fuzzy)
10746 (throw :fuzzy-match t)))
10747 nil))
10748 ;; All failed. Throw an error.
10749 (t (goto-char origin)
10750 (error "No match for fuzzy expression: %s" normalized)))
10751 ;; Disclose surroundings of match, if appropriate.
10752 (when (and (derived-mode-p 'org-mode) (not stealth))
10753 (org-show-context 'link-search))
10754 type))
10756 (defun org-get-buffer-for-internal-link (buffer)
10757 "Return a buffer to be used for displaying the link target of internal links."
10758 (cond
10759 ((not org-display-internal-link-with-indirect-buffer)
10760 buffer)
10761 ((string-suffix-p "(Clone)" (buffer-name buffer))
10762 (message "Buffer is already a clone, not making another one")
10763 ;; we also do not modify visibility in this case
10764 buffer)
10765 (t ; make a new indirect buffer for displaying the link
10766 (let* ((bn (buffer-name buffer))
10767 (ibn (concat bn "(Clone)"))
10768 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10769 (with-current-buffer ib (org-overview))
10770 ib))))
10772 (defun org-do-occur (regexp &optional cleanup)
10773 "Call the Emacs command `occur'.
10774 If CLEANUP is non-nil, remove the printout of the regular expression
10775 in the *Occur* buffer. This is useful if the regex is long and not useful
10776 to read."
10777 (occur regexp)
10778 (when cleanup
10779 (let ((cwin (selected-window)) win beg end)
10780 (when (setq win (get-buffer-window "*Occur*"))
10781 (select-window win))
10782 (goto-char (point-min))
10783 (when (re-search-forward "match[a-z]+" nil t)
10784 (setq beg (match-end 0))
10785 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10786 (setq end (1- (match-beginning 0)))))
10787 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10788 (goto-char (point-min))
10789 (select-window cwin))))
10791 ;;; The mark ring for links jumps
10793 (defvar org-mark-ring nil
10794 "Mark ring for positions before jumps in Org mode.")
10795 (defvar org-mark-ring-last-goto nil
10796 "Last position in the mark ring used to go back.")
10797 ;; Fill and close the ring
10798 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10799 (dotimes (_ org-mark-ring-length)
10800 (push (make-marker) org-mark-ring))
10801 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10802 org-mark-ring)
10804 (defun org-mark-ring-push (&optional pos buffer)
10805 "Put the current position or POS into the mark ring and rotate it."
10806 (interactive)
10807 (setq pos (or pos (point)))
10808 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10809 (move-marker (car org-mark-ring)
10810 (or pos (point))
10811 (or buffer (current-buffer)))
10812 (message "%s"
10813 (substitute-command-keys
10814 "Position saved to mark ring, go back with \
10815 `\\[org-mark-ring-goto]'.")))
10817 (defun org-mark-ring-goto (&optional n)
10818 "Jump to the previous position in the mark ring.
10819 With prefix arg N, jump back that many stored positions. When
10820 called several times in succession, walk through the entire ring.
10821 Org mode commands jumping to a different position in the current file,
10822 or to another Org file, automatically push the old position onto the ring."
10823 (interactive "p")
10824 (let (p m)
10825 (if (eq last-command this-command)
10826 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10827 (setq p org-mark-ring))
10828 (setq org-mark-ring-last-goto p)
10829 (setq m (car p))
10830 (pop-to-buffer-same-window (marker-buffer m))
10831 (goto-char m)
10832 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10834 (defun org-add-angle-brackets (s)
10835 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10836 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10839 ;;; Following specific links
10841 (defvar org-agenda-buffer-tmp-name)
10842 (defvar org-agenda-start-on-weekday)
10843 (defun org-follow-timestamp-link ()
10844 "Open an agenda view for the time-stamp date/range at point."
10845 (cond
10846 ((org-at-date-range-p t)
10847 (let ((org-agenda-start-on-weekday)
10848 (t1 (match-string 1))
10849 (t2 (match-string 2)) tt1 tt2)
10850 (setq tt1 (time-to-days (org-time-string-to-time t1))
10851 tt2 (time-to-days (org-time-string-to-time t2)))
10852 (let ((org-agenda-buffer-tmp-name
10853 (format "*Org Agenda(a:%s)"
10854 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10855 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10856 ((org-at-timestamp-p 'lax)
10857 (let ((org-agenda-buffer-tmp-name
10858 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10859 (org-agenda-list nil (time-to-days (org-time-string-to-time
10860 (substring (match-string 1) 0 10)))
10861 1)))
10862 (t (error "This should not happen"))))
10865 ;;; Following file links
10866 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10867 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10868 (declare-function mailcap-mime-info
10869 "mailcap" (string &optional request no-decode))
10870 (defvar org-wait nil)
10871 (defun org-open-file (path &optional in-emacs line search)
10872 "Open the file at PATH.
10873 First, this expands any special file name abbreviations. Then the
10874 configuration variable `org-file-apps' is checked if it contains an
10875 entry for this file type, and if yes, the corresponding command is launched.
10877 If no application is found, Emacs simply visits the file.
10879 With optional prefix argument IN-EMACS, Emacs will visit the file.
10880 With a double \\[universal-argument] \\[universal-argument] \
10881 prefix arg, Org tries to avoid opening in Emacs
10882 and to use an external application to visit the file.
10884 Optional LINE specifies a line to go to, optional SEARCH a string
10885 to search for. If LINE or SEARCH is given, the file will be
10886 opened in Emacs, unless an entry from org-file-apps that makes
10887 use of groups in a regexp matches.
10889 If you want to change the way frames are used when following a
10890 link, please customize `org-link-frame-setup'.
10892 If the file does not exist, an error is thrown."
10893 (let* ((file (if (equal path "")
10894 buffer-file-name
10895 (substitute-in-file-name (expand-file-name path))))
10896 (file-apps (append org-file-apps (org-default-apps)))
10897 (apps (cl-remove-if
10898 'org-file-apps-entry-match-against-dlink-p file-apps))
10899 (apps-dlink (cl-remove-if-not
10900 'org-file-apps-entry-match-against-dlink-p file-apps))
10901 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10902 (dirp (unless remp (file-directory-p file)))
10903 (file (if (and dirp org-open-directory-means-index-dot-org)
10904 (concat (file-name-as-directory file) "index.org")
10905 file))
10906 (a-m-a-p (assq 'auto-mode apps))
10907 (dfile (downcase file))
10908 ;; Reconstruct the original link from the PATH, LINE and
10909 ;; SEARCH args.
10910 (link (cond (line (concat file "::" (number-to-string line)))
10911 (search (concat file "::" search))
10912 (t file)))
10913 (dlink (downcase link))
10914 (ext
10915 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10916 (match-string 1 dfile)))
10917 (save-position-maybe
10918 (let ((old-buffer (current-buffer))
10919 (old-pos (point))
10920 (old-mode major-mode))
10921 (lambda ()
10922 (and (derived-mode-p 'org-mode)
10923 (eq old-mode 'org-mode)
10924 (or (not (eq old-buffer (current-buffer)))
10925 (not (eq old-pos (point))))
10926 (org-mark-ring-push old-pos old-buffer)))))
10927 cmd link-match-data)
10928 (cond
10929 ((member in-emacs '((16) system))
10930 (setq cmd (cdr (assq 'system apps))))
10931 (in-emacs (setq cmd 'emacs))
10933 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10934 (and dirp (cdr (assq 'directory apps)))
10935 ;; First, try matching against apps-dlink if we
10936 ;; get a match here, store the match data for
10937 ;; later.
10938 (let ((match (assoc-default dlink apps-dlink
10939 'string-match)))
10940 (if match
10941 (progn (setq link-match-data (match-data))
10942 match)
10943 (progn (setq in-emacs (or in-emacs line search))
10944 nil))) ; if we have no match in apps-dlink,
10945 ; always open the file in emacs if line or search
10946 ; is given (for backwards compatibility)
10947 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10948 'string-match)
10949 (cdr (assoc ext apps))
10950 (cdr (assq t apps))))))
10951 (when (eq cmd 'system)
10952 (setq cmd (cdr (assq 'system apps))))
10953 (when (eq cmd 'default)
10954 (setq cmd (cdr (assoc t apps))))
10955 (when (eq cmd 'mailcap)
10956 (require 'mailcap)
10957 (mailcap-parse-mailcaps)
10958 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10959 (command (mailcap-mime-info mime-type)))
10960 (if (stringp command)
10961 (setq cmd command)
10962 (setq cmd 'emacs))))
10963 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10964 (not (file-exists-p file))
10965 (not org-open-non-existing-files))
10966 (user-error "No such file: %s" file))
10967 (cond
10968 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10969 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10970 (while (string-match "['\"]%s['\"]" cmd)
10971 (setq cmd (replace-match "%s" t t cmd)))
10972 (setq cmd (replace-regexp-in-string
10973 "%s"
10974 (shell-quote-argument (convert-standard-filename file))
10976 nil t))
10978 ;; Replace "%1", "%2" etc. in command with group matches from regex
10979 (save-match-data
10980 (let ((match-index 1)
10981 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10982 (set-match-data link-match-data)
10983 (while (<= match-index number-of-groups)
10984 (let ((regex (concat "%" (number-to-string match-index)))
10985 (replace-with (match-string match-index dlink)))
10986 (while (string-match regex cmd)
10987 (setq cmd (replace-match replace-with t t cmd))))
10988 (setq match-index (+ match-index 1)))))
10990 (save-window-excursion
10991 (message "Running %s...done" cmd)
10992 (start-process-shell-command cmd nil cmd)
10993 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10994 ((or (stringp cmd)
10995 (eq cmd 'emacs))
10996 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10997 (widen)
10998 (cond (line (org-goto-line line)
10999 (when (derived-mode-p 'org-mode) (org-reveal)))
11000 (search (condition-case err
11001 (org-link-search search)
11002 ;; Save position before error-ing out so user
11003 ;; can easily move back to the original buffer.
11004 (error (funcall save-position-maybe)
11005 (error (nth 1 err)))))))
11006 ((functionp cmd)
11007 (save-match-data
11008 (set-match-data link-match-data)
11009 (condition-case nil
11010 (funcall cmd file link)
11011 ;; FIXME: Remove this check when most default installations
11012 ;; of Emacs have at least Org 9.0.
11013 ((debug wrong-number-of-arguments wrong-type-argument
11014 invalid-function)
11015 (user-error "Please see Org News for version 9.0 about \
11016 `org-file-apps'--Lisp error: %S" cmd)))))
11017 ((consp cmd)
11018 ;; FIXME: Remove this check when most default installations of
11019 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11020 ;; fall back to `org-link-frame-setup' for an old usage of
11021 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11022 (user-error "Please see Org News for version 9.0 about \
11023 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11024 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11025 (funcall save-position-maybe)))
11027 (defun org-file-apps-entry-match-against-dlink-p (entry)
11028 "This function returns non-nil if `entry' uses a regular
11029 expression which should be matched against the whole link by
11030 org-open-file.
11032 It assumes that is the case when the entry uses a regular
11033 expression which has at least one grouping construct and the
11034 action is either a lisp form or a command string containing
11035 `%1', i.e. using at least one subexpression match as a
11036 parameter."
11037 (let ((selector (car entry))
11038 (action (cdr entry)))
11039 (if (stringp selector)
11040 (and (> (regexp-opt-depth selector) 0)
11041 (or (and (stringp action)
11042 (string-match "%[0-9]" action))
11043 (consp action)))
11044 nil)))
11046 (defun org-default-apps ()
11047 "Return the default applications for this operating system."
11048 (cond
11049 ((eq system-type 'darwin)
11050 org-file-apps-defaults-macosx)
11051 ((eq system-type 'windows-nt)
11052 org-file-apps-defaults-windowsnt)
11053 (t org-file-apps-defaults-gnu)))
11055 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11056 "Convert extensions to regular expressions in the cars of LIST.
11057 Also, weed out any non-string entries, because the return value is used
11058 only for regexp matching.
11059 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11060 point to the symbol `emacs', indicating that the file should
11061 be opened in Emacs."
11062 (append
11063 (delq nil
11064 (mapcar (lambda (x)
11065 (unless (not (stringp (car x)))
11066 (if (string-match "\\W" (car x))
11068 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11069 list))
11070 (when add-auto-mode
11071 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11073 (defvar ange-ftp-name-format)
11074 (defun org-file-remote-p (file)
11075 "Test whether FILE specifies a location on a remote system.
11076 Return non-nil if the location is indeed remote.
11078 For example, the filename \"/user@host:/foo\" specifies a location
11079 on the system \"/user@host:\"."
11080 (cond ((fboundp 'file-remote-p)
11081 (file-remote-p file))
11082 ((fboundp 'tramp-handle-file-remote-p)
11083 (tramp-handle-file-remote-p file))
11084 ((and (boundp 'ange-ftp-name-format)
11085 (string-match (car ange-ftp-name-format) file))
11086 t)))
11089 ;;;; Refiling
11091 (defun org-get-org-file ()
11092 "Read a filename, with default directory `org-directory'."
11093 (let ((default (or org-default-notes-file remember-data-file)))
11094 (read-file-name (format "File name [%s]: " default)
11095 (file-name-as-directory org-directory)
11096 default)))
11098 (defun org-notes-order-reversed-p ()
11099 "Check if the current file should receive notes in reversed order."
11100 (cond
11101 ((not org-reverse-note-order) nil)
11102 ((eq t org-reverse-note-order) t)
11103 ((not (listp org-reverse-note-order)) nil)
11104 (t (catch 'exit
11105 (dolist (entry org-reverse-note-order)
11106 (when (string-match (car entry) buffer-file-name)
11107 (throw 'exit (cdr entry))))))))
11109 (defvar org-refile-target-table nil
11110 "The list of refile targets, created by `org-refile'.")
11112 (defvar org-agenda-new-buffers nil
11113 "Buffers created to visit agenda files.")
11115 (defvar org-refile-cache nil
11116 "Cache for refile targets.")
11118 (defvar org-refile-markers nil
11119 "All the markers used for caching refile locations.")
11121 (defun org-refile-marker (pos)
11122 "Get a new refile marker, but only if caching is in use."
11123 (if (not org-refile-use-cache)
11125 (let ((m (make-marker)))
11126 (move-marker m pos)
11127 (push m org-refile-markers)
11128 m)))
11130 (defun org-refile-cache-clear ()
11131 "Clear the refile cache and disable all the markers."
11132 (dolist (m org-refile-markers) (move-marker m nil))
11133 (setq org-refile-markers nil)
11134 (setq org-refile-cache nil)
11135 (message "Refile cache has been cleared"))
11137 (defun org-refile-cache-check-set (set)
11138 "Check if all the markers in the cache still have live buffers."
11139 (let (marker)
11140 (catch 'exit
11141 (while (and set (setq marker (nth 3 (pop set))))
11142 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11143 (when (and marker (null (marker-buffer marker)))
11144 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11145 (sit-for 3)
11146 (throw 'exit nil)))
11147 t)))
11149 (defun org-refile-cache-put (set &rest identifiers)
11150 "Push the refile targets SET into the cache, under IDENTIFIERS."
11151 (let* ((key (sha1 (prin1-to-string identifiers)))
11152 (entry (assoc key org-refile-cache)))
11153 (if entry
11154 (setcdr entry set)
11155 (push (cons key set) org-refile-cache))))
11157 (defun org-refile-cache-get (&rest identifiers)
11158 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11159 (cond
11160 ((not org-refile-cache) nil)
11161 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11163 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11164 org-refile-cache))))
11165 (and set (org-refile-cache-check-set set) set)))))
11167 (defvar org-outline-path-cache nil
11168 "Alist between buffer positions and outline paths.
11169 It value is an alist (POSITION . PATH) where POSITION is the
11170 buffer position at the beginning of an entry and PATH is a list
11171 of strings describing the outline path for that entry, in reverse
11172 order.")
11174 (defun org-refile-get-targets (&optional default-buffer)
11175 "Produce a table with refile targets."
11176 (let ((case-fold-search nil)
11177 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11178 (entries (or org-refile-targets '((nil . (:level . 1)))))
11179 targets tgs files desc descre)
11180 (message "Getting targets...")
11181 (with-current-buffer (or default-buffer (current-buffer))
11182 (dolist (entry entries)
11183 (setq files (car entry) desc (cdr entry))
11184 (cond
11185 ((null files) (setq files (list (current-buffer))))
11186 ((eq files 'org-agenda-files)
11187 (setq files (org-agenda-files 'unrestricted)))
11188 ((and (symbolp files) (fboundp files))
11189 (setq files (funcall files)))
11190 ((and (symbolp files) (boundp files))
11191 (setq files (symbol-value files))))
11192 (when (stringp files) (setq files (list files)))
11193 (cond
11194 ((eq (car desc) :tag)
11195 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11196 ((eq (car desc) :todo)
11197 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11198 ((eq (car desc) :regexp)
11199 (setq descre (cdr desc)))
11200 ((eq (car desc) :level)
11201 (setq descre (concat "^\\*\\{" (number-to-string
11202 (if org-odd-levels-only
11203 (1- (* 2 (cdr desc)))
11204 (cdr desc)))
11205 "\\}[ \t]")))
11206 ((eq (car desc) :maxlevel)
11207 (setq descre (concat "^\\*\\{1," (number-to-string
11208 (if org-odd-levels-only
11209 (1- (* 2 (cdr desc)))
11210 (cdr desc)))
11211 "\\}[ \t]")))
11212 (t (error "Bad refiling target description %s" desc)))
11213 (dolist (f files)
11214 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11216 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11217 (progn
11218 (when (bufferp f)
11219 (setq f (buffer-file-name (buffer-base-buffer f))))
11220 (setq f (and f (expand-file-name f)))
11221 (when (eq org-refile-use-outline-path 'file)
11222 (push (list (file-name-nondirectory f) f nil nil) tgs))
11223 (when (eq org-refile-use-outline-path 'buffer-name)
11224 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11225 (when (eq org-refile-use-outline-path 'full-file-path)
11226 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11227 (org-with-wide-buffer
11228 (goto-char (point-min))
11229 (setq org-outline-path-cache nil)
11230 (while (re-search-forward descre nil t)
11231 (beginning-of-line)
11232 (let ((case-fold-search nil))
11233 (looking-at org-complex-heading-regexp))
11234 (let ((begin (point))
11235 (heading (match-string-no-properties 4)))
11236 (unless (or (and
11237 org-refile-target-verify-function
11238 (not
11239 (funcall org-refile-target-verify-function)))
11240 (not heading))
11241 (let ((re (format org-complex-heading-regexp-format
11242 (regexp-quote heading)))
11243 (target
11244 (if (not org-refile-use-outline-path) heading
11245 (mapconcat
11246 #'identity
11247 (append
11248 (pcase org-refile-use-outline-path
11249 (`file (list (file-name-nondirectory
11250 (buffer-file-name
11251 (buffer-base-buffer)))))
11252 (`full-file-path
11253 (list (buffer-file-name
11254 (buffer-base-buffer))))
11255 (`buffer-name
11256 (list (buffer-name
11257 (buffer-base-buffer))))
11258 (_ nil))
11259 (mapcar (lambda (s) (replace-regexp-in-string
11260 "/" "\\/" s nil t))
11261 (org-get-outline-path t t)))
11262 "/"))))
11263 (push (list target f re (org-refile-marker (point)))
11264 tgs)))
11265 (when (= (point) begin)
11266 ;; Verification function has not moved point.
11267 (end-of-line)))))))
11268 (when org-refile-use-cache
11269 (org-refile-cache-put tgs (buffer-file-name) descre))
11270 (setq targets (append tgs targets))))))
11271 (message "Getting targets...done")
11272 (delete-dups (nreverse targets))))
11274 (defun org--get-outline-path-1 (&optional use-cache)
11275 "Return outline path to current headline.
11277 Outline path is a list of strings, in reverse order. When
11278 optional argument USE-CACHE is non-nil, make use of a cache. See
11279 `org-get-outline-path' for details.
11281 Assume buffer is widened and point is on a headline."
11282 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11283 (let ((p (point))
11284 (heading (let ((case-fold-search nil))
11285 (looking-at org-complex-heading-regexp)
11286 (if (not (match-end 4)) ""
11287 ;; Remove statistics cookies.
11288 (org-trim
11289 (org-link-display-format
11290 (replace-regexp-in-string
11291 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11292 (match-string-no-properties 4))))))))
11293 (if (org-up-heading-safe)
11294 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11295 (when use-cache
11296 (push (cons p path) org-outline-path-cache))
11297 path)
11298 ;; This is a new root node. Since we assume we are moving
11299 ;; forward, we can drop previous cache so as to limit number
11300 ;; of associations there.
11301 (let ((path (list heading)))
11302 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11303 path)))))
11305 (defun org-get-outline-path (&optional with-self use-cache)
11306 "Return the outline path to the current entry.
11308 An outline path is a list of ancestors for current headline, as
11309 a list of strings. Statistics cookies are removed and links are
11310 replaced with their description, if any, or their path otherwise.
11312 When optional argument WITH-SELF is non-nil, the path also
11313 includes the current headline.
11315 When optional argument USE-CACHE is non-nil, cache outline paths
11316 between calls to this function so as to avoid backtracking. This
11317 argument is useful when planning to find more than one outline
11318 path in the same document. In that case, there are two
11319 conditions to satisfy:
11320 - `org-outline-path-cache' is set to nil before starting the
11321 process;
11322 - outline paths are computed by increasing buffer positions."
11323 (org-with-wide-buffer
11324 (and (or (and with-self (org-back-to-heading t))
11325 (org-up-heading-safe))
11326 (reverse (org--get-outline-path-1 use-cache)))))
11328 (defun org-format-outline-path (path &optional width prefix separator)
11329 "Format the outline path PATH for display.
11330 WIDTH is the maximum number of characters that is available.
11331 PREFIX is a prefix to be included in the returned string,
11332 such as the file name.
11333 SEPARATOR is inserted between the different parts of the path,
11334 the default is \"/\"."
11335 (setq width (or width 79))
11336 (setq path (delq nil path))
11337 (unless (> width 0)
11338 (user-error "Argument `width' must be positive"))
11339 (setq separator (or separator "/"))
11340 (let* ((org-odd-levels-only nil)
11341 (fpath (concat
11342 prefix (and prefix path separator)
11343 (mapconcat
11344 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11345 (cl-loop for head in path
11346 for n from 0
11347 collect (org-add-props
11348 head nil 'face
11349 (nth (% n org-n-level-faces) org-level-faces)))
11350 separator))))
11351 (when (> (length fpath) width)
11352 (if (< width 7)
11353 ;; It's unlikely that `width' will be this small, but don't
11354 ;; waste characters by adding ".." if it is.
11355 (setq fpath (substring fpath 0 width))
11356 (setf (substring fpath (- width 2)) "..")))
11357 fpath))
11359 (defun org-display-outline-path (&optional file current separator just-return-string)
11360 "Display the current outline path in the echo area.
11362 If FILE is non-nil, prepend the output with the file name.
11363 If CURRENT is non-nil, append the current heading to the output.
11364 SEPARATOR is passed through to `org-format-outline-path'. It separates
11365 the different parts of the path and defaults to \"/\".
11366 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11367 (interactive "P")
11368 (let* (case-fold-search
11369 (bfn (buffer-file-name (buffer-base-buffer)))
11370 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11371 res)
11372 (when current (setq path (append path
11373 (save-excursion
11374 (org-back-to-heading t)
11375 (when (looking-at org-complex-heading-regexp)
11376 (list (match-string 4)))))))
11377 (setq res
11378 (org-format-outline-path
11379 path
11380 (1- (frame-width))
11381 (and file bfn (concat (file-name-nondirectory bfn) separator))
11382 separator))
11383 (if just-return-string
11384 (org-no-properties res)
11385 (org-unlogged-message "%s" res))))
11387 (defvar org-refile-history nil
11388 "History for refiling operations.")
11390 (defvar org-after-refile-insert-hook nil
11391 "Hook run after `org-refile' has inserted its stuff at the new location.
11392 Note that this is still *before* the stuff will be removed from
11393 the *old* location.")
11395 (defvar org-capture-last-stored-marker)
11396 (defvar org-refile-keep nil
11397 "Non-nil means `org-refile' will copy instead of refile.")
11399 (defun org-copy ()
11400 "Like `org-refile', but copy."
11401 (interactive)
11402 (let ((org-refile-keep t))
11403 (funcall 'org-refile nil nil nil "Copy")))
11405 (defun org-refile (&optional arg default-buffer rfloc msg)
11406 "Move the entry or entries at point to another heading.
11408 The list of target headings is compiled using the information in
11409 `org-refile-targets', which see.
11411 At the target location, the entry is filed as a subitem of the
11412 target heading. Depending on `org-reverse-note-order', the new
11413 subitem will either be the first or the last subitem.
11415 If there is an active region, all entries in that region will be
11416 refiled. However, the region must fulfill the requirement that
11417 the first heading sets the top-level of the moved text.
11419 With a `\\[universal-argument]' ARG, the command will only visit the target \
11420 location
11421 and not actually move anything.
11423 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11424 location where the last
11425 refiling operation has put the subtree.
11427 With a numeric prefix argument of `2', refile to the running clock.
11429 With a numeric prefix argument of `3', emulate `org-refile-keep'
11430 being set to t and copy to the target location, don't move it.
11431 Beware that keeping refiled entries may result in duplicated ID
11432 properties.
11434 RFLOC can be a refile location obtained in a different way.
11436 MSG is a string to replace \"Refile\" in the default prompt with
11437 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11439 See also `org-refile-use-outline-path'.
11441 If you are using target caching (see `org-refile-use-cache'), you
11442 have to clear the target cache in order to find new targets.
11443 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11444 prefix argument (`C-u C-u C-u C-c C-w')."
11445 (interactive "P")
11446 (if (member arg '(0 (64)))
11447 (org-refile-cache-clear)
11448 (let* ((actionmsg (cond (msg msg)
11449 ((equal arg 3) "Refile (and keep)")
11450 (t "Refile")))
11451 (regionp (org-region-active-p))
11452 (region-start (and regionp (region-beginning)))
11453 (region-end (and regionp (region-end)))
11454 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11455 pos it nbuf file level reversed)
11456 (setq last-command nil)
11457 (when regionp
11458 (goto-char region-start)
11459 (or (bolp) (goto-char (point-at-bol)))
11460 (setq region-start (point))
11461 (unless (or (org-kill-is-subtree-p
11462 (buffer-substring region-start region-end))
11463 (prog1 org-refile-active-region-within-subtree
11464 (let ((s (point-at-eol)))
11465 (org-toggle-heading)
11466 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11467 (user-error "The region is not a (sequence of) subtree(s)")))
11468 (if (equal arg '(16))
11469 (org-refile-goto-last-stored)
11470 (when (or
11471 (and (equal arg 2)
11472 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11473 (prog1
11474 (setq it (list (or org-clock-heading "running clock")
11475 (buffer-file-name
11476 (marker-buffer org-clock-hd-marker))
11478 (marker-position org-clock-hd-marker)))
11479 (setq arg nil)))
11480 (setq it
11481 (or rfloc
11482 (let (heading-text)
11483 (save-excursion
11484 (unless (and arg (listp arg))
11485 (org-back-to-heading t)
11486 (setq heading-text
11487 (replace-regexp-in-string
11488 org-bracket-link-regexp
11489 "\\3"
11490 (or (nth 4 (org-heading-components))
11491 ""))))
11492 (org-refile-get-location
11493 (cond ((and arg (listp arg)) "Goto")
11494 (regionp (concat actionmsg " region to"))
11495 (t (concat actionmsg " subtree \""
11496 heading-text "\" to")))
11497 default-buffer
11498 (and (not (equal '(4) arg))
11499 org-refile-allow-creating-parent-nodes)))))))
11500 (setq file (nth 1 it)
11501 pos (nth 3 it))
11502 (when (and (not arg)
11504 (equal (buffer-file-name) file)
11505 (if regionp
11506 (and (>= pos region-start)
11507 (<= pos region-end))
11508 (and (>= pos (point))
11509 (< pos (save-excursion
11510 (org-end-of-subtree t t))))))
11511 (error "Cannot refile to position inside the tree or region"))
11512 (setq nbuf (or (find-buffer-visiting file)
11513 (find-file-noselect file)))
11514 (if (and arg (not (equal arg 3)))
11515 (progn
11516 (pop-to-buffer-same-window nbuf)
11517 (goto-char (cond (pos)
11518 ((org-notes-order-reversed-p) (point-min))
11519 (t (point-max))))
11520 (org-show-context 'org-goto))
11521 (if regionp
11522 (progn
11523 (org-kill-new (buffer-substring region-start region-end))
11524 (org-save-markers-in-region region-start region-end))
11525 (org-copy-subtree 1 nil t))
11526 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11527 (find-file-noselect file)))
11528 (setq reversed (org-notes-order-reversed-p))
11529 (org-with-wide-buffer
11530 (if pos
11531 (progn
11532 (goto-char pos)
11533 (setq level (org-get-valid-level (funcall outline-level) 1))
11534 (goto-char
11535 (if reversed
11536 (or (outline-next-heading) (point-max))
11537 (or (save-excursion (org-get-next-sibling))
11538 (org-end-of-subtree t t)
11539 (point-max)))))
11540 (setq level 1)
11541 (if (not reversed)
11542 (goto-char (point-max))
11543 (goto-char (point-min))
11544 (or (outline-next-heading) (goto-char (point-max)))))
11545 (unless (bolp) (newline))
11546 (org-paste-subtree level nil nil t)
11547 (when org-log-refile
11548 (org-add-log-setup 'refile nil nil org-log-refile)
11549 (unless (eq org-log-refile 'note)
11550 (save-excursion (org-add-log-note))))
11551 (and org-auto-align-tags
11552 (let ((org-loop-over-headlines-in-active-region nil))
11553 (org-set-tags nil t)))
11554 (let ((bookmark-name (plist-get org-bookmark-names-plist
11555 :last-refile)))
11556 (when bookmark-name
11557 (with-demoted-errors
11558 (bookmark-set bookmark-name))))
11559 ;; If we are refiling for capture, make sure that the
11560 ;; last-capture pointers point here
11561 (when (bound-and-true-p org-capture-is-refiling)
11562 (let ((bookmark-name (plist-get org-bookmark-names-plist
11563 :last-capture-marker)))
11564 (when bookmark-name
11565 (with-demoted-errors
11566 (bookmark-set bookmark-name))))
11567 (move-marker org-capture-last-stored-marker (point)))
11568 (when (fboundp 'deactivate-mark) (deactivate-mark))
11569 (run-hooks 'org-after-refile-insert-hook)))
11570 (unless org-refile-keep
11571 (if regionp
11572 (delete-region (point) (+ (point) (- region-end region-start)))
11573 (org-preserve-local-variables
11574 (delete-region
11575 (and (org-back-to-heading t) (point))
11576 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11577 (when (featurep 'org-inlinetask)
11578 (org-inlinetask-remove-END-maybe))
11579 (setq org-markers-to-move nil)
11580 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11582 (defun org-refile-goto-last-stored ()
11583 "Go to the location where the last refile was stored."
11584 (interactive)
11585 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11586 (message "This is the location of the last refile"))
11588 (defun org-refile--get-location (refloc tbl)
11589 "When user refile to REFLOC, find the associated target in TBL.
11590 Also check `org-refile-target-table'."
11591 (car (delq
11593 (mapcar
11594 (lambda (r) (or (assoc r tbl)
11595 (assoc r org-refile-target-table)))
11596 (list (replace-regexp-in-string "/$" "" refloc)
11597 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11599 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11600 "Prompt the user for a refile location, using PROMPT.
11601 PROMPT should not be suffixed with a colon and a space, because
11602 this function appends the default value from
11603 `org-refile-history' automatically, if that is not empty."
11604 (let ((org-refile-targets org-refile-targets)
11605 (org-refile-use-outline-path org-refile-use-outline-path))
11606 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11607 (unless org-refile-target-table
11608 (user-error "No refile targets"))
11609 (let* ((cbuf (current-buffer))
11610 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11611 (cfunc (if (and org-refile-use-outline-path
11612 org-outline-path-complete-in-steps)
11613 #'org-olpath-completing-read
11614 #'completing-read))
11615 (extra (if org-refile-use-outline-path "/" ""))
11616 (cbnex (concat (buffer-name) extra))
11617 (filename (and cfn (expand-file-name cfn)))
11618 (tbl (mapcar
11619 (lambda (x)
11620 (if (and (not (member org-refile-use-outline-path
11621 '(file full-file-path)))
11622 (not (equal filename (nth 1 x))))
11623 (cons (concat (car x) extra " ("
11624 (file-name-nondirectory (nth 1 x)) ")")
11625 (cdr x))
11626 (cons (concat (car x) extra) (cdr x))))
11627 org-refile-target-table))
11628 (completion-ignore-case t)
11629 cdef
11630 (prompt (concat prompt
11631 (or (and (car org-refile-history)
11632 (concat " (default " (car org-refile-history) ")"))
11633 (and (assoc cbnex tbl) (setq cdef cbnex)
11634 (concat " (default " cbnex ")"))) ": "))
11635 pa answ parent-target child parent old-hist)
11636 (setq old-hist org-refile-history)
11637 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11638 nil 'org-refile-history (or cdef (car org-refile-history))))
11639 (if (setq pa (org-refile--get-location answ tbl))
11640 (progn
11641 (org-refile-check-position pa)
11642 (when (or (not org-refile-history)
11643 (not (eq old-hist org-refile-history))
11644 (not (equal (car pa) (car org-refile-history))))
11645 (setq org-refile-history
11646 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11647 org-refile-history
11648 (cdr org-refile-history))))
11649 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11650 (pop org-refile-history)))
11652 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11653 (progn
11654 (setq parent (match-string 1 answ)
11655 child (match-string 2 answ))
11656 (setq parent-target (org-refile--get-location parent tbl))
11657 (when (and parent-target
11658 (or (eq new-nodes t)
11659 (and (eq new-nodes 'confirm)
11660 (y-or-n-p (format "Create new node \"%s\"? "
11661 child)))))
11662 (org-refile-new-child parent-target child)))
11663 (user-error "Invalid target location")))))
11665 (declare-function org-string-nw-p "org-macs" (s))
11666 (defun org-refile-check-position (refile-pointer)
11667 "Check if the refile pointer matches the headline to which it points."
11668 (let* ((file (nth 1 refile-pointer))
11669 (re (nth 2 refile-pointer))
11670 (pos (nth 3 refile-pointer))
11671 buffer)
11672 (if (and (not (markerp pos)) (not file))
11673 (user-error "Please indicate a target file in the refile path")
11674 (when (org-string-nw-p re)
11675 (setq buffer (if (markerp pos)
11676 (marker-buffer pos)
11677 (or (find-buffer-visiting file)
11678 (find-file-noselect file))))
11679 (with-current-buffer buffer
11680 (org-with-wide-buffer
11681 (goto-char pos)
11682 (beginning-of-line 1)
11683 (unless (looking-at-p re)
11684 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11686 (defun org-refile-new-child (parent-target child)
11687 "Use refile target PARENT-TARGET to add new CHILD below it."
11688 (unless parent-target
11689 (error "Cannot find parent for new node"))
11690 (let ((file (nth 1 parent-target))
11691 (pos (nth 3 parent-target))
11692 level)
11693 (with-current-buffer (or (find-buffer-visiting file)
11694 (find-file-noselect file))
11695 (org-with-wide-buffer
11696 (if pos
11697 (goto-char pos)
11698 (goto-char (point-max))
11699 (unless (bolp) (newline)))
11700 (when (looking-at org-outline-regexp)
11701 (setq level (funcall outline-level))
11702 (org-end-of-subtree t t))
11703 (org-back-over-empty-lines)
11704 (insert "\n" (make-string
11705 (if pos (org-get-valid-level level 1) 1) ?*)
11706 " " child "\n")
11707 (beginning-of-line 0)
11708 (list (concat (car parent-target) "/" child) file "" (point))))))
11710 (defun org-olpath-completing-read (prompt collection &rest args)
11711 "Read an outline path like a file name."
11712 (let ((thetable collection))
11713 (apply #'completing-read
11714 prompt
11715 (lambda (string predicate &optional flag)
11716 (cond
11717 ((eq flag nil) (try-completion string thetable))
11718 ((eq flag t)
11719 (let ((l (length string)))
11720 (mapcar (lambda (x)
11721 (let ((r (substring x l))
11722 (f (if (string-match " ([^)]*)$" x)
11723 (match-string 0 x)
11724 "")))
11725 (if (string-match "/" r)
11726 (concat string (substring r 0 (match-end 0)) f)
11727 x)))
11728 (all-completions string thetable predicate))))
11729 ;; Exact match?
11730 ((eq flag 'lambda) (assoc string thetable))))
11731 args)))
11733 ;;;; Dynamic blocks
11735 (defun org-find-dblock (name)
11736 "Find the first dynamic block with name NAME in the buffer.
11737 If not found, stay at current position and return nil."
11738 (let ((case-fold-search t) pos)
11739 (save-excursion
11740 (goto-char (point-min))
11741 (setq pos (and (re-search-forward
11742 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11743 (match-beginning 0))))
11744 (when pos (goto-char pos))
11745 pos))
11747 (defun org-create-dblock (plist)
11748 "Create a dynamic block section, with parameters taken from PLIST.
11749 PLIST must contain a :name entry which is used as the name of the block."
11750 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11751 (end-of-line 1)
11752 (newline))
11753 (let ((col (current-column))
11754 (name (plist-get plist :name)))
11755 (insert "#+BEGIN: " name)
11756 (while plist
11757 (if (eq (car plist) :name)
11758 (setq plist (cddr plist))
11759 (insert " " (prin1-to-string (pop plist)))))
11760 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11761 (beginning-of-line -2)))
11763 (defun org-prepare-dblock ()
11764 "Prepare dynamic block for refresh.
11765 This empties the block, puts the cursor at the insert position and returns
11766 the property list including an extra property :name with the block name."
11767 (unless (looking-at org-dblock-start-re)
11768 (user-error "Not at a dynamic block"))
11769 (let* ((begdel (1+ (match-end 0)))
11770 (name (org-no-properties (match-string 1)))
11771 (params (append (list :name name)
11772 (read (concat "(" (match-string 3) ")")))))
11773 (save-excursion
11774 (beginning-of-line 1)
11775 (skip-chars-forward " \t")
11776 (setq params (plist-put params :indentation-column (current-column))))
11777 (unless (re-search-forward org-dblock-end-re nil t)
11778 (error "Dynamic block not terminated"))
11779 (setq params
11780 (append params
11781 (list :content (buffer-substring
11782 begdel (match-beginning 0)))))
11783 (delete-region begdel (match-beginning 0))
11784 (goto-char begdel)
11785 (open-line 1)
11786 params))
11788 (defun org-map-dblocks (&optional command)
11789 "Apply COMMAND to all dynamic blocks in the current buffer.
11790 If COMMAND is not given, use `org-update-dblock'."
11791 (let ((cmd (or command 'org-update-dblock)))
11792 (save-excursion
11793 (goto-char (point-min))
11794 (while (re-search-forward org-dblock-start-re nil t)
11795 (goto-char (match-beginning 0))
11796 (save-excursion
11797 (condition-case nil
11798 (funcall cmd)
11799 (error (message "Error during update of dynamic block"))))
11800 (unless (re-search-forward org-dblock-end-re nil t)
11801 (error "Dynamic block not terminated"))))))
11803 (defun org-dblock-update (&optional arg)
11804 "User command for updating dynamic blocks.
11805 Update the dynamic block at point. With prefix ARG, update all dynamic
11806 blocks in the buffer."
11807 (interactive "P")
11808 (if arg
11809 (org-update-all-dblocks)
11810 (or (looking-at org-dblock-start-re)
11811 (org-beginning-of-dblock))
11812 (org-update-dblock)))
11814 (defun org-update-dblock ()
11815 "Update the dynamic block at point.
11816 This means to empty the block, parse for parameters and then call
11817 the correct writing function."
11818 (interactive)
11819 (save-excursion
11820 (let* ((win (selected-window))
11821 (pos (point))
11822 (line (org-current-line))
11823 (params (org-prepare-dblock))
11824 (name (plist-get params :name))
11825 (indent (plist-get params :indentation-column))
11826 (cmd (intern (concat "org-dblock-write:" name))))
11827 (message "Updating dynamic block `%s' at line %d..." name line)
11828 (funcall cmd params)
11829 (message "Updating dynamic block `%s' at line %d...done" name line)
11830 (goto-char pos)
11831 (when (and indent (> indent 0))
11832 (setq indent (make-string indent ?\ ))
11833 (save-excursion
11834 (select-window win)
11835 (org-beginning-of-dblock)
11836 (forward-line 1)
11837 (while (not (looking-at org-dblock-end-re))
11838 (insert indent)
11839 (beginning-of-line 2))
11840 (when (looking-at org-dblock-end-re)
11841 (and (looking-at "[ \t]+")
11842 (replace-match ""))
11843 (insert indent)))))))
11845 (defun org-beginning-of-dblock ()
11846 "Find the beginning of the dynamic block at point.
11847 Error if there is no such block at point."
11848 (let ((pos (point))
11849 beg)
11850 (end-of-line 1)
11851 (if (and (re-search-backward org-dblock-start-re nil t)
11852 (setq beg (match-beginning 0))
11853 (re-search-forward org-dblock-end-re nil t)
11854 (> (match-end 0) pos))
11855 (goto-char beg)
11856 (goto-char pos)
11857 (error "Not in a dynamic block"))))
11859 (defun org-update-all-dblocks ()
11860 "Update all dynamic blocks in the buffer.
11861 This function can be used in a hook."
11862 (interactive)
11863 (when (derived-mode-p 'org-mode)
11864 (org-map-dblocks 'org-update-dblock)))
11867 ;;;; Completion
11869 (declare-function org-export-backend-options "ox" (cl-x) t)
11870 (defun org-get-export-keywords ()
11871 "Return a list of all currently understood export keywords.
11872 Export keywords include options, block names, attributes and
11873 keywords relative to each registered export back-end."
11874 (let (keywords)
11875 (dolist (backend
11876 (bound-and-true-p org-export-registered-backends)
11877 (delq nil keywords))
11878 ;; Back-end name (for keywords, like #+LATEX:)
11879 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11880 (dolist (option-entry (org-export-backend-options backend))
11881 ;; Back-end options.
11882 (push (nth 1 option-entry) keywords)))))
11884 (defconst org-options-keywords
11885 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11886 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11887 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11888 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11889 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11891 (defcustom org-structure-template-alist
11892 '((?a . "export ascii")
11893 (?c . "center")
11894 (?C . "comment")
11895 (?e . "example")
11896 (?E . "export")
11897 (?h . "export html")
11898 (?l . "export latex")
11899 (?q . "quote")
11900 (?s . "src")
11901 (?v . "verse"))
11902 "Structure completion elements.
11903 This is an alist of characters and values. When
11904 `org-insert-structure-template' is called, an additional key is
11905 read. The key is first looked up in this alist, and the
11906 corresponding structure is inserted, with \"#+BEGIN_\" and
11907 \"#+END_\" added automatically."
11908 :group 'org-edit-structure
11909 :type '(repeat
11910 (cons (character :tag "Key")
11911 (string :tag "Template")))
11912 :package-version '(Org . "9.2"))
11914 (defun org-insert-structure-template (type)
11915 "Insert a block structure of the type #+begin_foo/#+end_foo.
11916 First read a character, which can be one of the keys in
11917 `org-structure-template-alist'. When it is <TAB>, prompt the
11918 user for a string to use. With an active region, wrap the region
11919 in the block. Otherwise, insert an empty block."
11920 (interactive
11921 (list
11922 (let* ((key (read-key "Key: "))
11923 (struct-string
11924 (or (cdr (assq key org-structure-template-alist))
11925 (and (= key ?\t)
11926 (read-string "Structure type: "))
11927 (user-error "`%c' has no structure definition" key))))
11928 struct-string)))
11929 (let* ((region? (use-region-p))
11930 (s (if region? (region-beginning) (point)))
11931 (e (copy-marker (if region? (region-end) (point)) t))
11932 column)
11933 (when (string-match-p
11934 (concat "\\`" (regexp-opt '("example" "export" "src")))
11935 type)
11936 (org-escape-code-in-region s e))
11937 (goto-char s)
11938 (setq column (current-indentation))
11939 (beginning-of-line)
11940 (indent-to column)
11941 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11942 (goto-char e)
11943 (if (bolp)
11944 (progn
11945 (skip-chars-backward " \n\t")
11946 (forward-line))
11947 (end-of-line)
11948 (insert "\n"))
11949 (indent-to column)
11950 (insert (format "#+end_%s\n"
11951 (car (split-string type))))
11952 (when (or (not region?)
11953 (string-match-p "src\\|\\`export\\'" type))
11954 (goto-char s)
11955 (end-of-line))
11956 (set-marker e nil)))
11958 ;;;; TODO, DEADLINE, Comments
11960 (defun org-toggle-comment ()
11961 "Change the COMMENT state of an entry."
11962 (interactive)
11963 (save-excursion
11964 (org-back-to-heading)
11965 (let ((case-fold-search nil))
11966 (looking-at org-complex-heading-regexp))
11967 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11968 (skip-chars-forward " \t")
11969 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11970 (if (org-in-commented-heading-p t)
11971 (delete-region (point)
11972 (progn (search-forward " " (line-end-position) 'move)
11973 (skip-chars-forward " \t")
11974 (point)))
11975 (insert org-comment-string)
11976 (unless (eolp) (insert " ")))))
11978 (defvar org-last-todo-state-is-todo nil
11979 "This is non-nil when the last TODO state change led to a TODO state.
11980 If the last change removed the TODO tag or switched to DONE, then
11981 this is nil.")
11983 (defvar org-setting-tags nil) ; dynamically skipped
11985 (defvar org-todo-setup-filter-hook nil
11986 "Hook for functions that pre-filter todo specs.
11987 Each function takes a todo spec and returns either nil or the spec
11988 transformed into canonical form." )
11990 (defvar org-todo-get-default-hook nil
11991 "Hook for functions that get a default item for todo.
11992 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11993 nil or a string to be used for the todo mark." )
11995 (defvar org-agenda-headline-snapshot-before-repeat)
11997 (defun org-current-effective-time ()
11998 "Return current time adjusted for `org-extend-today-until' variable."
11999 (let* ((ct (org-current-time))
12000 (dct (decode-time ct))
12001 (ct1
12002 (cond
12003 (org-use-last-clock-out-time-as-effective-time
12004 (or (org-clock-get-last-clock-out-time) ct))
12005 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12006 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12007 (t ct))))
12008 ct1))
12010 (defun org-todo-yesterday (&optional arg)
12011 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12012 (interactive "P")
12013 (if (eq major-mode 'org-agenda-mode)
12014 (apply 'org-agenda-todo-yesterday arg)
12015 (let* ((org-use-effective-time t)
12016 (hour (nth 2 (decode-time (org-current-time))))
12017 (org-extend-today-until (1+ hour)))
12018 (org-todo arg))))
12020 (defvar org-block-entry-blocking ""
12021 "First entry preventing the TODO state change.")
12023 (defun org-cancel-repeater ()
12024 "Cancel a repeater by setting its numeric value to zero."
12025 (interactive)
12026 (save-excursion
12027 (org-back-to-heading t)
12028 (let ((bound1 (point))
12029 (bound0 (save-excursion (outline-next-heading) (point))))
12030 (when (and (re-search-forward
12031 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12032 org-deadline-time-regexp "\\)\\|\\("
12033 org-ts-regexp "\\)")
12034 bound0 t)
12035 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12036 bound1 t))
12037 (replace-match "0" t nil nil 1)))))
12039 (defvar org-state)
12040 (defvar org-blocked-by-checkboxes)
12041 (defun org-todo (&optional arg)
12042 "Change the TODO state of an item.
12044 The state of an item is given by a keyword at the start of the heading,
12045 like
12046 *** TODO Write paper
12047 *** DONE Call mom
12049 The different keywords are specified in the variable `org-todo-keywords'.
12050 By default the available states are \"TODO\" and \"DONE\". So, for this
12051 example: when the item starts with TODO, it is changed to DONE.
12052 When it starts with DONE, the DONE is removed. And when neither TODO nor
12053 DONE are present, add TODO at the beginning of the heading.
12055 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12056 state.
12057 With numeric prefix ARG, switch to that state.
12058 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12059 next set of TODO \
12060 keywords (nextset).
12061 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12062 prefix, circumvent any state blocking.
12063 With a numeric prefix arg of 0, inhibit note taking for the change.
12064 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12066 When called through ELisp, arg is also interpreted in the following way:
12067 `none' -> empty state
12068 \"\" -> switch to empty state
12069 `done' -> switch to DONE
12070 `nextset' -> switch to the next set of keywords
12071 `previousset' -> switch to the previous set of keywords
12072 \"WAITING\" -> switch to the specified keyword, but only if it
12073 really is a member of `org-todo-keywords'."
12074 (interactive "P")
12075 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12076 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12077 'region-start-level 'region))
12078 org-loop-over-headlines-in-active-region)
12079 (org-map-entries
12080 `(org-todo ,arg)
12081 org-loop-over-headlines-in-active-region
12082 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12083 (when (equal arg '(16)) (setq arg 'nextset))
12084 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12085 (let ((org-blocker-hook org-blocker-hook)
12086 commentp
12087 case-fold-search)
12088 (when (equal arg '(64))
12089 (setq arg nil org-blocker-hook nil))
12090 (when (and org-blocker-hook
12091 (or org-inhibit-blocking
12092 (org-entry-get nil "NOBLOCKING")))
12093 (setq org-blocker-hook nil))
12094 (save-excursion
12095 (catch 'exit
12096 (org-back-to-heading t)
12097 (when (org-in-commented-heading-p t)
12098 (org-toggle-comment)
12099 (setq commentp t))
12100 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12101 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12102 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12103 (let* ((match-data (match-data))
12104 (startpos (copy-marker (line-beginning-position)))
12105 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12106 (org-log-done org-log-done)
12107 (org-log-repeat org-log-repeat)
12108 (org-todo-log-states org-todo-log-states)
12109 (org-inhibit-logging
12110 (if (equal arg 0)
12111 (progn (setq arg nil) 'note) org-inhibit-logging))
12112 (this (match-string 1))
12113 (hl-pos (match-beginning 0))
12114 (head (org-get-todo-sequence-head this))
12115 (ass (assoc head org-todo-kwd-alist))
12116 (interpret (nth 1 ass))
12117 (done-word (nth 3 ass))
12118 (final-done-word (nth 4 ass))
12119 (org-last-state (or this ""))
12120 (completion-ignore-case t)
12121 (member (member this org-todo-keywords-1))
12122 (tail (cdr member))
12123 (org-state (cond
12124 ((and org-todo-key-trigger
12125 (or (and (equal arg '(4))
12126 (eq org-use-fast-todo-selection 'prefix))
12127 (and (not arg) org-use-fast-todo-selection
12128 (not (eq org-use-fast-todo-selection
12129 'prefix)))))
12130 ;; Use fast selection.
12131 (org-fast-todo-selection))
12132 ((and (equal arg '(4))
12133 (or (not org-use-fast-todo-selection)
12134 (not org-todo-key-trigger)))
12135 ;; Read a state with completion.
12136 (completing-read
12137 "State: " (mapcar #'list org-todo-keywords-1)
12138 nil t))
12139 ((eq arg 'right)
12140 (if this
12141 (if tail (car tail) nil)
12142 (car org-todo-keywords-1)))
12143 ((eq arg 'left)
12144 (unless (equal member org-todo-keywords-1)
12145 (if this
12146 (nth (- (length org-todo-keywords-1)
12147 (length tail) 2)
12148 org-todo-keywords-1)
12149 (org-last org-todo-keywords-1))))
12150 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12151 (setq arg nil))) ;hack to fall back to cycling
12152 (arg
12153 ;; User or caller requests a specific state.
12154 (cond
12155 ((equal arg "") nil)
12156 ((eq arg 'none) nil)
12157 ((eq arg 'done) (or done-word (car org-done-keywords)))
12158 ((eq arg 'nextset)
12159 (or (car (cdr (member head org-todo-heads)))
12160 (car org-todo-heads)))
12161 ((eq arg 'previousset)
12162 (let ((org-todo-heads (reverse org-todo-heads)))
12163 (or (car (cdr (member head org-todo-heads)))
12164 (car org-todo-heads))))
12165 ((car (member arg org-todo-keywords-1)))
12166 ((stringp arg)
12167 (user-error "State `%s' not valid in this file" arg))
12168 ((nth (1- (prefix-numeric-value arg))
12169 org-todo-keywords-1))))
12170 ((null member) (or head (car org-todo-keywords-1)))
12171 ((equal this final-done-word) nil) ;-> make empty
12172 ((null tail) nil) ;-> first entry
12173 ((memq interpret '(type priority))
12174 (if (eq this-command last-command)
12175 (car tail)
12176 (if (> (length tail) 0)
12177 (or done-word (car org-done-keywords))
12178 nil)))
12180 (car tail))))
12181 (org-state (or
12182 (run-hook-with-args-until-success
12183 'org-todo-get-default-hook org-state org-last-state)
12184 org-state))
12185 (next (if org-state (concat " " org-state " ") " "))
12186 (change-plist (list :type 'todo-state-change :from this :to org-state
12187 :position startpos))
12188 dolog now-done-p)
12189 (when org-blocker-hook
12190 (let (org-blocked-by-checkboxes block-reason)
12191 (setq org-last-todo-state-is-todo
12192 (not (member this org-done-keywords)))
12193 (unless (save-excursion
12194 (save-match-data
12195 (org-with-wide-buffer
12196 (run-hook-with-args-until-failure
12197 'org-blocker-hook change-plist))))
12198 (setq block-reason (if org-blocked-by-checkboxes
12199 "contained checkboxes"
12200 (format "\"%s\"" org-block-entry-blocking)))
12201 (if (called-interactively-p 'interactive)
12202 (user-error "TODO state change from %s to %s blocked (by %s)"
12203 this org-state block-reason)
12204 ;; Fail silently.
12205 (message "TODO state change from %s to %s blocked (by %s)"
12206 this org-state block-reason)
12207 (throw 'exit nil)))))
12208 (store-match-data match-data)
12209 (replace-match next t t)
12210 (cond ((equal this org-state)
12211 (message "TODO state was already %s" (org-trim next)))
12212 ((not (pos-visible-in-window-p hl-pos))
12213 (message "TODO state changed to %s" (org-trim next))))
12214 (unless head
12215 (setq head (org-get-todo-sequence-head org-state)
12216 ass (assoc head org-todo-kwd-alist)
12217 interpret (nth 1 ass)
12218 done-word (nth 3 ass)
12219 final-done-word (nth 4 ass)))
12220 (when (memq arg '(nextset previousset))
12221 (message "Keyword-Set %d/%d: %s"
12222 (- (length org-todo-sets) -1
12223 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12224 (length org-todo-sets)
12225 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12226 (setq org-last-todo-state-is-todo
12227 (not (member org-state org-done-keywords)))
12228 (setq now-done-p (and (member org-state org-done-keywords)
12229 (not (member this org-done-keywords))))
12230 (and logging (org-local-logging logging))
12231 (when (and (or org-todo-log-states org-log-done)
12232 (not (eq org-inhibit-logging t))
12233 (not (memq arg '(nextset previousset))))
12234 ;; We need to look at recording a time and note.
12235 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12236 (nth 2 (assoc this org-todo-log-states))))
12237 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12238 (setq dolog 'time))
12239 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12240 (and org-state
12241 (member org-state org-not-done-keywords)
12242 (not (member this org-not-done-keywords))))
12243 ;; This is now a todo state and was not one before
12244 ;; If there was a CLOSED time stamp, get rid of it.
12245 (org-add-planning-info nil nil 'closed))
12246 (when (and now-done-p org-log-done)
12247 ;; It is now done, and it was not done before.
12248 (org-add-planning-info 'closed (org-current-effective-time))
12249 (when (and (not dolog) (eq 'note org-log-done))
12250 (org-add-log-setup 'done org-state this 'note)))
12251 (when (and org-state dolog)
12252 ;; This is a non-nil state, and we need to log it.
12253 (org-add-log-setup 'state org-state this dolog)))
12254 ;; Fixup tag positioning.
12255 (org-todo-trigger-tag-changes org-state)
12256 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12257 (when org-provide-todo-statistics
12258 (org-update-parent-todo-statistics))
12259 (run-hooks 'org-after-todo-state-change-hook)
12260 (when (and arg (not (member org-state org-done-keywords)))
12261 (setq head (org-get-todo-sequence-head org-state)))
12262 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12263 ;; Do we need to trigger a repeat?
12264 (when now-done-p
12265 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12266 ;; This is for the agenda, take a snapshot of the headline.
12267 (save-match-data
12268 (setq org-agenda-headline-snapshot-before-repeat
12269 (org-get-heading))))
12270 (org-auto-repeat-maybe org-state))
12271 ;; Fixup cursor location if close to the keyword.
12272 (when (and (outline-on-heading-p)
12273 (not (bolp))
12274 (save-excursion (beginning-of-line 1)
12275 (looking-at org-todo-line-regexp))
12276 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12277 (goto-char (or (match-end 2) (match-end 1)))
12278 (and (looking-at " ") (just-one-space)))
12279 (when org-trigger-hook
12280 (save-excursion
12281 (run-hook-with-args 'org-trigger-hook change-plist)))
12282 (when commentp (org-toggle-comment))))))))
12284 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12285 "Block turning an entry into a TODO, using the hierarchy.
12286 This checks whether the current task should be blocked from state
12287 changes. Such blocking occurs when:
12289 1. The task has children which are not all in a completed state.
12291 2. A task has a parent with the property :ORDERED:, and there
12292 are siblings prior to the current task with incomplete
12293 status.
12295 3. The parent of the task is blocked because it has siblings that should
12296 be done first, or is child of a block grandparent TODO entry."
12298 (if (not org-enforce-todo-dependencies)
12299 t ; if locally turned off don't block
12300 (catch 'dont-block
12301 ;; If this is not a todo state change, or if this entry is already DONE,
12302 ;; do not block
12303 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12304 (member (plist-get change-plist :from)
12305 (cons 'done org-done-keywords))
12306 (member (plist-get change-plist :to)
12307 (cons 'todo org-not-done-keywords))
12308 (not (plist-get change-plist :to)))
12309 (throw 'dont-block t))
12310 ;; If this task has children, and any are undone, it's blocked
12311 (save-excursion
12312 (org-back-to-heading t)
12313 (let ((this-level (funcall outline-level)))
12314 (outline-next-heading)
12315 (let ((child-level (funcall outline-level)))
12316 (while (and (not (eobp))
12317 (> child-level this-level))
12318 ;; this todo has children, check whether they are all
12319 ;; completed
12320 (when (and (not (org-entry-is-done-p))
12321 (org-entry-is-todo-p))
12322 (setq org-block-entry-blocking (org-get-heading))
12323 (throw 'dont-block nil))
12324 (outline-next-heading)
12325 (setq child-level (funcall outline-level))))))
12326 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12327 ;; any previous siblings are undone, it's blocked
12328 (save-excursion
12329 (org-back-to-heading t)
12330 (let* ((pos (point))
12331 (parent-pos (and (org-up-heading-safe) (point)))
12332 (case-fold-search nil))
12333 (unless parent-pos (throw 'dont-block t)) ; no parent
12334 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12335 (forward-line 1)
12336 (re-search-forward org-not-done-heading-regexp pos t))
12337 (setq org-block-entry-blocking (match-string 0))
12338 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12339 ;; Search further up the hierarchy, to see if an ancestor is blocked
12340 (while t
12341 (goto-char parent-pos)
12342 (unless (looking-at org-not-done-heading-regexp)
12343 (throw 'dont-block t)) ; do not block, parent is not a TODO
12344 (setq pos (point))
12345 (setq parent-pos (and (org-up-heading-safe) (point)))
12346 (unless parent-pos (throw 'dont-block t)) ; no parent
12347 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12348 (forward-line 1)
12349 (re-search-forward org-not-done-heading-regexp pos t)
12350 (setq org-block-entry-blocking (org-get-heading)))
12351 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12353 (defcustom org-track-ordered-property-with-tag nil
12354 "Should the ORDERED property also be shown as a tag?
12355 The ORDERED property decides if an entry should require subtasks to be
12356 completed in sequence. Since a property is not very visible, setting
12357 this option means that toggling the ORDERED property with the command
12358 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12359 not relevant for the behavior, but it makes things more visible.
12361 Note that toggling the tag with tags commands will not change the property
12362 and therefore not influence behavior!
12364 This can be t, meaning the tag ORDERED should be used, It can also be a
12365 string to select a different tag for this task."
12366 :group 'org-todo
12367 :type '(choice
12368 (const :tag "No tracking" nil)
12369 (const :tag "Track with ORDERED tag" t)
12370 (string :tag "Use other tag")))
12372 (defun org-toggle-ordered-property ()
12373 "Toggle the ORDERED property of the current entry.
12374 For better visibility, you can track the value of this property with a tag.
12375 See variable `org-track-ordered-property-with-tag'."
12376 (interactive)
12377 (let* ((t1 org-track-ordered-property-with-tag)
12378 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12379 (save-excursion
12380 (org-back-to-heading)
12381 (if (org-entry-get nil "ORDERED")
12382 (progn
12383 (org-delete-property "ORDERED")
12384 (and tag (org-toggle-tag tag 'off))
12385 (message "Subtasks can be completed in arbitrary order"))
12386 (org-entry-put nil "ORDERED" "t")
12387 (and tag (org-toggle-tag tag 'on))
12388 (message "Subtasks must be completed in sequence")))))
12390 (defun org-block-todo-from-checkboxes (change-plist)
12391 "Block turning an entry into a TODO, using checkboxes.
12392 This checks whether the current task should be blocked from state
12393 changes because there are unchecked boxes in this entry."
12394 (if (not org-enforce-todo-checkbox-dependencies)
12395 t ; if locally turned off don't block
12396 (catch 'dont-block
12397 ;; If this is not a todo state change, or if this entry is already DONE,
12398 ;; do not block
12399 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12400 (member (plist-get change-plist :from)
12401 (cons 'done org-done-keywords))
12402 (member (plist-get change-plist :to)
12403 (cons 'todo org-not-done-keywords))
12404 (not (plist-get change-plist :to)))
12405 (throw 'dont-block t))
12406 ;; If this task has checkboxes that are not checked, it's blocked
12407 (save-excursion
12408 (org-back-to-heading t)
12409 (let ((beg (point)) end)
12410 (outline-next-heading)
12411 (setq end (point))
12412 (goto-char beg)
12413 (when (org-list-search-forward
12414 (concat (org-item-beginning-re)
12415 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12416 "\\[[- ]\\]")
12417 end t)
12418 (when (boundp 'org-blocked-by-checkboxes)
12419 (setq org-blocked-by-checkboxes t))
12420 (throw 'dont-block nil))))
12421 t))) ; do not block
12423 (defun org-entry-blocked-p ()
12424 "Non-nil if entry at point is blocked."
12425 (and (not (org-entry-get nil "NOBLOCKING"))
12426 (member (org-entry-get nil "TODO") org-not-done-keywords)
12427 (not (run-hook-with-args-until-failure
12428 'org-blocker-hook
12429 (list :type 'todo-state-change
12430 :position (point)
12431 :from 'todo
12432 :to 'done)))))
12434 (defun org-update-statistics-cookies (all)
12435 "Update the statistics cookie, either from TODO or from checkboxes.
12436 This should be called with the cursor in a line with a statistics
12437 cookie. When called with a \\[universal-argument] prefix, update
12438 all statistics cookies in the buffer."
12439 (interactive "P")
12440 (if all
12441 (progn
12442 (org-update-checkbox-count 'all)
12443 (org-map-entries 'org-update-parent-todo-statistics))
12444 (if (not (org-at-heading-p))
12445 (org-update-checkbox-count)
12446 (let ((pos (point-marker))
12447 end l1 l2)
12448 (ignore-errors (org-back-to-heading t))
12449 (if (not (org-at-heading-p))
12450 (org-update-checkbox-count)
12451 (setq l1 (org-outline-level))
12452 (setq end (save-excursion
12453 (outline-next-heading)
12454 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12455 (point)))
12456 (if (and (save-excursion
12457 (re-search-forward
12458 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12459 (not (save-excursion (re-search-forward
12460 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12461 (org-update-checkbox-count)
12462 (if (and l2 (> l2 l1))
12463 (progn
12464 (goto-char end)
12465 (org-update-parent-todo-statistics))
12466 (goto-char pos)
12467 (beginning-of-line 1)
12468 (while (re-search-forward
12469 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12470 (point-at-eol) t)
12471 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12472 (goto-char pos)
12473 (move-marker pos nil)))))
12475 (defvar org-entry-property-inherited-from) ;; defined below
12476 (defun org-update-parent-todo-statistics ()
12477 "Update any statistics cookie in the parent of the current headline.
12478 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12479 the entire subtree and this will travel up the hierarchy and update
12480 statistics everywhere."
12481 (let* ((prop (save-excursion (org-up-heading-safe)
12482 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12483 (recursive (or (not org-hierarchical-todo-statistics)
12484 (and prop (string-match "\\<recursive\\>" prop))))
12485 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12487 (first t)
12488 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12489 level ltoggle l1 new ndel
12490 (cnt-all 0) (cnt-done 0) is-percent kwd
12491 checkbox-beg cookie-present)
12492 (catch 'exit
12493 (save-excursion
12494 (beginning-of-line 1)
12495 (setq ltoggle (funcall outline-level))
12496 ;; Three situations are to consider:
12498 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12499 ;; to the top-level ancestor on the headline;
12501 ;; 2. If parent has "recursive" property, repeat up to the
12502 ;; headline setting that property, taking inheritance into
12503 ;; account;
12505 ;; 3. Else, move up to direct parent and proceed only once.
12506 (while (and (setq level (org-up-heading-safe))
12507 (or recursive first)
12508 (>= (point) lim))
12509 (setq first nil cookie-present nil)
12510 (unless (and level
12511 (not (string-match
12512 "\\<checkbox\\>"
12513 (downcase (or (org-entry-get nil "COOKIE_DATA")
12514 "")))))
12515 (throw 'exit nil))
12516 (while (re-search-forward box-re (point-at-eol) t)
12517 (setq cnt-all 0 cnt-done 0 cookie-present t)
12518 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12519 (save-match-data
12520 (unless (outline-next-heading) (throw 'exit nil))
12521 (while (and (looking-at org-complex-heading-regexp)
12522 (> (setq l1 (length (match-string 1))) level))
12523 (setq kwd (and (or recursive (= l1 ltoggle))
12524 (match-string 2)))
12525 (if (or (eq org-provide-todo-statistics 'all-headlines)
12526 (and (eq org-provide-todo-statistics t)
12527 (or (member kwd org-done-keywords)))
12528 (and (listp org-provide-todo-statistics)
12529 (stringp (car org-provide-todo-statistics))
12530 (or (member kwd org-provide-todo-statistics)
12531 (member kwd org-done-keywords)))
12532 (and (listp org-provide-todo-statistics)
12533 (listp (car org-provide-todo-statistics))
12534 (or (member kwd (car org-provide-todo-statistics))
12535 (and (member kwd org-done-keywords)
12536 (member kwd (cadr org-provide-todo-statistics))))))
12537 (setq cnt-all (1+ cnt-all))
12538 (and (eq org-provide-todo-statistics t)
12540 (setq cnt-all (1+ cnt-all))))
12541 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12542 (member kwd org-done-keywords))
12543 (and (listp org-provide-todo-statistics)
12544 (listp (car org-provide-todo-statistics))
12545 (member kwd org-done-keywords)
12546 (member kwd (cadr org-provide-todo-statistics)))
12547 (and (listp org-provide-todo-statistics)
12548 (stringp (car org-provide-todo-statistics))
12549 (member kwd org-done-keywords)))
12550 (setq cnt-done (1+ cnt-done)))
12551 (outline-next-heading)))
12552 (setq new
12553 (if is-percent
12554 (format "[%d%%]" (floor (* 100.0 cnt-done)
12555 (max 1 cnt-all)))
12556 (format "[%d/%d]" cnt-done cnt-all))
12557 ndel (- (match-end 0) checkbox-beg))
12558 (goto-char checkbox-beg)
12559 (insert new)
12560 (delete-region (point) (+ (point) ndel))
12561 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12562 (when cookie-present
12563 (run-hook-with-args 'org-after-todo-statistics-hook
12564 cnt-done (- cnt-all cnt-done))))))
12565 (run-hooks 'org-todo-statistics-hook)))
12567 (defvar org-after-todo-statistics-hook nil
12568 "Hook that is called after a TODO statistics cookie has been updated.
12569 Each function is called with two arguments: the number of not-done entries
12570 and the number of done entries.
12572 For example, the following function, when added to this hook, will switch
12573 an entry to DONE when all children are done, and back to TODO when new
12574 entries are set to a TODO status. Note that this hook is only called
12575 when there is a statistics cookie in the headline!
12577 (defun org-summary-todo (n-done n-not-done)
12578 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12579 (let (org-log-done org-log-states) ; turn off logging
12580 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12583 (defvar org-todo-statistics-hook nil
12584 "Hook that is run whenever Org thinks TODO statistics should be updated.
12585 This hook runs even if there is no statistics cookie present, in which case
12586 `org-after-todo-statistics-hook' would not run.")
12588 (defun org-todo-trigger-tag-changes (state)
12589 "Apply the changes defined in `org-todo-state-tags-triggers'."
12590 (let ((l org-todo-state-tags-triggers)
12591 changes)
12592 (when (or (not state) (equal state ""))
12593 (setq changes (append changes (cdr (assoc "" l)))))
12594 (when (and (stringp state) (> (length state) 0))
12595 (setq changes (append changes (cdr (assoc state l)))))
12596 (when (member state org-not-done-keywords)
12597 (setq changes (append changes (cdr (assq 'todo l)))))
12598 (when (member state org-done-keywords)
12599 (setq changes (append changes (cdr (assq 'done l)))))
12600 (dolist (c changes)
12601 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12603 (defun org-local-logging (value)
12604 "Get logging settings from a property VALUE."
12605 ;; Directly set the variables, they are already local.
12606 (setq org-log-done nil
12607 org-log-repeat nil
12608 org-todo-log-states nil)
12609 (dolist (w (split-string value))
12610 (let (a)
12611 (cond
12612 ((setq a (assoc w org-startup-options))
12613 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12614 (set (nth 1 a) (nth 2 a))))
12615 ((setq a (org-extract-log-state-settings w))
12616 (and (member (car a) org-todo-keywords-1)
12617 (push a org-todo-log-states)))))))
12619 (defun org-get-todo-sequence-head (kwd)
12620 "Return the head of the TODO sequence to which KWD belongs.
12621 If KWD is not set, check if there is a text property remembering the
12622 right sequence."
12623 (let (p)
12624 (cond
12625 ((not kwd)
12626 (or (get-text-property (point-at-bol) 'org-todo-head)
12627 (progn
12628 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12629 nil (point-at-eol)))
12630 (get-text-property p 'org-todo-head))))
12631 ((not (member kwd org-todo-keywords-1))
12632 (car org-todo-keywords-1))
12633 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12635 (defun org-fast-todo-selection ()
12636 "Fast TODO keyword selection with single keys.
12637 Returns the new TODO keyword, or nil if no state change should occur."
12638 (let* ((fulltable org-todo-key-alist)
12639 (done-keywords org-done-keywords) ;; needed for the faces.
12640 (maxlen (apply 'max (mapcar
12641 (lambda (x)
12642 (if (stringp (car x)) (string-width (car x)) 0))
12643 fulltable)))
12644 (expert nil)
12645 (fwidth (+ maxlen 3 1 3))
12646 (ncol (/ (- (window-width) 4) fwidth))
12647 tg cnt e c tbl
12648 groups ingroup)
12649 (save-excursion
12650 (save-window-excursion
12651 (if expert
12652 (set-buffer (get-buffer-create " *Org todo*"))
12653 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12654 (erase-buffer)
12655 (setq-local org-done-keywords done-keywords)
12656 (setq tbl fulltable cnt 0)
12657 (while (setq e (pop tbl))
12658 (cond
12659 ((equal e '(:startgroup))
12660 (push '() groups) (setq ingroup t)
12661 (unless (= cnt 0)
12662 (setq cnt 0)
12663 (insert "\n"))
12664 (insert "{ "))
12665 ((equal e '(:endgroup))
12666 (setq ingroup nil cnt 0)
12667 (insert "}\n"))
12668 ((equal e '(:newline))
12669 (unless (= cnt 0)
12670 (setq cnt 0)
12671 (insert "\n")
12672 (setq e (car tbl))
12673 (while (equal (car tbl) '(:newline))
12674 (insert "\n")
12675 (setq tbl (cdr tbl)))))
12677 (setq tg (car e) c (cdr e))
12678 (when ingroup (push tg (car groups)))
12679 (setq tg (org-add-props tg nil 'face
12680 (org-get-todo-face tg)))
12681 (when (and (= cnt 0) (not ingroup)) (insert " "))
12682 (insert "[" c "] " tg (make-string
12683 (- fwidth 4 (length tg)) ?\ ))
12684 (when (= (setq cnt (1+ cnt)) ncol)
12685 (insert "\n")
12686 (when ingroup (insert " "))
12687 (setq cnt 0)))))
12688 (insert "\n")
12689 (goto-char (point-min))
12690 (unless expert (org-fit-window-to-buffer))
12691 (message "[a-z..]:Set [SPC]:clear")
12692 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12693 (cond
12694 ((or (= c ?\C-g)
12695 (and (= c ?q) (not (rassoc c fulltable))))
12696 (setq quit-flag t))
12697 ((= c ?\ ) nil)
12698 ((setq e (rassoc c fulltable) tg (car e))
12700 (t (setq quit-flag t)))))))
12702 (defun org-entry-is-todo-p ()
12703 (member (org-get-todo-state) org-not-done-keywords))
12705 (defun org-entry-is-done-p ()
12706 (member (org-get-todo-state) org-done-keywords))
12708 (defun org-get-todo-state ()
12709 "Return the TODO keyword of the current subtree."
12710 (save-excursion
12711 (org-back-to-heading t)
12712 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12713 (match-end 2)
12714 (match-string 2))))
12716 (defun org-at-date-range-p (&optional inactive-ok)
12717 "Non-nil if point is inside a date range.
12719 When optional argument INACTIVE-OK is non-nil, also consider
12720 inactive time ranges.
12722 When this function returns a non-nil value, match data is set
12723 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12724 on INACTIVE-OK."
12725 (interactive)
12726 (save-excursion
12727 (catch 'exit
12728 (let ((pos (point)))
12729 (skip-chars-backward "^[<\r\n")
12730 (skip-chars-backward "<[")
12731 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12732 (>= (match-end 0) pos)
12733 (throw 'exit t))
12734 (skip-chars-backward "^<[\r\n")
12735 (skip-chars-backward "<[")
12736 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12737 (>= (match-end 0) pos)
12738 (throw 'exit t)))
12739 nil)))
12741 (defun org-get-repeat (&optional timestamp)
12742 "Check if there is a time-stamp with repeater in this entry.
12744 Return the repeater, as a string, or nil. Also return nil when
12745 this function is called before first heading.
12747 When optional argument TIMESTAMP is a string, extract the
12748 repeater from there instead."
12749 (save-match-data
12750 (cond (timestamp
12751 (and (string-match org-repeat-re timestamp)
12752 (match-string-no-properties 1 timestamp)))
12753 ((org-before-first-heading-p) nil)
12755 (save-excursion
12756 (org-back-to-heading t)
12757 (let ((end (org-entry-end-position)))
12758 (catch :repeat
12759 (while (re-search-forward org-repeat-re end t)
12760 (when (save-match-data (org-at-timestamp-p 'agenda))
12761 (throw :repeat (match-string-no-properties 1)))))))))))
12763 (defvar org-last-changed-timestamp)
12764 (defvar org-last-inserted-timestamp)
12765 (defvar org-log-post-message)
12766 (defvar org-log-note-purpose)
12767 (defvar org-log-note-how nil)
12768 (defvar org-log-note-extra)
12769 (defun org-auto-repeat-maybe (done-word)
12770 "Check if the current headline contains a repeated time-stamp.
12772 If yes, set TODO state back to what it was and change the base date
12773 of repeating deadline/scheduled time stamps to new date.
12775 This function is run automatically after each state change to a DONE state."
12776 (let* ((repeat (org-get-repeat))
12777 (aa (assoc org-last-state org-todo-kwd-alist))
12778 (interpret (nth 1 aa))
12779 (head (nth 2 aa))
12780 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12781 (msg "Entry repeats: ")
12782 (org-log-done nil)
12783 (org-todo-log-states nil)
12784 (end (copy-marker (org-entry-end-position))))
12785 (unwind-protect
12786 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12787 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12788 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12789 (and (stringp org-todo-repeat-to-state)
12790 org-todo-repeat-to-state)
12791 (and org-todo-repeat-to-state org-last-state))))
12792 (org-todo (cond
12793 ((and to-state (member to-state org-todo-keywords-1))
12794 to-state)
12795 ((eq interpret 'type) org-last-state)
12796 (head)
12797 (t 'none))))
12798 (org-back-to-heading t)
12799 (org-add-planning-info nil nil 'closed)
12800 ;; When `org-log-repeat' is non-nil or entry contains
12801 ;; a clock, set LAST_REPEAT property.
12802 (when (or org-log-repeat
12803 (catch :clock
12804 (save-excursion
12805 (while (re-search-forward org-clock-line-re end t)
12806 (when (org-at-clock-log-p) (throw :clock t))))))
12807 (org-entry-put nil "LAST_REPEAT" (format-time-string
12808 (org-time-stamp-format t t)
12809 (current-time))))
12810 (when org-log-repeat
12811 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12812 (memq 'org-add-log-note post-command-hook))
12813 ;; We are already setup for some record.
12814 (when (eq org-log-repeat 'note)
12815 ;; Make sure we take a note, not only a time stamp.
12816 (setq org-log-note-how 'note))
12817 ;; Set up for taking a record.
12818 (org-add-log-setup 'state
12819 (or done-word (car org-done-keywords))
12820 org-last-state
12821 org-log-repeat)))
12822 (let ((planning-re (regexp-opt
12823 (list org-scheduled-string org-deadline-string))))
12824 (while (re-search-forward org-ts-regexp end t)
12825 (let* ((ts (match-string 0))
12826 (planning? (org-at-planning-p))
12827 (type (if (not planning?) "Plain:"
12828 (save-excursion
12829 (re-search-backward
12830 planning-re (line-beginning-position) t)
12831 (match-string 0)))))
12832 (cond
12833 ;; Ignore fake time-stamps (e.g., within comments).
12834 ((not (org-at-timestamp-p 'agenda)))
12835 ;; Time-stamps without a repeater are usually
12836 ;; skipped. However, a SCHEDULED time-stamp without
12837 ;; one is removed, as they are no longer relevant.
12838 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12839 ts))
12840 (when (equal type org-scheduled-string)
12841 (org-remove-timestamp-with-keyword type)))
12843 (let ((n (string-to-number (match-string 2 ts)))
12844 (what (match-string 3 ts)))
12845 (when (equal what "w") (setq n (* n 7) what "d"))
12846 (when (and (equal what "h")
12847 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12848 ts)))
12849 (user-error
12850 "Cannot repeat in Repeat in %d hour(s) because no hour \
12851 has been set"
12853 ;; Preparation, see if we need to modify the start
12854 ;; date for the change.
12855 (when (match-end 1)
12856 (let ((time (save-match-data
12857 (org-time-string-to-time ts))))
12858 (cond
12859 ((equal (match-string 1 ts) ".")
12860 ;; Shift starting date to today
12861 (org-timestamp-change
12862 (- (org-today) (time-to-days time))
12863 'day))
12864 ((equal (match-string 1 ts) "+")
12865 (let ((nshiftmax 10)
12866 (nshift 0))
12867 (while (or (= nshift 0)
12868 (not (time-less-p (current-time) time)))
12869 (when (= (cl-incf nshift) nshiftmax)
12870 (or (y-or-n-p
12871 (format "%d repeater intervals were not \
12872 enough to shift date past today. Continue? "
12873 nshift))
12874 (user-error "Abort")))
12875 (org-timestamp-change n (cdr (assoc what whata)))
12876 (org-in-regexp org-ts-regexp3)
12877 (setq ts (match-string 1))
12878 (setq time
12879 (save-match-data
12880 (org-time-string-to-time ts)))))
12881 (org-timestamp-change (- n) (cdr (assoc what whata)))
12882 ;; Rematch, so that we have everything in place
12883 ;; for the real shift.
12884 (org-in-regexp org-ts-regexp3)
12885 (setq ts (match-string 1))
12886 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12887 ts)))))
12888 (save-excursion
12889 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12890 (setq msg
12891 (concat
12892 msg type " " org-last-changed-timestamp " "))))))))
12893 (setq org-log-post-message msg)
12894 (message "%s" msg))
12895 (set-marker end nil))))
12897 (defun org-show-todo-tree (arg)
12898 "Make a compact tree which shows all headlines marked with TODO.
12899 The tree will show the lines where the regexp matches, and all higher
12900 headlines above the match.
12901 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12902 With a numeric prefix N, construct a sparse tree for the Nth element
12903 of `org-todo-keywords-1'."
12904 (interactive "P")
12905 (let ((case-fold-search nil)
12906 (kwd-re
12907 (cond ((null arg) org-not-done-regexp)
12908 ((equal arg '(4))
12909 (let ((kwd
12910 (completing-read "Keyword (or KWD1|KWD2|...): "
12911 (mapcar #'list org-todo-keywords-1))))
12912 (concat "\\("
12913 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12914 "\\)\\>")))
12915 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12916 (regexp-quote (nth (1- (prefix-numeric-value arg))
12917 org-todo-keywords-1)))
12918 (t (user-error "Invalid prefix argument: %s" arg)))))
12919 (message "%d TODO entries found"
12920 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12922 (defun org--deadline-or-schedule (arg type time)
12923 "Insert DEADLINE or SCHEDULE information in current entry.
12924 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12925 `org-schedule' for information about ARG and TIME arguments."
12926 (let* ((deadline? (eq type 'deadline))
12927 (keyword (if deadline? org-deadline-string org-scheduled-string))
12928 (log (if deadline? org-log-redeadline org-log-reschedule))
12929 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12930 (old-date-time (and old-date (org-time-string-to-time old-date)))
12931 ;; Save repeater cookie from either TIME or current scheduled
12932 ;; time stamp. We are going to insert it back at the end of
12933 ;; the process.
12934 (repeater (or (and (org-string-nw-p time)
12935 ;; We use `org-repeat-re' because we need
12936 ;; to tell the difference between a real
12937 ;; repeater and a time delta, e.g. "+2d".
12938 (string-match org-repeat-re time)
12939 (match-string 1 time))
12940 (and (org-string-nw-p old-date)
12941 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12942 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12943 old-date)
12944 (match-string 1 old-date)))))
12945 (pcase arg
12946 (`(4)
12947 (when (and old-date log)
12948 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12949 nil old-date log))
12950 (org-remove-timestamp-with-keyword keyword)
12951 (message (if deadline? "Item no longer has a deadline."
12952 "Item is no longer scheduled.")))
12953 (`(16)
12954 (save-excursion
12955 (org-back-to-heading t)
12956 (let ((regexp (if deadline? org-deadline-time-regexp
12957 org-scheduled-time-regexp)))
12958 (if (not (re-search-forward regexp (line-end-position 2) t))
12959 (user-error (if deadline? "No deadline information to update"
12960 "No scheduled information to update"))
12961 (let* ((rpl0 (match-string 1))
12962 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12963 (msg (if deadline? "Warn starting from" "Delay until")))
12964 (replace-match
12965 (concat keyword
12966 " <" rpl
12967 (format " -%dd"
12968 (abs (- (time-to-days
12969 (save-match-data
12970 (org-read-date
12971 nil t nil msg old-date-time)))
12972 (time-to-days old-date-time))))
12973 ">") t t))))))
12975 (org-add-planning-info type time 'closed)
12976 (when (and old-date
12978 (not (equal old-date org-last-inserted-timestamp)))
12979 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12980 org-last-inserted-timestamp
12981 old-date
12982 log))
12983 (when repeater
12984 (save-excursion
12985 (org-back-to-heading t)
12986 (when (re-search-forward
12987 (concat keyword " " org-last-inserted-timestamp)
12988 (line-end-position 2)
12990 (goto-char (1- (match-end 0)))
12991 (insert " " repeater)
12992 (setq org-last-inserted-timestamp
12993 (concat (substring org-last-inserted-timestamp 0 -1)
12994 " " repeater
12995 (substring org-last-inserted-timestamp -1))))))
12996 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12997 org-last-inserted-timestamp)))))
12999 (defun org-deadline (arg &optional time)
13000 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13001 With one universal prefix argument, remove any deadline from the item.
13002 With two universal prefix arguments, prompt for a warning delay.
13003 With argument TIME, set the deadline at the corresponding date. TIME
13004 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13005 (interactive "P")
13006 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13007 (org-map-entries
13008 (lambda () (org--deadline-or-schedule arg 'deadline time))
13010 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13011 'region-start-level
13012 'region)
13013 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13014 (org--deadline-or-schedule arg 'deadline time)))
13016 (defun org-schedule (arg &optional time)
13017 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13018 With one universal prefix argument, remove any scheduling date from the item.
13019 With two universal prefix arguments, prompt for a delay cookie.
13020 With argument TIME, scheduled at the corresponding date. TIME can
13021 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13022 (interactive "P")
13023 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13024 (org-map-entries
13025 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13027 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13028 'region-start-level
13029 'region)
13030 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13031 (org--deadline-or-schedule arg 'scheduled time)))
13033 (defun org-get-scheduled-time (pom &optional inherit)
13034 "Get the scheduled time as a time tuple, of a format suitable
13035 for calling org-schedule with, or if there is no scheduling,
13036 returns nil."
13037 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13038 (when time
13039 (apply 'encode-time (org-parse-time-string time)))))
13041 (defun org-get-deadline-time (pom &optional inherit)
13042 "Get the deadline as a time tuple, of a format suitable for
13043 calling org-deadline with, or if there is no scheduling, returns
13044 nil."
13045 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13046 (when time
13047 (apply 'encode-time (org-parse-time-string time)))))
13049 (defun org-remove-timestamp-with-keyword (keyword)
13050 "Remove all time stamps with KEYWORD in the current entry."
13051 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13052 beg)
13053 (save-excursion
13054 (org-back-to-heading t)
13055 (setq beg (point))
13056 (outline-next-heading)
13057 (while (re-search-backward re beg t)
13058 (replace-match "")
13059 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13060 (equal (char-before) ?\ ))
13061 (backward-delete-char 1)
13062 (when (string-match "^[ \t]*$" (buffer-substring
13063 (point-at-bol) (point-at-eol)))
13064 (delete-region (point-at-bol)
13065 (min (point-max) (1+ (point-at-eol))))))))))
13067 (defvar org-time-was-given) ; dynamically scoped parameter
13068 (defvar org-end-time-was-given) ; dynamically scoped parameter
13070 (defun org-at-planning-p ()
13071 "Non-nil when point is on a planning info line."
13072 ;; This is as accurate and faster than `org-element-at-point' since
13073 ;; planning info location is fixed in the section.
13074 (org-with-wide-buffer
13075 (beginning-of-line)
13076 (and (looking-at-p org-planning-line-re)
13077 (eq (point)
13078 (ignore-errors
13079 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13080 (org-back-to-heading t)
13081 (org-with-limited-levels (org-back-to-heading t)))
13082 (line-beginning-position 2))))))
13084 (defun org-add-planning-info (what &optional time &rest remove)
13085 "Insert new timestamp with keyword in the planning line.
13086 WHAT indicates what kind of time stamp to add. It is a symbol
13087 among `closed', `deadline', `scheduled' and nil. TIME indicates
13088 the time to use. If none is given, the user is prompted for
13089 a date. REMOVE indicates what kind of entries to remove. An old
13090 WHAT entry will also be removed."
13091 (let (org-time-was-given org-end-time-was-given default-time default-input)
13092 (catch 'exit
13093 (when (and (memq what '(scheduled deadline))
13094 (or (not time)
13095 (and (stringp time)
13096 (string-match "^[-+]+[0-9]" time))))
13097 ;; Try to get a default date/time from existing timestamp
13098 (save-excursion
13099 (org-back-to-heading t)
13100 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13101 (when (re-search-forward (if (eq what 'scheduled)
13102 org-scheduled-time-regexp
13103 org-deadline-time-regexp)
13104 end t)
13105 (setq ts (match-string 1)
13106 default-time (apply 'encode-time (org-parse-time-string ts))
13107 default-input (and ts (org-get-compact-tod ts)))))))
13108 (when what
13109 (setq time
13110 (if (stringp time)
13111 ;; This is a string (relative or absolute), set
13112 ;; proper date.
13113 (apply #'encode-time
13114 (org-read-date-analyze
13115 time default-time (decode-time default-time)))
13116 ;; If necessary, get the time from the user
13117 (or time (org-read-date nil 'to-time nil nil
13118 default-time default-input)))))
13120 (org-with-wide-buffer
13121 (org-back-to-heading t)
13122 (forward-line)
13123 (unless (bolp) (insert "\n"))
13124 (cond ((looking-at-p org-planning-line-re)
13125 ;; Move to current indentation.
13126 (skip-chars-forward " \t")
13127 ;; Check if we have to remove something.
13128 (dolist (type (if what (cons what remove) remove))
13129 (save-excursion
13130 (when (re-search-forward
13131 (cl-case type
13132 (closed org-closed-time-regexp)
13133 (deadline org-deadline-time-regexp)
13134 (scheduled org-scheduled-time-regexp)
13135 (otherwise
13136 (error "Invalid planning type: %s" type)))
13137 (line-end-position) t)
13138 ;; Delete until next keyword or end of line.
13139 (delete-region
13140 (match-beginning 0)
13141 (if (re-search-forward org-keyword-time-not-clock-regexp
13142 (line-end-position)
13144 (match-beginning 0)
13145 (line-end-position))))))
13146 ;; If there is nothing more to add and no more keyword
13147 ;; is left, remove the line completely.
13148 (if (and (looking-at-p "[ \t]*$") (not what))
13149 (delete-region (line-beginning-position)
13150 (line-beginning-position 2))
13151 ;; If we removed last keyword, do not leave trailing
13152 ;; white space at the end of line.
13153 (let ((p (point)))
13154 (save-excursion
13155 (end-of-line)
13156 (unless (= (skip-chars-backward " \t" p) 0)
13157 (delete-region (point) (line-end-position)))))))
13158 ((not what) (throw 'exit nil)) ; Nothing to do.
13159 (t (insert-before-markers "\n")
13160 (backward-char 1)
13161 (when org-adapt-indentation
13162 (indent-to-column (1+ (org-outline-level))))))
13163 (when what
13164 ;; Insert planning keyword.
13165 (insert (cl-case what
13166 (closed org-closed-string)
13167 (deadline org-deadline-string)
13168 (scheduled org-scheduled-string)
13169 (otherwise (error "Invalid planning type: %s" what)))
13170 " ")
13171 ;; Insert associated timestamp.
13172 (let ((ts (org-insert-time-stamp
13173 time
13174 (or org-time-was-given
13175 (and (eq what 'closed) org-log-done-with-time))
13176 (eq what 'closed)
13177 nil nil (list org-end-time-was-given))))
13178 (unless (eolp) (insert " "))
13179 ts))))))
13181 (defvar org-log-note-marker (make-marker)
13182 "Marker pointing at the entry where the note is to be inserted.")
13183 (defvar org-log-note-purpose nil)
13184 (defvar org-log-note-state nil)
13185 (defvar org-log-note-previous-state nil)
13186 (defvar org-log-note-extra nil)
13187 (defvar org-log-note-window-configuration nil)
13188 (defvar org-log-note-return-to (make-marker))
13189 (defvar org-log-note-effective-time nil
13190 "Remembered current time so that dynamically scoped
13191 `org-extend-today-until' affects timestamps in state change log")
13193 (defvar org-log-post-message nil
13194 "Message to be displayed after a log note has been stored.
13195 The auto-repeater uses this.")
13197 (defun org-add-note ()
13198 "Add a note to the current entry.
13199 This is done in the same way as adding a state change note."
13200 (interactive)
13201 (org-add-log-setup 'note))
13203 (defun org-log-beginning (&optional create)
13204 "Return expected start of log notes in current entry.
13205 When optional argument CREATE is non-nil, the function creates
13206 a drawer to store notes, if necessary. Returned position ignores
13207 narrowing."
13208 (org-with-wide-buffer
13209 (let ((drawer (org-log-into-drawer)))
13210 (cond
13211 (drawer
13212 (org-end-of-meta-data)
13213 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13214 (end (if (org-at-heading-p) (point)
13215 (save-excursion (outline-next-heading) (point))))
13216 (case-fold-search t))
13217 (catch 'exit
13218 ;; Try to find existing drawer.
13219 (while (re-search-forward regexp end t)
13220 (let ((element (org-element-at-point)))
13221 (when (eq (org-element-type element) 'drawer)
13222 (let ((cend (org-element-property :contents-end element)))
13223 (when (and (not org-log-states-order-reversed) cend)
13224 (goto-char cend)))
13225 (throw 'exit nil))))
13226 ;; No drawer found. Create one, if permitted.
13227 (when create
13228 (unless (bolp) (insert "\n"))
13229 (let ((beg (point)))
13230 (insert ":" drawer ":\n:END:\n")
13231 (org-indent-region beg (point)))
13232 (end-of-line -1)))))
13234 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13235 (skip-chars-forward " \t\n")
13236 (beginning-of-line)
13237 (unless org-log-states-order-reversed
13238 (org-skip-over-state-notes)
13239 (skip-chars-backward " \t\n")
13240 (forward-line)))))
13241 (if (bolp) (point) (line-beginning-position 2))))
13243 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13244 "Set up the post command hook to take a note.
13245 If this is about to TODO state change, the new state is expected in STATE.
13246 HOW is an indicator what kind of note should be created.
13247 EXTRA is additional text that will be inserted into the notes buffer."
13248 (move-marker org-log-note-marker (point))
13249 (setq org-log-note-purpose purpose
13250 org-log-note-state state
13251 org-log-note-previous-state prev-state
13252 org-log-note-how how
13253 org-log-note-extra extra
13254 org-log-note-effective-time (org-current-effective-time))
13255 (add-hook 'post-command-hook 'org-add-log-note 'append))
13257 (defun org-skip-over-state-notes ()
13258 "Skip past the list of State notes in an entry."
13259 (when (ignore-errors (goto-char (org-in-item-p)))
13260 (let* ((struct (org-list-struct))
13261 (prevs (org-list-prevs-alist struct))
13262 (regexp
13263 (concat "[ \t]*- +"
13264 (replace-regexp-in-string
13265 " +" " +"
13266 (org-replace-escapes
13267 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13268 `(("%d" . ,org-ts-regexp-inactive)
13269 ("%D" . ,org-ts-regexp)
13270 ("%s" . "\"\\S-+\"")
13271 ("%S" . "\"\\S-+\"")
13272 ("%t" . ,org-ts-regexp-inactive)
13273 ("%T" . ,org-ts-regexp)
13274 ("%u" . ".*?")
13275 ("%U" . ".*?")))))))
13276 (while (looking-at-p regexp)
13277 (goto-char (or (org-list-get-next-item (point) struct prevs)
13278 (org-list-get-item-end (point) struct)))))))
13280 (defun org-add-log-note (&optional _purpose)
13281 "Pop up a window for taking a note, and add this note later."
13282 (remove-hook 'post-command-hook 'org-add-log-note)
13283 (setq org-log-note-window-configuration (current-window-configuration))
13284 (delete-other-windows)
13285 (move-marker org-log-note-return-to (point))
13286 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13287 (goto-char org-log-note-marker)
13288 (org-switch-to-buffer-other-window "*Org Note*")
13289 (erase-buffer)
13290 (if (memq org-log-note-how '(time state))
13291 (org-store-log-note)
13292 (let ((org-inhibit-startup t)) (org-mode))
13293 (insert (format "# Insert note for %s.
13294 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13295 (cond
13296 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13297 ((eq org-log-note-purpose 'done) "closed todo item")
13298 ((eq org-log-note-purpose 'state)
13299 (format "state change from \"%s\" to \"%s\""
13300 (or org-log-note-previous-state "")
13301 (or org-log-note-state "")))
13302 ((eq org-log-note-purpose 'reschedule)
13303 "rescheduling")
13304 ((eq org-log-note-purpose 'delschedule)
13305 "no longer scheduled")
13306 ((eq org-log-note-purpose 'redeadline)
13307 "changing deadline")
13308 ((eq org-log-note-purpose 'deldeadline)
13309 "removing deadline")
13310 ((eq org-log-note-purpose 'refile)
13311 "refiling")
13312 ((eq org-log-note-purpose 'note)
13313 "this entry")
13314 (t (error "This should not happen")))))
13315 (when org-log-note-extra (insert org-log-note-extra))
13316 (setq-local org-finish-function 'org-store-log-note)
13317 (run-hooks 'org-log-buffer-setup-hook)))
13319 (defvar org-note-abort nil) ; dynamically scoped
13320 (defun org-store-log-note ()
13321 "Finish taking a log note, and insert it to where it belongs."
13322 (let ((txt (prog1 (buffer-string)
13323 (kill-buffer)))
13324 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13325 lines)
13326 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13327 (setq txt (replace-match "" t t txt)))
13328 (when (string-match "\\s-+\\'" txt)
13329 (setq txt (replace-match "" t t txt)))
13330 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13331 (when (org-string-nw-p note)
13332 (setq note
13333 (org-replace-escapes
13334 note
13335 (list (cons "%u" (user-login-name))
13336 (cons "%U" user-full-name)
13337 (cons "%t" (format-time-string
13338 (org-time-stamp-format 'long 'inactive)
13339 org-log-note-effective-time))
13340 (cons "%T" (format-time-string
13341 (org-time-stamp-format 'long nil)
13342 org-log-note-effective-time))
13343 (cons "%d" (format-time-string
13344 (org-time-stamp-format nil 'inactive)
13345 org-log-note-effective-time))
13346 (cons "%D" (format-time-string
13347 (org-time-stamp-format nil nil)
13348 org-log-note-effective-time))
13349 (cons "%s" (cond
13350 ((not org-log-note-state) "")
13351 ((string-match-p org-ts-regexp
13352 org-log-note-state)
13353 (format "\"[%s]\""
13354 (substring org-log-note-state 1 -1)))
13355 (t (format "\"%s\"" org-log-note-state))))
13356 (cons "%S"
13357 (cond
13358 ((not org-log-note-previous-state) "")
13359 ((string-match-p org-ts-regexp
13360 org-log-note-previous-state)
13361 (format "\"[%s]\""
13362 (substring
13363 org-log-note-previous-state 1 -1)))
13364 (t (format "\"%s\""
13365 org-log-note-previous-state)))))))
13366 (when lines (setq note (concat note " \\\\")))
13367 (push note lines))
13368 (when (and lines (not org-note-abort))
13369 (with-current-buffer (marker-buffer org-log-note-marker)
13370 (org-with-wide-buffer
13371 ;; Find location for the new note.
13372 (goto-char org-log-note-marker)
13373 (set-marker org-log-note-marker nil)
13374 ;; Note associated to a clock is to be located right after
13375 ;; the clock. Do not move point.
13376 (unless (eq org-log-note-purpose 'clock-out)
13377 (goto-char (org-log-beginning t)))
13378 ;; Make sure point is at the beginning of an empty line.
13379 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13380 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13381 ;; In an existing list, add a new item at the top level.
13382 ;; Otherwise, indent line like a regular one.
13383 (let ((itemp (org-in-item-p)))
13384 (if itemp
13385 (indent-line-to
13386 (let ((struct (save-excursion
13387 (goto-char itemp) (org-list-struct))))
13388 (org-list-get-ind (org-list-get-top-point struct) struct)))
13389 (org-indent-line)))
13390 (insert (org-list-bullet-string "-") (pop lines))
13391 (let ((ind (org-list-item-body-column (line-beginning-position))))
13392 (dolist (line lines)
13393 (insert "\n")
13394 (indent-line-to ind)
13395 (insert line)))
13396 (message "Note stored")
13397 (org-back-to-heading t)
13398 (org-cycle-hide-drawers 'children))
13399 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13400 ;; from within `org-add-log-note' because `buffer-undo-list'
13401 ;; is then modified outside of `org-with-remote-undo'.
13402 (when (eq this-command 'org-agenda-todo)
13403 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13404 ;; Don't add undo information when called from `org-agenda-todo'.
13405 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13406 (set-window-configuration org-log-note-window-configuration)
13407 (with-current-buffer (marker-buffer org-log-note-return-to)
13408 (goto-char org-log-note-return-to))
13409 (move-marker org-log-note-return-to nil)
13410 (when org-log-post-message (message "%s" org-log-post-message))))
13412 (defun org-remove-empty-drawer-at (pos)
13413 "Remove an empty drawer at position POS.
13414 POS may also be a marker."
13415 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13416 (org-with-wide-buffer
13417 (goto-char pos)
13418 (let ((drawer (org-element-at-point)))
13419 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13420 (not (org-element-property :contents-begin drawer)))
13421 (delete-region (org-element-property :begin drawer)
13422 (progn (goto-char (org-element-property :end drawer))
13423 (skip-chars-backward " \r\t\n")
13424 (forward-line)
13425 (point))))))))
13427 (defvar org-ts-type nil)
13428 (defun org-sparse-tree (&optional arg type)
13429 "Create a sparse tree, prompt for the details.
13430 This command can create sparse trees. You first need to select the type
13431 of match used to create the tree:
13433 t Show all TODO entries.
13434 T Show entries with a specific TODO keyword.
13435 m Show entries selected by a tags/property match.
13436 p Enter a property name and its value (both with completion on existing
13437 names/values) and show entries with that property.
13438 r Show entries matching a regular expression (`/' can be used as well).
13439 b Show deadlines and scheduled items before a date.
13440 a Show deadlines and scheduled items after a date.
13441 d Show deadlines due within `org-deadline-warning-days'.
13442 D Show deadlines and scheduled items between a date range."
13443 (interactive "P")
13444 (setq type (or type org-sparse-tree-default-date-type))
13445 (setq org-ts-type type)
13446 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13447 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13448 \[c]ycle through date types: %s"
13449 (cl-case type
13450 (all "all timestamps")
13451 (scheduled "only scheduled")
13452 (deadline "only deadline")
13453 (active "only active timestamps")
13454 (inactive "only inactive timestamps")
13455 (closed "with a closed time-stamp")
13456 (otherwise "scheduled/deadline")))
13457 (let ((answer (read-char-exclusive)))
13458 (cl-case answer
13460 (org-sparse-tree
13462 (cadr
13463 (memq type '(nil all scheduled deadline active inactive closed)))))
13464 (?d (call-interactively 'org-check-deadlines))
13465 (?b (call-interactively 'org-check-before-date))
13466 (?a (call-interactively 'org-check-after-date))
13467 (?D (call-interactively 'org-check-dates-range))
13468 (?t (call-interactively 'org-show-todo-tree))
13469 (?T (org-show-todo-tree '(4)))
13470 (?m (call-interactively 'org-match-sparse-tree))
13471 ((?p ?P)
13472 (let* ((kwd (completing-read
13473 "Property: " (mapcar #'list (org-buffer-property-keys))))
13474 (value (completing-read
13475 "Value: " (mapcar #'list (org-property-values kwd)))))
13476 (unless (string-match "\\`{.*}\\'" value)
13477 (setq value (concat "\"" value "\"")))
13478 (org-match-sparse-tree arg (concat kwd "=" value))))
13479 ((?r ?R ?/) (call-interactively 'org-occur))
13480 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13482 (defvar-local org-occur-highlights nil
13483 "List of overlays used for occur matches.")
13484 (defvar-local org-occur-parameters nil
13485 "Parameters of the active org-occur calls.
13486 This is a list, each call to org-occur pushes as cons cell,
13487 containing the regular expression and the callback, onto the list.
13488 The list can contain several entries if `org-occur' has been called
13489 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13490 will only contain one set of parameters. When the highlights are
13491 removed (for example with `C-c C-c', or with the next edit (depending
13492 on `org-remove-highlights-with-change'), this variable is emptied
13493 as well.")
13495 (defun org-occur (regexp &optional keep-previous callback)
13496 "Make a compact tree which shows all matches of REGEXP.
13498 The tree will show the lines where the regexp matches, and any other context
13499 defined in `org-show-context-detail', which see.
13501 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13502 done by a previous call to `org-occur' will be kept, to allow stacking of
13503 calls to this command.
13505 Optional argument CALLBACK can be a function of no argument. In this case,
13506 it is called with point at the end of the match, match data being set
13507 accordingly. Current match is shown only if the return value is non-nil.
13508 The function must neither move point nor alter narrowing."
13509 (interactive "sRegexp: \nP")
13510 (when (equal regexp "")
13511 (user-error "Regexp cannot be empty"))
13512 (unless keep-previous
13513 (org-remove-occur-highlights nil nil t))
13514 (push (cons regexp callback) org-occur-parameters)
13515 (let ((cnt 0))
13516 (save-excursion
13517 (goto-char (point-min))
13518 (when (or (not keep-previous) ; do not want to keep
13519 (not org-occur-highlights)) ; no previous matches
13520 ;; hide everything
13521 (org-overview))
13522 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13523 (isearch-no-upper-case-p regexp t)
13524 org-occur-case-fold-search)))
13525 (while (re-search-forward regexp nil t)
13526 (when (or (not callback)
13527 (save-match-data (funcall callback)))
13528 (setq cnt (1+ cnt))
13529 (when org-highlight-sparse-tree-matches
13530 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13531 (org-show-context 'occur-tree)))))
13532 (when org-remove-highlights-with-change
13533 (add-hook 'before-change-functions 'org-remove-occur-highlights
13534 nil 'local))
13535 (unless org-sparse-tree-open-archived-trees
13536 (org-hide-archived-subtrees (point-min) (point-max)))
13537 (run-hooks 'org-occur-hook)
13538 (when (called-interactively-p 'interactive)
13539 (message "%d match(es) for regexp %s" cnt regexp))
13540 cnt))
13542 (defun org-occur-next-match (&optional n _reset)
13543 "Function for `next-error-function' to find sparse tree matches.
13544 N is the number of matches to move, when negative move backwards.
13545 This function always goes back to the starting point when no
13546 match is found."
13547 (let* ((limit (if (< n 0) (point-min) (point-max)))
13548 (search-func (if (< n 0)
13549 'previous-single-char-property-change
13550 'next-single-char-property-change))
13551 (n (abs n))
13552 (pos (point))
13554 (catch 'exit
13555 (while (setq p1 (funcall search-func (point) 'org-type))
13556 (when (equal p1 limit)
13557 (goto-char pos)
13558 (user-error "No more matches"))
13559 (when (equal (get-char-property p1 'org-type) 'org-occur)
13560 (setq n (1- n))
13561 (when (= n 0)
13562 (goto-char p1)
13563 (throw 'exit (point))))
13564 (goto-char p1))
13565 (goto-char p1)
13566 (user-error "No more matches"))))
13568 (defun org-show-context (&optional key)
13569 "Make sure point and context are visible.
13570 Optional argument KEY, when non-nil, is a symbol. See
13571 `org-show-context-detail' for allowed values and how much is to
13572 be shown."
13573 (org-show-set-visibility
13574 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13575 ((cdr (assq key org-show-context-detail)))
13576 (t (cdr (assq 'default org-show-context-detail))))))
13578 (defun org-show-set-visibility (detail)
13579 "Set visibility around point according to DETAIL.
13580 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13581 `tree', `canonical' or t. See `org-show-context-detail' for more
13582 information."
13583 ;; Show current heading and possibly its entry, following headline
13584 ;; or all children.
13585 (if (and (org-at-heading-p) (not (eq detail 'local)))
13586 (org-flag-heading nil)
13587 (org-show-entry)
13588 ;; If point is hidden within a drawer or a block, make sure to
13589 ;; expose it.
13590 (dolist (o (overlays-at (point)))
13591 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13592 (delete-overlay o)))
13593 (unless (org-before-first-heading-p)
13594 (org-with-limited-levels
13595 (cl-case detail
13596 ((tree canonical t) (org-show-children))
13597 ((nil minimal ancestors))
13598 (t (save-excursion
13599 (outline-next-heading)
13600 (org-flag-heading nil)))))))
13601 ;; Show all siblings.
13602 (when (eq detail 'lineage) (org-show-siblings))
13603 ;; Show ancestors, possibly with their children.
13604 (when (memq detail '(ancestors lineage tree canonical t))
13605 (save-excursion
13606 (while (org-up-heading-safe)
13607 (org-flag-heading nil)
13608 (when (memq detail '(canonical t)) (org-show-entry))
13609 (when (memq detail '(tree canonical t)) (org-show-children))))))
13611 (defvar org-reveal-start-hook nil
13612 "Hook run before revealing a location.")
13614 (defun org-reveal (&optional siblings)
13615 "Show current entry, hierarchy above it, and the following headline.
13617 This can be used to show a consistent set of context around
13618 locations exposed with `org-show-context'.
13620 With optional argument SIBLINGS, on each level of the hierarchy all
13621 siblings are shown. This repairs the tree structure to what it would
13622 look like when opened with hierarchical calls to `org-cycle'.
13624 With a \\[universal-argument] \\[universal-argument] prefix, \
13625 go to the parent and show the entire tree."
13626 (interactive "P")
13627 (run-hooks 'org-reveal-start-hook)
13628 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13629 ((equal siblings '(16))
13630 (save-excursion
13631 (when (org-up-heading-safe)
13632 (org-show-subtree)
13633 (run-hook-with-args 'org-cycle-hook 'subtree))))
13634 (t (org-show-set-visibility 'lineage))))
13636 (defun org-highlight-new-match (beg end)
13637 "Highlight from BEG to END and mark the highlight is an occur headline."
13638 (let ((ov (make-overlay beg end)))
13639 (overlay-put ov 'face 'secondary-selection)
13640 (overlay-put ov 'org-type 'org-occur)
13641 (push ov org-occur-highlights)))
13643 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13644 "Remove the occur highlights from the buffer.
13645 BEG and END are ignored. If NOREMOVE is nil, remove this function
13646 from the `before-change-functions' in the current buffer."
13647 (interactive)
13648 (unless org-inhibit-highlight-removal
13649 (mapc #'delete-overlay org-occur-highlights)
13650 (setq org-occur-highlights nil)
13651 (setq org-occur-parameters nil)
13652 (unless noremove
13653 (remove-hook 'before-change-functions
13654 'org-remove-occur-highlights 'local))))
13656 ;;;; Priorities
13658 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13659 "Regular expression matching the priority indicator.")
13661 (defvar org-remove-priority-next-time nil)
13663 (defun org-priority-up ()
13664 "Increase the priority of the current item."
13665 (interactive)
13666 (org-priority 'up))
13668 (defun org-priority-down ()
13669 "Decrease the priority of the current item."
13670 (interactive)
13671 (org-priority 'down))
13673 (defun org-priority (&optional action _show)
13674 "Change the priority of an item.
13675 ACTION can be `set', `up', `down', or a character."
13676 (interactive "P")
13677 (if (equal action '(4))
13678 (org-show-priority)
13679 (unless org-enable-priority-commands
13680 (user-error "Priority commands are disabled"))
13681 (setq action (or action 'set))
13682 (let (current new news have remove)
13683 (save-excursion
13684 (org-back-to-heading t)
13685 (when (looking-at org-priority-regexp)
13686 (setq current (string-to-char (match-string 2))
13687 have t))
13688 (cond
13689 ((eq action 'remove)
13690 (setq remove t new ?\ ))
13691 ((or (eq action 'set)
13692 (integerp action))
13693 (if (not (eq action 'set))
13694 (setq new action)
13695 (message "Priority %c-%c, SPC to remove: "
13696 org-highest-priority org-lowest-priority)
13697 (save-match-data
13698 (setq new (read-char-exclusive))))
13699 (when (and (= (upcase org-highest-priority) org-highest-priority)
13700 (= (upcase org-lowest-priority) org-lowest-priority))
13701 (setq new (upcase new)))
13702 (cond ((equal new ?\ ) (setq remove t))
13703 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13704 (user-error "Priority must be between `%c' and `%c'"
13705 org-highest-priority org-lowest-priority))))
13706 ((eq action 'up)
13707 (setq new (if have
13708 (1- current) ; normal cycling
13709 ;; last priority was empty
13710 (if (eq last-command this-command)
13711 org-lowest-priority ; wrap around empty to lowest
13712 ;; default
13713 (if org-priority-start-cycle-with-default
13714 org-default-priority
13715 (1- org-default-priority))))))
13716 ((eq action 'down)
13717 (setq new (if have
13718 (1+ current) ; normal cycling
13719 ;; last priority was empty
13720 (if (eq last-command this-command)
13721 org-highest-priority ; wrap around empty to highest
13722 ;; default
13723 (if org-priority-start-cycle-with-default
13724 org-default-priority
13725 (1+ org-default-priority))))))
13726 (t (user-error "Invalid action")))
13727 (when (or (< (upcase new) org-highest-priority)
13728 (> (upcase new) org-lowest-priority))
13729 (if (and (memq action '(up down))
13730 (not have) (not (eq last-command this-command)))
13731 ;; `new' is from default priority
13732 (error
13733 "The default can not be set, see `org-default-priority' why")
13734 ;; normal cycling: `new' is beyond highest/lowest priority
13735 ;; and is wrapped around to the empty priority
13736 (setq remove t)))
13737 (setq news (format "%c" new))
13738 (if have
13739 (if remove
13740 (replace-match "" t t nil 1)
13741 (replace-match news t t nil 2))
13742 (if remove
13743 (user-error "No priority cookie found in line")
13744 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13745 (if (match-end 2)
13746 (progn
13747 (goto-char (match-end 2))
13748 (insert " [#" news "]"))
13749 (goto-char (match-beginning 3))
13750 (insert "[#" news "] "))))
13751 (org-set-tags nil 'align))
13752 (if remove
13753 (message "Priority removed")
13754 (message "Priority of current item set to %s" news)))))
13756 (defun org-show-priority ()
13757 "Show the priority of the current item.
13758 This priority is composed of the main priority given with the [#A] cookies,
13759 and by additional input from the age of a schedules or deadline entry."
13760 (interactive)
13761 (let ((pri (if (eq major-mode 'org-agenda-mode)
13762 (org-get-at-bol 'priority)
13763 (save-excursion
13764 (save-match-data
13765 (beginning-of-line)
13766 (and (looking-at org-heading-regexp)
13767 (org-get-priority (match-string 0))))))))
13768 (message "Priority is %d" (if pri pri -1000))))
13770 (defun org-get-priority (s)
13771 "Find priority cookie and return priority."
13772 (save-match-data
13773 (if (functionp org-get-priority-function)
13774 (funcall org-get-priority-function)
13775 (if (not (string-match org-priority-regexp s))
13776 (* 1000 (- org-lowest-priority org-default-priority))
13777 (* 1000 (- org-lowest-priority
13778 (string-to-char (match-string 2 s))))))))
13780 ;;;; Tags
13782 (defvar org-agenda-archives-mode)
13783 (defvar org-map-continue-from nil
13784 "Position from where mapping should continue.
13785 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13787 (defvar org-scanner-tags nil
13788 "The current tag list while the tags scanner is running.")
13790 (defvar org-trust-scanner-tags nil
13791 "Should `org-get-tags-at' use the tags for the scanner.
13792 This is for internal dynamical scoping only.
13793 When this is non-nil, the function `org-get-tags-at' will return the value
13794 of `org-scanner-tags' instead of building the list by itself. This
13795 can lead to large speed-ups when the tags scanner is used in a file with
13796 many entries, and when the list of tags is retrieved, for example to
13797 obtain a list of properties. Building the tags list for each entry in such
13798 a file becomes an N^2 operation - but with this variable set, it scales
13799 as N.")
13801 (defvar org--matcher-tags-todo-only nil)
13803 (defun org-scan-tags (action matcher todo-only &optional start-level)
13804 "Scan headline tags with inheritance and produce output ACTION.
13806 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13807 or `agenda' to produce an entry list for an agenda view. It can also be
13808 a Lisp form or a function that should be called at each matched headline, in
13809 this case the return value is a list of all return values from these calls.
13811 MATCHER is a function accepting three arguments, returning
13812 a non-nil value whenever a given set of tags qualifies a headline
13813 for inclusion. See `org-make-tags-matcher' for more information.
13814 As a special case, it can also be set to t (respectively nil) in
13815 order to match all (respectively none) headline.
13817 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13818 included in the output.
13820 START-LEVEL can be a string with asterisks, reducing the scope to
13821 headlines matching this string."
13822 (require 'org-agenda)
13823 (let* ((re (concat "^"
13824 (if start-level
13825 ;; Get the correct level to match
13826 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13827 org-outline-regexp)
13828 " *\\(\\<\\("
13829 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13830 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13831 (props (list 'face 'default
13832 'done-face 'org-agenda-done
13833 'undone-face 'default
13834 'mouse-face 'highlight
13835 'org-not-done-regexp org-not-done-regexp
13836 'org-todo-regexp org-todo-regexp
13837 'org-complex-heading-regexp org-complex-heading-regexp
13838 'help-echo
13839 (format "mouse-2 or RET jump to org file %s"
13840 (abbreviate-file-name
13841 (or (buffer-file-name (buffer-base-buffer))
13842 (buffer-name (buffer-base-buffer)))))))
13843 (org-map-continue-from nil)
13844 lspos tags tags-list
13845 (tags-alist (list (cons 0 org-file-tags)))
13846 (llast 0) rtn rtn1 level category i txt
13847 todo marker entry priority
13848 ts-date ts-date-type ts-date-pair)
13849 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13850 (setq action (list 'lambda nil action)))
13851 (save-excursion
13852 (goto-char (point-min))
13853 (when (eq action 'sparse-tree)
13854 (org-overview)
13855 (org-remove-occur-highlights))
13856 (while (let (case-fold-search)
13857 (re-search-forward re nil t))
13858 (setq org-map-continue-from nil)
13859 (catch :skip
13860 (setq todo
13861 ;; TODO: is the 1-2 difference a bug?
13862 (when (match-end 1) (match-string-no-properties 2))
13863 tags (when (match-end 4) (match-string-no-properties 4)))
13864 (goto-char (setq lspos (match-beginning 0)))
13865 (setq level (org-reduced-level (org-outline-level))
13866 category (org-get-category))
13867 (when (eq action 'agenda)
13868 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13869 ts-date (car ts-date-pair)
13870 ts-date-type (cdr ts-date-pair)))
13871 (setq i llast llast level)
13872 ;; remove tag lists from same and sublevels
13873 (while (>= i level)
13874 (when (setq entry (assoc i tags-alist))
13875 (setq tags-alist (delete entry tags-alist)))
13876 (setq i (1- i)))
13877 ;; add the next tags
13878 (when tags
13879 (setq tags (org-split-string tags ":")
13880 tags-alist
13881 (cons (cons level tags) tags-alist)))
13882 ;; compile tags for current headline
13883 (setq tags-list
13884 (if org-use-tag-inheritance
13885 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13886 tags)
13887 org-scanner-tags tags-list)
13888 (when org-use-tag-inheritance
13889 (setcdr (car tags-alist)
13890 (mapcar (lambda (x)
13891 (setq x (copy-sequence x))
13892 (org-add-prop-inherited x))
13893 (cdar tags-alist))))
13894 (when (and tags org-use-tag-inheritance
13895 (or (not (eq t org-use-tag-inheritance))
13896 org-tags-exclude-from-inheritance))
13897 ;; Selective inheritance, remove uninherited ones.
13898 (setcdr (car tags-alist)
13899 (org-remove-uninherited-tags (cdar tags-alist))))
13900 (when (and
13902 ;; eval matcher only when the todo condition is OK
13903 (and (or (not todo-only) (member todo org-todo-keywords-1))
13904 (if (functionp matcher)
13905 (let ((case-fold-search t) (org-trust-scanner-tags t))
13906 (funcall matcher todo tags-list level))
13907 matcher))
13909 ;; Call the skipper, but return t if it does not
13910 ;; skip, so that the `and' form continues evaluating.
13911 (progn
13912 (unless (eq action 'sparse-tree) (org-agenda-skip))
13915 ;; Check if timestamps are deselecting this entry
13916 (or (not todo-only)
13917 (and (member todo org-todo-keywords-1)
13918 (or (not org-agenda-tags-todo-honor-ignore-options)
13919 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13921 ;; select this headline
13922 (cond
13923 ((eq action 'sparse-tree)
13924 (and org-highlight-sparse-tree-matches
13925 (org-get-heading) (match-end 0)
13926 (org-highlight-new-match
13927 (match-beginning 1) (match-end 1)))
13928 (org-show-context 'tags-tree))
13929 ((eq action 'agenda)
13930 (setq txt (org-agenda-format-item
13932 (concat
13933 (if (eq org-tags-match-list-sublevels 'indented)
13934 (make-string (1- level) ?.) "")
13935 (org-get-heading))
13936 (make-string level ?\s)
13937 category
13938 tags-list)
13939 priority (org-get-priority txt))
13940 (goto-char lspos)
13941 (setq marker (org-agenda-new-marker))
13942 (org-add-props txt props
13943 'org-marker marker 'org-hd-marker marker 'org-category category
13944 'todo-state todo
13945 'ts-date ts-date
13946 'priority priority
13947 'type (concat "tagsmatch" ts-date-type))
13948 (push txt rtn))
13949 ((functionp action)
13950 (setq org-map-continue-from nil)
13951 (save-excursion
13952 (setq rtn1 (funcall action))
13953 (push rtn1 rtn)))
13954 (t (user-error "Invalid action")))
13956 ;; if we are to skip sublevels, jump to end of subtree
13957 (unless org-tags-match-list-sublevels
13958 (org-end-of-subtree t)
13959 (backward-char 1))))
13960 ;; Get the correct position from where to continue
13961 (if org-map-continue-from
13962 (goto-char org-map-continue-from)
13963 (and (= (point) lspos) (end-of-line 1)))))
13964 (when (and (eq action 'sparse-tree)
13965 (not org-sparse-tree-open-archived-trees))
13966 (org-hide-archived-subtrees (point-min) (point-max)))
13967 (nreverse rtn)))
13969 (defun org-remove-uninherited-tags (tags)
13970 "Remove all tags that are not inherited from the list TAGS."
13971 (cond
13972 ((eq org-use-tag-inheritance t)
13973 (if org-tags-exclude-from-inheritance
13974 (org-delete-all org-tags-exclude-from-inheritance tags)
13975 tags))
13976 ((not org-use-tag-inheritance) nil)
13977 ((stringp org-use-tag-inheritance)
13978 (delq nil (mapcar
13979 (lambda (x)
13980 (if (and (string-match org-use-tag-inheritance x)
13981 (not (member x org-tags-exclude-from-inheritance)))
13982 x nil))
13983 tags)))
13984 ((listp org-use-tag-inheritance)
13985 (delq nil (mapcar
13986 (lambda (x)
13987 (if (member x org-use-tag-inheritance) x nil))
13988 tags)))))
13990 (defun org-match-sparse-tree (&optional todo-only match)
13991 "Create a sparse tree according to tags string MATCH.
13993 MATCH is a string with match syntax. It can contain a selection
13994 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13995 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13996 those. See the manual for details.
13998 If optional argument TODO-ONLY is non-nil, only select lines that
13999 are also TODO tasks."
14000 (interactive "P")
14001 (org-agenda-prepare-buffers (list (current-buffer)))
14002 (let ((org--matcher-tags-todo-only todo-only))
14003 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14004 org--matcher-tags-todo-only)))
14006 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14008 (defvar org-cached-props nil)
14009 (defun org-cached-entry-get (pom property)
14010 (if (or (eq t org-use-property-inheritance)
14011 (and (stringp org-use-property-inheritance)
14012 (let ((case-fold-search t))
14013 (string-match-p org-use-property-inheritance property)))
14014 (and (listp org-use-property-inheritance)
14015 (member-ignore-case property org-use-property-inheritance)))
14016 ;; Caching is not possible, check it directly.
14017 (org-entry-get pom property 'inherit)
14018 ;; Get all properties, so we can do complicated checks easily.
14019 (cdr (assoc-string property
14020 (or org-cached-props
14021 (setq org-cached-props (org-entry-properties pom)))
14022 t))))
14024 (defun org-global-tags-completion-table (&optional files)
14025 "Return the list of all tags in all agenda buffer/files.
14026 Optional FILES argument is a list of files which can be used
14027 instead of the agenda files."
14028 (save-excursion
14029 (org-uniquify
14030 (delq nil
14031 (apply #'append
14032 (mapcar
14033 (lambda (file)
14034 (set-buffer (find-file-noselect file))
14035 (mapcar (lambda (x)
14036 (and (stringp (car-safe x))
14037 (list (car-safe x))))
14038 (or org-current-tag-alist (org-get-buffer-tags))))
14039 (if (car-safe files) files
14040 (org-agenda-files))))))))
14042 (defun org-make-tags-matcher (match)
14043 "Create the TAGS/TODO matcher form for the selection string MATCH.
14045 Returns a cons of the selection string MATCH and a function
14046 implementing the matcher.
14048 The matcher is to be called at an Org entry, with point on the
14049 headline, and returns non-nil if the entry matches the selection
14050 string MATCH. It must be called with three arguments: the TODO
14051 keyword at the entry (or nil if none), the list of all tags at
14052 the entry including inherited ones and the reduced level of the
14053 headline. Additionally, the category of the entry, if any, must
14054 be specified as the text property `org-category' on the headline.
14056 This function sets the variable `org--matcher-tags-todo-only' to
14057 a non-nil value if the matcher restricts matching to TODO
14058 entries, otherwise it is not touched.
14060 See also `org-scan-tags'."
14061 (unless match
14062 ;; Get a new match request, with completion against the global
14063 ;; tags table and the local tags in current buffer.
14064 (let ((org-last-tags-completion-table
14065 (org-uniquify
14066 (delq nil (append (org-get-buffer-tags)
14067 (org-global-tags-completion-table))))))
14068 (setq match
14069 (completing-read
14070 "Match: "
14071 'org-tags-completion-function nil nil nil 'org-tags-history))))
14073 (let ((match0 match)
14074 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14075 (start 0)
14076 tagsmatch todomatch tagsmatcher todomatcher)
14078 ;; Expand group tags.
14079 (setq match (org-tags-expand match))
14081 ;; Check if there is a TODO part of this match, which would be the
14082 ;; part after a "/". To make sure that this slash is not part of
14083 ;; a property value to be matched against, we also check that
14084 ;; there is no / after that slash. First, find the last slash.
14085 (let ((s 0))
14086 (while (string-match "/+" match s)
14087 (setq start (match-beginning 0))
14088 (setq s (match-end 0))))
14089 (if (and (string-match "/+" match start)
14090 (not (string-match-p "\"" match start)))
14091 ;; Match contains also a TODO-matching request.
14092 (progn
14093 (setq tagsmatch (substring match 0 (match-beginning 0)))
14094 (setq todomatch (substring match (match-end 0)))
14095 (when (string-prefix-p "!" todomatch)
14096 (setq org--matcher-tags-todo-only t)
14097 (setq todomatch (substring todomatch 1)))
14098 (when (string-match "\\`\\s-*\\'" todomatch)
14099 (setq todomatch nil)))
14100 ;; Only matching tags.
14101 (setq tagsmatch match)
14102 (setq todomatch nil))
14104 ;; Make the tags matcher.
14105 (when (org-string-nw-p tagsmatch)
14106 (let ((orlist nil)
14107 (orterms (org-split-string tagsmatch "|"))
14108 term)
14109 (while (setq term (pop orterms))
14110 (while (and (equal (substring term -1) "\\") orterms)
14111 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14112 (while (string-match re term)
14113 (let* ((rest (substring term (match-end 0)))
14114 (minus (and (match-end 1)
14115 (equal (match-string 1 term) "-")))
14116 (tag (save-match-data
14117 (replace-regexp-in-string
14118 "\\\\-" "-" (match-string 2 term))))
14119 (regexp (eq (string-to-char tag) ?{))
14120 (levelp (match-end 4))
14121 (propp (match-end 5))
14123 (cond
14124 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14125 (levelp
14126 `(,(org-op-to-function (match-string 3 term))
14127 level
14128 ,(string-to-number (match-string 4 term))))
14129 (propp
14130 (let* ((gv (pcase (upcase (match-string 5 term))
14131 ("CATEGORY"
14132 '(get-text-property (point) 'org-category))
14133 ("TODO" 'todo)
14134 (p `(org-cached-entry-get nil ,p))))
14135 (pv (match-string 7 term))
14136 (regexp (eq (string-to-char pv) ?{))
14137 (strp (eq (string-to-char pv) ?\"))
14138 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14139 (po (org-op-to-function (match-string 6 term)
14140 (if timep 'time strp))))
14141 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14142 (when timep (setq pv (org-matcher-time pv)))
14143 (cond ((and regexp (eq po 'org<>))
14144 `(not (string-match ,pv (or ,gv ""))))
14145 (regexp `(string-match ,pv (or ,gv "")))
14146 (strp `(,po (or ,gv "") ,pv))
14148 `(,po
14149 (string-to-number (or ,gv ""))
14150 ,(string-to-number pv))))))
14151 (t `(member ,tag tags-list)))))
14152 (push (if minus `(not ,mm) mm) tagsmatcher)
14153 (setq term rest)))
14154 (push `(and ,@tagsmatcher) orlist)
14155 (setq tagsmatcher nil))
14156 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14158 ;; Make the TODO matcher.
14159 (when (org-string-nw-p todomatch)
14160 (let ((orlist nil))
14161 (dolist (term (org-split-string todomatch "|"))
14162 (while (string-match re term)
14163 (let* ((minus (and (match-end 1)
14164 (equal (match-string 1 term) "-")))
14165 (kwd (match-string 2 term))
14166 (regexp (eq (string-to-char kwd) ?{))
14167 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14168 `(equal todo ,kwd))))
14169 (push (if minus `(not ,mm) mm) todomatcher))
14170 (setq term (substring term (match-end 0))))
14171 (push (if (> (length todomatcher) 1)
14172 (cons 'and todomatcher)
14173 (car todomatcher))
14174 orlist)
14175 (setq todomatcher nil))
14176 (setq todomatcher (cons 'or orlist))))
14178 ;; Return the string and function of the matcher. If no
14179 ;; tags-specific or todo-specific matcher exists, match
14180 ;; everything.
14181 (let ((matcher (if (and tagsmatcher todomatcher)
14182 `(and ,tagsmatcher ,todomatcher)
14183 (or tagsmatcher todomatcher t))))
14184 (when org--matcher-tags-todo-only
14185 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14186 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14188 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14189 "Expand group tags in MATCH.
14191 This replaces every group tag in MATCH with a regexp tag search.
14192 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14193 will be replaced like this:
14195 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14196 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14197 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14199 Replacing by a regexp preserves the structure of the match.
14200 E.g., this expansion
14202 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14204 will match anything tagged with \"Lab\" and \"Home\", or tagged
14205 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14207 A group tag in MATCH can contain regular expressions of its own.
14208 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14209 will be replaced like this:
14211 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14213 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14214 assumed to be a single group tag, and the function will return
14215 the list of tags in this group.
14217 When DOWNCASE is non-nil, expand downcased TAGS."
14218 (if org-group-tags
14219 (let* ((case-fold-search t)
14220 (stable org-mode-syntax-table)
14221 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14222 (taggroups (if downcased
14223 (mapcar (lambda (tg) (mapcar #'downcase tg))
14224 taggroups)
14225 taggroups))
14226 (taggroups-keys (mapcar #'car taggroups))
14227 (return-match (if downcased (downcase match) match))
14228 (count 0)
14229 (work-already-expanded tags-already-expanded)
14230 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14231 ;; @ and _ are allowed as word-components in tags.
14232 (modify-syntax-entry ?@ "w" stable)
14233 (modify-syntax-entry ?_ "w" stable)
14234 ;; Temporarily replace regexp-expressions in the match-expression.
14235 (while (string-match "{.+?}" return-match)
14236 (cl-incf count)
14237 (push (match-string 0 return-match) regexps-in-match)
14238 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14239 (while (and taggroups-keys
14240 (with-syntax-table stable
14241 (string-match
14242 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14243 (regexp-opt taggroups-keys) "\\>\\)")
14244 return-match)))
14245 (let* ((dir (match-string 1 return-match))
14246 (tag (match-string 2 return-match))
14247 (tag (if downcased (downcase tag) tag)))
14248 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14249 (member tag work-already-expanded))
14250 (setq tags-in-group (assoc tag taggroups))
14251 (push tag work-already-expanded)
14252 ;; Recursively expand each tag in the group, if the tag hasn't
14253 ;; already been expanded. Restore the match-data after all recursive calls.
14254 (save-match-data
14255 (let (tags-expanded)
14256 (dolist (x (cdr tags-in-group))
14257 (if (and (member x taggroups-keys)
14258 (not (member x work-already-expanded)))
14259 (setq tags-expanded
14260 (delete-dups
14261 (append
14262 (org-tags-expand x t downcased
14263 work-already-expanded)
14264 tags-expanded)))
14265 (setq tags-expanded
14266 (append (list x) tags-expanded)))
14267 (setq work-already-expanded
14268 (delete-dups
14269 (append tags-expanded
14270 work-already-expanded))))
14271 (setq tags-in-group
14272 (delete-dups (cons (car tags-in-group)
14273 tags-expanded)))))
14274 ;; Filter tag-regexps from tags.
14275 (setq regexp-in-group-escaped
14276 (delq nil (mapcar (lambda (x)
14277 (if (stringp x)
14278 (and (equal "{" (substring x 0 1))
14279 (equal "}" (substring x -1))
14282 tags-in-group))
14283 regexp-in-group
14284 (mapcar (lambda (x)
14285 (substring x 1 -1))
14286 regexp-in-group-escaped)
14287 tags-in-group
14288 (delq nil (mapcar (lambda (x)
14289 (if (stringp x)
14290 (and (not (equal "{" (substring x 0 1)))
14291 (not (equal "}" (substring x -1)))
14294 tags-in-group)))
14295 ;; If single-as-list, do no more in the while-loop.
14296 (if (not single-as-list)
14297 (progn
14298 (when regexp-in-group
14299 (setq regexp-in-group
14300 (concat "\\|"
14301 (mapconcat 'identity regexp-in-group
14302 "\\|"))))
14303 (setq tags-in-group
14304 (concat dir
14305 "{\\<"
14306 (regexp-opt tags-in-group)
14307 "\\>"
14308 regexp-in-group
14309 "}"))
14310 (when (stringp tags-in-group)
14311 (org-add-props tags-in-group '(grouptag t)))
14312 (setq return-match
14313 (replace-match tags-in-group t t return-match)))
14314 (setq tags-in-group
14315 (append regexp-in-group-escaped tags-in-group))))
14316 (setq taggroups-keys (delete tag taggroups-keys))))
14317 ;; Add the regular expressions back into the match-expression again.
14318 (while regexps-in-match
14319 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14320 (pop regexps-in-match)
14321 return-match t t))
14322 (cl-decf count))
14323 (if single-as-list
14324 (if tags-in-group tags-in-group (list return-match))
14325 return-match))
14326 (if single-as-list
14327 (list (if downcased (downcase match) match))
14328 match)))
14330 (defun org-op-to-function (op &optional stringp)
14331 "Turn an operator into the appropriate function."
14332 (setq op
14333 (cond
14334 ((equal op "<" ) '(< string< org-time<))
14335 ((equal op ">" ) '(> org-string> org-time>))
14336 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14337 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14338 ((member op '("=" "==")) '(= string= org-time=))
14339 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14340 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14342 (defun org<> (a b) (not (= a b)))
14343 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14344 (defun org-string>= (a b) (not (string< a b)))
14345 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14346 (defun org-string<> (a b) (not (string= a b)))
14347 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14348 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14349 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14350 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14351 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14352 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14353 (defun org-2ft (s)
14354 "Convert S to a floating point time.
14355 If S is already a number, just return it. If it is a string, parse
14356 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14357 (cond
14358 ((numberp s) s)
14359 ((stringp s)
14360 (condition-case nil
14361 (float-time (apply #'encode-time (org-parse-time-string s)))
14362 (error 0.)))
14363 (t 0.)))
14365 (defun org-time-today ()
14366 "Time in seconds today at 0:00.
14367 Returns the float number of seconds since the beginning of the
14368 epoch to the beginning of today (00:00)."
14369 (float-time (apply 'encode-time
14370 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14372 (defun org-matcher-time (s)
14373 "Interpret a time comparison value."
14374 (save-match-data
14375 (cond
14376 ((string= s "<now>") (float-time))
14377 ((string= s "<today>") (org-time-today))
14378 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14379 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14380 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14381 (+ (org-time-today)
14382 (* (string-to-number (match-string 1 s))
14383 (cdr (assoc (match-string 2 s)
14384 '(("d" . 86400.0) ("w" . 604800.0)
14385 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14386 (t (org-2ft s)))))
14388 (defun org-match-any-p (re list)
14389 "Does re match any element of list?"
14390 (setq list (mapcar (lambda (x) (string-match re x)) list))
14391 (delq nil list))
14393 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14394 (defvar org-tags-overlay (make-overlay 1 1))
14395 (delete-overlay org-tags-overlay)
14397 (defun org-get-local-tags-at (&optional pos)
14398 "Get a list of tags defined in the current headline."
14399 (org-get-tags-at pos 'local))
14401 (defun org-get-local-tags ()
14402 "Get a list of tags defined in the current headline."
14403 (org-get-tags-at nil 'local))
14405 (defun org-get-tags-at (&optional pos local)
14406 "Get a list of all headline tags applicable at POS.
14407 POS defaults to point. If tags are inherited, the list contains
14408 the targets in the same sequence as the headlines appear, i.e.
14409 the tags of the current headline come last.
14410 When LOCAL is non-nil, only return tags from the current headline,
14411 ignore inherited ones."
14412 (interactive)
14413 (if (and org-trust-scanner-tags
14414 (or (not pos) (equal pos (point)))
14415 (not local))
14416 org-scanner-tags
14417 (let (tags ltags lastpos parent)
14418 (save-excursion
14419 (save-restriction
14420 (widen)
14421 (goto-char (or pos (point)))
14422 (save-match-data
14423 (catch 'done
14424 (condition-case nil
14425 (progn
14426 (org-back-to-heading t)
14427 (while (not (equal lastpos (point)))
14428 (setq lastpos (point))
14429 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14430 (setq ltags (org-split-string
14431 (match-string-no-properties 1) ":"))
14432 (when parent
14433 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14434 (setq tags (append
14435 (if parent
14436 (org-remove-uninherited-tags ltags)
14437 ltags)
14438 tags)))
14439 (or org-use-tag-inheritance (throw 'done t))
14440 (when local (throw 'done t))
14441 (or (org-up-heading-safe) (error nil))
14442 (setq parent t)))
14443 (error nil)))))
14444 (if local
14445 tags
14446 (reverse (delete-dups
14447 (reverse (append
14448 (org-remove-uninherited-tags
14449 org-file-tags)
14450 tags)))))))))
14452 (defun org-add-prop-inherited (s)
14453 (add-text-properties 0 (length s) '(inherited t) s)
14456 (defun org-toggle-tag (tag &optional onoff)
14457 "Toggle the tag TAG for the current line.
14458 If ONOFF is `on' or `off', don't toggle but set to this state."
14459 (save-excursion
14460 (org-back-to-heading t)
14461 (let ((current
14462 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14463 (line-end-position) t)
14464 (let ((tags (match-string 1)))
14465 ;; Clear current tags.
14466 (replace-match "")
14467 ;; Reverse the tags list so any new tag is appended to
14468 ;; the current list of tags.
14469 (nreverse (org-split-string tags ":")))))
14470 res)
14471 (pcase onoff
14472 (`off (setq current (delete tag current)))
14473 ((or `on (guard (not (member tag current))))
14474 (setq res t)
14475 (cl-pushnew tag current :test #'equal))
14476 (_ (setq current (delete tag current))))
14477 (end-of-line)
14478 (if current
14479 (progn
14480 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14481 (org-set-tags nil t))
14482 (delete-horizontal-space))
14483 (run-hooks 'org-after-tags-change-hook)
14484 res)))
14486 (defun org--align-tags-here (to-col)
14487 "Align tags on the current headline to TO-COL.
14488 Assume point is on a headline."
14489 (let ((pos (point)))
14490 (beginning-of-line)
14491 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14492 (>= pos (match-beginning 2)))
14493 ;; No tags or point within tags: do not align.
14494 (goto-char pos)
14495 (goto-char (match-beginning 1))
14496 (let ((shift (max (- (if (>= to-col 0) to-col
14497 (- (abs to-col) (string-width (match-string 2))))
14498 (current-column))
14499 1)))
14500 (replace-match (make-string shift ?\s) nil nil nil 1)
14501 ;; Preserve initial position, if possible. In any case, stop
14502 ;; before tags.
14503 (when (< pos (point)) (goto-char pos))))))
14505 (defun org-set-tags-command (&optional arg just-align)
14506 "Call the set-tags command for the current entry."
14507 (interactive "P")
14508 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14509 (org-set-tags arg just-align)
14510 (save-excursion
14511 (unless (and (org-region-active-p)
14512 org-loop-over-headlines-in-active-region)
14513 (org-back-to-heading t))
14514 (org-set-tags arg just-align))))
14516 (defun org-set-tags-to (data)
14517 "Set the tags of the current entry to DATA, replacing the current tags.
14518 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14519 If DATA is nil or the empty string, any tags will be removed."
14520 (interactive "sTags: ")
14521 (setq data
14522 (cond
14523 ((eq data nil) "")
14524 ((equal data "") "")
14525 ((stringp data)
14526 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14527 ":"))
14528 ((listp data)
14529 (concat ":" (mapconcat 'identity data ":") ":"))))
14530 (when data
14531 (save-excursion
14532 (org-back-to-heading t)
14533 (when (let ((case-fold-search nil))
14534 (looking-at org-complex-heading-regexp))
14535 (if (match-end 5)
14536 (progn
14537 (goto-char (match-beginning 5))
14538 (insert data)
14539 (delete-region (point) (point-at-eol))
14540 (org-set-tags nil 'align))
14541 (goto-char (point-at-eol))
14542 (insert " " data)
14543 (org-set-tags nil 'align)))
14544 (beginning-of-line 1)
14545 (when (looking-at ".*?\\([ \t]+\\)$")
14546 (delete-region (match-beginning 1) (match-end 1))))))
14548 (defun org-align-all-tags ()
14549 "Align the tags in all headings."
14550 (interactive)
14551 (save-excursion
14552 (or (ignore-errors (org-back-to-heading t))
14553 (outline-next-heading))
14554 (if (org-at-heading-p)
14555 (org-set-tags t)
14556 (message "No headings"))))
14558 (defvar org-indent-indentation-per-level)
14559 (defun org-set-tags (&optional arg just-align)
14560 "Set the tags for the current headline.
14561 With prefix ARG, realign all tags in headings in the current buffer.
14562 When JUST-ALIGN is non-nil, only align tags."
14563 (interactive "P")
14564 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14565 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14566 'region-start-level
14567 'region))
14568 org-loop-over-headlines-in-active-region)
14569 (org-map-entries
14570 ;; We don't use ARG and JUST-ALIGN here because these args
14571 ;; are not useful when looping over headlines.
14572 #'org-set-tags
14573 org-loop-over-headlines-in-active-region
14575 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14576 (let ((org-setting-tags t))
14577 (if arg
14578 (save-excursion
14579 (goto-char (point-min))
14580 (while (re-search-forward org-outline-regexp-bol nil t)
14581 (org-set-tags nil t)
14582 (end-of-line))
14583 (message "All tags realigned to column %d" org-tags-column))
14584 (let* ((current (org-get-tags-string))
14585 (tags
14586 (if just-align current
14587 ;; Get a new set of tags from the user.
14588 (save-excursion
14589 (let* ((seen)
14590 (table
14591 (setq
14592 org-last-tags-completion-table
14593 ;; Uniquify tags in alists, yet preserve
14594 ;; structure (i.e., keywords).
14595 (delq nil
14596 (mapcar
14597 (lambda (pair)
14598 (let ((head (car pair)))
14599 (cond ((symbolp head) pair)
14600 ((member head seen) nil)
14601 (t (push head seen)
14602 pair))))
14603 (append
14604 (or org-current-tag-alist
14605 (org-get-buffer-tags))
14606 (and
14607 org-complete-tags-always-offer-all-agenda-tags
14608 (org-global-tags-completion-table
14609 (org-agenda-files))))))))
14610 (current-tags (org-split-string current ":"))
14611 (inherited-tags
14612 (nreverse (nthcdr (length current-tags)
14613 (nreverse (org-get-tags-at))))))
14614 (replace-regexp-in-string
14615 "\\([-+&]+\\|,\\)"
14617 (if (or (eq t org-use-fast-tag-selection)
14618 (and org-use-fast-tag-selection
14619 (delq nil (mapcar #'cdr table))))
14620 (org-fast-tag-selection
14621 current-tags inherited-tags table
14622 (and org-fast-tag-selection-include-todo
14623 org-todo-key-alist))
14624 (let ((org-add-colon-after-tag-completion
14625 (< 1 (length table))))
14626 (org-trim
14627 (completing-read
14628 "Tags: "
14629 #'org-tags-completion-function
14630 nil nil current 'org-tags-history))))))))))
14632 (when org-tags-sort-function
14633 (setq tags
14634 (mapconcat
14635 #'identity
14636 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14637 org-tags-sort-function)
14638 ":")))
14640 (if (or (string= ":" tags)
14641 (string= "::" tags))
14642 (setq tags ""))
14643 (if (not (org-string-nw-p tags)) (setq tags "")
14644 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14645 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14647 ;; Insert new tags at the correct column.
14648 (unless (equal current tags)
14649 (save-excursion
14650 (beginning-of-line)
14651 (let ((case-fold-search nil))
14652 (looking-at org-complex-heading-regexp))
14653 ;; Remove current tags, if any.
14654 (when (match-end 5) (replace-match "" nil nil nil 5))
14655 ;; Insert new tags, if any. Otherwise, remove trailing
14656 ;; white spaces.
14657 (end-of-line)
14658 (if (not (equal tags ""))
14659 ;; When text is being inserted on an invisible
14660 ;; region boundary, it can be inadvertently sucked
14661 ;; into invisibility.
14662 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14663 (skip-chars-backward " \t")
14664 (delete-region (point) (line-end-position)))))
14665 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14666 ;; is on.
14667 (unless (equal tags "")
14668 (let* ((level (save-excursion
14669 (beginning-of-line)
14670 (skip-chars-forward "\\*")))
14671 (offset (if (bound-and-true-p org-indent-mode)
14672 (* (1- org-indent-indentation-per-level)
14673 (1- level))
14675 (tags-column
14676 (+ org-tags-column
14677 (if (> org-tags-column 0) (- offset) offset))))
14678 (org--align-tags-here tags-column))))
14679 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14681 (defun org-change-tag-in-region (beg end tag off)
14682 "Add or remove TAG for each entry in the region.
14683 This works in the agenda, and also in an Org buffer."
14684 (interactive
14685 (list (region-beginning) (region-end)
14686 (let ((org-last-tags-completion-table
14687 (if (derived-mode-p 'org-mode)
14688 (org-uniquify
14689 (delq nil (append (org-get-buffer-tags)
14690 (org-global-tags-completion-table))))
14691 (org-global-tags-completion-table))))
14692 (completing-read
14693 "Tag: " 'org-tags-completion-function nil nil nil
14694 'org-tags-history))
14695 (progn
14696 (message "[s]et or [r]emove? ")
14697 (equal (read-char-exclusive) ?r))))
14698 (when (fboundp 'deactivate-mark) (deactivate-mark))
14699 (let ((agendap (equal major-mode 'org-agenda-mode))
14700 l1 l2 m buf pos newhead (cnt 0))
14701 (goto-char end)
14702 (setq l2 (1- (org-current-line)))
14703 (goto-char beg)
14704 (setq l1 (org-current-line))
14705 (cl-loop for l from l1 to l2 do
14706 (org-goto-line l)
14707 (setq m (get-text-property (point) 'org-hd-marker))
14708 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14709 (and agendap m))
14710 (setq buf (if agendap (marker-buffer m) (current-buffer))
14711 pos (if agendap m (point)))
14712 (with-current-buffer buf
14713 (save-excursion
14714 (save-restriction
14715 (goto-char pos)
14716 (setq cnt (1+ cnt))
14717 (org-toggle-tag tag (if off 'off 'on))
14718 (setq newhead (org-get-heading)))))
14719 (and agendap (org-agenda-change-all-lines newhead m))))
14720 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14722 (defun org-tags-completion-function (string _predicate &optional flag)
14723 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14724 (confirm (lambda (x) (stringp (car x)))))
14725 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14726 (setq s1 (match-string 1 string)
14727 s2 (match-string 2 string))
14728 (setq s1 "" s2 string))
14729 (cond
14730 ((eq flag nil)
14731 ;; try completion
14732 (setq rtn (try-completion s2 ctable confirm))
14733 (when (stringp rtn)
14734 (setq rtn
14735 (concat s1 s2 (substring rtn (length s2))
14736 (if (and org-add-colon-after-tag-completion
14737 (assoc rtn ctable))
14738 ":" ""))))
14739 rtn)
14740 ((eq flag t)
14741 ;; all-completions
14742 (all-completions s2 ctable confirm))
14743 ((eq flag 'lambda)
14744 ;; exact match?
14745 (assoc s2 ctable)))))
14747 (defun org-fast-tag-insert (kwd tags face &optional end)
14748 "Insert KDW, and the TAGS, the latter with face FACE.
14749 Also insert END."
14750 (insert (format "%-12s" (concat kwd ":"))
14751 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14752 (or end "")))
14754 (defun org-fast-tag-show-exit (flag)
14755 (save-excursion
14756 (org-goto-line 3)
14757 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14758 (replace-match ""))
14759 (when flag
14760 (end-of-line 1)
14761 (org-move-to-column (- (window-width) 19) t)
14762 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14764 (defun org-set-current-tags-overlay (current prefix)
14765 "Add an overlay to CURRENT tag with PREFIX."
14766 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14767 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14768 (org-overlay-display org-tags-overlay (concat prefix s))))
14770 (defvar org-last-tag-selection-key nil)
14771 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14772 "Fast tag selection with single keys.
14773 CURRENT is the current list of tags in the headline, INHERITED is the
14774 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14775 possibly with grouping information. TODO-TABLE is a similar table with
14776 TODO keywords, should these have keys assigned to them.
14777 If the keys are nil, a-z are automatically assigned.
14778 Returns the new tags string, or nil to not change the current settings."
14779 (let* ((fulltable (append table todo-table))
14780 (maxlen (apply 'max (mapcar
14781 (lambda (x)
14782 (if (stringp (car x)) (string-width (car x)) 0))
14783 fulltable)))
14784 (buf (current-buffer))
14785 (expert (eq org-fast-tag-selection-single-key 'expert))
14786 (buffer-tags nil)
14787 (fwidth (+ maxlen 3 1 3))
14788 (ncol (/ (- (window-width) 4) fwidth))
14789 (i-face 'org-done)
14790 (c-face 'org-todo)
14791 tg cnt e c char c1 c2 ntable tbl rtn
14792 ov-start ov-end ov-prefix
14793 (exit-after-next org-fast-tag-selection-single-key)
14794 (done-keywords org-done-keywords)
14795 groups ingroup intaggroup)
14796 (save-excursion
14797 (beginning-of-line 1)
14798 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14799 (setq ov-start (match-beginning 1)
14800 ov-end (match-end 1)
14801 ov-prefix "")
14802 (setq ov-start (1- (point-at-eol))
14803 ov-end (1+ ov-start))
14804 (skip-chars-forward "^\n\r")
14805 (setq ov-prefix
14806 (concat
14807 (buffer-substring (1- (point)) (point))
14808 (if (> (current-column) org-tags-column)
14810 (make-string (- org-tags-column (current-column)) ?\ ))))))
14811 (move-overlay org-tags-overlay ov-start ov-end)
14812 (save-window-excursion
14813 (if expert
14814 (set-buffer (get-buffer-create " *Org tags*"))
14815 (delete-other-windows)
14816 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14817 (org-switch-to-buffer-other-window " *Org tags*"))
14818 (erase-buffer)
14819 (setq-local org-done-keywords done-keywords)
14820 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14821 (org-fast-tag-insert "Current" current c-face "\n\n")
14822 (org-fast-tag-show-exit exit-after-next)
14823 (org-set-current-tags-overlay current ov-prefix)
14824 (setq tbl fulltable char ?a cnt 0)
14825 (while (setq e (pop tbl))
14826 (cond
14827 ((eq (car e) :startgroup)
14828 (push '() groups) (setq ingroup t)
14829 (unless (zerop cnt)
14830 (setq cnt 0)
14831 (insert "\n"))
14832 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14833 ((eq (car e) :endgroup)
14834 (setq ingroup nil cnt 0)
14835 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14836 ((eq (car e) :startgrouptag)
14837 (setq intaggroup t)
14838 (unless (zerop cnt)
14839 (setq cnt 0)
14840 (insert "\n"))
14841 (insert "[ "))
14842 ((eq (car e) :endgrouptag)
14843 (setq intaggroup nil cnt 0)
14844 (insert "]\n"))
14845 ((equal e '(:newline))
14846 (unless (zerop cnt)
14847 (setq cnt 0)
14848 (insert "\n")
14849 (setq e (car tbl))
14850 (while (equal (car tbl) '(:newline))
14851 (insert "\n")
14852 (setq tbl (cdr tbl)))))
14853 ((equal e '(:grouptags)) (insert " : "))
14855 (setq tg (copy-sequence (car e)) c2 nil)
14856 (if (cdr e)
14857 (setq c (cdr e))
14858 ;; automatically assign a character.
14859 (setq c1 (string-to-char
14860 (downcase (substring
14861 tg (if (= (string-to-char tg) ?@) 1 0)))))
14862 (if (or (rassoc c1 ntable) (rassoc c1 table))
14863 (while (or (rassoc char ntable) (rassoc char table))
14864 (setq char (1+ char)))
14865 (setq c2 c1))
14866 (setq c (or c2 char)))
14867 (when ingroup (push tg (car groups)))
14868 (setq tg (org-add-props tg nil 'face
14869 (cond
14870 ((not (assoc tg table))
14871 (org-get-todo-face tg))
14872 ((member tg current) c-face)
14873 ((member tg inherited) i-face))))
14874 (when (equal (caar tbl) :grouptags)
14875 (org-add-props tg nil 'face 'org-tag-group))
14876 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14877 (insert "[" c "] " tg (make-string
14878 (- fwidth 4 (length tg)) ?\ ))
14879 (push (cons tg c) ntable)
14880 (when (= (cl-incf cnt) ncol)
14881 (insert "\n")
14882 (when (or ingroup intaggroup) (insert " "))
14883 (setq cnt 0)))))
14884 (setq ntable (nreverse ntable))
14885 (insert "\n")
14886 (goto-char (point-min))
14887 (unless expert (org-fit-window-to-buffer))
14888 (setq rtn
14889 (catch 'exit
14890 (while t
14891 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14892 (if (not groups) "no " "")
14893 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14894 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14895 (setq org-last-tag-selection-key c)
14896 (cond
14897 ((= c ?\r) (throw 'exit t))
14898 ((= c ?!)
14899 (setq groups (not groups))
14900 (goto-char (point-min))
14901 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14902 ((= c ?\C-c)
14903 (if (not expert)
14904 (org-fast-tag-show-exit
14905 (setq exit-after-next (not exit-after-next)))
14906 (setq expert nil)
14907 (delete-other-windows)
14908 (set-window-buffer (split-window-vertically) " *Org tags*")
14909 (org-switch-to-buffer-other-window " *Org tags*")
14910 (org-fit-window-to-buffer)))
14911 ((or (= c ?\C-g)
14912 (and (= c ?q) (not (rassoc c ntable))))
14913 (delete-overlay org-tags-overlay)
14914 (setq quit-flag t))
14915 ((= c ?\ )
14916 (setq current nil)
14917 (when exit-after-next (setq exit-after-next 'now)))
14918 ((= c ?\t)
14919 (condition-case nil
14920 (setq tg (completing-read
14921 "Tag: "
14922 (or buffer-tags
14923 (with-current-buffer buf
14924 (setq buffer-tags
14925 (org-get-buffer-tags))))))
14926 (quit (setq tg "")))
14927 (when (string-match "\\S-" tg)
14928 (cl-pushnew (list tg) buffer-tags :test #'equal)
14929 (if (member tg current)
14930 (setq current (delete tg current))
14931 (push tg current)))
14932 (when exit-after-next (setq exit-after-next 'now)))
14933 ((setq e (rassoc c todo-table) tg (car e))
14934 (with-current-buffer buf
14935 (save-excursion (org-todo tg)))
14936 (when exit-after-next (setq exit-after-next 'now)))
14937 ((setq e (rassoc c ntable) tg (car e))
14938 (if (member tg current)
14939 (setq current (delete tg current))
14940 (cl-loop for g in groups do
14941 (when (member tg g)
14942 (dolist (x g) (setq current (delete x current)))))
14943 (push tg current))
14944 (when exit-after-next (setq exit-after-next 'now))))
14946 ;; Create a sorted list
14947 (setq current
14948 (sort current
14949 (lambda (a b)
14950 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14951 (when (eq exit-after-next 'now) (throw 'exit t))
14952 (goto-char (point-min))
14953 (beginning-of-line 2)
14954 (delete-region (point) (point-at-eol))
14955 (org-fast-tag-insert "Current" current c-face)
14956 (org-set-current-tags-overlay current ov-prefix)
14957 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14958 (setq tg (match-string 1))
14959 (add-text-properties
14960 (match-beginning 1) (match-end 1)
14961 (list 'face
14962 (cond
14963 ((member tg current) c-face)
14964 ((member tg inherited) i-face)
14965 (t (get-text-property (match-beginning 1) 'face))))))
14966 (goto-char (point-min)))))
14967 (delete-overlay org-tags-overlay)
14968 (if rtn
14969 (mapconcat 'identity current ":")
14970 nil))))
14972 (defun org-get-tags-string ()
14973 "Get the TAGS string in the current headline."
14974 (unless (org-at-heading-p t)
14975 (user-error "Not on a heading"))
14976 (save-excursion
14977 (beginning-of-line 1)
14978 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14979 (match-string-no-properties 1)
14980 "")))
14982 (defun org-get-tags ()
14983 "Get the list of tags specified in the current headline."
14984 (org-split-string (org-get-tags-string) ":"))
14986 (defun org-get-buffer-tags ()
14987 "Get a table of all tags used in the buffer, for completion."
14988 (org-with-wide-buffer
14989 (goto-char (point-min))
14990 (let ((tag-re (concat org-outline-regexp-bol
14991 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14992 tags)
14993 (while (re-search-forward tag-re nil t)
14994 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14995 (push tag tags)))
14996 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14998 ;;;; The mapping API
15000 (defvar org-agenda-skip-comment-trees)
15001 (defvar org-agenda-skip-function)
15002 (defun org-map-entries (func &optional match scope &rest skip)
15003 "Call FUNC at each headline selected by MATCH in SCOPE.
15005 FUNC is a function or a lisp form. The function will be called without
15006 arguments, with the cursor positioned at the beginning of the headline.
15007 The return values of all calls to the function will be collected and
15008 returned as a list.
15010 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15011 does not need to preserve point. After evaluation, the cursor will be
15012 moved to the end of the line (presumably of the headline of the
15013 processed entry) and search continues from there. Under some
15014 circumstances, this may not produce the wanted results. For example,
15015 if you have removed (e.g. archived) the current (sub)tree it could
15016 mean that the next entry will be skipped entirely. In such cases, you
15017 can specify the position from where search should continue by making
15018 FUNC set the variable `org-map-continue-from' to the desired buffer
15019 position.
15021 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15022 Only headlines that are matched by this query will be considered during
15023 the iteration. When MATCH is nil or t, all headlines will be
15024 visited by the iteration.
15026 SCOPE determines the scope of this command. It can be any of:
15028 nil The current buffer, respecting the restriction if any
15029 tree The subtree started with the entry at point
15030 region The entries within the active region, if any
15031 region-start-level
15032 The entries within the active region, but only those at
15033 the same level than the first one.
15034 file The current buffer, without restriction
15035 file-with-archives
15036 The current buffer, and any archives associated with it
15037 agenda All agenda files
15038 agenda-with-archives
15039 All agenda files with any archive files associated with them
15040 \(file1 file2 ...)
15041 If this is a list, all files in the list will be scanned
15043 The remaining args are treated as settings for the skipping facilities of
15044 the scanner. The following items can be given here:
15046 archive skip trees with the archive tag
15047 comment skip trees with the COMMENT keyword
15048 function or Emacs Lisp form:
15049 will be used as value for `org-agenda-skip-function', so
15050 whenever the function returns a position, FUNC will not be
15051 called for that entry and search will continue from the
15052 position returned
15054 If your function needs to retrieve the tags including inherited tags
15055 at the *current* entry, you can use the value of the variable
15056 `org-scanner-tags' which will be much faster than getting the value
15057 with `org-get-tags-at'. If your function gets properties with
15058 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15059 to t around the call to `org-entry-properties' to get the same speedup.
15060 Note that if your function moves around to retrieve tags and properties at
15061 a *different* entry, you cannot use these techniques."
15062 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15063 (not (org-region-active-p)))
15064 (let* ((org-agenda-archives-mode nil) ; just to make sure
15065 (org-agenda-skip-archived-trees (memq 'archive skip))
15066 (org-agenda-skip-comment-trees (memq 'comment skip))
15067 (org-agenda-skip-function
15068 (car (org-delete-all '(comment archive) skip)))
15069 (org-tags-match-list-sublevels t)
15070 (start-level (eq scope 'region-start-level))
15071 matcher res
15072 org-todo-keywords-for-agenda
15073 org-done-keywords-for-agenda
15074 org-todo-keyword-alist-for-agenda
15075 org-tag-alist-for-agenda
15076 org--matcher-tags-todo-only)
15078 (cond
15079 ((eq match t) (setq matcher t))
15080 ((eq match nil) (setq matcher t))
15081 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15083 (save-excursion
15084 (save-restriction
15085 (cond ((eq scope 'tree)
15086 (org-back-to-heading t)
15087 (org-narrow-to-subtree)
15088 (setq scope nil))
15089 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15090 (org-region-active-p))
15091 ;; If needed, set start-level to a string like "2"
15092 (when start-level
15093 (save-excursion
15094 (goto-char (region-beginning))
15095 (unless (org-at-heading-p) (outline-next-heading))
15096 (setq start-level (org-current-level))))
15097 (narrow-to-region (region-beginning)
15098 (save-excursion
15099 (goto-char (region-end))
15100 (unless (and (bolp) (org-at-heading-p))
15101 (outline-next-heading))
15102 (point)))
15103 (setq scope nil)))
15105 (if (not scope)
15106 (progn
15107 (org-agenda-prepare-buffers
15108 (and buffer-file-name (list buffer-file-name)))
15109 (setq res
15110 (org-scan-tags
15111 func matcher org--matcher-tags-todo-only start-level)))
15112 ;; Get the right scope
15113 (cond
15114 ((and scope (listp scope) (symbolp (car scope)))
15115 (setq scope (eval scope)))
15116 ((eq scope 'agenda)
15117 (setq scope (org-agenda-files t)))
15118 ((eq scope 'agenda-with-archives)
15119 (setq scope (org-agenda-files t))
15120 (setq scope (org-add-archive-files scope)))
15121 ((eq scope 'file)
15122 (setq scope (and buffer-file-name (list buffer-file-name))))
15123 ((eq scope 'file-with-archives)
15124 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15125 (org-agenda-prepare-buffers scope)
15126 (dolist (file scope)
15127 (with-current-buffer (org-find-base-buffer-visiting file)
15128 (org-with-wide-buffer
15129 (goto-char (point-min))
15130 (setq res
15131 (append
15133 (org-scan-tags
15134 func matcher org--matcher-tags-todo-only)))))))))
15135 res)))
15137 ;;; Properties API
15139 (defconst org-special-properties
15140 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15141 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15142 "The special properties valid in Org mode.
15143 These are properties that are not defined in the property drawer,
15144 but in some other way.")
15146 (defconst org-default-properties
15147 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15148 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15149 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15150 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15151 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15152 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15153 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15154 "Some properties that are used by Org mode for various purposes.
15155 Being in this list makes sure that they are offered for completion.")
15157 (defun org--valid-property-p (property)
15158 "Non nil when string PROPERTY is a valid property name."
15159 (not
15160 (or (equal property "")
15161 (string-match-p "\\s-" property))))
15163 (defun org--update-property-plist (key val props)
15164 "Associate KEY to VAL in alist PROPS.
15165 Modifications are made by side-effect. Return new alist."
15166 (let* ((appending (string= (substring key -1) "+"))
15167 (key (if appending (substring key 0 -1) key))
15168 (old (assoc-string key props t)))
15169 (if (not old) (cons (cons key val) props)
15170 (setcdr old (if appending (concat (cdr old) " " val) val))
15171 props)))
15173 (defun org-get-property-block (&optional beg force)
15174 "Return the (beg . end) range of the body of the property drawer.
15175 BEG is the beginning of the current subtree, or of the part
15176 before the first headline. If it is not given, it will be found.
15177 If the drawer does not exist, create it if FORCE is non-nil, or
15178 return nil."
15179 (org-with-wide-buffer
15180 (when beg (goto-char beg))
15181 (unless (org-before-first-heading-p)
15182 (let ((beg (cond (beg)
15183 ((or (not (featurep 'org-inlinetask))
15184 (org-inlinetask-in-task-p))
15185 (org-back-to-heading t))
15186 (t (org-with-limited-levels (org-back-to-heading t))))))
15187 (forward-line)
15188 (when (looking-at-p org-planning-line-re) (forward-line))
15189 (cond ((looking-at org-property-drawer-re)
15190 (forward-line)
15191 (cons (point) (progn (goto-char (match-end 0))
15192 (line-beginning-position))))
15193 (force
15194 (goto-char beg)
15195 (org-insert-property-drawer)
15196 (let ((pos (save-excursion (search-forward ":END:")
15197 (line-beginning-position))))
15198 (cons pos pos))))))))
15200 (defun org-at-property-p ()
15201 "Non-nil when point is inside a property drawer.
15202 See `org-property-re' for match data, if applicable."
15203 (save-excursion
15204 (beginning-of-line)
15205 (and (looking-at org-property-re)
15206 (let ((property-drawer (save-match-data (org-get-property-block))))
15207 (and property-drawer
15208 (>= (point) (car property-drawer))
15209 (< (point) (cdr property-drawer)))))))
15211 (defun org-property-action ()
15212 "Do an action on properties."
15213 (interactive)
15214 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15215 (let ((c (read-char-exclusive)))
15216 (cl-case c
15217 (?s (call-interactively #'org-set-property))
15218 (?d (call-interactively #'org-delete-property))
15219 (?D (call-interactively #'org-delete-property-globally))
15220 (?c (call-interactively #'org-compute-property-at-point))
15221 (otherwise (user-error "No such property action %c" c)))))
15223 (defun org-inc-effort ()
15224 "Increment the value of the effort property in the current entry."
15225 (interactive)
15226 (org-set-effort nil t))
15228 (defvar org-clock-effort) ; Defined in org-clock.el.
15229 (defvar org-clock-current-task) ; Defined in org-clock.el.
15230 (defun org-set-effort (&optional value increment)
15231 "Set the effort property of the current entry.
15232 With numerical prefix arg, use the nth allowed value, 0 stands for the
15233 10th allowed value.
15235 When INCREMENT is non-nil, set the property to the next allowed value."
15236 (interactive "P")
15237 (when (equal value 0) (setq value 10))
15238 (let* ((completion-ignore-case t)
15239 (prop org-effort-property)
15240 (cur (org-entry-get nil prop))
15241 (allowed (org-property-get-allowed-values nil prop 'table))
15242 (existing (mapcar 'list (org-property-values prop)))
15243 (heading (nth 4 (org-heading-components)))
15245 (val (cond
15246 ((stringp value) value)
15247 ((and allowed (integerp value))
15248 (or (car (nth (1- value) allowed))
15249 (car (org-last allowed))))
15250 ((and allowed increment)
15251 (or (cl-caadr (member (list cur) allowed))
15252 (user-error "Allowed effort values are not set")))
15253 (allowed
15254 (message "Select 1-9,0, [RET%s]: %s"
15255 (if cur (concat "=" cur) "")
15256 (mapconcat 'car allowed " "))
15257 (setq rpl (read-char-exclusive))
15258 (if (equal rpl ?\r)
15260 (setq rpl (- rpl ?0))
15261 (when (equal rpl 0) (setq rpl 10))
15262 (if (and (> rpl 0) (<= rpl (length allowed)))
15263 (car (nth (1- rpl) allowed))
15264 (org-completing-read "Effort: " allowed nil))))
15266 (org-completing-read
15267 (concat "Effort" (and cur (string-match "\\S-" cur)
15268 (concat " [" cur "]"))
15269 ": ")
15270 existing nil nil "" nil cur)))))
15271 (unless (equal (org-entry-get nil prop) val)
15272 (org-entry-put nil prop val))
15273 (org-refresh-property
15274 '((effort . identity)
15275 (effort-minutes . org-duration-to-minutes))
15276 val)
15277 (when (equal heading (bound-and-true-p org-clock-current-task))
15278 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15279 (org-clock-update-mode-line))
15280 (message "%s is now %s" prop val)))
15282 (defun org-entry-properties (&optional pom which)
15283 "Get all properties of the current entry.
15285 When POM is a buffer position, get all properties from the entry
15286 there instead.
15288 This includes the TODO keyword, the tags, time strings for
15289 deadline, scheduled, and clocking, and any additional properties
15290 defined in the entry.
15292 If WHICH is nil or `all', get all properties. If WHICH is
15293 `special' or `standard', only get that subclass. If WHICH is
15294 a string, only get that property.
15296 Return value is an alist. Keys are properties, as upcased
15297 strings."
15298 (org-with-point-at pom
15299 (when (and (derived-mode-p 'org-mode)
15300 (ignore-errors (org-back-to-heading t)))
15301 (catch 'exit
15302 (let* ((beg (point))
15303 (specific (and (stringp which) (upcase which)))
15304 (which (cond ((not specific) which)
15305 ((member specific org-special-properties) 'special)
15306 (t 'standard)))
15307 props)
15308 ;; Get the special properties, like TODO and TAGS.
15309 (when (memq which '(nil all special))
15310 (when (or (not specific) (string= specific "CLOCKSUM"))
15311 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15312 (when clocksum
15313 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15314 props)))
15315 (when specific (throw 'exit props)))
15316 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15317 (let ((clocksumt (get-text-property (point)
15318 :org-clock-minutes-today)))
15319 (when clocksumt
15320 (push (cons "CLOCKSUM_T"
15321 (org-duration-from-minutes clocksumt))
15322 props)))
15323 (when specific (throw 'exit props)))
15324 (when (or (not specific) (string= specific "ITEM"))
15325 (let ((case-fold-search nil))
15326 (when (looking-at org-complex-heading-regexp)
15327 (push (cons "ITEM"
15328 (let ((title (match-string-no-properties 4)))
15329 (if (org-string-nw-p title)
15330 (org-remove-tabs title)
15331 "")))
15332 props)))
15333 (when specific (throw 'exit props)))
15334 (when (or (not specific) (string= specific "TODO"))
15335 (let ((case-fold-search nil))
15336 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15337 (push (cons "TODO" (match-string-no-properties 2)) props)))
15338 (when specific (throw 'exit props)))
15339 (when (or (not specific) (string= specific "PRIORITY"))
15340 (push (cons "PRIORITY"
15341 (if (looking-at org-priority-regexp)
15342 (match-string-no-properties 2)
15343 (char-to-string org-default-priority)))
15344 props)
15345 (when specific (throw 'exit props)))
15346 (when (or (not specific) (string= specific "FILE"))
15347 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15348 props)
15349 (when specific (throw 'exit props)))
15350 (when (or (not specific) (string= specific "TAGS"))
15351 (let ((value (org-string-nw-p (org-get-tags-string))))
15352 (when value (push (cons "TAGS" value) props)))
15353 (when specific (throw 'exit props)))
15354 (when (or (not specific) (string= specific "ALLTAGS"))
15355 (let ((value (org-get-tags-at)))
15356 (when value
15357 (push (cons "ALLTAGS"
15358 (format ":%s:" (mapconcat #'identity value ":")))
15359 props)))
15360 (when specific (throw 'exit props)))
15361 (when (or (not specific) (string= specific "BLOCKED"))
15362 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15363 (when specific (throw 'exit props)))
15364 (when (or (not specific)
15365 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15366 (forward-line)
15367 (when (looking-at-p org-planning-line-re)
15368 (end-of-line)
15369 (let ((bol (line-beginning-position))
15370 ;; Backward compatibility: time keywords used to
15371 ;; be configurable (before 8.3). Make sure we
15372 ;; get the correct keyword.
15373 (key-assoc `(("CLOSED" . ,org-closed-string)
15374 ("DEADLINE" . ,org-deadline-string)
15375 ("SCHEDULED" . ,org-scheduled-string))))
15376 (dolist (pair (if specific (list (assoc specific key-assoc))
15377 key-assoc))
15378 (save-excursion
15379 (when (search-backward (cdr pair) bol t)
15380 (goto-char (match-end 0))
15381 (skip-chars-forward " \t")
15382 (and (looking-at org-ts-regexp-both)
15383 (push (cons (car pair)
15384 (match-string-no-properties 0))
15385 props)))))))
15386 (when specific (throw 'exit props)))
15387 (when (or (not specific)
15388 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15389 (let ((find-ts
15390 (lambda (end ts)
15391 ;; Fix next time-stamp before END. TS is the
15392 ;; list of time-stamps found so far.
15393 (let ((ts ts)
15394 (regexp (cond
15395 ((string= specific "TIMESTAMP")
15396 org-ts-regexp)
15397 ((string= specific "TIMESTAMP_IA")
15398 org-ts-regexp-inactive)
15399 ((assoc "TIMESTAMP_IA" ts)
15400 org-ts-regexp)
15401 ((assoc "TIMESTAMP" ts)
15402 org-ts-regexp-inactive)
15403 (t org-ts-regexp-both))))
15404 (catch 'next
15405 (while (re-search-forward regexp end t)
15406 (backward-char)
15407 (let ((object (org-element-context)))
15408 ;; Accept to match timestamps in node
15409 ;; properties, too.
15410 (when (memq (org-element-type object)
15411 '(node-property timestamp))
15412 (let ((type
15413 (org-element-property :type object)))
15414 (cond
15415 ((and (memq type '(active active-range))
15416 (not (equal specific "TIMESTAMP_IA")))
15417 (unless (assoc "TIMESTAMP" ts)
15418 (push (cons "TIMESTAMP"
15419 (org-element-property
15420 :raw-value object))
15422 (when specific (throw 'exit ts))))
15423 ((and (memq type '(inactive inactive-range))
15424 (not (string= specific "TIMESTAMP")))
15425 (unless (assoc "TIMESTAMP_IA" ts)
15426 (push (cons "TIMESTAMP_IA"
15427 (org-element-property
15428 :raw-value object))
15430 (when specific (throw 'exit ts))))))
15431 ;; Both timestamp types are found,
15432 ;; move to next part.
15433 (when (= (length ts) 2) (throw 'next ts)))))
15434 ts)))))
15435 (goto-char beg)
15436 ;; First look for timestamps within headline.
15437 (let ((ts (funcall find-ts (line-end-position) nil)))
15438 (if (= (length ts) 2) (setq props (nconc ts props))
15439 ;; Then find timestamps in the section, skipping
15440 ;; planning line.
15441 (let ((end (save-excursion (outline-next-heading))))
15442 (forward-line)
15443 (when (looking-at-p org-planning-line-re) (forward-line))
15444 (setq props (nconc (funcall find-ts end ts) props))))))))
15445 ;; Get the standard properties, like :PROP:.
15446 (when (memq which '(nil all standard))
15447 ;; If we are looking after a specific property, delegate
15448 ;; to `org-entry-get', which is faster. However, make an
15449 ;; exception for "CATEGORY", since it can be also set
15450 ;; through keywords (i.e. #+CATEGORY).
15451 (if (and specific (not (equal specific "CATEGORY")))
15452 (let ((value (org-entry-get beg specific nil t)))
15453 (throw 'exit (and value (list (cons specific value)))))
15454 (let ((range (org-get-property-block beg)))
15455 (when range
15456 (let ((end (cdr range)) seen-base)
15457 (goto-char (car range))
15458 ;; Unlike to `org--update-property-plist', we
15459 ;; handle the case where base values is found
15460 ;; after its extension. We also forbid standard
15461 ;; properties to be named as special properties.
15462 (while (re-search-forward org-property-re end t)
15463 (let* ((key (upcase (match-string-no-properties 2)))
15464 (extendp (string-match-p "\\+\\'" key))
15465 (key-base (if extendp (substring key 0 -1) key))
15466 (value (match-string-no-properties 3)))
15467 (cond
15468 ((member-ignore-case key-base org-special-properties))
15469 (extendp
15470 (setq props
15471 (org--update-property-plist key value props)))
15472 ((member key seen-base))
15473 (t (push key seen-base)
15474 (let ((p (assoc-string key props t)))
15475 (if p (setcdr p (concat value " " (cdr p)))
15476 (push (cons key value) props))))))))))))
15477 (unless (assoc "CATEGORY" props)
15478 (push (cons "CATEGORY" (org-get-category beg)) props)
15479 (when (string= specific "CATEGORY") (throw 'exit props)))
15480 ;; Return value.
15481 props)))))
15483 (defun org--property-local-values (property literal-nil)
15484 "Return value for PROPERTY in current entry.
15485 Value is a list whose car is the base value for PROPERTY and cdr
15486 a list of accumulated values. Return nil if neither is found in
15487 the entry. Also return nil when PROPERTY is set to \"nil\",
15488 unless LITERAL-NIL is non-nil."
15489 (let ((range (org-get-property-block)))
15490 (when range
15491 (goto-char (car range))
15492 (let* ((case-fold-search t)
15493 (end (cdr range))
15494 (value
15495 ;; Base value.
15496 (save-excursion
15497 (let ((v (and (re-search-forward
15498 (org-re-property property nil t) end t)
15499 (match-string-no-properties 3))))
15500 (list (if literal-nil v (org-not-nil v)))))))
15501 ;; Find additional values.
15502 (let* ((property+ (org-re-property (concat property "+") nil t)))
15503 (while (re-search-forward property+ end t)
15504 (push (match-string-no-properties 3) value)))
15505 ;; Return final values.
15506 (and (not (equal value '(nil))) (nreverse value))))))
15508 (defun org--property-global-value (property literal-nil)
15509 "Return value for PROPERTY in current buffer.
15510 Return value is a string. Return nil if property is not set
15511 globally. Also return nil when PROPERTY is set to \"nil\",
15512 unless LITERAL-NIL is non-nil."
15513 (let ((global
15514 (cdr (or (assoc-string property org-file-properties t)
15515 (assoc-string property org-global-properties t)
15516 (assoc-string property org-global-properties-fixed t)))))
15517 (if literal-nil global (org-not-nil global))))
15519 (defun org-entry-get (pom property &optional inherit literal-nil)
15520 "Get value of PROPERTY for entry or content at point-or-marker POM.
15522 If INHERIT is non-nil and the entry does not have the property,
15523 then also check higher levels of the hierarchy. If INHERIT is
15524 the symbol `selective', use inheritance only if the setting in
15525 `org-use-property-inheritance' selects PROPERTY for inheritance.
15527 If the property is present but empty, the return value is the
15528 empty string. If the property is not present at all, nil is
15529 returned. In any other case, return the value as a string.
15530 Search is case-insensitive.
15532 If LITERAL-NIL is set, return the string value \"nil\" as
15533 a string, do not interpret it as the list atom nil. This is used
15534 for inheritance when a \"nil\" value can supersede a non-nil
15535 value higher up the hierarchy."
15536 (org-with-point-at pom
15537 (cond
15538 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15539 ;; We need a special property. Use `org-entry-properties' to
15540 ;; retrieve it, but specify the wanted property.
15541 (cdr (assoc-string property (org-entry-properties nil property))))
15542 ((and inherit
15543 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15544 (org-entry-get-with-inheritance property literal-nil))
15546 (let* ((local (org--property-local-values property literal-nil))
15547 (value (and local (mapconcat #'identity (delq nil local) " "))))
15548 (if literal-nil value (org-not-nil value)))))))
15550 (defun org-property-or-variable-value (var &optional inherit)
15551 "Check if there is a property fixing the value of VAR.
15552 If yes, return this value. If not, return the current value of the variable."
15553 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15554 (if (and prop (stringp prop) (string-match "\\S-" prop))
15555 (read prop)
15556 (symbol-value var))))
15558 (defun org-entry-delete (pom property)
15559 "Delete PROPERTY from entry at point-or-marker POM.
15560 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15561 non-nil when a property was removed."
15562 (org-with-point-at pom
15563 (pcase (org-get-property-block)
15564 (`(,begin . ,origin)
15565 (let* ((end (copy-marker origin))
15566 (re (org-re-property
15567 (concat (regexp-quote property) "\\+?") t t)))
15568 (goto-char begin)
15569 (while (re-search-forward re end t)
15570 (delete-region (match-beginning 0) (line-beginning-position 2)))
15571 ;; If drawer is empty, remove it altogether.
15572 (when (= begin end)
15573 (delete-region (line-beginning-position 0)
15574 (line-beginning-position 2)))
15575 ;; Return non-nil if some property was removed.
15576 (prog1 (/= end origin) (set-marker end nil))))
15577 (_ nil))))
15579 ;; Multi-values properties are properties that contain multiple values
15580 ;; These values are assumed to be single words, separated by whitespace.
15581 (defun org-entry-add-to-multivalued-property (pom property value)
15582 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15583 (let* ((old (org-entry-get pom property))
15584 (values (and old (split-string old))))
15585 (setq value (org-entry-protect-space value))
15586 (unless (member value values)
15587 (setq values (append values (list value)))
15588 (org-entry-put pom property (mapconcat #'identity values " ")))))
15590 (defun org-entry-remove-from-multivalued-property (pom property value)
15591 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15592 (let* ((old (org-entry-get pom property))
15593 (values (and old (split-string old))))
15594 (setq value (org-entry-protect-space value))
15595 (when (member value values)
15596 (setq values (delete value values))
15597 (org-entry-put pom property (mapconcat #'identity values " ")))))
15599 (defun org-entry-member-in-multivalued-property (pom property value)
15600 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15601 (let* ((old (org-entry-get pom property))
15602 (values (and old (split-string old))))
15603 (setq value (org-entry-protect-space value))
15604 (member value values)))
15606 (defun org-entry-get-multivalued-property (pom property)
15607 "Return a list of values in a multivalued property."
15608 (let* ((value (org-entry-get pom property))
15609 (values (and value (split-string value))))
15610 (mapcar #'org-entry-restore-space values)))
15612 (defun org-entry-put-multivalued-property (pom property &rest values)
15613 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15614 VALUES should be a list of strings. Spaces will be protected."
15615 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15616 (let* ((value (org-entry-get pom property))
15617 (values (and value (split-string value))))
15618 (mapcar #'org-entry-restore-space values)))
15620 (defun org-entry-protect-space (s)
15621 "Protect spaces and newline in string S."
15622 (while (string-match " " s)
15623 (setq s (replace-match "%20" t t s)))
15624 (while (string-match "\n" s)
15625 (setq s (replace-match "%0A" t t s)))
15628 (defun org-entry-restore-space (s)
15629 "Restore spaces and newline in string S."
15630 (while (string-match "%20" s)
15631 (setq s (replace-match " " t t s)))
15632 (while (string-match "%0A" s)
15633 (setq s (replace-match "\n" t t s)))
15636 (defvar org-entry-property-inherited-from (make-marker)
15637 "Marker pointing to the entry from where a property was inherited.
15638 Each call to `org-entry-get-with-inheritance' will set this marker to the
15639 location of the entry where the inheritance search matched. If there was
15640 no match, the marker will point nowhere.
15641 Note that also `org-entry-get' calls this function, if the INHERIT flag
15642 is set.")
15644 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15645 "Get PROPERTY of entry or content at point, search higher levels if needed.
15646 The search will stop at the first ancestor which has the property defined.
15647 If the value found is \"nil\", return nil to show that the property
15648 should be considered as undefined (this is the meaning of nil here).
15649 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15650 (move-marker org-entry-property-inherited-from nil)
15651 (org-with-wide-buffer
15652 (let (value)
15653 (catch 'exit
15654 (while t
15655 (let ((v (org--property-local-values property literal-nil)))
15656 (when v
15657 (setq value
15658 (concat (mapconcat #'identity (delq nil v) " ")
15659 (and value " ")
15660 value)))
15661 (cond
15662 ((car v)
15663 (org-back-to-heading t)
15664 (move-marker org-entry-property-inherited-from (point))
15665 (throw 'exit nil))
15666 ((org-up-heading-safe))
15668 (let ((global (org--property-global-value property literal-nil)))
15669 (cond ((not global))
15670 (value (setq value (concat global " " value)))
15671 (t (setq value global))))
15672 (throw 'exit nil))))))
15673 (if literal-nil value (org-not-nil value)))))
15675 (defvar org-property-changed-functions nil
15676 "Hook called when the value of a property has changed.
15677 Each hook function should accept two arguments, the name of the property
15678 and the new value.")
15680 (defun org-entry-put (pom property value)
15681 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15683 If the value is nil, it is converted to the empty string. If it
15684 is not a string, an error is raised. Also raise an error on
15685 invalid property names.
15687 PROPERTY can be any regular property (see
15688 `org-special-properties'). It can also be \"TODO\",
15689 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15691 For the last two properties, VALUE may have any of the special
15692 values \"earlier\" and \"later\". The function then increases or
15693 decreases scheduled or deadline date by one day."
15694 (cond ((null value) (setq value ""))
15695 ((not (stringp value)) (error "Properties values should be strings"))
15696 ((not (org--valid-property-p property))
15697 (user-error "Invalid property name: \"%s\"" property)))
15698 (org-with-point-at pom
15699 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15700 (org-back-to-heading t)
15701 (org-with-limited-levels (org-back-to-heading t)))
15702 (let ((beg (point)))
15703 (cond
15704 ((equal property "TODO")
15705 (cond ((not (org-string-nw-p value)) (setq value 'none))
15706 ((not (member value org-todo-keywords-1))
15707 (user-error "\"%s\" is not a valid TODO state" value)))
15708 (org-todo value)
15709 (org-set-tags nil 'align))
15710 ((equal property "PRIORITY")
15711 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15712 (org-set-tags nil 'align))
15713 ((equal property "SCHEDULED")
15714 (forward-line)
15715 (if (and (looking-at-p org-planning-line-re)
15716 (re-search-forward
15717 org-scheduled-time-regexp (line-end-position) t))
15718 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15719 ((string= value "later") (org-timestamp-change 1 'day))
15720 ((string= value "") (org-schedule '(4)))
15721 (t (org-schedule nil value)))
15722 (if (member value '("earlier" "later" ""))
15723 (call-interactively #'org-schedule)
15724 (org-schedule nil value))))
15725 ((equal property "DEADLINE")
15726 (forward-line)
15727 (if (and (looking-at-p org-planning-line-re)
15728 (re-search-forward
15729 org-deadline-time-regexp (line-end-position) t))
15730 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15731 ((string= value "later") (org-timestamp-change 1 'day))
15732 ((string= value "") (org-deadline '(4)))
15733 (t (org-deadline nil value)))
15734 (if (member value '("earlier" "later" ""))
15735 (call-interactively #'org-deadline)
15736 (org-deadline nil value))))
15737 ((member property org-special-properties)
15738 (error "The %s property cannot be set with `org-entry-put'" property))
15740 (let* ((range (org-get-property-block beg 'force))
15741 (end (cdr range))
15742 (case-fold-search t))
15743 (goto-char (car range))
15744 (if (re-search-forward (org-re-property property nil t) end t)
15745 (progn (delete-region (match-beginning 0) (match-end 0))
15746 (goto-char (match-beginning 0)))
15747 (goto-char end)
15748 (insert "\n")
15749 (backward-char))
15750 (insert ":" property ":")
15751 (when value (insert " " value))
15752 (org-indent-line)))))
15753 (run-hook-with-args 'org-property-changed-functions property value)))
15755 (defun org-buffer-property-keys (&optional specials defaults columns)
15756 "Get all property keys in the current buffer.
15758 When SPECIALS is non-nil, also list the special properties that
15759 reflect things like tags and TODO state.
15761 When DEFAULTS is non-nil, also include properties that has
15762 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15763 DESCRIPTION, LOCATION, and LOGGING and others.
15765 When COLUMNS in non-nil, also include property names given in
15766 COLUMN formats in the current buffer."
15767 (let ((case-fold-search t)
15768 (props (append
15769 (and specials org-special-properties)
15770 (and defaults (cons org-effort-property org-default-properties))
15771 nil)))
15772 (org-with-wide-buffer
15773 (goto-char (point-min))
15774 (while (re-search-forward org-property-start-re nil t)
15775 (catch :skip
15776 (let ((range (org-get-property-block)))
15777 (unless range (throw :skip nil))
15778 (goto-char (car range))
15779 (let ((begin (car range))
15780 (end (cdr range)))
15781 ;; Make sure that found property block is not located
15782 ;; before current point, as it would generate an infloop.
15783 ;; It can happen, for example, in the following
15784 ;; situation:
15786 ;; * Headline
15787 ;; :PROPERTIES:
15788 ;; ...
15789 ;; :END:
15790 ;; *************** Inlinetask
15791 ;; #+BEGIN_EXAMPLE
15792 ;; :PROPERTIES:
15793 ;; #+END_EXAMPLE
15795 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15796 (while (< (point) end)
15797 (let ((p (progn (looking-at org-property-re)
15798 (match-string-no-properties 2))))
15799 ;; Only add true property name, not extension symbol.
15800 (push (if (not (string-match-p "\\+\\'" p)) p
15801 (substring p 0 -1))
15802 props))
15803 (forward-line))))
15804 (outline-next-heading)))
15805 (when columns
15806 (goto-char (point-min))
15807 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15808 (let ((element (org-element-at-point)))
15809 (when (memq (org-element-type element) '(keyword node-property))
15810 (let ((value (org-element-property :value element))
15811 (start 0))
15812 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15813 \\(?:{[^}]+}\\)?"
15814 value start)
15815 (setq start (match-end 0))
15816 (let ((p (match-string-no-properties 1 value)))
15817 (unless (member-ignore-case p org-special-properties)
15818 (push p props))))))))))
15819 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15821 (defun org-property-values (key)
15822 "List all non-nil values of property KEY in current buffer."
15823 (org-with-wide-buffer
15824 (goto-char (point-min))
15825 (let ((case-fold-search t)
15826 (re (org-re-property key))
15827 values)
15828 (while (re-search-forward re nil t)
15829 (push (org-entry-get (point) key) values))
15830 (delete-dups values))))
15832 (defun org-insert-property-drawer ()
15833 "Insert a property drawer into the current entry."
15834 (org-with-wide-buffer
15835 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15836 (org-back-to-heading t)
15837 (org-with-limited-levels (org-back-to-heading t)))
15838 (forward-line)
15839 (when (looking-at-p org-planning-line-re) (forward-line))
15840 (unless (looking-at-p org-property-drawer-re)
15841 ;; Make sure we start editing a line from current entry, not from
15842 ;; next one. It prevents extending text properties or overlays
15843 ;; belonging to the latter.
15844 (when (bolp) (backward-char))
15845 (let ((begin (1+ (point)))
15846 (inhibit-read-only t))
15847 (insert "\n:PROPERTIES:\n:END:")
15848 (when (eobp) (insert "\n"))
15849 (org-indent-region begin (point))))))
15851 (defun org-insert-drawer (&optional arg drawer)
15852 "Insert a drawer at point.
15854 When optional argument ARG is non-nil, insert a property drawer.
15856 Optional argument DRAWER, when non-nil, is a string representing
15857 drawer's name. Otherwise, the user is prompted for a name.
15859 If a region is active, insert the drawer around that region
15860 instead.
15862 Point is left between drawer's boundaries."
15863 (interactive "P")
15864 (let* ((drawer (if arg "PROPERTIES"
15865 (or drawer (read-from-minibuffer "Drawer: ")))))
15866 (cond
15867 ;; With C-u, fall back on `org-insert-property-drawer'
15868 (arg (org-insert-property-drawer))
15869 ;; Check validity of suggested drawer's name.
15870 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15871 (user-error "Invalid drawer name"))
15872 ;; With an active region, insert a drawer at point.
15873 ((not (org-region-active-p))
15874 (progn
15875 (unless (bolp) (insert "\n"))
15876 (insert (format ":%s:\n\n:END:\n" drawer))
15877 (forward-line -2)))
15878 ;; Otherwise, insert the drawer at point
15880 (let ((rbeg (region-beginning))
15881 (rend (copy-marker (region-end))))
15882 (unwind-protect
15883 (progn
15884 (goto-char rbeg)
15885 (beginning-of-line)
15886 (when (save-excursion
15887 (re-search-forward org-outline-regexp-bol rend t))
15888 (user-error "Drawers cannot contain headlines"))
15889 ;; Position point at the beginning of the first
15890 ;; non-blank line in region. Insert drawer's opening
15891 ;; there, then indent it.
15892 (org-skip-whitespace)
15893 (beginning-of-line)
15894 (insert ":" drawer ":\n")
15895 (forward-line -1)
15896 (indent-for-tab-command)
15897 ;; Move point to the beginning of the first blank line
15898 ;; after the last non-blank line in region. Insert
15899 ;; drawer's closing, then indent it.
15900 (goto-char rend)
15901 (skip-chars-backward " \r\t\n")
15902 (insert "\n:END:")
15903 (deactivate-mark t)
15904 (indent-for-tab-command)
15905 (unless (eolp) (insert "\n")))
15906 ;; Clear marker, whatever the outcome of insertion is.
15907 (set-marker rend nil)))))))
15909 (defvar org-property-set-functions-alist nil
15910 "Property set function alist.
15911 Each entry should have the following format:
15913 (PROPERTY . READ-FUNCTION)
15915 The read function will be called with the same argument as
15916 `org-completing-read'.")
15918 (defun org-set-property-function (property)
15919 "Get the function that should be used to set PROPERTY.
15920 This is computed according to `org-property-set-functions-alist'."
15921 (or (cdr (assoc property org-property-set-functions-alist))
15922 'org-completing-read))
15924 (defun org-read-property-value (property)
15925 "Read PROPERTY value from user."
15926 (let* ((completion-ignore-case t)
15927 (allowed (org-property-get-allowed-values nil property 'table))
15928 (cur (org-entry-get nil property))
15929 (prompt (concat property " value"
15930 (if (and cur (string-match "\\S-" cur))
15931 (concat " [" cur "]") "") ": "))
15932 (set-function (org-set-property-function property))
15933 (val (if allowed
15934 (funcall set-function prompt allowed nil
15935 (not (get-text-property 0 'org-unrestricted
15936 (caar allowed))))
15937 (funcall set-function prompt
15938 (mapcar 'list (org-property-values property))
15939 nil nil "" nil cur))))
15940 (org-trim val)))
15942 (defvar org-last-set-property nil)
15943 (defvar org-last-set-property-value nil)
15944 (defun org-read-property-name ()
15945 "Read a property name."
15946 (let ((completion-ignore-case t)
15947 (default-prop (or (and (org-at-property-p)
15948 (match-string-no-properties 2))
15949 org-last-set-property)))
15950 (org-completing-read
15951 (concat "Property"
15952 (if default-prop (concat " [" default-prop "]") "")
15953 ": ")
15954 (mapcar #'list (org-buffer-property-keys nil t t))
15955 nil nil nil nil default-prop)))
15957 (defun org-set-property-and-value (use-last)
15958 "Allow to set [PROPERTY]: [value] direction from prompt.
15959 When use-default, don't even ask, just use the last
15960 \"[PROPERTY]: [value]\" string from the history."
15961 (interactive "P")
15962 (let* ((completion-ignore-case t)
15963 (pv (or (and use-last org-last-set-property-value)
15964 (org-completing-read
15965 "Enter a \"[Property]: [value]\" pair: "
15966 nil nil nil nil nil
15967 org-last-set-property-value)))
15968 prop val)
15969 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15970 (setq prop (match-string 1 pv)
15971 val (match-string 2 pv))
15972 (org-set-property prop val))))
15974 (defun org-set-property (property value)
15975 "In the current entry, set PROPERTY to VALUE.
15977 When called interactively, this will prompt for a property name, offering
15978 completion on existing and default properties. And then it will prompt
15979 for a value, offering completion either on allowed values (via an inherited
15980 xxx_ALL property) or on existing values in other instances of this property
15981 in the current file.
15983 Throw an error when trying to set a property with an invalid name."
15984 (interactive (list nil nil))
15985 (let ((property (or property (org-read-property-name))))
15986 ;; `org-entry-put' also makes the following check, but this one
15987 ;; avoids polluting `org-last-set-property' and
15988 ;; `org-last-set-property-value' needlessly.
15989 (unless (org--valid-property-p property)
15990 (user-error "Invalid property name: \"%s\"" property))
15991 (let ((value (or value (org-read-property-value property)))
15992 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15993 (setq org-last-set-property property)
15994 (setq org-last-set-property-value (concat property ": " value))
15995 ;; Possibly postprocess the inserted value:
15996 (when fn (setq value (funcall fn value)))
15997 (unless (equal (org-entry-get nil property) value)
15998 (org-entry-put nil property value)))))
16000 (defun org-find-property (property &optional value)
16001 "Find first entry in buffer that sets PROPERTY.
16003 When optional argument VALUE is non-nil, only consider an entry
16004 if it contains PROPERTY set to this value. If PROPERTY should be
16005 explicitly set to nil, use string \"nil\" for VALUE.
16007 Return position where the entry begins, or nil if there is no
16008 such entry. If narrowing is in effect, only search the visible
16009 part of the buffer."
16010 (save-excursion
16011 (goto-char (point-min))
16012 (let ((case-fold-search t)
16013 (re (org-re-property property nil (not value) value)))
16014 (catch 'exit
16015 (while (re-search-forward re nil t)
16016 (when (if value (org-at-property-p)
16017 (org-entry-get (point) property nil t))
16018 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16020 (defun org-delete-property (property)
16021 "In the current entry, delete PROPERTY."
16022 (interactive
16023 (let* ((completion-ignore-case t)
16024 (cat (org-entry-get (point) "CATEGORY"))
16025 (props0 (org-entry-properties nil 'standard))
16026 (props (if cat props0
16027 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16028 (prop (if (< 1 (length props))
16029 (completing-read "Property: " props nil t)
16030 (caar props))))
16031 (list prop)))
16032 (if (not property)
16033 (message "No property to delete in this entry")
16034 (org-entry-delete nil property)
16035 (message "Property \"%s\" deleted" property)))
16037 (defun org-delete-property-globally (property)
16038 "Remove PROPERTY globally, from all entries.
16039 This function ignores narrowing, if any."
16040 (interactive
16041 (let* ((completion-ignore-case t)
16042 (prop (completing-read
16043 "Globally remove property: "
16044 (mapcar #'list (org-buffer-property-keys)))))
16045 (list prop)))
16046 (org-with-wide-buffer
16047 (goto-char (point-min))
16048 (let ((count 0)
16049 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16050 (while (re-search-forward re nil t)
16051 (when (org-entry-delete (point) property) (cl-incf count)))
16052 (message "Property \"%s\" removed from %d entries" property count))))
16054 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16056 (defun org-compute-property-at-point ()
16057 "Compute the property at point.
16058 This looks for an enclosing column format, extracts the operator and
16059 then applies it to the property in the column format's scope."
16060 (interactive)
16061 (unless (org-at-property-p)
16062 (user-error "Not at a property"))
16063 (let ((prop (match-string-no-properties 2)))
16064 (org-columns-get-format-and-top-level)
16065 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16066 (user-error "No operator defined for property %s" prop))
16067 (org-columns-compute prop)))
16069 (defvar org-property-allowed-value-functions nil
16070 "Hook for functions supplying allowed values for a specific property.
16071 The functions must take a single argument, the name of the property, and
16072 return a flat list of allowed values. If \":ETC\" is one of
16073 the values, this means that these values are intended as defaults for
16074 completion, but that other values should be allowed too.
16075 The functions must return nil if they are not responsible for this
16076 property.")
16078 (defun org-property-get-allowed-values (pom property &optional table)
16079 "Get allowed values for the property PROPERTY.
16080 When TABLE is non-nil, return an alist that can directly be used for
16081 completion."
16082 (let (vals)
16083 (cond
16084 ((equal property "TODO")
16085 (setq vals (org-with-point-at pom
16086 (append org-todo-keywords-1 '("")))))
16087 ((equal property "PRIORITY")
16088 (let ((n org-lowest-priority))
16089 (while (>= n org-highest-priority)
16090 (push (char-to-string n) vals)
16091 (setq n (1- n)))))
16092 ((equal property "CATEGORY"))
16093 ((member property org-special-properties))
16094 ((setq vals (run-hook-with-args-until-success
16095 'org-property-allowed-value-functions property)))
16097 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16098 (when (and vals (string-match "\\S-" vals))
16099 (setq vals (car (read-from-string (concat "(" vals ")"))))
16100 (setq vals (mapcar (lambda (x)
16101 (cond ((stringp x) x)
16102 ((numberp x) (number-to-string x))
16103 ((symbolp x) (symbol-name x))
16104 (t "???")))
16105 vals)))))
16106 (when (member ":ETC" vals)
16107 (setq vals (remove ":ETC" vals))
16108 (org-add-props (car vals) '(org-unrestricted t)))
16109 (if table (mapcar 'list vals) vals)))
16111 (defun org-property-previous-allowed-value (&optional _previous)
16112 "Switch to the next allowed value for this property."
16113 (interactive)
16114 (org-property-next-allowed-value t))
16116 (defun org-property-next-allowed-value (&optional previous)
16117 "Switch to the next allowed value for this property."
16118 (interactive)
16119 (unless (org-at-property-p)
16120 (user-error "Not at a property"))
16121 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16122 (key (match-string 2))
16123 (value (match-string 3))
16124 (allowed (or (org-property-get-allowed-values (point) key)
16125 (and (member value '("[ ]" "[-]" "[X]"))
16126 '("[ ]" "[X]"))))
16127 (heading (save-match-data (nth 4 (org-heading-components))))
16128 nval)
16129 (unless allowed
16130 (user-error "Allowed values for this property have not been defined"))
16131 (when previous (setq allowed (reverse allowed)))
16132 (when (member value allowed)
16133 (setq nval (car (cdr (member value allowed)))))
16134 (setq nval (or nval (car allowed)))
16135 (when (equal nval value)
16136 (user-error "Only one allowed value for this property"))
16137 (org-at-property-p)
16138 (replace-match (concat " :" key ": " nval) t t)
16139 (org-indent-line)
16140 (beginning-of-line 1)
16141 (skip-chars-forward " \t")
16142 (when (equal prop org-effort-property)
16143 (org-refresh-property
16144 '((effort . identity)
16145 (effort-minutes . org-duration-to-minutes))
16146 nval)
16147 (when (string= org-clock-current-task heading)
16148 (setq org-clock-effort nval)
16149 (org-clock-update-mode-line)))
16150 (run-hook-with-args 'org-property-changed-functions key nval)))
16152 (defun org-find-olp (path &optional this-buffer)
16153 "Return a marker pointing to the entry at outline path OLP.
16154 If anything goes wrong, throw an error.
16155 You can wrap this call to catch the error like this:
16157 (condition-case msg
16158 (org-mobile-locate-entry (match-string 4))
16159 (error (nth 1 msg)))
16161 The return value will then be either a string with the error message,
16162 or a marker if everything is OK.
16164 If THIS-BUFFER is set, the outline path does not contain a file,
16165 only headings."
16166 (let* ((file (if this-buffer buffer-file-name (pop path)))
16167 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16168 (level 1)
16169 (lmin 1)
16170 (lmax 1)
16171 end found flevel)
16172 (unless buffer (error "File not found :%s" file))
16173 (with-current-buffer buffer
16174 (unless (derived-mode-p 'org-mode)
16175 (error "Buffer %s needs to be in Org mode" buffer))
16176 (org-with-wide-buffer
16177 (goto-char (point-min))
16178 (dolist (heading path)
16179 (let ((re (format org-complex-heading-regexp-format
16180 (regexp-quote heading)))
16181 (cnt 0))
16182 (while (re-search-forward re end t)
16183 (setq level (- (match-end 1) (match-beginning 1)))
16184 (when (and (>= level lmin) (<= level lmax))
16185 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16186 (when (= cnt 0)
16187 (error "Heading not found on level %d: %s" lmax heading))
16188 (when (> cnt 1)
16189 (error "Heading not unique on level %d: %s" lmax heading))
16190 (goto-char found)
16191 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16192 (setq end (save-excursion (org-end-of-subtree t t)))))
16193 (when (org-at-heading-p)
16194 (point-marker))))))
16196 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16197 "Find node HEADING in BUFFER.
16198 Return a marker to the heading if it was found, or nil if not.
16199 If POS-ONLY is set, return just the position instead of a marker.
16201 The heading text must match exact, but it may have a TODO keyword,
16202 a priority cookie and tags in the standard locations."
16203 (with-current-buffer (or buffer (current-buffer))
16204 (org-with-wide-buffer
16205 (goto-char (point-min))
16206 (let (case-fold-search)
16207 (when (re-search-forward
16208 (format org-complex-heading-regexp-format
16209 (regexp-quote heading)) nil t)
16210 (if pos-only
16211 (match-beginning 0)
16212 (move-marker (make-marker) (match-beginning 0))))))))
16214 (defun org-find-exact-heading-in-directory (heading &optional dir)
16215 "Find Org node headline HEADING in all .org files in directory DIR.
16216 When the target headline is found, return a marker to this location."
16217 (let ((files (directory-files (or dir default-directory)
16218 t "\\`[^.#].*\\.org\\'"))
16219 visiting m buffer)
16220 (catch 'found
16221 (dolist (file files)
16222 (message "trying %s" file)
16223 (setq visiting (org-find-base-buffer-visiting file))
16224 (setq buffer (or visiting (find-file-noselect file)))
16225 (setq m (org-find-exact-headline-in-buffer
16226 heading buffer))
16227 (when (and (not m) (not visiting)) (kill-buffer buffer))
16228 (and m (throw 'found m))))))
16230 (defun org-find-entry-with-id (ident)
16231 "Locate the entry that contains the ID property with exact value IDENT.
16232 IDENT can be a string, a symbol or a number, this function will search for
16233 the string representation of it.
16234 Return the position where this entry starts, or nil if there is no such entry."
16235 (interactive "sID: ")
16236 (let ((id (cond
16237 ((stringp ident) ident)
16238 ((symbolp ident) (symbol-name ident))
16239 ((numberp ident) (number-to-string ident))
16240 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16241 (org-with-wide-buffer (org-find-property "ID" id))))
16243 ;;;; Timestamps
16245 (defvar org-last-changed-timestamp nil)
16246 (defvar org-last-inserted-timestamp nil
16247 "The last time stamp inserted with `org-insert-time-stamp'.")
16249 (defun org-time-stamp (arg &optional inactive)
16250 "Prompt for a date/time and insert a time stamp.
16252 If the user specifies a time like HH:MM or if this command is
16253 called with at least one prefix argument, the time stamp contains
16254 the date and the time. Otherwise, only the date is included.
16256 All parts of a date not specified by the user are filled in from
16257 the timestamp at point, if any, or the current date/time
16258 otherwise.
16260 If there is already a timestamp at the cursor, it is replaced.
16262 With two universal prefix arguments, insert an active timestamp
16263 with the current time without prompting the user.
16265 When called from lisp, the timestamp is inactive if INACTIVE is
16266 non-nil."
16267 (interactive "P")
16268 (let* ((ts (cond
16269 ((org-at-date-range-p t)
16270 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16271 ((org-at-timestamp-p 'lax) (match-string 0))))
16272 ;; Default time is either the timestamp at point or today.
16273 ;; When entering a range, only the range start is considered.
16274 (default-time (if (not ts) (current-time)
16275 (apply #'encode-time (org-parse-time-string ts))))
16276 (default-input (and ts (org-get-compact-tod ts)))
16277 (repeater (and ts
16278 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16279 (match-string 0 ts)))
16280 org-time-was-given
16281 org-end-time-was-given
16282 (time
16283 (and (if (equal arg '(16)) (current-time)
16284 ;; Preserve `this-command' and `last-command'.
16285 (let ((this-command this-command)
16286 (last-command last-command))
16287 (org-read-date
16288 arg 'totime nil nil default-time default-input
16289 inactive))))))
16290 (cond
16291 ((and ts
16292 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16293 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16294 (insert "--")
16295 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16297 ;; Make sure we're on a timestamp. When in the middle of a date
16298 ;; range, move arbitrarily to range end.
16299 (unless (org-at-timestamp-p 'lax)
16300 (skip-chars-forward "-")
16301 (org-at-timestamp-p 'lax))
16302 (replace-match "")
16303 (setq org-last-changed-timestamp
16304 (org-insert-time-stamp
16305 time (or org-time-was-given arg)
16306 inactive nil nil (list org-end-time-was-given)))
16307 (when repeater
16308 (backward-char)
16309 (insert " " repeater)
16310 (setq org-last-changed-timestamp
16311 (concat (substring org-last-inserted-timestamp 0 -1)
16312 " " repeater ">")))
16313 (message "Timestamp updated"))
16314 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16315 (t (org-insert-time-stamp
16316 time (or org-time-was-given arg) inactive nil nil
16317 (list org-end-time-was-given))))))
16319 ;; FIXME: can we use this for something else, like computing time differences?
16320 (defun org-get-compact-tod (s)
16321 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16322 (let* ((t1 (match-string 1 s))
16323 (h1 (string-to-number (match-string 2 s)))
16324 (m1 (string-to-number (match-string 3 s)))
16325 (t2 (and (match-end 4) (match-string 5 s)))
16326 (h2 (and t2 (string-to-number (match-string 6 s))))
16327 (m2 (and t2 (string-to-number (match-string 7 s))))
16328 dh dm)
16329 (if (not t2)
16331 (setq dh (- h2 h1) dm (- m2 m1))
16332 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16333 (concat t1 "+" (number-to-string dh)
16334 (and (/= 0 dm) (format ":%02d" dm)))))))
16336 (defun org-time-stamp-inactive (&optional arg)
16337 "Insert an inactive time stamp.
16338 An inactive time stamp is enclosed in square brackets instead of angle
16339 brackets. It is inactive in the sense that it does not trigger agenda entries,
16340 does not link to the calendar and cannot be changed with the S-cursor keys.
16341 So these are more for recording a certain time/date."
16342 (interactive "P")
16343 (org-time-stamp arg 'inactive))
16345 (defvar org-date-ovl (make-overlay 1 1))
16346 (overlay-put org-date-ovl 'face 'org-date-selected)
16347 (delete-overlay org-date-ovl)
16349 (defvar org-ans1) ; dynamically scoped parameter
16350 (defvar org-ans2) ; dynamically scoped parameter
16352 (defvar org-plain-time-of-day-regexp) ; defined below
16354 (defvar org-overriding-default-time nil) ; dynamically scoped
16355 (defvar org-read-date-overlay nil)
16356 (defvar org-dcst nil) ; dynamically scoped
16357 (defvar org-read-date-history nil)
16358 (defvar org-read-date-final-answer nil)
16359 (defvar org-read-date-analyze-futurep nil)
16360 (defvar org-read-date-analyze-forced-year nil)
16361 (defvar org-read-date-inactive)
16363 (defvar org-read-date-minibuffer-local-map
16364 (let* ((map (make-sparse-keymap)))
16365 (set-keymap-parent map minibuffer-local-map)
16366 (org-defkey map (kbd ".")
16367 (lambda () (interactive)
16368 ;; Are we at the beginning of the prompt?
16369 (if (looking-back "^[^:]+: "
16370 (let ((inhibit-field-text-motion t))
16371 (line-beginning-position)))
16372 (org-eval-in-calendar '(calendar-goto-today))
16373 (insert "."))))
16374 (org-defkey map (kbd "C-.")
16375 (lambda () (interactive)
16376 (org-eval-in-calendar '(calendar-goto-today))))
16377 (org-defkey map [(meta shift left)]
16378 (lambda () (interactive)
16379 (org-eval-in-calendar '(calendar-backward-month 1))))
16380 (org-defkey map [(meta shift right)]
16381 (lambda () (interactive)
16382 (org-eval-in-calendar '(calendar-forward-month 1))))
16383 (org-defkey map [(meta shift up)]
16384 (lambda () (interactive)
16385 (org-eval-in-calendar '(calendar-backward-year 1))))
16386 (org-defkey map [(meta shift down)]
16387 (lambda () (interactive)
16388 (org-eval-in-calendar '(calendar-forward-year 1))))
16389 (org-defkey map [?\e (shift left)]
16390 (lambda () (interactive)
16391 (org-eval-in-calendar '(calendar-backward-month 1))))
16392 (org-defkey map [?\e (shift right)]
16393 (lambda () (interactive)
16394 (org-eval-in-calendar '(calendar-forward-month 1))))
16395 (org-defkey map [?\e (shift up)]
16396 (lambda () (interactive)
16397 (org-eval-in-calendar '(calendar-backward-year 1))))
16398 (org-defkey map [?\e (shift down)]
16399 (lambda () (interactive)
16400 (org-eval-in-calendar '(calendar-forward-year 1))))
16401 (org-defkey map [(shift up)]
16402 (lambda () (interactive)
16403 (org-eval-in-calendar '(calendar-backward-week 1))))
16404 (org-defkey map [(shift down)]
16405 (lambda () (interactive)
16406 (org-eval-in-calendar '(calendar-forward-week 1))))
16407 (org-defkey map [(shift left)]
16408 (lambda () (interactive)
16409 (org-eval-in-calendar '(calendar-backward-day 1))))
16410 (org-defkey map [(shift right)]
16411 (lambda () (interactive)
16412 (org-eval-in-calendar '(calendar-forward-day 1))))
16413 (org-defkey map "!"
16414 (lambda () (interactive)
16415 (org-eval-in-calendar '(diary-view-entries))
16416 (message "")))
16417 (org-defkey map ">"
16418 (lambda () (interactive)
16419 (org-eval-in-calendar '(calendar-scroll-left 1))))
16420 (org-defkey map "<"
16421 (lambda () (interactive)
16422 (org-eval-in-calendar '(calendar-scroll-right 1))))
16423 (org-defkey map "\C-v"
16424 (lambda () (interactive)
16425 (org-eval-in-calendar
16426 '(calendar-scroll-left-three-months 1))))
16427 (org-defkey map "\M-v"
16428 (lambda () (interactive)
16429 (org-eval-in-calendar
16430 '(calendar-scroll-right-three-months 1))))
16431 map)
16432 "Keymap for minibuffer commands when using `org-read-date'.")
16434 (defvar org-def)
16435 (defvar org-defdecode)
16436 (defvar org-with-time)
16438 (defvar calendar-setup) ; Dynamically scoped.
16439 (defun org-read-date (&optional with-time to-time from-string prompt
16440 default-time default-input inactive)
16441 "Read a date, possibly a time, and make things smooth for the user.
16442 The prompt will suggest to enter an ISO date, but you can also enter anything
16443 which will at least partially be understood by `parse-time-string'.
16444 Unrecognized parts of the date will default to the current day, month, year,
16445 hour and minute. If this command is called to replace a timestamp at point,
16446 or to enter the second timestamp of a range, the default time is taken
16447 from the existing stamp. Furthermore, the command prefers the future,
16448 so if you are giving a date where the year is not given, and the day-month
16449 combination is already past in the current year, it will assume you
16450 mean next year. For details, see the manual. A few examples:
16452 3-2-5 --> 2003-02-05
16453 feb 15 --> currentyear-02-15
16454 2/15 --> currentyear-02-15
16455 sep 12 9 --> 2009-09-12
16456 12:45 --> today 12:45
16457 22 sept 0:34 --> currentyear-09-22 0:34
16458 12 --> currentyear-currentmonth-12
16459 Fri --> nearest Friday after today
16460 -Tue --> last Tuesday
16461 etc.
16463 Furthermore you can specify a relative date by giving, as the *first* thing
16464 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16465 change in days weeks, months, years.
16466 With a single plus or minus, the date is relative to today. With a double
16467 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16468 +4d --> four days from today
16469 +4 --> same as above
16470 +2w --> two weeks from today
16471 ++5 --> five days from default date
16473 The function understands only English month and weekday abbreviations.
16475 While prompting, a calendar is popped up - you can also select the
16476 date with the mouse (button 1). The calendar shows a period of three
16477 months. To scroll it to other months, use the keys `>' and `<'.
16478 If you don't like the calendar, turn it off with
16479 (setq org-read-date-popup-calendar nil)
16481 With optional argument TO-TIME, the date will immediately be converted
16482 to an internal time.
16483 With an optional argument WITH-TIME, the prompt will suggest to
16484 also insert a time. Note that when WITH-TIME is not set, you can
16485 still enter a time, and this function will inform the calling routine
16486 about this change. The calling routine may then choose to change the
16487 format used to insert the time stamp into the buffer to include the time.
16488 With optional argument FROM-STRING, read from this string instead from
16489 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16490 the time/date that is used for everything that is not specified by the
16491 user."
16492 (require 'parse-time)
16493 (let* ((org-with-time with-time)
16494 (org-time-stamp-rounding-minutes
16495 (if (equal org-with-time '(16))
16496 '(0 0)
16497 org-time-stamp-rounding-minutes))
16498 (org-dcst org-display-custom-times)
16499 (ct (org-current-time))
16500 (org-def (or org-overriding-default-time default-time ct))
16501 (org-defdecode (decode-time org-def))
16502 (cur-frame (selected-frame))
16503 (mouse-autoselect-window nil) ; Don't let the mouse jump
16504 (calendar-setup
16505 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16506 (calendar-move-hook nil)
16507 (calendar-view-diary-initially-flag nil)
16508 (calendar-view-holidays-initially-flag nil)
16509 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16510 ;; Rationalize `org-def' and `org-defdecode', if required.
16511 (when (< (nth 2 org-defdecode) org-extend-today-until)
16512 (setf (nth 2 org-defdecode) -1)
16513 (setf (nth 1 org-defdecode) 59)
16514 (setq org-def (apply #'encode-time org-defdecode))
16515 (setq org-defdecode (decode-time org-def)))
16516 (let* ((timestr (format-time-string
16517 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16518 org-def))
16519 (prompt (concat (if prompt (concat prompt " ") "")
16520 (format "Date+time [%s]: " timestr))))
16521 (cond
16522 (from-string (setq ans from-string))
16523 (org-read-date-popup-calendar
16524 (save-excursion
16525 (save-window-excursion
16526 (calendar)
16527 (when (eq calendar-setup 'calendar-only)
16528 (setq cal-frame
16529 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16530 (select-frame cal-frame))
16531 (org-eval-in-calendar '(setq cursor-type nil) t)
16532 (unwind-protect
16533 (progn
16534 (calendar-forward-day (- (time-to-days org-def)
16535 (calendar-absolute-from-gregorian
16536 (calendar-current-date))))
16537 (org-eval-in-calendar nil t)
16538 (let* ((old-map (current-local-map))
16539 (map (copy-keymap calendar-mode-map))
16540 (minibuffer-local-map
16541 (copy-keymap org-read-date-minibuffer-local-map)))
16542 (org-defkey map (kbd "RET") 'org-calendar-select)
16543 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16544 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16545 (unwind-protect
16546 (progn
16547 (use-local-map map)
16548 (setq org-read-date-inactive inactive)
16549 (add-hook 'post-command-hook 'org-read-date-display)
16550 (setq org-ans0
16551 (read-string prompt
16552 default-input
16553 'org-read-date-history
16554 nil))
16555 ;; org-ans0: from prompt
16556 ;; org-ans1: from mouse click
16557 ;; org-ans2: from calendar motion
16558 (setq ans
16559 (concat org-ans0 " " (or org-ans1 org-ans2))))
16560 (remove-hook 'post-command-hook 'org-read-date-display)
16561 (use-local-map old-map)
16562 (when org-read-date-overlay
16563 (delete-overlay org-read-date-overlay)
16564 (setq org-read-date-overlay nil)))))
16565 (bury-buffer "*Calendar*")
16566 (when cal-frame
16567 (delete-frame cal-frame)
16568 (select-frame-set-input-focus cur-frame))))))
16570 (t ; Naked prompt only
16571 (unwind-protect
16572 (setq ans (read-string prompt default-input
16573 'org-read-date-history timestr))
16574 (when org-read-date-overlay
16575 (delete-overlay org-read-date-overlay)
16576 (setq org-read-date-overlay nil))))))
16578 (setq final (org-read-date-analyze ans org-def org-defdecode))
16580 (when org-read-date-analyze-forced-year
16581 (message "Year was forced into %s"
16582 (if org-read-date-force-compatible-dates
16583 "compatible range (1970-2037)"
16584 "range representable on this machine"))
16585 (ding))
16587 ;; One round trip to get rid of 34th of August and stuff like that....
16588 (setq final (decode-time (apply 'encode-time final)))
16590 (setq org-read-date-final-answer ans)
16592 (if to-time
16593 (apply 'encode-time final)
16594 (if (and (boundp 'org-time-was-given) org-time-was-given)
16595 (format "%04d-%02d-%02d %02d:%02d"
16596 (nth 5 final) (nth 4 final) (nth 3 final)
16597 (nth 2 final) (nth 1 final))
16598 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16600 (defun org-read-date-display ()
16601 "Display the current date prompt interpretation in the minibuffer."
16602 (when org-read-date-display-live
16603 (when org-read-date-overlay
16604 (delete-overlay org-read-date-overlay))
16605 (when (minibufferp (current-buffer))
16606 (save-excursion
16607 (end-of-line 1)
16608 (while (not (equal (buffer-substring
16609 (max (point-min) (- (point) 4)) (point))
16610 " "))
16611 (insert " ")))
16612 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16613 " " (or org-ans1 org-ans2)))
16614 (org-end-time-was-given nil)
16615 (f (org-read-date-analyze ans org-def org-defdecode))
16616 (fmts (if org-dcst
16617 org-time-stamp-custom-formats
16618 org-time-stamp-formats))
16619 (fmt (if (or org-with-time
16620 (and (boundp 'org-time-was-given) org-time-was-given))
16621 (cdr fmts)
16622 (car fmts)))
16623 (txt (format-time-string fmt (apply 'encode-time f)))
16624 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16625 (txt (concat "=> " txt)))
16626 (when (and org-end-time-was-given
16627 (string-match org-plain-time-of-day-regexp txt))
16628 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16629 org-end-time-was-given
16630 (substring txt (match-end 0)))))
16631 (when org-read-date-analyze-futurep
16632 (setq txt (concat txt " (=>F)")))
16633 (setq org-read-date-overlay
16634 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16635 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16637 (defun org-read-date-analyze (ans def defdecode)
16638 "Analyze the combined answer of the date prompt."
16639 ;; FIXME: cleanup and comment
16640 ;; Pass `current-time' result to `decode-time' (instead of calling
16641 ;; without arguments) so that only `current-time' has to be
16642 ;; overridden in tests.
16643 (let ((org-def def)
16644 (org-defdecode defdecode)
16645 (nowdecode (decode-time (current-time)))
16646 delta deltan deltaw deltadef year month day
16647 hour minute second wday pm h2 m2 tl wday1
16648 iso-year iso-weekday iso-week iso-date futurep kill-year)
16649 (setq org-read-date-analyze-futurep nil
16650 org-read-date-analyze-forced-year nil)
16651 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16652 (setq ans "+0"))
16654 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16655 (setq ans (replace-match "" t t ans)
16656 deltan (car delta)
16657 deltaw (nth 1 delta)
16658 deltadef (nth 2 delta)))
16660 ;; Check if there is an iso week date in there. If yes, store the
16661 ;; info and postpone interpreting it until the rest of the parsing
16662 ;; is done.
16663 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16664 (setq iso-year (when (match-end 1)
16665 (org-small-year-to-year
16666 (string-to-number (match-string 1 ans))))
16667 iso-weekday (when (match-end 3)
16668 (string-to-number (match-string 3 ans)))
16669 iso-week (string-to-number (match-string 2 ans)))
16670 (setq ans (replace-match "" t t ans)))
16672 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16673 (when (string-match
16674 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16675 (setq year (if (match-end 2)
16676 (string-to-number (match-string 2 ans))
16677 (progn (setq kill-year t)
16678 (string-to-number (format-time-string "%Y"))))
16679 month (string-to-number (match-string 3 ans))
16680 day (string-to-number (match-string 4 ans)))
16681 (setq year (org-small-year-to-year year))
16682 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16683 t nil ans)))
16685 ;; Help matching dotted european dates
16686 (when (string-match
16687 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16688 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16689 (setq kill-year t)
16690 (string-to-number (format-time-string "%Y")))
16691 day (string-to-number (match-string 1 ans))
16692 month (string-to-number (match-string 2 ans))
16693 ans (replace-match (format "%04d-%02d-%02d" year month day)
16694 t nil ans)))
16696 ;; Help matching american dates, like 5/30 or 5/30/7
16697 (when (string-match
16698 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16699 (setq year (if (match-end 4)
16700 (string-to-number (match-string 4 ans))
16701 (progn (setq kill-year t)
16702 (string-to-number (format-time-string "%Y"))))
16703 month (string-to-number (match-string 1 ans))
16704 day (string-to-number (match-string 2 ans)))
16705 (setq year (org-small-year-to-year year))
16706 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16707 t nil ans)))
16708 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16709 ;; If there is a time with am/pm, and *no* time without it, we convert
16710 ;; so that matching will be successful.
16711 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16712 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16713 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16714 (setq hour (string-to-number (match-string 1 ans))
16715 minute (if (match-end 3)
16716 (string-to-number (match-string 3 ans))
16718 pm (equal ?p
16719 (string-to-char (downcase (match-string 4 ans)))))
16720 (if (and (= hour 12) (not pm))
16721 (setq hour 0)
16722 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16723 (setq ans (replace-match (format "%02d:%02d" hour minute)
16724 t t ans))))
16726 ;; Check if a time range is given as a duration
16727 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16728 (setq hour (string-to-number (match-string 1 ans))
16729 h2 (+ hour (string-to-number (match-string 3 ans)))
16730 minute (string-to-number (match-string 2 ans))
16731 m2 (+ minute (if (match-end 5) (string-to-number
16732 (match-string 5 ans))0)))
16733 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16734 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16735 t t ans)))
16737 ;; Check if there is a time range
16738 (when (boundp 'org-end-time-was-given)
16739 (setq org-time-was-given nil)
16740 (when (and (string-match org-plain-time-of-day-regexp ans)
16741 (match-end 8))
16742 (setq org-end-time-was-given (match-string 8 ans))
16743 (setq ans (concat (substring ans 0 (match-beginning 7))
16744 (substring ans (match-end 7))))))
16746 (setq tl (parse-time-string ans)
16747 day (or (nth 3 tl) (nth 3 org-defdecode))
16748 month
16749 (cond ((nth 4 tl))
16750 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16751 ;; Day was specified. Make sure DAY+MONTH
16752 ;; combination happens in the future.
16753 ((nth 3 tl)
16754 (setq futurep t)
16755 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16756 (nth 4 nowdecode)))
16757 (t (nth 4 org-defdecode)))
16758 year
16759 (cond ((and (not kill-year) (nth 5 tl)))
16760 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16761 ;; Month was guessed in the future and is at least
16762 ;; equal to NOWDECODE's. Fix year accordingly.
16763 (futurep
16764 (if (or (> month (nth 4 nowdecode))
16765 (>= day (nth 3 nowdecode)))
16766 (nth 5 nowdecode)
16767 (1+ (nth 5 nowdecode))))
16768 ;; Month was specified. Make sure MONTH+YEAR
16769 ;; combination happens in the future.
16770 ((nth 4 tl)
16771 (setq futurep t)
16772 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16773 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16774 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16775 (t (nth 5 nowdecode))))
16776 (t (nth 5 org-defdecode)))
16777 hour (or (nth 2 tl) (nth 2 org-defdecode))
16778 minute (or (nth 1 tl) (nth 1 org-defdecode))
16779 second (or (nth 0 tl) 0)
16780 wday (nth 6 tl))
16782 (when (and (eq org-read-date-prefer-future 'time)
16783 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16784 (equal day (nth 3 nowdecode))
16785 (equal month (nth 4 nowdecode))
16786 (equal year (nth 5 nowdecode))
16787 (nth 2 tl)
16788 (or (< (nth 2 tl) (nth 2 nowdecode))
16789 (and (= (nth 2 tl) (nth 2 nowdecode))
16790 (nth 1 tl)
16791 (< (nth 1 tl) (nth 1 nowdecode)))))
16792 (setq day (1+ day)
16793 futurep t))
16795 ;; Special date definitions below
16796 (cond
16797 (iso-week
16798 ;; There was an iso week
16799 (require 'cal-iso)
16800 (setq futurep nil)
16801 (setq year (or iso-year year)
16802 day (or iso-weekday wday 1)
16803 wday nil ; to make sure that the trigger below does not match
16804 iso-date (calendar-gregorian-from-absolute
16805 (calendar-iso-to-absolute
16806 (list iso-week day year))))
16807 ; FIXME: Should we also push ISO weeks into the future?
16808 ; (when (and org-read-date-prefer-future
16809 ; (not iso-year)
16810 ; (< (calendar-absolute-from-gregorian iso-date)
16811 ; (time-to-days (current-time))))
16812 ; (setq year (1+ year)
16813 ; iso-date (calendar-gregorian-from-absolute
16814 ; (calendar-iso-to-absolute
16815 ; (list iso-week day year)))))
16816 (setq month (car iso-date)
16817 year (nth 2 iso-date)
16818 day (nth 1 iso-date)))
16819 (deltan
16820 (setq futurep nil)
16821 (unless deltadef
16822 ;; Pass `current-time' result to `decode-time' (instead of
16823 ;; calling without arguments) so that only `current-time' has
16824 ;; to be overridden in tests.
16825 (let ((now (decode-time (current-time))))
16826 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16827 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16828 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16829 ((equal deltaw "m") (setq month (+ month deltan)))
16830 ((equal deltaw "y") (setq year (+ year deltan)))))
16831 ((and wday (not (nth 3 tl)))
16832 ;; Weekday was given, but no day, so pick that day in the week
16833 ;; on or after the derived date.
16834 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16835 (unless (equal wday wday1)
16836 (setq day (+ day (% (- wday wday1 -7) 7))))))
16837 (when (and (boundp 'org-time-was-given)
16838 (nth 2 tl))
16839 (setq org-time-was-given t))
16840 (when (< year 100) (setq year (+ 2000 year)))
16841 ;; Check of the date is representable
16842 (if org-read-date-force-compatible-dates
16843 (progn
16844 (when (< year 1970)
16845 (setq year 1970 org-read-date-analyze-forced-year t))
16846 (when (> year 2037)
16847 (setq year 2037 org-read-date-analyze-forced-year t)))
16848 (condition-case nil
16849 (ignore (encode-time second minute hour day month year))
16850 (error
16851 (setq year (nth 5 org-defdecode))
16852 (setq org-read-date-analyze-forced-year t))))
16853 (setq org-read-date-analyze-futurep futurep)
16854 (list second minute hour day month year)))
16856 (defvar parse-time-weekdays)
16857 (defun org-read-date-get-relative (s today default)
16858 "Check string S for special relative date string.
16859 TODAY and DEFAULT are internal times, for today and for a default.
16860 Return shift list (N what def-flag)
16861 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16862 N is the number of WHATs to shift.
16863 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16864 the DEFAULT date rather than TODAY."
16865 (require 'parse-time)
16866 (when (and
16867 (string-match
16868 (concat
16869 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16870 "\\([0-9]+\\)?"
16871 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16872 "\\([ \t]\\|$\\)") s)
16873 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16874 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16875 (string-to-char (substring (match-string 1 s) -1))
16876 ?+))
16877 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16878 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16879 (what (if (match-end 3) (match-string 3 s) "d"))
16880 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16881 (date (if rel default today))
16882 (wday (nth 6 (decode-time date)))
16883 delta)
16884 (if wday1
16885 (progn
16886 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16887 (when (= delta 0) (setq delta 7))
16888 (when (= dir ?-)
16889 (setq delta (- delta 7))
16890 (when (= delta 0) (setq delta -7)))
16891 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16892 (list delta "d" rel))
16893 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16895 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16896 "Turn a user-specified date into the internal representation.
16897 The internal representation needed by the calendar is (month day year).
16898 This is a wrapper to handle the brain-dead convention in calendar that
16899 user function argument order change dependent on argument order."
16900 (pcase calendar-date-style
16901 (`american (list arg1 arg2 arg3))
16902 (`european (list arg2 arg1 arg3))
16903 (`iso (list arg2 arg3 arg1))))
16905 (defun org-eval-in-calendar (form &optional keepdate)
16906 "Eval FORM in the calendar window and return to current window.
16907 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16908 (let ((sf (selected-frame))
16909 (sw (selected-window)))
16910 (select-window (get-buffer-window "*Calendar*" t))
16911 (eval form)
16912 (when (and (not keepdate) (calendar-cursor-to-date))
16913 (let* ((date (calendar-cursor-to-date))
16914 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16915 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16916 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16917 (select-window sw)
16918 (select-frame-set-input-focus sf)))
16920 (defun org-calendar-select ()
16921 "Return to `org-read-date' with the date currently selected.
16922 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16923 (interactive)
16924 (when (calendar-cursor-to-date)
16925 (let* ((date (calendar-cursor-to-date))
16926 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16927 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16928 (when (active-minibuffer-window) (exit-minibuffer))))
16930 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16931 "Insert a date stamp for the date given by the internal TIME.
16932 See `format-time-string' for the format of TIME.
16933 WITH-HM means use the stamp format that includes the time of the day.
16934 INACTIVE means use square brackets instead of angular ones, so that the
16935 stamp will not contribute to the agenda.
16936 PRE and POST are optional strings to be inserted before and after the
16937 stamp.
16938 The command returns the inserted time stamp."
16939 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16940 stamp)
16941 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16942 (insert-before-markers (or pre ""))
16943 (when (listp extra)
16944 (setq extra (car extra))
16945 (if (and (stringp extra)
16946 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16947 (setq extra (format "-%02d:%02d"
16948 (string-to-number (match-string 1 extra))
16949 (string-to-number (match-string 2 extra))))
16950 (setq extra nil)))
16951 (when extra
16952 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16953 (insert-before-markers (setq stamp (format-time-string fmt time)))
16954 (insert-before-markers (or post ""))
16955 (setq org-last-inserted-timestamp stamp)))
16957 (defun org-toggle-time-stamp-overlays ()
16958 "Toggle the use of custom time stamp formats."
16959 (interactive)
16960 (setq org-display-custom-times (not org-display-custom-times))
16961 (unless org-display-custom-times
16962 (let ((p (point-min)) (bmp (buffer-modified-p)))
16963 (while (setq p (next-single-property-change p 'display))
16964 (when (and (get-text-property p 'display)
16965 (eq (get-text-property p 'face) 'org-date))
16966 (remove-text-properties
16967 p (setq p (next-single-property-change p 'display))
16968 '(display t))))
16969 (set-buffer-modified-p bmp)))
16970 (org-restart-font-lock)
16971 (setq org-table-may-need-update t)
16972 (if org-display-custom-times
16973 (message "Time stamps are overlaid with custom format")
16974 (message "Time stamp overlays removed")))
16976 (defun org-display-custom-time (beg end)
16977 "Overlay modified time stamp format over timestamp between BEG and END."
16978 (let* ((ts (buffer-substring beg end))
16979 t1 with-hm tf time str (off 0))
16980 (save-match-data
16981 (setq t1 (org-parse-time-string ts t))
16982 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16983 (setq off (- (match-end 0) (match-beginning 0)))))
16984 (setq end (- end off))
16985 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16986 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16987 time (org-fix-decoded-time t1)
16988 str (org-add-props
16989 (format-time-string
16990 (substring tf 1 -1) (apply 'encode-time time))
16991 nil 'mouse-face 'highlight))
16992 (put-text-property beg end 'display str)))
16994 (defun org-fix-decoded-time (time)
16995 "Set 0 instead of nil for the first 6 elements of time.
16996 Don't touch the rest."
16997 (let ((n 0))
16998 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17000 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17001 "Difference between TIMESTAMP-STRING and now in days.
17002 If SECONDS is non-nil, return the difference in seconds."
17003 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17004 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17005 (funcall fdiff (current-time)))))
17007 (defun org-deadline-close-p (timestamp-string &optional ndays)
17008 "Is the time in TIMESTAMP-STRING close to the current date?"
17009 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17010 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17011 (not (org-entry-is-done-p))))
17013 (defun org-get-wdays (ts &optional delay zero-delay)
17014 "Get the deadline lead time appropriate for timestring TS.
17015 When DELAY is non-nil, get the delay time for scheduled items
17016 instead of the deadline lead time. When ZERO-DELAY is non-nil
17017 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17018 don't try to find the delay cookie in the scheduled timestamp."
17019 (let ((tv (if delay org-scheduled-delay-days
17020 org-deadline-warning-days)))
17021 (cond
17022 ((or (and delay (< tv 0))
17023 (and delay zero-delay (<= tv 0))
17024 (and (not delay) (<= tv 0)))
17025 ;; Enforce this value no matter what
17026 (- tv))
17027 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17028 ;; lead time is specified.
17029 (floor (* (string-to-number (match-string 1 ts))
17030 (cdr (assoc (match-string 2 ts)
17031 '(("d" . 1) ("w" . 7)
17032 ("m" . 30.4) ("y" . 365.25)
17033 ("h" . 0.041667)))))))
17034 ;; go for the default.
17035 (t tv))))
17037 (defun org-calendar-select-mouse (ev)
17038 "Return to `org-read-date' with the date currently selected.
17039 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17040 (interactive "e")
17041 (mouse-set-point ev)
17042 (when (calendar-cursor-to-date)
17043 (let* ((date (calendar-cursor-to-date))
17044 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17045 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17046 (when (active-minibuffer-window) (exit-minibuffer))))
17048 (defun org-check-deadlines (ndays)
17049 "Check if there are any deadlines due or past due.
17050 A deadline is considered due if it happens within `org-deadline-warning-days'
17051 days from today's date. If the deadline appears in an entry marked DONE,
17052 it is not shown. A numeric prefix argument NDAYS can be used to test that
17053 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17054 are shown."
17055 (interactive "P")
17056 (let* ((org-warn-days
17057 (cond
17058 ((equal ndays '(4)) 100000)
17059 (ndays (prefix-numeric-value ndays))
17060 (t (abs org-deadline-warning-days))))
17061 (case-fold-search nil)
17062 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17063 (callback
17064 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17065 (message "%d deadlines past-due or due within %d days"
17066 (org-occur regexp nil callback)
17067 org-warn-days)))
17069 (defsubst org-re-timestamp (type)
17070 "Return a regexp for timestamp TYPE.
17071 Allowed values for TYPE are:
17073 all: all timestamps
17074 active: only active timestamps (<...>)
17075 inactive: only inactive timestamps ([...])
17076 scheduled: only scheduled timestamps
17077 deadline: only deadline timestamps
17078 closed: only closed time-stamps
17080 When TYPE is nil, fall back on returning a regexp that matches
17081 both scheduled and deadline timestamps."
17082 (cl-case type
17083 (all org-ts-regexp-both)
17084 (active org-ts-regexp)
17085 (inactive org-ts-regexp-inactive)
17086 (scheduled org-scheduled-time-regexp)
17087 (deadline org-deadline-time-regexp)
17088 (closed org-closed-time-regexp)
17089 (otherwise
17090 (concat "\\<"
17091 (regexp-opt (list org-deadline-string org-scheduled-string))
17092 " *<\\([^>]+\\)>"))))
17094 (defun org-check-before-date (d)
17095 "Check if there are deadlines or scheduled entries before date D."
17096 (interactive (list (org-read-date)))
17097 (let* ((case-fold-search nil)
17098 (regexp (org-re-timestamp org-ts-type))
17099 (ts-type org-ts-type)
17100 (callback
17101 (lambda ()
17102 (let ((match (match-string 1)))
17103 (and (if (memq ts-type '(active inactive all))
17104 (eq (org-element-type (save-excursion
17105 (backward-char)
17106 (org-element-context)))
17107 'timestamp)
17108 (org-at-planning-p))
17109 (time-less-p
17110 (org-time-string-to-time match)
17111 (org-time-string-to-time d)))))))
17112 (message "%d entries before %s"
17113 (org-occur regexp nil callback)
17114 d)))
17116 (defun org-check-after-date (d)
17117 "Check if there are deadlines or scheduled entries after date D."
17118 (interactive (list (org-read-date)))
17119 (let* ((case-fold-search nil)
17120 (regexp (org-re-timestamp org-ts-type))
17121 (ts-type org-ts-type)
17122 (callback
17123 (lambda ()
17124 (let ((match (match-string 1)))
17125 (and (if (memq ts-type '(active inactive all))
17126 (eq (org-element-type (save-excursion
17127 (backward-char)
17128 (org-element-context)))
17129 'timestamp)
17130 (org-at-planning-p))
17131 (not (time-less-p
17132 (org-time-string-to-time match)
17133 (org-time-string-to-time d))))))))
17134 (message "%d entries after %s"
17135 (org-occur regexp nil callback)
17136 d)))
17138 (defun org-check-dates-range (start-date end-date)
17139 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17140 (interactive (list (org-read-date nil nil nil "Range starts")
17141 (org-read-date nil nil nil "Range end")))
17142 (let ((case-fold-search nil)
17143 (regexp (org-re-timestamp org-ts-type))
17144 (callback
17145 (let ((type org-ts-type))
17146 (lambda ()
17147 (let ((match (match-string 1)))
17148 (and
17149 (if (memq type '(active inactive all))
17150 (eq (org-element-type (save-excursion
17151 (backward-char)
17152 (org-element-context)))
17153 'timestamp)
17154 (org-at-planning-p))
17155 (not (time-less-p
17156 (org-time-string-to-time match)
17157 (org-time-string-to-time start-date)))
17158 (time-less-p
17159 (org-time-string-to-time match)
17160 (org-time-string-to-time end-date))))))))
17161 (message "%d entries between %s and %s"
17162 (org-occur regexp nil callback) start-date end-date)))
17164 (defun org-evaluate-time-range (&optional to-buffer)
17165 "Evaluate a time range by computing the difference between start and end.
17166 Normally the result is just printed in the echo area, but with prefix arg
17167 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17168 If the time range is actually in a table, the result is inserted into the
17169 next column.
17170 For time difference computation, a year is assumed to be exactly 365
17171 days in order to avoid rounding problems."
17172 (interactive "P")
17174 (org-clock-update-time-maybe)
17175 (save-excursion
17176 (unless (org-at-date-range-p t)
17177 (goto-char (point-at-bol))
17178 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17179 (unless (org-at-date-range-p t)
17180 (user-error "Not at a time-stamp range, and none found in current line")))
17181 (let* ((ts1 (match-string 1))
17182 (ts2 (match-string 2))
17183 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17184 (match-end (match-end 0))
17185 (time1 (org-time-string-to-time ts1))
17186 (time2 (org-time-string-to-time ts2))
17187 (t1 (float-time time1))
17188 (t2 (float-time time2))
17189 (diff (abs (- t2 t1)))
17190 (negative (< (- t2 t1) 0))
17191 ;; (ys (floor (* 365 24 60 60)))
17192 (ds (* 24 60 60))
17193 (hs (* 60 60))
17194 (fy "%dy %dd %02d:%02d")
17195 (fy1 "%dy %dd")
17196 (fd "%dd %02d:%02d")
17197 (fd1 "%dd")
17198 (fh "%02d:%02d")
17199 y d h m align)
17200 (if havetime
17201 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17203 d (floor (/ diff ds)) diff (mod diff ds)
17204 h (floor (/ diff hs)) diff (mod diff hs)
17205 m (floor (/ diff 60)))
17206 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17208 d (floor (+ (/ diff ds) 0.5))
17209 h 0 m 0))
17210 (if (not to-buffer)
17211 (message "%s" (org-make-tdiff-string y d h m))
17212 (if (org-at-table-p)
17213 (progn
17214 (goto-char match-end)
17215 (setq align t)
17216 (and (looking-at " *|") (goto-char (match-end 0))))
17217 (goto-char match-end))
17218 (when (looking-at
17219 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17220 (replace-match ""))
17221 (when negative (insert " -"))
17222 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17223 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17224 (insert " " (format fh h m))))
17225 (when align (org-table-align))
17226 (message "Time difference inserted")))))
17228 (defun org-make-tdiff-string (y d h m)
17229 (let ((fmt "")
17230 (l nil))
17231 (when (> y 0)
17232 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17233 (push y l))
17234 (when (> d 0)
17235 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17236 (push d l))
17237 (when (> h 0)
17238 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17239 (push h l))
17240 (when (> m 0)
17241 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17242 (push m l))
17243 (apply 'format fmt (nreverse l))))
17245 (defun org-time-string-to-time (s)
17246 "Convert timestamp string S into internal time."
17247 (apply #'encode-time (org-parse-time-string s)))
17249 (defun org-time-string-to-seconds (s)
17250 "Convert a timestamp string S into a number of seconds."
17251 (float-time (org-time-string-to-time s)))
17253 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17255 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17256 "Convert time stamp S to an absolute day number.
17258 If DAYNR in non-nil, and there is a specifier for a cyclic time
17259 stamp, get the closest date to DAYNR. If PREFER is
17260 `past' (respectively `future') return a date past (respectively
17261 after) or equal to DAYNR.
17263 POS is the location of time stamp S, as a buffer position in
17264 BUFFER.
17266 Diary sexp timestamps are matched against DAYNR, when non-nil.
17267 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17268 signaled."
17269 (cond
17270 ((string-match "\\`%%\\((.*)\\)" s)
17271 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17272 ;; only able to match individual dates. If it fails, raise an
17273 ;; error.
17274 (if (and daynr
17275 (org-diary-sexp-entry
17276 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17277 daynr
17278 (signal 'org-diary-sexp-no-match (list s))))
17279 (daynr (org-closest-date s daynr prefer))
17280 (t (time-to-days
17281 (condition-case errdata
17282 (apply #'encode-time (org-parse-time-string s))
17283 (error (error "Bad timestamp `%s'%s\nError was: %s"
17285 (if (not (and buffer pos)) ""
17286 (format-message " at %d in buffer `%s'" pos buffer))
17287 (cdr errdata))))))))
17289 (defun org-days-to-iso-week (days)
17290 "Return the iso week number."
17291 (require 'cal-iso)
17292 (car (calendar-iso-from-absolute days)))
17294 (defun org-small-year-to-year (year)
17295 "Convert 2-digit years into 4-digit years.
17296 YEAR is expanded into one of the 30 next years, if possible, or
17297 into a past one. Any year larger than 99 is returned unchanged."
17298 (if (>= year 100) year
17299 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17300 (century (/ current 100))
17301 (offset (- year (% current 100))))
17302 (cond ((> offset 30) (+ (* (1- century) 100) year))
17303 ((> offset -70) (+ (* century 100) year))
17304 (t (+ (* (1+ century) 100) year))))))
17306 (defun org-time-from-absolute (d)
17307 "Return the time corresponding to date D.
17308 D may be an absolute day number, or a calendar-type list (month day year)."
17309 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17310 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17312 (defvar org-agenda-current-date)
17313 (defun org-calendar-holiday ()
17314 "List of holidays, for Diary display in Org mode."
17315 (require 'holidays)
17316 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17317 (and hl (mapconcat #'identity hl "; "))))
17319 (defun org-diary-sexp-entry (sexp entry d)
17320 "Process a SEXP diary ENTRY for date D."
17321 (require 'diary-lib)
17322 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17323 ;; dynamically.
17324 (let* ((sexp `(let ((entry ,entry)
17325 (date ',d))
17326 ,(car (read-from-string sexp))))
17327 (result (if calendar-debug-sexp (eval sexp)
17328 (condition-case nil
17329 (eval sexp)
17330 (error
17331 (beep)
17332 (message "Bad sexp at line %d in %s: %s"
17333 (org-current-line)
17334 (buffer-file-name) sexp)
17335 (sleep-for 2))))))
17336 (cond ((stringp result) (split-string result "; "))
17337 ((and (consp result)
17338 (not (consp (cdr result)))
17339 (stringp (cdr result))) (cdr result))
17340 ((and (consp result)
17341 (stringp (car result))) result)
17342 (result entry))))
17344 (defun org-diary-to-ical-string (frombuf)
17345 "Get iCalendar entries from diary entries in buffer FROMBUF.
17346 This uses the icalendar.el library."
17347 (let* ((tmpdir temporary-file-directory)
17348 (tmpfile (make-temp-name
17349 (expand-file-name "orgics" tmpdir)))
17350 buf rtn b e)
17351 (with-current-buffer frombuf
17352 (icalendar-export-region (point-min) (point-max) tmpfile)
17353 (setq buf (find-buffer-visiting tmpfile))
17354 (set-buffer buf)
17355 (goto-char (point-min))
17356 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17357 (setq b (match-beginning 0)))
17358 (goto-char (point-max))
17359 (when (re-search-backward "^END:VEVENT" nil t)
17360 (setq e (match-end 0)))
17361 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17362 (kill-buffer buf)
17363 (delete-file tmpfile)
17364 rtn))
17366 (defun org-closest-date (start current prefer)
17367 "Return closest date to CURRENT starting from START.
17369 CURRENT and START are both time stamps.
17371 When PREFER is `past', return a date that is either CURRENT or
17372 past. When PREFER is `future', return a date that is either
17373 CURRENT or future.
17375 Only time stamps with a repeater are modified. Any other time
17376 stamp stay unchanged. In any case, return value is an absolute
17377 day number."
17378 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17379 ;; No repeater. Do not shift time stamp.
17380 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17381 (let ((value (string-to-number (match-string 1 start)))
17382 (type (match-string 2 start)))
17383 (if (= 0 value)
17384 ;; Repeater with a 0-value is considered as void.
17385 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17386 (let* ((base (org-date-to-gregorian start))
17387 (target (org-date-to-gregorian current))
17388 (sday (calendar-absolute-from-gregorian base))
17389 (cday (calendar-absolute-from-gregorian target))
17390 n1 n2)
17391 ;; If START is already past CURRENT, just return START.
17392 (if (<= cday sday) sday
17393 ;; Compute closest date before (N1) and closest date past
17394 ;; (N2) CURRENT.
17395 (pcase type
17396 ("h"
17397 (let ((missing-hours
17398 (mod (+ (- (* 24 (- cday sday))
17399 (nth 2 (org-parse-time-string start)))
17400 org-extend-today-until)
17401 value)))
17402 (setf n1 (if (= missing-hours 0) cday
17403 (- cday (1+ (/ missing-hours 24)))))
17404 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17405 ((or "d" "w")
17406 (let ((value (if (equal type "w") (* 7 value) value)))
17407 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17408 (setf n2 (+ n1 value))))
17409 ("m"
17410 (let* ((add-months
17411 (lambda (d n)
17412 ;; Add N months to gregorian date D, i.e.,
17413 ;; a list (MONTH DAY YEAR). Return a valid
17414 ;; gregorian date.
17415 (let ((m (+ (nth 0 d) n)))
17416 (list (mod m 12)
17417 (nth 1 d)
17418 (+ (/ m 12) (nth 2 d))))))
17419 (months ; Complete months to TARGET.
17420 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17421 (- (nth 0 target) (nth 0 base))
17422 ;; If START's day is greater than
17423 ;; TARGET's, remove incomplete month.
17424 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17425 value)
17426 value))
17427 (before (funcall add-months base months)))
17428 (setf n1 (calendar-absolute-from-gregorian before))
17429 (setf n2
17430 (calendar-absolute-from-gregorian
17431 (funcall add-months before value)))))
17433 (let* ((d (nth 1 base))
17434 (m (nth 0 base))
17435 (y (nth 2 base))
17436 (years ; Complete years to TARGET.
17437 (* (/ (- (nth 2 target)
17439 ;; If START's month and day are
17440 ;; greater than TARGET's, remove
17441 ;; incomplete year.
17442 (if (or (> (nth 0 target) m)
17443 (and (= (nth 0 target) m)
17444 (> (nth 1 target) d)))
17447 value)
17448 value))
17449 (before (list m d (+ y years))))
17450 (setf n1 (calendar-absolute-from-gregorian before))
17451 (setf n2 (calendar-absolute-from-gregorian
17452 (list m d (+ (nth 2 before) value)))))))
17453 ;; Handle PREFER parameter, if any.
17454 (cond
17455 ((eq prefer 'past) (if (= cday n2) n2 n1))
17456 ((eq prefer 'future) (if (= cday n1) n1 n2))
17457 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17459 (defun org-date-to-gregorian (d)
17460 "Turn any specification of date D into a Gregorian date for the calendar."
17461 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17462 ((and (listp d) (= (length d) 3)) d)
17463 ((stringp d)
17464 (let ((d (org-parse-time-string d)))
17465 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17466 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17468 (defun org-parse-time-string (s &optional nodefault)
17469 "Parse the standard Org time string.
17471 This should be a lot faster than the normal `parse-time-string'.
17473 If time is not given, defaults to 0:00. However, with optional
17474 NODEFAULT, hour and minute fields will be nil if not given."
17475 (cond ((string-match org-ts-regexp0 s)
17476 (list 0
17477 (when (or (match-beginning 8) (not nodefault))
17478 (string-to-number (or (match-string 8 s) "0")))
17479 (when (or (match-beginning 7) (not nodefault))
17480 (string-to-number (or (match-string 7 s) "0")))
17481 (string-to-number (match-string 4 s))
17482 (string-to-number (match-string 3 s))
17483 (string-to-number (match-string 2 s))
17484 nil nil nil))
17485 ((string-match "^<[^>]+>$" s)
17486 ;; FIXME: `decode-time' needs to be called with ZONE as its
17487 ;; second argument. However, this requires at least Emacs
17488 ;; 25.1. We can do it when we switch to this version as our
17489 ;; minimal requirement.
17490 (decode-time (seconds-to-time (org-matcher-time s))))
17491 (t (error "Not a standard Org time string: %s" s))))
17493 (defun org-timestamp-up (&optional arg)
17494 "Increase the date item at the cursor by one.
17495 If the cursor is on the year, change the year. If it is on the month,
17496 the day or the time, change that.
17497 With prefix ARG, change by that many units."
17498 (interactive "p")
17499 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17501 (defun org-timestamp-down (&optional arg)
17502 "Decrease the date item at the cursor by one.
17503 If the cursor is on the year, change the year. If it is on the month,
17504 the day or the time, change that.
17505 With prefix ARG, change by that many units."
17506 (interactive "p")
17507 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17509 (defun org-timestamp-up-day (&optional arg)
17510 "Increase the date in the time stamp by one day.
17511 With prefix ARG, change that many days."
17512 (interactive "p")
17513 (if (and (not (org-at-timestamp-p 'lax))
17514 (org-at-heading-p))
17515 (org-todo 'up)
17516 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17518 (defun org-timestamp-down-day (&optional arg)
17519 "Decrease the date in the time stamp by one day.
17520 With prefix ARG, change that many days."
17521 (interactive "p")
17522 (if (and (not (org-at-timestamp-p 'lax))
17523 (org-at-heading-p))
17524 (org-todo 'down)
17525 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17527 (defun org-at-timestamp-p (&optional extended)
17528 "Non-nil if point is inside a timestamp.
17530 By default, the function only consider syntactically valid active
17531 timestamps. However, the caller may have a broader definition
17532 for timestamps. As a consequence, optional argument EXTENDED can
17533 be set to the following values
17535 `inactive'
17537 Include also syntactically valid inactive timestamps.
17539 `agenda'
17541 Include timestamps allowed in Agenda, i.e., those in
17542 properties drawers, planning lines and clock lines.
17544 `lax'
17546 Ignore context. The function matches any part of the
17547 document looking like a timestamp. This includes comments,
17548 example blocks...
17550 For backward-compatibility with Org 9.0, every other non-nil
17551 value is equivalent to `inactive'.
17553 When at a timestamp, return the position of the point as a symbol
17554 among `bracket', `after', `year', `month', `hour', `minute',
17555 `day' or a number of character from the last know part of the
17556 time stamp.
17558 When matching, the match groups are the following:
17559 group 1: year
17560 group 2: month
17561 group 3: day number
17562 group 4: day name
17563 group 5: hours, if any
17564 group 6: minutes, if any"
17565 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17566 (pos (point))
17567 (match?
17568 (let ((boundaries (org-in-regexp regexp)))
17569 (save-match-data
17570 (cond ((null boundaries) nil)
17571 ((eq extended 'lax) t)
17573 (or (and (eq extended 'agenda)
17574 (or (org-at-planning-p)
17575 (org-at-property-p)
17576 (and (bound-and-true-p
17577 org-agenda-include-inactive-timestamps)
17578 (org-at-clock-log-p))))
17579 (eq 'timestamp
17580 (save-excursion
17581 (when (= pos (cdr boundaries)) (forward-char -1))
17582 (org-element-type (org-element-context)))))))))))
17583 (cond
17584 ((not match?) nil)
17585 ((= pos (match-beginning 0)) 'bracket)
17586 ;; Distinguish location right before the closing bracket from
17587 ;; right after it.
17588 ((= pos (1- (match-end 0))) 'bracket)
17589 ((= pos (match-end 0)) 'after)
17590 ((org-pos-in-match-range pos 2) 'year)
17591 ((org-pos-in-match-range pos 3) 'month)
17592 ((org-pos-in-match-range pos 7) 'hour)
17593 ((org-pos-in-match-range pos 8) 'minute)
17594 ((or (org-pos-in-match-range pos 4)
17595 (org-pos-in-match-range pos 5)) 'day)
17596 ((and (> pos (or (match-end 8) (match-end 5)))
17597 (< pos (match-end 0)))
17598 (- pos (or (match-end 8) (match-end 5))))
17599 (t 'day))))
17601 (defun org-toggle-timestamp-type ()
17602 "Toggle the type (<active> or [inactive]) of a time stamp."
17603 (interactive)
17604 (when (org-at-timestamp-p 'lax)
17605 (let ((beg (match-beginning 0)) (end (match-end 0))
17606 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17607 (save-excursion
17608 (goto-char beg)
17609 (while (re-search-forward "[][<>]" end t)
17610 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17611 t t)))
17612 (message "Timestamp is now %sactive"
17613 (if (equal (char-after beg) ?<) "" "in")))))
17615 (defun org-at-clock-log-p ()
17616 "Non-nil if point is on a clock log line."
17617 (and (org-match-line org-clock-line-re)
17618 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17620 (defvar org-clock-history) ; defined in org-clock.el
17621 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17622 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17623 "Change the date in the time stamp at point.
17624 The date will be changed by N times WHAT. WHAT can be `day', `month',
17625 `year', `minute', `second'. If WHAT is not given, the cursor position
17626 in the timestamp determines what will be changed.
17627 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17628 (let ((origin (point))
17629 (timestamp? (org-at-timestamp-p 'lax))
17630 origin-cat
17631 with-hm inactive
17632 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17633 extra rem
17634 ts time time0 fixnext clrgx)
17635 (unless timestamp? (user-error "Not at a timestamp"))
17636 (if (and (not what) (eq timestamp? 'bracket))
17637 (org-toggle-timestamp-type)
17638 ;; Point isn't on brackets. Remember the part of the time-stamp
17639 ;; the point was in. Indeed, size of time-stamps may change,
17640 ;; but point must be kept in the same category nonetheless.
17641 (setq origin-cat timestamp?)
17642 (when (and (not what) (not (eq timestamp? 'day))
17643 org-display-custom-times
17644 (get-text-property (point) 'display)
17645 (not (get-text-property (1- (point)) 'display)))
17646 (setq timestamp? 'day))
17647 (setq timestamp? (or what timestamp?)
17648 inactive (= (char-after (match-beginning 0)) ?\[)
17649 ts (match-string 0))
17650 (replace-match "")
17651 (when (string-match
17652 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17654 (setq extra (match-string 1 ts))
17655 (when suppress-tmp-delay
17656 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17657 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17658 (setq with-hm t))
17659 (setq time0 (org-parse-time-string ts))
17660 (when (and updown
17661 (eq timestamp? 'minute)
17662 (not current-prefix-arg))
17663 ;; This looks like s-up and s-down. Change by one rounding step.
17664 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17665 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17666 (setcar (cdr time0) (+ (nth 1 time0)
17667 (if (> n 0) (- rem) (- dm rem))))))
17668 (setq time
17669 (apply #'encode-time
17670 (or (car time0) 0)
17671 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17672 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17673 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17674 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17675 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17676 (nthcdr 6 time0)))
17677 (when (and (memq timestamp? '(hour minute))
17678 extra
17679 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17680 (setq extra (org-modify-ts-extra
17681 extra
17682 (if (eq timestamp? 'hour) 2 5)
17683 n dm)))
17684 (when (integerp timestamp?)
17685 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17686 (when (eq what 'calendar)
17687 (let ((cal-date (org-get-date-from-calendar)))
17688 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17689 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17690 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17691 (setcar time0 (or (car time0) 0))
17692 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17693 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17694 (setq time (apply 'encode-time time0))))
17695 ;; Insert the new time-stamp, and ensure point stays in the same
17696 ;; category as before (i.e. not after the last position in that
17697 ;; category).
17698 (let ((pos (point)))
17699 ;; Stay before inserted string. `save-excursion' is of no use.
17700 (setq org-last-changed-timestamp
17701 (org-insert-time-stamp time with-hm inactive nil nil extra))
17702 (goto-char pos))
17703 (save-match-data
17704 (looking-at org-ts-regexp3)
17705 (goto-char
17706 (pcase origin-cat
17707 ;; `day' category ends before `hour' if any, or at the end
17708 ;; of the day name.
17709 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17710 (`hour (min (match-end 7) origin))
17711 (`minute (min (1- (match-end 8)) origin))
17712 ((pred integerp) (min (1- (match-end 0)) origin))
17713 ;; Point was right after the time-stamp. However, the
17714 ;; time-stamp length might have changed, so refer to
17715 ;; (match-end 0) instead.
17716 (`after (match-end 0))
17717 ;; `year' and `month' have both fixed size: point couldn't
17718 ;; have moved into another part.
17719 (_ origin))))
17720 ;; Update clock if on a CLOCK line.
17721 (org-clock-update-time-maybe)
17722 ;; Maybe adjust the closest clock in `org-clock-history'
17723 (when org-clock-adjust-closest
17724 (if (not (and (org-at-clock-log-p)
17725 (< 1 (length (delq nil (mapcar 'marker-position
17726 org-clock-history))))))
17727 (message "No clock to adjust")
17728 (cond ((save-excursion ; fix previous clock?
17729 (re-search-backward org-ts-regexp0 nil t)
17730 (looking-back (concat org-clock-string " \\[")
17731 (line-beginning-position)))
17732 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17733 ((save-excursion ; fix next clock?
17734 (re-search-backward org-ts-regexp0 nil t)
17735 (looking-at (concat org-ts-regexp0 "\\] =>")))
17736 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17737 (save-window-excursion
17738 ;; Find closest clock to point, adjust the previous/next one in history
17739 (let* ((p (save-excursion (org-back-to-heading t)))
17740 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17741 (clfixnth
17742 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17743 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17744 (if (not clfixpos)
17745 (message "No clock to adjust")
17746 (save-excursion
17747 (org-goto-marker-or-bmk clfixpos)
17748 (org-show-subtree)
17749 (when (re-search-forward clrgx nil t)
17750 (goto-char (match-beginning 1))
17751 (let (org-clock-adjust-closest)
17752 (org-timestamp-change n timestamp? updown))
17753 (message "Clock adjusted in %s for heading: %s"
17754 (file-name-nondirectory (buffer-file-name))
17755 (org-get-heading t t)))))))))
17756 ;; Try to recenter the calendar window, if any.
17757 (when (and org-calendar-follow-timestamp-change
17758 (get-buffer-window "*Calendar*" t)
17759 (memq timestamp? '(day month year)))
17760 (org-recenter-calendar (time-to-days time))))))
17762 (defun org-modify-ts-extra (s pos n dm)
17763 "Change the different parts of the lead-time and repeat fields in timestamp."
17764 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17765 ng h m new rem)
17766 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17767 (cond
17768 ((or (org-pos-in-match-range pos 2)
17769 (org-pos-in-match-range pos 3))
17770 (setq m (string-to-number (match-string 3 s))
17771 h (string-to-number (match-string 2 s)))
17772 (if (org-pos-in-match-range pos 2)
17773 (setq h (+ h n))
17774 (setq n (* dm (with-no-warnings (signum n))))
17775 (unless (= 0 (setq rem (% m dm)))
17776 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17777 (setq m (+ m n)))
17778 (when (< m 0) (setq m (+ m 60) h (1- h)))
17779 (when (> m 59) (setq m (- m 60) h (1+ h)))
17780 (setq h (mod h 24))
17781 (setq ng 1 new (format "-%02d:%02d" h m)))
17782 ((org-pos-in-match-range pos 6)
17783 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17784 ((org-pos-in-match-range pos 5)
17785 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17787 ((org-pos-in-match-range pos 9)
17788 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17789 ((org-pos-in-match-range pos 8)
17790 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17792 (when ng
17793 (setq s (concat
17794 (substring s 0 (match-beginning ng))
17796 (substring s (match-end ng))))))
17799 (defun org-recenter-calendar (d)
17800 "If the calendar is visible, recenter it to date D."
17801 (let ((cwin (get-buffer-window "*Calendar*" t)))
17802 (when cwin
17803 (let ((calendar-move-hook nil))
17804 (with-selected-window cwin
17805 (calendar-goto-date
17806 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17808 (defun org-goto-calendar (&optional arg)
17809 "Go to the Emacs calendar at the current date.
17810 If there is a time stamp in the current line, go to that date.
17811 A prefix ARG can be used to force the current date."
17812 (interactive "P")
17813 (let ((calendar-move-hook nil)
17814 (calendar-view-holidays-initially-flag nil)
17815 (calendar-view-diary-initially-flag nil)
17816 diff)
17817 (when (or (org-at-timestamp-p 'lax)
17818 (org-match-line (concat ".*" org-ts-regexp)))
17819 (let ((d1 (time-to-days (current-time)))
17820 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17821 (setq diff (- d2 d1))))
17822 (calendar)
17823 (calendar-goto-today)
17824 (when (and diff (not arg)) (calendar-forward-day diff))))
17826 (defun org-get-date-from-calendar ()
17827 "Return a list (month day year) of date at point in calendar."
17828 (with-current-buffer "*Calendar*"
17829 (save-match-data
17830 (calendar-cursor-to-date))))
17832 (defun org-date-from-calendar ()
17833 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17834 If there is already a time stamp at the cursor position, update it."
17835 (interactive)
17836 (if (org-at-timestamp-p 'lax)
17837 (org-timestamp-change 0 'calendar)
17838 (let ((cal-date (org-get-date-from-calendar)))
17839 (org-insert-time-stamp
17840 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17842 (defcustom org-effort-durations
17843 `(("min" . 1)
17844 ("h" . 60)
17845 ("d" . ,(* 60 8))
17846 ("w" . ,(* 60 8 5))
17847 ("m" . ,(* 60 8 5 4))
17848 ("y" . ,(* 60 8 5 40)))
17849 "Conversion factor to minutes for an effort modifier.
17851 Each entry has the form (MODIFIER . MINUTES).
17853 In an effort string, a number followed by MODIFIER is multiplied
17854 by the specified number of MINUTES to obtain an effort in
17855 minutes.
17857 For example, if the value of this variable is ((\"hours\" . 60)), then an
17858 effort string \"2hours\" is equivalent to 120 minutes."
17859 :group 'org-agenda
17860 :version "26.1"
17861 :package-version '(Org . "8.3")
17862 :type '(alist :key-type (string :tag "Modifier")
17863 :value-type (number :tag "Minutes")))
17865 (defcustom org-image-actual-width t
17866 "Should we use the actual width of images when inlining them?
17868 When set to t, always use the image width.
17870 When set to a number, use imagemagick (when available) to set
17871 the image's width to this value.
17873 When set to a number in a list, try to get the width from any
17874 #+ATTR.* keyword if it matches a width specification like
17876 #+ATTR_HTML: :width 300px
17878 and fall back on that number if none is found.
17880 When set to nil, try to get the width from an #+ATTR.* keyword
17881 and fall back on the original width if none is found.
17883 This requires Emacs >= 24.1, build with imagemagick support."
17884 :group 'org-appearance
17885 :version "24.4"
17886 :package-version '(Org . "8.0")
17887 :type '(choice
17888 (const :tag "Use the image width" t)
17889 (integer :tag "Use a number of pixels")
17890 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17891 (const :tag "Use #+ATTR* or don't resize" nil)))
17893 (defcustom org-agenda-inhibit-startup nil
17894 "Inhibit startup when preparing agenda buffers.
17895 When this variable is t, the initialization of the Org agenda
17896 buffers is inhibited: e.g. the visibility state is not set, the
17897 tables are not re-aligned, etc."
17898 :type 'boolean
17899 :version "24.3"
17900 :group 'org-agenda)
17902 (defcustom org-agenda-ignore-properties nil
17903 "Avoid updating text properties when building the agenda.
17904 Properties are used to prepare buffers for effort estimates,
17905 appointments, statistics and subtree-local categories.
17906 If you don't use these in the agenda, you can add them to this
17907 list and agenda building will be a bit faster.
17908 The value is a list, with zero or more of the symbols `effort', `appt',
17909 `stats' or `category'."
17910 :type '(set :greedy t
17911 (const effort)
17912 (const appt)
17913 (const stats)
17914 (const category))
17915 :version "26.1"
17916 :package-version '(Org . "8.3")
17917 :group 'org-agenda)
17919 ;;;; Files
17921 (defun org-save-all-org-buffers ()
17922 "Save all Org buffers without user confirmation."
17923 (interactive)
17924 (message "Saving all Org buffers...")
17925 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17926 (when (featurep 'org-id) (org-id-locations-save))
17927 (message "Saving all Org buffers... done"))
17929 (defun org-revert-all-org-buffers ()
17930 "Revert all Org buffers.
17931 Prompt for confirmation when there are unsaved changes.
17932 Be sure you know what you are doing before letting this function
17933 overwrite your changes.
17935 This function is useful in a setup where one tracks org files
17936 with a version control system, to revert on one machine after pulling
17937 changes from another. I believe the procedure must be like this:
17939 1. M-x org-save-all-org-buffers
17940 2. Pull changes from the other machine, resolve conflicts
17941 3. M-x org-revert-all-org-buffers"
17942 (interactive)
17943 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17944 (user-error "Abort"))
17945 (save-excursion
17946 (save-window-excursion
17947 (dolist (b (buffer-list))
17948 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17949 (with-current-buffer b buffer-file-name))
17950 (pop-to-buffer-same-window b)
17951 (revert-buffer t 'no-confirm)))
17952 (when (and (featurep 'org-id) org-id-track-globally)
17953 (org-id-locations-load)))))
17955 ;;;; Agenda files
17957 ;;;###autoload
17958 (defun org-switchb (&optional arg)
17959 "Switch between Org buffers.
17961 With `\\[universal-argument]' prefix, restrict available buffers to files.
17963 With `\\[universal-argument] \\[universal-argument]' \
17964 prefix, restrict available buffers to agenda files."
17965 (interactive "P")
17966 (let ((blist (org-buffer-list
17967 (cond ((equal arg '(4)) 'files)
17968 ((equal arg '(16)) 'agenda)))))
17969 (pop-to-buffer-same-window
17970 (completing-read "Org buffer: "
17971 (mapcar #'list (mapcar #'buffer-name blist))
17972 nil t))))
17974 (defun org-buffer-list (&optional predicate exclude-tmp)
17975 "Return a list of Org buffers.
17976 PREDICATE can be `export', `files' or `agenda'.
17978 export restrict the list to Export buffers.
17979 files restrict the list to buffers visiting Org files.
17980 agenda restrict the list to buffers visiting agenda files.
17982 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17983 (let* ((bfn nil)
17984 (agenda-files (and (eq predicate 'agenda)
17985 (mapcar 'file-truename (org-agenda-files t))))
17986 (filter
17987 (cond
17988 ((eq predicate 'files)
17989 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17990 ((eq predicate 'export)
17991 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17992 ((eq predicate 'agenda)
17993 (lambda (b)
17994 (with-current-buffer b
17995 (and (derived-mode-p 'org-mode)
17996 (setq bfn (buffer-file-name b))
17997 (member (file-truename bfn) agenda-files)))))
17998 (t (lambda (b) (with-current-buffer b
17999 (or (derived-mode-p 'org-mode)
18000 (string-match "\\*Org .*Export"
18001 (buffer-name b)))))))))
18002 (delq nil
18003 (mapcar
18004 (lambda(b)
18005 (if (and (funcall filter b)
18006 (or (not exclude-tmp)
18007 (not (string-match "tmp" (buffer-name b)))))
18009 nil))
18010 (buffer-list)))))
18012 (defun org-agenda-files (&optional unrestricted archives)
18013 "Get the list of agenda files.
18014 Optional UNRESTRICTED means return the full list even if a restriction
18015 is currently in place.
18016 When ARCHIVES is t, include all archive files that are really being
18017 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18018 `org-agenda-archives-mode' is t."
18019 (let ((files
18020 (cond
18021 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18022 ((stringp org-agenda-files) (org-read-agenda-file-list))
18023 ((listp org-agenda-files) org-agenda-files)
18024 (t (error "Invalid value of `org-agenda-files'")))))
18025 (setq files (apply 'append
18026 (mapcar (lambda (f)
18027 (if (file-directory-p f)
18028 (directory-files
18029 f t org-agenda-file-regexp)
18030 (list f)))
18031 files)))
18032 (when org-agenda-skip-unavailable-files
18033 (setq files (delq nil
18034 (mapcar (function
18035 (lambda (file)
18036 (and (file-readable-p file) file)))
18037 files))))
18038 (when (or (eq archives t)
18039 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18040 (setq files (org-add-archive-files files)))
18041 files))
18043 (defun org-agenda-file-p (&optional file)
18044 "Return non-nil, if FILE is an agenda file.
18045 If FILE is omitted, use the file associated with the current
18046 buffer."
18047 (let ((fname (or file (buffer-file-name))))
18048 (and fname
18049 (member (file-truename fname)
18050 (mapcar #'file-truename (org-agenda-files t))))))
18052 (defun org-edit-agenda-file-list ()
18053 "Edit the list of agenda files.
18054 Depending on setup, this either uses customize to edit the variable
18055 `org-agenda-files', or it visits the file that is holding the list. In the
18056 latter case, the buffer is set up in a way that saving it automatically kills
18057 the buffer and restores the previous window configuration."
18058 (interactive)
18059 (if (stringp org-agenda-files)
18060 (let ((cw (current-window-configuration)))
18061 (find-file org-agenda-files)
18062 (setq-local org-window-configuration cw)
18063 (add-hook 'after-save-hook
18064 (lambda ()
18065 (set-window-configuration
18066 (prog1 org-window-configuration
18067 (kill-buffer (current-buffer))))
18068 (org-install-agenda-files-menu)
18069 (message "New agenda file list installed"))
18070 nil 'local)
18071 (message "%s" (substitute-command-keys
18072 "Edit list and finish with \\[save-buffer]")))
18073 (customize-variable 'org-agenda-files)))
18075 (defun org-store-new-agenda-file-list (list)
18076 "Set new value for the agenda file list and save it correctly."
18077 (if (stringp org-agenda-files)
18078 (let ((fe (org-read-agenda-file-list t)) b u)
18079 (while (setq b (find-buffer-visiting org-agenda-files))
18080 (kill-buffer b))
18081 (with-temp-file org-agenda-files
18082 (insert
18083 (mapconcat
18084 (lambda (f) ;; Keep un-expanded entries.
18085 (if (setq u (assoc f fe))
18086 (cdr u)
18088 list "\n")
18089 "\n")))
18090 (let ((org-mode-hook nil) (org-inhibit-startup t)
18091 (org-insert-mode-line-in-empty-file nil))
18092 (setq org-agenda-files list)
18093 (customize-save-variable 'org-agenda-files org-agenda-files))))
18095 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18096 "Read the list of agenda files from a file.
18097 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18098 filenames, used by `org-store-new-agenda-file-list' to write back
18099 un-expanded file names."
18100 (when (file-directory-p org-agenda-files)
18101 (error "`org-agenda-files' cannot be a single directory"))
18102 (when (stringp org-agenda-files)
18103 (with-temp-buffer
18104 (insert-file-contents org-agenda-files)
18105 (mapcar
18106 (lambda (f)
18107 (let ((e (expand-file-name (substitute-in-file-name f)
18108 org-directory)))
18109 (if pair-with-expansion
18110 (cons e f)
18111 e)))
18112 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18114 ;;;###autoload
18115 (defun org-cycle-agenda-files ()
18116 "Cycle through the files in `org-agenda-files'.
18117 If the current buffer visits an agenda file, find the next one in the list.
18118 If the current buffer does not, find the first agenda file."
18119 (interactive)
18120 (let* ((fs (or (org-agenda-files t)
18121 (user-error "No agenda files")))
18122 (files (copy-sequence fs))
18123 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18124 file)
18125 (when tcf
18126 (while (and (setq file (pop files))
18127 (not (equal (file-truename file) tcf)))))
18128 (find-file (car (or files fs)))
18129 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18131 (defun org-agenda-file-to-front (&optional to-end)
18132 "Move/add the current file to the top of the agenda file list.
18133 If the file is not present in the list, it is added to the front. If it is
18134 present, it is moved there. With optional argument TO-END, add/move to the
18135 end of the list."
18136 (interactive "P")
18137 (let ((org-agenda-skip-unavailable-files nil)
18138 (file-alist (mapcar (lambda (x)
18139 (cons (file-truename x) x))
18140 (org-agenda-files t)))
18141 (ctf (file-truename
18142 (or buffer-file-name
18143 (user-error "Please save the current buffer to a file"))))
18144 x had)
18145 (setq x (assoc ctf file-alist) had x)
18147 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18148 (if to-end
18149 (setq file-alist (append (delq x file-alist) (list x)))
18150 (setq file-alist (cons x (delq x file-alist))))
18151 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18152 (org-install-agenda-files-menu)
18153 (message "File %s to %s of agenda file list"
18154 (if had "moved" "added") (if to-end "end" "front"))))
18156 (defun org-remove-file (&optional file)
18157 "Remove current file from the list of files in variable `org-agenda-files'.
18158 These are the files which are being checked for agenda entries.
18159 Optional argument FILE means use this file instead of the current."
18160 (interactive)
18161 (let* ((org-agenda-skip-unavailable-files nil)
18162 (file (or file buffer-file-name
18163 (user-error "Current buffer does not visit a file")))
18164 (true-file (file-truename file))
18165 (afile (abbreviate-file-name file))
18166 (files (delq nil (mapcar
18167 (lambda (x)
18168 (unless (equal true-file
18169 (file-truename x))
18171 (org-agenda-files t)))))
18172 (if (not (= (length files) (length (org-agenda-files t))))
18173 (progn
18174 (org-store-new-agenda-file-list files)
18175 (org-install-agenda-files-menu)
18176 (message "Removed from Org Agenda list: %s" afile))
18177 (message "File was not in list: %s (not removed)" afile))))
18179 (defun org-file-menu-entry (file)
18180 (vector file (list 'find-file file) t))
18182 (defun org-check-agenda-file (file)
18183 "Make sure FILE exists. If not, ask user what to do."
18184 (unless (file-exists-p file)
18185 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18186 (abbreviate-file-name file))
18187 (let ((r (downcase (read-char-exclusive))))
18188 (cond
18189 ((equal r ?r)
18190 (org-remove-file file)
18191 (throw 'nextfile t))
18192 (t (user-error "Abort"))))))
18194 (defun org-get-agenda-file-buffer (file)
18195 "Get an agenda buffer visiting FILE.
18196 If the buffer needs to be created, add it to the list of buffers
18197 which might be released later."
18198 (let ((buf (org-find-base-buffer-visiting file)))
18199 (if buf
18200 buf ; just return it
18201 ;; Make a new buffer and remember it
18202 (setq buf (find-file-noselect file))
18203 (when buf (push buf org-agenda-new-buffers))
18204 buf)))
18206 (defun org-release-buffers (blist)
18207 "Release all buffers in list, asking the user for confirmation when needed.
18208 When a buffer is unmodified, it is just killed. When modified, it is saved
18209 \(if the user agrees) and then killed."
18210 (let (file)
18211 (dolist (buf blist)
18212 (setq file (buffer-file-name buf))
18213 (when (and (buffer-modified-p buf)
18214 file
18215 (y-or-n-p (format "Save file %s? " file)))
18216 (with-current-buffer buf (save-buffer)))
18217 (kill-buffer buf))))
18219 (defun org-agenda-prepare-buffers (files)
18220 "Create buffers for all agenda files, protect archived trees and comments."
18221 (interactive)
18222 (let ((pa '(:org-archived t))
18223 (pc '(:org-comment t))
18224 (pall '(:org-archived t :org-comment t))
18225 (inhibit-read-only t)
18226 (org-inhibit-startup org-agenda-inhibit-startup)
18227 (rea (concat ":" org-archive-tag ":"))
18228 re pos)
18229 (setq org-tag-alist-for-agenda nil
18230 org-tag-groups-alist-for-agenda nil)
18231 (save-excursion
18232 (save-restriction
18233 (dolist (file files)
18234 (catch 'nextfile
18235 (if (bufferp file)
18236 (set-buffer file)
18237 (org-check-agenda-file file)
18238 (set-buffer (org-get-agenda-file-buffer file)))
18239 (widen)
18240 (org-set-regexps-and-options 'tags-only)
18241 (setq pos (point))
18242 (or (memq 'category org-agenda-ignore-properties)
18243 (org-refresh-category-properties))
18244 (or (memq 'stats org-agenda-ignore-properties)
18245 (org-refresh-stats-properties))
18246 (or (memq 'effort org-agenda-ignore-properties)
18247 (org-refresh-effort-properties))
18248 (or (memq 'appt org-agenda-ignore-properties)
18249 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18250 (setq org-todo-keywords-for-agenda
18251 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18252 (setq org-done-keywords-for-agenda
18253 (append org-done-keywords-for-agenda org-done-keywords))
18254 (setq org-todo-keyword-alist-for-agenda
18255 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18256 (setq org-tag-alist-for-agenda
18257 (org-uniquify
18258 (append org-tag-alist-for-agenda
18259 org-current-tag-alist)))
18260 ;; Merge current file's tag groups into global
18261 ;; `org-tag-groups-alist-for-agenda'.
18262 (when org-group-tags
18263 (dolist (alist org-tag-groups-alist)
18264 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18265 (if old
18266 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18267 (push alist org-tag-groups-alist-for-agenda)))))
18268 (org-with-silent-modifications
18269 (save-excursion
18270 (remove-text-properties (point-min) (point-max) pall)
18271 (when org-agenda-skip-archived-trees
18272 (goto-char (point-min))
18273 (while (re-search-forward rea nil t)
18274 (when (org-at-heading-p t)
18275 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18276 (goto-char (point-min))
18277 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18278 (while (re-search-forward re nil t)
18279 (when (save-match-data (org-in-commented-heading-p t))
18280 (add-text-properties
18281 (match-beginning 0) (org-end-of-subtree t) pc)))))
18282 (goto-char pos)))))
18283 (setq org-todo-keywords-for-agenda
18284 (org-uniquify org-todo-keywords-for-agenda))
18285 (setq org-todo-keyword-alist-for-agenda
18286 (org-uniquify org-todo-keyword-alist-for-agenda))))
18289 ;;;; CDLaTeX minor mode
18291 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18292 "Keymap for the minor `org-cdlatex-mode'.")
18294 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18295 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18296 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18297 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18298 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18300 (defvar org-cdlatex-texmathp-advice-is-done nil
18301 "Flag remembering if we have applied the advice to texmathp already.")
18303 (define-minor-mode org-cdlatex-mode
18304 "Toggle the minor `org-cdlatex-mode'.
18305 This mode supports entering LaTeX environment and math in LaTeX fragments
18306 in Org mode.
18307 \\{org-cdlatex-mode-map}"
18308 nil " OCDL" nil
18309 (when org-cdlatex-mode
18310 (require 'cdlatex)
18311 (run-hooks 'cdlatex-mode-hook)
18312 (cdlatex-compute-tables))
18313 (unless org-cdlatex-texmathp-advice-is-done
18314 (setq org-cdlatex-texmathp-advice-is-done t)
18315 (defadvice texmathp (around org-math-always-on activate)
18316 "Always return t in Org buffers.
18317 This is because we want to insert math symbols without dollars even outside
18318 the LaTeX math segments. If Org mode thinks that point is actually inside
18319 an embedded LaTeX fragment, let `texmathp' do its job.
18320 `\\[org-cdlatex-mode-map]'"
18321 (interactive)
18322 (let (p)
18323 (cond
18324 ((not (derived-mode-p 'org-mode)) ad-do-it)
18325 ((eq this-command 'cdlatex-math-symbol)
18326 (setq ad-return-value t
18327 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18329 (let ((p (org-inside-LaTeX-fragment-p)))
18330 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18331 (setq ad-return-value t
18332 texmathp-why '("Org mode embedded math" . 0))
18333 (when p ad-do-it)))))))))
18335 (defun turn-on-org-cdlatex ()
18336 "Unconditionally turn on `org-cdlatex-mode'."
18337 (org-cdlatex-mode 1))
18339 (defun org-try-cdlatex-tab ()
18340 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18341 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18342 - inside a LaTeX fragment, or
18343 - after the first word in a line, where an abbreviation expansion could
18344 insert a LaTeX environment."
18345 (when org-cdlatex-mode
18346 (cond
18347 ;; Before any word on the line: No expansion possible.
18348 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18349 ;; Just after first word on the line: Expand it. Make sure it
18350 ;; cannot happen on headlines, though.
18351 ((save-excursion
18352 (skip-chars-backward "a-zA-Z0-9*")
18353 (skip-chars-backward " \t")
18354 (and (bolp) (not (org-at-heading-p))))
18355 (cdlatex-tab) t)
18356 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18358 (defun org-cdlatex-underscore-caret (&optional _arg)
18359 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18360 Revert to the normal definition outside of these fragments."
18361 (interactive "P")
18362 (if (org-inside-LaTeX-fragment-p)
18363 (call-interactively 'cdlatex-sub-superscript)
18364 (let (org-cdlatex-mode)
18365 (call-interactively (key-binding (vector last-input-event))))))
18367 (defun org-cdlatex-math-modify (&optional _arg)
18368 "Execute `cdlatex-math-modify' in LaTeX fragments.
18369 Revert to the normal definition outside of these fragments."
18370 (interactive "P")
18371 (if (org-inside-LaTeX-fragment-p)
18372 (call-interactively 'cdlatex-math-modify)
18373 (let (org-cdlatex-mode)
18374 (call-interactively (key-binding (vector last-input-event))))))
18376 (defun org-cdlatex-environment-indent (&optional environment item)
18377 "Execute `cdlatex-environment' and indent the inserted environment.
18379 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18381 The inserted environment is indented to current indentation
18382 unless point is at the beginning of the line, in which the
18383 environment remains unintended."
18384 (interactive)
18385 ;; cdlatex-environment always return nil. Therefore, capture output
18386 ;; first and determine if an environment was selected.
18387 (let* ((beg (point-marker))
18388 (end (copy-marker (point) t))
18389 (inserted (progn
18390 (ignore-errors (cdlatex-environment environment item))
18391 (< beg end)))
18392 ;; Figure out how many lines to move forward after the
18393 ;; environment has been inserted.
18394 (lines (when inserted
18395 (save-excursion
18396 (- (cl-loop while (< beg (point))
18397 with x = 0
18398 do (forward-line -1)
18399 (cl-incf x)
18400 finally return x)
18401 (if (progn (goto-char beg)
18402 (and (progn (skip-chars-forward " \t") (eolp))
18403 (progn (skip-chars-backward " \t") (bolp))))
18404 1 0)))))
18405 (env (org-trim (delete-and-extract-region beg end))))
18406 (when inserted
18407 ;; Get indentation of next line unless at column 0.
18408 (let ((ind (if (bolp) 0
18409 (save-excursion
18410 (org-return-indent)
18411 (prog1 (org-get-indentation)
18412 (when (progn (skip-chars-forward " \t") (eolp))
18413 (delete-region beg (point)))))))
18414 (bol (progn (skip-chars-backward " \t") (bolp))))
18415 ;; Insert a newline before environment unless at column zero
18416 ;; to "escape" the current line. Insert a newline if
18417 ;; something is one the same line as \end{ENVIRONMENT}.
18418 (insert
18419 (concat (unless bol "\n") env
18420 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18421 (unless (zerop ind)
18422 (save-excursion
18423 (goto-char beg)
18424 (while (< (point) end)
18425 (unless (eolp) (indent-line-to ind))
18426 (forward-line))))
18427 (goto-char beg)
18428 (forward-line lines)
18429 (indent-line-to ind)))
18430 (set-marker beg nil)
18431 (set-marker end nil)))
18434 ;;;; LaTeX fragments
18436 (defun org-inside-LaTeX-fragment-p ()
18437 "Test if point is inside a LaTeX fragment.
18438 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18439 sequence appearing also before point.
18440 Even though the matchers for math are configurable, this function assumes
18441 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18442 delimiters are skipped when they have been removed by customization.
18443 The return value is nil, or a cons cell with the delimiter and the
18444 position of this delimiter.
18446 This function does a reasonably good job, but can locally be fooled by
18447 for example currency specifications. For example it will assume being in
18448 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18449 fragments that are properly closed, but during editing, we have to live
18450 with the uncertainty caused by missing closing delimiters. This function
18451 looks only before point, not after."
18452 (catch 'exit
18453 (let ((pos (point))
18454 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18455 (lim (save-excursion (org-backward-paragraph) (point)))
18456 dd-on str (start 0) m re)
18457 (goto-char pos)
18458 (when dodollar
18459 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18460 re (nth 1 (assoc "$" org-latex-regexps)))
18461 (while (string-match re str start)
18462 (cond
18463 ((= (match-end 0) (length str))
18464 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18465 ((= (match-end 0) (- (length str) 5))
18466 (throw 'exit nil))
18467 (t (setq start (match-end 0))))))
18468 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18469 (goto-char pos)
18470 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18471 (and (match-beginning 2) (throw 'exit nil))
18472 ;; count $$
18473 (while (re-search-backward "\\$\\$" lim t)
18474 (setq dd-on (not dd-on)))
18475 (goto-char pos)
18476 (when dd-on (cons "$$" m))))))
18478 (defun org-inside-latex-macro-p ()
18479 "Is point inside a LaTeX macro or its arguments?"
18480 (save-match-data
18481 (org-in-regexp
18482 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18484 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18485 "Build an overlay between BEG and END using IMAGE file.
18486 Argument IMAGETYPE is the extension of the displayed image,
18487 as a string. It defaults to \"png\"."
18488 (let ((ov (make-overlay beg end))
18489 (imagetype (or (intern imagetype) 'png)))
18490 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18491 (overlay-put ov 'evaporate t)
18492 (overlay-put ov
18493 'modification-hooks
18494 (list (lambda (o _flag _beg _end &optional _l)
18495 (delete-overlay o))))
18496 (overlay-put ov
18497 'display
18498 (list 'image :type imagetype :file image :ascent 'center))))
18500 (defun org--list-latex-overlays (&optional beg end)
18501 "List all Org LaTeX overlays in current buffer.
18502 Limit to overlays between BEG and END when those are provided."
18503 (cl-remove-if-not
18504 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18505 (overlays-in (or beg (point-min)) (or end (point-max)))))
18507 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18508 "Remove all overlays with LaTeX fragment images in current buffer.
18509 When optional arguments BEG and END are non-nil, remove all
18510 overlays between them instead. Return a non-nil value when some
18511 overlays were removed, nil otherwise."
18512 (let ((overlays (org--list-latex-overlays beg end)))
18513 (mapc #'delete-overlay overlays)
18514 overlays))
18516 (defun org-toggle-latex-fragment (&optional arg)
18517 "Preview the LaTeX fragment at point, or all locally or globally.
18519 If the cursor is on a LaTeX fragment, create the image and overlay
18520 it over the source code, if there is none. Remove it otherwise.
18521 If there is no fragment at point, display all fragments in the
18522 current section.
18524 With prefix ARG, preview or clear image for all fragments in the
18525 current subtree or in the whole buffer when used before the first
18526 headline. With a prefix ARG `\\[universal-argument] \
18527 \\[universal-argument]' preview or clear images
18528 for all fragments in the buffer."
18529 (interactive "P")
18530 (when (display-graphic-p)
18531 (catch 'exit
18532 (save-excursion
18533 (let (beg end msg)
18534 (cond
18535 ((or (equal arg '(16))
18536 (and (equal arg '(4))
18537 (org-with-limited-levels (org-before-first-heading-p))))
18538 (if (org-remove-latex-fragment-image-overlays)
18539 (progn (message "LaTeX fragments images removed from buffer")
18540 (throw 'exit nil))
18541 (setq msg "Creating images for buffer...")))
18542 ((equal arg '(4))
18543 (org-with-limited-levels (org-back-to-heading t))
18544 (setq beg (point))
18545 (setq end (progn (org-end-of-subtree t) (point)))
18546 (if (org-remove-latex-fragment-image-overlays beg end)
18547 (progn
18548 (message "LaTeX fragment images removed from subtree")
18549 (throw 'exit nil))
18550 (setq msg "Creating images for subtree...")))
18551 ((let ((datum (org-element-context)))
18552 (when (memq (org-element-type datum)
18553 '(latex-environment latex-fragment))
18554 (setq beg (org-element-property :begin datum))
18555 (setq end (org-element-property :end datum))
18556 (if (org-remove-latex-fragment-image-overlays beg end)
18557 (progn (message "LaTeX fragment image removed")
18558 (throw 'exit nil))
18559 (setq msg "Creating image...")))))
18561 (org-with-limited-levels
18562 (setq beg (if (org-at-heading-p) (line-beginning-position)
18563 (outline-previous-heading)
18564 (point)))
18565 (setq end (progn (outline-next-heading) (point)))
18566 (if (org-remove-latex-fragment-image-overlays beg end)
18567 (progn
18568 (message "LaTeX fragment images removed from section")
18569 (throw 'exit nil))
18570 (setq msg "Creating images for section...")))))
18571 (let ((file (buffer-file-name (buffer-base-buffer))))
18572 (org-format-latex
18573 (concat org-preview-latex-image-directory "org-ltximg")
18574 beg end
18575 ;; Emacs cannot overlay images from remote hosts. Create
18576 ;; it in `temporary-file-directory' instead.
18577 (if (or (not file) (file-remote-p file))
18578 temporary-file-directory
18579 default-directory)
18580 'overlays msg 'forbuffer org-preview-latex-default-process))
18581 (message (concat msg "done")))))))
18583 (defun org-format-latex
18584 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18585 "Replace LaTeX fragments with links to an image.
18587 The function takes care of creating the replacement image.
18589 Only consider fragments between BEG and END when those are
18590 provided.
18592 When optional argument OVERLAYS is non-nil, display the image on
18593 top of the fragment instead of replacing it.
18595 PROCESSING-TYPE is the conversion method to use, as a symbol.
18597 Some of the options can be changed using the variable
18598 `org-format-latex-options', which see."
18599 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18600 (unless (eq processing-type 'verbatim)
18601 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18602 (cnt 0)
18603 checkdir-flag)
18604 (goto-char (or beg (point-min)))
18605 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18606 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18607 (overlay-recenter (or end (point-max))))
18608 (while (re-search-forward math-regexp end t)
18609 (unless (and overlays
18610 (eq (get-char-property (point) 'org-overlay-type)
18611 'org-latex-overlay))
18612 (let* ((context (org-element-context))
18613 (type (org-element-type context)))
18614 (when (memq type '(latex-environment latex-fragment))
18615 (let ((block-type (eq type 'latex-environment))
18616 (value (org-element-property :value context))
18617 (beg (org-element-property :begin context))
18618 (end (save-excursion
18619 (goto-char (org-element-property :end context))
18620 (skip-chars-backward " \r\t\n")
18621 (point))))
18622 (cond
18623 ((eq processing-type 'mathjax)
18624 ;; Prepare for MathJax processing.
18625 (if (not (string-match "\\`\\$\\$?" value))
18626 (goto-char end)
18627 (delete-region beg end)
18628 (if (string= (match-string 0 value) "$$")
18629 (insert "\\[" (substring value 2 -2) "\\]")
18630 (insert "\\(" (substring value 1 -1) "\\)"))))
18631 ((assq processing-type org-preview-latex-process-alist)
18632 ;; Process to an image.
18633 (cl-incf cnt)
18634 (goto-char beg)
18635 (let* ((processing-info
18636 (cdr (assq processing-type org-preview-latex-process-alist)))
18637 (face (face-at-point))
18638 ;; Get the colors from the face at point.
18640 (let ((color (plist-get org-format-latex-options
18641 :foreground)))
18642 (if (and forbuffer (eq color 'auto))
18643 (face-attribute face :foreground nil 'default)
18644 color)))
18646 (let ((color (plist-get org-format-latex-options
18647 :background)))
18648 (if (and forbuffer (eq color 'auto))
18649 (face-attribute face :background nil 'default)
18650 color)))
18651 (hash (sha1 (prin1-to-string
18652 (list org-format-latex-header
18653 org-latex-default-packages-alist
18654 org-latex-packages-alist
18655 org-format-latex-options
18656 forbuffer value fg bg))))
18657 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18658 (absprefix (expand-file-name prefix dir))
18659 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18660 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18661 (sep (and block-type "\n\n"))
18662 (link (concat sep "[[file:" linkfile "]]" sep))
18663 (options
18664 (org-combine-plists
18665 org-format-latex-options
18666 `(:foreground ,fg :background ,bg))))
18667 (when msg (message msg cnt))
18668 (unless checkdir-flag ; Ensure the directory exists.
18669 (setq checkdir-flag t)
18670 (let ((todir (file-name-directory absprefix)))
18671 (unless (file-directory-p todir)
18672 (make-directory todir t))))
18673 (unless (file-exists-p movefile)
18674 (org-create-formula-image
18675 value movefile options forbuffer processing-type))
18676 (if overlays
18677 (progn
18678 (dolist (o (overlays-in beg end))
18679 (when (eq (overlay-get o 'org-overlay-type)
18680 'org-latex-overlay)
18681 (delete-overlay o)))
18682 (org--format-latex-make-overlay beg end movefile imagetype)
18683 (goto-char end))
18684 (delete-region beg end)
18685 (insert
18686 (org-add-props link
18687 (list 'org-latex-src
18688 (replace-regexp-in-string "\"" "" value)
18689 'org-latex-src-embed-type
18690 (if block-type 'paragraph 'character)))))))
18691 ((eq processing-type 'mathml)
18692 ;; Process to MathML.
18693 (unless (org-format-latex-mathml-available-p)
18694 (user-error "LaTeX to MathML converter not configured"))
18695 (cl-incf cnt)
18696 (when msg (message msg cnt))
18697 (goto-char beg)
18698 (delete-region beg end)
18699 (insert (org-format-latex-as-mathml
18700 value block-type prefix dir)))
18702 (error "Unknown conversion process %s for LaTeX fragments"
18703 processing-type)))))))))))
18705 (defun org-create-math-formula (latex-frag &optional mathml-file)
18706 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18707 Use `org-latex-to-mathml-convert-command'. If the conversion is
18708 sucessful, return the portion between \"<math...> </math>\"
18709 elements otherwise return nil. When MATHML-FILE is specified,
18710 write the results in to that file. When invoked as an
18711 interactive command, prompt for LATEX-FRAG, with initial value
18712 set to the current active region and echo the results for user
18713 inspection."
18714 (interactive (list (let ((frag (when (org-region-active-p)
18715 (buffer-substring-no-properties
18716 (region-beginning) (region-end)))))
18717 (read-string "LaTeX Fragment: " frag nil frag))))
18718 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18719 (let* ((tmp-in-file
18720 (let ((file (file-relative-name
18721 (make-temp-name (expand-file-name "ltxmathml-in")))))
18722 (write-region latex-frag nil file)
18723 file))
18724 (tmp-out-file (file-relative-name
18725 (make-temp-name (expand-file-name "ltxmathml-out"))))
18726 (cmd (format-spec
18727 org-latex-to-mathml-convert-command
18728 `((?j . ,(and org-latex-to-mathml-jar-file
18729 (shell-quote-argument
18730 (expand-file-name
18731 org-latex-to-mathml-jar-file))))
18732 (?I . ,(shell-quote-argument tmp-in-file))
18733 (?i . ,latex-frag)
18734 (?o . ,(shell-quote-argument tmp-out-file)))))
18735 mathml shell-command-output)
18736 (when (called-interactively-p 'any)
18737 (unless (org-format-latex-mathml-available-p)
18738 (user-error "LaTeX to MathML converter not configured")))
18739 (message "Running %s" cmd)
18740 (setq shell-command-output (shell-command-to-string cmd))
18741 (setq mathml
18742 (when (file-readable-p tmp-out-file)
18743 (with-current-buffer (find-file-noselect tmp-out-file t)
18744 (goto-char (point-min))
18745 (when (re-search-forward
18746 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18747 (regexp-quote
18748 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18749 nil t)
18750 (prog1 (match-string 0) (kill-buffer))))))
18751 (cond
18752 (mathml
18753 (setq mathml
18754 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18755 (when mathml-file
18756 (write-region mathml nil mathml-file))
18757 (when (called-interactively-p 'any)
18758 (message mathml)))
18759 ((message "LaTeX to MathML conversion failed")
18760 (message shell-command-output)))
18761 (delete-file tmp-in-file)
18762 (when (file-exists-p tmp-out-file)
18763 (delete-file tmp-out-file))
18764 mathml))
18766 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18767 prefix &optional dir)
18768 "Use `org-create-math-formula' but check local cache first."
18769 (let* ((absprefix (expand-file-name prefix dir))
18770 (print-length nil) (print-level nil)
18771 (formula-id (concat
18772 "formula-"
18773 (sha1
18774 (prin1-to-string
18775 (list latex-frag
18776 org-latex-to-mathml-convert-command)))))
18777 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18778 (formula-cache-dir (file-name-directory formula-cache)))
18780 (unless (file-directory-p formula-cache-dir)
18781 (make-directory formula-cache-dir t))
18783 (unless (file-exists-p formula-cache)
18784 (org-create-math-formula latex-frag formula-cache))
18786 (if (file-exists-p formula-cache)
18787 ;; Successful conversion. Return the link to MathML file.
18788 (org-add-props
18789 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18790 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18791 'org-latex-src-embed-type (if latex-frag-type
18792 'paragraph 'character)))
18793 ;; Failed conversion. Return the LaTeX fragment verbatim
18794 latex-frag)))
18796 (defun org--get-display-dpi ()
18797 "Get the DPI of the display.
18798 The function assumes that the display has the same pixel width in
18799 the horizontal and vertical directions."
18800 (if (display-graphic-p)
18801 (round (/ (display-pixel-height)
18802 (/ (display-mm-height) 25.4)))
18803 (error "Attempt to calculate the dpi of a non-graphic display")))
18805 (defun org-create-formula-image
18806 (string tofile options buffer &optional processing-type)
18807 "Create an image from LaTeX source using external processes.
18809 The LaTeX STRING is saved to a temporary LaTeX file, then
18810 converted to an image file by process PROCESSING-TYPE defined in
18811 `org-preview-latex-process-alist'. A nil value defaults to
18812 `org-preview-latex-default-process'.
18814 The generated image file is eventually moved to TOFILE.
18816 The OPTIONS argument controls the size, foreground color and
18817 background color of the generated image.
18819 When BUFFER non-nil, this function is used for LaTeX previewing.
18820 Otherwise, it is used to deal with LaTeX snippets showed in
18821 a HTML file."
18822 (let* ((processing-type (or processing-type
18823 org-preview-latex-default-process))
18824 (processing-info
18825 (cdr (assq processing-type org-preview-latex-process-alist)))
18826 (programs (plist-get processing-info :programs))
18827 (error-message (or (plist-get processing-info :message) ""))
18828 (use-xcolor (plist-get processing-info :use-xcolor))
18829 (image-input-type (plist-get processing-info :image-input-type))
18830 (image-output-type (plist-get processing-info :image-output-type))
18831 (post-clean (or (plist-get processing-info :post-clean)
18832 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18833 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18834 (latex-header
18835 (or (plist-get processing-info :latex-header)
18836 (org-latex-make-preamble
18837 (org-export-get-environment (org-export-get-backend 'latex))
18838 org-format-latex-header
18839 'snippet)))
18840 (latex-compiler (plist-get processing-info :latex-compiler))
18841 (image-converter (plist-get processing-info :image-converter))
18842 (tmpdir temporary-file-directory)
18843 (texfilebase (make-temp-name
18844 (expand-file-name "orgtex" tmpdir)))
18845 (texfile (concat texfilebase ".tex"))
18846 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18847 '(1.0 . 1.0)))
18848 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18849 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18850 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18851 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18852 "Black"))
18853 (bg (or (plist-get options (if buffer :background :html-background))
18854 "Transparent"))
18855 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18856 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18857 (dolist (program programs)
18858 (org-check-external-command program error-message))
18859 (if use-xcolor
18860 (progn (if (eq fg 'default)
18861 (setq fg (org-latex-color :foreground))
18862 (setq fg (org-latex-color-format fg)))
18863 (if (eq bg 'default)
18864 (setq bg (org-latex-color :background))
18865 (setq bg (org-latex-color-format
18866 (if (string= bg "Transparent") "white" bg))))
18867 (with-temp-file texfile
18868 (insert latex-header)
18869 (insert "\n\\begin{document}\n"
18870 "\\definecolor{fg}{rgb}{" fg "}\n"
18871 "\\definecolor{bg}{rgb}{" bg "}\n"
18872 "\n\\pagecolor{bg}\n"
18873 "\n{\\color{fg}\n"
18874 string
18875 "\n}\n"
18876 "\n\\end{document}\n")))
18877 (if (eq fg 'default)
18878 (setq fg (org-dvipng-color :foreground))
18879 (unless (string= fg "Transparent")
18880 (setq fg (org-dvipng-color-format fg))))
18881 (if (eq bg 'default)
18882 (setq bg (org-dvipng-color :background))
18883 (unless (string= bg "Transparent")
18884 (setq bg (org-dvipng-color-format bg))))
18885 (with-temp-file texfile
18886 (insert latex-header)
18887 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18889 (let* ((err-msg (format "Please adjust `%s' part of \
18890 `org-preview-latex-process-alist'."
18891 processing-type))
18892 (image-input-file
18893 (org-compile-file
18894 texfile latex-compiler image-input-type err-msg log-buf))
18895 (image-output-file
18896 (org-compile-file
18897 image-input-file image-converter image-output-type err-msg log-buf
18898 `((?F . ,(shell-quote-argument fg))
18899 (?B . ,(shell-quote-argument bg))
18900 (?D . ,(shell-quote-argument (format "%s" dpi)))
18901 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18902 (copy-file image-output-file tofile 'replace)
18903 (dolist (e post-clean)
18904 (when (file-exists-p (concat texfilebase e))
18905 (delete-file (concat texfilebase e))))
18906 image-output-file)))
18908 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18909 "Fill a LaTeX header template TPL.
18910 In the template, the following place holders will be recognized:
18912 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18913 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18914 [PACKAGES] \\usepackage statements for PKG
18915 [NO-PACKAGES] do not include PKG
18916 [EXTRA] the string EXTRA
18917 [NO-EXTRA] do not include EXTRA
18919 For backward compatibility, if both the positive and the negative place
18920 holder is missing, the positive one (without the \"NO-\") will be
18921 assumed to be present at the end of the template.
18922 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18923 EXTRA is a string.
18924 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18925 (let (rpl (end ""))
18926 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18927 (setq rpl (if (or (match-end 1) (not def-pkg))
18928 "" (org-latex-packages-to-string def-pkg snippets-p t))
18929 tpl (replace-match rpl t t tpl))
18930 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18932 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18933 (setq rpl (if (or (match-end 1) (not pkg))
18934 "" (org-latex-packages-to-string pkg snippets-p t))
18935 tpl (replace-match rpl t t tpl))
18936 (when pkg (setq end
18937 (concat end "\n"
18938 (org-latex-packages-to-string pkg snippets-p)))))
18940 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18941 (setq rpl (if (or (match-end 1) (not extra))
18942 "" (concat extra "\n"))
18943 tpl (replace-match rpl t t tpl))
18944 (when (and extra (string-match "\\S-" extra))
18945 (setq end (concat end "\n" extra))))
18947 (if (string-match "\\S-" end)
18948 (concat tpl "\n" end)
18949 tpl)))
18951 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18952 "Turn an alist of packages into a string with the \\usepackage macros."
18953 (setq pkg (mapconcat (lambda(p)
18954 (cond
18955 ((stringp p) p)
18956 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18957 (format "%% Package %s omitted" (cadr p)))
18958 ((equal "" (car p))
18959 (format "\\usepackage{%s}" (cadr p)))
18961 (format "\\usepackage[%s]{%s}"
18962 (car p) (cadr p)))))
18964 "\n"))
18965 (if newline (concat pkg "\n") pkg))
18967 (defun org-dvipng-color (attr)
18968 "Return a RGB color specification for dvipng."
18969 (org-dvipng-color-format (face-attribute 'default attr nil)))
18971 (defun org-dvipng-color-format (color-name)
18972 "Convert COLOR-NAME to a RGB color value for dvipng."
18973 (apply #'format "rgb %s %s %s"
18974 (mapcar 'org-normalize-color
18975 (color-values color-name))))
18977 (defun org-latex-color (attr)
18978 "Return a RGB color for the LaTeX color package."
18979 (org-latex-color-format (face-attribute 'default attr nil)))
18981 (defun org-latex-color-format (color-name)
18982 "Convert COLOR-NAME to a RGB color value."
18983 (apply #'format "%s,%s,%s"
18984 (mapcar 'org-normalize-color
18985 (color-values color-name))))
18987 (defun org-normalize-color (value)
18988 "Return string to be used as color value for an RGB component."
18989 (format "%g" (/ value 65535.0)))
18993 ;; Image display
18995 (defvar-local org-inline-image-overlays nil)
18997 (defun org-toggle-inline-images (&optional include-linked)
18998 "Toggle the display of inline images.
18999 INCLUDE-LINKED is passed to `org-display-inline-images'."
19000 (interactive "P")
19001 (if org-inline-image-overlays
19002 (progn
19003 (org-remove-inline-images)
19004 (when (called-interactively-p 'interactive)
19005 (message "Inline image display turned off")))
19006 (org-display-inline-images include-linked)
19007 (when (called-interactively-p 'interactive)
19008 (message (if org-inline-image-overlays
19009 (format "%d images displayed inline"
19010 (length org-inline-image-overlays))
19011 "No images to display inline")))))
19013 (defun org-redisplay-inline-images ()
19014 "Refresh the display of inline images."
19015 (interactive)
19016 (if (not org-inline-image-overlays)
19017 (org-toggle-inline-images)
19018 (org-toggle-inline-images)
19019 (org-toggle-inline-images)))
19021 (defun org-display-inline-images (&optional include-linked refresh beg end)
19022 "Display inline images.
19024 An inline image is a link which follows either of these
19025 conventions:
19027 1. Its path is a file with an extension matching return value
19028 from `image-file-name-regexp' and it has no contents.
19030 2. Its description consists in a single link of the previous
19031 type.
19033 When optional argument INCLUDE-LINKED is non-nil, also links with
19034 a text description part will be inlined. This can be nice for
19035 a quick look at those images, but it does not reflect what
19036 exported files will look like.
19038 When optional argument REFRESH is non-nil, refresh existing
19039 images between BEG and END. This will create new image displays
19040 only if necessary. BEG and END default to the buffer
19041 boundaries."
19042 (interactive "P")
19043 (when (display-graphic-p)
19044 (unless refresh
19045 (org-remove-inline-images)
19046 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19047 (org-with-wide-buffer
19048 (goto-char (or beg (point-min)))
19049 (let* ((case-fold-search t)
19050 (file-extension-re (image-file-name-regexp))
19051 (link-abbrevs (mapcar #'car
19052 (append org-link-abbrev-alist-local
19053 org-link-abbrev-alist)))
19054 ;; Check absolute, relative file names and explicit
19055 ;; "file:" links. Also check link abbreviations since
19056 ;; some might expand to "file" links.
19057 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19058 (if (not link-abbrevs) ""
19059 (format "\\|\\(?:%s:\\)"
19060 (regexp-opt link-abbrevs))))))
19061 (while (re-search-forward file-types-re end t)
19062 (let ((link (save-match-data (org-element-context))))
19063 ;; Check if we're at an inline image, i.e., an image file
19064 ;; link without a description (unless INCLUDE-LINKED is
19065 ;; non-nil).
19066 (when (and (equal "file" (org-element-property :type link))
19067 (or include-linked
19068 (null (org-element-contents link)))
19069 (string-match-p file-extension-re
19070 (org-element-property :path link)))
19071 (let ((file (expand-file-name
19072 (org-link-unescape
19073 (org-element-property :path link)))))
19074 (when (file-exists-p file)
19075 (let ((width
19076 ;; Apply `org-image-actual-width' specifications.
19077 (cond
19078 ((not (image-type-available-p 'imagemagick)) nil)
19079 ((eq org-image-actual-width t) nil)
19080 ((listp org-image-actual-width)
19082 ;; First try to find a width among
19083 ;; attributes associated to the paragraph
19084 ;; containing link.
19085 (let ((paragraph
19086 (let ((e link))
19087 (while (and (setq e (org-element-property
19088 :parent e))
19089 (not (eq (org-element-type e)
19090 'paragraph))))
19091 e)))
19092 (when paragraph
19093 (save-excursion
19094 (goto-char (org-element-property :begin paragraph))
19095 (when
19096 (re-search-forward
19097 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19098 (org-element-property
19099 :post-affiliated paragraph)
19101 (string-to-number (match-string 1))))))
19102 ;; Otherwise, fall-back to provided number.
19103 (car org-image-actual-width)))
19104 ((numberp org-image-actual-width)
19105 org-image-actual-width)))
19106 (old (get-char-property-and-overlay
19107 (org-element-property :begin link)
19108 'org-image-overlay)))
19109 (if (and (car-safe old) refresh)
19110 (image-refresh (overlay-get (cdr old) 'display))
19111 (let ((image (create-image file
19112 (and width 'imagemagick)
19114 :width width)))
19115 (when image
19116 (let ((ov (make-overlay
19117 (org-element-property :begin link)
19118 (progn
19119 (goto-char
19120 (org-element-property :end link))
19121 (skip-chars-backward " \t")
19122 (point)))))
19123 (overlay-put ov 'display image)
19124 (overlay-put ov 'face 'default)
19125 (overlay-put ov 'org-image-overlay t)
19126 (overlay-put
19127 ov 'modification-hooks
19128 (list 'org-display-inline-remove-overlay))
19129 (push ov org-inline-image-overlays)))))))))))))))
19131 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19132 "Remove inline-display overlay if a corresponding region is modified."
19133 (let ((inhibit-modification-hooks t))
19134 (when (and ov after)
19135 (delete ov org-inline-image-overlays)
19136 (delete-overlay ov))))
19138 (defun org-remove-inline-images ()
19139 "Remove inline display of images."
19140 (interactive)
19141 (mapc #'delete-overlay org-inline-image-overlays)
19142 (setq org-inline-image-overlays nil))
19144 ;;;; Key bindings
19146 (defun org-remap (map &rest commands)
19147 "In MAP, remap the functions given in COMMANDS.
19148 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19149 (let (new old)
19150 (while commands
19151 (setq old (pop commands) new (pop commands))
19152 (org-defkey map (vector 'remap old) new))))
19154 ;; Outline functions from `outline-mode-prefix-map'
19155 ;; that can be remapped in Org:
19156 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19157 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19158 (define-key org-mode-map [remap outline-forward-same-level]
19159 'org-forward-heading-same-level)
19160 (define-key org-mode-map [remap outline-backward-same-level]
19161 'org-backward-heading-same-level)
19162 (define-key org-mode-map [remap outline-show-branches]
19163 'org-kill-note-or-show-branches)
19164 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19165 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19166 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19167 (define-key org-mode-map [remap outline-next-visible-heading]
19168 'org-next-visible-heading)
19169 (define-key org-mode-map [remap outline-previous-visible-heading]
19170 'org-previous-visible-heading)
19171 (define-key org-mode-map [remap show-children] 'org-show-children)
19173 ;; Outline functions from `outline-mode-prefix-map' that can not
19174 ;; be remapped in Org:
19176 ;; - the column "key binding" shows whether the Outline function is still
19177 ;; available in Org mode on the same key that it has been bound to in
19178 ;; Outline mode:
19179 ;; - "overridden": key used for a different functionality in Org mode
19180 ;; - else: key still bound to the same Outline function in Org mode
19182 ;; | Outline function | key binding | Org replacement |
19183 ;; |------------------------------------+-------------+--------------------------|
19184 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19185 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19186 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19187 ;; | `show-entry' | overridden | no replacement |
19188 ;; | `show-branches' | `C-c C-k' | still same function |
19189 ;; | `show-subtree' | overridden | visibility cycling |
19190 ;; | `show-all' | overridden | no replacement |
19191 ;; | `hide-subtree' | overridden | visibility cycling |
19192 ;; | `hide-body' | overridden | no replacement |
19193 ;; | `hide-entry' | overridden | visibility cycling |
19194 ;; | `hide-leaves' | overridden | no replacement |
19195 ;; | `hide-sublevels' | overridden | no replacement |
19196 ;; | `hide-other' | overridden | no replacement |
19198 ;; Make `C-c C-x' a prefix key
19199 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19201 ;; TAB key with modifiers
19202 (org-defkey org-mode-map "\C-i" 'org-cycle)
19203 (org-defkey org-mode-map [(tab)] 'org-cycle)
19204 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19205 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19207 ;; The following line is necessary under Suse GNU/Linux
19208 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19209 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19210 (define-key org-mode-map [backtab] 'org-shifttab)
19212 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19213 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19214 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19216 ;; Cursor keys with modifiers
19217 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19218 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19219 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19220 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19222 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19223 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19224 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19225 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19226 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19227 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19229 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19230 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19231 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19232 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19234 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19235 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19236 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19237 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19239 ;; Babel keys
19240 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19241 (dolist (pair org-babel-key-bindings)
19242 (define-key org-babel-map (car pair) (cdr pair)))
19244 ;;; Extra keys for tty access.
19245 ;; We only set them when really needed because otherwise the
19246 ;; menus don't show the simple keys
19248 (when (or org-use-extra-keys (not window-system))
19249 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19250 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19251 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19252 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19253 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19254 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19255 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19256 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19257 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19258 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19259 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19260 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19261 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19262 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19263 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19264 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19265 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19266 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19267 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19268 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19269 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19270 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19271 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19272 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19273 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19274 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19275 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19276 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19278 ;; All the other keys
19279 (org-remap org-mode-map
19280 'self-insert-command 'org-self-insert-command
19281 'delete-char 'org-delete-char
19282 'delete-backward-char 'org-delete-backward-char)
19283 (org-defkey org-mode-map "|" 'org-force-self-insert)
19285 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19286 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19287 (if (boundp 'narrow-map)
19288 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19289 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19290 (if (boundp 'narrow-map)
19291 (org-defkey narrow-map "b" 'org-narrow-to-block)
19292 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19293 (if (boundp 'narrow-map)
19294 (org-defkey narrow-map "e" 'org-narrow-to-element)
19295 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19296 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19297 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19298 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19299 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19300 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19301 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19302 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19303 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19304 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19305 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19306 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19307 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19308 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19309 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19310 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19311 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19312 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19313 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19314 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19315 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19316 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19317 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19318 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19319 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19320 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19321 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19322 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19323 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19324 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19325 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19326 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19327 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19328 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19329 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19330 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19331 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19332 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19333 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19334 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19335 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19336 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19337 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19338 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19339 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19340 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19341 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19342 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19343 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19344 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19345 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19346 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19347 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19348 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19349 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19350 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19351 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19352 (org-defkey org-mode-map "\C-c^" 'org-sort)
19353 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19354 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19355 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19356 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19357 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19358 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19359 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19360 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19361 (org-defkey org-mode-map "\C-m" 'org-return)
19362 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19363 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19364 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19365 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19366 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19367 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19368 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19369 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19370 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19371 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19372 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19373 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19374 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19375 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19376 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19377 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19378 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19379 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19380 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19381 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19382 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19383 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19384 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19385 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19386 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19388 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19389 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19390 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19392 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19393 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19394 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19395 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19396 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19397 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19398 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19399 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19400 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19401 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19402 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19403 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19404 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19405 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19406 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19407 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19408 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19409 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19410 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19411 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19412 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19413 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19414 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19416 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19417 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19418 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19419 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19420 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19422 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19424 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19426 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19427 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19429 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19432 (defconst org-speed-commands-default
19434 ("Outline Navigation")
19435 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19436 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19437 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19438 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19439 ("F" . org-next-block)
19440 ("B" . org-previous-block)
19441 ("u" . (org-speed-move-safe 'outline-up-heading))
19442 ("j" . org-goto)
19443 ("g" . (org-refile t))
19444 ("Outline Visibility")
19445 ("c" . org-cycle)
19446 ("C" . org-shifttab)
19447 (" " . org-display-outline-path)
19448 ("s" . org-narrow-to-subtree)
19449 ("=" . org-columns)
19450 ("Outline Structure Editing")
19451 ("U" . org-metaup)
19452 ("D" . org-metadown)
19453 ("r" . org-metaright)
19454 ("l" . org-metaleft)
19455 ("R" . org-shiftmetaright)
19456 ("L" . org-shiftmetaleft)
19457 ("i" . (progn (forward-char 1) (call-interactively
19458 'org-insert-heading-respect-content)))
19459 ("^" . org-sort)
19460 ("w" . org-refile)
19461 ("a" . org-archive-subtree-default-with-confirmation)
19462 ("@" . org-mark-subtree)
19463 ("#" . org-toggle-comment)
19464 ("Clock Commands")
19465 ("I" . org-clock-in)
19466 ("O" . org-clock-out)
19467 ("Meta Data Editing")
19468 ("t" . org-todo)
19469 ("," . (org-priority))
19470 ("0" . (org-priority ?\ ))
19471 ("1" . (org-priority ?A))
19472 ("2" . (org-priority ?B))
19473 ("3" . (org-priority ?C))
19474 (":" . org-set-tags-command)
19475 ("e" . org-set-effort)
19476 ("E" . org-inc-effort)
19477 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19478 (org-entry-put (point) "APPT_WARNTIME" m)))
19479 ("Agenda Views etc")
19480 ("v" . org-agenda)
19481 ("/" . org-sparse-tree)
19482 ("Misc")
19483 ("o" . org-open-at-point)
19484 ("?" . org-speed-command-help)
19485 ("<" . (org-agenda-set-restriction-lock 'subtree))
19486 (">" . (org-agenda-remove-restriction-lock))
19488 "The default speed commands.")
19490 (defun org-print-speed-command (e)
19491 (if (> (length (car e)) 1)
19492 (progn
19493 (princ "\n")
19494 (princ (car e))
19495 (princ "\n")
19496 (princ (make-string (length (car e)) ?-))
19497 (princ "\n"))
19498 (princ (car e))
19499 (princ " ")
19500 (if (symbolp (cdr e))
19501 (princ (symbol-name (cdr e)))
19502 (prin1 (cdr e)))
19503 (princ "\n")))
19505 (defun org-speed-command-help ()
19506 "Show the available speed commands."
19507 (interactive)
19508 (if (not org-use-speed-commands)
19509 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19510 (with-output-to-temp-buffer "*Help*"
19511 (princ "User-defined Speed commands\n===========================\n")
19512 (mapc #'org-print-speed-command org-speed-commands-user)
19513 (princ "\n")
19514 (princ "Built-in Speed commands\n=======================\n")
19515 (mapc #'org-print-speed-command org-speed-commands-default))
19516 (with-current-buffer "*Help*"
19517 (setq truncate-lines t))))
19519 (defun org-speed-move-safe (cmd)
19520 "Execute CMD, but make sure that the cursor always ends up in a headline.
19521 If not, return to the original position and throw an error."
19522 (interactive)
19523 (let ((pos (point)))
19524 (call-interactively cmd)
19525 (unless (and (bolp) (org-at-heading-p))
19526 (goto-char pos)
19527 (error "Boundary reached while executing %s" cmd))))
19529 (defvar org-self-insert-command-undo-counter 0)
19531 (defvar org-table-auto-blank-field) ; defined in org-table.el
19532 (defvar org-speed-command nil)
19534 (defun org-speed-command-activate (keys)
19535 "Hook for activating single-letter speed commands.
19536 `org-speed-commands-default' specifies a minimal command set.
19537 Use `org-speed-commands-user' for further customization."
19538 (when (or (and (bolp) (looking-at org-outline-regexp))
19539 (and (functionp org-use-speed-commands)
19540 (funcall org-use-speed-commands)))
19541 (cdr (assoc keys (append org-speed-commands-user
19542 org-speed-commands-default)))))
19544 (defun org-babel-speed-command-activate (keys)
19545 "Hook for activating single-letter code block commands."
19546 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19547 (cdr (assoc keys org-babel-key-bindings))))
19549 (defcustom org-speed-command-hook
19550 '(org-speed-command-activate org-babel-speed-command-activate)
19551 "Hook for activating speed commands at strategic locations.
19552 Hook functions are called in sequence until a valid handler is
19553 found.
19555 Each hook takes a single argument, a user-pressed command key
19556 which is also a `self-insert-command' from the global map.
19558 Within the hook, examine the cursor position and the command key
19559 and return nil or a valid handler as appropriate. Handler could
19560 be one of an interactive command, a function, or a form.
19562 Set `org-use-speed-commands' to non-nil value to enable this
19563 hook. The default setting is `org-speed-command-activate'."
19564 :group 'org-structure
19565 :version "24.1"
19566 :type 'hook)
19568 (defun org-self-insert-command (N)
19569 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19570 If the cursor is in a table looking at whitespace, the whitespace is
19571 overwritten, and the table is not marked as requiring realignment."
19572 (interactive "p")
19573 (org-check-before-invisible-edit 'insert)
19574 (cond
19575 ((and org-use-speed-commands
19576 (let ((kv (this-command-keys-vector)))
19577 (setq org-speed-command
19578 (run-hook-with-args-until-success
19579 'org-speed-command-hook
19580 (make-string 1 (aref kv (1- (length kv))))))))
19581 (cond
19582 ((commandp org-speed-command)
19583 (setq this-command org-speed-command)
19584 (call-interactively org-speed-command))
19585 ((functionp org-speed-command)
19586 (funcall org-speed-command))
19587 ((and org-speed-command (listp org-speed-command))
19588 (eval org-speed-command))
19589 (t (let (org-use-speed-commands)
19590 (call-interactively 'org-self-insert-command)))))
19591 ((and
19592 (org-at-table-p)
19593 (eq N 1)
19594 (not (org-region-active-p))
19595 (progn
19596 ;; Check if we blank the field, and if that triggers align.
19597 (and (featurep 'org-table) org-table-auto-blank-field
19598 (memq last-command
19599 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19600 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19601 ;; Got extra space, this field does not determine
19602 ;; column width.
19603 (let (org-table-may-need-update) (org-table-blank-field))
19604 ;; No extra space, this field may determine column
19605 ;; width.
19606 (org-table-blank-field)))
19608 (looking-at "[^|\n]* \\( \\)|"))
19609 ;; There is room for insertion without re-aligning the table.
19610 (delete-region (match-beginning 1) (match-end 1))
19611 (self-insert-command N))
19613 (setq org-table-may-need-update t)
19614 (self-insert-command N)
19615 (org-fix-tags-on-the-fly)
19616 (when org-self-insert-cluster-for-undo
19617 (if (not (eq last-command 'org-self-insert-command))
19618 (setq org-self-insert-command-undo-counter 1)
19619 (if (>= org-self-insert-command-undo-counter 20)
19620 (setq org-self-insert-command-undo-counter 1)
19621 (and (> org-self-insert-command-undo-counter 0)
19622 buffer-undo-list (listp buffer-undo-list)
19623 (not (cadr buffer-undo-list)) ; remove nil entry
19624 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19625 (setq org-self-insert-command-undo-counter
19626 (1+ org-self-insert-command-undo-counter))))))))
19628 (defun org-check-before-invisible-edit (kind)
19629 "Check is editing if kind KIND would be dangerous with invisible text around.
19630 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19631 ;; First, try to get out of here as quickly as possible, to reduce overhead
19632 (when (and org-catch-invisible-edits
19633 (or (not (boundp 'visible-mode)) (not visible-mode))
19634 (or (get-char-property (point) 'invisible)
19635 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19636 ;; OK, we need to take a closer look. Do not consider
19637 ;; invisibility obtained through text properties (e.g., link
19638 ;; fontification), as it cannot be toggled.
19639 (let* ((invisible-at-point
19640 (pcase (get-char-property-and-overlay (point) 'invisible)
19641 (`(,_ . ,(and (pred overlayp) o)) o)))
19642 ;; Assume that point cannot land in the middle of an
19643 ;; overlay, or between two overlays.
19644 (invisible-before-point
19645 (and (not invisible-at-point)
19646 (not (bobp))
19647 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19648 (`(,_ . ,(and (pred overlayp) o)) o))))
19649 (border-and-ok-direction
19651 ;; Check if we are acting predictably before invisible
19652 ;; text.
19653 (and invisible-at-point
19654 (memq kind '(insert delete-backward)))
19655 ;; Check if we are acting predictably after invisible text
19656 ;; This works not well, and I have turned it off. It seems
19657 ;; better to always show and stop after invisible text.
19658 ;; (and (not invisible-at-point) invisible-before-point
19659 ;; (memq kind '(insert delete)))
19661 (when (or invisible-at-point invisible-before-point)
19662 (when (eq org-catch-invisible-edits 'error)
19663 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19664 (if (and org-custom-properties-overlays
19665 (y-or-n-p "Display invisible properties in this buffer? "))
19666 (org-toggle-custom-properties-visibility)
19667 ;; Make the area visible
19668 (save-excursion
19669 (when invisible-before-point
19670 (goto-char
19671 (previous-single-char-property-change (point) 'invisible)))
19672 ;; Remove whatever overlay is currently making yet-to-be
19673 ;; edited text invisible. Also remove nested invisibility
19674 ;; related overlays.
19675 (delete-overlay (or invisible-at-point invisible-before-point))
19676 (let ((origin (if invisible-at-point (point) (1- (point)))))
19677 (while (pcase (get-char-property-and-overlay origin 'invisible)
19678 (`(,_ . ,(and (pred overlayp) o))
19679 (delete-overlay o)
19680 t)))))
19681 (cond
19682 ((eq org-catch-invisible-edits 'show)
19683 ;; That's it, we do the edit after showing
19684 (message
19685 "Unfolding invisible region around point before editing")
19686 (sit-for 1))
19687 ((and (eq org-catch-invisible-edits 'smart)
19688 border-and-ok-direction)
19689 (message "Unfolding invisible region around point before editing"))
19691 ;; Don't do the edit, make the user repeat it in full visibility
19692 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19694 (defun org-fix-tags-on-the-fly ()
19695 "Align tags in headline at point.
19696 Unlike to `org-set-tags', it ignores region and sorting."
19697 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19698 (org-at-heading-p))
19699 (let ((org-ignore-region t)
19700 (org-tags-sort-function nil))
19701 (org-set-tags nil t))))
19703 (defun org-delete-backward-char (N)
19704 "Like `delete-backward-char', insert whitespace at field end in tables.
19705 When deleting backwards, in tables this function will insert whitespace in
19706 front of the next \"|\" separator, to keep the table aligned. The table will
19707 still be marked for re-alignment if the field did fill the entire column,
19708 because, in this case the deletion might narrow the column."
19709 (interactive "p")
19710 (save-match-data
19711 (org-check-before-invisible-edit 'delete-backward)
19712 (if (and (org-at-table-p)
19713 (eq N 1)
19714 (not (org-region-active-p))
19715 (string-match "|" (buffer-substring (point-at-bol) (point)))
19716 (looking-at ".*?|"))
19717 (let ((pos (point))
19718 (noalign (looking-at "[^|\n\r]* |"))
19719 (c org-table-may-need-update))
19720 (backward-delete-char N)
19721 (unless overwrite-mode
19722 (skip-chars-forward "^|")
19723 (insert " ")
19724 (goto-char (1- pos)))
19725 ;; noalign: if there were two spaces at the end, this field
19726 ;; does not determine the width of the column.
19727 (when noalign (setq org-table-may-need-update c)))
19728 (backward-delete-char N)
19729 (org-fix-tags-on-the-fly))))
19731 (defun org-delete-char (N)
19732 "Like `delete-char', but insert whitespace at field end in tables.
19733 When deleting characters, in tables this function will insert whitespace in
19734 front of the next \"|\" separator, to keep the table aligned. The table will
19735 still be marked for re-alignment if the field did fill the entire column,
19736 because, in this case the deletion might narrow the column."
19737 (interactive "p")
19738 (save-match-data
19739 (org-check-before-invisible-edit 'delete)
19740 (if (and (org-at-table-p)
19741 (not (bolp))
19742 (not (= (char-after) ?|))
19743 (eq N 1))
19744 (if (looking-at ".*?|")
19745 (let ((pos (point))
19746 (noalign (looking-at "[^|\n\r]* |"))
19747 (c org-table-may-need-update))
19748 (replace-match
19749 (concat (substring (match-string 0) 1 -1) " |") nil t)
19750 (goto-char pos)
19751 ;; noalign: if there were two spaces at the end, this field
19752 ;; does not determine the width of the column.
19753 (when noalign (setq org-table-may-need-update c)))
19754 (delete-char N))
19755 (delete-char N)
19756 (org-fix-tags-on-the-fly))))
19758 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19759 (put 'org-self-insert-command 'delete-selection
19760 (lambda ()
19761 (not (run-hook-with-args-until-success
19762 'self-insert-uses-region-functions))))
19763 (put 'orgtbl-self-insert-command 'delete-selection
19764 (lambda ()
19765 (not (run-hook-with-args-until-success
19766 'self-insert-uses-region-functions))))
19767 (put 'org-delete-char 'delete-selection 'supersede)
19768 (put 'org-delete-backward-char 'delete-selection 'supersede)
19769 (put 'org-yank 'delete-selection 'yank)
19771 ;; Make `flyspell-mode' delay after some commands
19772 (put 'org-self-insert-command 'flyspell-delayed t)
19773 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19774 (put 'org-delete-char 'flyspell-delayed t)
19775 (put 'org-delete-backward-char 'flyspell-delayed t)
19777 ;; Make pabbrev-mode expand after Org mode commands
19778 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19779 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19781 (defun org-transpose-words ()
19782 "Transpose words for Org.
19783 This uses the `org-mode-transpose-word-syntax-table' syntax
19784 table, which interprets characters in `org-emphasis-alist' as
19785 word constituents."
19786 (interactive)
19787 (with-syntax-table org-mode-transpose-word-syntax-table
19788 (call-interactively 'transpose-words)))
19789 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19791 (defvar org-ctrl-c-ctrl-c-hook nil
19792 "Hook for functions attaching themselves to `C-c C-c'.
19794 This can be used to add additional functionality to the C-c C-c
19795 key which executes context-dependent commands. This hook is run
19796 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19797 run after the last test.
19799 Each function will be called with no arguments. The function
19800 must check if the context is appropriate for it to act. If yes,
19801 it should do its thing and then return a non-nil value. If the
19802 context is wrong, just do nothing and return nil.")
19804 (defvar org-ctrl-c-ctrl-c-final-hook nil
19805 "Hook for functions attaching themselves to `C-c C-c'.
19807 This can be used to add additional functionality to the C-c C-c
19808 key which executes context-dependent commands. This hook is run
19809 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19810 before the first test.
19812 Each function will be called with no arguments. The function
19813 must check if the context is appropriate for it to act. If yes,
19814 it should do its thing and then return a non-nil value. If the
19815 context is wrong, just do nothing and return nil.")
19817 (defvar org-tab-first-hook nil
19818 "Hook for functions to attach themselves to TAB.
19819 See `org-ctrl-c-ctrl-c-hook' for more information.
19820 This hook runs as the first action when TAB is pressed, even before
19821 `org-cycle' messes around with the `outline-regexp' to cater for
19822 inline tasks and plain list item folding.
19823 If any function in this hook returns t, any other actions that
19824 would have been caused by TAB (such as table field motion or visibility
19825 cycling) will not occur.")
19827 (defvar org-tab-after-check-for-table-hook nil
19828 "Hook for functions to attach themselves to TAB.
19829 See `org-ctrl-c-ctrl-c-hook' for more information.
19830 This hook runs after it has been established that the cursor is not in a
19831 table, but before checking if the cursor is in a headline or if global cycling
19832 should be done.
19833 If any function in this hook returns t, not other actions like visibility
19834 cycling will be done.")
19836 (defvar org-tab-after-check-for-cycling-hook nil
19837 "Hook for functions to attach themselves to TAB.
19838 See `org-ctrl-c-ctrl-c-hook' for more information.
19839 This hook runs after it has been established that not table field motion and
19840 not visibility should be done because of current context. This is probably
19841 the place where a package like yasnippets can hook in.")
19843 (defvar org-tab-before-tab-emulation-hook nil
19844 "Hook for functions to attach themselves to TAB.
19845 See `org-ctrl-c-ctrl-c-hook' for more information.
19846 This hook runs after every other options for TAB have been exhausted, but
19847 before indentation and \t insertion takes place.")
19849 (defvar org-metaleft-hook nil
19850 "Hook for functions attaching themselves to `M-left'.
19851 See `org-ctrl-c-ctrl-c-hook' for more information.")
19852 (defvar org-metaright-hook nil
19853 "Hook for functions attaching themselves to `M-right'.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-metaup-hook nil
19856 "Hook for functions attaching themselves to `M-up'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-metadown-hook nil
19859 "Hook for functions attaching themselves to `M-down'.
19860 See `org-ctrl-c-ctrl-c-hook' for more information.")
19861 (defvar org-shiftmetaleft-hook nil
19862 "Hook for functions attaching themselves to `M-S-left'.
19863 See `org-ctrl-c-ctrl-c-hook' for more information.")
19864 (defvar org-shiftmetaright-hook nil
19865 "Hook for functions attaching themselves to `M-S-right'.
19866 See `org-ctrl-c-ctrl-c-hook' for more information.")
19867 (defvar org-shiftmetaup-hook nil
19868 "Hook for functions attaching themselves to `M-S-up'.
19869 See `org-ctrl-c-ctrl-c-hook' for more information.")
19870 (defvar org-shiftmetadown-hook nil
19871 "Hook for functions attaching themselves to `M-S-down'.
19872 See `org-ctrl-c-ctrl-c-hook' for more information.")
19873 (defvar org-metareturn-hook nil
19874 "Hook for functions attaching themselves to `M-RET'.
19875 See `org-ctrl-c-ctrl-c-hook' for more information.")
19876 (defvar org-shiftup-hook nil
19877 "Hook for functions attaching themselves to `S-up'.
19878 See `org-ctrl-c-ctrl-c-hook' for more information.")
19879 (defvar org-shiftup-final-hook nil
19880 "Hook for functions attaching themselves to `S-up'.
19881 This one runs after all other options except shift-select have been excluded.
19882 See `org-ctrl-c-ctrl-c-hook' for more information.")
19883 (defvar org-shiftdown-hook nil
19884 "Hook for functions attaching themselves to `S-down'.
19885 See `org-ctrl-c-ctrl-c-hook' for more information.")
19886 (defvar org-shiftdown-final-hook nil
19887 "Hook for functions attaching themselves to `S-down'.
19888 This one runs after all other options except shift-select have been excluded.
19889 See `org-ctrl-c-ctrl-c-hook' for more information.")
19890 (defvar org-shiftleft-hook nil
19891 "Hook for functions attaching themselves to `S-left'.
19892 See `org-ctrl-c-ctrl-c-hook' for more information.")
19893 (defvar org-shiftleft-final-hook nil
19894 "Hook for functions attaching themselves to `S-left'.
19895 This one runs after all other options except shift-select have been excluded.
19896 See `org-ctrl-c-ctrl-c-hook' for more information.")
19897 (defvar org-shiftright-hook nil
19898 "Hook for functions attaching themselves to `S-right'.
19899 See `org-ctrl-c-ctrl-c-hook' for more information.")
19900 (defvar org-shiftright-final-hook nil
19901 "Hook for functions attaching themselves to `S-right'.
19902 This one runs after all other options except shift-select have been excluded.
19903 See `org-ctrl-c-ctrl-c-hook' for more information.")
19905 (defun org-modifier-cursor-error ()
19906 "Throw an error, a modified cursor command was applied in wrong context."
19907 (user-error "This command is active in special context like tables, headlines or items"))
19909 (defun org-shiftselect-error ()
19910 "Throw an error because Shift-Cursor command was applied in wrong context."
19911 (if (and (boundp 'shift-select-mode) shift-select-mode)
19912 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19913 (user-error "This command works only in special context like headlines or timestamps")))
19915 (defun org-call-for-shift-select (cmd)
19916 (let ((this-command-keys-shift-translated t))
19917 (call-interactively cmd)))
19919 (defun org-shifttab (&optional arg)
19920 "Global visibility cycling or move to previous table field.
19921 Call `org-table-previous-field' within a table.
19922 When ARG is nil, cycle globally through visibility states.
19923 When ARG is a numeric prefix, show contents of this level."
19924 (interactive "P")
19925 (cond
19926 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19927 ((integerp arg)
19928 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19929 (message "Content view to level: %d" arg)
19930 (org-content (prefix-numeric-value arg2))
19931 (org-cycle-show-empty-lines t)
19932 (setq org-cycle-global-status 'overview)))
19933 (t (call-interactively 'org-global-cycle))))
19935 (defun org-shiftmetaleft ()
19936 "Promote subtree or delete table column.
19937 Calls `org-promote-subtree', `org-outdent-item-tree', or
19938 `org-table-delete-column', depending on context. See the
19939 individual commands for more information."
19940 (interactive)
19941 (cond
19942 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19943 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19944 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19945 ((if (not (org-region-active-p)) (org-at-item-p)
19946 (save-excursion (goto-char (region-beginning))
19947 (org-at-item-p)))
19948 (call-interactively 'org-outdent-item-tree))
19949 (t (org-modifier-cursor-error))))
19951 (defun org-shiftmetaright ()
19952 "Demote subtree or insert table column.
19953 Calls `org-demote-subtree', `org-indent-item-tree', or
19954 `org-table-insert-column', depending on context. See the
19955 individual commands for more information."
19956 (interactive)
19957 (cond
19958 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19959 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19960 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19961 ((if (not (org-region-active-p)) (org-at-item-p)
19962 (save-excursion (goto-char (region-beginning))
19963 (org-at-item-p)))
19964 (call-interactively 'org-indent-item-tree))
19965 (t (org-modifier-cursor-error))))
19967 (defun org-shiftmetaup (&optional _arg)
19968 "Drag the line at point up.
19969 In a table, kill the current row.
19970 On a clock timestamp, update the value of the timestamp like `S-<up>'
19971 but also adjust the previous clocked item in the clock history.
19972 Everywhere else, drag the line at point up."
19973 (interactive "P")
19974 (cond
19975 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19976 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19977 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19978 (call-interactively 'org-timestamp-up)))
19979 (t (call-interactively 'org-drag-line-backward))))
19981 (defun org-shiftmetadown (&optional _arg)
19982 "Drag the line at point down.
19983 In a table, insert an empty row at the current line.
19984 On a clock timestamp, update the value of the timestamp like `S-<down>'
19985 but also adjust the previous clocked item in the clock history.
19986 Everywhere else, drag the line at point down."
19987 (interactive "P")
19988 (cond
19989 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19990 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19991 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19992 (call-interactively 'org-timestamp-down)))
19993 (t (call-interactively 'org-drag-line-forward))))
19995 (defsubst org-hidden-tree-error ()
19996 (user-error
19997 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19999 (defun org-metaleft (&optional _arg)
20000 "Promote heading, list item at point or move table column left.
20002 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20003 depending on context. With no specific context, calls the Emacs
20004 default `backward-word'. See the individual commands for more
20005 information.
20007 This function runs the hook `org-metaleft-hook' as a first step,
20008 and returns at first non-nil value."
20009 (interactive "P")
20010 (cond
20011 ((run-hook-with-args-until-success 'org-metaleft-hook))
20012 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20013 ((org-with-limited-levels
20014 (or (org-at-heading-p)
20015 (and (org-region-active-p)
20016 (save-excursion
20017 (goto-char (region-beginning))
20018 (org-at-heading-p)))))
20019 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20020 (call-interactively 'org-do-promote))
20021 ;; At an inline task.
20022 ((org-at-heading-p)
20023 (call-interactively 'org-inlinetask-promote))
20024 ((or (org-at-item-p)
20025 (and (org-region-active-p)
20026 (save-excursion
20027 (goto-char (region-beginning))
20028 (org-at-item-p))))
20029 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20030 (call-interactively 'org-outdent-item))
20031 (t (call-interactively 'backward-word))))
20033 (defun org-metaright (&optional _arg)
20034 "Demote heading, list item at point or move table column right.
20036 In front of a drawer or a block keyword, indent it correctly.
20038 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20039 `org-indent-drawer' or `org-indent-block' depending on context.
20040 With no specific context, calls the Emacs default `forward-word'.
20041 See the individual commands for more information.
20043 This function runs the hook `org-metaright-hook' as a first step,
20044 and returns at first non-nil value."
20045 (interactive "P")
20046 (cond
20047 ((run-hook-with-args-until-success 'org-metaright-hook))
20048 ((org-at-table-p) (call-interactively 'org-table-move-column))
20049 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20050 ((org-at-block-p) (call-interactively 'org-indent-block))
20051 ((org-with-limited-levels
20052 (or (org-at-heading-p)
20053 (and (org-region-active-p)
20054 (save-excursion
20055 (goto-char (region-beginning))
20056 (org-at-heading-p)))))
20057 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20058 (call-interactively 'org-do-demote))
20059 ;; At an inline task.
20060 ((org-at-heading-p)
20061 (call-interactively 'org-inlinetask-demote))
20062 ((or (org-at-item-p)
20063 (and (org-region-active-p)
20064 (save-excursion
20065 (goto-char (region-beginning))
20066 (org-at-item-p))))
20067 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20068 (call-interactively 'org-indent-item))
20069 (t (call-interactively 'forward-word))))
20071 (defun org-check-for-hidden (what)
20072 "Check if there are hidden headlines/items in the current visual line.
20073 WHAT can be either `headlines' or `items'. If the current line is
20074 an outline or item heading and it has a folded subtree below it,
20075 this function returns t, nil otherwise."
20076 (let ((re (cond
20077 ((eq what 'headlines) org-outline-regexp-bol)
20078 ((eq what 'items) (org-item-beginning-re))
20079 (t (error "This should not happen"))))
20080 beg end)
20081 (save-excursion
20082 (catch 'exit
20083 (unless (org-region-active-p)
20084 (setq beg (point-at-bol))
20085 (beginning-of-line 2)
20086 (while (and (not (eobp)) ;; this is like `next-line'
20087 (get-char-property (1- (point)) 'invisible))
20088 (beginning-of-line 2))
20089 (setq end (point))
20090 (goto-char beg)
20091 (goto-char (point-at-eol))
20092 (setq end (max end (point)))
20093 (while (re-search-forward re end t)
20094 (when (get-char-property (match-beginning 0) 'invisible)
20095 (throw 'exit t))))
20096 nil))))
20098 (defun org-metaup (&optional _arg)
20099 "Move subtree up or move table row up.
20100 Calls `org-move-subtree-up' or `org-table-move-row' or
20101 `org-move-item-up', depending on context. See the individual commands
20102 for more information."
20103 (interactive "P")
20104 (cond
20105 ((run-hook-with-args-until-success 'org-metaup-hook))
20106 ((org-region-active-p)
20107 (let* ((a (min (region-beginning) (region-end)))
20108 (b (1- (max (region-beginning) (region-end))))
20109 (c (save-excursion (goto-char a)
20110 (move-beginning-of-line 0)))
20111 (d (save-excursion (goto-char a)
20112 (move-end-of-line 0) (point))))
20113 (transpose-regions a b c d)
20114 (goto-char c)))
20115 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20116 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20117 ((org-at-item-p) (call-interactively 'org-move-item-up))
20118 (t (org-drag-element-backward))))
20120 (defun org-metadown (&optional _arg)
20121 "Move subtree down or move table row down.
20122 Calls `org-move-subtree-down' or `org-table-move-row' or
20123 `org-move-item-down', depending on context. See the individual
20124 commands for more information."
20125 (interactive "P")
20126 (cond
20127 ((run-hook-with-args-until-success 'org-metadown-hook))
20128 ((org-region-active-p)
20129 (let* ((a (min (region-beginning) (region-end)))
20130 (b (max (region-beginning) (region-end)))
20131 (c (save-excursion (goto-char b)
20132 (move-beginning-of-line 1)))
20133 (d (save-excursion (goto-char b)
20134 (move-end-of-line 1) (1+ (point)))))
20135 (transpose-regions a b c d)
20136 (goto-char d)))
20137 ((org-at-table-p) (call-interactively 'org-table-move-row))
20138 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20139 ((org-at-item-p) (call-interactively 'org-move-item-down))
20140 (t (org-drag-element-forward))))
20142 (defun org-shiftup (&optional arg)
20143 "Increase item in timestamp or increase priority of current headline.
20144 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20145 depending on context. See the individual commands for more information."
20146 (interactive "P")
20147 (cond
20148 ((run-hook-with-args-until-success 'org-shiftup-hook))
20149 ((and org-support-shift-select (org-region-active-p))
20150 (org-call-for-shift-select 'previous-line))
20151 ((org-at-timestamp-p 'lax)
20152 (call-interactively (if org-edit-timestamp-down-means-later
20153 'org-timestamp-down 'org-timestamp-up)))
20154 ((and (not (eq org-support-shift-select 'always))
20155 org-enable-priority-commands
20156 (org-at-heading-p))
20157 (call-interactively 'org-priority-up))
20158 ((and (not org-support-shift-select) (org-at-item-p))
20159 (call-interactively 'org-previous-item))
20160 ((org-clocktable-try-shift 'up arg))
20161 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20162 (org-support-shift-select
20163 (org-call-for-shift-select 'previous-line))
20164 (t (org-shiftselect-error))))
20166 (defun org-shiftdown (&optional arg)
20167 "Decrease item in timestamp or decrease priority of current headline.
20168 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20169 depending on context. See the individual commands for more information."
20170 (interactive "P")
20171 (cond
20172 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20173 ((and org-support-shift-select (org-region-active-p))
20174 (org-call-for-shift-select 'next-line))
20175 ((org-at-timestamp-p 'lax)
20176 (call-interactively (if org-edit-timestamp-down-means-later
20177 'org-timestamp-up 'org-timestamp-down)))
20178 ((and (not (eq org-support-shift-select 'always))
20179 org-enable-priority-commands
20180 (org-at-heading-p))
20181 (call-interactively 'org-priority-down))
20182 ((and (not org-support-shift-select) (org-at-item-p))
20183 (call-interactively 'org-next-item))
20184 ((org-clocktable-try-shift 'down arg))
20185 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20186 (org-support-shift-select
20187 (org-call-for-shift-select 'next-line))
20188 (t (org-shiftselect-error))))
20190 (defun org-shiftright (&optional arg)
20191 "Cycle the thing at point or in the current line, depending on context.
20192 Depending on context, this does one of the following:
20194 - switch a timestamp at point one day into the future
20195 - on a headline, switch to the next TODO keyword.
20196 - on an item, switch entire list to the next bullet type
20197 - on a property line, switch to the next allowed value
20198 - on a clocktable definition line, move time block into the future"
20199 (interactive "P")
20200 (cond
20201 ((run-hook-with-args-until-success 'org-shiftright-hook))
20202 ((and org-support-shift-select (org-region-active-p))
20203 (org-call-for-shift-select 'forward-char))
20204 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20205 ((and (not (eq org-support-shift-select 'always))
20206 (org-at-heading-p))
20207 (let ((org-inhibit-logging
20208 (not org-treat-S-cursor-todo-selection-as-state-change))
20209 (org-inhibit-blocking
20210 (not org-treat-S-cursor-todo-selection-as-state-change)))
20211 (org-call-with-arg 'org-todo 'right)))
20212 ((or (and org-support-shift-select
20213 (not (eq org-support-shift-select 'always))
20214 (org-at-item-bullet-p))
20215 (and (not org-support-shift-select) (org-at-item-p)))
20216 (org-call-with-arg 'org-cycle-list-bullet nil))
20217 ((and (not (eq org-support-shift-select 'always))
20218 (org-at-property-p))
20219 (call-interactively 'org-property-next-allowed-value))
20220 ((org-clocktable-try-shift 'right arg))
20221 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20222 (org-support-shift-select
20223 (org-call-for-shift-select 'forward-char))
20224 (t (org-shiftselect-error))))
20226 (defun org-shiftleft (&optional arg)
20227 "Cycle the thing at point or in the current line, depending on context.
20228 Depending on context, this does one of the following:
20230 - switch a timestamp at point one day into the past
20231 - on a headline, switch to the previous TODO keyword.
20232 - on an item, switch entire list to the previous bullet type
20233 - on a property line, switch to the previous allowed value
20234 - on a clocktable definition line, move time block into the past"
20235 (interactive "P")
20236 (cond
20237 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20238 ((and org-support-shift-select (org-region-active-p))
20239 (org-call-for-shift-select 'backward-char))
20240 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20241 ((and (not (eq org-support-shift-select 'always))
20242 (org-at-heading-p))
20243 (let ((org-inhibit-logging
20244 (not org-treat-S-cursor-todo-selection-as-state-change))
20245 (org-inhibit-blocking
20246 (not org-treat-S-cursor-todo-selection-as-state-change)))
20247 (org-call-with-arg 'org-todo 'left)))
20248 ((or (and org-support-shift-select
20249 (not (eq org-support-shift-select 'always))
20250 (org-at-item-bullet-p))
20251 (and (not org-support-shift-select) (org-at-item-p)))
20252 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20253 ((and (not (eq org-support-shift-select 'always))
20254 (org-at-property-p))
20255 (call-interactively 'org-property-previous-allowed-value))
20256 ((org-clocktable-try-shift 'left arg))
20257 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20258 (org-support-shift-select
20259 (org-call-for-shift-select 'backward-char))
20260 (t (org-shiftselect-error))))
20262 (defun org-shiftcontrolright ()
20263 "Switch to next TODO set."
20264 (interactive)
20265 (cond
20266 ((and org-support-shift-select (org-region-active-p))
20267 (org-call-for-shift-select 'forward-word))
20268 ((and (not (eq org-support-shift-select 'always))
20269 (org-at-heading-p))
20270 (org-call-with-arg 'org-todo 'nextset))
20271 (org-support-shift-select
20272 (org-call-for-shift-select 'forward-word))
20273 (t (org-shiftselect-error))))
20275 (defun org-shiftcontrolleft ()
20276 "Switch to previous TODO set."
20277 (interactive)
20278 (cond
20279 ((and org-support-shift-select (org-region-active-p))
20280 (org-call-for-shift-select 'backward-word))
20281 ((and (not (eq org-support-shift-select 'always))
20282 (org-at-heading-p))
20283 (org-call-with-arg 'org-todo 'previousset))
20284 (org-support-shift-select
20285 (org-call-for-shift-select 'backward-word))
20286 (t (org-shiftselect-error))))
20288 (defun org-shiftcontrolup (&optional n)
20289 "Change timestamps synchronously up in CLOCK log lines.
20290 Optional argument N tells to change by that many units."
20291 (interactive "P")
20292 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20293 (let (org-support-shift-select)
20294 (org-clock-timestamps-up n))
20295 (user-error "Not at a clock log")))
20297 (defun org-shiftcontroldown (&optional n)
20298 "Change timestamps synchronously down in CLOCK log lines.
20299 Optional argument N tells to change by that many units."
20300 (interactive "P")
20301 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20302 (let (org-support-shift-select)
20303 (org-clock-timestamps-down n))
20304 (user-error "Not at a clock log")))
20306 (defun org-increase-number-at-point (&optional inc)
20307 "Increment the number at point.
20308 With an optional prefix numeric argument INC, increment using
20309 this numeric value."
20310 (interactive "p")
20311 (if (not (number-at-point))
20312 (user-error "Not on a number")
20313 (unless inc (setq inc 1))
20314 (let ((pos (point))
20315 (beg (skip-chars-backward "-+^/*0-9eE."))
20316 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20317 (setq nap (buffer-substring-no-properties
20318 (+ pos beg) (+ pos beg end)))
20319 (delete-region (+ pos beg) (+ pos beg end))
20320 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20321 (when (org-at-table-p)
20322 (org-table-align)
20323 (org-table-end-of-field 1))))
20325 (defun org-decrease-number-at-point (&optional inc)
20326 "Decrement the number at point.
20327 With an optional prefix numeric argument INC, decrement using
20328 this numeric value."
20329 (interactive "p")
20330 (org-increase-number-at-point (- (or inc 1))))
20332 (defun org-ctrl-c-ret ()
20333 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20334 (interactive)
20335 (cond
20336 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20337 (t (call-interactively 'org-insert-heading))))
20339 (defun org-find-visible ()
20340 (let ((s (point)))
20341 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20342 (get-char-property s 'invisible)))
20344 (defun org-find-invisible ()
20345 (let ((s (point)))
20346 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20347 (not (get-char-property s 'invisible))))
20350 (defun org-copy-visible (beg end)
20351 "Copy the visible parts of the region."
20352 (interactive "r")
20353 (let ((result ""))
20354 (while (/= beg end)
20355 (when (get-char-property beg 'invisible)
20356 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20357 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20358 (setq result (concat result (buffer-substring beg next)))
20359 (setq beg next)))
20360 (kill-new result)))
20362 (defun org-copy-special ()
20363 "Copy region in table or copy current subtree.
20364 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20365 context. See the individual commands for more information."
20366 (interactive)
20367 (call-interactively
20368 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20370 (defun org-cut-special ()
20371 "Cut region in table or cut current subtree.
20372 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20373 context. See the individual commands for more information."
20374 (interactive)
20375 (call-interactively
20376 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20378 (defun org-paste-special (arg)
20379 "Paste rectangular region into table, or past subtree relative to level.
20380 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20381 See the individual commands for more information."
20382 (interactive "P")
20383 (if (org-at-table-p)
20384 (org-table-paste-rectangle)
20385 (org-paste-subtree arg)))
20387 (defun org-edit-special (&optional arg)
20388 "Call a special editor for the element at point.
20389 When at a table, call the formula editor with `org-table-edit-formulas'.
20390 When in a source code block, call `org-edit-src-code'.
20391 When in a fixed-width region, call `org-edit-fixed-width-region'.
20392 When in an export block, call `org-edit-export-block'.
20393 When in a LaTeX environment, call `org-edit-latex-environment'.
20394 When at an #+INCLUDE keyword, visit the included file.
20395 When at a footnote reference, call `org-edit-footnote-reference'
20396 On a link, call `ffap' to visit the link at point.
20397 Otherwise, return a user error."
20398 (interactive "P")
20399 (let ((element (org-element-at-point)))
20400 (barf-if-buffer-read-only)
20401 (pcase (org-element-type element)
20402 (`src-block
20403 (if (not arg) (org-edit-src-code)
20404 (let* ((info (org-babel-get-src-block-info))
20405 (lang (nth 0 info))
20406 (params (nth 2 info))
20407 (session (cdr (assq :session params))))
20408 (if (not session) (org-edit-src-code)
20409 ;; At a src-block with a session and function called with
20410 ;; an ARG: switch to the buffer related to the inferior
20411 ;; process.
20412 (switch-to-buffer
20413 (funcall (intern (concat "org-babel-prep-session:" lang))
20414 session params))))))
20415 (`keyword
20416 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20417 (org-open-link-from-string
20418 (format "[[%s]]"
20419 (expand-file-name
20420 (let ((value (org-element-property :value element)))
20421 (cond ((org-file-url-p value)
20422 (user-error "The file is specified as a URL, cannot be edited"))
20423 ((not (org-string-nw-p value))
20424 (user-error "No file to edit"))
20425 ((string-match "\\`\"\\(.*?\\)\"" value)
20426 (match-string 1 value))
20427 ((string-match "\\`[^ \t\"]\\S-*" value)
20428 (match-string 0 value))
20429 (t (user-error "No valid file specified")))))))
20430 (user-error "No special environment to edit here")))
20431 (`table
20432 (if (eq (org-element-property :type element) 'table.el)
20433 (org-edit-table.el)
20434 (call-interactively 'org-table-edit-formulas)))
20435 ;; Only Org tables contain `table-row' type elements.
20436 (`table-row (call-interactively 'org-table-edit-formulas))
20437 (`example-block (org-edit-src-code))
20438 (`export-block (org-edit-export-block))
20439 (`fixed-width (org-edit-fixed-width-region))
20440 (`latex-environment (org-edit-latex-environment))
20442 ;; No notable element at point. Though, we may be at a link or
20443 ;; a footnote reference, which are objects. Thus, scan deeper.
20444 (let ((context (org-element-context element)))
20445 (pcase (org-element-type context)
20446 (`footnote-reference (org-edit-footnote-reference))
20447 (`inline-src-block (org-edit-inline-src-code))
20448 (`link (call-interactively #'ffap))
20449 (_ (user-error "No special environment to edit here"))))))))
20451 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20452 (defun org-ctrl-c-ctrl-c (&optional arg)
20453 "Set tags in headline, or update according to changed information at point.
20455 This command does many different things, depending on context:
20457 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20458 this is what we do.
20460 - If the cursor is on a statistics cookie, update it.
20462 - If the cursor is in a headline, prompt for tags and insert them
20463 into the current line, aligned to `org-tags-column'. When called
20464 with prefix arg, realign all tags in the current buffer.
20466 - If the cursor is in one of the special #+KEYWORD lines, this
20467 triggers scanning the buffer for these lines and updating the
20468 information.
20470 - If the cursor is inside a table, realign the table. This command
20471 works even if the automatic table editor has been turned off.
20473 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20474 the entire table.
20476 - If the cursor is at a footnote reference or definition, jump to
20477 the corresponding definition or references, respectively.
20479 - If the cursor is a the beginning of a dynamic block, update it.
20481 - If the current buffer is a capture buffer, close note and file it.
20483 - If the cursor is on a <<<target>>>, update radio targets and
20484 corresponding links in this buffer.
20486 - If the cursor is on a numbered item in a plain list, renumber the
20487 ordered list.
20489 - If the cursor is on a checkbox, toggle it.
20491 - If the cursor is on a code block, evaluate it. The variable
20492 `org-confirm-babel-evaluate' can be used to control prompting
20493 before code block evaluation, by default every code block
20494 evaluation requires confirmation. Code block evaluation can be
20495 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20496 (interactive "P")
20497 (cond
20498 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20499 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20500 (org-remove-occur-highlights)
20501 (message "Temporary highlights/overlays removed from current buffer"))
20502 ((and (local-variable-p 'org-finish-function)
20503 (fboundp org-finish-function))
20504 (funcall org-finish-function))
20505 ((org-babel-hash-at-point))
20506 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20508 (let* ((context
20509 (org-element-lineage
20510 (org-element-context)
20511 ;; Limit to supported contexts.
20512 '(babel-call clock dynamic-block footnote-definition
20513 footnote-reference inline-babel-call inline-src-block
20514 inlinetask item keyword node-property paragraph
20515 plain-list planning property-drawer radio-target
20516 src-block statistics-cookie table table-cell table-row
20517 timestamp)
20519 (type (org-element-type context)))
20520 ;; For convenience: at the first line of a paragraph on the same
20521 ;; line as an item, apply function on that item instead.
20522 (when (eq type 'paragraph)
20523 (let ((parent (org-element-property :parent context)))
20524 (when (and (eq (org-element-type parent) 'item)
20525 (= (line-beginning-position)
20526 (org-element-property :begin parent)))
20527 (setq context parent)
20528 (setq type 'item))))
20529 ;; Act according to type of element or object at point.
20531 ;; Do nothing on a blank line, except if it is contained in
20532 ;; a src block. Hence, we first check if point is in such
20533 ;; a block and then if it is at a blank line.
20534 (pcase type
20535 ((or `inline-src-block `src-block)
20536 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20537 (org-babel-eval-wipe-error-buffer)
20538 (org-babel-execute-src-block
20539 current-prefix-arg (org-babel-get-src-block-info nil context))))
20540 ((guard (org-match-line "[ \t]*$"))
20541 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20542 (user-error
20543 (substitute-command-keys
20544 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20545 ((or `babel-call `inline-babel-call)
20546 (let ((info (org-babel-lob-get-info context)))
20547 (when info (org-babel-execute-src-block nil info))))
20548 (`clock (org-clock-update-time-maybe))
20549 (`dynamic-block
20550 (save-excursion
20551 (goto-char (org-element-property :post-affiliated context))
20552 (org-update-dblock)))
20553 (`footnote-definition
20554 (goto-char (org-element-property :post-affiliated context))
20555 (call-interactively 'org-footnote-action))
20556 (`footnote-reference (call-interactively #'org-footnote-action))
20557 ((or `headline `inlinetask)
20558 (save-excursion (goto-char (org-element-property :begin context))
20559 (call-interactively #'org-set-tags)))
20560 (`item
20561 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20562 ;; unconditionally, whereas `C-u' will toggle its presence.
20563 ;; Without a universal argument, if the item has a checkbox,
20564 ;; toggle it. Otherwise repair the list.
20565 (let* ((box (org-element-property :checkbox context))
20566 (struct (org-element-property :structure context))
20567 (old-struct (copy-tree struct))
20568 (parents (org-list-parents-alist struct))
20569 (prevs (org-list-prevs-alist struct))
20570 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20571 (org-list-set-checkbox
20572 (org-element-property :begin context) struct
20573 (cond ((equal arg '(16)) "[-]")
20574 ((and (not box) (equal arg '(4))) "[ ]")
20575 ((or (not box) (equal arg '(4))) nil)
20576 ((eq box 'on) "[ ]")
20577 (t "[X]")))
20578 ;; Mimic `org-list-write-struct' but with grabbing a return
20579 ;; value from `org-list-struct-fix-box'.
20580 (org-list-struct-fix-ind struct parents 2)
20581 (org-list-struct-fix-item-end struct)
20582 (org-list-struct-fix-bul struct prevs)
20583 (org-list-struct-fix-ind struct parents)
20584 (let ((block-item
20585 (org-list-struct-fix-box struct parents prevs orderedp)))
20586 (if (and box (equal struct old-struct))
20587 (if (equal arg '(16))
20588 (message "Checkboxes already reset")
20589 (user-error "Cannot toggle this checkbox: %s"
20590 (if (eq box 'on)
20591 "all subitems checked"
20592 "unchecked subitems")))
20593 (org-list-struct-apply-struct struct old-struct)
20594 (org-update-checkbox-count-maybe))
20595 (when block-item
20596 (message "Checkboxes were removed due to empty box at line %d"
20597 (org-current-line block-item))))))
20598 (`keyword
20599 (let ((org-inhibit-startup-visibility-stuff t)
20600 (org-startup-align-all-tables nil))
20601 (when (boundp 'org-table-coordinate-overlays)
20602 (mapc #'delete-overlay org-table-coordinate-overlays)
20603 (setq org-table-coordinate-overlays nil))
20604 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20605 (message "Local setup has been refreshed"))
20606 (`plain-list
20607 ;; At a plain list, with a double C-u argument, set
20608 ;; checkboxes of each item to "[-]", whereas a single one
20609 ;; will toggle their presence according to the state of the
20610 ;; first item in the list. Without an argument, repair the
20611 ;; list.
20612 (let* ((begin (org-element-property :contents-begin context))
20613 (beginm (move-marker (make-marker) begin))
20614 (struct (org-element-property :structure context))
20615 (old-struct (copy-tree struct))
20616 (first-box (save-excursion
20617 (goto-char begin)
20618 (looking-at org-list-full-item-re)
20619 (match-string-no-properties 3)))
20620 (new-box (cond ((equal arg '(16)) "[-]")
20621 ((equal arg '(4)) (unless first-box "[ ]"))
20622 ((equal first-box "[X]") "[ ]")
20623 (t "[X]"))))
20624 (cond
20625 (arg
20626 (dolist (pos
20627 (org-list-get-all-items
20628 begin struct (org-list-prevs-alist struct)))
20629 (org-list-set-checkbox pos struct new-box)))
20630 ((and first-box (eq (point) begin))
20631 ;; For convenience, when point is at bol on the first
20632 ;; item of the list and no argument is provided, simply
20633 ;; toggle checkbox of that item, if any.
20634 (org-list-set-checkbox begin struct new-box)))
20635 (org-list-write-struct
20636 struct (org-list-parents-alist struct) old-struct)
20637 (org-update-checkbox-count-maybe)
20638 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20639 ((or `property-drawer `node-property)
20640 (call-interactively #'org-property-action))
20641 (`radio-target
20642 (call-interactively #'org-update-radio-target-regexp))
20643 (`statistics-cookie
20644 (call-interactively #'org-update-statistics-cookies))
20645 ((or `table `table-cell `table-row)
20646 ;; At a table, recalculate every field and align it. Also
20647 ;; send the table if necessary. If the table has
20648 ;; a `table.el' type, just give up. At a table row or cell,
20649 ;; maybe recalculate line but always align table.
20650 (if (eq (org-element-property :type context) 'table.el)
20651 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20652 Use `\\[org-edit-special]' to edit table.el tables"))
20653 (if (or (eq type 'table)
20654 ;; Check if point is at a TBLFM line.
20655 (and (eq type 'table-row)
20656 (= (point) (org-element-property :end context))))
20657 (save-excursion
20658 (if (org-at-TBLFM-p)
20659 (progn (require 'org-table)
20660 (org-table-calc-current-TBLFM))
20661 (goto-char (org-element-property :contents-begin context))
20662 (org-call-with-arg 'org-table-recalculate (or arg t))
20663 (orgtbl-send-table 'maybe)))
20664 (org-table-maybe-eval-formula)
20665 (cond (arg (call-interactively #'org-table-recalculate))
20666 ((org-table-maybe-recalculate-line))
20667 (t (org-table-align))))))
20668 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20669 (org-timestamp-change 0 'day))
20670 ((and `nil (guard (org-at-heading-p)))
20671 ;; When point is on an unsupported object type, we can miss
20672 ;; the fact that it also is at a heading. Handle it here.
20673 (call-interactively #'org-set-tags))
20674 ((guard
20675 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20677 (user-error
20678 (substitute-command-keys
20679 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20681 (defun org-mode-restart ()
20682 (interactive)
20683 (let ((indent-status (bound-and-true-p org-indent-mode)))
20684 (funcall major-mode)
20685 (hack-local-variables)
20686 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20687 (org-indent-mode -1))
20688 (org-reset-file-cache))
20689 (message "%s restarted" major-mode))
20691 (defun org-kill-note-or-show-branches ()
20692 "Abort storing current note, or call `outline-show-branches'."
20693 (interactive)
20694 (if (not org-finish-function)
20695 (progn
20696 (outline-hide-subtree)
20697 (call-interactively 'outline-show-branches))
20698 (let ((org-note-abort t))
20699 (funcall org-finish-function))))
20701 (defun org-delete-indentation (&optional arg)
20702 "Join current line to previous and fix whitespace at join.
20704 If previous line is a headline add to headline title. Otherwise
20705 the function calls `delete-indentation'.
20707 With a non-nil optional argument, join it to the following one."
20708 (interactive "*P")
20709 (if (save-excursion
20710 (beginning-of-line (if arg 1 0))
20711 (let ((case-fold-search nil))
20712 (looking-at org-complex-heading-regexp)))
20713 ;; At headline.
20714 (let ((tags-column (when (match-beginning 5)
20715 (save-excursion (goto-char (match-beginning 5))
20716 (current-column))))
20717 (string (concat " " (progn (when arg (forward-line 1))
20718 (org-trim (delete-and-extract-region
20719 (line-beginning-position)
20720 (line-end-position)))))))
20721 (unless (bobp) (delete-region (point) (1- (point))))
20722 (goto-char (or (match-end 4)
20723 (match-beginning 5)
20724 (match-end 0)))
20725 (skip-chars-backward " \t")
20726 (save-excursion (insert string))
20727 ;; Adjust alignment of tags.
20728 (cond
20729 ((not tags-column)) ;no tags
20730 (org-auto-align-tags (org-set-tags nil t))
20731 (t (org--align-tags-here tags-column)))) ;preserve tags column
20732 (delete-indentation arg)))
20734 (defun org-open-line (n)
20735 "Insert a new row in tables, call `open-line' elsewhere.
20736 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20737 As a special case, when a document starts with a table, allow to
20738 call `open-line' on the very first character."
20739 (interactive "*p")
20740 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20741 (org-table-insert-row)
20742 (open-line n)))
20744 (defun org-return (&optional indent)
20745 "Goto next table row or insert a newline.
20747 Calls `org-table-next-row' or `newline', depending on context.
20749 When optional INDENT argument is non-nil, call
20750 `newline-and-indent' instead of `newline'.
20752 When `org-return-follows-link' is non-nil and point is on
20753 a timestamp or a link, call `org-open-at-point'. However, it
20754 will not happen if point is in a table or on a \"dead\"
20755 object (e.g., within a comment). In these case, you need to use
20756 `org-open-at-point' directly."
20757 (interactive)
20758 (let ((context (if org-return-follows-link (org-element-context)
20759 (org-element-at-point))))
20760 (cond
20761 ;; In a table, call `org-table-next-row'. However, before first
20762 ;; column or after last one, split the table.
20763 ((or (and (eq (org-element-type context) 'table)
20764 (>= (point) (org-element-property :contents-begin context))
20765 (< (point) (org-element-property :contents-end context)))
20766 (org-element-lineage context '(table-row table-cell) t))
20767 (if (or (looking-at-p "[ \t]*$")
20768 (save-excursion (skip-chars-backward " \t") (bolp)))
20769 (insert "\n")
20770 (org-table-justify-field-maybe)
20771 (call-interactively #'org-table-next-row)))
20772 ;; On a link or a timestamp, call `org-open-at-point' if
20773 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20774 ;; locations, e.g., in a comment, as `org-open-at-point'.
20775 ((and org-return-follows-link
20776 (or (org-in-regexp org-ts-regexp-both nil t)
20777 (org-in-regexp org-tsr-regexp-both nil t)
20778 (org-in-regexp org-any-link-re nil t)))
20779 (call-interactively #'org-open-at-point))
20780 ;; Insert newline in heading, but preserve tags.
20781 ((and (not (bolp))
20782 (save-excursion (beginning-of-line)
20783 (let ((case-fold-search nil))
20784 (looking-at org-complex-heading-regexp))))
20785 ;; At headline. Split line. However, if point is on keyword,
20786 ;; priority cookie or tags, do not break any of them: add
20787 ;; a newline after the headline instead.
20788 (let ((tags-column (and (match-beginning 5)
20789 (save-excursion (goto-char (match-beginning 5))
20790 (current-column))))
20791 (string
20792 (when (and (match-end 4) (org-point-in-group (point) 4))
20793 (delete-and-extract-region (point) (match-end 4)))))
20794 ;; Adjust tag alignment.
20795 (cond
20796 ((not (and tags-column string)))
20797 (org-auto-align-tags (org-set-tags nil t))
20798 (t (org--align-tags-here tags-column))) ;preserve tags column
20799 (end-of-line)
20800 (org-show-entry)
20801 (if indent (newline-and-indent) (newline))
20802 (when string (save-excursion (insert (org-trim string))))))
20803 ;; In a list, make sure indenting keeps trailing text within.
20804 ((and indent
20805 (not (eolp))
20806 (org-element-lineage context '(item)))
20807 (let ((trailing-data
20808 (delete-and-extract-region (point) (line-end-position))))
20809 (newline-and-indent)
20810 (save-excursion (insert trailing-data))))
20811 (t (if indent (newline-and-indent) (newline))))))
20813 (defun org-return-indent ()
20814 "Goto next table row or insert a newline and indent.
20815 Calls `org-table-next-row' or `newline-and-indent', depending on
20816 context. See the individual commands for more information."
20817 (interactive)
20818 (org-return t))
20820 (defun org-ctrl-c-tab (&optional _arg)
20821 "Toggle columns width in a table, or show children.
20822 Call `org-table-toggle-column-width' if point is in a table.
20823 Otherwise, call `org-show-children'."
20824 (interactive "p")
20825 (call-interactively
20826 (if (org-at-table-p) #'org-table-toggle-column-width
20827 #'org-show-children)))
20829 (defun org-ctrl-c-star ()
20830 "Compute table, or change heading status of lines.
20831 Calls `org-table-recalculate' or `org-toggle-heading',
20832 depending on context."
20833 (interactive)
20834 (cond
20835 ((org-at-table-p)
20836 (call-interactively 'org-table-recalculate))
20838 ;; Convert all lines in region to list items
20839 (call-interactively 'org-toggle-heading))))
20841 (defun org-ctrl-c-minus ()
20842 "Insert separator line in table or modify bullet status of line.
20843 Also turns a plain line or a region of lines into list items.
20844 Calls `org-table-insert-hline', `org-toggle-item', or
20845 `org-cycle-list-bullet', depending on context."
20846 (interactive)
20847 (cond
20848 ((org-at-table-p)
20849 (call-interactively 'org-table-insert-hline))
20850 ((org-region-active-p)
20851 (call-interactively 'org-toggle-item))
20852 ((org-in-item-p)
20853 (call-interactively 'org-cycle-list-bullet))
20855 (call-interactively 'org-toggle-item))))
20857 (defun org-toggle-heading (&optional nstars)
20858 "Convert headings to normal text, or items or text to headings.
20859 If there is no active region, only convert the current line.
20861 With a `\\[universal-argument]' prefix, convert the whole list at
20862 point into heading.
20864 In a region:
20866 - If the first non blank line is a headline, remove the stars
20867 from all headlines in the region.
20869 - If it is a normal line, turn each and every normal line (i.e.,
20870 not an heading or an item) in the region into headings. If you
20871 want to convert only the first line of this region, use one
20872 universal prefix argument.
20874 - If it is a plain list item, turn all plain list items into headings.
20876 When converting a line into a heading, the number of stars is chosen
20877 such that the lines become children of the current entry. However,
20878 when a numeric prefix argument is given, its value determines the
20879 number of stars to add."
20880 (interactive "P")
20881 (let ((skip-blanks
20882 (function
20883 ;; Return beginning of first non-blank line, starting from
20884 ;; line at POS.
20885 (lambda (pos)
20886 (save-excursion
20887 (goto-char pos)
20888 (while (org-at-comment-p) (forward-line))
20889 (skip-chars-forward " \r\t\n")
20890 (point-at-bol)))))
20891 beg end toggled)
20892 ;; Determine boundaries of changes. If a universal prefix has
20893 ;; been given, put the list in a region. If region ends at a bol,
20894 ;; do not consider the last line to be in the region.
20896 (when (and current-prefix-arg (org-at-item-p))
20897 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20898 (org-mark-element))
20900 (if (org-region-active-p)
20901 (setq beg (funcall skip-blanks (region-beginning))
20902 end (copy-marker (save-excursion
20903 (goto-char (region-end))
20904 (if (bolp) (point) (point-at-eol)))))
20905 (setq beg (funcall skip-blanks (point-at-bol))
20906 end (copy-marker (point-at-eol))))
20907 ;; Ensure inline tasks don't count as headings.
20908 (org-with-limited-levels
20909 (save-excursion
20910 (goto-char beg)
20911 (cond
20912 ;; Case 1. Started at an heading: de-star headings.
20913 ((org-at-heading-p)
20914 (while (< (point) end)
20915 (when (org-at-heading-p t)
20916 (looking-at org-outline-regexp) (replace-match "")
20917 (setq toggled t))
20918 (forward-line)))
20919 ;; Case 2. Started at an item: change items into headlines.
20920 ;; One star will be added by `org-list-to-subtree'.
20921 ((org-at-item-p)
20922 (while (< (point) end)
20923 (when (org-at-item-p)
20924 ;; Pay attention to cases when region ends before list.
20925 (let* ((struct (org-list-struct))
20926 (list-end
20927 (min (org-list-get-bottom-point struct) (1+ end))))
20928 (save-restriction
20929 (narrow-to-region (point) list-end)
20930 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20931 (setq toggled t))
20932 (forward-line)))
20933 ;; Case 3. Started at normal text: make every line an heading,
20934 ;; skipping headlines and items.
20935 (t (let* ((stars
20936 (make-string
20937 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20938 (add-stars
20939 (cond (nstars "") ; stars from prefix only
20940 ((equal stars "") "*") ; before first heading
20941 (org-odd-levels-only "**") ; inside heading, odd
20942 (t "*"))) ; inside heading, oddeven
20943 (rpl (concat stars add-stars " "))
20944 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20945 (while (< (point) (if (equal nstars '(4)) lend end))
20946 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20947 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20948 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20949 (forward-line)))))))
20950 (unless toggled (message "Cannot toggle heading from here"))))
20952 (defun org-meta-return (&optional arg)
20953 "Insert a new heading or wrap a region in a table.
20954 Calls `org-insert-heading', `org-insert-item' or
20955 `org-table-wrap-region', depending on context. When called with
20956 an argument, unconditionally call `org-insert-heading'."
20957 (interactive "P")
20958 (org-check-before-invisible-edit 'insert)
20959 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20960 (call-interactively (cond (arg #'org-insert-heading)
20961 ((org-at-table-p) #'org-table-wrap-region)
20962 ((org-in-item-p) #'org-insert-item)
20963 (t #'org-insert-heading)))))
20965 ;;; Menu entries
20967 (defsubst org-in-subtree-not-table-p ()
20968 "Are we in a subtree and not in a table?"
20969 (and (not (org-before-first-heading-p))
20970 (not (org-at-table-p))))
20972 ;; Define the Org mode menus
20973 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20974 '("Tbl"
20975 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20976 ["Next Field" org-cycle (org-at-table-p)]
20977 ["Previous Field" org-shifttab (org-at-table-p)]
20978 ["Next Row" org-return (org-at-table-p)]
20979 "--"
20980 ["Blank Field" org-table-blank-field (org-at-table-p)]
20981 ["Edit Field" org-table-edit-field (org-at-table-p)]
20982 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20983 "--"
20984 ("Column"
20985 ["Move Column Left" org-metaleft (org-at-table-p)]
20986 ["Move Column Right" org-metaright (org-at-table-p)]
20987 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20988 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20989 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20990 ("Row"
20991 ["Move Row Up" org-metaup (org-at-table-p)]
20992 ["Move Row Down" org-metadown (org-at-table-p)]
20993 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20994 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20995 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20996 "--"
20997 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20998 ("Rectangle"
20999 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21000 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21001 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21002 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21003 "--"
21004 ("Calculate"
21005 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21006 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21007 ["Edit Formulas" org-edit-special (org-at-table-p)]
21008 "--"
21009 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21010 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21011 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21012 "--"
21013 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21014 "--"
21015 ["Sum Column/Rectangle" org-table-sum
21016 (or (org-at-table-p) (org-region-active-p))]
21017 ["Which Column?" org-table-current-column (org-at-table-p)])
21018 ["Debug Formulas"
21019 org-table-toggle-formula-debugger
21020 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21021 ["Show Col/Row Numbers"
21022 org-table-toggle-coordinate-overlays
21023 :style toggle
21024 :selected (bound-and-true-p org-table-overlay-coordinates)]
21025 "--"
21026 ["Create" org-table-create (not (org-at-table-p))]
21027 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21028 ["Import from File" org-table-import (not (org-at-table-p))]
21029 ["Export to File" org-table-export (org-at-table-p)]
21030 "--"
21031 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21032 "--"
21033 ("Plot"
21034 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21035 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21037 (easy-menu-define org-org-menu org-mode-map "Org menu"
21038 '("Org"
21039 ("Show/Hide"
21040 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21041 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21042 ["Sparse Tree..." org-sparse-tree t]
21043 ["Reveal Context" org-reveal t]
21044 ["Show All" outline-show-all t]
21045 "--"
21046 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21047 "--"
21048 ["New Heading" org-insert-heading t]
21049 ("Navigate Headings"
21050 ["Up" outline-up-heading t]
21051 ["Next" outline-next-visible-heading t]
21052 ["Previous" outline-previous-visible-heading t]
21053 ["Next Same Level" outline-forward-same-level t]
21054 ["Previous Same Level" outline-backward-same-level t]
21055 "--"
21056 ["Jump" org-goto t])
21057 ("Edit Structure"
21058 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21059 "--"
21060 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21061 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21062 "--"
21063 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21064 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21065 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21066 "--"
21067 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21068 "--"
21069 ["Copy visible text" org-copy-visible t]
21070 "--"
21071 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21072 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21073 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21074 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21075 "--"
21076 ["Sort Region/Children" org-sort t]
21077 "--"
21078 ["Convert to odd levels" org-convert-to-odd-levels t]
21079 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21080 ("Editing"
21081 ["Emphasis..." org-emphasize t]
21082 ["Edit Source Example" org-edit-special t]
21083 "--"
21084 ["Footnote new/jump" org-footnote-action t]
21085 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21086 ("Archive"
21087 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21088 "--"
21089 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21090 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21091 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21093 "--"
21094 ("Hyperlinks"
21095 ["Store Link (Global)" org-store-link t]
21096 ["Find existing link to here" org-occur-link-in-agenda-files t]
21097 ["Insert Link" org-insert-link t]
21098 ["Follow Link" org-open-at-point t]
21099 "--"
21100 ["Next link" org-next-link t]
21101 ["Previous link" org-previous-link t]
21102 "--"
21103 ["Descriptive Links"
21104 org-toggle-link-display
21105 :style radio
21106 :selected org-descriptive-links
21108 ["Literal Links"
21109 org-toggle-link-display
21110 :style radio
21111 :selected (not org-descriptive-links)])
21112 "--"
21113 ("TODO Lists"
21114 ["TODO/DONE/-" org-todo t]
21115 ("Select keyword"
21116 ["Next keyword" org-shiftright (org-at-heading-p)]
21117 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21118 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21119 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21120 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21121 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21122 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21123 "--"
21124 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21125 :selected org-enforce-todo-dependencies :style toggle :active t]
21126 "Settings for tree at point"
21127 ["Do Children sequentially" org-toggle-ordered-property :style radio
21128 :selected (org-entry-get nil "ORDERED")
21129 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21130 ["Do Children parallel" org-toggle-ordered-property :style radio
21131 :selected (not (org-entry-get nil "ORDERED"))
21132 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21133 "--"
21134 ["Set Priority" org-priority t]
21135 ["Priority Up" org-shiftup t]
21136 ["Priority Down" org-shiftdown t]
21137 "--"
21138 ["Get news from all feeds" org-feed-update-all t]
21139 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21140 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21141 ("TAGS and Properties"
21142 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21143 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21144 "--"
21145 ["Set property" org-set-property (not (org-before-first-heading-p))]
21146 ["Column view of properties" org-columns t]
21147 ["Insert Column View DBlock" org-columns-insert-dblock t])
21148 ("Dates and Scheduling"
21149 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21150 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21151 ("Change Date"
21152 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21153 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21154 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21155 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21156 ["Compute Time Range" org-evaluate-time-range t]
21157 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21158 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21159 "--"
21160 ["Custom time format" org-toggle-time-stamp-overlays
21161 :style radio :selected org-display-custom-times]
21162 "--"
21163 ["Goto Calendar" org-goto-calendar t]
21164 ["Date from Calendar" org-date-from-calendar t]
21165 "--"
21166 ["Start/Restart Timer" org-timer-start t]
21167 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21168 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21169 ["Insert Timer String" org-timer t]
21170 ["Insert Timer Item" org-timer-item t])
21171 ("Logging work"
21172 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21173 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21174 ["Clock out" org-clock-out t]
21175 ["Clock cancel" org-clock-cancel t]
21176 "--"
21177 ["Mark as default task" org-clock-mark-default-task t]
21178 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21179 ["Goto running clock" org-clock-goto t]
21180 "--"
21181 ["Display times" org-clock-display t]
21182 ["Create clock table" org-clock-report t]
21183 "--"
21184 ["Record DONE time"
21185 (progn (setq org-log-done (not org-log-done))
21186 (message "Switching to %s will %s record a timestamp"
21187 (car org-done-keywords)
21188 (if org-log-done "automatically" "not")))
21189 :style toggle :selected org-log-done])
21190 "--"
21191 ["Agenda Command..." org-agenda t]
21192 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21193 ("File List for Agenda")
21194 ("Special views current file"
21195 ["TODO Tree" org-show-todo-tree t]
21196 ["Check Deadlines" org-check-deadlines t]
21197 ["Tags/Property tree" org-match-sparse-tree t])
21198 "--"
21199 ["Export/Publish..." org-export-dispatch t]
21200 ("LaTeX"
21201 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21202 :style toggle :selected org-cdlatex-mode]
21203 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21204 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21205 ["Modify math symbol" org-cdlatex-math-modify
21206 (org-inside-LaTeX-fragment-p)]
21207 ["Insert citation" org-reftex-citation t])
21208 "--"
21209 ("MobileOrg"
21210 ["Push Files and Views" org-mobile-push t]
21211 ["Get Captured and Flagged" org-mobile-pull t]
21212 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21213 "--"
21214 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21215 "--"
21216 ("Documentation"
21217 ["Show Version" org-version t]
21218 ["Info Documentation" org-info t])
21219 ("Customize"
21220 ["Browse Org Group" org-customize t]
21221 "--"
21222 ["Expand This Menu" org-create-customize-menu
21223 (fboundp 'customize-menu-create)])
21224 ["Send bug report" org-submit-bug-report t]
21225 "--"
21226 ("Refresh/Reload"
21227 ["Refresh setup current buffer" org-mode-restart t]
21228 ["Reload Org (after update)" org-reload t]
21229 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21232 (defun org-info (&optional node)
21233 "Read documentation for Org in the info system.
21234 With optional NODE, go directly to that node."
21235 (interactive)
21236 (info (format "(org)%s" (or node ""))))
21238 ;;;###autoload
21239 (defun org-submit-bug-report ()
21240 "Submit a bug report on Org via mail.
21242 Don't hesitate to report any problems or inaccurate documentation.
21244 If you don't have setup sending mail from (X)Emacs, please copy the
21245 output buffer into your mail program, as it gives us important
21246 information about your Org version and configuration."
21247 (interactive)
21248 (require 'reporter)
21249 (defvar reporter-prompt-for-summary-p)
21250 (org-load-modules-maybe)
21251 (org-require-autoloaded-modules)
21252 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21253 (reporter-submit-bug-report
21254 "emacs-orgmode@gnu.org"
21255 (org-version nil 'full)
21256 (let (list)
21257 (save-window-excursion
21258 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21259 (delete-other-windows)
21260 (erase-buffer)
21261 (insert "You are about to submit a bug report to the Org mailing list.
21263 We would like to add your full Org and Outline configuration to the
21264 bug report. This greatly simplifies the work of the maintainer and
21265 other experts on the mailing list.
21267 HOWEVER, some variables you have customized may contain private
21268 information. The names of customers, colleagues, or friends, might
21269 appear in the form of file names, tags, todo states, or search strings.
21270 If you answer yes to the prompt, you might want to check and remove
21271 such private information before sending the email.")
21272 (add-text-properties (point-min) (point-max) '(face org-warning))
21273 (when (yes-or-no-p "Include your Org configuration ")
21274 (mapatoms
21275 (lambda (v)
21276 (and (boundp v)
21277 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21278 (or (and (symbol-value v)
21279 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21280 (and
21281 (get v 'custom-type) (get v 'standard-value)
21282 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21283 (push v list)))))
21284 (kill-buffer (get-buffer "*Warn about privacy*"))
21285 list))
21286 nil nil
21287 "Remember to cover the basics, that is, what you expected to happen and
21288 what in fact did happen. You don't know how to make a good report? See
21290 http://orgmode.org/manual/Feedback.html#Feedback
21292 Your bug report will be posted to the Org mailing list.
21293 ------------------------------------------------------------------------")
21294 (save-excursion
21295 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21296 (replace-match "\\1Bug: \\3 [\\2]")))))
21299 (defun org-install-agenda-files-menu ()
21300 (let ((bl (buffer-list)))
21301 (save-excursion
21302 (while bl
21303 (set-buffer (pop bl))
21304 (when (derived-mode-p 'org-mode) (setq bl nil)))
21305 (when (derived-mode-p 'org-mode)
21306 (easy-menu-change
21307 '("Org") "File List for Agenda"
21308 (append
21309 (list
21310 ["Edit File List" (org-edit-agenda-file-list) t]
21311 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21312 ["Remove Current File from List" org-remove-file t]
21313 ["Cycle through agenda files" org-cycle-agenda-files t]
21314 ["Occur in all agenda files" org-occur-in-agenda-files t]
21315 "--")
21316 (mapcar 'org-file-menu-entry
21317 ;; Prevent initialization from failing.
21318 (ignore-errors (org-agenda-files t)))))))))
21320 ;;;; Documentation
21322 (defun org-require-autoloaded-modules ()
21323 (interactive)
21324 (mapc #'require
21325 '(org-agenda org-archive org-attach org-clock org-colview org-id
21326 org-table org-timer)))
21328 ;;;###autoload
21329 (defun org-reload (&optional uncompiled)
21330 "Reload all org lisp files.
21331 With prefix arg UNCOMPILED, load the uncompiled versions."
21332 (interactive "P")
21333 (require 'loadhist)
21334 (let* ((org-dir (org-find-library-dir "org"))
21335 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21336 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21337 (remove-re (format "\\`%s\\'"
21338 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21339 (feats (delete-dups
21340 (mapcar 'file-name-sans-extension
21341 (mapcar 'file-name-nondirectory
21342 (delq nil
21343 (mapcar 'feature-file
21344 features))))))
21345 (lfeat (append
21346 (sort
21347 (setq feats
21348 (delq nil (mapcar
21349 (lambda (f)
21350 (if (and (string-match feature-re f)
21351 (not (string-match remove-re f)))
21352 f nil))
21353 feats)))
21354 'string-lessp)
21355 (list "org-version" "org")))
21356 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21357 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21358 load-uncore load-misses)
21359 (setq load-misses
21360 (delq 't
21361 (mapcar (lambda (f)
21362 (or (org-load-noerror-mustsuffix (concat org-dir f))
21363 (and (string= org-dir contrib-dir)
21364 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21365 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21366 (add-to-list 'load-uncore f 'append)
21369 lfeat)))
21370 (when load-uncore
21371 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21372 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21373 (if load-misses
21374 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21375 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21376 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21378 ;;;###autoload
21379 (defun org-customize ()
21380 "Call the customize function with org as argument."
21381 (interactive)
21382 (org-load-modules-maybe)
21383 (org-require-autoloaded-modules)
21384 (customize-browse 'org))
21386 (defun org-create-customize-menu ()
21387 "Create a full customization menu for Org mode, insert it into the menu."
21388 (interactive)
21389 (org-load-modules-maybe)
21390 (org-require-autoloaded-modules)
21391 (if (fboundp 'customize-menu-create)
21392 (progn
21393 (easy-menu-change
21394 '("Org") "Customize"
21395 `(["Browse Org group" org-customize t]
21396 "--"
21397 ,(customize-menu-create 'org)
21398 ["Set" Custom-set t]
21399 ["Save" Custom-save t]
21400 ["Reset to Current" Custom-reset-current t]
21401 ["Reset to Saved" Custom-reset-saved t]
21402 ["Reset to Standard Settings" Custom-reset-standard t]))
21403 (message "\"Org\"-menu now contains full customization menu"))
21404 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21406 ;;;; Miscellaneous stuff
21408 ;;; Generally useful functions
21410 (defun org-link-display-format (s)
21411 "Replace links in string S with their description.
21412 If there is no description, use the link target."
21413 (save-match-data
21414 (replace-regexp-in-string
21415 org-bracket-link-analytic-regexp
21416 (lambda (m)
21417 (if (match-end 5) (match-string 5 m)
21418 (concat (match-string 1 m) (match-string 3 m))))
21419 s nil t)))
21421 (defun org-toggle-link-display ()
21422 "Toggle the literal or descriptive display of links."
21423 (interactive)
21424 (if org-descriptive-links
21425 (progn (org-remove-from-invisibility-spec '(org-link))
21426 (org-restart-font-lock)
21427 (setq org-descriptive-links nil))
21428 (progn (add-to-invisibility-spec '(org-link))
21429 (org-restart-font-lock)
21430 (setq org-descriptive-links t))))
21432 (defun org-in-clocktable-p ()
21433 "Check if the cursor is in a clocktable."
21434 (let ((pos (point)) start)
21435 (save-excursion
21436 (end-of-line 1)
21437 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21438 (setq start (match-beginning 0))
21439 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21440 (>= (match-end 0) pos)
21441 start))))
21443 (defun org-in-verbatim-emphasis ()
21444 (save-match-data
21445 (and (org-in-regexp org-verbatim-re 2)
21446 (>= (point) (match-beginning 3))
21447 (<= (point) (match-end 4)))))
21449 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21450 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21451 (if (and marker (marker-buffer marker)
21452 (buffer-live-p (marker-buffer marker)))
21453 (progn
21454 (pop-to-buffer-same-window (marker-buffer marker))
21455 (when (or (> marker (point-max)) (< marker (point-min)))
21456 (widen))
21457 (goto-char marker)
21458 (org-show-context 'org-goto))
21459 (if bookmark
21460 (bookmark-jump bookmark)
21461 (error "Cannot find location"))))
21463 (defun org-quote-csv-field (s)
21464 "Quote field for inclusion in CSV material."
21465 (if (string-match "[\",]" s)
21466 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21469 (defun org-force-self-insert (N)
21470 "Needed to enforce self-insert under remapping."
21471 (interactive "p")
21472 (self-insert-command N))
21474 (defun org-get-indentation (&optional line)
21475 "Get the indentation of the current line, interpreting tabs.
21476 When LINE is given, assume it represents a line and compute its indentation."
21477 (if line
21478 (when (string-match "^ *" (org-remove-tabs line))
21479 (match-end 0))
21480 (save-excursion
21481 (beginning-of-line 1)
21482 (skip-chars-forward " \t")
21483 (current-column))))
21485 (defun org-get-string-indentation (s)
21486 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21487 (let ((n -1) (i 0) (w tab-width) c)
21488 (catch 'exit
21489 (while (< (setq n (1+ n)) (length s))
21490 (setq c (aref s n))
21491 (cond ((= c ?\ ) (setq i (1+ i)))
21492 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21493 (t (throw 'exit t)))))
21496 (defun org-fix-indentation (line ind)
21497 "Fix indentation in LINE.
21498 IND is a cons cell with target and minimum indentation.
21499 If the current indentation in LINE is smaller than the minimum,
21500 leave it alone. If it is larger than ind, set it to the target."
21501 (let* ((l (org-remove-tabs line))
21502 (i (org-get-indentation l))
21503 (i1 (car ind)) (i2 (cdr ind)))
21504 (when (>= i i2) (setq l (substring line i2)))
21505 (if (> i1 0)
21506 (concat (make-string i1 ?\ ) l)
21507 l)))
21509 (defun org-fill-template (template alist)
21510 "Find each %key of ALIST in TEMPLATE and replace it."
21511 (let ((case-fold-search nil))
21512 (dolist (entry (sort (copy-sequence alist)
21513 (lambda (a b) (< (length (car a)) (length (car b))))))
21514 (setq template
21515 (replace-regexp-in-string
21516 (concat "%" (regexp-quote (car entry)))
21517 (or (cdr entry) "") template t t)))
21518 template))
21520 (defun org-quote-vert (s)
21521 "Replace \"|\" with \"\\vert\"."
21522 (while (string-match "|" s)
21523 (setq s (replace-match "\\vert" t t s)))
21526 (defun org-uuidgen-p (s)
21527 "Is S an ID created by UUIDGEN?"
21528 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21530 (defun org-in-src-block-p (&optional inside)
21531 "Whether point is in a code source block.
21532 When INSIDE is non-nil, don't consider we are within a src block
21533 when point is at #+BEGIN_SRC or #+END_SRC."
21534 (let ((case-fold-search t))
21535 (or (and (eq (get-char-property (point) 'src-block) t))
21536 (and (not inside)
21537 (save-match-data
21538 (save-excursion
21539 (beginning-of-line)
21540 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21542 (defun org-context ()
21543 "Return a list of contexts of the current cursor position.
21544 If several contexts apply, all are returned.
21545 Each context entry is a list with a symbol naming the context, and
21546 two positions indicating start and end of the context. Possible
21547 contexts are:
21549 :headline anywhere in a headline
21550 :headline-stars on the leading stars in a headline
21551 :todo-keyword on a TODO keyword (including DONE) in a headline
21552 :tags on the TAGS in a headline
21553 :priority on the priority cookie in a headline
21554 :item on the first line of a plain list item
21555 :item-bullet on the bullet/number of a plain list item
21556 :checkbox on the checkbox in a plain list item
21557 :table in an Org table
21558 :table-special on a special filed in a table
21559 :table-table in a table.el table
21560 :clocktable in a clocktable
21561 :src-block in a source block
21562 :link on a hyperlink
21563 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21564 :target on a <<target>>
21565 :radio-target on a <<<radio-target>>>
21566 :latex-fragment on a LaTeX fragment
21567 :latex-preview on a LaTeX fragment with overlaid preview image
21569 This function expects the position to be visible because it uses font-lock
21570 faces as a help to recognize the following contexts: :table-special, :link,
21571 and :keyword."
21572 (let* ((f (get-text-property (point) 'face))
21573 (faces (if (listp f) f (list f)))
21574 (case-fold-search t)
21575 (p (point)) clist o)
21576 ;; First the large context
21577 (cond
21578 ((org-at-heading-p t)
21579 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21580 (when (progn
21581 (beginning-of-line 1)
21582 (looking-at org-todo-line-tags-regexp))
21583 (push (org-point-in-group p 1 :headline-stars) clist)
21584 (push (org-point-in-group p 2 :todo-keyword) clist)
21585 (push (org-point-in-group p 4 :tags) clist))
21586 (goto-char p)
21587 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21588 (when (looking-at "\\[#[A-Z0-9]\\]")
21589 (push (org-point-in-group p 0 :priority) clist)))
21591 ((org-at-item-p)
21592 (push (org-point-in-group p 2 :item-bullet) clist)
21593 (push (list :item (point-at-bol)
21594 (save-excursion (org-end-of-item) (point)))
21595 clist)
21596 (and (org-at-item-checkbox-p)
21597 (push (org-point-in-group p 0 :checkbox) clist)))
21599 ((org-at-table-p)
21600 (push (list :table (org-table-begin) (org-table-end)) clist)
21601 (when (memq 'org-formula faces)
21602 (push (list :table-special
21603 (previous-single-property-change p 'face)
21604 (next-single-property-change p 'face)) clist)))
21605 ((org-at-table-p 'any)
21606 (push (list :table-table) clist)))
21607 (goto-char p)
21609 (let ((case-fold-search t))
21610 ;; New the "medium" contexts: clocktables, source blocks
21611 (cond ((org-in-clocktable-p)
21612 (push (list :clocktable
21613 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21614 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21615 (match-beginning 1))
21616 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21617 (match-end 0))) clist))
21618 ((org-in-src-block-p)
21619 (push (list :src-block
21620 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21621 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21622 (match-beginning 1))
21623 (and (search-forward "#+END_SRC" nil t)
21624 (match-beginning 0))) clist))))
21625 (goto-char p)
21627 ;; Now the small context
21628 (cond
21629 ((org-at-timestamp-p)
21630 (push (org-point-in-group p 0 :timestamp) clist))
21631 ((memq 'org-link faces)
21632 (push (list :link
21633 (previous-single-property-change p 'face)
21634 (next-single-property-change p 'face)) clist))
21635 ((memq 'org-special-keyword faces)
21636 (push (list :keyword
21637 (previous-single-property-change p 'face)
21638 (next-single-property-change p 'face)) clist))
21639 ((org-at-target-p)
21640 (push (org-point-in-group p 0 :target) clist)
21641 (goto-char (1- (match-beginning 0)))
21642 (when (looking-at org-radio-target-regexp)
21643 (push (org-point-in-group p 0 :radio-target) clist))
21644 (goto-char p))
21645 ((setq o (cl-some
21646 (lambda (o)
21647 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21649 (overlays-at (point))))
21650 (push (list :latex-fragment
21651 (overlay-start o) (overlay-end o)) clist)
21652 (push (list :latex-preview
21653 (overlay-start o) (overlay-end o)) clist))
21654 ((org-inside-LaTeX-fragment-p)
21655 ;; FIXME: positions wrong.
21656 (push (list :latex-fragment (point) (point)) clist)))
21658 (setq clist (nreverse (delq nil clist)))
21659 clist))
21661 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21662 "Non-nil when point is between matches of START-RE and END-RE.
21664 Also return a non-nil value when point is on one of the matches.
21666 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21667 buffer positions. Default values are the positions of headlines
21668 surrounding the point.
21670 The functions returns a cons cell whose car (resp. cdr) is the
21671 position before START-RE (resp. after END-RE)."
21672 (save-match-data
21673 (let ((pos (point))
21674 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21675 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21676 beg end)
21677 (save-excursion
21678 ;; Point is on a block when on START-RE or if START-RE can be
21679 ;; found before it...
21680 (and (or (org-in-regexp start-re)
21681 (re-search-backward start-re limit-up t))
21682 (setq beg (match-beginning 0))
21683 ;; ... and END-RE after it...
21684 (goto-char (match-end 0))
21685 (re-search-forward end-re limit-down t)
21686 (> (setq end (match-end 0)) pos)
21687 ;; ... without another START-RE in-between.
21688 (goto-char (match-beginning 0))
21689 (not (re-search-backward start-re (1+ beg) t))
21690 ;; Return value.
21691 (cons beg end))))))
21693 (defun org-in-block-p (names)
21694 "Non-nil when point belongs to a block whose name belongs to NAMES.
21696 NAMES is a list of strings containing names of blocks.
21698 Return first block name matched, or nil. Beware that in case of
21699 nested blocks, the returned name may not belong to the closest
21700 block from point."
21701 (save-match-data
21702 (catch 'exit
21703 (let ((case-fold-search t)
21704 (lim-up (save-excursion (outline-previous-heading)))
21705 (lim-down (save-excursion (outline-next-heading))))
21706 (dolist (name names)
21707 (let ((n (regexp-quote name)))
21708 (when (org-between-regexps-p
21709 (concat "^[ \t]*#\\+begin_" n)
21710 (concat "^[ \t]*#\\+end_" n)
21711 lim-up lim-down)
21712 (throw 'exit n)))))
21713 nil)))
21715 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21716 "Call `multi-occur' with buffers for all agenda files."
21717 (interactive "sOrg-files matching: ")
21718 (let* ((files (org-agenda-files))
21719 (tnames (mapcar #'file-truename files))
21720 (extra org-agenda-text-search-extra-files))
21721 (when (eq (car extra) 'agenda-archives)
21722 (setq extra (cdr extra))
21723 (setq files (org-add-archive-files files)))
21724 (dolist (f extra)
21725 (unless (member (file-truename f) tnames)
21726 (unless (member f files) (setq files (append files (list f))))
21727 (setq tnames (append tnames (list (file-truename f))))))
21728 (multi-occur
21729 (mapcar (lambda (x)
21730 (with-current-buffer
21731 ;; FIXME: Why not just (find-file-noselect x)?
21732 ;; Is it to avoid the "revert buffer" prompt?
21733 (or (get-file-buffer x) (find-file-noselect x))
21734 (widen)
21735 (current-buffer)))
21736 files)
21737 regexp)))
21739 (add-hook 'occur-mode-find-occurrence-hook
21740 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21742 (defun org-occur-link-in-agenda-files ()
21743 "Create a link and search for it in the agendas.
21744 The link is not stored in `org-stored-links', it is just created
21745 for the search purpose."
21746 (interactive)
21747 (let ((link (condition-case nil
21748 (org-store-link nil)
21749 (error "Unable to create a link to here"))))
21750 (org-occur-in-agenda-files (regexp-quote link))))
21752 (defun org-back-over-empty-lines ()
21753 "Move backwards over whitespace, to the beginning of the first empty line.
21754 Returns the number of empty lines passed."
21755 (let ((pos (point)))
21756 (if (cdr (assq 'heading org-blank-before-new-entry))
21757 (skip-chars-backward " \t\n\r")
21758 (unless (eobp)
21759 (forward-line -1)))
21760 (beginning-of-line 2)
21761 (goto-char (min (point) pos))
21762 (count-lines (point) pos)))
21764 (defun org-switch-to-buffer-other-window (&rest args)
21765 "Switch to buffer in a second window on the current frame.
21766 In particular, do not allow pop-up frames.
21767 Returns the newly created buffer."
21768 (org-no-popups
21769 (apply 'switch-to-buffer-other-window args)))
21771 (defun org-replace-escapes (string table)
21772 "Replace %-escapes in STRING with values in TABLE.
21773 TABLE is an association list with keys like \"%a\" and string values.
21774 The sequences in STRING may contain normal field width and padding information,
21775 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21776 so values can contain further %-escapes if they are define later in TABLE."
21777 (let ((tbl (copy-alist table))
21778 (case-fold-search nil)
21779 (pchg 0)
21780 re rpl)
21781 (dolist (e tbl)
21782 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21783 (when (and (cdr e) (string-match re (cdr e)))
21784 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21785 (safe "SREF"))
21786 (add-text-properties 0 3 (list 'sref sref) safe)
21787 (setcdr e (replace-match safe t t (cdr e)))))
21788 (while (string-match re string)
21789 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21790 (cdr e)))
21791 (setq string (replace-match rpl t t string))))
21792 (while (setq pchg (next-property-change pchg string))
21793 (let ((sref (get-text-property pchg 'sref string)))
21794 (when (and sref (string-match "SREF" string pchg))
21795 (setq string (replace-match sref t t string)))))
21796 string))
21798 ;;; TODO: Only called once, from ox-odt which should probably use
21799 ;;; org-export-inline-image-p or something.
21800 (defun org-file-image-p (file)
21801 "Return non-nil if FILE is an image."
21802 (save-match-data
21803 (string-match (image-file-name-regexp) file)))
21805 (defun org-get-cursor-date (&optional with-time)
21806 "Return the date at cursor in as a time.
21807 This works in the calendar and in the agenda, anywhere else it just
21808 returns the current time.
21809 If WITH-TIME is non-nil, returns the time of the event at point (in
21810 the agenda) or the current time of the day."
21811 (let (date day defd tp hod mod)
21812 (when with-time
21813 (setq tp (get-text-property (point) 'time))
21814 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21815 (setq hod (string-to-number (match-string 1 tp))
21816 mod (string-to-number (match-string 2 tp))))
21817 (or tp (let ((now (decode-time)))
21818 (setq hod (nth 2 now)
21819 mod (nth 1 now)))))
21820 (cond
21821 ((eq major-mode 'calendar-mode)
21822 (setq date (calendar-cursor-to-date)
21823 defd (encode-time 0 (or mod 0) (or hod 0)
21824 (nth 1 date) (nth 0 date) (nth 2 date))))
21825 ((eq major-mode 'org-agenda-mode)
21826 (setq day (get-text-property (point) 'day))
21827 (when day
21828 (setq date (calendar-gregorian-from-absolute day)
21829 defd (encode-time 0 (or mod 0) (or hod 0)
21830 (nth 1 date) (nth 0 date) (nth 2 date))))))
21831 (or defd (current-time))))
21833 (defun org-mark-subtree (&optional up)
21834 "Mark the current subtree.
21835 This puts point at the start of the current subtree, and mark at
21836 the end. If a numeric prefix UP is given, move up into the
21837 hierarchy of headlines by UP levels before marking the subtree."
21838 (interactive "P")
21839 (org-with-limited-levels
21840 (cond ((org-at-heading-p) (beginning-of-line))
21841 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21842 (t (outline-previous-visible-heading 1))))
21843 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21844 (if (called-interactively-p 'any)
21845 (call-interactively 'org-mark-element)
21846 (org-mark-element)))
21848 (defun org-file-newer-than-p (file time)
21849 "Non-nil if FILE is newer than TIME.
21850 FILE is a filename, as a string, TIME is a list of integers, as
21851 returned by, e.g., `current-time'."
21852 (and (file-exists-p file)
21853 ;; Only compare times up to whole seconds as some file-systems
21854 ;; (e.g. HFS+) do not retain any finer granularity. As
21855 ;; a consequence, make sure we return non-nil when the two
21856 ;; times are equal.
21857 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21858 (cl-subseq time 0 2)))))
21860 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21861 "Compile a SOURCE file using PROCESS.
21863 PROCESS is either a function or a list of shell commands, as
21864 strings. EXT is a file extension, without the leading dot, as
21865 a string. It is used to check if the process actually succeeded.
21867 PROCESS must create a file with the same base name and directory
21868 as SOURCE, but ending with EXT. The function then returns its
21869 filename. Otherwise, it raises an error. The error message can
21870 then be refined by providing string ERR-MSG, which is appended to
21871 the standard message.
21873 If PROCESS is a function, it is called with a single argument:
21874 the SOURCE file.
21876 If it is a list of commands, each of them is called using
21877 `shell-command'. By default, in each command, %b, %f, %F, %o and
21878 %O are replaced with, respectively, SOURCE base name, name, full
21879 name, directory and absolute output file name. It is possible,
21880 however, to use more place-holders by specifying them in optional
21881 argument SPEC, as an alist following the pattern
21883 (CHARACTER . REPLACEMENT-STRING).
21885 When PROCESS is a list of commands, optional argument LOG-BUF can
21886 be set to a buffer or a buffer name. `shell-command' then uses
21887 it for output."
21888 (let* ((base-name (file-name-base source))
21889 (full-name (file-truename source))
21890 (out-dir (or (file-name-directory source) "./"))
21891 (output (expand-file-name (concat base-name "." ext) out-dir))
21892 (time (current-time))
21893 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21894 (save-window-excursion
21895 (pcase process
21896 ((pred functionp) (funcall process (shell-quote-argument source)))
21897 ((pred consp)
21898 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21899 (spec (append spec
21900 `((?b . ,(shell-quote-argument base-name))
21901 (?f . ,(shell-quote-argument source))
21902 (?F . ,(shell-quote-argument full-name))
21903 (?o . ,(shell-quote-argument out-dir))
21904 (?O . ,(shell-quote-argument output))))))
21905 (dolist (command process)
21906 (shell-command (format-spec command spec) log-buf))
21907 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21908 (_ (error "No valid command to process %S%s" source err-msg))))
21909 ;; Check for process failure. Output file is expected to be
21910 ;; located in the same directory as SOURCE.
21911 (unless (org-file-newer-than-p output time)
21912 (error (format "File %S wasn't produced%s" output err-msg)))
21913 output))
21915 ;;; Indentation
21917 (defvar org-element-greater-elements)
21918 (defun org--get-expected-indentation (element contentsp)
21919 "Expected indentation column for current line, according to ELEMENT.
21920 ELEMENT is an element containing point. CONTENTSP is non-nil
21921 when indentation is to be computed according to contents of
21922 ELEMENT."
21923 (let ((type (org-element-type element))
21924 (start (org-element-property :begin element))
21925 (post-affiliated (org-element-property :post-affiliated element)))
21926 (org-with-wide-buffer
21927 (cond
21928 (contentsp
21929 (cl-case type
21930 ((diary-sexp footnote-definition) 0)
21931 ((headline inlinetask nil)
21932 (if (not org-adapt-indentation) 0
21933 (let ((level (org-current-level)))
21934 (if level (1+ level) 0))))
21935 ((item plain-list) (org-list-item-body-column post-affiliated))
21937 (goto-char start)
21938 (org-get-indentation))))
21939 ((memq type '(headline inlinetask nil))
21940 (if (org-match-line "[ \t]*$")
21941 (org--get-expected-indentation element t)
21943 ((memq type '(diary-sexp footnote-definition)) 0)
21944 ;; First paragraph of a footnote definition or an item.
21945 ;; Indent like parent.
21946 ((< (line-beginning-position) start)
21947 (org--get-expected-indentation
21948 (org-element-property :parent element) t))
21949 ;; At first line: indent according to previous sibling, if any,
21950 ;; ignoring footnote definitions and inline tasks, or parent's
21951 ;; contents.
21952 ((= (line-beginning-position) start)
21953 (catch 'exit
21954 (while t
21955 (if (= (point-min) start) (throw 'exit 0)
21956 (goto-char (1- start))
21957 (let* ((previous (org-element-at-point))
21958 (parent previous))
21959 (while (and parent (<= (org-element-property :end parent) start))
21960 (setq previous parent
21961 parent (org-element-property :parent parent)))
21962 (cond
21963 ((not previous) (throw 'exit 0))
21964 ((> (org-element-property :end previous) start)
21965 (throw 'exit (org--get-expected-indentation previous t)))
21966 ((memq (org-element-type previous)
21967 '(footnote-definition inlinetask))
21968 (setq start (org-element-property :begin previous)))
21969 (t (goto-char (org-element-property :begin previous))
21970 (throw 'exit
21971 (if (bolp) (org-get-indentation)
21972 ;; At first paragraph in an item or
21973 ;; a footnote definition.
21974 (org--get-expected-indentation
21975 (org-element-property :parent previous) t))))))))))
21976 ;; Otherwise, move to the first non-blank line above.
21978 (beginning-of-line)
21979 (let ((pos (point)))
21980 (skip-chars-backward " \r\t\n")
21981 (cond
21982 ;; Two blank lines end a footnote definition or a plain
21983 ;; list. When we indent an empty line after them, the
21984 ;; containing list or footnote definition is over, so it
21985 ;; qualifies as a previous sibling. Therefore, we indent
21986 ;; like its first line.
21987 ((and (memq type '(footnote-definition plain-list))
21988 (> (count-lines (point) pos) 2))
21989 (goto-char start)
21990 (org-get-indentation))
21991 ;; Line above is the first one of a paragraph at the
21992 ;; beginning of an item or a footnote definition. Indent
21993 ;; like parent.
21994 ((< (line-beginning-position) start)
21995 (org--get-expected-indentation
21996 (org-element-property :parent element) t))
21997 ;; Line above is the beginning of an element, i.e., point
21998 ;; was originally on the blank lines between element's start
21999 ;; and contents.
22000 ((= (line-beginning-position) post-affiliated)
22001 (org--get-expected-indentation element t))
22002 ;; POS is after contents in a greater element. Indent like
22003 ;; the beginning of the element.
22004 ((and (memq type org-element-greater-elements)
22005 (let ((cend (org-element-property :contents-end element)))
22006 (and cend (<= cend pos))))
22007 ;; As a special case, if point is at the end of a footnote
22008 ;; definition or an item, indent like the very last element
22009 ;; within. If that last element is an item, indent like
22010 ;; its contents.
22011 (if (memq type '(footnote-definition item plain-list))
22012 (let ((last (org-element-at-point)))
22013 (goto-char pos)
22014 (org--get-expected-indentation
22015 last (eq (org-element-type last) 'item)))
22016 (goto-char start)
22017 (org-get-indentation)))
22018 ;; In any other case, indent like the current line.
22019 (t (org-get-indentation)))))))))
22021 (defun org--align-node-property ()
22022 "Align node property at point.
22023 Alignment is done according to `org-property-format', which see."
22024 (when (save-excursion
22025 (beginning-of-line)
22026 (looking-at org-property-re))
22027 (replace-match
22028 (concat (match-string 4)
22029 (org-trim
22030 (format org-property-format (match-string 1) (match-string 3))))
22031 t t)))
22033 (defun org-indent-line ()
22034 "Indent line depending on context.
22036 Indentation is done according to the following rules:
22038 - Footnote definitions, diary sexps, headlines and inline tasks
22039 have to start at column 0.
22041 - On the very first line of an element, consider, in order, the
22042 next rules until one matches:
22044 1. If there's a sibling element before, ignoring footnote
22045 definitions and inline tasks, indent like its first line.
22047 2. If element has a parent, indent like its contents. More
22048 precisely, if parent is an item, indent after the
22049 description part, if any, or the bullet (see
22050 `org-list-description-max-indent'). Else, indent like
22051 parent's first line.
22053 3. Otherwise, indent relatively to current level, if
22054 `org-adapt-indentation' is non-nil, or to left margin.
22056 - On a blank line at the end of an element, indent according to
22057 the type of the element. More precisely
22059 1. If element is a plain list, an item, or a footnote
22060 definition, indent like the very last element within.
22062 2. If element is a paragraph, indent like its last non blank
22063 line.
22065 3. Otherwise, indent like its very first line.
22067 - In the code part of a source block, use language major mode
22068 to indent current line if `org-src-tab-acts-natively' is
22069 non-nil. If it is nil, do nothing.
22071 - Otherwise, indent like the first non-blank line above.
22073 The function doesn't indent an item as it could break the whole
22074 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22075 `\\[org-shiftmetaright]'.
22077 Also align node properties according to `org-property-format'."
22078 (interactive)
22079 (cond
22080 (orgstruct-is-++
22081 (let ((indent-line-function
22082 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22083 (indent-according-to-mode)))
22084 ((org-at-heading-p) 'noindent)
22086 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22087 (type (org-element-type element)))
22088 (cond ((and (memq type '(plain-list item))
22089 (= (line-beginning-position)
22090 (org-element-property :post-affiliated element)))
22091 'noindent)
22092 ((and (eq type 'latex-environment)
22093 (>= (point) (org-element-property :post-affiliated element))
22094 (< (point) (org-with-wide-buffer
22095 (goto-char (org-element-property :end element))
22096 (skip-chars-backward " \r\t\n")
22097 (line-beginning-position 2))))
22098 'noindent)
22099 ((and (eq type 'src-block)
22100 org-src-tab-acts-natively
22101 (> (line-beginning-position)
22102 (org-element-property :post-affiliated element))
22103 (< (line-beginning-position)
22104 (org-with-wide-buffer
22105 (goto-char (org-element-property :end element))
22106 (skip-chars-backward " \r\t\n")
22107 (line-beginning-position))))
22108 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22110 (let ((column (org--get-expected-indentation element nil)))
22111 ;; Preserve current column.
22112 (if (<= (current-column) (current-indentation))
22113 (indent-line-to column)
22114 (save-excursion (indent-line-to column))))
22115 ;; Align node property. Also preserve current column.
22116 (when (eq type 'node-property)
22117 (let ((column (current-column)))
22118 (org--align-node-property)
22119 (org-move-to-column column)))))))))
22121 (defun org-indent-region (start end)
22122 "Indent each non-blank line in the region.
22123 Called from a program, START and END specify the region to
22124 indent. The function will not indent contents of example blocks,
22125 verse blocks and export blocks as leading white spaces are
22126 assumed to be significant there."
22127 (interactive "r")
22128 (save-excursion
22129 (goto-char start)
22130 (skip-chars-forward " \r\t\n")
22131 (unless (eobp) (beginning-of-line))
22132 (let ((indent-to
22133 (lambda (ind pos)
22134 ;; Set IND as indentation for all lines between point and
22135 ;; POS. Blank lines are ignored. Leave point after POS
22136 ;; once done.
22137 (let ((limit (copy-marker pos)))
22138 (while (< (point) limit)
22139 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22140 (forward-line))
22141 (set-marker limit nil))))
22142 (end (copy-marker end)))
22143 (while (< (point) end)
22144 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22145 (let* ((element (org-element-at-point))
22146 (type (org-element-type element))
22147 (element-end (copy-marker (org-element-property :end element)))
22148 (ind (org--get-expected-indentation element nil)))
22149 (cond
22150 ;; Element indented as a single block. Example blocks
22151 ;; preserving indentation are a special case since the
22152 ;; "contents" must not be indented whereas the block
22153 ;; boundaries can.
22154 ((or (memq type '(export-block latex-environment))
22155 (and (eq type 'example-block)
22156 (not
22157 (or org-src-preserve-indentation
22158 (org-element-property :preserve-indent element)))))
22159 (let ((offset (- ind (org-get-indentation))))
22160 (unless (zerop offset)
22161 (indent-rigidly (org-element-property :begin element)
22162 (org-element-property :end element)
22163 offset)))
22164 (goto-char element-end))
22165 ;; Elements indented line wise. Be sure to exclude
22166 ;; example blocks (preserving indentation) and source
22167 ;; blocks from this category as they are treated
22168 ;; specially later.
22169 ((or (memq type '(paragraph table table-row))
22170 (not (or (org-element-property :contents-begin element)
22171 (memq type '(example-block src-block)))))
22172 (when (eq type 'node-property)
22173 (org--align-node-property)
22174 (beginning-of-line))
22175 (funcall indent-to ind (min element-end end)))
22176 ;; Elements consisting of three parts: before the
22177 ;; contents, the contents, and after the contents. The
22178 ;; contents are treated specially, according to the
22179 ;; element type, or not indented at all. Other parts are
22180 ;; indented as a single block.
22182 (let* ((post (copy-marker
22183 (org-element-property :post-affiliated element)))
22184 (cbeg
22185 (copy-marker
22186 (cond
22187 ((not (org-element-property :contents-begin element))
22188 ;; Fake contents for source blocks.
22189 (org-with-wide-buffer
22190 (goto-char post)
22191 (line-beginning-position 2)))
22192 ((memq type '(footnote-definition item plain-list))
22193 ;; Contents in these elements could start on
22194 ;; the same line as the beginning of the
22195 ;; element. Make sure we start indenting
22196 ;; from the second line.
22197 (org-with-wide-buffer
22198 (goto-char post)
22199 (end-of-line)
22200 (skip-chars-forward " \r\t\n")
22201 (if (eobp) (point) (line-beginning-position))))
22202 (t (org-element-property :contents-begin element)))))
22203 (cend (copy-marker
22204 (or (org-element-property :contents-end element)
22205 ;; Fake contents for source blocks.
22206 (org-with-wide-buffer
22207 (goto-char element-end)
22208 (skip-chars-backward " \r\t\n")
22209 (line-beginning-position)))
22210 t)))
22211 ;; Do not change items indentation individually as it
22212 ;; might break the list as a whole. On the other
22213 ;; hand, when at a plain list, indent it as a whole.
22214 (cond ((eq type 'plain-list)
22215 (let ((offset (- ind (org-get-indentation))))
22216 (unless (zerop offset)
22217 (indent-rigidly (org-element-property :begin element)
22218 (org-element-property :end element)
22219 offset))
22220 (goto-char cbeg)))
22221 ((eq type 'item) (goto-char cbeg))
22222 (t (funcall indent-to ind (min cbeg end))))
22223 (when (< (point) end)
22224 (cl-case type
22225 ((example-block verse-block))
22226 (src-block
22227 ;; In a source block, indent source code
22228 ;; according to language major mode, but only if
22229 ;; `org-src-tab-acts-natively' is non-nil.
22230 (when (and (< (point) end) org-src-tab-acts-natively)
22231 (ignore-errors
22232 (org-babel-do-in-edit-buffer
22233 (indent-region (point-min) (point-max))))))
22234 (t (org-indent-region (point) (min cend end))))
22235 (goto-char (min cend end))
22236 (when (< (point) end)
22237 (funcall indent-to ind (min element-end end))))
22238 (set-marker post nil)
22239 (set-marker cbeg nil)
22240 (set-marker cend nil))))
22241 (set-marker element-end nil))))
22242 (set-marker end nil))))
22244 (defun org-indent-drawer ()
22245 "Indent the drawer at point."
22246 (interactive)
22247 (unless (save-excursion
22248 (beginning-of-line)
22249 (looking-at-p org-drawer-regexp))
22250 (user-error "Not at a drawer"))
22251 (let ((element (org-element-at-point)))
22252 (unless (memq (org-element-type element) '(drawer property-drawer))
22253 (user-error "Not at a drawer"))
22254 (org-with-wide-buffer
22255 (org-indent-region (org-element-property :begin element)
22256 (org-element-property :end element))))
22257 (message "Drawer at point indented"))
22259 (defun org-indent-block ()
22260 "Indent the block at point."
22261 (interactive)
22262 (unless (save-excursion
22263 (beginning-of-line)
22264 (let ((case-fold-search t))
22265 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22266 (user-error "Not at a block"))
22267 (let ((element (org-element-at-point)))
22268 (unless (memq (org-element-type element)
22269 '(comment-block center-block dynamic-block example-block
22270 export-block quote-block special-block
22271 src-block verse-block))
22272 (user-error "Not at a block"))
22273 (org-with-wide-buffer
22274 (org-indent-region (org-element-property :begin element)
22275 (org-element-property :end element))))
22276 (message "Block at point indented"))
22279 ;;; Filling
22281 ;; We use our own fill-paragraph and auto-fill functions.
22283 ;; `org-fill-paragraph' relies on adaptive filling and context
22284 ;; checking. Appropriate `fill-prefix' is computed with
22285 ;; `org-adaptive-fill-function'.
22287 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22288 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22289 ;; `org-adaptive-fill-function' value. Internally,
22290 ;; `org-comment-line-break-function' breaks the line.
22292 ;; `org-setup-filling' installs filling and auto-filling related
22293 ;; variables during `org-mode' initialization.
22295 (defun org-setup-filling ()
22296 (require 'org-element)
22297 ;; Prevent auto-fill from inserting unwanted new items.
22298 (when (boundp 'fill-nobreak-predicate)
22299 (setq-local
22300 fill-nobreak-predicate
22301 (org-uniquify
22302 (append fill-nobreak-predicate
22303 '(org-fill-line-break-nobreak-p
22304 org-fill-n-macro-as-item-nobreak-p
22305 org-fill-paragraph-with-timestamp-nobreak-p)))))
22306 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22307 (setq-local paragraph-start paragraph-ending)
22308 (setq-local paragraph-separate paragraph-ending))
22309 (setq-local fill-paragraph-function 'org-fill-paragraph)
22310 (setq-local auto-fill-inhibit-regexp nil)
22311 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22312 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22313 (setq-local comment-line-break-function 'org-comment-line-break-function))
22315 (defun org-fill-line-break-nobreak-p ()
22316 "Non-nil when a new line at point would create an Org line break."
22317 (save-excursion
22318 (skip-chars-backward "[ \t]")
22319 (skip-chars-backward "\\\\")
22320 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22322 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22323 "Non-nil when a new line at point would split a timestamp."
22324 (and (org-at-timestamp-p 'lax)
22325 (not (looking-at org-ts-regexp-both))))
22327 (defun org-fill-n-macro-as-item-nobreak-p ()
22328 "Non-nil when a new line at point would create a new list."
22329 ;; During export, a "n" macro followed by a dot or a closing
22330 ;; parenthesis can end up being parsed as a new list item.
22331 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22333 (declare-function message-in-body-p "message" ())
22334 (defvar orgtbl-line-start-regexp) ; From org-table.el
22335 (defun org-adaptive-fill-function ()
22336 "Compute a fill prefix for the current line.
22337 Return fill prefix, as a string, or nil if current line isn't
22338 meant to be filled. For convenience, if `adaptive-fill-regexp'
22339 matches in paragraphs or comments, use it."
22340 (catch 'exit
22341 (when (derived-mode-p 'message-mode)
22342 (save-excursion
22343 (beginning-of-line)
22344 (cond ((not (message-in-body-p)) (throw 'exit nil))
22345 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22346 ((looking-at message-cite-prefix-regexp)
22347 (throw 'exit (match-string-no-properties 0)))
22348 ((looking-at org-outline-regexp)
22349 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22350 (org-with-wide-buffer
22351 (unless (org-at-heading-p)
22352 (let* ((p (line-beginning-position))
22353 (element (save-excursion
22354 (beginning-of-line)
22355 (org-element-at-point)))
22356 (type (org-element-type element))
22357 (post-affiliated (org-element-property :post-affiliated element)))
22358 (unless (< p post-affiliated)
22359 (cl-case type
22360 (comment
22361 (save-excursion
22362 (beginning-of-line)
22363 (looking-at "[ \t]*")
22364 (concat (match-string 0) "# ")))
22365 (footnote-definition "")
22366 ((item plain-list)
22367 (make-string (org-list-item-body-column post-affiliated) ?\s))
22368 (paragraph
22369 ;; Fill prefix is usually the same as the current line,
22370 ;; unless the paragraph is at the beginning of an item.
22371 (let ((parent (org-element-property :parent element)))
22372 (save-excursion
22373 (beginning-of-line)
22374 (cond ((eq (org-element-type parent) 'item)
22375 (make-string (org-list-item-body-column
22376 (org-element-property :begin parent))
22377 ?\s))
22378 ((and adaptive-fill-regexp
22379 ;; Locally disable
22380 ;; `adaptive-fill-function' to let
22381 ;; `fill-context-prefix' handle
22382 ;; `adaptive-fill-regexp' variable.
22383 (let (adaptive-fill-function)
22384 (fill-context-prefix
22385 post-affiliated
22386 (org-element-property :end element)))))
22387 ((looking-at "[ \t]+") (match-string 0))
22388 (t "")))))
22389 (comment-block
22390 ;; Only fill contents if P is within block boundaries.
22391 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22392 (forward-line)
22393 (point)))
22394 (cend (save-excursion
22395 (goto-char (org-element-property :end element))
22396 (skip-chars-backward " \r\t\n")
22397 (line-beginning-position))))
22398 (when (and (>= p cbeg) (< p cend))
22399 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22400 (match-string 0)
22401 "")))))))))))
22403 (declare-function message-goto-body "message" ())
22404 (defvar message-cite-prefix-regexp) ; From message.el
22406 (defun org-fill-element (&optional justify)
22407 "Fill element at point, when applicable.
22409 This function only applies to comment blocks, comments, example
22410 blocks and paragraphs. Also, as a special case, re-align table
22411 when point is at one.
22413 If JUSTIFY is non-nil (interactively, with prefix argument),
22414 justify as well. If `sentence-end-double-space' is non-nil, then
22415 period followed by one space does not end a sentence, so don't
22416 break a line there. The variable `fill-column' controls the
22417 width for filling.
22419 For convenience, when point is at a plain list, an item or
22420 a footnote definition, try to fill the first paragraph within."
22421 (with-syntax-table org-mode-transpose-word-syntax-table
22422 ;; Move to end of line in order to get the first paragraph within
22423 ;; a plain list or a footnote definition.
22424 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22425 ;; First check if point is in a blank line at the beginning of
22426 ;; the buffer. In that case, ignore filling.
22427 (cl-case (org-element-type element)
22428 ;; Use major mode filling function is src blocks.
22429 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22430 ;; Align Org tables, leave table.el tables as-is.
22431 (table-row (org-table-align) t)
22432 (table
22433 (when (eq (org-element-property :type element) 'org)
22434 (save-excursion
22435 (goto-char (org-element-property :post-affiliated element))
22436 (org-table-align)))
22438 (paragraph
22439 ;; Paragraphs may contain `line-break' type objects.
22440 (let ((beg (max (point-min)
22441 (org-element-property :contents-begin element)))
22442 (end (min (point-max)
22443 (org-element-property :contents-end element))))
22444 ;; Do nothing if point is at an affiliated keyword.
22445 (if (< (line-end-position) beg) t
22446 (when (derived-mode-p 'message-mode)
22447 ;; In `message-mode', do not fill following citation
22448 ;; in current paragraph nor text before message body.
22449 (let ((body-start (save-excursion (message-goto-body))))
22450 (when body-start (setq beg (max body-start beg))))
22451 (when (save-excursion
22452 (re-search-forward
22453 (concat "^" message-cite-prefix-regexp) end t))
22454 (setq end (match-beginning 0))))
22455 ;; Fill paragraph, taking line breaks into account.
22456 (save-excursion
22457 (goto-char beg)
22458 (let ((cuts (list beg)))
22459 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22460 (when (eq 'line-break
22461 (org-element-type
22462 (save-excursion (backward-char)
22463 (org-element-context))))
22464 (push (point) cuts)))
22465 (dolist (c (delq end cuts))
22466 (fill-region-as-paragraph c end justify)
22467 (setq end c))))
22468 t)))
22469 ;; Contents of `comment-block' type elements should be
22470 ;; filled as plain text, but only if point is within block
22471 ;; markers.
22472 (comment-block
22473 (let* ((case-fold-search t)
22474 (beg (save-excursion
22475 (goto-char (org-element-property :begin element))
22476 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22477 (forward-line)
22478 (point)))
22479 (end (save-excursion
22480 (goto-char (org-element-property :end element))
22481 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22482 (line-beginning-position))))
22483 (if (or (< (point) beg) (> (point) end)) t
22484 (fill-region-as-paragraph
22485 (save-excursion (end-of-line)
22486 (re-search-backward "^[ \t]*$" beg 'move)
22487 (line-beginning-position))
22488 (save-excursion (beginning-of-line)
22489 (re-search-forward "^[ \t]*$" end 'move)
22490 (line-beginning-position))
22491 justify))))
22492 ;; Fill comments.
22493 (comment
22494 (let ((begin (org-element-property :post-affiliated element))
22495 (end (org-element-property :end element)))
22496 (when (and (>= (point) begin) (<= (point) end))
22497 (let ((begin (save-excursion
22498 (end-of-line)
22499 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22500 (progn (forward-line) (point))
22501 begin)))
22502 (end (save-excursion
22503 (end-of-line)
22504 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22505 (1- (line-beginning-position))
22506 (skip-chars-backward " \r\t\n")
22507 (line-end-position)))))
22508 ;; Do not fill comments when at a blank line.
22509 (when (> end begin)
22510 (let ((fill-prefix
22511 (save-excursion
22512 (beginning-of-line)
22513 (looking-at "[ \t]*#")
22514 (let ((comment-prefix (match-string 0)))
22515 (goto-char (match-end 0))
22516 (if (looking-at adaptive-fill-regexp)
22517 (concat comment-prefix (match-string 0))
22518 (concat comment-prefix " "))))))
22519 (save-excursion
22520 (fill-region-as-paragraph begin end justify))))))
22522 ;; Ignore every other element.
22523 (otherwise t)))))
22525 (defun org-fill-paragraph (&optional justify region)
22526 "Fill element at point, when applicable.
22528 This function only applies to comment blocks, comments, example
22529 blocks and paragraphs. Also, as a special case, re-align table
22530 when point is at one.
22532 For convenience, when point is at a plain list, an item or
22533 a footnote definition, try to fill the first paragraph within.
22535 If JUSTIFY is non-nil (interactively, with prefix argument),
22536 justify as well. If `sentence-end-double-space' is non-nil, then
22537 period followed by one space does not end a sentence, so don't
22538 break a line there. The variable `fill-column' controls the
22539 width for filling.
22541 The REGION argument is non-nil if called interactively; in that
22542 case, if Transient Mark mode is enabled and the mark is active,
22543 fill each of the elements in the active region, instead of just
22544 filling the current element."
22545 (interactive (progn
22546 (barf-if-buffer-read-only)
22547 (list (if current-prefix-arg 'full) t)))
22548 (cond
22549 ((and (derived-mode-p 'message-mode)
22550 (or (not (message-in-body-p))
22551 (save-excursion (move-beginning-of-line 1)
22552 (looking-at message-cite-prefix-regexp))))
22553 ;; First ensure filling is correct in message-mode.
22554 (let ((fill-paragraph-function
22555 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22556 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22557 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22558 (paragraph-separate
22559 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22560 (fill-paragraph nil)))
22561 ((and region transient-mark-mode mark-active
22562 (not (eq (region-beginning) (region-end))))
22563 (let ((origin (point-marker))
22564 (start (region-beginning)))
22565 (unwind-protect
22566 (progn
22567 (goto-char (region-end))
22568 (while (> (point) start)
22569 (org-backward-paragraph)
22570 (org-fill-element justify)))
22571 (goto-char origin)
22572 (set-marker origin nil))))
22573 (t (org-fill-element justify))))
22574 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22576 (defun org-auto-fill-function ()
22577 "Auto-fill function."
22578 ;; Check if auto-filling is meaningful.
22579 (let ((fc (current-fill-column)))
22580 (when (and fc (> (current-column) fc))
22581 (let* ((fill-prefix (org-adaptive-fill-function))
22582 ;; Enforce empty fill prefix, if required. Otherwise, it
22583 ;; will be computed again.
22584 (adaptive-fill-mode (not (equal fill-prefix ""))))
22585 (when fill-prefix (do-auto-fill))))))
22587 (defun org-comment-line-break-function (&optional soft)
22588 "Break line at point and indent, continuing comment if within one.
22589 The inserted newline is marked hard if variable
22590 `use-hard-newlines' is true, unless optional argument SOFT is
22591 non-nil."
22592 (if soft (insert-and-inherit ?\n) (newline 1))
22593 (save-excursion (forward-char -1) (delete-horizontal-space))
22594 (delete-horizontal-space)
22595 (indent-to-left-margin)
22596 (insert-before-markers-and-inherit fill-prefix))
22599 ;;; Fixed Width Areas
22601 (defun org-toggle-fixed-width ()
22602 "Toggle fixed-width markup.
22604 Add or remove fixed-width markup on current line, whenever it
22605 makes sense. Return an error otherwise.
22607 If a region is active and if it contains only fixed-width areas
22608 or blank lines, remove all fixed-width markup in it. If the
22609 region contains anything else, convert all non-fixed-width lines
22610 to fixed-width ones.
22612 Blank lines at the end of the region are ignored unless the
22613 region only contains such lines."
22614 (interactive)
22615 (if (not (org-region-active-p))
22616 ;; No region:
22618 ;; Remove fixed width marker only in a fixed-with element.
22620 ;; Add fixed width maker in paragraphs, in blank lines after
22621 ;; elements or at the beginning of a headline or an inlinetask,
22622 ;; and before any one-line elements (e.g., a clock).
22623 (progn
22624 (beginning-of-line)
22625 (let* ((element (org-element-at-point))
22626 (type (org-element-type element)))
22627 (cond
22628 ((and (eq type 'fixed-width)
22629 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22630 (replace-match
22631 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22632 ((and (memq type '(babel-call clock comment diary-sexp headline
22633 horizontal-rule keyword paragraph
22634 planning))
22635 (<= (org-element-property :post-affiliated element) (point)))
22636 (skip-chars-forward " \t")
22637 (insert ": "))
22638 ((and (looking-at-p "[ \t]*$")
22639 (or (eq type 'inlinetask)
22640 (save-excursion
22641 (skip-chars-forward " \r\t\n")
22642 (<= (org-element-property :end element) (point)))))
22643 (delete-region (point) (line-end-position))
22644 (org-indent-line)
22645 (insert ": "))
22646 (t (user-error "Cannot insert a fixed-width line here")))))
22647 ;; Region active.
22648 (let* ((begin (save-excursion
22649 (goto-char (region-beginning))
22650 (line-beginning-position)))
22651 (end (copy-marker
22652 (save-excursion
22653 (goto-char (region-end))
22654 (unless (eolp) (beginning-of-line))
22655 (if (save-excursion (re-search-backward "\\S-" begin t))
22656 (progn (skip-chars-backward " \r\t\n") (point))
22657 (point)))))
22658 (all-fixed-width-p
22659 (catch 'not-all-p
22660 (save-excursion
22661 (goto-char begin)
22662 (skip-chars-forward " \r\t\n")
22663 (when (eobp) (throw 'not-all-p nil))
22664 (while (< (point) end)
22665 (let ((element (org-element-at-point)))
22666 (if (eq (org-element-type element) 'fixed-width)
22667 (goto-char (org-element-property :end element))
22668 (throw 'not-all-p nil))))
22669 t))))
22670 (if all-fixed-width-p
22671 (save-excursion
22672 (goto-char begin)
22673 (while (< (point) end)
22674 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22675 (replace-match
22676 "" nil nil nil
22677 (if (= (line-end-position) (match-end 0)) 0 1)))
22678 (forward-line)))
22679 (let ((min-ind (point-max)))
22680 ;; Find minimum indentation across all lines.
22681 (save-excursion
22682 (goto-char begin)
22683 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22684 (setq min-ind 0)
22685 (catch 'zerop
22686 (while (< (point) end)
22687 (unless (looking-at-p "[ \t]*$")
22688 (let ((ind (org-get-indentation)))
22689 (setq min-ind (min min-ind ind))
22690 (when (zerop ind) (throw 'zerop t))))
22691 (forward-line)))))
22692 ;; Loop over all lines and add fixed-width markup everywhere
22693 ;; but in fixed-width lines.
22694 (save-excursion
22695 (goto-char begin)
22696 (while (< (point) end)
22697 (cond
22698 ((org-at-heading-p)
22699 (insert ": ")
22700 (forward-line)
22701 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22702 (insert ":")
22703 (forward-line)))
22704 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22705 (let* ((element (org-element-at-point))
22706 (element-end (org-element-property :end element)))
22707 (if (eq (org-element-type element) 'fixed-width)
22708 (progn (goto-char element-end)
22709 (skip-chars-backward " \r\t\n")
22710 (forward-line))
22711 (let ((limit (min end element-end)))
22712 (while (< (point) limit)
22713 (org-move-to-column min-ind t)
22714 (insert ": ")
22715 (forward-line))))))
22717 (org-move-to-column min-ind t)
22718 (insert ": ")
22719 (forward-line)))))))
22720 (set-marker end nil))))
22723 ;;; Comments
22725 ;; Org comments syntax is quite complex. It requires the entire line
22726 ;; to be just a comment. Also, even with the right syntax at the
22727 ;; beginning of line, some elements (e.g., verse-block or
22728 ;; example-block) don't accept comments. Usual Emacs comment commands
22729 ;; cannot cope with those requirements. Therefore, Org replaces them.
22731 ;; Org still relies on `comment-dwim', but cannot trust
22732 ;; `comment-only-p'. So, `comment-region-function' and
22733 ;; `uncomment-region-function' both point
22734 ;; to`org-comment-or-uncomment-region'. Eventually,
22735 ;; `org-insert-comment' takes care of insertion of comments at the
22736 ;; beginning of line.
22738 ;; `org-setup-comments-handling' install comments related variables
22739 ;; during `org-mode' initialization.
22741 (defun org-setup-comments-handling ()
22742 (interactive)
22743 (setq-local comment-use-syntax nil)
22744 (setq-local comment-start "# ")
22745 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22746 (setq-local comment-insert-comment-function 'org-insert-comment)
22747 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22748 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22750 (defun org-insert-comment ()
22751 "Insert an empty comment above current line.
22752 If the line is empty, insert comment at its beginning. When
22753 point is within a source block, comment according to the related
22754 major mode."
22755 (if (let ((element (org-element-at-point)))
22756 (and (eq (org-element-type element) 'src-block)
22757 (< (save-excursion
22758 (goto-char (org-element-property :post-affiliated element))
22759 (line-end-position))
22760 (point))
22761 (> (save-excursion
22762 (goto-char (org-element-property :end element))
22763 (skip-chars-backward " \r\t\n")
22764 (line-beginning-position))
22765 (point))))
22766 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22767 (beginning-of-line)
22768 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22769 (open-line 1))
22770 (org-indent-line)
22771 (insert "# ")))
22773 (defvar comment-empty-lines) ; From newcomment.el.
22774 (defun org-comment-or-uncomment-region (beg end &rest _)
22775 "Comment or uncomment each non-blank line in the region.
22776 Uncomment each non-blank line between BEG and END if it only
22777 contains commented lines. Otherwise, comment them. If region is
22778 strictly within a source block, use appropriate comment syntax."
22779 (if (let ((element (org-element-at-point)))
22780 (and (eq (org-element-type element) 'src-block)
22781 (< (save-excursion
22782 (goto-char (org-element-property :post-affiliated element))
22783 (line-end-position))
22784 beg)
22785 (>= (save-excursion
22786 (goto-char (org-element-property :end element))
22787 (skip-chars-backward " \r\t\n")
22788 (line-beginning-position))
22789 end)))
22790 ;; Translate region boundaries for the Org buffer to the source
22791 ;; buffer.
22792 (let ((offset (- end beg)))
22793 (save-excursion
22794 (goto-char beg)
22795 (org-babel-do-in-edit-buffer
22796 (comment-or-uncomment-region (point) (+ offset (point))))))
22797 (save-restriction
22798 ;; Restrict region
22799 (narrow-to-region (save-excursion (goto-char beg)
22800 (skip-chars-forward " \r\t\n" end)
22801 (line-beginning-position))
22802 (save-excursion (goto-char end)
22803 (skip-chars-backward " \r\t\n" beg)
22804 (line-end-position)))
22805 (let ((uncommentp
22806 ;; UNCOMMENTP is non-nil when every non blank line between
22807 ;; BEG and END is a comment.
22808 (save-excursion
22809 (goto-char (point-min))
22810 (while (and (not (eobp))
22811 (let ((element (org-element-at-point)))
22812 (and (eq (org-element-type element) 'comment)
22813 (goto-char (min (point-max)
22814 (org-element-property
22815 :end element)))))))
22816 (eobp))))
22817 (if uncommentp
22818 ;; Only blank lines and comments in region: uncomment it.
22819 (save-excursion
22820 (goto-char (point-min))
22821 (while (not (eobp))
22822 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22823 (replace-match "" nil nil nil 1))
22824 (forward-line)))
22825 ;; Comment each line in region.
22826 (let ((min-indent (point-max)))
22827 ;; First find the minimum indentation across all lines.
22828 (save-excursion
22829 (goto-char (point-min))
22830 (while (and (not (eobp)) (not (zerop min-indent)))
22831 (unless (looking-at "[ \t]*$")
22832 (setq min-indent (min min-indent (current-indentation))))
22833 (forward-line)))
22834 ;; Then loop over all lines.
22835 (save-excursion
22836 (goto-char (point-min))
22837 (while (not (eobp))
22838 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22839 ;; Don't get fooled by invisible text (e.g. link path)
22840 ;; when moving to column MIN-INDENT.
22841 (let ((buffer-invisibility-spec nil))
22842 (org-move-to-column min-indent t))
22843 (insert comment-start))
22844 (forward-line)))))))))
22846 (defun org-comment-dwim (_arg)
22847 "Call the comment command you mean.
22848 Call `org-toggle-comment' if on a heading, otherwise call
22849 `comment-dwim', within a source edit buffer if needed."
22850 (interactive "*P")
22851 (cond ((org-at-heading-p)
22852 (call-interactively #'org-toggle-comment))
22853 ((org-in-src-block-p)
22854 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22855 (t (call-interactively #'comment-dwim))))
22858 ;;; Timestamps API
22860 ;; This section contains tools to operate on timestamp objects, as
22861 ;; returned by, e.g. `org-element-context'.
22863 (defun org-timestamp--to-internal-time (timestamp &optional end)
22864 "Encode TIMESTAMP object into Emacs internal time.
22865 Use end of date range or time range when END is non-nil."
22866 (apply #'encode-time
22867 (cons 0
22868 (mapcar
22869 (lambda (prop) (or (org-element-property prop timestamp) 0))
22870 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22871 '(:minute-start :hour-start :day-start :month-start
22872 :year-start))))))
22874 (defun org-timestamp-has-time-p (timestamp)
22875 "Non-nil when TIMESTAMP has a time specified."
22876 (org-element-property :hour-start timestamp))
22878 (defun org-timestamp-format (timestamp format &optional end utc)
22879 "Format a TIMESTAMP object into a string.
22881 FORMAT is a format specifier to be passed to
22882 `format-time-string'.
22884 When optional argument END is non-nil, use end of date-range or
22885 time-range, if possible.
22887 When optional argument UTC is non-nil, time will be expressed as
22888 Universal Time."
22889 (format-time-string
22890 format (org-timestamp--to-internal-time timestamp end)
22891 (and utc t)))
22893 (defun org-timestamp-split-range (timestamp &optional end)
22894 "Extract a TIMESTAMP object from a date or time range.
22896 END, when non-nil, means extract the end of the range.
22897 Otherwise, extract its start.
22899 Return a new timestamp object."
22900 (let ((type (org-element-property :type timestamp)))
22901 (if (memq type '(active inactive diary)) timestamp
22902 (let ((split-ts (org-element-copy timestamp)))
22903 ;; Set new type.
22904 (org-element-put-property
22905 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22906 ;; Copy start properties over end properties if END is
22907 ;; non-nil. Otherwise, copy end properties over `start' ones.
22908 (let ((p-alist '((:minute-start . :minute-end)
22909 (:hour-start . :hour-end)
22910 (:day-start . :day-end)
22911 (:month-start . :month-end)
22912 (:year-start . :year-end))))
22913 (dolist (p-cell p-alist)
22914 (org-element-put-property
22915 split-ts
22916 (funcall (if end #'car #'cdr) p-cell)
22917 (org-element-property
22918 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22919 ;; Eventually refresh `:raw-value'.
22920 (org-element-put-property split-ts :raw-value nil)
22921 (org-element-put-property
22922 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22924 (defun org-timestamp-translate (timestamp &optional boundary)
22925 "Translate TIMESTAMP object to custom format.
22927 Format string is defined in `org-time-stamp-custom-formats',
22928 which see.
22930 When optional argument BOUNDARY is non-nil, it is either the
22931 symbol `start' or `end'. In this case, only translate the
22932 starting or ending part of TIMESTAMP if it is a date or time
22933 range. Otherwise, translate both parts.
22935 Return timestamp as-is if `org-display-custom-times' is nil or if
22936 it has a `diary' type."
22937 (let ((type (org-element-property :type timestamp)))
22938 (if (or (not org-display-custom-times) (eq type 'diary))
22939 (org-element-interpret-data timestamp)
22940 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22941 org-time-stamp-custom-formats)))
22942 (if (and (not boundary) (memq type '(active-range inactive-range)))
22943 (concat (org-timestamp-format timestamp fmt)
22944 "--"
22945 (org-timestamp-format timestamp fmt t))
22946 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22950 ;;; Other stuff.
22952 (defvar reftex-docstruct-symbol)
22953 (defvar org--rds)
22955 (defun org-reftex-citation ()
22956 "Use reftex-citation to insert a citation into the buffer.
22957 This looks for a line like
22959 #+BIBLIOGRAPHY: foo plain option:-d
22961 and derives from it that foo.bib is the bibliography file relevant
22962 for this document. It then installs the necessary environment for RefTeX
22963 to work in this buffer and calls `reftex-citation' to insert a citation
22964 into the buffer.
22966 Export of such citations to both LaTeX and HTML is handled by the contributed
22967 package ox-bibtex by Taru Karttunen."
22968 (interactive)
22969 (let ((reftex-docstruct-symbol 'org--rds)
22970 org--rds bib)
22971 (org-with-wide-buffer
22972 (let ((case-fold-search t)
22973 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22974 (if (not (save-excursion
22975 (or (re-search-forward re nil t)
22976 (re-search-backward re nil t))))
22977 (user-error "No bibliography defined in file")
22978 (setq bib (concat (match-string 1) ".bib")
22979 org--rds (list (list 'bib bib))))))
22980 (call-interactively 'reftex-citation)))
22982 ;;;; Functions extending outline functionality
22984 (defun org-beginning-of-line (&optional n)
22985 "Go to the beginning of the current visible line.
22987 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22988 tags on the first attempt, and only move to after the tags when
22989 the cursor is already beyond the end of the headline.
22991 With argument N not nil or 1, move forward N - 1 lines first."
22992 (interactive "^p")
22993 (let ((origin (point))
22994 (special (pcase org-special-ctrl-a/e
22995 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22996 deactivate-mark)
22997 ;; First move to a visible line.
22998 (if (bound-and-true-p visual-line-mode)
22999 (beginning-of-visual-line n)
23000 (move-beginning-of-line n)
23001 ;; `move-beginning-of-line' may leave point after invisible
23002 ;; characters if line starts with such of these (e.g., with
23003 ;; a link at column 0). Really move to the beginning of the
23004 ;; current visible line.
23005 (beginning-of-line))
23006 (cond
23007 ;; No special behavior. Point is already at the beginning of
23008 ;; a line, logical or visual.
23009 ((not special))
23010 ;; `beginning-of-visual-line' left point before logical beginning
23011 ;; of line: point is at the beginning of a visual line. Bail
23012 ;; out.
23013 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23014 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23015 ;; At a headline, special position is before the title, but
23016 ;; after any TODO keyword or priority cookie.
23017 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23018 (line-end-position)))
23019 (bol (point)))
23020 (if (eq special 'reversed)
23021 (when (and (= origin bol) (eq last-command this-command))
23022 (goto-char refpos))
23023 (when (or (> origin refpos) (= origin bol))
23024 (goto-char refpos)))))
23025 ((and (looking-at org-list-full-item-re)
23026 (memq (org-element-type (save-match-data (org-element-at-point)))
23027 '(item plain-list)))
23028 ;; Set special position at first white space character after
23029 ;; bullet, and check-box, if any.
23030 (let ((after-bullet
23031 (let ((box (match-end 3)))
23032 (cond ((not box) (match-end 1))
23033 ((eq (char-after box) ?\s) (1+ box))
23034 (t box)))))
23035 (if (eq special 'reversed)
23036 (when (and (= (point) origin) (eq last-command this-command))
23037 (goto-char after-bullet))
23038 (when (or (> origin after-bullet) (= (point) origin))
23039 (goto-char after-bullet)))))
23040 ;; No special context. Point is already at beginning of line.
23041 (t nil))))
23043 (defun org-end-of-line (&optional n)
23044 "Go to the end of the line, but before ellipsis, if any.
23046 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23047 tags on the first attempt, and only move to after the tags when
23048 the cursor is already beyond the end of the headline.
23050 With argument N not nil or 1, move forward N - 1 lines first."
23051 (interactive "^p")
23052 (let ((origin (point))
23053 (special (pcase org-special-ctrl-a/e
23054 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23055 deactivate-mark)
23056 ;; First move to a visible line.
23057 (if (bound-and-true-p visual-line-mode)
23058 (beginning-of-visual-line n)
23059 (move-beginning-of-line n))
23060 (cond
23061 ;; At a headline, with tags.
23062 ((and special
23063 (save-excursion
23064 (beginning-of-line)
23065 (let ((case-fold-search nil))
23066 (looking-at org-complex-heading-regexp)))
23067 (match-end 5))
23068 (let ((tags (save-excursion
23069 (goto-char (match-beginning 5))
23070 (skip-chars-backward " \t")
23071 (point)))
23072 (visual-end (and (bound-and-true-p visual-line-mode)
23073 (save-excursion
23074 (end-of-visual-line)
23075 (point)))))
23076 ;; If `end-of-visual-line' brings us before end of line or
23077 ;; even tags, i.e., the headline spans over multiple visual
23078 ;; lines, move there.
23079 (cond ((and visual-end
23080 (< visual-end tags)
23081 (<= origin visual-end))
23082 (goto-char visual-end))
23083 ((eq special 'reversed)
23084 (if (and (= origin (line-end-position))
23085 (eq this-command last-command))
23086 (goto-char tags)
23087 (end-of-line)))
23089 (if (or (< origin tags) (= origin (line-end-position)))
23090 (goto-char tags)
23091 (end-of-line))))))
23092 ((bound-and-true-p visual-line-mode)
23093 (let ((bol (line-beginning-position)))
23094 (end-of-visual-line)
23095 ;; If `end-of-visual-line' gets us past the ellipsis at the
23096 ;; end of a line, backtrack and use `end-of-line' instead.
23097 (when (/= bol (line-beginning-position))
23098 (goto-char bol)
23099 (end-of-line))))
23100 (t (end-of-line)))))
23102 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23103 (define-key org-mode-map "\C-e" 'org-end-of-line)
23105 (defun org-backward-sentence (&optional _arg)
23106 "Go to beginning of sentence, or beginning of table field.
23107 This will call `backward-sentence' or `org-table-beginning-of-field',
23108 depending on context."
23109 (interactive)
23110 (let* ((element (org-element-at-point))
23111 (contents-begin (org-element-property :contents-begin element))
23112 (table (org-element-lineage element '(table) t)))
23113 (if (and table
23114 (> (point) contents-begin)
23115 (<= (point) (org-element-property :contents-end table)))
23116 (call-interactively #'org-table-beginning-of-field)
23117 (save-restriction
23118 (when (and contents-begin
23119 (< (point-min) contents-begin)
23120 (> (point) contents-begin))
23121 (narrow-to-region contents-begin
23122 (org-element-property :contents-end element)))
23123 (call-interactively #'backward-sentence)))))
23125 (defun org-forward-sentence (&optional _arg)
23126 "Go to end of sentence, or end of table field.
23127 This will call `forward-sentence' or `org-table-end-of-field',
23128 depending on context."
23129 (interactive)
23130 (if (and (org-at-heading-p)
23131 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23132 (save-restriction
23133 (narrow-to-region (line-beginning-position) (line-end-position))
23134 (call-interactively #'forward-sentence))
23135 (let* ((element (org-element-at-point))
23136 (contents-end (org-element-property :contents-end element))
23137 (table (org-element-lineage element '(table) t)))
23138 (if (and table
23139 (>= (point) (org-element-property :contents-begin table))
23140 (< (point) contents-end))
23141 (call-interactively #'org-table-end-of-field)
23142 (save-restriction
23143 (when (and contents-end
23144 (> (point-max) contents-end)
23145 ;; Skip blank lines between elements.
23146 (< (org-element-property :end element)
23147 (save-excursion (goto-char contents-end)
23148 (skip-chars-forward " \r\t\n"))))
23149 (narrow-to-region (org-element-property :contents-begin element)
23150 contents-end))
23151 ;; End of heading is considered as the end of a sentence.
23152 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23153 (call-interactively #'forward-sentence)))))))
23155 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23156 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23158 (defun org-kill-line (&optional _arg)
23159 "Kill line, to tags or end of line."
23160 (interactive)
23161 (cond
23162 ((or (not org-special-ctrl-k)
23163 (bolp)
23164 (not (org-at-heading-p)))
23165 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23166 org-ctrl-k-protect-subtree
23167 (or (eq org-ctrl-k-protect-subtree 'error)
23168 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23169 (user-error "C-k aborted as it would kill a hidden subtree"))
23170 (call-interactively
23171 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23172 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23173 (kill-region (point) (match-beginning 1))
23174 (org-set-tags nil t))
23175 (t (kill-region (point) (point-at-eol)))))
23177 (define-key org-mode-map "\C-k" 'org-kill-line)
23179 (defun org-yank (&optional arg)
23180 "Yank. If the kill is a subtree, treat it specially.
23181 This command will look at the current kill and check if is a single
23182 subtree, or a series of subtrees[1]. If it passes the test, and if the
23183 cursor is at the beginning of a line or after the stars of a currently
23184 empty headline, then the yank is handled specially. How exactly depends
23185 on the value of the following variables.
23187 `org-yank-folded-subtrees'
23188 By default, this variable is non-nil, which results in
23189 subtree(s) being folded after insertion, except if doing so
23190 would swallow text after the yanked text.
23192 `org-yank-adjusted-subtrees'
23193 When non-nil (the default value is nil), the subtree will be
23194 promoted or demoted in order to fit into the local outline tree
23195 structure, which means that the level will be adjusted so that it
23196 becomes the smaller one of the two *visible* surrounding headings.
23198 Any prefix to this command will cause `yank' to be called directly with
23199 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23200 will just
23201 plainly yank the text as it is.
23203 \[1] The test checks if the first non-white line is a heading
23204 and if there are no other headings with fewer stars."
23205 (interactive "P")
23206 (org-yank-generic 'yank arg))
23208 (defun org-yank-generic (command arg)
23209 "Perform some yank-like command.
23211 This function implements the behavior described in the `org-yank'
23212 documentation. However, it has been generalized to work for any
23213 interactive command with similar behavior."
23215 ;; pretend to be command COMMAND
23216 (setq this-command command)
23218 (if arg
23219 (call-interactively command)
23221 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23222 (and (org-kill-is-subtree-p)
23223 (or (bolp)
23224 (and (looking-at "[ \t]*$")
23225 (string-match
23226 "\\`\\*+\\'"
23227 (buffer-substring (point-at-bol) (point)))))))
23228 swallowp)
23229 (cond
23230 ((and subtreep org-yank-folded-subtrees)
23231 (let ((beg (point))
23232 end)
23233 (if (and subtreep org-yank-adjusted-subtrees)
23234 (org-paste-subtree nil nil 'for-yank)
23235 (call-interactively command))
23237 (setq end (point))
23238 (goto-char beg)
23239 (when (and (bolp) subtreep
23240 (not (setq swallowp
23241 (org-yank-folding-would-swallow-text beg end))))
23242 (org-with-limited-levels
23243 (or (looking-at org-outline-regexp)
23244 (re-search-forward org-outline-regexp-bol end t))
23245 (while (and (< (point) end) (looking-at org-outline-regexp))
23246 (outline-hide-subtree)
23247 (org-cycle-show-empty-lines 'folded)
23248 (condition-case nil
23249 (outline-forward-same-level 1)
23250 (error (goto-char end))))))
23251 (when swallowp
23252 (message
23253 "Inserted text not folded because that would swallow text"))
23255 (goto-char end)
23256 (skip-chars-forward " \t\n\r")
23257 (beginning-of-line 1)
23258 (push-mark beg 'nomsg)))
23259 ((and subtreep org-yank-adjusted-subtrees)
23260 (let ((beg (point-at-bol)))
23261 (org-paste-subtree nil nil 'for-yank)
23262 (push-mark beg 'nomsg)))
23264 (call-interactively command))))))
23266 (defun org-yank-folding-would-swallow-text (beg end)
23267 "Would hide-subtree at BEG swallow any text after END?"
23268 (let (level)
23269 (org-with-limited-levels
23270 (save-excursion
23271 (goto-char beg)
23272 (when (or (looking-at org-outline-regexp)
23273 (re-search-forward org-outline-regexp-bol end t))
23274 (setq level (org-outline-level)))
23275 (goto-char end)
23276 (skip-chars-forward " \t\r\n\v\f")
23277 (not (or (eobp)
23278 (and (bolp) (looking-at-p org-outline-regexp)
23279 (<= (org-outline-level) level))))))))
23281 (define-key org-mode-map "\C-y" 'org-yank)
23283 (defun org-back-to-heading (&optional invisible-ok)
23284 "Call `outline-back-to-heading', but provide a better error message."
23285 (condition-case nil
23286 (outline-back-to-heading invisible-ok)
23287 (error (error "Before first headline at position %d in buffer %s"
23288 (point) (current-buffer)))))
23290 (defun org-before-first-heading-p ()
23291 "Before first heading?"
23292 (save-excursion
23293 (end-of-line)
23294 (null (re-search-backward org-outline-regexp-bol nil t))))
23296 (defun org-at-heading-p (&optional ignored)
23297 (outline-on-heading-p t))
23299 (defun org-in-commented-heading-p (&optional no-inheritance)
23300 "Non-nil if point is under a commented heading.
23301 This function also checks ancestors of the current headline,
23302 unless optional argument NO-INHERITANCE is non-nil."
23303 (cond
23304 ((org-before-first-heading-p) nil)
23305 ((let ((headline (nth 4 (org-heading-components))))
23306 (and headline
23307 (let ((case-fold-search nil))
23308 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23309 headline)))))
23310 (no-inheritance nil)
23312 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23314 (defun org-at-comment-p nil
23315 "Is cursor in a commented line?"
23316 (save-excursion
23317 (save-match-data
23318 (beginning-of-line)
23319 (looking-at "^[ \t]*# "))))
23321 (defun org-at-drawer-p nil
23322 "Is cursor at a drawer keyword?"
23323 (save-excursion
23324 (move-beginning-of-line 1)
23325 (looking-at org-drawer-regexp)))
23327 (defun org-at-block-p nil
23328 "Is cursor at a block keyword?"
23329 (save-excursion
23330 (move-beginning-of-line 1)
23331 (looking-at org-block-regexp)))
23333 (defun org-point-at-end-of-empty-headline ()
23334 "If point is at the end of an empty headline, return t, else nil.
23335 If the heading only contains a TODO keyword, it is still still considered
23336 empty."
23337 (let ((case-fold-search nil))
23338 (and (looking-at "[ \t]*$")
23339 org-todo-line-regexp
23340 (save-excursion
23341 (beginning-of-line)
23342 (looking-at org-todo-line-regexp)
23343 (string= (match-string 3) "")))))
23345 (defun org-at-heading-or-item-p ()
23346 (or (org-at-heading-p) (org-at-item-p)))
23348 (defun org-at-target-p ()
23349 (or (org-in-regexp org-radio-target-regexp)
23350 (org-in-regexp org-target-regexp)))
23351 ;; Compatibility alias with Org versions < 7.8.03
23352 (defalias 'org-on-target-p 'org-at-target-p)
23354 (defun org-up-heading-all (arg)
23355 "Move to the heading line of which the present line is a subheading.
23356 This function considers both visible and invisible heading lines.
23357 With argument, move up ARG levels."
23358 (outline-up-heading arg t))
23360 (defun org-up-heading-safe ()
23361 "Move to the heading line of which the present line is a subheading.
23362 This version will not throw an error. It will return the level of the
23363 headline found, or nil if no higher level is found.
23365 Also, this function will be a lot faster than `outline-up-heading',
23366 because it relies on stars being the outline starters. This can really
23367 make a significant difference in outlines with very many siblings."
23368 (when (ignore-errors (org-back-to-heading t))
23369 (let ((level-up (1- (funcall outline-level))))
23370 (and (> level-up 0)
23371 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23372 (funcall outline-level)))))
23374 (defun org-first-sibling-p ()
23375 "Is this heading the first child of its parents?"
23376 (interactive)
23377 (let ((re org-outline-regexp-bol)
23378 level l)
23379 (unless (org-at-heading-p t)
23380 (user-error "Not at a heading"))
23381 (setq level (funcall outline-level))
23382 (save-excursion
23383 (if (not (re-search-backward re nil t))
23385 (setq l (funcall outline-level))
23386 (< l level)))))
23388 (defun org-goto-sibling (&optional previous)
23389 "Goto the next sibling, even if it is invisible.
23390 When PREVIOUS is set, go to the previous sibling instead. Returns t
23391 when a sibling was found. When none is found, return nil and don't
23392 move point."
23393 (let ((fun (if previous 're-search-backward 're-search-forward))
23394 (pos (point))
23395 (re org-outline-regexp-bol)
23396 level l)
23397 (when (ignore-errors (org-back-to-heading t))
23398 (setq level (funcall outline-level))
23399 (catch 'exit
23400 (or previous (forward-char 1))
23401 (while (funcall fun re nil t)
23402 (setq l (funcall outline-level))
23403 (when (< l level) (goto-char pos) (throw 'exit nil))
23404 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23405 (goto-char pos)
23406 nil))))
23408 (defun org-show-siblings ()
23409 "Show all siblings of the current headline."
23410 (save-excursion
23411 (while (org-goto-sibling) (org-flag-heading nil)))
23412 (save-excursion
23413 (while (org-goto-sibling 'previous)
23414 (org-flag-heading nil))))
23416 (defun org-goto-first-child ()
23417 "Goto the first child, even if it is invisible.
23418 Return t when a child was found. Otherwise don't move point and
23419 return nil."
23420 (let (level (pos (point)) (re org-outline-regexp-bol))
23421 (when (ignore-errors (org-back-to-heading t))
23422 (setq level (outline-level))
23423 (forward-char 1)
23424 (if (and (re-search-forward re nil t) (> (outline-level) level))
23425 (progn (goto-char (match-beginning 0)) t)
23426 (goto-char pos) nil))))
23428 (defun org-show-hidden-entry ()
23429 "Show an entry where even the heading is hidden."
23430 (save-excursion
23431 (org-show-entry)))
23433 (defun org-flag-heading (flag &optional entry)
23434 "Flag the current heading. FLAG non-nil means make invisible.
23435 When ENTRY is non-nil, show the entire entry."
23436 (save-excursion
23437 (org-back-to-heading t)
23438 ;; Check if we should show the entire entry
23439 (if entry
23440 (progn
23441 (org-show-entry)
23442 (save-excursion
23443 (and (outline-next-heading)
23444 (org-flag-heading nil))))
23445 (outline-flag-region (max (point-min) (1- (point)))
23446 (save-excursion (outline-end-of-heading) (point))
23447 flag))))
23449 (defun org-get-next-sibling ()
23450 "Move to next heading of the same level, and return point.
23451 If there is no such heading, return nil.
23452 This is like outline-next-sibling, but invisible headings are ok."
23453 (let ((level (funcall outline-level)))
23454 (outline-next-heading)
23455 (while (and (not (eobp)) (> (funcall outline-level) level))
23456 (outline-next-heading))
23457 (unless (or (eobp) (< (funcall outline-level) level))
23458 (point))))
23460 (defun org-get-last-sibling ()
23461 "Move to previous heading of the same level, and return point.
23462 If there is no such heading, return nil."
23463 (let ((opoint (point))
23464 (level (funcall outline-level)))
23465 (outline-previous-heading)
23466 (when (and (/= (point) opoint) (outline-on-heading-p t))
23467 (while (and (> (funcall outline-level) level)
23468 (not (bobp)))
23469 (outline-previous-heading))
23470 (unless (< (funcall outline-level) level)
23471 (point)))))
23473 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23474 "Goto to the end of a subtree."
23475 ;; This contains an exact copy of the original function, but it uses
23476 ;; `org-back-to-heading', to make it work also in invisible
23477 ;; trees. And is uses an invisible-ok argument.
23478 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23479 ;; Furthermore, when used inside Org, finding the end of a large subtree
23480 ;; with many children and grandchildren etc, this can be much faster
23481 ;; than the outline version.
23482 (org-back-to-heading invisible-ok)
23483 (let ((first t)
23484 (level (funcall outline-level)))
23485 (if (and (derived-mode-p 'org-mode) (< level 1000))
23486 ;; A true heading (not a plain list item), in Org
23487 ;; This means we can easily find the end by looking
23488 ;; only for the right number of stars. Using a regexp to do
23489 ;; this is so much faster than using a Lisp loop.
23490 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23491 (forward-char 1)
23492 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23493 ;; something else, do it the slow way
23494 (while (and (not (eobp))
23495 (or first (> (funcall outline-level) level)))
23496 (setq first nil)
23497 (outline-next-heading)))
23498 (unless to-heading
23499 (when (memq (preceding-char) '(?\n ?\^M))
23500 ;; Go to end of line before heading
23501 (forward-char -1)
23502 (when (memq (preceding-char) '(?\n ?\^M))
23503 ;; leave blank line before heading
23504 (forward-char -1)))))
23505 (point))
23507 (defun org-end-of-meta-data (&optional full)
23508 "Skip planning line and properties drawer in current entry.
23509 When optional argument FULL is non-nil, also skip empty lines,
23510 clocking lines and regular drawers at the beginning of the
23511 entry."
23512 (org-back-to-heading t)
23513 (forward-line)
23514 (when (looking-at-p org-planning-line-re) (forward-line))
23515 (when (looking-at org-property-drawer-re)
23516 (goto-char (match-end 0))
23517 (forward-line))
23518 (when (and full (not (org-at-heading-p)))
23519 (catch 'exit
23520 (let ((end (save-excursion (outline-next-heading) (point)))
23521 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23522 (while (not (eobp))
23523 (cond ((looking-at-p org-drawer-regexp)
23524 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23525 (forward-line)
23526 (throw 'exit t)))
23527 ((looking-at-p re) (forward-line))
23528 (t (throw 'exit t))))))))
23530 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23531 "Move forward to the ARG'th subheading at same level as this one.
23532 Stop at the first and last subheadings of a superior heading.
23533 Normally this only looks at visible headings, but when INVISIBLE-OK is
23534 non-nil it will also look at invisible ones."
23535 (interactive "p")
23536 (let ((backward? (and arg (< arg 0))))
23537 (if (org-before-first-heading-p)
23538 (if backward? (goto-char (point-min)) (outline-next-heading))
23539 (org-back-to-heading invisible-ok)
23540 (unless backward? (end-of-line)) ;do not match current headline
23541 (let ((level (- (match-end 0) (match-beginning 0) 1))
23542 (f (if backward? #'re-search-backward #'re-search-forward))
23543 (count (if arg (abs arg) 1))
23544 (result (point)))
23545 (while (and (> count 0)
23546 (funcall f org-outline-regexp-bol nil 'move))
23547 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23548 (cond ((< l level) (setq count 0))
23549 ((and (= l level)
23550 (or invisible-ok
23551 (not (org-invisible-p
23552 (line-beginning-position)))))
23553 (cl-decf count)
23554 (when (= l level) (setq result (point)))))))
23555 (goto-char result))
23556 (beginning-of-line))))
23558 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23559 "Move backward to the ARG'th subheading at same level as this one.
23560 Stop at the first and last subheadings of a superior heading."
23561 (interactive "p")
23562 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23564 (defun org-next-visible-heading (arg)
23565 "Move to the next visible heading.
23567 This function wraps `outline-next-visible-heading' with
23568 `org-with-limited-levels' in order to skip over inline tasks and
23569 respect customization of `org-odd-levels-only'."
23570 (interactive "p")
23571 (org-with-limited-levels
23572 (outline-next-visible-heading arg)))
23574 (defun org-previous-visible-heading (arg)
23575 "Move to the previous visible heading.
23577 This function wraps `outline-previous-visible-heading' with
23578 `org-with-limited-levels' in order to skip over inline tasks and
23579 respect customization of `org-odd-levels-only'."
23580 (interactive "p")
23581 (org-with-limited-levels
23582 (outline-previous-visible-heading arg)))
23584 (defun org-next-block (arg &optional backward block-regexp)
23585 "Jump to the next block.
23587 With a prefix argument ARG, jump forward ARG many blocks.
23589 When BACKWARD is non-nil, jump to the previous block.
23591 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23592 Match data is set according to this regexp when the function
23593 returns.
23595 Return point at beginning of the opening line of found block.
23596 Throw an error if no block is found."
23597 (interactive "p")
23598 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23599 (case-fold-search t)
23600 (search-fn (if backward #'re-search-backward #'re-search-forward))
23601 (count (or arg 1))
23602 (origin (point))
23603 last-element)
23604 (if backward (beginning-of-line) (end-of-line))
23605 (while (and (> count 0) (funcall search-fn re nil t))
23606 (let ((element (save-excursion
23607 (goto-char (match-beginning 0))
23608 (save-match-data (org-element-at-point)))))
23609 (when (and (memq (org-element-type element)
23610 '(center-block comment-block dynamic-block
23611 example-block export-block quote-block
23612 special-block src-block verse-block))
23613 (<= (match-beginning 0)
23614 (org-element-property :post-affiliated element)))
23615 (setq last-element element)
23616 (cl-decf count))))
23617 (if (= count 0)
23618 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23619 (save-match-data (org-show-context)))
23620 (goto-char origin)
23621 (user-error "No %s code blocks" (if backward "previous" "further")))))
23623 (defun org-previous-block (arg &optional block-regexp)
23624 "Jump to the previous block.
23625 With a prefix argument ARG, jump backward ARG many source blocks.
23626 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23627 (interactive "p")
23628 (org-next-block arg t block-regexp))
23630 (defun org-forward-paragraph ()
23631 "Move forward to beginning of next paragraph or equivalent.
23633 The function moves point to the beginning of the next visible
23634 structural element, which can be a paragraph, a table, a list
23635 item, etc. It also provides some special moves for convenience:
23637 - On an affiliated keyword, jump to the beginning of the
23638 relative element.
23639 - On an item or a footnote definition, move to the second
23640 element inside, if any.
23641 - On a table or a property drawer, jump after it.
23642 - On a verse or source block, stop after blank lines."
23643 (interactive)
23644 (unless (eobp)
23645 (let* ((deactivate-mark nil)
23646 (element (org-element-at-point))
23647 (type (org-element-type element))
23648 (post-affiliated (org-element-property :post-affiliated element))
23649 (contents-begin (org-element-property :contents-begin element))
23650 (contents-end (org-element-property :contents-end element))
23651 (end (let ((end (org-element-property :end element)) (parent element))
23652 (while (and (setq parent (org-element-property :parent parent))
23653 (= (org-element-property :contents-end parent) end))
23654 (setq end (org-element-property :end parent)))
23655 end)))
23656 (cond ((not element)
23657 (skip-chars-forward " \r\t\n")
23658 (or (eobp) (beginning-of-line)))
23659 ;; On affiliated keywords, move to element's beginning.
23660 ((< (point) post-affiliated)
23661 (goto-char post-affiliated))
23662 ;; At a table row, move to the end of the table. Similarly,
23663 ;; at a node property, move to the end of the property
23664 ;; drawer.
23665 ((memq type '(node-property table-row))
23666 (goto-char (org-element-property
23667 :end (org-element-property :parent element))))
23668 ((memq type '(property-drawer table)) (goto-char end))
23669 ;; Consider blank lines as separators in verse and source
23670 ;; blocks to ease editing.
23671 ((memq type '(src-block verse-block))
23672 (when (eq type 'src-block)
23673 (setq contents-end
23674 (save-excursion (goto-char end)
23675 (skip-chars-backward " \r\t\n")
23676 (line-beginning-position))))
23677 (beginning-of-line)
23678 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23679 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23680 (goto-char end)
23681 (skip-chars-forward " \r\t\n")
23682 (if (= (point) contents-end) (goto-char end)
23683 (beginning-of-line))))
23684 ;; With no contents, just skip element.
23685 ((not contents-begin) (goto-char end))
23686 ;; If contents are invisible, skip the element altogether.
23687 ((org-invisible-p (line-end-position))
23688 (cl-case type
23689 (headline
23690 (org-with-limited-levels (outline-next-visible-heading 1)))
23691 ;; At a plain list, make sure we move to the next item
23692 ;; instead of skipping the whole list.
23693 (plain-list (forward-char)
23694 (org-forward-paragraph))
23695 (otherwise (goto-char end))))
23696 ((>= (point) contents-end) (goto-char end))
23697 ((>= (point) contents-begin)
23698 ;; This can only happen on paragraphs and plain lists.
23699 (cl-case type
23700 (paragraph (goto-char end))
23701 ;; At a plain list, try to move to second element in
23702 ;; first item, if possible.
23703 (plain-list (end-of-line)
23704 (org-forward-paragraph))))
23705 ;; When contents start on the middle of a line (e.g. in
23706 ;; items and footnote definitions), try to reach first
23707 ;; element starting after current line.
23708 ((> (line-end-position) contents-begin)
23709 (end-of-line)
23710 (org-forward-paragraph))
23711 (t (goto-char contents-begin))))))
23713 (defun org-backward-paragraph ()
23714 "Move backward to start of previous paragraph or equivalent.
23716 The function moves point to the beginning of the current
23717 structural element, which can be a paragraph, a table, a list
23718 item, etc., or to the beginning of the previous visible one if
23719 point is already there. It also provides some special moves for
23720 convenience:
23722 - On an affiliated keyword, jump to the first one.
23723 - On a table or a property drawer, move to its beginning.
23724 - On comment, example, export, src and verse blocks, stop
23725 before blank lines."
23726 (interactive)
23727 (unless (bobp)
23728 (let* ((deactivate-mark nil)
23729 (element (org-element-at-point))
23730 (type (org-element-type element))
23731 (contents-end (org-element-property :contents-end element))
23732 (post-affiliated (org-element-property :post-affiliated element))
23733 (begin (org-element-property :begin element))
23734 (special? ;blocks handled specially
23735 (memq type '(comment-block example-block export-block src-block
23736 verse-block)))
23737 (contents-begin
23738 (if special?
23739 ;; These types have no proper contents. Fake line
23740 ;; below the block opening line as contents beginning.
23741 (save-excursion (goto-char begin) (line-beginning-position 2))
23742 (org-element-property :contents-begin element))))
23743 (cond
23744 ((not element) (goto-char (point-min)))
23745 ((= (point) begin)
23746 (backward-char)
23747 (org-backward-paragraph))
23748 ((<= (point) post-affiliated) (goto-char begin))
23749 ;; Special behavior: on a table or a property drawer, move to
23750 ;; its beginning.
23751 ((memq type '(node-property table-row))
23752 (goto-char (org-element-property
23753 :post-affiliated (org-element-property :parent element))))
23754 (special?
23755 (if (<= (point) contents-begin) (goto-char post-affiliated)
23756 ;; Inside a verse block, see blank lines as paragraph
23757 ;; separators.
23758 (let ((origin (point)))
23759 (skip-chars-backward " \r\t\n" contents-begin)
23760 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23761 (skip-chars-forward " \r\t\n" origin)
23762 (if (= (point) origin) (goto-char contents-begin)
23763 (beginning-of-line))))))
23764 ((eq type 'paragraph) (goto-char contents-begin)
23765 ;; When at first paragraph in an item or a footnote definition,
23766 ;; move directly to beginning of line.
23767 (let ((parent-contents
23768 (org-element-property
23769 :contents-begin (org-element-property :parent element))))
23770 (when (and parent-contents (= parent-contents contents-begin))
23771 (beginning-of-line))))
23772 ;; At the end of a greater element, move to the beginning of
23773 ;; the last element within.
23774 ((and contents-end (>= (point) contents-end))
23775 (goto-char (1- contents-end))
23776 (org-backward-paragraph))
23777 (t (goto-char (or post-affiliated begin))))
23778 ;; Ensure we never leave point invisible.
23779 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23781 (defun org-forward-element ()
23782 "Move forward by one element.
23783 Move to the next element at the same level, when possible."
23784 (interactive)
23785 (cond ((eobp) (user-error "Cannot move further down"))
23786 ((org-with-limited-levels (org-at-heading-p))
23787 (let ((origin (point)))
23788 (goto-char (org-end-of-subtree nil t))
23789 (unless (org-with-limited-levels (org-at-heading-p))
23790 (goto-char origin)
23791 (user-error "Cannot move further down"))))
23793 (let* ((elem (org-element-at-point))
23794 (end (org-element-property :end elem))
23795 (parent (org-element-property :parent elem)))
23796 (cond ((and parent (= (org-element-property :contents-end parent) end))
23797 (goto-char (org-element-property :end parent)))
23798 ((integer-or-marker-p end) (goto-char end))
23799 (t (message "No element at point")))))))
23801 (defun org-backward-element ()
23802 "Move backward by one element.
23803 Move to the previous element at the same level, when possible."
23804 (interactive)
23805 (cond ((bobp) (user-error "Cannot move further up"))
23806 ((org-with-limited-levels (org-at-heading-p))
23807 ;; At a headline, move to the previous one, if any, or stay
23808 ;; here.
23809 (let ((origin (point)))
23810 (org-with-limited-levels (org-backward-heading-same-level 1))
23811 ;; When current headline has no sibling above, move to its
23812 ;; parent.
23813 (when (= (point) origin)
23814 (or (org-with-limited-levels (org-up-heading-safe))
23815 (progn (goto-char origin)
23816 (user-error "Cannot move further up"))))))
23818 (let* ((elem (org-element-at-point))
23819 (beg (org-element-property :begin elem)))
23820 (cond
23821 ;; Move to beginning of current element if point isn't
23822 ;; there already.
23823 ((null beg) (message "No element at point"))
23824 ((/= (point) beg) (goto-char beg))
23825 (t (goto-char beg)
23826 (skip-chars-backward " \r\t\n")
23827 (unless (bobp)
23828 (let ((prev (org-element-at-point)))
23829 (goto-char (org-element-property :begin prev))
23830 (while (and (setq prev (org-element-property :parent prev))
23831 (<= (org-element-property :end prev) beg))
23832 (goto-char (org-element-property :begin prev)))))))))))
23834 (defun org-up-element ()
23835 "Move to upper element."
23836 (interactive)
23837 (if (org-with-limited-levels (org-at-heading-p))
23838 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23839 (let* ((elem (org-element-at-point))
23840 (parent (org-element-property :parent elem)))
23841 (if parent (goto-char (org-element-property :begin parent))
23842 (if (org-with-limited-levels (org-before-first-heading-p))
23843 (user-error "No surrounding element")
23844 (org-with-limited-levels (org-back-to-heading)))))))
23846 (defun org-down-element ()
23847 "Move to inner element."
23848 (interactive)
23849 (let ((element (org-element-at-point)))
23850 (cond
23851 ((memq (org-element-type element) '(plain-list table))
23852 (goto-char (org-element-property :contents-begin element))
23853 (forward-char))
23854 ((memq (org-element-type element) org-element-greater-elements)
23855 ;; If contents are hidden, first disclose them.
23856 (when (org-invisible-p (line-end-position)) (org-cycle))
23857 (goto-char (or (org-element-property :contents-begin element)
23858 (user-error "No content for this element"))))
23859 (t (user-error "No inner element")))))
23861 (defun org-drag-element-backward ()
23862 "Move backward element at point."
23863 (interactive)
23864 (let ((elem (or (org-element-at-point)
23865 (user-error "No element at point"))))
23866 (if (eq (org-element-type elem) 'headline)
23867 ;; Preserve point when moving a whole tree, even if point was
23868 ;; on blank lines below the headline.
23869 (let ((offset (skip-chars-backward " \t\n")))
23870 (unwind-protect (org-move-subtree-up)
23871 (forward-char (- offset))))
23872 (let ((prev-elem
23873 (save-excursion
23874 (goto-char (org-element-property :begin elem))
23875 (skip-chars-backward " \r\t\n")
23876 (unless (bobp)
23877 (let* ((beg (org-element-property :begin elem))
23878 (prev (org-element-at-point))
23879 (up prev))
23880 (while (and (setq up (org-element-property :parent up))
23881 (<= (org-element-property :end up) beg))
23882 (setq prev up))
23883 prev)))))
23884 ;; Error out if no previous element or previous element is
23885 ;; a parent of the current one.
23886 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23887 (user-error "Cannot drag element backward")
23888 (let ((pos (point)))
23889 (org-element-swap-A-B prev-elem elem)
23890 (goto-char (+ (org-element-property :begin prev-elem)
23891 (- pos (org-element-property :begin elem))))))))))
23893 (defun org-drag-element-forward ()
23894 "Move forward element at point."
23895 (interactive)
23896 (let* ((pos (point))
23897 (elem (or (org-element-at-point)
23898 (user-error "No element at point"))))
23899 (when (= (point-max) (org-element-property :end elem))
23900 (user-error "Cannot drag element forward"))
23901 (goto-char (org-element-property :end elem))
23902 (let ((next-elem (org-element-at-point)))
23903 (when (or (org-element-nested-p elem next-elem)
23904 (and (eq (org-element-type next-elem) 'headline)
23905 (not (eq (org-element-type elem) 'headline))))
23906 (goto-char pos)
23907 (user-error "Cannot drag element forward"))
23908 ;; Compute new position of point: it's shifted by NEXT-ELEM
23909 ;; body's length (without final blanks) and by the length of
23910 ;; blanks between ELEM and NEXT-ELEM.
23911 (let ((size-next (- (save-excursion
23912 (goto-char (org-element-property :end next-elem))
23913 (skip-chars-backward " \r\t\n")
23914 (forward-line)
23915 ;; Small correction if buffer doesn't end
23916 ;; with a newline character.
23917 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23918 (org-element-property :begin next-elem)))
23919 (size-blank (- (org-element-property :end elem)
23920 (save-excursion
23921 (goto-char (org-element-property :end elem))
23922 (skip-chars-backward " \r\t\n")
23923 (forward-line)
23924 (point)))))
23925 (org-element-swap-A-B elem next-elem)
23926 (goto-char (+ pos size-next size-blank))))))
23928 (defun org-drag-line-forward (arg)
23929 "Drag the line at point ARG lines forward."
23930 (interactive "p")
23931 (dotimes (_ (abs arg))
23932 (let ((c (current-column)))
23933 (if (< 0 arg)
23934 (progn
23935 (beginning-of-line 2)
23936 (transpose-lines 1)
23937 (beginning-of-line 0))
23938 (transpose-lines 1)
23939 (beginning-of-line -1))
23940 (org-move-to-column c))))
23942 (defun org-drag-line-backward (arg)
23943 "Drag the line at point ARG lines backward."
23944 (interactive "p")
23945 (org-drag-line-forward (- arg)))
23947 (defun org-mark-element ()
23948 "Put point at beginning of this element, mark at end.
23950 Interactively, if this command is repeated or (in Transient Mark
23951 mode) if the mark is active, it marks the next element after the
23952 ones already marked."
23953 (interactive)
23954 (let (deactivate-mark)
23955 (if (and (called-interactively-p 'any)
23956 (or (and (eq last-command this-command) (mark t))
23957 (and transient-mark-mode mark-active)))
23958 (set-mark
23959 (save-excursion
23960 (goto-char (mark))
23961 (goto-char (org-element-property :end (org-element-at-point)))))
23962 (let ((element (org-element-at-point)))
23963 (end-of-line)
23964 (push-mark (org-element-property :end element) t t)
23965 (goto-char (org-element-property :begin element))))))
23967 (defun org-narrow-to-element ()
23968 "Narrow buffer to current element."
23969 (interactive)
23970 (let ((elem (org-element-at-point)))
23971 (cond
23972 ((eq (car elem) 'headline)
23973 (narrow-to-region
23974 (org-element-property :begin elem)
23975 (org-element-property :end elem)))
23976 ((memq (car elem) org-element-greater-elements)
23977 (narrow-to-region
23978 (org-element-property :contents-begin elem)
23979 (org-element-property :contents-end elem)))
23981 (narrow-to-region
23982 (org-element-property :begin elem)
23983 (org-element-property :end elem))))))
23985 (defun org-transpose-element ()
23986 "Transpose current and previous elements, keeping blank lines between.
23987 Point is moved after both elements."
23988 (interactive)
23989 (org-skip-whitespace)
23990 (let ((end (org-element-property :end (org-element-at-point))))
23991 (org-drag-element-backward)
23992 (goto-char end)))
23994 (defun org-unindent-buffer ()
23995 "Un-indent the visible part of the buffer.
23996 Relative indentation (between items, inside blocks, etc.) isn't
23997 modified."
23998 (interactive)
23999 (unless (eq major-mode 'org-mode)
24000 (user-error "Cannot un-indent a buffer not in Org mode"))
24001 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24002 (unindent-tree
24003 (lambda (contents)
24004 (dolist (element (reverse contents))
24005 (if (memq (org-element-type element) '(headline section))
24006 (funcall unindent-tree (org-element-contents element))
24007 (save-excursion
24008 (save-restriction
24009 (narrow-to-region
24010 (org-element-property :begin element)
24011 (org-element-property :end element))
24012 (org-do-remove-indentation))))))))
24013 (funcall unindent-tree (org-element-contents parse-tree))))
24015 (defun org-show-children (&optional level)
24016 "Show all direct subheadings of this heading.
24017 Prefix arg LEVEL is how many levels below the current level
24018 should be shown. Default is enough to cause the following
24019 heading to appear."
24020 (interactive "p")
24021 ;; If `orgstruct-mode' is active, use the slower version.
24022 (if orgstruct-mode (call-interactively #'outline-show-children)
24023 (save-excursion
24024 (org-back-to-heading t)
24025 (let* ((current-level (funcall outline-level))
24026 (max-level (org-get-valid-level
24027 current-level
24028 (if level (prefix-numeric-value level) 1)))
24029 (end (save-excursion (org-end-of-subtree t t)))
24030 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24031 (past-first-child nil)
24032 ;; Make sure to skip inlinetasks.
24033 (re (format regexp-fmt
24034 current-level
24035 (cond
24036 ((not (featurep 'org-inlinetask)) "")
24037 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24039 (t (1- org-inlinetask-min-level))))))
24040 ;; Display parent heading.
24041 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24042 (forward-line)
24043 ;; Display children. First child may be deeper than expected
24044 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24045 ;; MAX-LEVEL accordingly.
24046 (while (re-search-forward re end t)
24047 (unless past-first-child
24048 (setq re (format regexp-fmt
24049 current-level
24050 (max (funcall outline-level) max-level)))
24051 (setq past-first-child t))
24052 (outline-flag-region
24053 (line-end-position 0) (line-end-position) nil))))))
24055 (defun org-show-subtree ()
24056 "Show everything after this heading at deeper levels."
24057 (interactive)
24058 (outline-flag-region
24059 (point)
24060 (save-excursion
24061 (org-end-of-subtree t t))
24062 nil))
24064 (defun org-show-entry ()
24065 "Show the body directly following this heading.
24066 Show the heading too, if it is currently invisible."
24067 (interactive)
24068 (save-excursion
24069 (ignore-errors
24070 (org-back-to-heading t)
24071 (outline-flag-region
24072 (max (point-min) (1- (point)))
24073 (save-excursion
24074 (if (re-search-forward
24075 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24076 (match-beginning 1)
24077 (point-max)))
24078 nil)
24079 (org-cycle-hide-drawers 'children))))
24081 (defun org-make-options-regexp (kwds &optional extra)
24082 "Make a regular expression for keyword lines.
24083 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24084 when non-nil, is a regexp matching keywords names."
24085 (concat "^[ \t]*#\\+\\("
24086 (regexp-opt kwds)
24087 (and extra (concat (and kwds "\\|") extra))
24088 "\\):[ \t]*\\(.*\\)"))
24090 ;;;; Finish up
24092 (provide 'org)
24094 (run-hooks 'org-load-hook)
24096 ;;; org.el ends here