Remove reference to Message mode
[org-mode/org-tableheadings.git] / lisp / org.el
bloba09c82ce1a73e53e2e5a2db4fe9855fd21c55462
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'.
96 (defvar org-outline-regexp "\\*+ "
97 "Regexp to match Org headlines.")
99 (defvar org-outline-regexp-bol "^\\*+ "
100 "Regexp to match Org headlines.
101 This is similar to `org-outline-regexp' but additionally makes
102 sure that we are at the beginning of the line.")
104 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
105 "Matches a headline, putting stars and text into groups.
106 Stars are put in group 1 and the trimmed body in group 2.")
108 (declare-function calendar-check-holidays "holidays" (date))
109 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
110 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
111 (declare-function org-add-archive-files "org-archive" (files))
112 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
113 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
114 (declare-function org-agenda-redo "org-agenda" (&optional all))
115 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
116 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
117 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
120 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
121 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
125 (declare-function org-clock-update-time-maybe "org-clock" ())
126 (declare-function org-clocking-buffer "org-clock" ())
127 (declare-function org-clocktable-shift "org-clock" (dir n))
128 (declare-function
129 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-link-parser "org-element" ())
139 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
140 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
141 (declare-function org-element-property "org-element" (property element))
142 (declare-function org-element-put-property "org-element" (element property value))
143 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
144 (declare-function org-element-type "org-element" (element))
145 (declare-function org-element-update-syntax "org-element" ())
146 (declare-function org-id-find-id-file "org-id" (id))
147 (declare-function org-id-get-create "org-id" (&optional force))
148 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
149 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
150 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
151 (declare-function org-plot/gnuplot "org-plot" (&optional params))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
158 (declare-function org-table-cut-region "org-table" (beg end))
159 (declare-function org-table-edit-field "org-table" (arg))
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function org-table-next-row "org-table" ())
167 (declare-function org-table-paste-rectangle "org-table" ())
168 (declare-function org-table-recalculate "org-table" (&optional all noalign))
169 (declare-function
170 org-table-sort-lines "org-table"
171 (&optional with-case sorting-type getkey-func compare-func interactive?))
172 (declare-function org-table-shrink "org-table" (&optional begin end))
173 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
174 (declare-function org-table-wrap-region "org-table" (arg))
175 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
176 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
177 (declare-function orgtbl-mode "org-table" (&optional arg))
178 (declare-function org-export-get-backend "ox" (name))
179 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
180 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
182 (defvar ffap-url-regexp)
183 (defvar org-element-paragraph-separate)
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the Org file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Ebnf2ps" ebnf2ps)
258 (const :tag "Emacs Lisp" emacs-lisp)
259 (const :tag "Forth" forth)
260 (const :tag "Fortran" fortran)
261 (const :tag "Gnuplot" gnuplot)
262 (const :tag "Haskell" haskell)
263 (const :tag "hledger" hledger)
264 (const :tag "IO" io)
265 (const :tag "J" J)
266 (const :tag "Java" java)
267 (const :tag "Javascript" js)
268 (const :tag "LaTeX" latex)
269 (const :tag "Ledger" ledger)
270 (const :tag "Lilypond" lilypond)
271 (const :tag "Lisp" lisp)
272 (const :tag "Makefile" makefile)
273 (const :tag "Maxima" maxima)
274 (const :tag "Matlab" matlab)
275 (const :tag "Mscgen" mscgen)
276 (const :tag "Ocaml" ocaml)
277 (const :tag "Octave" octave)
278 (const :tag "Org" org)
279 (const :tag "Perl" perl)
280 (const :tag "Pico Lisp" picolisp)
281 (const :tag "PlantUML" plantuml)
282 (const :tag "Python" python)
283 (const :tag "Ruby" ruby)
284 (const :tag "Sass" sass)
285 (const :tag "Scala" scala)
286 (const :tag "Scheme" scheme)
287 (const :tag "Screen" screen)
288 (const :tag "Shell Script" shell)
289 (const :tag "Shen" shen)
290 (const :tag "Sql" sql)
291 (const :tag "Sqlite" sqlite)
292 (const :tag "Stan" stan)
293 (const :tag "Vala" vala))
294 :value-type (boolean :tag "Activate" :value t)))
296 ;;;; Customization variables
297 (defcustom org-clone-delete-id nil
298 "Remove ID property of clones of a subtree.
299 When non-nil, clones of a subtree don't inherit the ID property.
300 Otherwise they inherit the ID property with a new unique
301 identifier."
302 :type 'boolean
303 :version "24.1"
304 :group 'org-id)
306 ;;; Version
307 (org-check-version)
309 ;;;###autoload
310 (defun org-version (&optional here full message)
311 "Show the Org version.
312 Interactively, or when MESSAGE is non-nil, show it in echo area.
313 With prefix argument, or when HERE is non-nil, insert it at point.
314 In non-interactive uses, a reduced version string is output unless
315 FULL is given."
316 (interactive (list current-prefix-arg t (not current-prefix-arg)))
317 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
318 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
319 (load-suffixes (list ".el"))
320 (org-install-dir
321 (ignore-errors (org-find-library-dir "org-loaddefs"))))
322 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
323 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
324 (let* ((load-suffixes save-load-suffixes)
325 (release (org-release))
326 (git-version (org-git-version))
327 (version (format "Org mode version %s (%s @ %s)"
328 release
329 git-version
330 (if org-install-dir
331 (if (string= org-dir org-install-dir)
332 org-install-dir
333 (concat "mixed installation! "
334 org-install-dir
335 " and "
336 org-dir))
337 "org-loaddefs.el can not be found!")))
338 (version1 (if full version release)))
339 (when here (insert version1))
340 (when message (message "%s" version1))
341 version1)))
343 (defconst org-version (org-version))
346 ;;; Syntax Constants
348 ;;;; Block
350 (defconst org-block-regexp
351 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
352 "Regular expression for hiding blocks.")
354 (defconst org-dblock-start-re
355 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
356 "Matches the start line of a dynamic block, with parameters.")
358 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
359 "Matches the end of a dynamic block.")
361 ;;;; Clock and Planning
363 (defconst org-clock-string "CLOCK:"
364 "String used as prefix for timestamps clocking work hours on an item.")
366 (defvar org-closed-string "CLOSED:"
367 "String used as the prefix for timestamps logging closing a TODO entry.")
369 (defvar org-deadline-string "DEADLINE:"
370 "String to mark deadline entries.
371 \\<org-mode-map>
372 A deadline is this string, followed by a time stamp. It must be
373 a word, terminated by a colon. You can insert a schedule keyword
374 and a timestamp with `\\[org-deadline]'.")
376 (defvar org-scheduled-string "SCHEDULED:"
377 "String to mark scheduled TODO entries.
378 \\<org-mode-map>
379 A schedule is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-schedule]'.")
383 (defconst org-ds-keyword-length
384 (+ 2
385 (apply #'max
386 (mapcar #'length
387 (list org-deadline-string org-scheduled-string
388 org-clock-string org-closed-string))))
389 "Maximum length of the DEADLINE and SCHEDULED keywords.")
391 (defconst org-planning-line-re
392 (concat "^[ \t]*"
393 (regexp-opt
394 (list org-closed-string org-deadline-string org-scheduled-string)
396 "Matches a line with planning info.
397 Matched keyword is in group 1.")
399 (defconst org-clock-line-re
400 (concat "^[ \t]*" org-clock-string)
401 "Matches a line with clock info.")
403 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
404 "Matches the DEADLINE keyword.")
406 (defconst org-deadline-time-regexp
407 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
408 "Matches the DEADLINE keyword together with a time stamp.")
410 (defconst org-deadline-time-hour-regexp
411 (concat "\\<" org-deadline-string
412 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
413 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
415 (defconst org-deadline-line-regexp
416 (concat "\\<\\(" org-deadline-string "\\).*")
417 "Matches the DEADLINE keyword and the rest of the line.")
419 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
420 "Matches the SCHEDULED keyword.")
422 (defconst org-scheduled-time-regexp
423 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
424 "Matches the SCHEDULED keyword together with a time stamp.")
426 (defconst org-scheduled-time-hour-regexp
427 (concat "\\<" org-scheduled-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
431 (defconst org-closed-time-regexp
432 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
433 "Matches the CLOSED keyword together with a time stamp.")
435 (defconst org-keyword-time-regexp
436 (concat "\\<"
437 (regexp-opt
438 (list org-scheduled-string org-deadline-string org-closed-string
439 org-clock-string)
441 " *[[<]\\([^]>]+\\)[]>]")
442 "Matches any of the 4 keywords, together with the time stamp.")
444 (defconst org-keyword-time-not-clock-regexp
445 (concat
446 "\\<"
447 (regexp-opt
448 (list org-scheduled-string org-deadline-string org-closed-string) t)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 3 keywords, together with the time stamp.")
452 (defconst org-maybe-keyword-time-regexp
453 (concat "\\(\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string
456 org-clock-string)
458 "\\)?"
459 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
460 "\\|"
461 "<%%([^\r\n>]*>\\)")
462 "Matches a timestamp, possibly preceded by a keyword.")
464 (defconst org-all-time-keywords
465 (mapcar (lambda (w) (substring w 0 -1))
466 (list org-scheduled-string org-deadline-string
467 org-clock-string org-closed-string))
468 "List of time keywords.")
470 ;;;; Drawer
472 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
473 "Matches first or last line of a hidden block.
474 Group 1 contains drawer's name or \"END\".")
476 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
477 "Regular expression matching the first line of a property drawer.")
479 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
480 "Regular expression matching the last line of a property drawer.")
482 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
483 "Regular expression matching the first line of a clock drawer.")
485 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
486 "Regular expression matching the last line of a clock drawer.")
488 (defconst org-property-drawer-re
489 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
490 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
491 "[ \t]*:END:[ \t]*$")
492 "Matches an entire property drawer.")
494 (defconst org-clock-drawer-re
495 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
496 org-clock-drawer-end-re "\\)\n?")
497 "Matches an entire clock drawer.")
499 ;;;; Headline
501 (defconst org-heading-keyword-regexp-format
502 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
503 "Printf format for a regexp matching a headline with some keyword.
504 This regexp will match the headline of any node which has the
505 exact keyword that is put into the format. The keyword isn't in
506 any group by default, but the stars and the body are.")
508 (defconst org-heading-keyword-maybe-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline, possibly with some keyword.
511 This regexp can match any headline with the specified keyword, or
512 without a keyword. The keyword isn't in any group by default,
513 but the stars and the body are.")
515 (defconst org-archive-tag "ARCHIVE"
516 "The tag that marks a subtree as archived.
517 An archived subtree does not open during visibility cycling, and does
518 not contribute to the agenda listings.")
520 (eval-and-compile
521 (defconst org-comment-string "COMMENT"
522 "Entries starting with this keyword will never be exported.
523 \\<org-mode-map>
524 An entry can be toggled between COMMENT and normal with
525 `\\[org-toggle-comment]'."))
528 ;;;; LaTeX Environments and Fragments
530 (defconst org-latex-regexps
531 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
532 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
533 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
534 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
535 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
536 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
537 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
538 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
539 "Regular expressions for matching embedded LaTeX.")
541 ;;;; Node Property
543 (defconst org-effort-property "Effort"
544 "The property that is being used to keep track of effort estimates.
545 Effort estimates given in this property need to have the format H:MM.")
547 ;;;; Table
549 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
550 "Detect an org-type or table-type table.")
552 (defconst org-table-line-regexp "^[ \t]*|"
553 "Detect an org-type table line.")
555 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
556 "Detect an org-type table line.")
558 (defconst org-table-hline-regexp "^[ \t]*|-"
559 "Detect an org-type table hline.")
561 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
562 "Detect a table-type table hline.")
564 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
565 "Detect the first line outside a table when searching from within it.
566 This works for both table types.")
568 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
569 "Detect a #+TBLFM line.")
571 ;;;; Timestamp
573 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
574 "Regular expression for fast time stamp matching.")
576 (defconst org-ts-regexp-inactive
577 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
578 "Regular expression for fast inactive time stamp matching.")
580 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp0
584 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
585 "Regular expression matching time strings for analysis.
586 This one does not require the space after the date, so it can be used
587 on a string that terminates immediately after the date.")
589 (defconst org-ts-regexp1 "\\(\\([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.")
592 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
593 "Regular expression matching time stamps, with groups.")
595 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
596 "Regular expression matching time stamps (also [..]), with groups.")
598 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tr-regexp-both
602 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
606 org-ts-regexp "\\)?")
607 "Regular expression matching a time stamp or time stamp range.")
609 (defconst org-tsr-regexp-both
610 (concat org-ts-regexp-both "\\(--?-?"
611 org-ts-regexp-both "\\)?")
612 "Regular expression matching a time stamp or time stamp range.
613 The time stamps may be either active or inactive.")
615 (defconst org-repeat-re
616 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
617 "Regular expression for specifying repeated events.
618 After a match, group 1 contains the repeat expression.")
620 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
621 "Formats for `format-time-string' which are used for time stamps.")
624 ;;; The custom variables
626 (defgroup org nil
627 "Outline-based notes management and organizer."
628 :tag "Org"
629 :group 'outlines
630 :group 'calendar)
632 (defcustom org-mode-hook nil
633 "Mode hook for Org mode, run after the mode was turned on."
634 :group 'org
635 :type 'hook)
637 (defcustom org-load-hook nil
638 "Hook that is run after org.el has been loaded."
639 :group 'org
640 :type 'hook)
642 (defcustom org-log-buffer-setup-hook nil
643 "Hook that is run after an Org log buffer is created."
644 :group 'org
645 :version "24.1"
646 :type 'hook)
648 (defvar org-modules) ; defined below
649 (defvar org-modules-loaded nil
650 "Have the modules been loaded already?")
652 (defun org-load-modules-maybe (&optional force)
653 "Load all extensions listed in `org-modules'."
654 (when (or force (not org-modules-loaded))
655 (dolist (ext org-modules)
656 (condition-case nil (require ext)
657 (error (message "Problems while trying to load feature `%s'" ext))))
658 (setq org-modules-loaded t)))
660 (defun org-set-modules (var value)
661 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
662 (set var value)
663 (when (featurep 'org)
664 (org-load-modules-maybe 'force)
665 (org-element-cache-reset 'all)))
667 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
668 "Modules that should always be loaded together with org.el.
670 If a description starts with <C>, the file is not part of Emacs
671 and loading it will require that you have downloaded and properly
672 installed the Org mode distribution.
674 You can also use this system to load external packages (i.e. neither Org
675 core modules, nor modules from the CONTRIB directory). Just add symbols
676 to the end of the list. If the package is called org-xyz.el, then you need
677 to add the symbol `xyz', and the package must have a call to:
679 (provide \\='org-xyz)
681 For export specific modules, see also `org-export-backends'."
682 :group 'org
683 :set 'org-set-modules
684 :version "24.4"
685 :package-version '(Org . "8.0")
686 :type
687 '(set :greedy t
688 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
689 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
690 (const :tag " crypt: Encryption of subtrees" org-crypt)
691 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
692 (const :tag " docview: Links to doc-view buffers" org-docview)
693 (const :tag " eww: Store link to url of eww" org-eww)
694 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
695 (const :tag " habit: Track your consistency with habits" org-habit)
696 (const :tag " id: Global IDs for identifying entries" org-id)
697 (const :tag " info: Links to Info nodes" org-info)
698 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
699 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
700 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
701 (const :tag " mouse: Additional mouse support" org-mouse)
702 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
703 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
704 (const :tag " tempo: Fast completion for structures" org-tempo)
705 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
707 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
708 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
709 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
710 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
711 (const :tag "C collector: Collect properties into tables" org-collector)
712 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
713 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
714 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
715 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
716 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
717 (const :tag "C eval: Include command output as text" org-eval)
718 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
719 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
720 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
721 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
722 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
723 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
724 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
725 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
726 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
727 (const :tag "C man: Support for links to manpages in Org mode" org-man)
728 (const :tag "C mew: Links to Mew folders/messages" org-mew)
729 (const :tag "C mtags: Support for muse-like tags" org-mtags)
730 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
731 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
732 (const :tag "C registry: A registry for Org links" org-registry)
733 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
734 (const :tag "C secretary: Team management with org-mode" org-secretary)
735 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
736 (const :tag "C toc: Table of contents for Org buffer" org-toc)
737 (const :tag "C track: Keep up with Org mode development" org-track)
738 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
739 (const :tag "C vm: Links to VM folders/messages" org-vm)
740 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
741 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
742 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
744 (defvar org-export-registered-backends) ; From ox.el.
745 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
746 (declare-function org-export-backend-name "ox" (backend) t)
747 (defcustom org-export-backends '(ascii html icalendar latex odt)
748 "List of export back-ends that should be always available.
750 If a description starts with <C>, the file is not part of Emacs
751 and loading it will require that you have downloaded and properly
752 installed the Org mode distribution.
754 Unlike to `org-modules', libraries in this list will not be
755 loaded along with Org, but only once the export framework is
756 needed.
758 This variable needs to be set before org.el is loaded. If you
759 need to make a change while Emacs is running, use the customize
760 interface or run the following code, where VAL stands for the new
761 value of the variable, after updating it:
763 (progn
764 (setq org-export-registered-backends
765 (cl-remove-if-not
766 (lambda (backend)
767 (let ((name (org-export-backend-name backend)))
768 (or (memq name val)
769 (catch \\='parentp
770 (dolist (b val)
771 (and (org-export-derived-backend-p b name)
772 (throw \\='parentp t)))))))
773 org-export-registered-backends))
774 (let ((new-list (mapcar #\\='org-export-backend-name
775 org-export-registered-backends)))
776 (dolist (backend val)
777 (cond
778 ((not (load (format \"ox-%s\" backend) t t))
779 (message \"Problems while trying to load export back-end \\=`%s\\='\"
780 backend))
781 ((not (memq backend new-list)) (push backend new-list))))
782 (set-default \\='org-export-backends new-list)))
784 Adding a back-end to this list will also pull the back-end it
785 depends on, if any."
786 :group 'org
787 :group 'org-export
788 :version "26.1"
789 :package-version '(Org . "9.0")
790 :initialize 'custom-initialize-set
791 :set (lambda (var val)
792 (if (not (featurep 'ox)) (set-default var val)
793 ;; Any back-end not required anymore (not present in VAL and not
794 ;; a parent of any back-end in the new value) is removed from the
795 ;; list of registered back-ends.
796 (setq org-export-registered-backends
797 (cl-remove-if-not
798 (lambda (backend)
799 (let ((name (org-export-backend-name backend)))
800 (or (memq name val)
801 (catch 'parentp
802 (dolist (b val)
803 (and (org-export-derived-backend-p b name)
804 (throw 'parentp t)))))))
805 org-export-registered-backends))
806 ;; Now build NEW-LIST of both new back-ends and required
807 ;; parents.
808 (let ((new-list (mapcar #'org-export-backend-name
809 org-export-registered-backends)))
810 (dolist (backend val)
811 (cond
812 ((not (load (format "ox-%s" backend) t t))
813 (message "Problems while trying to load export back-end `%s'"
814 backend))
815 ((not (memq backend new-list)) (push backend new-list))))
816 ;; Set VAR to that list with fixed dependencies.
817 (set-default var new-list))))
818 :type '(set :greedy t
819 (const :tag " ascii Export buffer to ASCII format" ascii)
820 (const :tag " beamer Export buffer to Beamer presentation" beamer)
821 (const :tag " html Export buffer to HTML format" html)
822 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
823 (const :tag " latex Export buffer to LaTeX format" latex)
824 (const :tag " man Export buffer to MAN format" man)
825 (const :tag " md Export buffer to Markdown format" md)
826 (const :tag " odt Export buffer to ODT format" odt)
827 (const :tag " org Export buffer to Org format" org)
828 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
829 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
830 (const :tag "C deck Export buffer to deck.js presentations" deck)
831 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
832 (const :tag "C groff Export buffer to Groff format" groff)
833 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
834 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
835 (const :tag "C s5 Export buffer to s5 presentations" s5)
836 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
838 (eval-after-load 'ox
839 '(dolist (backend org-export-backends)
840 (condition-case nil (require (intern (format "ox-%s" backend)))
841 (error (message "Problems while trying to load export back-end `%s'"
842 backend)))))
844 (defcustom org-support-shift-select nil
845 "Non-nil means make shift-cursor commands select text when possible.
846 \\<org-mode-map>\
848 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
849 start selecting a region, or enlarge regions started in this way.
850 In Org mode, in special contexts, these same keys are used for
851 other purposes, important enough to compete with shift selection.
852 Org tries to balance these needs by supporting `shift-select-mode'
853 outside these special contexts, under control of this variable.
855 The default of this variable is nil, to avoid confusing behavior. Shifted
856 cursor keys will then execute Org commands in the following contexts:
857 - on a headline, changing TODO state (left/right) and priority (up/down)
858 - on a time stamp, changing the time
859 - in a plain list item, changing the bullet type
860 - in a property definition line, switching between allowed values
861 - in the BEGIN line of a clock table (changing the time block).
862 Outside these contexts, the commands will throw an error.
864 When this variable is t and the cursor is not in a special
865 context, Org mode will support shift-selection for making and
866 enlarging regions. To make this more effective, the bullet
867 cycling will no longer happen anywhere in an item line, but only
868 if the cursor is exactly on the bullet.
870 If you set this variable to the symbol `always', then the keys
871 will not be special in headlines, property lines, and item lines,
872 to make shift selection work there as well. If this is what you
873 want, you can use the following alternative commands:
874 `\\[org-todo]' and `\\[org-priority]' \
875 to change TODO state and priority,
876 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
877 can be used to switch TODO sets,
878 `\\[org-ctrl-c-minus]' to cycle item bullet types,
879 and properties can be edited by hand or in column view.
881 However, when the cursor is on a timestamp, shift-cursor commands
882 will still edit the time stamp - this is just too good to give up."
883 :group 'org
884 :type '(choice
885 (const :tag "Never" nil)
886 (const :tag "When outside special context" t)
887 (const :tag "Everywhere except timestamps" always)))
889 (defcustom org-loop-over-headlines-in-active-region nil
890 "Shall some commands act upon headlines in the active region?
892 When set to t, some commands will be performed in all headlines
893 within the active region.
895 When set to `start-level', some commands will be performed in all
896 headlines within the active region, provided that these headlines
897 are of the same level than the first one.
899 When set to a string, those commands will be performed on the
900 matching headlines within the active region. Such string must be
901 a tags/property/todo match as it is used in the agenda tags view.
903 The list of commands is: `org-schedule', `org-deadline',
904 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
905 `org-archive-to-archive-sibling'. The archiving commands skip
906 already archived entries."
907 :type '(choice (const :tag "Don't loop" nil)
908 (const :tag "All headlines in active region" t)
909 (const :tag "In active region, headlines at the same level than the first one" start-level)
910 (string :tag "Tags/Property/Todo matcher"))
911 :version "24.1"
912 :group 'org-todo
913 :group 'org-archive)
915 (defcustom org-startup-folded t
916 "Non-nil means entering Org mode will switch to OVERVIEW.
918 This can also be configured on a per-file basis by adding one of
919 the following lines anywhere in the buffer:
921 #+STARTUP: fold (or `overview', this is equivalent)
922 #+STARTUP: nofold (or `showall', this is equivalent)
923 #+STARTUP: content
924 #+STARTUP: showeverything
926 Set `org-agenda-inhibit-startup' to a non-nil value if you want
927 to ignore this option when Org opens agenda files for the first
928 time."
929 :group 'org-startup
930 :type '(choice
931 (const :tag "nofold: show all" nil)
932 (const :tag "fold: overview" t)
933 (const :tag "content: all headlines" content)
934 (const :tag "show everything, even drawers" showeverything)))
936 (defcustom org-startup-truncated t
937 "Non-nil means entering Org mode will set `truncate-lines'.
938 This is useful since some lines containing links can be very long and
939 uninteresting. Also tables look terrible when wrapped.
941 The variable `org-startup-truncated' allows to configure
942 truncation for Org mode different to the other modes that use the
943 variable `truncate-lines' and as a shortcut instead of putting
944 the variable `truncate-lines' into the `org-mode-hook'. If one
945 wants to configure truncation for Org mode not statically but
946 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
947 the variable `truncate-lines' has to be used because in such a
948 case it is too late to set the variable `org-startup-truncated'."
949 :group 'org-startup
950 :type 'boolean)
952 (defcustom org-startup-indented nil
953 "Non-nil means turn on `org-indent-mode' on startup.
954 This can also be configured on a per-file basis by adding one of
955 the following lines anywhere in the buffer:
957 #+STARTUP: indent
958 #+STARTUP: noindent"
959 :group 'org-structure
960 :type '(choice
961 (const :tag "Not" nil)
962 (const :tag "Globally (slow on startup in large files)" t)))
964 (defcustom org-use-sub-superscripts t
965 "Non-nil means interpret \"_\" and \"^\" for display.
967 If you want to control how Org exports those characters, see
968 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
969 used to be an alias for `org-export-with-sub-superscripts' in
970 Org <8.0, it is not anymore.
972 When this option is turned on, you can use TeX-like syntax for
973 sub- and superscripts within the buffer. Several characters after
974 \"_\" or \"^\" will be considered as a single item - so grouping
975 with {} is normally not needed. For example, the following things
976 will be parsed as single sub- or superscripts:
978 10^24 or 10^tau several digits will be considered 1 item.
979 10^-12 or 10^-tau a leading sign with digits or a word
980 x^2-y^3 will be read as x^2 - y^3, because items are
981 terminated by almost any nonword/nondigit char.
982 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
984 Still, ambiguity is possible. So when in doubt, use {} to enclose
985 the sub/superscript. If you set this variable to the symbol `{}',
986 the braces are *required* in order to trigger interpretations as
987 sub/superscript. This can be helpful in documents that need \"_\"
988 frequently in plain text."
989 :group 'org-startup
990 :version "24.4"
991 :package-version '(Org . "8.0")
992 :type '(choice
993 (const :tag "Always interpret" t)
994 (const :tag "Only with braces" {})
995 (const :tag "Never interpret" nil)))
997 (defcustom org-startup-with-beamer-mode nil
998 "Non-nil means turn on `org-beamer-mode' on startup.
999 This can also be configured on a per-file basis by adding one of
1000 the following lines anywhere in the buffer:
1002 #+STARTUP: beamer"
1003 :group 'org-startup
1004 :version "24.1"
1005 :type 'boolean)
1007 (defcustom org-startup-align-all-tables nil
1008 "Non-nil means align all tables when visiting a file.
1009 This can also be configured on a per-file basis by adding one of
1010 the following lines anywhere in the buffer:
1011 #+STARTUP: align
1012 #+STARTUP: noalign"
1013 :group 'org-startup
1014 :type 'boolean)
1016 (defcustom org-startup-shrink-all-tables nil
1017 "Non-nil means shrink all table columns with a width cookie.
1018 This can also be configured on a per-file basis by adding one of
1019 the following lines anywhere in the buffer:
1020 #+STARTUP: shrink"
1021 :group 'org-startup
1022 :type 'boolean
1023 :version "27.1"
1024 :package-version '(Org . "9.2")
1025 :safe #'booleanp)
1027 (defcustom org-startup-with-inline-images nil
1028 "Non-nil means show inline images when loading a new Org file.
1029 This can also be configured on a per-file basis by adding one of
1030 the following lines anywhere in the buffer:
1031 #+STARTUP: inlineimages
1032 #+STARTUP: noinlineimages"
1033 :group 'org-startup
1034 :version "24.1"
1035 :type 'boolean)
1037 (defcustom org-startup-with-latex-preview nil
1038 "Non-nil means preview LaTeX fragments when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: latexpreview
1043 #+STARTUP: nolatexpreview"
1044 :group 'org-startup
1045 :version "24.4"
1046 :package-version '(Org . "8.0")
1047 :type 'boolean)
1049 (defcustom org-insert-mode-line-in-empty-file nil
1050 "Non-nil means insert the first line setting Org mode in empty files.
1051 When the function `org-mode' is called interactively in an empty file, this
1052 normally means that the file name does not automatically trigger Org mode.
1053 To ensure that the file will always be in Org mode in the future, a
1054 line enforcing Org mode will be inserted into the buffer, if this option
1055 has been set."
1056 :group 'org-startup
1057 :type 'boolean)
1059 (defcustom org-replace-disputed-keys nil
1060 "Non-nil means use alternative key bindings for some keys.
1061 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1062 These keys are also used by other packages like shift-selection-mode'
1063 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1064 If you want to use Org mode together with one of these other modes,
1065 or more generally if you would like to move some Org mode commands to
1066 other keys, set this variable and configure the keys with the variable
1067 `org-disputed-keys'.
1069 This option is only relevant at load-time of Org mode, and must be set
1070 *before* org.el is loaded. Changing it requires a restart of Emacs to
1071 become effective."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defcustom org-use-extra-keys nil
1076 "Non-nil means use extra key sequence definitions for certain commands.
1077 This happens automatically if `window-system' is nil. This
1078 variable lets you do the same manually. You must set it before
1079 loading Org."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org mode startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed."
1105 (when org-replace-disputed-keys
1106 (let* ((nkey (key-description key))
1107 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1108 org-disputed-keys)))
1109 (setq key (if x (cdr x) key))))
1110 key)
1112 (defun org-defkey (keymap key def)
1113 "Define a key, possibly translated, as returned by `org-key'."
1114 (define-key keymap (org-key key) def))
1116 (defcustom org-ellipsis nil
1117 "The ellipsis to use in the Org mode outline.
1119 When nil, just use the standard three dots. When a non-empty string,
1120 use that string instead.
1122 The change affects only Org mode (which will then use its own display table).
1123 Changing this requires executing `\\[org-mode]' in a buffer to become
1124 effective."
1125 :group 'org-startup
1126 :type '(choice (const :tag "Default" nil)
1127 (string :tag "String" :value "...#"))
1128 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1130 (defvar org-display-table nil
1131 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1133 (defgroup org-keywords nil
1134 "Keywords in Org mode."
1135 :tag "Org Keywords"
1136 :group 'org)
1138 (defcustom org-closed-keep-when-no-todo nil
1139 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1140 :group 'org-todo
1141 :group 'org-keywords
1142 :version "24.4"
1143 :package-version '(Org . "8.0")
1144 :type 'boolean)
1146 (defgroup org-structure nil
1147 "Options concerning the general structure of Org files."
1148 :tag "Org Structure"
1149 :group 'org)
1151 (defgroup org-reveal-location nil
1152 "Options about how to make context of a location visible."
1153 :tag "Org Reveal Location"
1154 :group 'org-structure)
1156 (defcustom org-show-context-detail '((agenda . local)
1157 (bookmark-jump . lineage)
1158 (isearch . lineage)
1159 (default . ancestors))
1160 "Alist between context and visibility span when revealing a location.
1162 \\<org-mode-map>Some actions may move point into invisible
1163 locations. As a consequence, Org always expose a neighborhood
1164 around point. How much is shown depends on the initial action,
1165 or context. Valid contexts are
1167 agenda when exposing an entry from the agenda
1168 org-goto when using the command `org-goto' (`\\[org-goto]')
1169 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1170 tags-tree when constructing a sparse tree based on tags matches
1171 link-search when exposing search matches associated with a link
1172 mark-goto when exposing the jump goal of a mark
1173 bookmark-jump when exposing a bookmark location
1174 isearch when exiting from an incremental search
1175 default default for all contexts not set explicitly
1177 Allowed visibility spans are
1179 minimal show current headline; if point is not on headline,
1180 also show entry
1182 local show current headline, entry and next headline
1184 ancestors show current headline and its direct ancestors; if
1185 point is not on headline, also show entry
1187 lineage show current headline, its direct ancestors and all
1188 their children; if point is not on headline, also show
1189 entry and first child
1191 tree show current headline, its direct ancestors and all
1192 their children; if point is not on headline, also show
1193 entry and all children
1195 canonical show current headline, its direct ancestors along with
1196 their entries and children; if point is not located on
1197 the headline, also show current entry and all children
1199 As special cases, a nil or t value means show all contexts in
1200 `minimal' or `canonical' view, respectively.
1202 Some views can make displayed information very compact, but also
1203 make it harder to edit the location of the match. In such
1204 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1205 more context."
1206 :group 'org-reveal-location
1207 :version "26.1"
1208 :package-version '(Org . "9.0")
1209 :type '(choice
1210 (const :tag "Canonical" t)
1211 (const :tag "Minimal" nil)
1212 (repeat :greedy t :tag "Individual contexts"
1213 (cons
1214 (choice :tag "Context"
1215 (const agenda)
1216 (const org-goto)
1217 (const occur-tree)
1218 (const tags-tree)
1219 (const link-search)
1220 (const mark-goto)
1221 (const bookmark-jump)
1222 (const isearch)
1223 (const default))
1224 (choice :tag "Detail level"
1225 (const minimal)
1226 (const local)
1227 (const ancestors)
1228 (const lineage)
1229 (const tree)
1230 (const canonical))))))
1232 (defcustom org-indirect-buffer-display 'other-window
1233 "How should indirect tree buffers be displayed?
1235 This applies to indirect buffers created with the commands
1236 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1238 Valid values are:
1239 current-window Display in the current window
1240 other-window Just display in another window.
1241 dedicated-frame Create one new frame, and re-use it each time.
1242 new-frame Make a new frame each time. Note that in this case
1243 previously-made indirect buffers are kept, and you need to
1244 kill these buffers yourself."
1245 :group 'org-structure
1246 :group 'org-agenda-windows
1247 :type '(choice
1248 (const :tag "In current window" current-window)
1249 (const :tag "In current frame, other window" other-window)
1250 (const :tag "Each time a new frame" new-frame)
1251 (const :tag "One dedicated frame" dedicated-frame)))
1253 (defcustom org-use-speed-commands nil
1254 "Non-nil means activate single letter commands at beginning of a headline.
1255 This may also be a function to test for appropriate locations where speed
1256 commands should be active.
1258 For example, to activate speed commands when the point is on any
1259 star at the beginning of the headline, you can do this:
1261 (setq org-use-speed-commands
1262 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1263 :group 'org-structure
1264 :type '(choice
1265 (const :tag "Never" nil)
1266 (const :tag "At beginning of headline stars" t)
1267 (function)))
1269 (defcustom org-speed-commands-user nil
1270 "Alist of additional speed commands.
1271 This list will be checked before `org-speed-commands-default'
1272 when the variable `org-use-speed-commands' is non-nil
1273 and when the cursor is at the beginning of a headline.
1274 The car of each entry is a string with a single letter, which must
1275 be assigned to `self-insert-command' in the global map.
1276 The cdr is either a command to be called interactively, a function
1277 to be called, or a form to be evaluated.
1278 An entry that is just a list with a single string will be interpreted
1279 as a descriptive headline that will be added when listing the speed
1280 commands in the Help buffer using the `?' speed command."
1281 :group 'org-structure
1282 :type '(repeat :value ("k" . ignore)
1283 (choice :value ("k" . ignore)
1284 (list :tag "Descriptive Headline" (string :tag "Headline"))
1285 (cons :tag "Letter and Command"
1286 (string :tag "Command letter")
1287 (choice
1288 (function)
1289 (sexp))))))
1291 (defcustom org-bookmark-names-plist
1292 '(:last-capture "org-capture-last-stored"
1293 :last-refile "org-refile-last-stored"
1294 :last-capture-marker "org-capture-last-stored-marker")
1295 "Names for bookmarks automatically set by some Org commands.
1296 This can provide strings as names for a number of bookmarks Org sets
1297 automatically. The following keys are currently implemented:
1298 :last-capture
1299 :last-capture-marker
1300 :last-refile
1301 When a key does not show up in the property list, the corresponding bookmark
1302 is not set."
1303 :group 'org-structure
1304 :type 'plist)
1306 (defgroup org-cycle nil
1307 "Options concerning visibility cycling in Org mode."
1308 :tag "Org Cycle"
1309 :group 'org-structure)
1311 (defcustom org-cycle-skip-children-state-if-no-children t
1312 "Non-nil means skip CHILDREN state in entries that don't have any."
1313 :group 'org-cycle
1314 :type 'boolean)
1316 (defcustom org-cycle-max-level nil
1317 "Maximum level which should still be subject to visibility cycling.
1318 Levels higher than this will, for cycling, be treated as text, not a headline.
1319 When `org-odd-levels-only' is set, a value of N in this variable actually
1320 means 2N-1 stars as the limiting headline.
1321 When nil, cycle all levels.
1322 Note that the limiting level of cycling is also influenced by
1323 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1324 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1325 than its value."
1326 :group 'org-cycle
1327 :type '(choice
1328 (const :tag "No limit" nil)
1329 (integer :tag "Maximum level")))
1331 (defcustom org-hide-block-startup nil
1332 "Non-nil means entering Org mode will fold all blocks.
1333 This can also be set in on a per-file basis with
1335 #+STARTUP: hideblocks
1336 #+STARTUP: showblocks"
1337 :group 'org-startup
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-global-at-bob nil
1342 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1344 This makes it possible to do global cycling without having to use `S-TAB'
1345 or `\\[universal-argument] TAB'. For this special case to work, the first \
1346 line of the buffer
1347 must not be a headline -- it may be empty or some other text.
1349 When used in this way, `org-cycle-hook' is disabled temporarily to make
1350 sure the cursor stays at the beginning of the buffer.
1352 When this option is nil, don't do anything special at the beginning of
1353 the buffer."
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-level-after-item/entry-creation t
1358 "Non-nil means cycle entry level or item indentation in new empty entries.
1360 When the cursor is at the end of an empty headline, i.e., with only stars
1361 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1362 and then all possible ancestor states, before returning to the original state.
1363 This makes data entry extremely fast: M-RET to create a new headline,
1364 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1366 When the cursor is at the end of an empty plain list item, one TAB will
1367 make it a subitem, two or more tabs will back up to make this an item
1368 higher up in the item hierarchy."
1369 :group 'org-cycle
1370 :type 'boolean)
1372 (defcustom org-cycle-emulate-tab t
1373 "Where should `org-cycle' emulate TAB.
1374 nil Never
1375 white Only in completely white lines
1376 whitestart Only at the beginning of lines, before the first non-white char
1377 t Everywhere except in headlines
1378 exc-hl-bol Everywhere except at the start of a headline
1379 If TAB is used in a place where it does not emulate TAB, the current subtree
1380 visibility is cycled."
1381 :group 'org-cycle
1382 :type '(choice (const :tag "Never" nil)
1383 (const :tag "Only in completely white lines" white)
1384 (const :tag "Before first char in a line" whitestart)
1385 (const :tag "Everywhere except in headlines" t)
1386 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1388 (defcustom org-cycle-separator-lines 2
1389 "Number of empty lines needed to keep an empty line between collapsed trees.
1390 If you leave an empty line between the end of a subtree and the following
1391 headline, this empty line is hidden when the subtree is folded.
1392 Org mode will leave (exactly) one empty line visible if the number of
1393 empty lines is equal or larger to the number given in this variable.
1394 So the default 2 means at least 2 empty lines after the end of a subtree
1395 are needed to produce free space between a collapsed subtree and the
1396 following headline.
1398 If the number is negative, and the number of empty lines is at least -N,
1399 all empty lines are shown.
1401 Special case: when 0, never leave empty lines in collapsed view."
1402 :group 'org-cycle
1403 :type 'integer)
1404 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1406 (defcustom org-pre-cycle-hook nil
1407 "Hook that is run before visibility cycling is happening.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that will be set right after running this hook. The
1410 argument is a symbol. Before a global state change, it can have the values
1411 `overview', `content', or `all'. Before a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook)
1416 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1417 org-cycle-hide-drawers
1418 org-cycle-show-empty-lines
1419 org-optimize-window-after-visibility-change)
1420 "Hook that is run after `org-cycle' has changed the buffer visibility.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that was set by the most recent `org-cycle' command. The
1423 argument is a symbol. After a global state change, it can have the values
1424 `overview', `contents', or `all'. After a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook
1428 :version "26.1"
1429 :package-version '(Org . "8.3"))
1431 (defgroup org-edit-structure nil
1432 "Options concerning structure editing in Org mode."
1433 :tag "Org Edit Structure"
1434 :group 'org-structure)
1436 (defcustom org-odd-levels-only nil
1437 "Non-nil means skip even levels and only use odd levels for the outline.
1438 This has the effect that two stars are being added/taken away in
1439 promotion/demotion commands. It also influences how levels are
1440 handled by the exporters.
1441 Changing it requires restart of `font-lock-mode' to become effective
1442 for fontification also in regions already fontified.
1443 You may also set this on a per-file basis by adding one of the following
1444 lines to the buffer:
1446 #+STARTUP: odd
1447 #+STARTUP: oddeven"
1448 :group 'org-edit-structure
1449 :group 'org-appearance
1450 :type 'boolean)
1452 (defcustom org-adapt-indentation t
1453 "Non-nil means adapt indentation to outline node level.
1455 When this variable is set, Org assumes that you write outlines by
1456 indenting text in each node to align with the headline (after the
1457 stars). The following issues are influenced by this variable:
1459 - The indentation is increased by one space in a demotion
1460 command, and decreased by one in a promotion command. However,
1461 in the latter case, if shifting some line in the entry body
1462 would alter document structure (e.g., insert a new headline),
1463 indentation is not changed at all.
1465 - Property drawers and planning information is inserted indented
1466 when this variable is set. When nil, they will not be indented.
1468 - TAB indents a line relative to current level. The lines below
1469 a headline will be indented when this variable is set.
1471 Note that this is all about true indentation, by adding and
1472 removing space characters. See also \"org-indent.el\" which does
1473 level-dependent indentation in a virtual way, i.e. at display
1474 time in Emacs."
1475 :group 'org-edit-structure
1476 :type 'boolean
1477 :safe #'booleanp)
1479 (defcustom org-special-ctrl-a/e nil
1480 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1482 When t, `C-a' will bring back the cursor to the beginning of the
1483 headline text, i.e. after the stars and after a possible TODO
1484 keyword. In an item, this will be the position after bullet and
1485 check-box, if any. When the cursor is already at that position,
1486 another `C-a' will bring it to the beginning of the line.
1488 `C-e' will jump to the end of the headline, ignoring the presence
1489 of tags in the headline. A second `C-e' will then jump to the
1490 true end of the line, after any tags. This also means that, when
1491 this variable is non-nil, `C-e' also will never jump beyond the
1492 end of the heading of a folded section, i.e. not after the
1493 ellipses.
1495 When set to the symbol `reversed', the first `C-a' or `C-e' works
1496 normally, going to the true line boundary first. Only a directly
1497 following, identical keypress will bring the cursor to the
1498 special positions.
1500 This may also be a cons cell where the behavior for `C-a' and
1501 `C-e' is set separately."
1502 :group 'org-edit-structure
1503 :type '(choice
1504 (const :tag "off" nil)
1505 (const :tag "on: after stars/bullet and before tags first" t)
1506 (const :tag "reversed: true line boundary first" reversed)
1507 (cons :tag "Set C-a and C-e separately"
1508 (choice :tag "Special C-a"
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet first" t)
1511 (const :tag "reversed: before stars/bullet first" reversed))
1512 (choice :tag "Special C-e"
1513 (const :tag "off" nil)
1514 (const :tag "on: before tags first" t)
1515 (const :tag "reversed: after tags first" reversed)))))
1516 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1518 (defcustom org-special-ctrl-k nil
1519 "Non-nil means `C-k' will behave specially in headlines.
1520 When nil, `C-k' will call the default `kill-line' command.
1521 When t, the following will happen while the cursor is in the headline:
1523 - When the cursor is at the beginning of a headline, kill the entire
1524 line and possible the folded subtree below the line.
1525 - When in the middle of the headline text, kill the headline up to the tags.
1526 - When after the headline text, kill the tags."
1527 :group 'org-edit-structure
1528 :type 'boolean)
1530 (defcustom org-ctrl-k-protect-subtree nil
1531 "Non-nil means, do not delete a hidden subtree with C-k.
1532 When set to the symbol `error', simply throw an error when C-k is
1533 used to kill (part-of) a headline that has hidden text behind it.
1534 Any other non-nil value will result in a query to the user, if it is
1535 OK to kill that hidden subtree. When nil, kill without remorse."
1536 :group 'org-edit-structure
1537 :version "24.1"
1538 :type '(choice
1539 (const :tag "Do not protect hidden subtrees" nil)
1540 (const :tag "Protect hidden subtrees with a security query" t)
1541 (const :tag "Never kill a hidden subtree with C-k" error)))
1543 (defcustom org-special-ctrl-o t
1544 "Non-nil means, make `C-o' insert a row in tables."
1545 :group 'org-edit-structure
1546 :type 'boolean)
1548 (defcustom org-catch-invisible-edits nil
1549 "Check if in invisible region before inserting or deleting a character.
1550 Valid values are:
1552 nil Do not check, so just do invisible edits.
1553 error Throw an error and do nothing.
1554 show Make point visible, and do the requested edit.
1555 show-and-error Make point visible, then throw an error and abort the edit.
1556 smart Make point visible, and do insertion/deletion if it is
1557 adjacent to visible text and the change feels predictable.
1558 Never delete a previously invisible character or add in the
1559 middle or right after an invisible region. Basically, this
1560 allows insertion and backward-delete right before ellipses.
1561 FIXME: maybe in this case we should not even show?"
1562 :group 'org-edit-structure
1563 :version "24.1"
1564 :type '(choice
1565 (const :tag "Do not check" nil)
1566 (const :tag "Throw error when trying to edit" error)
1567 (const :tag "Unhide, but do not do the edit" show-and-error)
1568 (const :tag "Show invisible part and do the edit" show)
1569 (const :tag "Be smart and do the right thing" smart)))
1571 (defcustom org-yank-folded-subtrees t
1572 "Non-nil means when yanking subtrees, fold them.
1573 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1574 it starts with a heading and all other headings in it are either children
1575 or siblings, then fold all the subtrees. However, do this only if no
1576 text after the yank would be swallowed into a folded tree by this action."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-yank-adjusted-subtrees nil
1581 "Non-nil means when yanking subtrees, adjust the level.
1582 With this setting, `org-paste-subtree' is used to insert the subtree, see
1583 this function for details."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-M-RET-may-split-line '((default . t))
1588 "Non-nil means M-RET will split the line at the cursor position.
1589 When nil, it will go to the end of the line before making a
1590 new line.
1591 You may also set this option in a different way for different
1592 contexts. Valid contexts are:
1594 headline when creating a new headline
1595 item when creating a new item
1596 table in a table field
1597 default the value to be used for all contexts not explicitly
1598 customized"
1599 :group 'org-structure
1600 :group 'org-table
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Never" nil)
1604 (repeat :greedy t :tag "Individual contexts"
1605 (cons
1606 (choice :tag "Context"
1607 (const headline)
1608 (const item)
1609 (const table)
1610 (const default))
1611 (boolean)))))
1614 (defcustom org-insert-heading-respect-content nil
1615 "Non-nil means insert new headings after the current subtree.
1616 \\<org-mode-map>
1617 When nil, the new heading is created directly after the current line.
1618 The commands `\\[org-insert-heading-respect-content]' and \
1619 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1620 for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1678 (defcustom org-occur-case-fold-search t
1679 "Non-nil means `org-occur' should be case-insensitive.
1680 If set to `smart' the search will be case-insensitive only if it
1681 doesn't specify any upper case character."
1682 :group 'org-sparse-trees
1683 :version "26.1"
1684 :type '(choice
1685 (const :tag "Case-sensitive" nil)
1686 (const :tag "Case-insensitive" t)
1687 (const :tag "Case-insensitive for lower case searches only" smart)))
1689 (defcustom org-occur-hook '(org-first-headline-recenter)
1690 "Hook that is run after `org-occur' has constructed a sparse tree.
1691 This can be used to recenter the window to show as much of the structure
1692 as possible."
1693 :group 'org-sparse-trees
1694 :type 'hook)
1696 (defgroup org-table nil
1697 "Options concerning tables in Org mode."
1698 :tag "Org Table"
1699 :group 'org)
1701 (defcustom org-self-insert-cluster-for-undo nil
1702 "Non-nil means cluster self-insert commands for undo when possible.
1703 If this is set, then, like in the Emacs command loop, 20 consecutive
1704 characters will be undone together.
1705 This is configurable, because there is some impact on typing performance."
1706 :group 'org-table
1707 :type 'boolean)
1709 (defcustom org-table-tab-recognizes-table.el t
1710 "Non-nil means TAB will automatically notice a table.el table.
1711 When it sees such a table, it moves point into it and - if necessary -
1712 calls `table-recognize-table'."
1713 :group 'org-table-editing
1714 :type 'boolean)
1716 (defgroup org-link nil
1717 "Options concerning links in Org mode."
1718 :tag "Org Link"
1719 :group 'org)
1721 (defvar-local org-link-abbrev-alist-local nil
1722 "Buffer-local version of `org-link-abbrev-alist', which see.
1723 The value of this is taken from the #+LINK lines.")
1725 (defcustom org-link-parameters
1726 '(("doi" :follow org--open-doi-link)
1727 ("elisp" :follow org--open-elisp-link)
1728 ("file" :complete org-file-complete-link)
1729 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1730 ("help" :follow org--open-help-link)
1731 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1732 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1733 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1734 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1735 ("shell" :follow org--open-shell-link))
1736 "An alist of properties that defines all the links in Org mode.
1737 The key in each association is a string of the link type.
1738 Subsequent optional elements make up a p-list of link properties.
1740 :follow - A function that takes the link path as an argument.
1742 :export - A function that takes the link path, description and
1743 export-backend as arguments.
1745 :store - A function responsible for storing the link. See the
1746 function `org-store-link-functions'.
1748 :complete - A function that inserts a link with completion. The
1749 function takes one optional prefix arg.
1751 :face - A face for the link, or a function that returns a face.
1752 The function takes one argument which is the link path. The
1753 default face is `org-link'.
1755 :mouse-face - The mouse-face. The default is `highlight'.
1757 :display - `full' will not fold the link in descriptive
1758 display. Default is `org-link'.
1760 :help-echo - A string or function that takes (window object position)
1761 as arguments and returns a string.
1763 :keymap - A keymap that is active on the link. The default is
1764 `org-mouse-map'.
1766 :htmlize-link - A function for the htmlize-link. Defaults
1767 to (list :uri \"type:path\")
1769 :activate-func - A function to run at the end of font-lock
1770 activation. The function must accept (link-start link-end path bracketp)
1771 as arguments."
1772 :group 'org-link
1773 :type '(alist :tag "Link display parameters"
1774 :value-type plist)
1775 :version "26.1"
1776 :package-version '(Org . "9.1"))
1778 (defun org-link-get-parameter (type key)
1779 "Get TYPE link property for KEY.
1780 TYPE is a string and KEY is a plist keyword."
1781 (plist-get
1782 (cdr (assoc type org-link-parameters))
1783 key))
1785 (defun org-link-set-parameters (type &rest parameters)
1786 "Set link TYPE properties to PARAMETERS.
1787 PARAMETERS should be :key val pairs."
1788 (let ((data (assoc type org-link-parameters)))
1789 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1790 (push (cons type parameters) org-link-parameters)
1791 (org-make-link-regexps)
1792 (org-element-update-syntax))))
1794 (defun org-link-types ()
1795 "Return a list of known link types."
1796 (mapcar #'car org-link-parameters))
1798 (defcustom org-link-abbrev-alist nil
1799 "Alist of link abbreviations.
1800 The car of each element is a string, to be replaced at the start of a link.
1801 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1802 links in Org buffers can have an optional tag after a double colon, e.g.,
1804 [[linkkey:tag][description]]
1806 The `linkkey' must be a single word, starting with a letter, followed
1807 by letters, numbers, `-' or `_'.
1809 If REPLACE is a string, the tag will simply be appended to create the link.
1810 If the string contains \"%s\", the tag will be inserted there. If the string
1811 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1812 at that point (see the function `url-hexify-string'). If the string contains
1813 the specifier \"%(my-function)\", then the custom function `my-function' will
1814 be invoked: this function takes the tag as its only argument and must return
1815 a string.
1817 REPLACE may also be a function that will be called with the tag as the
1818 only argument to create the link, which should be returned as a string.
1820 See the manual for examples."
1821 :group 'org-link
1822 :type '(repeat
1823 (cons
1824 (string :tag "Protocol")
1825 (choice
1826 (string :tag "Format")
1827 (function)))))
1829 (defcustom org-descriptive-links t
1830 "Non-nil means Org will display descriptive links.
1831 E.g. [[http://orgmode.org][Org website]] will be displayed as
1832 \"Org Website\", hiding the link itself and just displaying its
1833 description. When set to nil, Org will display the full links
1834 literally.
1836 You can interactively set the value of this variable by calling
1837 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1838 :group 'org-link
1839 :type 'boolean)
1841 (defcustom org-link-file-path-type 'adaptive
1842 "How the path name in file links should be stored.
1843 Valid values are:
1845 relative Relative to the current directory, i.e. the directory of the file
1846 into which the link is being inserted.
1847 absolute Absolute path, if possible with ~ for home directory.
1848 noabbrev Absolute path, no abbreviation of home directory.
1849 adaptive Use relative path for files in the current directory and sub-
1850 directories of it. For other files, use an absolute path."
1851 :group 'org-link
1852 :type '(choice
1853 (const relative)
1854 (const absolute)
1855 (const noabbrev)
1856 (const adaptive)))
1858 (defvaralias 'org-activate-links 'org-highlight-links)
1859 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1860 "Types of links that should be highlighted in Org files.
1862 This is a list of symbols, each one of them leading to the
1863 highlighting of a certain link type.
1865 You can still open links that are not highlighted.
1867 In principle, it does not hurt to turn on highlighting for all
1868 link types. There may be a small gain when turning off unused
1869 link types. The types are:
1871 bracket The recommended [[link][description]] or [[link]] links with hiding.
1872 angle Links in angular brackets that may contain whitespace like
1873 <bbdb:Carsten Dominik>.
1874 plain Plain links in normal text, no whitespace, like http://google.com.
1875 radio Text that is matched by a radio target, see manual for details.
1876 tag Tag settings in a headline (link to tag search).
1877 date Time stamps (link to calendar).
1878 footnote Footnote labels.
1880 If you set this variable during an Emacs session, use `org-mode-restart'
1881 in the Org buffer so that the change takes effect."
1882 :group 'org-link
1883 :group 'org-appearance
1884 :type '(set :greedy t
1885 (const :tag "Double bracket links" bracket)
1886 (const :tag "Angular bracket links" angle)
1887 (const :tag "Plain text links" plain)
1888 (const :tag "Radio target matches" radio)
1889 (const :tag "Tags" tag)
1890 (const :tag "Timestamps" date)
1891 (const :tag "Footnotes" footnote)))
1893 (defcustom org-make-link-description-function nil
1894 "Function to use for generating link descriptions from links.
1895 This function must take two parameters: the first one is the
1896 link, the second one is the description generated by
1897 `org-insert-link'. The function should return the description to
1898 use."
1899 :group 'org-link
1900 :type '(choice (const nil) (function)))
1902 (defgroup org-link-store nil
1903 "Options concerning storing links in Org mode."
1904 :tag "Org Store Link"
1905 :group 'org-link)
1907 (defcustom org-url-hexify-p t
1908 "When non-nil, hexify URL when creating a link."
1909 :type 'boolean
1910 :version "24.3"
1911 :group 'org-link-store)
1913 (defcustom org-email-link-description-format "Email %c: %.30s"
1914 "Format of the description part of a link to an email or usenet message.
1915 The following %-escapes will be replaced by corresponding information:
1917 %F full \"From\" field
1918 %f name, taken from \"From\" field, address if no name
1919 %T full \"To\" field
1920 %t first name in \"To\" field, address if no name
1921 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1922 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1923 %s subject
1924 %d date
1925 %m message-id.
1927 You may use normal field width specification between the % and the letter.
1928 This is for example useful to limit the length of the subject.
1930 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1931 :group 'org-link-store
1932 :type 'string)
1934 (defcustom org-from-is-user-regexp
1935 (let (r1 r2)
1936 (when (and user-mail-address (not (string= user-mail-address "")))
1937 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1938 (when (and user-full-name (not (string= user-full-name "")))
1939 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1940 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1941 "Regexp matched against the \"From:\" header of an email or usenet message.
1942 It should match if the message is from the user him/herself."
1943 :group 'org-link-store
1944 :type 'regexp)
1946 (defcustom org-context-in-file-links t
1947 "Non-nil means file links from `org-store-link' contain context.
1948 \\<org-mode-map>
1949 A search string will be added to the file name with :: as separator
1950 and used to find the context when the link is activated by the command
1951 `org-open-at-point'. When this option is t, the entire active region
1952 will be placed in the search string of the file link. If set to a
1953 positive integer, only the first n lines of context will be stored.
1955 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1956 \\[org-store-link]')
1957 negates this setting for the duration of the command."
1958 :group 'org-link-store
1959 :type '(choice boolean integer))
1961 (defcustom org-keep-stored-link-after-insertion nil
1962 "Non-nil means keep link in list for entire session.
1963 \\<org-mode-map>
1964 The command `org-store-link' adds a link pointing to the current
1965 location to an internal list. These links accumulate during a session.
1966 The command `org-insert-link' can be used to insert links into any
1967 Org file (offering completion for all stored links).
1969 When this option is nil, every link which has been inserted once using
1970 `\\[org-insert-link]' will be removed from the list, to make completing the \
1971 unused
1972 links more efficient."
1973 :group 'org-link-store
1974 :type 'boolean)
1976 (defgroup org-link-follow nil
1977 "Options concerning following links in Org mode."
1978 :tag "Org Follow Link"
1979 :group 'org-link)
1981 (defcustom org-link-translation-function nil
1982 "Function to translate links with different syntax to Org syntax.
1983 This can be used to translate links created for example by the Planner
1984 or emacs-wiki packages to Org syntax.
1985 The function must accept two parameters, a TYPE containing the link
1986 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1987 which is everything after the link protocol. It should return a cons
1988 with possibly modified values of type and path.
1989 Org contains a function for this, so if you set this variable to
1990 `org-translate-link-from-planner', you should be able follow many
1991 links created by planner."
1992 :group 'org-link-follow
1993 :type '(choice (const nil) (function)))
1995 (defcustom org-follow-link-hook nil
1996 "Hook that is run after a link has been followed."
1997 :group 'org-link-follow
1998 :type 'hook)
2000 (defcustom org-tab-follows-link nil
2001 "Non-nil means on links TAB will follow the link.
2002 Needs to be set before org.el is loaded.
2003 This really should not be used, it does not make sense, and the
2004 implementation is bad."
2005 :group 'org-link-follow
2006 :type 'boolean)
2008 (defcustom org-return-follows-link nil
2009 "Non-nil means on links RET will follow the link.
2010 In tables, the special behavior of RET has precedence."
2011 :group 'org-link-follow
2012 :type 'boolean)
2014 (defcustom org-mouse-1-follows-link
2015 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2016 "Non-nil means mouse-1 on a link will follow the link.
2017 A longer mouse click will still set point. Needs to be set
2018 before org.el is loaded."
2019 :group 'org-link-follow
2020 :version "26.1"
2021 :package-version '(Org . "8.3")
2022 :type '(choice
2023 (const :tag "A double click follows the link" double)
2024 (const :tag "Unconditionally follow the link with mouse-1" t)
2025 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2027 (defcustom org-mark-ring-length 4
2028 "Number of different positions to be recorded in the ring.
2029 Changing this requires a restart of Emacs to work correctly."
2030 :group 'org-link-follow
2031 :type 'integer)
2033 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2034 "Non-nil means internal fuzzy links can only match headlines.
2036 When nil, the a fuzzy link may point to a target or a named
2037 construct in the document. When set to the special value
2038 `query-to-create', offer to create a new headline when none
2039 matched.
2041 Spaces and statistics cookies are ignored during heading searches."
2042 :group 'org-link-follow
2043 :version "24.1"
2044 :type '(choice
2045 (const :tag "Use fuzzy text search" nil)
2046 (const :tag "Match only exact headline" t)
2047 (const :tag "Match exact headline or query to create it"
2048 query-to-create))
2049 :safe #'symbolp)
2051 (defcustom org-link-frame-setup
2052 '((vm . vm-visit-folder-other-frame)
2053 (vm-imap . vm-visit-imap-folder-other-frame)
2054 (gnus . org-gnus-no-new-news)
2055 (file . find-file-other-window)
2056 (wl . wl-other-frame))
2057 "Setup the frame configuration for following links.
2058 When following a link with Emacs, it may often be useful to display
2059 this link in another window or frame. This variable can be used to
2060 set this up for the different types of links.
2061 For VM, use any of
2062 `vm-visit-folder'
2063 `vm-visit-folder-other-window'
2064 `vm-visit-folder-other-frame'
2065 For Gnus, use any of
2066 `gnus'
2067 `gnus-other-frame'
2068 `org-gnus-no-new-news'
2069 For FILE, use any of
2070 `find-file'
2071 `find-file-other-window'
2072 `find-file-other-frame'
2073 For Wanderlust use any of
2074 `wl'
2075 `wl-other-frame'
2076 For the calendar, use the variable `calendar-setup'.
2077 For BBDB, it is currently only possible to display the matches in
2078 another window."
2079 :group 'org-link-follow
2080 :type '(list
2081 (cons (const vm)
2082 (choice
2083 (const vm-visit-folder)
2084 (const vm-visit-folder-other-window)
2085 (const vm-visit-folder-other-frame)))
2086 (cons (const vm-imap)
2087 (choice
2088 (const vm-visit-imap-folder)
2089 (const vm-visit-imap-folder-other-window)
2090 (const vm-visit-imap-folder-other-frame)))
2091 (cons (const gnus)
2092 (choice
2093 (const gnus)
2094 (const gnus-other-frame)
2095 (const org-gnus-no-new-news)))
2096 (cons (const file)
2097 (choice
2098 (const find-file)
2099 (const find-file-other-window)
2100 (const find-file-other-frame)))
2101 (cons (const wl)
2102 (choice
2103 (const wl)
2104 (const wl-other-frame)))))
2106 (defcustom org-display-internal-link-with-indirect-buffer nil
2107 "Non-nil means use indirect buffer to display infile links.
2108 Activating internal links (from one location in a file to another location
2109 in the same file) normally just jumps to the location. When the link is
2110 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2111 is displayed in
2112 another window. When this option is set, the other window actually displays
2113 an indirect buffer clone of the current buffer, to avoid any visibility
2114 changes to the current buffer."
2115 :group 'org-link-follow
2116 :type 'boolean)
2118 (defcustom org-open-non-existing-files nil
2119 "Non-nil means `org-open-file' will open non-existing files.
2120 When nil, an error will be generated.
2121 This variable applies only to external applications because they
2122 might choke on non-existing files. If the link is to a file that
2123 will be opened in Emacs, the variable is ignored."
2124 :group 'org-link-follow
2125 :type 'boolean)
2127 (defcustom org-open-directory-means-index-dot-org nil
2128 "Non-nil means a link to a directory really means to index.org.
2129 When nil, following a directory link will run dired or open a finder/explorer
2130 window on that directory."
2131 :group 'org-link-follow
2132 :type 'boolean)
2134 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2135 "Non-nil means ask for confirmation before executing shell links.
2136 Shell links can be dangerous: just think about a link
2138 [[shell:rm -rf ~/*][Google Search]]
2140 This link would show up in your Org document as \"Google Search\",
2141 but really it would remove your entire home directory.
2142 Therefore we advise against setting this variable to nil.
2143 Just change it to `y-or-n-p' if you want to confirm with a
2144 single keystroke rather than having to type \"yes\"."
2145 :group 'org-link-follow
2146 :type '(choice
2147 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2148 (const :tag "with y-or-n (faster)" y-or-n-p)
2149 (const :tag "no confirmation (dangerous)" nil)))
2150 (put 'org-confirm-shell-link-function
2151 'safe-local-variable
2152 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2154 (defcustom org-confirm-shell-link-not-regexp ""
2155 "A regexp to skip confirmation for shell links."
2156 :group 'org-link-follow
2157 :version "24.1"
2158 :type 'regexp)
2160 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2161 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2162 Elisp links can be dangerous: just think about a link
2164 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2166 This link would show up in your Org document as \"Google Search\",
2167 but really it would remove your entire home directory.
2168 Therefore we advise against setting this variable to nil.
2169 Just change it to `y-or-n-p' if you want to confirm with a
2170 single keystroke rather than having to type \"yes\"."
2171 :group 'org-link-follow
2172 :type '(choice
2173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2174 (const :tag "with y-or-n (faster)" y-or-n-p)
2175 (const :tag "no confirmation (dangerous)" nil)))
2176 (put 'org-confirm-shell-link-function
2177 'safe-local-variable
2178 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2180 (defcustom org-confirm-elisp-link-not-regexp ""
2181 "A regexp to skip confirmation for Elisp links."
2182 :group 'org-link-follow
2183 :version "24.1"
2184 :type 'regexp)
2186 (defconst org-file-apps-defaults-gnu
2187 '((remote . emacs)
2188 (system . mailcap)
2189 (t . mailcap))
2190 "Default file applications on a UNIX or GNU/Linux system.
2191 See `org-file-apps'.")
2193 (defconst org-file-apps-defaults-macosx
2194 '((remote . emacs)
2195 (system . "open %s")
2196 ("ps.gz" . "gv %s")
2197 ("eps.gz" . "gv %s")
2198 ("dvi" . "xdvi %s")
2199 ("fig" . "xfig %s")
2200 (t . "open %s"))
2201 "Default file applications on a macOS system.
2202 The system \"open\" is known as a default, but we use X11 applications
2203 for some files for which the OS does not have a good default.
2204 See `org-file-apps'.")
2206 (defconst org-file-apps-defaults-windowsnt
2207 (list '(remote . emacs)
2208 (cons 'system (lambda (file _path)
2209 (with-no-warnings (w32-shell-execute "open" file))))
2210 (cons t (lambda (file _path)
2211 (with-no-warnings (w32-shell-execute "open" file)))))
2212 "Default file applications on a Windows NT system.
2213 The system \"open\" is used for most files.
2214 See `org-file-apps'.")
2216 (defcustom org-file-apps
2217 '((auto-mode . emacs)
2218 ("\\.mm\\'" . default)
2219 ("\\.x?html?\\'" . default)
2220 ("\\.pdf\\'" . default))
2221 "External applications for opening `file:path' items in a document.
2222 \\<org-mode-map>\
2224 Org mode uses system defaults for different file types, but
2225 you can use this variable to set the application for a given file
2226 extension. The entries in this list are cons cells where the car identifies
2227 files and the cdr the corresponding command.
2229 Possible values for the file identifier are:
2231 \"string\" A string as a file identifier can be interpreted in different
2232 ways, depending on its contents:
2234 - Alphanumeric characters only:
2235 Match links with this file extension.
2236 Example: (\"pdf\" . \"evince %s\")
2237 to open PDFs with evince.
2239 - Regular expression: Match links where the
2240 filename matches the regexp. If you want to
2241 use groups here, use shy groups.
2243 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2244 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2245 to open *.html and *.xhtml with firefox.
2247 - Regular expression which contains (non-shy) groups:
2248 Match links where the whole link, including \"::\", and
2249 anything after that, matches the regexp.
2250 In a custom command string, %1, %2, etc. are replaced with
2251 the parts of the link that were matched by the groups.
2252 For backwards compatibility, if a command string is given
2253 that does not use any of the group matches, this case is
2254 handled identically to the second one (i.e. match against
2255 file name only).
2256 In a custom function, you can access the group matches with
2257 (match-string n link).
2259 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2260 \"evince -p %1 %s\")
2261 to open [[file:document.pdf::5]] with evince at page 5.
2263 `directory' Matches a directory
2264 `remote' Matches a remote file, accessible through tramp or efs.
2265 Remote files most likely should be visited through Emacs
2266 because external applications cannot handle such paths.
2267 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2268 so all files Emacs knows how to handle. Using this with
2269 command `emacs' will open most files in Emacs. Beware that this
2270 will also open html files inside Emacs, unless you add
2271 (\"html\" . default) to the list as well.
2272 `system' The system command to open files, like `open' on Windows
2273 and macOS, and mailcap under GNU/Linux. This is the command
2274 that will be selected if you call `org-open-at-point' with a
2275 double prefix argument (`\\[universal-argument] \
2276 \\[universal-argument] \\[org-open-at-point]').
2277 t Default for files not matched by any of the other options.
2279 Possible values for the command are:
2281 `emacs' The file will be visited by the current Emacs process.
2282 `default' Use the default application for this file type, which is the
2283 association for t in the list, most likely in the system-specific
2284 part. This can be used to overrule an unwanted setting in the
2285 system-specific variable.
2286 `system' Use the system command for opening files, like \"open\".
2287 This command is specified by the entry whose car is `system'.
2288 Most likely, the system-specific version of this variable
2289 does define this command, but you can overrule/replace it
2290 here.
2291 `mailcap' Use command specified in the mailcaps.
2292 string A command to be executed by a shell; %s will be replaced
2293 by the path to the file.
2294 function A Lisp function, which will be called with two arguments:
2295 the file path and the original link string, without the
2296 \"file:\" prefix.
2298 For more examples, see the system specific constants
2299 `org-file-apps-defaults-macosx'
2300 `org-file-apps-defaults-windowsnt'
2301 `org-file-apps-defaults-gnu'."
2302 :group 'org-link-follow
2303 :type '(repeat
2304 (cons (choice :value ""
2305 (string :tag "Extension")
2306 (const :tag "System command to open files" system)
2307 (const :tag "Default for unrecognized files" t)
2308 (const :tag "Remote file" remote)
2309 (const :tag "Links to a directory" directory)
2310 (const :tag "Any files that have Emacs modes"
2311 auto-mode))
2312 (choice :value ""
2313 (const :tag "Visit with Emacs" emacs)
2314 (const :tag "Use default" default)
2315 (const :tag "Use the system command" system)
2316 (string :tag "Command")
2317 (function :tag "Function")))))
2319 (defcustom org-doi-server-url "http://dx.doi.org/"
2320 "The URL of the DOI server."
2321 :type 'string
2322 :version "24.3"
2323 :group 'org-link-follow)
2325 (defgroup org-refile nil
2326 "Options concerning refiling entries in Org mode."
2327 :tag "Org Refile"
2328 :group 'org)
2330 (defcustom org-directory "~/org"
2331 "Directory with Org files.
2332 This is just a default location to look for Org files. There is no need
2333 at all to put your files into this directory. It is used in the
2334 following situations:
2336 1. When a capture template specifies a target file that is not an
2337 absolute path. The path will then be interpreted relative to
2338 `org-directory'
2339 2. When the value of variable `org-agenda-files' is a single file, any
2340 relative paths in this file will be taken as relative to
2341 `org-directory'."
2342 :group 'org-refile
2343 :group 'org-capture
2344 :type 'directory)
2346 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2347 "Default target for storing notes.
2348 Used as a fall back file for org-capture.el, for templates that
2349 do not specify a target file."
2350 :group 'org-refile
2351 :group 'org-capture
2352 :type 'file)
2354 (defcustom org-reverse-note-order nil
2355 "Non-nil means store new notes at the beginning of a file or entry.
2356 When nil, new notes will be filed to the end of a file or entry.
2357 This can also be a list with cons cells of regular expressions that
2358 are matched against file names, and values."
2359 :group 'org-capture
2360 :group 'org-refile
2361 :type '(choice
2362 (const :tag "Reverse always" t)
2363 (const :tag "Reverse never" nil)
2364 (repeat :tag "By file name regexp"
2365 (cons regexp boolean))))
2367 (defcustom org-log-refile nil
2368 "Information to record when a task is refiled.
2370 Possible values are:
2372 nil Don't add anything
2373 time Add a time stamp to the task
2374 note Prompt for a note and add it with template `org-log-note-headings'
2376 This option can also be set with on a per-file-basis with
2378 #+STARTUP: nologrefile
2379 #+STARTUP: logrefile
2380 #+STARTUP: lognoterefile
2382 You can have local logging settings for a subtree by setting the LOGGING
2383 property to one or more of these keywords.
2385 When bulk-refiling from the agenda, the value `note' is forbidden and
2386 will temporarily be changed to `time'."
2387 :group 'org-refile
2388 :group 'org-progress
2389 :version "24.1"
2390 :type '(choice
2391 (const :tag "No logging" nil)
2392 (const :tag "Record timestamp" time)
2393 (const :tag "Record timestamp with note." note)))
2395 (defcustom org-refile-targets nil
2396 "Targets for refiling entries with `\\[org-refile]'.
2397 This is a list of cons cells. Each cell contains:
2398 - a specification of the files to be considered, either a list of files,
2399 or a symbol whose function or variable value will be used to retrieve
2400 a file name or a list of file names. If you use `org-agenda-files' for
2401 that, all agenda files will be scanned for targets. Nil means consider
2402 headings in the current buffer.
2403 - A specification of how to find candidate refile targets. This may be
2404 any of:
2405 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2406 This tag has to be present in all target headlines, inheritance will
2407 not be considered.
2408 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2409 todo keyword.
2410 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2411 headlines that are refiling targets.
2412 - a cons cell (:level . N). Any headline of level N is considered a target.
2413 Note that, when `org-odd-levels-only' is set, level corresponds to
2414 order in hierarchy, not to the number of stars.
2415 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2416 Note that, when `org-odd-levels-only' is set, level corresponds to
2417 order in hierarchy, not to the number of stars.
2419 Each element of this list generates a set of possible targets.
2420 The union of these sets is presented (with completion) to
2421 the user by `org-refile'.
2423 You can set the variable `org-refile-target-verify-function' to a function
2424 to verify each headline found by the simple criteria above.
2426 When this variable is nil, all top-level headlines in the current buffer
2427 are used, equivalent to the value `((nil . (:level . 1))'."
2428 :group 'org-refile
2429 :type '(repeat
2430 (cons
2431 (choice :value org-agenda-files
2432 (const :tag "All agenda files" org-agenda-files)
2433 (const :tag "Current buffer" nil)
2434 (function) (variable) (file))
2435 (choice :tag "Identify target headline by"
2436 (cons :tag "Specific tag" (const :value :tag) (string))
2437 (cons :tag "TODO keyword" (const :value :todo) (string))
2438 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2439 (cons :tag "Level number" (const :value :level) (integer))
2440 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2442 (defcustom org-refile-target-verify-function nil
2443 "Function to verify if the headline at point should be a refile target.
2444 The function will be called without arguments, with point at the
2445 beginning of the headline. It should return t and leave point
2446 where it is if the headline is a valid target for refiling.
2448 If the target should not be selected, the function must return nil.
2449 In addition to this, it may move point to a place from where the search
2450 should be continued. For example, the function may decide that the entire
2451 subtree of the current entry should be excluded and move point to the end
2452 of the subtree."
2453 :group 'org-refile
2454 :type '(choice
2455 (const nil)
2456 (function)))
2458 (defcustom org-refile-use-cache nil
2459 "Non-nil means cache refile targets to speed up the process.
2460 \\<org-mode-map>\
2461 The cache for a particular file will be updated automatically when
2462 the buffer has been killed, or when any of the marker used for flagging
2463 refile targets no longer points at a live buffer.
2464 If you have added new entries to a buffer that might themselves be targets,
2465 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2466 if you find that easier, \
2467 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2468 \\[org-refile]'."
2469 :group 'org-refile
2470 :version "24.1"
2471 :type 'boolean)
2473 (defcustom org-refile-use-outline-path nil
2474 "Non-nil means provide refile targets as paths.
2475 So a level 3 headline will be available as level1/level2/level3.
2477 When the value is `file', also include the file name (without directory)
2478 into the path. In this case, you can also stop the completion after
2479 the file name, to get entries inserted as top level in the file.
2481 When `full-file-path', include the full file path.
2483 When `buffer-name', use the buffer name."
2484 :group 'org-refile
2485 :type '(choice
2486 (const :tag "Not" nil)
2487 (const :tag "Yes" t)
2488 (const :tag "Start with file name" file)
2489 (const :tag "Start with full file path" full-file-path)
2490 (const :tag "Start with buffer name" buffer-name)))
2492 (defcustom org-outline-path-complete-in-steps t
2493 "Non-nil means complete the outline path in hierarchical steps.
2494 When Org uses the refile interface to select an outline path (see
2495 `org-refile-use-outline-path'), the completion of the path can be
2496 done in a single go, or it can be done in steps down the headline
2497 hierarchy. Going in steps is probably the best if you do not use
2498 a special completion package like `ido' or `icicles'. However,
2499 when using these packages, going in one step can be very fast,
2500 while still showing the whole path to the entry."
2501 :group 'org-refile
2502 :type 'boolean)
2504 (defcustom org-refile-allow-creating-parent-nodes nil
2505 "Non-nil means allow the creation of new nodes as refile targets.
2506 New nodes are then created by adding \"/new node name\" to the completion
2507 of an existing node. When the value of this variable is `confirm',
2508 new node creation must be confirmed by the user (recommended).
2509 When nil, the completion must match an existing entry.
2511 Note that, if the new heading is not seen by the criteria
2512 listed in `org-refile-targets', multiple instances of the same
2513 heading would be created by trying again to file under the new
2514 heading."
2515 :group 'org-refile
2516 :type '(choice
2517 (const :tag "Never" nil)
2518 (const :tag "Always" t)
2519 (const :tag "Prompt for confirmation" confirm)))
2521 (defcustom org-refile-active-region-within-subtree nil
2522 "Non-nil means also refile active region within a subtree.
2524 By default `org-refile' doesn't allow refiling regions if they
2525 don't contain a set of subtrees, but it might be convenient to
2526 do so sometimes: in that case, the first line of the region is
2527 converted to a headline before refiling."
2528 :group 'org-refile
2529 :version "24.1"
2530 :type 'boolean)
2532 (defgroup org-todo nil
2533 "Options concerning TODO items in Org mode."
2534 :tag "Org TODO"
2535 :group 'org)
2537 (defgroup org-progress nil
2538 "Options concerning Progress logging in Org mode."
2539 :tag "Org Progress"
2540 :group 'org-time)
2542 (defvar org-todo-interpretation-widgets
2543 '((:tag "Sequence (cycling hits every state)" sequence)
2544 (:tag "Type (cycling directly to DONE)" type))
2545 "The available interpretation symbols for customizing `org-todo-keywords'.
2546 Interested libraries should add to this list.")
2548 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2549 "List of TODO entry keyword sequences and their interpretation.
2550 \\<org-mode-map>This is a list of sequences.
2552 Each sequence starts with a symbol, either `sequence' or `type',
2553 indicating if the keywords should be interpreted as a sequence of
2554 action steps, or as different types of TODO items. The first
2555 keywords are states requiring action - these states will select a headline
2556 for inclusion into the global TODO list Org produces. If one of the
2557 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2558 signify that no further action is necessary. If \"|\" is not found,
2559 the last keyword is treated as the only DONE state of the sequence.
2561 The command `\\[org-todo]' cycles an entry through these states, and one
2562 additional state where no keyword is present. For details about this
2563 cycling, see the manual.
2565 TODO keywords and interpretation can also be set on a per-file basis with
2566 the special #+SEQ_TODO and #+TYP_TODO lines.
2568 Each keyword can optionally specify a character for fast state selection
2569 \(in combination with the variable `org-use-fast-todo-selection')
2570 and specifiers for state change logging, using the same syntax that
2571 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2572 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2573 indicates to record a time stamp each time this state is selected.
2575 Each keyword may also specify if a timestamp or a note should be
2576 recorded when entering or leaving the state, by adding additional
2577 characters in the parenthesis after the keyword. This looks like this:
2578 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2579 record only the time of the state change. With X and Y being either
2580 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2581 Y when leaving the state if and only if the *target* state does not
2582 define X. You may omit any of the fast-selection key or X or /Y,
2583 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2585 For backward compatibility, this variable may also be just a list
2586 of keywords. In this case the interpretation (sequence or type) will be
2587 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2588 :group 'org-todo
2589 :group 'org-keywords
2590 :type '(choice
2591 (repeat :tag "Old syntax, just keywords"
2592 (string :tag "Keyword"))
2593 (repeat :tag "New syntax"
2594 (cons
2595 (choice
2596 :tag "Interpretation"
2597 ;;Quick and dirty way to see
2598 ;;`org-todo-interpretations'. This takes the
2599 ;;place of item arguments
2600 :convert-widget
2601 (lambda (widget)
2602 (widget-put widget
2603 :args (mapcar
2604 (lambda (x)
2605 (widget-convert
2606 (cons 'const x)))
2607 org-todo-interpretation-widgets))
2608 widget))
2609 (repeat
2610 (string :tag "Keyword"))))))
2612 (defvar-local org-todo-keywords-1 nil
2613 "All TODO and DONE keywords active in a buffer.")
2614 (defvar org-todo-keywords-for-agenda nil)
2615 (defvar org-done-keywords-for-agenda nil)
2616 (defvar org-todo-keyword-alist-for-agenda nil)
2617 (defvar org-tag-alist-for-agenda nil
2618 "Alist of all tags from all agenda files.")
2619 (defvar org-tag-groups-alist-for-agenda nil
2620 "Alist of all groups tags from all current agenda files.")
2621 (defvar-local org-tag-groups-alist nil)
2622 (defvar org-agenda-contributing-files nil)
2623 (defvar-local org-current-tag-alist nil
2624 "Alist of all tag groups in current buffer.
2625 This variable takes into consideration `org-tag-alist',
2626 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2627 (defvar-local org-not-done-keywords nil)
2628 (defvar-local org-done-keywords nil)
2629 (defvar-local org-todo-heads nil)
2630 (defvar-local org-todo-sets nil)
2631 (defvar-local org-todo-log-states nil)
2632 (defvar-local org-todo-kwd-alist nil)
2633 (defvar-local org-todo-key-alist nil)
2634 (defvar-local org-todo-key-trigger nil)
2636 (defcustom org-todo-interpretation 'sequence
2637 "Controls how TODO keywords are interpreted.
2638 This variable is in principle obsolete and is only used for
2639 backward compatibility, if the interpretation of todo keywords is
2640 not given already in `org-todo-keywords'. See that variable for
2641 more information."
2642 :group 'org-todo
2643 :group 'org-keywords
2644 :type '(choice (const sequence)
2645 (const type)))
2647 (defcustom org-use-fast-todo-selection t
2648 "\\<org-mode-map>\
2649 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2650 This variable describes if and under what circumstances the cycling
2651 mechanism for TODO keywords will be replaced by a single-key, direct
2652 selection scheme.
2654 When nil, fast selection is never used.
2656 When the symbol `prefix', it will be used when `org-todo' is called
2657 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2658 in an Org buffer, and
2659 `\\[universal-argument] t' in an agenda buffer.
2661 When t, fast selection is used by default. In this case, the prefix
2662 argument forces cycling instead.
2664 In all cases, the special interface is only used if access keys have
2665 actually been assigned by the user, i.e. if keywords in the configuration
2666 are followed by a letter in parenthesis, like TODO(t)."
2667 :group 'org-todo
2668 :type '(choice
2669 (const :tag "Never" nil)
2670 (const :tag "By default" t)
2671 (const :tag "Only with C-u C-c C-t" prefix)))
2673 (defcustom org-provide-todo-statistics t
2674 "Non-nil means update todo statistics after insert and toggle.
2675 ALL-HEADLINES means update todo statistics by including headlines
2676 with no TODO keyword as well, counting them as not done.
2677 A list of TODO keywords means the same, but skip keywords that are
2678 not in this list.
2679 When set to a list of two lists, the first list contains keywords
2680 to consider as TODO keywords, the second list contains keywords
2681 to consider as DONE keywords.
2683 When this is set, todo statistics is updated in the parent of the
2684 current entry each time a todo state is changed."
2685 :group 'org-todo
2686 :type '(choice
2687 (const :tag "Yes, only for TODO entries" t)
2688 (const :tag "Yes, including all entries" all-headlines)
2689 (repeat :tag "Yes, for TODOs in this list"
2690 (string :tag "TODO keyword"))
2691 (list :tag "Yes, for TODOs and DONEs in these lists"
2692 (repeat (string :tag "TODO keyword"))
2693 (repeat (string :tag "DONE keyword")))
2694 (other :tag "No TODO statistics" nil)))
2696 (defcustom org-hierarchical-todo-statistics t
2697 "Non-nil means TODO statistics covers just direct children.
2698 When nil, all entries in the subtree are considered.
2699 This has only an effect if `org-provide-todo-statistics' is set.
2700 To set this to nil for only a single subtree, use a COOKIE_DATA
2701 property and include the word \"recursive\" into the value."
2702 :group 'org-todo
2703 :type 'boolean)
2705 (defcustom org-after-todo-state-change-hook nil
2706 "Hook which is run after the state of a TODO item was changed.
2707 The new state (a string with a TODO keyword, or nil) is available in the
2708 Lisp variable `org-state'."
2709 :group 'org-todo
2710 :type 'hook)
2712 (defvar org-blocker-hook nil
2713 "Hook for functions that are allowed to block a state change.
2715 Functions in this hook should not modify the buffer.
2716 Each function gets as its single argument a property list,
2717 see `org-trigger-hook' for more information about this list.
2719 If any of the functions in this hook returns nil, the state change
2720 is blocked.")
2722 (defvar org-trigger-hook nil
2723 "Hook for functions that are triggered by a state change.
2725 Each function gets as its single argument a property list with at
2726 least the following elements:
2728 (:type type-of-change :position pos-at-entry-start
2729 :from old-state :to new-state)
2731 Depending on the type, more properties may be present.
2733 This mechanism is currently implemented for:
2735 TODO state changes
2736 ------------------
2737 :type todo-state-change
2738 :from previous state (keyword as a string), or nil, or a symbol
2739 `todo' or `done', to indicate the general type of state.
2740 :to new state, like in :from")
2742 (defcustom org-enforce-todo-dependencies nil
2743 "Non-nil means undone TODO entries will block switching the parent to DONE.
2744 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2745 be blocked if any prior sibling is not yet done.
2746 Finally, if the parent is blocked because of ordered siblings of its own,
2747 the child will also be blocked."
2748 :set (lambda (var val)
2749 (set var val)
2750 (if val
2751 (add-hook 'org-blocker-hook
2752 'org-block-todo-from-children-or-siblings-or-parent)
2753 (remove-hook 'org-blocker-hook
2754 'org-block-todo-from-children-or-siblings-or-parent)))
2755 :group 'org-todo
2756 :type 'boolean)
2758 (defcustom org-enforce-todo-checkbox-dependencies nil
2759 "Non-nil means unchecked boxes will block switching the parent to DONE.
2760 When this is nil, checkboxes have no influence on switching TODO states.
2761 When non-nil, you first need to check off all check boxes before the TODO
2762 entry can be switched to DONE.
2763 This variable needs to be set before org.el is loaded, and you need to
2764 restart Emacs after a change to make the change effective. The only way
2765 to change is while Emacs is running is through the customize interface."
2766 :set (lambda (var val)
2767 (set var val)
2768 (if val
2769 (add-hook 'org-blocker-hook
2770 'org-block-todo-from-checkboxes)
2771 (remove-hook 'org-blocker-hook
2772 'org-block-todo-from-checkboxes)))
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-treat-insert-todo-heading-as-state-change nil
2777 "Non-nil means inserting a TODO heading is treated as state change.
2778 So when the command `\\[org-insert-todo-heading]' is used, state change
2779 logging will apply if appropriate. When nil, the new TODO item will
2780 be inserted directly, and no logging will take place."
2781 :group 'org-todo
2782 :type 'boolean)
2784 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2785 "Non-nil means switching TODO states with S-cursor counts as state change.
2786 This is the default behavior. However, setting this to nil allows a
2787 convenient way to select a TODO state and bypass any logging associated
2788 with that."
2789 :group 'org-todo
2790 :type 'boolean)
2792 (defcustom org-todo-state-tags-triggers nil
2793 "Tag changes that should be triggered by TODO state changes.
2794 This is a list. Each entry is
2796 (state-change (tag . flag) .......)
2798 State-change can be a string with a state, and empty string to indicate the
2799 state that has no TODO keyword, or it can be one of the symbols `todo'
2800 or `done', meaning any not-done or done state, respectively."
2801 :group 'org-todo
2802 :group 'org-tags
2803 :type '(repeat
2804 (cons (choice :tag "When changing to"
2805 (const :tag "Not-done state" todo)
2806 (const :tag "Done state" done)
2807 (string :tag "State"))
2808 (repeat
2809 (cons :tag "Tag action"
2810 (string :tag "Tag")
2811 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2813 (defcustom org-log-done nil
2814 "Information to record when a task moves to the DONE state.
2816 Possible values are:
2818 nil Don't add anything, just change the keyword
2819 time Add a time stamp to the task
2820 note Prompt for a note and add it with template `org-log-note-headings'
2822 This option can also be set with on a per-file-basis with
2824 #+STARTUP: nologdone
2825 #+STARTUP: logdone
2826 #+STARTUP: lognotedone
2828 You can have local logging settings for a subtree by setting the LOGGING
2829 property to one or more of these keywords."
2830 :group 'org-todo
2831 :group 'org-progress
2832 :type '(choice
2833 (const :tag "No logging" nil)
2834 (const :tag "Record CLOSED timestamp" time)
2835 (const :tag "Record CLOSED timestamp with note." note)))
2837 ;; Normalize old uses of org-log-done.
2838 (cond
2839 ((eq org-log-done t) (setq org-log-done 'time))
2840 ((and (listp org-log-done) (memq 'done org-log-done))
2841 (setq org-log-done 'note)))
2843 (defcustom org-log-reschedule nil
2844 "Information to record when the scheduling date of a tasks is modified.
2846 Possible values are:
2848 nil Don't add anything, just change the date
2849 time Add a time stamp to the task
2850 note Prompt for a note and add it with template `org-log-note-headings'
2852 This option can also be set with on a per-file-basis with
2854 #+STARTUP: nologreschedule
2855 #+STARTUP: logreschedule
2856 #+STARTUP: lognotereschedule"
2857 :group 'org-todo
2858 :group 'org-progress
2859 :type '(choice
2860 (const :tag "No logging" nil)
2861 (const :tag "Record timestamp" time)
2862 (const :tag "Record timestamp with note." note)))
2864 (defcustom org-log-redeadline nil
2865 "Information to record when the deadline date of a tasks is modified.
2867 Possible values are:
2869 nil Don't add anything, just change the date
2870 time Add a time stamp to the task
2871 note Prompt for a note and add it with template `org-log-note-headings'
2873 This option can also be set with on a per-file-basis with
2875 #+STARTUP: nologredeadline
2876 #+STARTUP: logredeadline
2877 #+STARTUP: lognoteredeadline
2879 You can have local logging settings for a subtree by setting the LOGGING
2880 property to one or more of these keywords."
2881 :group 'org-todo
2882 :group 'org-progress
2883 :type '(choice
2884 (const :tag "No logging" nil)
2885 (const :tag "Record timestamp" time)
2886 (const :tag "Record timestamp with note." note)))
2888 (defcustom org-log-note-clock-out nil
2889 "Non-nil means record a note when clocking out of an item.
2890 This can also be configured on a per-file basis by adding one of
2891 the following lines anywhere in the buffer:
2893 #+STARTUP: lognoteclock-out
2894 #+STARTUP: nolognoteclock-out"
2895 :group 'org-todo
2896 :group 'org-progress
2897 :type 'boolean)
2899 (defcustom org-log-done-with-time t
2900 "Non-nil means the CLOSED time stamp will contain date and time.
2901 When nil, only the date will be recorded."
2902 :group 'org-progress
2903 :type 'boolean)
2905 (defcustom org-log-note-headings
2906 '((done . "CLOSING NOTE %t")
2907 (state . "State %-12s from %-12S %t")
2908 (note . "Note taken on %t")
2909 (reschedule . "Rescheduled from %S on %t")
2910 (delschedule . "Not scheduled, was %S on %t")
2911 (redeadline . "New deadline from %S on %t")
2912 (deldeadline . "Removed deadline, was %S on %t")
2913 (refile . "Refiled on %t")
2914 (clock-out . ""))
2915 "Headings for notes added to entries.
2917 The value is an alist, with the car being a symbol indicating the
2918 note context, and the cdr is the heading to be used. The heading
2919 may also be the empty string. The following placeholders can be
2920 used:
2922 %t a time stamp.
2923 %T an active time stamp instead the default inactive one
2924 %d a short-format time stamp.
2925 %D an active short-format time stamp.
2926 %s the new TODO state or time stamp (inactive), in double quotes.
2927 %S the old TODO state or time stamp (inactive), in double quotes.
2928 %u the user name.
2929 %U full user name.
2931 In fact, it is not a good idea to change the `state' entry,
2932 because Agenda Log mode depends on the format of these entries."
2933 :group 'org-todo
2934 :group 'org-progress
2935 :type '(list :greedy t
2936 (cons (const :tag "Heading when closing an item" done) string)
2937 (cons (const :tag
2938 "Heading when changing todo state (todo sequence only)"
2939 state) string)
2940 (cons (const :tag "Heading when just taking a note" note) string)
2941 (cons (const :tag "Heading when rescheduling" reschedule) string)
2942 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2943 (cons (const :tag "Heading when changing deadline" redeadline) string)
2944 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2945 (cons (const :tag "Heading when refiling" refile) string)
2946 (cons (const :tag "Heading when clocking out" clock-out) string)))
2948 (unless (assq 'note org-log-note-headings)
2949 (push '(note . "%t") org-log-note-headings))
2951 (defcustom org-log-into-drawer nil
2952 "Non-nil means insert state change notes and time stamps into a drawer.
2953 When nil, state changes notes will be inserted after the headline and
2954 any scheduling and clock lines, but not inside a drawer.
2956 The value of this variable should be the name of the drawer to use.
2957 LOGBOOK is proposed as the default drawer for this purpose, you can
2958 also set this to a string to define the drawer of your choice.
2960 A value of t is also allowed, representing \"LOGBOOK\".
2962 A value of t or nil can also be set with on a per-file-basis with
2964 #+STARTUP: logdrawer
2965 #+STARTUP: nologdrawer
2967 If this variable is set, `org-log-state-notes-insert-after-drawers'
2968 will be ignored.
2970 You can set the property LOG_INTO_DRAWER to overrule this setting for
2971 a subtree.
2973 Do not check directly this variable in a Lisp program. Call
2974 function `org-log-into-drawer' instead."
2975 :group 'org-todo
2976 :group 'org-progress
2977 :type '(choice
2978 (const :tag "Not into a drawer" nil)
2979 (const :tag "LOGBOOK" t)
2980 (string :tag "Other")))
2982 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2984 (defun org-log-into-drawer ()
2985 "Name of the log drawer, as a string, or nil.
2986 This is the value of `org-log-into-drawer'. However, if the
2987 current entry has or inherits a LOG_INTO_DRAWER property, it will
2988 be used instead of the default value."
2989 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2990 (cond ((equal p "nil") nil)
2991 ((equal p "t") "LOGBOOK")
2992 ((stringp p) p)
2993 (p "LOGBOOK")
2994 ((stringp org-log-into-drawer) org-log-into-drawer)
2995 (org-log-into-drawer "LOGBOOK"))))
2997 (defcustom org-log-state-notes-insert-after-drawers nil
2998 "Non-nil means insert state change notes after any drawers in entry.
2999 Only the drawers that *immediately* follow the headline and the
3000 deadline/scheduled line are skipped.
3001 When nil, insert notes right after the heading and perhaps the line
3002 with deadline/scheduling if present.
3004 This variable will have no effect if `org-log-into-drawer' is
3005 set."
3006 :group 'org-todo
3007 :group 'org-progress
3008 :type 'boolean)
3010 (defcustom org-log-states-order-reversed t
3011 "Non-nil means the latest state note will be directly after heading.
3012 When nil, the state change notes will be ordered according to time.
3014 This option can also be set with on a per-file-basis with
3016 #+STARTUP: logstatesreversed
3017 #+STARTUP: nologstatesreversed"
3018 :group 'org-todo
3019 :group 'org-progress
3020 :type 'boolean)
3022 (defcustom org-todo-repeat-to-state nil
3023 "The TODO state to which a repeater should return the repeating task.
3024 By default this is the first task of a TODO sequence or the
3025 previous state of a TYPE_TODO set. But you can specify to use
3026 the previous state in a TODO sequence or a string.
3028 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3029 entry, which has precedence over this option."
3030 :group 'org-todo
3031 :version "24.1"
3032 :type '(choice (const :tag "Use the previous TODO state" t)
3033 (const :tag "Use the head of the TODO sequence" nil)
3034 (string :tag "Use a specific TODO state")))
3036 (defcustom org-log-repeat 'time
3037 "Non-nil means record moving through the DONE state when triggering repeat.
3038 An auto-repeating task is immediately switched back to TODO when
3039 marked DONE. If you are not logging state changes (by adding \"@\"
3040 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3041 record a closing note, there will be no record of the task moving
3042 through DONE. This variable forces taking a note anyway.
3044 nil Don't force a record
3045 time Record a time stamp
3046 note Prompt for a note and add it with template `org-log-note-headings'
3048 This option can also be set with on a per-file-basis with
3050 #+STARTUP: nologrepeat
3051 #+STARTUP: logrepeat
3052 #+STARTUP: lognoterepeat
3054 You can have local logging settings for a subtree by setting the LOGGING
3055 property to one or more of these keywords."
3056 :group 'org-todo
3057 :group 'org-progress
3058 :type '(choice
3059 (const :tag "Don't force a record" nil)
3060 (const :tag "Force recording the DONE state" time)
3061 (const :tag "Force recording a note with the DONE state" note)))
3064 (defgroup org-priorities nil
3065 "Priorities in Org mode."
3066 :tag "Org Priorities"
3067 :group 'org-todo)
3069 (defcustom org-enable-priority-commands t
3070 "Non-nil means priority commands are active.
3071 When nil, these commands will be disabled, so that you never accidentally
3072 set a priority."
3073 :group 'org-priorities
3074 :type 'boolean)
3076 (defcustom org-highest-priority ?A
3077 "The highest priority of TODO items. A character like ?A, ?B etc.
3078 Must have a smaller ASCII number than `org-lowest-priority'."
3079 :group 'org-priorities
3080 :type 'character)
3082 (defcustom org-lowest-priority ?C
3083 "The lowest priority of TODO items. A character like ?A, ?B etc.
3084 Must have a larger ASCII number than `org-highest-priority'."
3085 :group 'org-priorities
3086 :type 'character)
3088 (defcustom org-default-priority ?B
3089 "The default priority of TODO items.
3090 This is the priority an item gets if no explicit priority is given.
3091 When starting to cycle on an empty priority the first step in the cycle
3092 depends on `org-priority-start-cycle-with-default'. The resulting first
3093 step priority must not exceed the range from `org-highest-priority' to
3094 `org-lowest-priority' which means that `org-default-priority' has to be
3095 in this range exclusive or inclusive the range boundaries. Else the
3096 first step refuses to set the default and the second will fall back
3097 to (depending on the command used) the highest or lowest priority."
3098 :group 'org-priorities
3099 :type 'character)
3101 (defcustom org-priority-start-cycle-with-default t
3102 "Non-nil means start with default priority when starting to cycle.
3103 When this is nil, the first step in the cycle will be (depending on the
3104 command used) one higher or lower than the default priority.
3105 See also `org-default-priority'."
3106 :group 'org-priorities
3107 :type 'boolean)
3109 (defcustom org-get-priority-function nil
3110 "Function to extract the priority from a string.
3111 The string is normally the headline. If this is nil Org computes the
3112 priority from the priority cookie like [#A] in the headline. It returns
3113 an integer, increasing by 1000 for each priority level.
3114 The user can set a different function here, which should take a string
3115 as an argument and return the numeric priority."
3116 :group 'org-priorities
3117 :version "24.1"
3118 :type '(choice
3119 (const nil)
3120 (function)))
3122 (defgroup org-time nil
3123 "Options concerning time stamps and deadlines in Org mode."
3124 :tag "Org Time"
3125 :group 'org)
3127 (defcustom org-time-stamp-rounding-minutes '(0 5)
3128 "Number of minutes to round time stamps to.
3129 \\<org-mode-map>\
3130 These are two values, the first applies when first creating a time stamp.
3131 The second applies when changing it with the commands `S-up' and `S-down'.
3132 When changing the time stamp, this means that it will change in steps
3133 of N minutes, as given by the second value.
3135 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3136 numbers should be factors of 60, so for example 5, 10, 15.
3138 When this is larger than 1, you can still force an exact time stamp by using
3139 a double prefix argument to a time stamp command like \
3140 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3141 and by using a prefix arg to `S-up/down' to specify the exact number
3142 of minutes to shift."
3143 :group 'org-time
3144 :get (lambda (var) ; Make sure both elements are there
3145 (if (integerp (default-value var))
3146 (list (default-value var) 5)
3147 (default-value var)))
3148 :type '(list
3149 (integer :tag "when inserting times")
3150 (integer :tag "when modifying times")))
3152 ;; Normalize old customizations of this variable.
3153 (when (integerp org-time-stamp-rounding-minutes)
3154 (setq org-time-stamp-rounding-minutes
3155 (list org-time-stamp-rounding-minutes
3156 org-time-stamp-rounding-minutes)))
3158 (defcustom org-display-custom-times nil
3159 "Non-nil means overlay custom formats over all time stamps.
3160 The formats are defined through the variable `org-time-stamp-custom-formats'.
3161 To turn this on on a per-file basis, insert anywhere in the file:
3162 #+STARTUP: customtime"
3163 :group 'org-time
3164 :set 'set-default
3165 :type 'sexp)
3166 (make-variable-buffer-local 'org-display-custom-times)
3168 (defcustom org-time-stamp-custom-formats
3169 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3170 "Custom formats for time stamps. See `format-time-string' for the syntax.
3171 These are overlaid over the default ISO format if the variable
3172 `org-display-custom-times' is set. Time like %H:%M should be at the
3173 end of the second format. The custom formats are also honored by export
3174 commands, if custom time display is turned on at the time of export."
3175 :group 'org-time
3176 :type 'sexp)
3178 (defun org-time-stamp-format (&optional long inactive)
3179 "Get the right format for a time string."
3180 (let ((f (if long (cdr org-time-stamp-formats)
3181 (car org-time-stamp-formats))))
3182 (if inactive
3183 (concat "[" (substring f 1 -1) "]")
3184 f)))
3186 (defcustom org-deadline-warning-days 14
3187 "Number of days before expiration during which a deadline becomes active.
3188 This variable governs the display in sparse trees and in the agenda.
3189 When 0 or negative, it means use this number (the absolute value of it)
3190 even if a deadline has a different individual lead time specified.
3192 Custom commands can set this variable in the options section."
3193 :group 'org-time
3194 :group 'org-agenda-daily/weekly
3195 :type 'integer)
3197 (defcustom org-scheduled-delay-days 0
3198 "Number of days before a scheduled item becomes active.
3199 This variable governs the display in sparse trees and in the agenda.
3200 The default value (i.e. 0) means: don't delay scheduled item.
3201 When negative, it means use this number (the absolute value of it)
3202 even if a scheduled item has a different individual delay time
3203 specified.
3205 Custom commands can set this variable in the options section."
3206 :group 'org-time
3207 :group 'org-agenda-daily/weekly
3208 :version "24.4"
3209 :package-version '(Org . "8.0")
3210 :type 'integer)
3212 (defcustom org-read-date-prefer-future t
3213 "Non-nil means assume future for incomplete date input from user.
3214 This affects the following situations:
3215 1. The user gives a month but not a year.
3216 For example, if it is April and you enter \"feb 2\", this will be read
3217 as Feb 2, *next* year. \"May 5\", however, will be this year.
3218 2. The user gives a day, but no month.
3219 For example, if today is the 15th, and you enter \"3\", Org will read
3220 this as the third of *next* month. However, if you enter \"17\",
3221 it will be considered as *this* month.
3223 If you set this variable to the symbol `time', then also the following
3224 will work:
3226 3. If the user gives a time.
3227 If the time is before now, it will be interpreted as tomorrow.
3229 Currently none of this works for ISO week specifications.
3231 When this option is nil, the current day, month and year will always be
3232 used as defaults.
3234 See also `org-agenda-jump-prefer-future'."
3235 :group 'org-time
3236 :type '(choice
3237 (const :tag "Never" nil)
3238 (const :tag "Check month and day" t)
3239 (const :tag "Check month, day, and time" time)))
3241 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3242 "Should the agenda jump command prefer the future for incomplete dates?
3243 The default is to do the same as configured in `org-read-date-prefer-future'.
3244 But you can also set a deviating value here.
3245 This may t or nil, or the symbol `org-read-date-prefer-future'."
3246 :group 'org-agenda
3247 :group 'org-time
3248 :version "24.1"
3249 :type '(choice
3250 (const :tag "Use org-read-date-prefer-future"
3251 org-read-date-prefer-future)
3252 (const :tag "Never" nil)
3253 (const :tag "Always" t)))
3255 (defcustom org-read-date-force-compatible-dates t
3256 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3258 Depending on the system Emacs is running on, certain dates cannot
3259 be represented with the type used internally to represent time.
3260 Dates between 1970-1-1 and 2038-1-1 can always be represented
3261 correctly. Some systems allow for earlier dates, some for later,
3262 some for both. One way to find out it to insert any date into an
3263 Org buffer, putting the cursor on the year and hitting S-up and
3264 S-down to test the range.
3266 When this variable is set to t, the date/time prompt will not let
3267 you specify dates outside the 1970-2037 range, so it is certain that
3268 these dates will work in whatever version of Emacs you are
3269 running, and also that you can move a file from one Emacs implementation
3270 to another. WHenever Org is forcing the year for you, it will display
3271 a message and beep.
3273 When this variable is nil, Org will check if the date is
3274 representable in the specific Emacs implementation you are using.
3275 If not, it will force a year, usually the current year, and beep
3276 to remind you. Currently this setting is not recommended because
3277 the likelihood that you will open your Org files in an Emacs that
3278 has limited date range is not negligible.
3280 A workaround for this problem is to use diary sexp dates for time
3281 stamps outside of this range."
3282 :group 'org-time
3283 :version "24.1"
3284 :type 'boolean)
3286 (defcustom org-read-date-display-live t
3287 "Non-nil means display current interpretation of date prompt live.
3288 This display will be in an overlay, in the minibuffer."
3289 :group 'org-time
3290 :type 'boolean)
3292 (defcustom org-read-date-popup-calendar t
3293 "Non-nil means pop up a calendar when prompting for a date.
3294 In the calendar, the date can be selected with mouse-1. However, the
3295 minibuffer will also be active, and you can simply enter the date as well.
3296 When nil, only the minibuffer will be available."
3297 :group 'org-time
3298 :type 'boolean)
3299 (defvaralias 'org-popup-calendar-for-date-prompt
3300 'org-read-date-popup-calendar)
3302 (defcustom org-extend-today-until 0
3303 "The hour when your day really ends. Must be an integer.
3304 This has influence for the following applications:
3305 - When switching the agenda to \"today\". It it is still earlier than
3306 the time given here, the day recognized as TODAY is actually yesterday.
3307 - When a date is read from the user and it is still before the time given
3308 here, the current date and time will be assumed to be yesterday, 23:59.
3309 Also, timestamps inserted in capture templates follow this rule.
3311 IMPORTANT: This is a feature whose implementation is and likely will
3312 remain incomplete. Really, it is only here because past midnight seems to
3313 be the favorite working time of John Wiegley :-)"
3314 :group 'org-time
3315 :type 'integer)
3317 (defcustom org-use-effective-time nil
3318 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3319 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3320 \"effective time\" of any timestamps between midnight and 8am will be
3321 23:59 of the previous day."
3322 :group 'org-time
3323 :version "24.1"
3324 :type 'boolean)
3326 (defcustom org-use-last-clock-out-time-as-effective-time nil
3327 "When non-nil, use the last clock out time for `org-todo'.
3328 Note that this option has precedence over the combined use of
3329 `org-use-effective-time' and `org-extend-today-until'."
3330 :group 'org-time
3331 :version "24.4"
3332 :package-version '(Org . "8.0")
3333 :type 'boolean)
3335 (defcustom org-edit-timestamp-down-means-later nil
3336 "Non-nil means S-down will increase the time in a time stamp.
3337 When nil, S-up will increase."
3338 :group 'org-time
3339 :type 'boolean)
3341 (defcustom org-calendar-follow-timestamp-change t
3342 "Non-nil means make the calendar window follow timestamp changes.
3343 When a timestamp is modified and the calendar window is visible, it will be
3344 moved to the new date."
3345 :group 'org-time
3346 :type 'boolean)
3348 (defgroup org-tags nil
3349 "Options concerning tags in Org mode."
3350 :tag "Org Tags"
3351 :group 'org)
3353 (defcustom org-tag-alist nil
3354 "Default tags available in Org files.
3356 The value of this variable is an alist. Associations either:
3358 (TAG)
3359 (TAG . SELECT)
3360 (SPECIAL)
3362 where TAG is a tag as a string, SELECT is character, used to
3363 select that tag through the fast tag selection interface, and
3364 SPECIAL is one of the following keywords: `:startgroup',
3365 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3366 `:newline'. These keywords are used to define a hierarchy of
3367 tags. See manual for details.
3369 When this variable is nil, Org mode bases tag input on what is
3370 already in the buffer. The value can be overridden locally by
3371 using a TAGS keyword, e.g.,
3373 #+TAGS: tag1 tag2
3375 See also `org-tag-persistent-alist' to sidestep this behavior."
3376 :group 'org-tags
3377 :type '(repeat
3378 (choice
3379 (cons :tag "Tag with key"
3380 (string :tag "Tag name")
3381 (character :tag "Access char"))
3382 (list :tag "Tag" (string :tag "Tag name"))
3383 (const :tag "Start radio group" (:startgroup))
3384 (const :tag "Start tag group, non distinct" (:startgrouptag))
3385 (const :tag "Group tags delimiter" (:grouptags))
3386 (const :tag "End radio group" (:endgroup))
3387 (const :tag "End tag group, non distinct" (:endgrouptag))
3388 (const :tag "New line" (:newline)))))
3390 (defcustom org-tag-persistent-alist nil
3391 "Tags always available in Org files.
3393 The value of this variable is an alist. Associations either:
3395 (TAG)
3396 (TAG . SELECT)
3397 (SPECIAL)
3399 where TAG is a tag as a string, SELECT is a character, used to
3400 select that tag through the fast tag selection interface, and
3401 SPECIAL is one of the following keywords: `:startgroup',
3402 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3403 `:newline'. These keywords are used to define a hierarchy of
3404 tags. See manual for details.
3406 Unlike to `org-tag-alist', tags defined in this variable do not
3407 depend on a local TAGS keyword. Instead, to disable these tags
3408 on a per-file basis, insert anywhere in the file:
3410 #+STARTUP: noptag"
3411 :group 'org-tags
3412 :type '(repeat
3413 (choice
3414 (cons :tag "Tag with key"
3415 (string :tag "Tag name")
3416 (character :tag "Access char"))
3417 (list :tag "Tag" (string :tag "Tag name"))
3418 (const :tag "Start radio group" (:startgroup))
3419 (const :tag "Start tag group, non distinct" (:startgrouptag))
3420 (const :tag "Group tags delimiter" (:grouptags))
3421 (const :tag "End radio group" (:endgroup))
3422 (const :tag "End tag group, non distinct" (:endgrouptag))
3423 (const :tag "New line" (:newline)))))
3425 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3426 "If non-nil, always offer completion for all tags of all agenda files.
3427 Instead of customizing this variable directly, you might want to
3428 set it locally for capture buffers, because there no list of
3429 tags in that file can be created dynamically (there are none).
3431 (add-hook \\='org-capture-mode-hook
3432 (lambda ()
3433 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3434 :group 'org-tags
3435 :version "24.1"
3436 :type 'boolean)
3438 (defvar org-file-tags nil
3439 "List of tags that can be inherited by all entries in the file.
3440 The tags will be inherited if the variable `org-use-tag-inheritance'
3441 says they should be.
3442 This variable is populated from #+FILETAGS lines.")
3444 (defcustom org-use-fast-tag-selection 'auto
3445 "Non-nil means use fast tag selection scheme.
3446 This is a special interface to select and deselect tags with single keys.
3447 When nil, fast selection is never used.
3448 When the symbol `auto', fast selection is used if and only if selection
3449 characters for tags have been configured, either through the variable
3450 `org-tag-alist' or through a #+TAGS line in the buffer.
3451 When t, fast selection is always used and selection keys are assigned
3452 automatically if necessary."
3453 :group 'org-tags
3454 :type '(choice
3455 (const :tag "Always" t)
3456 (const :tag "Never" nil)
3457 (const :tag "When selection characters are configured" auto)))
3459 (defcustom org-fast-tag-selection-single-key nil
3460 "Non-nil means fast tag selection exits after first change.
3461 When nil, you have to press RET to exit it.
3462 During fast tag selection, you can toggle this flag with `C-c'.
3463 This variable can also have the value `expert'. In this case, the window
3464 displaying the tags menu is not even shown, until you press C-c again."
3465 :group 'org-tags
3466 :type '(choice
3467 (const :tag "No" nil)
3468 (const :tag "Yes" t)
3469 (const :tag "Expert" expert)))
3471 (defvar org-fast-tag-selection-include-todo nil
3472 "Non-nil means fast tags selection interface will also offer TODO states.
3473 This is an undocumented feature, you should not rely on it.")
3475 (defcustom org-tags-column -77
3476 "The column to which tags should be indented in a headline.
3477 If this number is positive, it specifies the column. If it is negative,
3478 it means that the tags should be flushright to that column. For example,
3479 -80 works well for a normal 80 character screen.
3480 When 0, place tags directly after headline text, with only one space in
3481 between."
3482 :group 'org-tags
3483 :type 'integer)
3485 (defcustom org-auto-align-tags t
3486 "Non-nil keeps tags aligned when modifying headlines.
3487 Some operations (i.e. demoting) change the length of a headline and
3488 therefore shift the tags around. With this option turned on, after
3489 each such operation the tags are again aligned to `org-tags-column'."
3490 :group 'org-tags
3491 :type 'boolean)
3493 (defcustom org-use-tag-inheritance t
3494 "Non-nil means tags in levels apply also for sublevels.
3495 When nil, only the tags directly given in a specific line apply there.
3496 This may also be a list of tags that should be inherited, or a regexp that
3497 matches tags that should be inherited. Additional control is possible
3498 with the variable `org-tags-exclude-from-inheritance' which gives an
3499 explicit list of tags to be excluded from inheritance, even if the value of
3500 `org-use-tag-inheritance' would select it for inheritance.
3502 If this option is t, a match early-on in a tree can lead to a large
3503 number of matches in the subtree when constructing the agenda or creating
3504 a sparse tree. If you only want to see the first match in a tree during
3505 a search, check out the variable `org-tags-match-list-sublevels'."
3506 :group 'org-tags
3507 :type '(choice
3508 (const :tag "Not" nil)
3509 (const :tag "Always" t)
3510 (repeat :tag "Specific tags" (string :tag "Tag"))
3511 (regexp :tag "Tags matched by regexp")))
3513 (defcustom org-tags-exclude-from-inheritance nil
3514 "List of tags that should never be inherited.
3515 This is a way to exclude a few tags from inheritance. For way to do
3516 the opposite, to actively allow inheritance for selected tags,
3517 see the variable `org-use-tag-inheritance'."
3518 :group 'org-tags
3519 :type '(repeat (string :tag "Tag")))
3521 (defun org-tag-inherit-p (tag)
3522 "Check if TAG is one that should be inherited."
3523 (cond
3524 ((member tag org-tags-exclude-from-inheritance) nil)
3525 ((eq org-use-tag-inheritance t) t)
3526 ((not org-use-tag-inheritance) nil)
3527 ((stringp org-use-tag-inheritance)
3528 (string-match org-use-tag-inheritance tag))
3529 ((listp org-use-tag-inheritance)
3530 (member tag org-use-tag-inheritance))
3531 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3533 (defcustom org-tags-match-list-sublevels t
3534 "Non-nil means list also sublevels of headlines matching a search.
3535 This variable applies to tags/property searches, and also to stuck
3536 projects because this search is based on a tags match as well.
3538 When set to the symbol `indented', sublevels are indented with
3539 leading dots.
3541 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3542 the sublevels of a headline matching a tag search often also match
3543 the same search. Listing all of them can create very long lists.
3544 Setting this variable to nil causes subtrees of a match to be skipped.
3546 This variable is semi-obsolete and probably should always be true. It
3547 is better to limit inheritance to certain tags using the variables
3548 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No, don't list them" nil)
3552 (const :tag "Yes, do list them" t)
3553 (const :tag "List them, indented with leading dots" indented)))
3555 (defcustom org-tags-sort-function nil
3556 "When set, tags are sorted using this function as a comparator."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "No sorting" nil)
3560 (const :tag "Alphabetical" string<)
3561 (const :tag "Reverse alphabetical" string>)
3562 (function :tag "Custom function" nil)))
3564 (defvar org-tags-history nil
3565 "History of minibuffer reads for tags.")
3566 (defvar org-last-tags-completion-table nil
3567 "The last used completion table for tags.")
3568 (defvar org-after-tags-change-hook nil
3569 "Hook that is run after the tags in a line have changed.")
3571 (defgroup org-properties nil
3572 "Options concerning properties in Org mode."
3573 :tag "Org Properties"
3574 :group 'org)
3576 (defcustom org-property-format "%-10s %s"
3577 "How property key/value pairs should be formatted by `indent-line'.
3578 When `indent-line' hits a property definition, it will format the line
3579 according to this format, mainly to make sure that the values are
3580 lined-up with respect to each other."
3581 :group 'org-properties
3582 :type 'string)
3584 (defcustom org-properties-postprocess-alist nil
3585 "Alist of properties and functions to adjust inserted values.
3586 Elements of this alist must be of the form
3588 ([string] [function])
3590 where [string] must be a property name and [function] must be a
3591 lambda expression: this lambda expression must take one argument,
3592 the value to adjust, and return the new value as a string.
3594 For example, this element will allow the property \"Remaining\"
3595 to be updated wrt the relation between the \"Effort\" property
3596 and the clock summary:
3598 ((\"Remaining\" (lambda(value)
3599 (let ((clocksum (org-clock-sum-current-item))
3600 (effort (org-duration-to-minutes
3601 (org-entry-get (point) \"Effort\"))))
3602 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3603 :group 'org-properties
3604 :version "24.1"
3605 :type '(alist :key-type (string :tag "Property")
3606 :value-type (function :tag "Function")))
3608 (defcustom org-use-property-inheritance nil
3609 "Non-nil means properties apply also for sublevels.
3611 This setting is chiefly used during property searches. Turning it on can
3612 cause significant overhead when doing a search, which is why it is not
3613 on by default.
3615 When nil, only the properties directly given in the current entry count.
3616 When t, every property is inherited. The value may also be a list of
3617 properties that should have inheritance, or a regular expression matching
3618 properties that should be inherited.
3620 However, note that some special properties use inheritance under special
3621 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3622 and the properties ending in \"_ALL\" when they are used as descriptor
3623 for valid values of a property.
3625 Note for programmers:
3626 When querying an entry with `org-entry-get', you can control if inheritance
3627 should be used. By default, `org-entry-get' looks only at the local
3628 properties. You can request inheritance by setting the inherit argument
3629 to t (to force inheritance) or to `selective' (to respect the setting
3630 in this variable)."
3631 :group 'org-properties
3632 :type '(choice
3633 (const :tag "Not" nil)
3634 (const :tag "Always" t)
3635 (repeat :tag "Specific properties" (string :tag "Property"))
3636 (regexp :tag "Properties matched by regexp")))
3638 (defun org-property-inherit-p (property)
3639 "Return a non-nil value if PROPERTY should be inherited."
3640 (cond
3641 ((eq org-use-property-inheritance t) t)
3642 ((not org-use-property-inheritance) nil)
3643 ((stringp org-use-property-inheritance)
3644 (string-match org-use-property-inheritance property))
3645 ((listp org-use-property-inheritance)
3646 (member-ignore-case property org-use-property-inheritance))
3647 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3649 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3650 "The default column format, if no other format has been defined.
3651 This variable can be set on the per-file basis by inserting a line
3653 #+COLUMNS: %25ITEM ....."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-columns-ellipses ".."
3658 "The ellipses to be used when a field in column view is truncated.
3659 When this is the empty string, as many characters as possible are shown,
3660 but then there will be no visual indication that the field has been truncated.
3661 When this is a string of length N, the last N characters of a truncated
3662 field are replaced by this string. If the column is narrower than the
3663 ellipses string, only part of the ellipses string will be shown."
3664 :group 'org-properties
3665 :type 'string)
3667 (defconst org-global-properties-fixed
3668 '(("VISIBILITY_ALL" . "folded children content all")
3669 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3670 "List of property/value pairs that can be inherited by any entry.
3672 These are fixed values, for the preset properties. The user variable
3673 that can be used to add to this list is `org-global-properties'.
3675 The entries in this list are cons cells where the car is a property
3676 name and cdr is a string with the value. If the value represents
3677 multiple items like an \"_ALL\" property, separate the items by
3678 spaces.")
3680 (defcustom org-global-properties nil
3681 "List of property/value pairs that can be inherited by any entry.
3683 This list will be combined with the constant `org-global-properties-fixed'.
3685 The entries in this list are cons cells where the car is a property
3686 name and cdr is a string with the value.
3688 You can set buffer-local values for the same purpose in the variable
3689 `org-file-properties' this by adding lines like
3691 #+PROPERTY: NAME VALUE"
3692 :group 'org-properties
3693 :type '(repeat
3694 (cons (string :tag "Property")
3695 (string :tag "Value"))))
3697 (defvar-local org-file-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3699 Valid for the current buffer.
3700 This variable is populated from #+PROPERTY lines.")
3702 (defgroup org-agenda nil
3703 "Options concerning agenda views in Org mode."
3704 :tag "Org Agenda"
3705 :group 'org)
3707 (defvar-local org-category nil
3708 "Variable used by org files to set a category for agenda display.
3709 Such files should use a file variable to set it, for example
3711 # -*- mode: org; org-category: \"ELisp\"
3713 or contain a special line
3715 #+CATEGORY: ELisp
3717 If the file does not specify a category, then file's base name
3718 is used instead.")
3719 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3721 (defcustom org-agenda-files nil
3722 "The files to be used for agenda display.
3724 If an entry is a directory, all files in that directory that are matched
3725 by `org-agenda-file-regexp' will be part of the file list.
3727 If the value of the variable is not a list but a single file name, then
3728 the list of agenda files is actually stored and maintained in that file,
3729 one agenda file per line. In this file paths can be given relative to
3730 `org-directory'. Tilde expansion and environment variable substitution
3731 are also made.
3733 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3734 and removed with `\\[org-remove-file]'."
3735 :group 'org-agenda
3736 :type '(choice
3737 (repeat :tag "List of files and directories" file)
3738 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3740 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3741 "Regular expression to match files for `org-agenda-files'.
3742 If any element in the list in that variable contains a directory instead
3743 of a normal file, all files in that directory that are matched by this
3744 regular expression will be included."
3745 :group 'org-agenda
3746 :type 'regexp)
3748 (defcustom org-agenda-text-search-extra-files nil
3749 "List of extra files to be searched by text search commands.
3750 These files will be searched in addition to the agenda files by the
3751 commands `org-search-view' (`\\[org-agenda] s') \
3752 and `org-occur-in-agenda-files'.
3753 Note that these files will only be searched for text search commands,
3754 not for the other agenda views like todo lists, tag searches or the weekly
3755 agenda. This variable is intended to list notes and possibly archive files
3756 that should also be searched by these two commands.
3757 In fact, if the first element in the list is the symbol `agenda-archives',
3758 then all archive files of all agenda files will be added to the search
3759 scope."
3760 :group 'org-agenda
3761 :type '(set :greedy t
3762 (const :tag "Agenda Archives" agenda-archives)
3763 (repeat :inline t (file))))
3765 (defvaralias 'org-agenda-multi-occur-extra-files
3766 'org-agenda-text-search-extra-files)
3768 (defcustom org-agenda-skip-unavailable-files nil
3769 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3770 A nil value means to remove them, after a query, from the list."
3771 :group 'org-agenda
3772 :type 'boolean)
3774 (defcustom org-calendar-to-agenda-key [?c]
3775 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3776 The command `org-calendar-goto-agenda' will be bound to this key. The
3777 default is the character `c' because then `c' can be used to switch back and
3778 forth between agenda and calendar."
3779 :group 'org-agenda
3780 :type 'sexp)
3782 (defcustom org-calendar-insert-diary-entry-key [?i]
3783 "The key to be installed in `calendar-mode-map' for adding diary entries.
3784 This option is irrelevant until `org-agenda-diary-file' has been configured
3785 to point to an Org file. When that is the case, the command
3786 `org-agenda-diary-entry' will be bound to the key given here, by default
3787 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3788 if you want to continue doing this, you need to change this to a different
3789 key."
3790 :group 'org-agenda
3791 :type 'sexp)
3793 (defcustom org-agenda-diary-file 'diary-file
3794 "File to which to add new entries with the `i' key in agenda and calendar.
3795 When this is the symbol `diary-file', the functionality in the Emacs
3796 calendar will be used to add entries to the `diary-file'. But when this
3797 points to a file, `org-agenda-diary-entry' will be used instead."
3798 :group 'org-agenda
3799 :type '(choice
3800 (const :tag "The standard Emacs diary file" diary-file)
3801 (file :tag "Special Org file diary entries")))
3803 (eval-after-load "calendar"
3804 '(progn
3805 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3806 'org-calendar-goto-agenda)
3807 (add-hook 'calendar-mode-hook
3808 (lambda ()
3809 (unless (eq org-agenda-diary-file 'diary-file)
3810 (define-key calendar-mode-map
3811 org-calendar-insert-diary-entry-key
3812 'org-agenda-diary-entry))))))
3814 (defgroup org-latex nil
3815 "Options for embedding LaTeX code into Org mode."
3816 :tag "Org LaTeX"
3817 :group 'org)
3819 (defcustom org-format-latex-options
3820 '(:foreground default :background default :scale 1.0
3821 :html-foreground "Black" :html-background "Transparent"
3822 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3823 "Options for creating images from LaTeX fragments.
3824 This is a property list with the following properties:
3825 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3826 `default' means use the foreground of the default face.
3827 `auto' means use the foreground from the text face.
3828 :background the background color, or \"Transparent\".
3829 `default' means use the background of the default face.
3830 `auto' means use the background from the text face.
3831 :scale a scaling factor for the size of the images, to get more pixels
3832 :html-foreground, :html-background, :html-scale
3833 the same numbers for HTML export.
3834 :matchers a list indicating which matchers should be used to
3835 find LaTeX fragments. Valid members of this list are:
3836 \"begin\" find environments
3837 \"$1\" find single characters surrounded by $.$
3838 \"$\" find math expressions surrounded by $...$
3839 \"$$\" find math expressions surrounded by $$....$$
3840 \"\\(\" find math expressions surrounded by \\(...\\)
3841 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3842 :group 'org-latex
3843 :type 'plist)
3845 (defcustom org-format-latex-signal-error t
3846 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3847 When nil, just push out a message."
3848 :group 'org-latex
3849 :version "24.1"
3850 :type 'boolean)
3852 (defcustom org-latex-to-mathml-jar-file nil
3853 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3854 Use this to specify additional executable file say a jar file.
3856 When using MathToWeb as the converter, specify the full-path to
3857 your mathtoweb.jar file."
3858 :group 'org-latex
3859 :version "24.1"
3860 :type '(choice
3861 (const :tag "None" nil)
3862 (file :tag "JAR file" :must-match t)))
3864 (defcustom org-latex-to-mathml-convert-command nil
3865 "Command to convert LaTeX fragments to MathML.
3866 Replace format-specifiers in the command as noted below and use
3867 `shell-command' to convert LaTeX to MathML.
3868 %j: Executable file in fully expanded form as specified by
3869 `org-latex-to-mathml-jar-file'.
3870 %I: Input LaTeX file in fully expanded form.
3871 %i: The latex fragment to be converted.
3872 %o: Output MathML file.
3874 This command is used by `org-create-math-formula'.
3876 When using MathToWeb as the converter, set this option to
3877 \"java -jar %j -unicode -force -df %o %I\".
3879 When using LaTeXML set this option to
3880 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3881 :group 'org-latex
3882 :version "24.1"
3883 :type '(choice
3884 (const :tag "None" nil)
3885 (string :tag "\nShell command")))
3887 (defcustom org-preview-latex-default-process 'dvipng
3888 "The default process to convert LaTeX fragments to image files.
3889 All available processes and theirs documents can be found in
3890 `org-preview-latex-process-alist', which see."
3891 :group 'org-latex
3892 :version "26.1"
3893 :package-version '(Org . "9.0")
3894 :type 'symbol)
3896 (defcustom org-preview-latex-process-alist
3897 '((dvipng
3898 :programs ("latex" "dvipng")
3899 :description "dvi > png"
3900 :message "you need to install the programs: latex and dvipng."
3901 :image-input-type "dvi"
3902 :image-output-type "png"
3903 :image-size-adjust (1.0 . 1.0)
3904 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3905 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3906 (dvisvgm
3907 :programs ("latex" "dvisvgm")
3908 :description "dvi > svg"
3909 :message "you need to install the programs: latex and dvisvgm."
3910 :use-xcolor t
3911 :image-input-type "dvi"
3912 :image-output-type "svg"
3913 :image-size-adjust (1.7 . 1.5)
3914 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3915 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3916 (imagemagick
3917 :programs ("latex" "convert")
3918 :description "pdf > png"
3919 :message "you need to install the programs: latex and imagemagick."
3920 :use-xcolor t
3921 :image-input-type "pdf"
3922 :image-output-type "png"
3923 :image-size-adjust (1.0 . 1.0)
3924 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3925 :image-converter
3926 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3927 "Definitions of external processes for LaTeX previewing.
3928 Org mode can use some external commands to generate TeX snippet's images for
3929 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3930 `org-create-formula-image' how to call them.
3932 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3933 PROPERTIES accepts the following attributes:
3935 :programs list of strings, required programs.
3936 :description string, describe the process.
3937 :message string, message it when required programs cannot be found.
3938 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3939 :image-output-type string, output file type of image converter (e.g., \"png\").
3940 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3941 deal with background and foreground color of image.
3942 Otherwise, dvipng style background and foreground color
3943 format are generated. You may then refer to them in
3944 command options with \"%F\" and \"%B\".
3945 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3946 image size showed in buffer and the cdr element is for
3947 HTML file. This option is only useful for process
3948 developers, users should use variable
3949 `org-format-latex-options' instead.
3950 :post-clean list of strings, files matched are to be cleaned up once
3951 the image is generated. When nil, the files with \".dvi\",
3952 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3953 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3954 be cleaned up.
3955 :latex-header list of strings, the LaTeX header of the snippet file.
3956 When nil, the fallback value is used instead, which is
3957 controlled by `org-format-latex-header',
3958 `org-latex-default-packages-alist' and
3959 `org-latex-packages-alist', which see.
3960 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3961 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3962 replaced with values defined below.
3963 :image-converter list of image converter commands strings. Each of them is
3964 given to the shell and supports any of the following
3965 place-holders defined below.
3967 Place-holders used by `:image-converter' and `:latex-compiler':
3969 %f input file name
3970 %b base name of input file
3971 %o base directory of input file
3972 %O absolute output file name
3974 Place-holders only used by `:image-converter':
3976 %F foreground of image
3977 %B background of image
3978 %D dpi, which is used to adjust image size by some processing commands.
3979 %S the image size scale ratio, which is used to adjust image size by some
3980 processing commands."
3981 :group 'org-latex
3982 :version "26.1"
3983 :package-version '(Org . "9.0")
3984 :type '(alist :tag "LaTeX to image backends"
3985 :value-type (plist)))
3987 (defcustom org-preview-latex-image-directory "ltximg/"
3988 "Path to store latex preview images.
3989 A relative path here creates many directories relative to the
3990 processed org files paths. An absolute path puts all preview
3991 images at the same place."
3992 :group 'org-latex
3993 :version "26.1"
3994 :package-version '(Org . "9.0")
3995 :type 'string)
3997 (defun org-format-latex-mathml-available-p ()
3998 "Return t if `org-latex-to-mathml-convert-command' is usable."
3999 (save-match-data
4000 (when (and (boundp 'org-latex-to-mathml-convert-command)
4001 org-latex-to-mathml-convert-command)
4002 (let ((executable (car (split-string
4003 org-latex-to-mathml-convert-command))))
4004 (when (executable-find executable)
4005 (if (string-match
4006 "%j" org-latex-to-mathml-convert-command)
4007 (file-readable-p org-latex-to-mathml-jar-file)
4008 t))))))
4010 (defcustom org-format-latex-header "\\documentclass{article}
4011 \\usepackage[usenames]{color}
4012 \[PACKAGES]
4013 \[DEFAULT-PACKAGES]
4014 \\pagestyle{empty} % do not remove
4015 % The settings below are copied from fullpage.sty
4016 \\setlength{\\textwidth}{\\paperwidth}
4017 \\addtolength{\\textwidth}{-3cm}
4018 \\setlength{\\oddsidemargin}{1.5cm}
4019 \\addtolength{\\oddsidemargin}{-2.54cm}
4020 \\setlength{\\evensidemargin}{\\oddsidemargin}
4021 \\setlength{\\textheight}{\\paperheight}
4022 \\addtolength{\\textheight}{-\\headheight}
4023 \\addtolength{\\textheight}{-\\headsep}
4024 \\addtolength{\\textheight}{-\\footskip}
4025 \\addtolength{\\textheight}{-3cm}
4026 \\setlength{\\topmargin}{1.5cm}
4027 \\addtolength{\\topmargin}{-2.54cm}"
4028 "The document header used for processing LaTeX fragments.
4029 It is imperative that this header make sure that no page number
4030 appears on the page. The package defined in the variables
4031 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4032 will either replace the placeholder \"[PACKAGES]\" in this
4033 header, or they will be appended."
4034 :group 'org-latex
4035 :type 'string)
4037 (defun org-set-packages-alist (var val)
4038 "Set the packages alist and make sure it has 3 elements per entry."
4039 (set var (mapcar (lambda (x)
4040 (if (and (consp x) (= (length x) 2))
4041 (list (car x) (nth 1 x) t)
4043 val)))
4045 (defun org-get-packages-alist (var)
4046 "Get the packages alist and make sure it has 3 elements per entry."
4047 (mapcar (lambda (x)
4048 (if (and (consp x) (= (length x) 2))
4049 (list (car x) (nth 1 x) t)
4051 (default-value var)))
4053 (defcustom org-latex-default-packages-alist
4054 '(("AUTO" "inputenc" t ("pdflatex"))
4055 ("T1" "fontenc" t ("pdflatex"))
4056 ("" "graphicx" t)
4057 ("" "grffile" t)
4058 ("" "longtable" nil)
4059 ("" "wrapfig" nil)
4060 ("" "rotating" nil)
4061 ("normalem" "ulem" t)
4062 ("" "amsmath" t)
4063 ("" "textcomp" t)
4064 ("" "amssymb" t)
4065 ("" "capt-of" nil)
4066 ("" "hyperref" nil))
4067 "Alist of default packages to be inserted in the header.
4069 Change this only if one of the packages here causes an
4070 incompatibility with another package you are using.
4072 The packages in this list are needed by one part or another of
4073 Org mode to function properly:
4075 - inputenc, fontenc: for basic font and character selection
4076 - graphicx: for including images
4077 - grffile: allow periods and spaces in graphics file names
4078 - longtable: For multipage tables
4079 - wrapfig: for figure placement
4080 - rotating: for sideways figures and tables
4081 - ulem: for underline and strike-through
4082 - amsmath: for subscript and superscript and math environments
4083 - textcomp, amssymb: for various symbols used
4084 for interpreting the entities in `org-entities'. You can skip
4085 some of these packages if you don't use any of their symbols.
4086 - capt-of: for captions outside of floats
4087 - hyperref: for cross references
4089 Therefore you should not modify this variable unless you know
4090 what you are doing. The one reason to change it anyway is that
4091 you might be loading some other package that conflicts with one
4092 of the default packages. Each element is either a cell or
4093 a string.
4095 A cell is of the format
4097 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4099 If SNIPPET-FLAG is non-nil, the package also needs to be included
4100 when compiling LaTeX snippets into images for inclusion into
4101 non-LaTeX output. COMPILERS is a list of compilers that should
4102 include the package, see `org-latex-compiler'. If the document
4103 compiler is not in the list, and the list is non-nil, the package
4104 will not be inserted in the final document.
4106 A string will be inserted as-is in the header of the document."
4107 :group 'org-latex
4108 :group 'org-export-latex
4109 :set 'org-set-packages-alist
4110 :get 'org-get-packages-alist
4111 :version "26.1"
4112 :package-version '(Org . "8.3")
4113 :type '(repeat
4114 (choice
4115 (list :tag "options/package pair"
4116 (string :tag "options")
4117 (string :tag "package")
4118 (boolean :tag "Snippet")
4119 (choice
4120 (const :tag "For all compilers" nil)
4121 (repeat :tag "Allowed compiler" string)))
4122 (string :tag "A line of LaTeX"))))
4124 (defcustom org-latex-packages-alist nil
4125 "Alist of packages to be inserted in every LaTeX header.
4127 These will be inserted after `org-latex-default-packages-alist'.
4128 Each element is either a cell or a string.
4130 A cell is of the format:
4132 (\"options\" \"package\" SNIPPET-FLAG)
4134 SNIPPET-FLAG, when non-nil, indicates that this package is also
4135 needed when turning LaTeX snippets into images for inclusion into
4136 non-LaTeX output.
4138 A string will be inserted as-is in the header of the document.
4140 Make sure that you only list packages here which:
4142 - you want in every file;
4143 - do not conflict with the setup in `org-format-latex-header';
4144 - do not conflict with the default packages in
4145 `org-latex-default-packages-alist'."
4146 :group 'org-latex
4147 :group 'org-export-latex
4148 :set 'org-set-packages-alist
4149 :get 'org-get-packages-alist
4150 :type '(repeat
4151 (choice
4152 (list :tag "options/package pair"
4153 (string :tag "options")
4154 (string :tag "package")
4155 (boolean :tag "Snippet"))
4156 (string :tag "A line of LaTeX"))))
4158 (defgroup org-appearance nil
4159 "Settings for Org mode appearance."
4160 :tag "Org Appearance"
4161 :group 'org)
4163 (defcustom org-level-color-stars-only nil
4164 "Non-nil means fontify only the stars in each headline.
4165 When nil, the entire headline is fontified.
4166 Changing it requires restart of `font-lock-mode' to become effective
4167 also in regions already fontified."
4168 :group 'org-appearance
4169 :type 'boolean)
4171 (defcustom org-hide-leading-stars nil
4172 "Non-nil means hide the first N-1 stars in a headline.
4173 This works by using the face `org-hide' for these stars. This
4174 face is white for a light background, and black for a dark
4175 background. You may have to customize the face `org-hide' to
4176 make this work.
4177 Changing it requires restart of `font-lock-mode' to become effective
4178 also in regions already fontified.
4179 You may also set this on a per-file basis by adding one of the following
4180 lines to the buffer:
4182 #+STARTUP: hidestars
4183 #+STARTUP: showstars"
4184 :group 'org-appearance
4185 :type 'boolean)
4187 (defcustom org-hidden-keywords nil
4188 "List of symbols corresponding to keywords to be hidden the org buffer.
4189 For example, a value \\='(title) for this list will make the document's title
4190 appear in the buffer without the initial #+TITLE: keyword."
4191 :group 'org-appearance
4192 :version "24.1"
4193 :type '(set (const :tag "#+AUTHOR" author)
4194 (const :tag "#+DATE" date)
4195 (const :tag "#+EMAIL" email)
4196 (const :tag "#+TITLE" title)))
4198 (defcustom org-custom-properties nil
4199 "List of properties (as strings) with a special meaning.
4200 The default use of these custom properties is to let the user
4201 hide them with `org-toggle-custom-properties-visibility'."
4202 :group 'org-properties
4203 :group 'org-appearance
4204 :version "24.3"
4205 :type '(repeat (string :tag "Property Name")))
4207 (defcustom org-fontify-done-headline nil
4208 "Non-nil means change the face of a headline if it is marked DONE.
4209 Normally, only the TODO/DONE keyword indicates the state of a headline.
4210 When this is non-nil, the headline after the keyword is set to the
4211 `org-headline-done' as an additional indication."
4212 :group 'org-appearance
4213 :type 'boolean)
4215 (defcustom org-fontify-emphasized-text t
4216 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4217 Changing this variable requires a restart of Emacs to take effect."
4218 :group 'org-appearance
4219 :type 'boolean)
4221 (defcustom org-fontify-whole-heading-line nil
4222 "Non-nil means fontify the whole line for headings.
4223 This is useful when setting a background color for the
4224 org-level-* faces."
4225 :group 'org-appearance
4226 :type 'boolean)
4228 (defcustom org-highlight-latex-and-related nil
4229 "Non-nil means highlight LaTeX related syntax in the buffer.
4230 When non nil, the value should be a list containing any of the
4231 following symbols:
4232 `latex' Highlight LaTeX snippets and environments.
4233 `script' Highlight subscript and superscript.
4234 `entities' Highlight entities."
4235 :group 'org-appearance
4236 :version "24.4"
4237 :package-version '(Org . "8.0")
4238 :type '(choice
4239 (const :tag "No highlighting" nil)
4240 (set :greedy t :tag "Highlight"
4241 (const :tag "LaTeX snippets and environments" latex)
4242 (const :tag "Subscript and superscript" script)
4243 (const :tag "Entities" entities))))
4245 (defcustom org-hide-emphasis-markers nil
4246 "Non-nil mean font-lock should hide the emphasis marker characters."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-hide-macro-markers nil
4251 "Non-nil mean font-lock should hide the brackets marking macro calls."
4252 :group 'org-appearance
4253 :type 'boolean)
4255 (defcustom org-pretty-entities nil
4256 "Non-nil means show entities as UTF8 characters.
4257 When nil, the \\name form remains in the buffer."
4258 :group 'org-appearance
4259 :version "24.1"
4260 :type 'boolean)
4262 (defcustom org-pretty-entities-include-sub-superscripts t
4263 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4264 :group 'org-appearance
4265 :version "24.1"
4266 :type 'boolean)
4268 (defvar org-emph-re nil
4269 "Regular expression for matching emphasis.
4270 After a match, the match groups contain these elements:
4271 0 The match of the full regular expression, including the characters
4272 before and after the proper match
4273 1 The character before the proper match, or empty at beginning of line
4274 2 The proper match, including the leading and trailing markers
4275 3 The leading marker like * or /, indicating the type of highlighting
4276 4 The text between the emphasis markers, not including the markers
4277 5 The character after the match, empty at the end of a line")
4279 (defvar org-verbatim-re nil
4280 "Regular expression for matching verbatim text.")
4282 (defvar org-emphasis-regexp-components) ; defined just below
4283 (defvar org-emphasis-alist) ; defined just below
4284 (defun org-set-emph-re (var val)
4285 "Set variable and compute the emphasis regular expression."
4286 (set var val)
4287 (when (and (boundp 'org-emphasis-alist)
4288 (boundp 'org-emphasis-regexp-components)
4289 org-emphasis-alist org-emphasis-regexp-components)
4290 (pcase-let*
4291 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4292 (body (if (<= nl 0) body
4293 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4294 (template
4295 (format (concat "\\([%s]\\|^\\)" ;before markers
4296 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4297 "\\([%s]\\|$\\)") ;after markers
4298 pre border border body border post)))
4299 (setq org-emph-re (format template "*/_+"))
4300 (setq org-verbatim-re (format template "=~")))))
4302 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4303 ;; set this option proved cumbersome. See this message/thread:
4304 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4305 (defvar org-emphasis-regexp-components
4306 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4307 "Components used to build the regular expression for emphasis.
4308 This is a list with five entries. Terminology: In an emphasis string
4309 like \" *strong word* \", we call the initial space PREMATCH, the final
4310 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4311 and \"trong wor\" is the body. The different components in this variable
4312 specify what is allowed/forbidden in each part:
4314 pre Chars allowed as prematch. Beginning of line will be allowed too.
4315 post Chars allowed as postmatch. End of line will be allowed too.
4316 border The chars *forbidden* as border characters.
4317 body-regexp A regexp like \".\" to match a body character. Don't use
4318 non-shy groups here, and don't allow newline here.
4319 newline The maximum number of newlines allowed in an emphasis exp.
4321 You need to reload Org or to restart Emacs after setting this.")
4323 (defcustom org-emphasis-alist
4324 '(("*" bold)
4325 ("/" italic)
4326 ("_" underline)
4327 ("=" org-verbatim verbatim)
4328 ("~" org-code verbatim)
4329 ("+" (:strike-through t)))
4330 "Alist of characters and faces to emphasize text.
4331 Text starting and ending with a special character will be emphasized,
4332 for example *bold*, _underlined_ and /italic/. This variable sets the
4333 marker characters and the face to be used by font-lock for highlighting
4334 in Org buffers.
4336 You need to reload Org or to restart Emacs after customizing this."
4337 :group 'org-appearance
4338 :set 'org-set-emph-re
4339 :version "24.4"
4340 :package-version '(Org . "8.0")
4341 :type '(repeat
4342 (list
4343 (string :tag "Marker character")
4344 (choice
4345 (face :tag "Font-lock-face")
4346 (plist :tag "Face property list"))
4347 (option (const verbatim)))))
4349 (defvar org-protecting-blocks '("src" "example" "export")
4350 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4351 This is needed for font-lock setup.")
4353 ;;; Functions and variables from their packages
4354 ;; Declared here to avoid compiler warnings
4355 (defvar mark-active)
4357 ;; Various packages
4358 (declare-function calc-eval "calc" (str &optional separator &rest args))
4359 (declare-function calendar-forward-day "cal-move" (arg))
4360 (declare-function calendar-goto-date "cal-move" (date))
4361 (declare-function calendar-goto-today "cal-move" ())
4362 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4363 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4364 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4365 (declare-function cdlatex-tab "ext:cdlatex" ())
4366 (declare-function dired-get-filename
4367 "dired"
4368 (&optional localp no-error-if-not-filep))
4369 (declare-function iswitchb-read-buffer
4370 "iswitchb"
4371 (prompt &optional
4372 default require-match _predicate start matches-set))
4373 (declare-function org-agenda-change-all-lines
4374 "org-agenda"
4375 (newhead hdmarker &optional fixface just-this))
4376 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4377 "org-agenda"
4378 (&optional end))
4379 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4380 (declare-function org-agenda-format-item
4381 "org-agenda"
4382 (extra txt &optional level category tags dotime
4383 remove-re habitp))
4384 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4385 (declare-function org-agenda-save-markers-for-cut-and-paste
4386 "org-agenda"
4387 (beg end))
4388 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4389 (declare-function org-agenda-skip "org-agenda" ())
4390 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4391 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4392 (declare-function org-indent-mode "org-indent" (&optional arg))
4393 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4394 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4395 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4396 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4397 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4398 (declare-function parse-time-string "parse-time" (string))
4400 (defvar align-mode-rules-list)
4401 (defvar calc-embedded-close-formula)
4402 (defvar calc-embedded-open-formula)
4403 (defvar calc-embedded-open-mode)
4404 (defvar font-lock-unfontify-region-function)
4405 (defvar iswitchb-temp-buflist)
4406 (defvar org-agenda-tags-todo-honor-ignore-options)
4407 (defvar remember-data-file)
4408 (defvar texmathp-why)
4410 ;;;###autoload
4411 (defun turn-on-orgtbl ()
4412 "Unconditionally turn on `orgtbl-mode'."
4413 (require 'org-table)
4414 (orgtbl-mode 1))
4416 (defun org-at-table-p (&optional table-type)
4417 "Non-nil if the cursor is inside an Org table.
4418 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4419 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4420 (or (not (derived-mode-p 'org-mode))
4421 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4422 (and e (or table-type
4423 (eq 'org (org-element-property :type e))))))))
4425 (defun org-at-table.el-p ()
4426 "Non-nil when point is at a table.el table."
4427 (and (org-match-line "[ \t]*[|+]")
4428 (let ((element (org-element-at-point)))
4429 (and (eq (org-element-type element) 'table)
4430 (eq (org-element-property :type element) 'table.el)))))
4432 (defun org-at-table-hline-p ()
4433 "Non-nil when point is inside a hline in a table.
4434 Assume point is already in a table."
4435 (org-match-line org-table-hline-regexp))
4437 (defun org-table-map-tables (function &optional quietly)
4438 "Apply FUNCTION to the start of all tables in the buffer."
4439 (org-with-wide-buffer
4440 (goto-char (point-min))
4441 (while (re-search-forward org-table-any-line-regexp nil t)
4442 (unless quietly
4443 (message "Mapping tables: %d%%"
4444 (floor (* 100.0 (point)) (buffer-size))))
4445 (beginning-of-line 1)
4446 (when (and (looking-at org-table-line-regexp)
4447 ;; Exclude tables in src/example/verbatim/clocktable blocks
4448 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4449 (save-excursion (funcall function))
4450 (or (looking-at org-table-line-regexp)
4451 (forward-char 1)))
4452 (re-search-forward org-table-any-border-regexp nil 1)))
4453 (unless quietly (message "Mapping tables: done")))
4455 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4456 (declare-function org-clock-update-mode-line "org-clock" ())
4457 (declare-function org-resolve-clocks "org-clock"
4458 (&optional also-non-dangling-p prompt last-valid))
4460 (defun org-at-TBLFM-p (&optional pos)
4461 "Non-nil when point (or POS) is in #+TBLFM line."
4462 (save-excursion
4463 (goto-char (or pos (point)))
4464 (beginning-of-line)
4465 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4466 (eq (org-element-type (org-element-at-point)) 'table))))
4468 (defvar org-clock-start-time)
4469 (defvar org-clock-marker (make-marker)
4470 "Marker recording the last clock-in.")
4471 (defvar org-clock-hd-marker (make-marker)
4472 "Marker recording the last clock-in, but the headline position.")
4473 (defvar org-clock-heading ""
4474 "The heading of the current clock entry.")
4475 (defun org-clock-is-active ()
4476 "Return the buffer where the clock is currently running.
4477 Return nil if no clock is running."
4478 (marker-buffer org-clock-marker))
4480 (defun org-check-running-clock ()
4481 "Check if the current buffer contains the running clock.
4482 If yes, offer to stop it and to save the buffer with the changes."
4483 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4484 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4485 (buffer-name))))
4486 (org-clock-out)
4487 (when (y-or-n-p "Save changed buffer?")
4488 (save-buffer))))
4490 (defun org-clocktable-try-shift (dir n)
4491 "Check if this line starts a clock table, if yes, shift the time block."
4492 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4493 (org-clocktable-shift dir n)))
4495 ;;;###autoload
4496 (defun org-clock-persistence-insinuate ()
4497 "Set up hooks for clock persistence."
4498 (require 'org-clock)
4499 (add-hook 'org-mode-hook 'org-clock-load)
4500 (add-hook 'kill-emacs-hook 'org-clock-save))
4502 (defgroup org-archive nil
4503 "Options concerning archiving in Org mode."
4504 :tag "Org Archive"
4505 :group 'org-structure)
4507 (defcustom org-archive-location "%s_archive::"
4508 "The location where subtrees should be archived.
4510 The value of this variable is a string, consisting of two parts,
4511 separated by a double-colon. The first part is a filename and
4512 the second part is a headline.
4514 When the filename is omitted, archiving happens in the same file.
4515 %s in the filename will be replaced by the current file
4516 name (without the directory part). Archiving to a different file
4517 is useful to keep archived entries from contributing to the
4518 Org Agenda.
4520 The archived entries will be filed as subtrees of the specified
4521 headline. When the headline is omitted, the subtrees are simply
4522 filed away at the end of the file, as top-level entries. Also in
4523 the heading you can use %s to represent the file name, this can be
4524 useful when using the same archive for a number of different files.
4526 Here are a few examples:
4527 \"%s_archive::\"
4528 If the current file is Projects.org, archive in file
4529 Projects.org_archive, as top-level trees. This is the default.
4531 \"::* Archived Tasks\"
4532 Archive in the current file, under the top-level headline
4533 \"* Archived Tasks\".
4535 \"~/org/archive.org::\"
4536 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4538 \"~/org/archive.org::* From %s\"
4539 Archive in file ~/org/archive.org (absolute path), under headlines
4540 \"From FILENAME\" where file name is the current file name.
4542 \"~/org/datetree.org::datetree/* Finished Tasks\"
4543 The \"datetree/\" string is special, signifying to archive
4544 items to the datetree. Items are placed in either the CLOSED
4545 date of the item, or the current date if there is no CLOSED date.
4546 The heading will be a subentry to the current date. There doesn't
4547 need to be a heading, but there always needs to be a slash after
4548 datetree. For example, to store archived items directly in the
4549 datetree, use \"~/org/datetree.org::datetree/\".
4551 \"basement::** Finished Tasks\"
4552 Archive in file ./basement (relative path), as level 3 trees
4553 below the level 2 heading \"** Finished Tasks\".
4555 You may set this option on a per-file basis by adding to the buffer a
4556 line like
4558 #+ARCHIVE: basement::** Finished Tasks
4560 You may also define it locally for a subtree by setting an ARCHIVE property
4561 in the entry. If such a property is found in an entry, or anywhere up
4562 the hierarchy, it will be used."
4563 :group 'org-archive
4564 :type 'string)
4566 (defcustom org-agenda-skip-archived-trees t
4567 "Non-nil means the agenda will skip any items located in archived trees.
4568 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4569 variable is no longer recommended, you should leave it at the value t.
4570 Instead, use the key `v' to cycle the archives-mode in the agenda."
4571 :group 'org-archive
4572 :group 'org-agenda-skip
4573 :type 'boolean)
4575 (defcustom org-columns-skip-archived-trees t
4576 "Non-nil means ignore archived trees when creating column view."
4577 :group 'org-archive
4578 :group 'org-properties
4579 :type 'boolean)
4581 (defcustom org-cycle-open-archived-trees nil
4582 "Non-nil means `org-cycle' will open archived trees.
4583 An archived tree is a tree marked with the tag ARCHIVE.
4584 When nil, archived trees will stay folded. You can still open them with
4585 normal outline commands like `show-all', but not with the cycling commands."
4586 :group 'org-archive
4587 :group 'org-cycle
4588 :type 'boolean)
4590 (defcustom org-sparse-tree-open-archived-trees nil
4591 "Non-nil means sparse tree construction shows matches in archived trees.
4592 When nil, matches in these trees are highlighted, but the trees are kept in
4593 collapsed state."
4594 :group 'org-archive
4595 :group 'org-sparse-trees
4596 :type 'boolean)
4598 (defcustom org-sparse-tree-default-date-type nil
4599 "The default date type when building a sparse tree.
4600 When this is nil, a date is a scheduled or a deadline timestamp.
4601 Otherwise, these types are allowed:
4603 all: all timestamps
4604 active: only active timestamps (<...>)
4605 inactive: only inactive timestamps ([...])
4606 scheduled: only scheduled timestamps
4607 deadline: only deadline timestamps"
4608 :type '(choice (const :tag "Scheduled or deadline" nil)
4609 (const :tag "All timestamps" all)
4610 (const :tag "Only active timestamps" active)
4611 (const :tag "Only inactive timestamps" inactive)
4612 (const :tag "Only scheduled timestamps" scheduled)
4613 (const :tag "Only deadline timestamps" deadline)
4614 (const :tag "Only closed timestamps" closed))
4615 :version "26.1"
4616 :package-version '(Org . "8.3")
4617 :group 'org-sparse-trees)
4619 (defun org-cycle-hide-archived-subtrees (state)
4620 "Re-hide all archived subtrees after a visibility state change.
4621 STATE should be one of the symbols listed in the docstring of
4622 `org-cycle-hook'."
4623 (when (and (not org-cycle-open-archived-trees)
4624 (not (memq state '(overview folded))))
4625 (save-excursion
4626 (let* ((globalp (memq state '(contents all)))
4627 (beg (if globalp (point-min) (point)))
4628 (end (if globalp (point-max) (org-end-of-subtree t))))
4629 (org-hide-archived-subtrees beg end)
4630 (goto-char beg)
4631 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4632 (message "%s" (substitute-command-keys
4633 "Subtree is archived and stays closed. Use \
4634 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4636 (defun org-force-cycle-archived ()
4637 "Cycle subtree even if it is archived."
4638 (interactive)
4639 (setq this-command 'org-cycle)
4640 (let ((org-cycle-open-archived-trees t))
4641 (call-interactively 'org-cycle)))
4643 (defun org-hide-archived-subtrees (beg end)
4644 "Re-hide all archived subtrees after a visibility state change."
4645 (org-with-wide-buffer
4646 (let ((case-fold-search nil)
4647 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4648 (goto-char beg)
4649 ;; Include headline point is currently on.
4650 (beginning-of-line)
4651 (while (and (< (point) end) (re-search-forward re end t))
4652 (when (member org-archive-tag (org-get-tags))
4653 (org-flag-subtree t)
4654 (org-end-of-subtree t))))))
4656 (declare-function outline-end-of-heading "outline" ())
4657 (declare-function outline-flag-region "outline" (from to flag))
4658 (defun org-flag-subtree (flag)
4659 (save-excursion
4660 (org-back-to-heading t)
4661 (outline-end-of-heading)
4662 (outline-flag-region (point)
4663 (progn (org-end-of-subtree t) (point))
4664 flag)))
4666 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4668 ;; Declare Column View Code
4670 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4671 (declare-function org-columns-compute "org-colview" (property))
4673 ;; Declare ID code
4675 (declare-function org-id-store-link "org-id")
4676 (declare-function org-id-locations-load "org-id")
4677 (declare-function org-id-locations-save "org-id")
4678 (defvar org-id-track-globally)
4680 ;;; Variables for pre-computed regular expressions, all buffer local
4682 (defvar-local org-todo-regexp nil
4683 "Matches any of the TODO state keywords.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-not-done-regexp nil
4688 "Matches any of the TODO state keywords except the last one.
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-heading-regexp nil
4693 "Matches a TODO headline that is not done.
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-todo-line-regexp nil
4698 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4703 "Matches a headline and puts everything into groups:
4705 group 1: Stars
4706 group 2: The TODO keyword, maybe
4707 group 3: Priority cookie
4708 group 4: True headline
4709 group 5: Tags
4711 Since TODO keywords are case-sensitive, `case-fold-search' is
4712 expected to be bound to nil when matching against this regexp.")
4714 (defvar-local org-complex-heading-regexp-format nil
4715 "Printf format to make regexp to match an exact headline.
4716 This regexp will match the headline of any node which has the
4717 exact headline text that is put into the format, but may have any
4718 TODO state, priority and tags.")
4720 (defvar-local org-todo-line-tags-regexp nil
4721 "Matches a headline and puts TODO state into group 2 if present.
4722 Also put tags into group 4 if tags are present.")
4724 (defconst org-plain-time-of-day-regexp
4725 (concat
4726 "\\(\\<[012]?[0-9]"
4727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4728 "\\(--?"
4729 "\\(\\<[012]?[0-9]"
4730 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4731 "\\)?")
4732 "Regular expression to match a plain time or time range.
4733 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4734 groups carry important information:
4735 0 the full match
4736 1 the first time, range or not
4737 8 the second time, if it is a range.")
4739 (defconst org-plain-time-extension-regexp
4740 (concat
4741 "\\(\\<[012]?[0-9]"
4742 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4743 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4744 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4745 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4746 groups carry important information:
4747 0 the full match
4748 7 hours of duration
4749 9 minutes of duration")
4751 (defconst org-stamp-time-of-day-regexp
4752 (concat
4753 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4754 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4755 "\\(--?"
4756 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4757 "Regular expression to match a timestamp time or time range.
4758 After a match, the following groups carry important information:
4759 0 the full match
4760 1 date plus weekday, for back referencing to make sure both times are on the same day
4761 2 the first time, range or not
4762 4 the second time, if it is a range.")
4764 (defconst org-startup-options
4765 '(("fold" org-startup-folded t)
4766 ("overview" org-startup-folded t)
4767 ("nofold" org-startup-folded nil)
4768 ("showall" org-startup-folded nil)
4769 ("showeverything" org-startup-folded showeverything)
4770 ("content" org-startup-folded content)
4771 ("indent" org-startup-indented t)
4772 ("noindent" org-startup-indented nil)
4773 ("hidestars" org-hide-leading-stars t)
4774 ("showstars" org-hide-leading-stars nil)
4775 ("odd" org-odd-levels-only t)
4776 ("oddeven" org-odd-levels-only nil)
4777 ("align" org-startup-align-all-tables t)
4778 ("noalign" org-startup-align-all-tables nil)
4779 ("shrink" org-startup-shrink-all-tables t)
4780 ("inlineimages" org-startup-with-inline-images t)
4781 ("noinlineimages" org-startup-with-inline-images nil)
4782 ("latexpreview" org-startup-with-latex-preview t)
4783 ("nolatexpreview" org-startup-with-latex-preview nil)
4784 ("customtime" org-display-custom-times t)
4785 ("logdone" org-log-done time)
4786 ("lognotedone" org-log-done note)
4787 ("nologdone" org-log-done nil)
4788 ("lognoteclock-out" org-log-note-clock-out t)
4789 ("nolognoteclock-out" org-log-note-clock-out nil)
4790 ("logrepeat" org-log-repeat state)
4791 ("lognoterepeat" org-log-repeat note)
4792 ("logdrawer" org-log-into-drawer t)
4793 ("nologdrawer" org-log-into-drawer nil)
4794 ("logstatesreversed" org-log-states-order-reversed t)
4795 ("nologstatesreversed" org-log-states-order-reversed nil)
4796 ("nologrepeat" org-log-repeat nil)
4797 ("logreschedule" org-log-reschedule time)
4798 ("lognotereschedule" org-log-reschedule note)
4799 ("nologreschedule" org-log-reschedule nil)
4800 ("logredeadline" org-log-redeadline time)
4801 ("lognoteredeadline" org-log-redeadline note)
4802 ("nologredeadline" org-log-redeadline nil)
4803 ("logrefile" org-log-refile time)
4804 ("lognoterefile" org-log-refile note)
4805 ("nologrefile" org-log-refile nil)
4806 ("fninline" org-footnote-define-inline t)
4807 ("nofninline" org-footnote-define-inline nil)
4808 ("fnlocal" org-footnote-section nil)
4809 ("fnauto" org-footnote-auto-label t)
4810 ("fnprompt" org-footnote-auto-label nil)
4811 ("fnconfirm" org-footnote-auto-label confirm)
4812 ("fnplain" org-footnote-auto-label plain)
4813 ("fnadjust" org-footnote-auto-adjust t)
4814 ("nofnadjust" org-footnote-auto-adjust nil)
4815 ("constcgs" constants-unit-system cgs)
4816 ("constSI" constants-unit-system SI)
4817 ("noptag" org-tag-persistent-alist nil)
4818 ("hideblocks" org-hide-block-startup t)
4819 ("nohideblocks" org-hide-block-startup nil)
4820 ("beamer" org-startup-with-beamer-mode t)
4821 ("entitiespretty" org-pretty-entities t)
4822 ("entitiesplain" org-pretty-entities nil))
4823 "Variable associated with STARTUP options for org-mode.
4824 Each element is a list of three items: the startup options (as written
4825 in the #+STARTUP line), the corresponding variable, and the value to set
4826 this variable to if the option is found. An optional forth element PUSH
4827 means to push this value onto the list in the variable.")
4829 (defcustom org-group-tags t
4830 "When non-nil (the default), use group tags.
4831 This can be turned on/off through `org-toggle-tags-groups'."
4832 :group 'org-tags
4833 :group 'org-startup
4834 :type 'boolean)
4836 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4838 (defun org-toggle-tags-groups ()
4839 "Toggle support for group tags.
4840 Support for group tags is controlled by the option
4841 `org-group-tags', which is non-nil by default."
4842 (interactive)
4843 (setq org-group-tags (not org-group-tags))
4844 (cond ((and (derived-mode-p 'org-agenda-mode)
4845 org-group-tags)
4846 (org-agenda-redo))
4847 ((derived-mode-p 'org-mode)
4848 (let ((org-inhibit-startup t)) (org-mode))))
4849 (message "Groups tags support has been turned %s"
4850 (if org-group-tags "on" "off")))
4852 (defun org-set-regexps-and-options (&optional tags-only)
4853 "Precompute regular expressions used in the current buffer.
4854 When optional argument TAGS-ONLY is non-nil, only compute tags
4855 related expressions."
4856 (when (derived-mode-p 'org-mode)
4857 (let ((alist (org--setup-collect-keywords
4858 (org-make-options-regexp
4859 (append '("FILETAGS" "TAGS" "SETUPFILE")
4860 (and (not tags-only)
4861 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4862 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4863 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4864 ;; Startup options. Get this early since it does change
4865 ;; behavior for other options (e.g., tags).
4866 (let ((startup (cdr (assq 'startup alist))))
4867 (dolist (option startup)
4868 (let ((entry (assoc-string option org-startup-options t)))
4869 (when entry
4870 (let ((var (nth 1 entry))
4871 (val (nth 2 entry)))
4872 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4873 (unless (listp (symbol-value var))
4874 (set (make-local-variable var) nil))
4875 (add-to-list var val)))))))
4876 (setq-local org-file-tags
4877 (mapcar #'org-add-prop-inherited
4878 (cdr (assq 'filetags alist))))
4879 (setq org-current-tag-alist
4880 (append org-tag-persistent-alist
4881 (let ((tags (cdr (assq 'tags alist))))
4882 (if tags (org-tag-string-to-alist tags)
4883 org-tag-alist))))
4884 (setq org-tag-groups-alist
4885 (org-tag-alist-to-groups org-current-tag-alist))
4886 (unless tags-only
4887 ;; File properties.
4888 (setq-local org-file-properties (cdr (assq 'property alist)))
4889 ;; Archive location.
4890 (let ((archive (cdr (assq 'archive alist))))
4891 (when archive (setq-local org-archive-location archive)))
4892 ;; Category.
4893 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4894 (when cat
4895 (setq-local org-category (intern cat))
4896 (setq-local org-file-properties
4897 (org--update-property-plist
4898 "CATEGORY" cat org-file-properties))))
4899 ;; Columns.
4900 (let ((column (cdr (assq 'columns alist))))
4901 (when column (setq-local org-columns-default-format column)))
4902 ;; Constants.
4903 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4904 ;; Link abbreviations.
4905 (let ((links (cdr (assq 'link alist))))
4906 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4907 ;; Priorities.
4908 (let ((priorities (cdr (assq 'priorities alist))))
4909 (when priorities
4910 (setq-local org-highest-priority (nth 0 priorities))
4911 (setq-local org-lowest-priority (nth 1 priorities))
4912 (setq-local org-default-priority (nth 2 priorities))))
4913 ;; Scripts.
4914 (let ((scripts (assq 'scripts alist)))
4915 (when scripts
4916 (setq-local org-use-sub-superscripts (cdr scripts))))
4917 ;; TODO keywords.
4918 (setq-local org-todo-kwd-alist nil)
4919 (setq-local org-todo-key-alist nil)
4920 (setq-local org-todo-key-trigger nil)
4921 (setq-local org-todo-keywords-1 nil)
4922 (setq-local org-done-keywords nil)
4923 (setq-local org-todo-heads nil)
4924 (setq-local org-todo-sets nil)
4925 (setq-local org-todo-log-states nil)
4926 (let ((todo-sequences
4927 (or (nreverse (cdr (assq 'todo alist)))
4928 (let ((d (default-value 'org-todo-keywords)))
4929 (if (not (stringp (car d))) d
4930 ;; XXX: Backward compatibility code.
4931 (list (cons org-todo-interpretation d)))))))
4932 (dolist (sequence todo-sequences)
4933 (let* ((sequence (or (run-hook-with-args-until-success
4934 'org-todo-setup-filter-hook sequence)
4935 sequence))
4936 (sequence-type (car sequence))
4937 (keywords (cdr sequence))
4938 (sep (member "|" keywords))
4939 names alist)
4940 (dolist (k (remove "|" keywords))
4941 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4943 (error "Invalid TODO keyword %s" k))
4944 (let ((name (match-string 1 k))
4945 (key (match-string 2 k))
4946 (log (org-extract-log-state-settings k)))
4947 (push name names)
4948 (push (cons name (and key (string-to-char key))) alist)
4949 (when log (push log org-todo-log-states))))
4950 (let* ((names (nreverse names))
4951 (done (if sep (org-remove-keyword-keys (cdr sep))
4952 (last names)))
4953 (head (car names))
4954 (tail (list sequence-type head (car done) (org-last done))))
4955 (add-to-list 'org-todo-heads head 'append)
4956 (push names org-todo-sets)
4957 (setq org-done-keywords (append org-done-keywords done nil))
4958 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4959 (setq org-todo-key-alist
4960 (append org-todo-key-alist
4961 (and alist
4962 (append '((:startgroup))
4963 (nreverse alist)
4964 '((:endgroup))))))
4965 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4966 (setq org-todo-sets (nreverse org-todo-sets)
4967 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4968 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4969 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4970 ;; Compute the regular expressions and other local variables.
4971 ;; Using `org-outline-regexp-bol' would complicate them much,
4972 ;; because of the fixed white space at the end of that string.
4973 (unless org-done-keywords
4974 (setq org-done-keywords
4975 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4976 (setq org-not-done-keywords
4977 (org-delete-all org-done-keywords
4978 (copy-sequence org-todo-keywords-1))
4979 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4980 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4981 org-not-done-heading-regexp
4982 (format org-heading-keyword-regexp-format org-not-done-regexp)
4983 org-todo-line-regexp
4984 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4985 org-complex-heading-regexp
4986 (concat "^\\(\\*+\\)"
4987 "\\(?: +" org-todo-regexp "\\)?"
4988 "\\(?: +\\(\\[#.\\]\\)\\)?"
4989 "\\(?: +\\(.*?\\)\\)??"
4990 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4991 "[ \t]*$")
4992 org-complex-heading-regexp-format
4993 (concat "^\\(\\*+\\)"
4994 "\\(?: +" org-todo-regexp "\\)?"
4995 "\\(?: +\\(\\[#.\\]\\)\\)?"
4996 "\\(?: +"
4997 ;; Stats cookies can be stuck to body.
4998 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4999 "\\(%s\\)"
5000 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5001 "\\)"
5002 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5003 "[ \t]*$")
5004 org-todo-line-tags-regexp
5005 (concat "^\\(\\*+\\)"
5006 "\\(?: +" org-todo-regexp "\\)?"
5007 "\\(?: +\\(.*?\\)\\)??"
5008 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5009 "[ \t]*$"))
5010 (org-compute-latex-and-related-regexp)))))
5012 (defun org--setup-collect-keywords (regexp &optional files alist)
5013 "Return setup keywords values as an alist.
5015 REGEXP matches a subset of setup keywords. FILES is a list of
5016 file names already visited. It is used to avoid circular setup
5017 files. ALIST, when non-nil, is the alist computed so far.
5019 Return value contains the following keys: `archive', `category',
5020 `columns', `constants', `filetags', `link', `priorities',
5021 `property', `scripts', `startup', `tags' and `todo'."
5022 (org-with-wide-buffer
5023 (goto-char (point-min))
5024 (let ((case-fold-search t))
5025 (while (re-search-forward regexp nil t)
5026 (let ((element (org-element-at-point)))
5027 (when (eq (org-element-type element) 'keyword)
5028 (let ((key (org-element-property :key element))
5029 (value (org-element-property :value element)))
5030 (cond
5031 ((equal key "ARCHIVE")
5032 (when (org-string-nw-p value)
5033 (push (cons 'archive value) alist)))
5034 ((equal key "CATEGORY") (push (cons 'category value) alist))
5035 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5036 ((equal key "CONSTANTS")
5037 (let* ((constants (assq 'constants alist))
5038 (store (cdr constants)))
5039 (dolist (pair (split-string value))
5040 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5041 pair)
5042 (let* ((name (match-string 1 pair))
5043 (value (match-string 2 pair))
5044 (old (assoc name store)))
5045 (if old (setcdr old value)
5046 (push (cons name value) store)))))
5047 (if constants (setcdr constants store)
5048 (push (cons 'constants store) alist))))
5049 ((equal key "FILETAGS")
5050 (when (org-string-nw-p value)
5051 (let ((old (assq 'filetags alist))
5052 (new (apply #'nconc
5053 (mapcar (lambda (x) (org-split-string x ":"))
5054 (split-string value)))))
5055 (if old (setcdr old (append new (cdr old)))
5056 (push (cons 'filetags new) alist)))))
5057 ((equal key "LINK")
5058 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5059 (let ((links (assq 'link alist))
5060 (pair (cons (match-string-no-properties 1 value)
5061 (match-string-no-properties 2 value))))
5062 (if links (push pair (cdr links))
5063 (push (list 'link pair) alist)))))
5064 ((equal key "OPTIONS")
5065 (when (and (org-string-nw-p value)
5066 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5067 (push (cons 'scripts (read (match-string 1 value))) alist)))
5068 ((equal key "PRIORITIES")
5069 (push (cons 'priorities
5070 (let ((prio (split-string value)))
5071 (if (< (length prio) 3) '(?A ?C ?B)
5072 (mapcar #'string-to-char prio))))
5073 alist))
5074 ((equal key "PROPERTY")
5075 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5076 (let* ((property (assq 'property alist))
5077 (value (org--update-property-plist
5078 (match-string-no-properties 1 value)
5079 (match-string-no-properties 2 value)
5080 (cdr property))))
5081 (if property (setcdr property value)
5082 (push (cons 'property value) alist)))))
5083 ((equal key "STARTUP")
5084 (let ((startup (assq 'startup alist)))
5085 (if startup
5086 (setcdr startup
5087 (append (cdr startup) (split-string value)))
5088 (push (cons 'startup (split-string value)) alist))))
5089 ((equal key "TAGS")
5090 (let ((tag-cell (assq 'tags alist)))
5091 (if tag-cell
5092 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5093 (push (cons 'tags value) alist))))
5094 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5095 (let ((todo (assq 'todo alist))
5096 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5097 (split-string value))))
5098 (if todo (push value (cdr todo))
5099 (push (list 'todo value) alist))))
5100 ((equal key "SETUPFILE")
5101 (unless buffer-read-only ; Do not check in Gnus messages.
5102 (let ((f (and (org-string-nw-p value)
5103 (expand-file-name
5104 (org-unbracket-string "\"" "\"" value)))))
5105 (when (and f (file-readable-p f) (not (member f files)))
5106 (with-temp-buffer
5107 (setq default-directory (file-name-directory f))
5108 (insert-file-contents f)
5109 (setq alist
5110 ;; Fake Org mode to benefit from cache
5111 ;; without recurring needlessly.
5112 (let ((major-mode 'org-mode))
5113 (org--setup-collect-keywords
5114 regexp (cons f files) alist)))))))))))))))
5115 alist)
5117 (defun org-tag-string-to-alist (s)
5118 "Return tag alist associated to string S.
5119 S is a value for TAGS keyword or produced with
5120 `org-tag-alist-to-string'. Return value is an alist suitable for
5121 `org-tag-alist' or `org-tag-persistent-alist'."
5122 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5123 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5124 "\\|{.+?}\\)" ; regular expression
5125 "\\(?:(\\(.\\))\\)?\\'"))
5126 alist group-flag)
5127 (dolist (tokens lines (cdr (nreverse alist)))
5128 (push '(:newline) alist)
5129 (while tokens
5130 (let ((token (pop tokens)))
5131 (pcase token
5132 ("{"
5133 (push '(:startgroup) alist)
5134 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5135 ("}"
5136 (push '(:endgroup) alist)
5137 (setq group-flag nil))
5138 ("["
5139 (push '(:startgrouptag) alist)
5140 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5141 ("]"
5142 (push '(:endgrouptag) alist)
5143 (setq group-flag nil))
5144 (":"
5145 (push '(:grouptags) alist))
5146 ((guard (string-match tag-re token))
5147 (let ((tag (match-string 1 token))
5148 (key (and (match-beginning 2)
5149 (string-to-char (match-string 2 token)))))
5150 ;; Push all tags in groups, no matter if they already
5151 ;; appear somewhere else in the list.
5152 (when (or group-flag (not (assoc tag alist)))
5153 (push (cons tag key) alist))))))))))
5155 (defun org-tag-alist-to-string (alist &optional skip-key)
5156 "Return tag string associated to ALIST.
5158 ALIST is an alist, as defined in `org-tag-alist' or
5159 `org-tag-persistent-alist', or produced with
5160 `org-tag-string-to-alist'.
5162 Return value is a string suitable as a value for \"TAGS\"
5163 keyword.
5165 When optional argument SKIP-KEY is non-nil, skip selection keys
5166 next to tags."
5167 (mapconcat (lambda (token)
5168 (pcase token
5169 (`(:startgroup) "{")
5170 (`(:endgroup) "}")
5171 (`(:startgrouptag) "[")
5172 (`(:endgrouptag) "]")
5173 (`(:grouptags) ":")
5174 (`(:newline) "\\n")
5175 ((and
5176 (guard (not skip-key))
5177 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5178 (format "%s(%c)" tag key))
5179 (`(,(and tag (pred stringp)) . ,_) tag)
5180 (_ (user-error "Invalid tag token: %S" token))))
5181 alist
5182 " "))
5184 (defun org-tag-alist-to-groups (alist)
5185 "Return group alist from tag ALIST.
5186 ALIST is an alist, as defined in `org-tag-alist' or
5187 `org-tag-persistent-alist', or produced with
5188 `org-tag-string-to-alist'. Return value is an alist following
5189 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5190 a string, summarizing TAGS, as a list of strings."
5191 (let (groups group-status current-group)
5192 (dolist (token alist (nreverse groups))
5193 (pcase token
5194 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5195 (`(,(or :endgroup :endgrouptag))
5196 (when (eq group-status 'append)
5197 (push (nreverse current-group) groups))
5198 (setq group-status nil))
5199 (`(:grouptags) (setq group-status 'append))
5200 ((and `(,tag . ,_) (guard group-status))
5201 (if (eq group-status 'append) (push tag current-group)
5202 (setq current-group (list tag))))
5203 (_ nil)))))
5205 (defvar org--file-cache (make-hash-table :test #'equal)
5206 "Hash table to store contents of files referenced via a URL.
5207 This is the cache of file URLs read using `org-file-contents'.")
5209 (defun org-reset-file-cache ()
5210 "Reset the cache of files downloaded by `org-file-contents'."
5211 (clrhash org--file-cache))
5213 (defun org-file-url-p (file)
5214 "Non-nil if FILE is a URL."
5215 (require 'ffap)
5216 (string-match-p ffap-url-regexp file))
5218 (defun org-file-contents (file &optional noerror nocache)
5219 "Return the contents of FILE, as a string.
5221 FILE can be a file name or URL.
5223 If FILE is a URL, download the contents. If the URL contents are
5224 already cached in the `org--file-cache' hash table, the download step
5225 is skipped.
5227 If NOERROR is non-nil, ignore the error when unable to read the FILE
5228 from file or URL.
5230 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5231 is available. This option applies only if FILE is a URL."
5232 (let* ((is-url (org-file-url-p file))
5233 (cache (and is-url
5234 (not nocache)
5235 (gethash file org--file-cache))))
5236 (cond
5237 (cache)
5238 (is-url
5239 (with-current-buffer (url-retrieve-synchronously file)
5240 (goto-char (point-min))
5241 ;; Move point to after the url-retrieve header.
5242 (search-forward "\n\n" nil :move)
5243 ;; Search for the success code only in the url-retrieve header.
5244 (if (save-excursion
5245 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5246 ;; Update the cache `org--file-cache' and return contents.
5247 (puthash file
5248 (buffer-substring-no-properties (point) (point-max))
5249 org--file-cache)
5250 (funcall (if noerror #'message #'user-error)
5251 "Unable to fetch file from %S"
5252 file))))
5254 (with-temp-buffer
5255 (condition-case nil
5256 (progn
5257 (insert-file-contents file)
5258 (buffer-string))
5259 (file-error
5260 (funcall (if noerror #'message #'user-error)
5261 "Unable to read file %S"
5262 file))))))))
5264 (defun org-extract-log-state-settings (x)
5265 "Extract the log state setting from a TODO keyword string.
5266 This will extract info from a string like \"WAIT(w@/!)\"."
5267 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5268 (let ((kw (match-string 1 x))
5269 (log1 (and (match-end 3) (match-string 3 x)))
5270 (log2 (and (match-end 4) (match-string 4 x))))
5271 (and (or log1 log2)
5272 (list kw
5273 (and log1 (if (equal log1 "!") 'time 'note))
5274 (and log2 (if (equal log2 "!") 'time 'note)))))))
5276 (defun org-remove-keyword-keys (list)
5277 "Remove a pair of parenthesis at the end of each string in LIST."
5278 (mapcar (lambda (x)
5279 (if (string-match "(.*)$" x)
5280 (substring x 0 (match-beginning 0))
5282 list))
5284 (defun org-assign-fast-keys (alist)
5285 "Assign fast keys to a keyword-key alist.
5286 Respect keys that are already there."
5287 (let (new e (alt ?0))
5288 (while (setq e (pop alist))
5289 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5290 (cdr e)) ;; Key already assigned.
5291 (push e new)
5292 (let ((clist (string-to-list (downcase (car e))))
5293 (used (append new alist)))
5294 (when (= (car clist) ?@)
5295 (pop clist))
5296 (while (and clist (rassoc (car clist) used))
5297 (pop clist))
5298 (unless clist
5299 (while (rassoc alt used)
5300 (cl-incf alt)))
5301 (push (cons (car e) (or (car clist) alt)) new))))
5302 (nreverse new)))
5304 ;;; Some variables used in various places
5306 (defvar org-window-configuration nil
5307 "Used in various places to store a window configuration.")
5308 (defvar org-selected-window nil
5309 "Used in various places to store a window configuration.")
5310 (defvar org-finish-function nil
5311 "Function to be called when `C-c C-c' is used.
5312 This is for getting out of special buffers like capture.")
5313 (defvar org-last-state)
5315 ;; Defined somewhere in this file, but used before definition.
5316 (defvar org-entities) ;; defined in org-entities.el
5317 (defvar org-struct-menu)
5318 (defvar org-org-menu)
5319 (defvar org-tbl-menu)
5321 ;;;; Define the Org mode
5323 ;; We use a before-change function to check if a table might need
5324 ;; an update.
5325 (defvar org-table-may-need-update t
5326 "Indicates that a table might need an update.
5327 This variable is set by `org-before-change-function'.
5328 `org-table-align' sets it back to nil.")
5329 (defun org-before-change-function (_beg _end)
5330 "Every change indicates that a table might need an update."
5331 (setq org-table-may-need-update t))
5332 (defvar org-mode-map)
5333 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5334 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5335 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5336 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5337 (defvar org-table-buffer-is-an nil)
5339 (defvar bidi-paragraph-direction)
5340 (defvar buffer-face-mode-face)
5342 (require 'outline)
5344 ;; Other stuff we need.
5345 (require 'time-date)
5346 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5347 (require 'easymenu)
5348 (autoload 'easy-menu-add "easymenu")
5349 (require 'overlay)
5351 ;; (require 'org-macs) moved higher up in the file before it is first used
5352 (require 'org-entities)
5353 ;; (require 'org-compat) moved higher up in the file before it is first used
5354 (require 'org-faces)
5355 (require 'org-list)
5356 (require 'org-pcomplete)
5357 (require 'org-src)
5358 (require 'org-footnote)
5359 (require 'org-macro)
5361 ;; babel
5362 (require 'ob)
5364 ;;;###autoload
5365 (define-derived-mode org-mode outline-mode "Org"
5366 "Outline-based notes management and organizer, alias
5367 \"Carsten's outline-mode for keeping track of everything.\"
5369 Org mode develops organizational tasks around a NOTES file which
5370 contains information about projects as plain text. Org mode is
5371 implemented on top of Outline mode, which is ideal to keep the content
5372 of large files well structured. It supports ToDo items, deadlines and
5373 time stamps, which magically appear in the diary listing of the Emacs
5374 calendar. Tables are easily created with a built-in table editor.
5375 Plain text URL-like links connect to websites, emails (VM), Usenet
5376 messages (Gnus), BBDB entries, and any files related to the project.
5377 For printing and sharing of notes, an Org file (or a part of it)
5378 can be exported as a structured ASCII or HTML file.
5380 The following commands are available:
5382 \\{org-mode-map}"
5384 ;; Get rid of Outline menus, they are not needed
5385 ;; Need to do this here because define-derived-mode sets up
5386 ;; the keymap so late. Still, it is a waste to call this each time
5387 ;; we switch another buffer into Org mode.
5388 (define-key org-mode-map [menu-bar headings] 'undefined)
5389 (define-key org-mode-map [menu-bar hide] 'undefined)
5390 (define-key org-mode-map [menu-bar show] 'undefined)
5392 (org-load-modules-maybe)
5393 (org-install-agenda-files-menu)
5394 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5395 (add-to-invisibility-spec '(org-hide-block . t))
5396 (setq-local outline-regexp org-outline-regexp)
5397 (setq-local outline-level 'org-outline-level)
5398 (setq bidi-paragraph-direction 'left-to-right)
5399 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5400 (unless org-display-table
5401 (setq org-display-table (make-display-table)))
5402 (set-display-table-slot
5403 org-display-table 4
5404 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5405 org-ellipsis)))
5406 (setq buffer-display-table org-display-table))
5407 (org-set-regexps-and-options)
5408 (org-set-font-lock-defaults)
5409 (when (and org-tag-faces (not org-tags-special-faces-re))
5410 ;; tag faces set outside customize.... force initialization.
5411 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5412 ;; Calc embedded
5413 (setq-local calc-embedded-open-mode "# ")
5414 ;; Modify a few syntax entries
5415 (modify-syntax-entry ?@ "w")
5416 (modify-syntax-entry ?\" "\"")
5417 (modify-syntax-entry ?\\ "_")
5418 (modify-syntax-entry ?~ "_")
5419 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5420 ;; Activate before-change-function
5421 (setq-local org-table-may-need-update t)
5422 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5423 ;; Check for running clock before killing a buffer
5424 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5425 ;; Initialize macros templates.
5426 (org-macro-initialize-templates)
5427 ;; Initialize radio targets.
5428 (org-update-radio-target-regexp)
5429 ;; Indentation.
5430 (setq-local indent-line-function 'org-indent-line)
5431 (setq-local indent-region-function 'org-indent-region)
5432 ;; Filling and auto-filling.
5433 (org-setup-filling)
5434 ;; Comments.
5435 (org-setup-comments-handling)
5436 ;; Initialize cache.
5437 (org-element-cache-reset)
5438 ;; Beginning/end of defun
5439 (setq-local beginning-of-defun-function 'org-backward-element)
5440 (setq-local end-of-defun-function
5441 (lambda ()
5442 (if (not (org-at-heading-p))
5443 (org-forward-element)
5444 (org-forward-element)
5445 (forward-char -1))))
5446 ;; Next error for sparse trees
5447 (setq-local next-error-function 'org-occur-next-match)
5448 ;; Make sure dependence stuff works reliably, even for users who set it
5449 ;; too late :-(
5450 (if org-enforce-todo-dependencies
5451 (add-hook 'org-blocker-hook
5452 'org-block-todo-from-children-or-siblings-or-parent)
5453 (remove-hook 'org-blocker-hook
5454 'org-block-todo-from-children-or-siblings-or-parent))
5455 (if org-enforce-todo-checkbox-dependencies
5456 (add-hook 'org-blocker-hook
5457 'org-block-todo-from-checkboxes)
5458 (remove-hook 'org-blocker-hook
5459 'org-block-todo-from-checkboxes))
5461 ;; Align options lines
5462 (setq-local
5463 align-mode-rules-list
5464 '((org-in-buffer-settings
5465 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5466 (modes . '(org-mode)))))
5468 ;; Imenu
5469 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5471 ;; Make isearch reveal context
5472 (setq-local outline-isearch-open-invisible-function
5473 (lambda (&rest _) (org-show-context 'isearch)))
5475 ;; Setup the pcomplete hooks
5476 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5477 (setq-local pcomplete-command-name-function 'org-command-at-point)
5478 (setq-local pcomplete-default-completion-function 'ignore)
5479 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5480 (setq-local pcomplete-termination-string "")
5481 (setq-local buffer-face-mode-face 'org-default)
5483 ;; If empty file that did not turn on Org mode automatically, make
5484 ;; it to.
5485 (when (and org-insert-mode-line-in-empty-file
5486 (called-interactively-p 'any)
5487 (= (point-min) (point-max)))
5488 (insert "# -*- mode: org -*-\n\n"))
5489 (unless org-inhibit-startup
5490 (org-unmodified
5491 (when org-startup-with-beamer-mode (org-beamer-mode))
5492 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5493 (org-table-map-tables
5494 (cond ((and org-startup-align-all-tables
5495 org-startup-shrink-all-tables)
5496 (lambda () (org-table-align) (org-table-shrink)))
5497 (org-startup-align-all-tables #'org-table-align)
5498 (t #'org-table-shrink))
5500 (when org-startup-with-inline-images (org-display-inline-images))
5501 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5502 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5503 (when org-startup-truncated (setq truncate-lines t))
5504 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5505 (org-refresh-effort-properties)))
5506 ;; Try to set `org-hide' face correctly.
5507 (let ((foreground (org-find-invisible-foreground)))
5508 (when foreground
5509 (set-face-foreground 'org-hide foreground))))
5511 ;; Update `customize-package-emacs-version-alist'
5512 (add-to-list 'customize-package-emacs-version-alist
5513 '(Org ("8.0" . "24.4")
5514 ("8.1" . "24.4")
5515 ("8.2" . "24.4")
5516 ("8.2.7" . "24.4")
5517 ("8.3" . "26.1")
5518 ("9.0" . "26.1")
5519 ("9.1" . "26.1")
5520 ("9.2" . "27.1")))
5522 (defvar org-mode-transpose-word-syntax-table
5523 (let ((st (make-syntax-table text-mode-syntax-table)))
5524 (dolist (c org-emphasis-alist st)
5525 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5527 (when (fboundp 'abbrev-table-put)
5528 (abbrev-table-put org-mode-abbrev-table
5529 :parents (list text-mode-abbrev-table)))
5531 (defun org-find-invisible-foreground ()
5532 (let ((candidates (remove
5533 "unspecified-bg"
5534 (nconc
5535 (list (face-background 'default)
5536 (face-background 'org-default))
5537 (mapcar
5538 (lambda (alist)
5539 (when (boundp alist)
5540 (cdr (assq 'background-color (symbol-value alist)))))
5541 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5542 (list (face-foreground 'org-hide))))))
5543 (car (remove nil candidates))))
5545 (defun org-current-time (&optional rounding-minutes past)
5546 "Current time, possibly rounded to ROUNDING-MINUTES.
5547 When ROUNDING-MINUTES is not an integer, fall back on the car of
5548 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5549 the rounding returns a past time."
5550 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5551 (car org-time-stamp-rounding-minutes)))
5552 (time (decode-time)) res)
5553 (if (< r 1)
5554 (current-time)
5555 (setq res
5556 (apply 'encode-time
5557 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5558 (nthcdr 2 time))))
5559 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5560 (seconds-to-time (- (float-time res) (* r 60)))
5561 res))))
5563 (defun org-today ()
5564 "Return today date, considering `org-extend-today-until'."
5565 (time-to-days
5566 (time-subtract (current-time)
5567 (list 0 (* 3600 org-extend-today-until) 0))))
5569 ;;;; Font-Lock stuff, including the activators
5571 (defvar org-mouse-map (make-sparse-keymap))
5572 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5573 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5574 (when org-mouse-1-follows-link
5575 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5576 (when org-tab-follows-link
5577 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5578 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5580 (require 'font-lock)
5582 (defconst org-non-link-chars "]\t\n\r<>")
5583 (defvar org-link-types-re nil
5584 "Matches a link that has a url-like prefix like \"http:\"")
5585 (defvar org-link-re-with-space nil
5586 "Matches a link with spaces, optional angular brackets around it.")
5587 (defvar org-link-re-with-space2 nil
5588 "Matches a link with spaces, optional angular brackets around it.")
5589 (defvar org-link-re-with-space3 nil
5590 "Matches a link with spaces, only for internal part in bracket links.")
5591 (defvar org-angle-link-re nil
5592 "Matches link with angular brackets, spaces are allowed.")
5593 (defvar org-plain-link-re nil
5594 "Matches plain link, without spaces.")
5595 (defvar org-bracket-link-regexp nil
5596 "Matches a link in double brackets.")
5597 (defvar org-bracket-link-analytic-regexp nil
5598 "Regular expression used to analyze links.
5599 Here is what the match groups contain after a match:
5600 1: http:
5601 2: http
5602 3: path
5603 4: [desc]
5604 5: desc")
5605 (defvar org-bracket-link-analytic-regexp++ nil
5606 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5607 (defvar org-any-link-re nil
5608 "Regular expression matching any link.")
5610 (defconst org-match-sexp-depth 3
5611 "Number of stacked braces for sub/superscript matching.")
5613 (defun org-create-multibrace-regexp (left right n)
5614 "Create a regular expression which will match a balanced sexp.
5615 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5616 as single character strings.
5617 The regexp returned will match the entire expression including the
5618 delimiters. It will also define a single group which contains the
5619 match except for the outermost delimiters. The maximum depth of
5620 stacked delimiters is N. Escaping delimiters is not possible."
5621 (let* ((nothing (concat "[^" left right "]*?"))
5622 (or "\\|")
5623 (re nothing)
5624 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5625 (while (> n 1)
5626 (setq n (1- n)
5627 re (concat re or next)
5628 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5629 (concat left "\\(" re "\\)" right)))
5631 (defconst org-match-substring-regexp
5632 (concat
5633 "\\(\\S-\\)\\([_^]\\)\\("
5634 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5635 "\\|"
5636 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5637 "\\|"
5638 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5639 "The regular expression matching a sub- or superscript.")
5641 (defconst org-match-substring-with-braces-regexp
5642 (concat
5643 "\\(\\S-\\)\\([_^]\\)"
5644 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5645 "The regular expression matching a sub- or superscript, forcing braces.")
5647 (defun org-make-link-regexps ()
5648 "Update the link regular expressions.
5649 This should be called after the variable `org-link-parameters' has changed."
5650 (let ((types-re (regexp-opt (org-link-types) t)))
5651 (setq org-link-types-re
5652 (concat "\\`" types-re ":")
5653 org-link-re-with-space
5654 (concat "<?" types-re ":"
5655 "\\([^" org-non-link-chars " ]"
5656 "[^" org-non-link-chars "]*"
5657 "[^" org-non-link-chars " ]\\)>?")
5658 org-link-re-with-space2
5659 (concat "<?" types-re ":"
5660 "\\([^" org-non-link-chars " ]"
5661 "[^\t\n\r]*"
5662 "[^" org-non-link-chars " ]\\)>?")
5663 org-link-re-with-space3
5664 (concat "<?" types-re ":"
5665 "\\([^" org-non-link-chars " ]"
5666 "[^\t\n\r]*\\)")
5667 org-angle-link-re
5668 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5669 types-re)
5670 org-plain-link-re
5671 (concat
5672 "\\<" types-re ":"
5673 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5674 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5675 org-bracket-link-regexp
5676 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5677 org-bracket-link-analytic-regexp
5678 (concat
5679 "\\[\\["
5680 "\\(" types-re ":\\)?"
5681 "\\([^]]+\\)"
5682 "\\]"
5683 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5684 "\\]")
5685 org-bracket-link-analytic-regexp++
5686 (concat
5687 "\\[\\["
5688 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5689 "\\([^]]+\\)"
5690 "\\]"
5691 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5692 "\\]")
5693 org-any-link-re
5694 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5695 org-angle-link-re "\\)\\|\\("
5696 org-plain-link-re "\\)"))))
5698 (org-make-link-regexps)
5700 (defvar org-emph-face nil)
5702 (defun org-do-emphasis-faces (limit)
5703 "Run through the buffer and emphasize strings."
5704 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5705 (car org-emphasis-regexp-components))))
5706 (catch :exit
5707 (while (re-search-forward quick-re limit t)
5708 (let* ((marker (match-string 2))
5709 (verbatim? (member marker '("~" "="))))
5710 (when (save-excursion
5711 (goto-char (match-beginning 0))
5712 (and
5713 ;; Do not match table hlines.
5714 (not (and (equal marker "+")
5715 (org-match-line
5716 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5717 ;; Do not match headline stars. Do not consider
5718 ;; stars of a headline as closing marker for bold
5719 ;; markup either.
5720 (not (and (equal marker "*")
5721 (save-excursion
5722 (forward-char)
5723 (skip-chars-backward "*")
5724 (looking-at-p org-outline-regexp-bol))))
5725 ;; Match full emphasis markup regexp.
5726 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5727 ;; Do not span over paragraph boundaries.
5728 (not (string-match-p org-element-paragraph-separate
5729 (match-string 2)))
5730 ;; Do not span over cells in table rows.
5731 (not (and (save-match-data (org-match-line "[ \t]*|"))
5732 (string-match-p "|" (match-string 4))))))
5733 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5734 (font-lock-prepend-text-property
5735 (match-beginning 2) (match-end 2) 'face face)
5736 (when verbatim?
5737 (org-remove-flyspell-overlays-in
5738 (match-beginning 0) (match-end 0)))
5739 (add-text-properties (match-beginning 2) (match-end 2)
5740 '(font-lock-multiline t org-emphasis t))
5741 (when org-hide-emphasis-markers
5742 (add-text-properties (match-end 4) (match-beginning 5)
5743 '(invisible org-link))
5744 (add-text-properties (match-beginning 3) (match-end 3)
5745 '(invisible org-link)))
5746 (throw :exit t))))))))
5748 (defun org-emphasize (&optional char)
5749 "Insert or change an emphasis, i.e. a font like bold or italic.
5750 If there is an active region, change that region to a new emphasis.
5751 If there is no region, just insert the marker characters and position
5752 the cursor between them.
5753 CHAR should be the marker character. If it is a space, it means to
5754 remove the emphasis of the selected region.
5755 If CHAR is not given (for example in an interactive call) it will be
5756 prompted for."
5757 (interactive)
5758 (let ((erc org-emphasis-regexp-components)
5759 (string "") beg end move s)
5760 (if (org-region-active-p)
5761 (setq beg (region-beginning)
5762 end (region-end)
5763 string (buffer-substring beg end))
5764 (setq move t))
5766 (unless char
5767 (message "Emphasis marker or tag: [%s]"
5768 (mapconcat #'car org-emphasis-alist ""))
5769 (setq char (read-char-exclusive)))
5770 (if (equal char ?\s)
5771 (setq s ""
5772 move nil)
5773 (unless (assoc (char-to-string char) org-emphasis-alist)
5774 (user-error "No such emphasis marker: \"%c\"" char))
5775 (setq s (char-to-string char)))
5776 (while (and (> (length string) 1)
5777 (equal (substring string 0 1) (substring string -1))
5778 (assoc (substring string 0 1) org-emphasis-alist))
5779 (setq string (substring string 1 -1)))
5780 (setq string (concat s string s))
5781 (when beg (delete-region beg end))
5782 (unless (or (bolp)
5783 (string-match (concat "[" (nth 0 erc) "\n]")
5784 (char-to-string (char-before (point)))))
5785 (insert " "))
5786 (unless (or (eobp)
5787 (string-match (concat "[" (nth 1 erc) "\n]")
5788 (char-to-string (char-after (point)))))
5789 (insert " ") (backward-char 1))
5790 (insert string)
5791 (and move (backward-char 1))))
5793 (defconst org-nonsticky-props
5794 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5796 (defsubst org-rear-nonsticky-at (pos)
5797 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5799 (defun org-activate-links (limit)
5800 "Add link properties to links.
5801 This includes angle, plain, and bracket links."
5802 (catch :exit
5803 (while (re-search-forward org-any-link-re limit t)
5804 (let* ((start (match-beginning 0))
5805 (end (match-end 0))
5806 (style (cond ((eq ?< (char-after start)) 'angle)
5807 ((eq ?\[ (char-after (1+ start))) 'bracket)
5808 (t 'plain))))
5809 (when (and (memq style org-highlight-links)
5810 ;; Do not confuse plain links with tags.
5811 (not (and (eq style 'plain)
5812 (let ((face (get-text-property
5813 (max (1- start) (point-min)) 'face)))
5814 (if (consp face) (memq 'org-tag face)
5815 (eq 'org-tag face))))))
5816 (let* ((link-object (save-excursion
5817 (goto-char start)
5818 (save-match-data (org-element-link-parser))))
5819 (link (org-element-property :raw-link link-object))
5820 (type (org-element-property :type link-object))
5821 (path (org-element-property :path link-object))
5822 (properties ;for link's visible part
5823 (list
5824 'face (pcase (org-link-get-parameter type :face)
5825 ((and (pred functionp) face) (funcall face path))
5826 ((and (pred facep) face) face)
5827 ((and (pred consp) face) face) ;anonymous
5828 (_ 'org-link))
5829 'mouse-face (or (org-link-get-parameter type :mouse-face)
5830 'highlight)
5831 'keymap (or (org-link-get-parameter type :keymap)
5832 org-mouse-map)
5833 'help-echo (pcase (org-link-get-parameter type :help-echo)
5834 ((and (pred stringp) echo) echo)
5835 ((and (pred functionp) echo) echo)
5836 (_ (concat "LINK: " link)))
5837 'htmlize-link (pcase (org-link-get-parameter type
5838 :htmlize-link)
5839 ((and (pred functionp) f) (funcall f))
5840 (_ `(:uri ,link)))
5841 'font-lock-multiline t)))
5842 (org-remove-flyspell-overlays-in start end)
5843 (org-rear-nonsticky-at end)
5844 (if (not (eq 'bracket style))
5845 (add-text-properties start end properties)
5846 ;; Handle invisible parts in bracket links.
5847 (remove-text-properties start end '(invisible nil))
5848 (let ((hidden
5849 (append `(invisible
5850 ,(or (org-link-get-parameter type :display)
5851 'org-link))
5852 properties))
5853 (visible-start (or (match-beginning 4) (match-beginning 2)))
5854 (visible-end (or (match-end 4) (match-end 2))))
5855 (add-text-properties start visible-start hidden)
5856 (add-text-properties visible-start visible-end properties)
5857 (add-text-properties visible-end end hidden)
5858 (org-rear-nonsticky-at visible-start)
5859 (org-rear-nonsticky-at visible-end)))
5860 (let ((f (org-link-get-parameter type :activate-func)))
5861 (when (functionp f)
5862 (funcall f start end path (eq style 'bracket))))
5863 (throw :exit t))))) ;signal success
5864 nil))
5866 (defun org-activate-code (limit)
5867 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5868 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5869 (remove-text-properties (match-beginning 0) (match-end 0)
5870 '(display t invisible t intangible t))
5873 (defcustom org-src-fontify-natively t
5874 "When non-nil, fontify code in code blocks.
5875 See also the `org-block' face."
5876 :type 'boolean
5877 :version "26.1"
5878 :package-version '(Org . "8.3")
5879 :group 'org-appearance
5880 :group 'org-babel)
5882 (defcustom org-allow-promoting-top-level-subtree nil
5883 "When non-nil, allow promoting a top level subtree.
5884 The leading star of the top level headline will be replaced
5885 by a #."
5886 :type 'boolean
5887 :version "24.1"
5888 :group 'org-appearance)
5890 (defun org-fontify-meta-lines-and-blocks (limit)
5891 (condition-case nil
5892 (org-fontify-meta-lines-and-blocks-1 limit)
5893 (error (message "org-mode fontification error in %S at %d"
5894 (current-buffer)
5895 (line-number-at-pos)))))
5897 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5898 "Fontify #+ lines and blocks."
5899 (let ((case-fold-search t))
5900 (when (re-search-forward
5901 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5902 limit t)
5903 (let ((beg (match-beginning 0))
5904 (block-start (match-end 0))
5905 (block-end nil)
5906 (lang (match-string 7))
5907 (beg1 (line-beginning-position 2))
5908 (dc1 (downcase (match-string 2)))
5909 (dc3 (downcase (match-string 3)))
5910 end end1 quoting block-type)
5911 (cond
5912 ((and (match-end 4) (equal dc3 "+begin"))
5913 ;; Truly a block
5914 (setq block-type (downcase (match-string 5))
5915 quoting (member block-type org-protecting-blocks))
5916 (when (re-search-forward
5917 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5918 nil t) ;; on purpose, we look further than LIMIT
5919 (setq end (min (point-max) (match-end 0))
5920 end1 (min (point-max) (1- (match-beginning 0))))
5921 (setq block-end (match-beginning 0))
5922 (when quoting
5923 (org-remove-flyspell-overlays-in beg1 end1)
5924 (remove-text-properties beg end
5925 '(display t invisible t intangible t)))
5926 (add-text-properties
5927 beg end '(font-lock-fontified t font-lock-multiline t))
5928 (add-text-properties beg beg1 '(face org-meta-line))
5929 (org-remove-flyspell-overlays-in beg beg1)
5930 (add-text-properties ; For end_src
5931 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5932 (org-remove-flyspell-overlays-in end1 end)
5933 (cond
5934 ((and lang (not (string= lang "")) org-src-fontify-natively)
5935 (org-src-font-lock-fontify-block lang block-start block-end)
5936 (add-text-properties beg1 block-end '(src-block t)))
5937 (quoting
5938 (add-text-properties beg1 (min (point-max) (1+ end1))
5939 (list 'face
5940 (list :inherit
5941 (let ((face-name
5942 (intern (format "org-block-%s" lang))))
5943 (append (and (facep face-name) (list face-name))
5944 '(org-block))))))) ; end of source block
5945 ((not org-fontify-quote-and-verse-blocks))
5946 ((string= block-type "quote")
5947 (add-face-text-property
5948 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5949 ((string= block-type "verse")
5950 (add-face-text-property
5951 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5952 (add-text-properties beg beg1 '(face org-block-begin-line))
5953 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5954 '(face org-block-end-line))
5956 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5957 (org-remove-flyspell-overlays-in
5958 (match-beginning 0)
5959 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5960 (add-text-properties
5961 beg (match-end 3)
5962 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5963 '(font-lock-fontified t invisible t)
5964 '(font-lock-fontified t face org-document-info-keyword)))
5965 (add-text-properties
5966 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5967 (if (string-equal dc1 "+title:")
5968 '(font-lock-fontified t face org-document-title)
5969 '(font-lock-fontified t face org-document-info))))
5970 ((string-prefix-p "+caption" dc1)
5971 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5972 (remove-text-properties (match-beginning 0) (match-end 0)
5973 '(display t invisible t intangible t))
5974 ;; Handle short captions.
5975 (save-excursion
5976 (beginning-of-line)
5977 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5978 (add-text-properties (line-beginning-position) (match-end 1)
5979 '(font-lock-fontified t face org-meta-line))
5980 (add-text-properties (match-end 0) (line-end-position)
5981 '(font-lock-fontified t face org-block))
5983 ((member dc3 '(" " ""))
5984 (org-remove-flyspell-overlays-in beg (match-end 0))
5985 (add-text-properties
5986 beg (match-end 0)
5987 '(font-lock-fontified t face font-lock-comment-face)))
5988 (t ;; just any other in-buffer setting, but not indented
5989 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5990 (remove-text-properties (match-beginning 0) (match-end 0)
5991 '(display t invisible t intangible t))
5992 (add-text-properties beg (match-end 0)
5993 '(font-lock-fontified t face org-meta-line))
5994 t))))))
5996 (defun org-fontify-drawers (limit)
5997 "Fontify drawers."
5998 (when (re-search-forward org-drawer-regexp limit t)
5999 (add-text-properties
6000 (match-beginning 0) (match-end 0)
6001 '(font-lock-fontified t face org-special-keyword))
6002 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6005 (defun org-fontify-macros (limit)
6006 "Fontify macros."
6007 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6008 (add-text-properties
6009 (match-beginning 0) (match-end 0)
6010 '(font-lock-fontified t face org-macro))
6011 (when org-hide-macro-markers
6012 (add-text-properties (match-end 2) (match-beginning 2)
6013 '(invisible t))
6014 (add-text-properties (match-beginning 1) (match-end 1)
6015 '(invisible t)))
6016 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (defun org-activate-footnote-links (limit)
6020 "Add text properties for footnotes."
6021 (let ((fn (org-footnote-next-reference-or-definition limit)))
6022 (when fn
6023 (let* ((beg (nth 1 fn))
6024 (end (nth 2 fn))
6025 (label (car fn))
6026 (referencep (/= (line-beginning-position) beg)))
6027 (when (and referencep (nth 3 fn))
6028 (save-excursion
6029 (goto-char beg)
6030 (search-forward (or label "fn:"))
6031 (org-remove-flyspell-overlays-in beg (match-end 0))))
6032 (add-text-properties beg end
6033 (list 'mouse-face 'highlight
6034 'keymap org-mouse-map
6035 'help-echo
6036 (if referencep "Footnote reference"
6037 "Footnote definition")
6038 'font-lock-fontified t
6039 'font-lock-multiline t
6040 'face 'org-footnote))))))
6042 (defun org-activate-dates (limit)
6043 "Add text properties for dates."
6044 (when (and (re-search-forward org-tsr-regexp-both limit t)
6045 (not (equal (char-before (match-beginning 0)) 91)))
6046 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6047 (add-text-properties (match-beginning 0) (match-end 0)
6048 (list 'mouse-face 'highlight
6049 'keymap org-mouse-map))
6050 (org-rear-nonsticky-at (match-end 0))
6051 (when org-display-custom-times
6052 ;; If it's a date range, activate custom time for second date.
6053 (when (match-end 3)
6054 (org-display-custom-time (match-beginning 3) (match-end 3)))
6055 (org-display-custom-time (match-beginning 1) (match-end 1)))
6058 (defvar-local org-target-link-regexp nil
6059 "Regular expression matching radio targets in plain text.")
6061 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6062 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6063 border border border))
6064 "Regular expression matching a link target.")
6066 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6067 "Regular expression matching a radio target.")
6069 (defconst org-any-target-regexp
6070 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6071 "Regular expression matching any target.")
6073 (defun org-activate-target-links (limit)
6074 "Add text properties for target matches."
6075 (when org-target-link-regexp
6076 (let ((case-fold-search t))
6077 (when (re-search-forward org-target-link-regexp limit t)
6078 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6079 (add-text-properties (match-beginning 1) (match-end 1)
6080 (list 'mouse-face 'highlight
6081 'keymap org-mouse-map
6082 'help-echo "Radio target link"
6083 'org-linked-text t))
6084 (org-rear-nonsticky-at (match-end 1))
6085 t))))
6087 (defun org-update-radio-target-regexp ()
6088 "Find all radio targets in this file and update the regular expression.
6089 Also refresh fontification if needed."
6090 (interactive)
6091 (let ((old-regexp org-target-link-regexp)
6092 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6093 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6094 (targets
6095 (org-with-wide-buffer
6096 (goto-char (point-min))
6097 (let (rtn)
6098 (while (re-search-forward org-radio-target-regexp nil t)
6099 ;; Make sure point is really within the object.
6100 (backward-char)
6101 (let ((obj (org-element-context)))
6102 (when (eq (org-element-type obj) 'radio-target)
6103 (cl-pushnew (org-element-property :value obj) rtn
6104 :test #'equal))))
6105 rtn))))
6106 (setq org-target-link-regexp
6107 (and targets
6108 (concat before-re
6109 (mapconcat
6110 (lambda (x)
6111 (replace-regexp-in-string
6112 " +" "\\s-+" (regexp-quote x) t t))
6113 targets
6114 "\\|")
6115 after-re)))
6116 (unless (equal old-regexp org-target-link-regexp)
6117 ;; Clean-up cache.
6118 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6119 ((not org-target-link-regexp) old-regexp)
6121 (concat before-re
6122 (mapconcat
6123 (lambda (re)
6124 (substring re (length before-re)
6125 (- (length after-re))))
6126 (list old-regexp org-target-link-regexp)
6127 "\\|")
6128 after-re)))))
6129 (org-with-wide-buffer
6130 (goto-char (point-min))
6131 (while (re-search-forward regexp nil t)
6132 (org-element-cache-refresh (match-beginning 1)))))
6133 ;; Re fontify buffer.
6134 (when (memq 'radio org-highlight-links)
6135 (org-restart-font-lock)))))
6137 (defvar org-latex-and-related-regexp nil
6138 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6140 (defun org-compute-latex-and-related-regexp ()
6141 "Compute regular expression for LaTeX, entities and sub/superscript.
6142 Result depends on variable `org-highlight-latex-and-related'."
6143 (setq-local
6144 org-latex-and-related-regexp
6145 (let* ((re-sub
6146 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6147 ((eq org-use-sub-superscripts '{})
6148 (list org-match-substring-with-braces-regexp))
6149 (org-use-sub-superscripts (list org-match-substring-regexp))))
6150 (re-latex
6151 (when (memq 'latex org-highlight-latex-and-related)
6152 (let ((matchers (plist-get org-format-latex-options :matchers)))
6153 (delq nil
6154 (mapcar (lambda (x)
6155 (and (member (car x) matchers) (nth 1 x)))
6156 org-latex-regexps)))))
6157 (re-entities
6158 (when (memq 'entities org-highlight-latex-and-related)
6159 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6160 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6162 (defun org-do-latex-and-related (limit)
6163 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6164 LIMIT bounds the search for syntax to highlight. Stop at first
6165 highlighted object, if any. Return t if some highlighting was
6166 done, nil otherwise."
6167 (when (org-string-nw-p org-latex-and-related-regexp)
6168 (catch 'found
6169 (while (re-search-forward org-latex-and-related-regexp limit t)
6170 (unless
6171 (cl-some
6172 (lambda (f)
6173 (memq f '(org-code org-verbatim underline org-special-keyword)))
6174 (save-excursion
6175 (goto-char (1+ (match-beginning 0)))
6176 (face-at-point nil t)))
6177 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6178 '(?_ ?^))
6180 0)))
6181 (font-lock-prepend-text-property
6182 (+ offset (match-beginning 0)) (match-end 0)
6183 'face 'org-latex-and-related)
6184 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6185 '(font-lock-multiline t)))
6186 (throw 'found t)))
6187 nil)))
6189 (defun org-restart-font-lock ()
6190 "Restart `font-lock-mode', to force refontification."
6191 (when (and (boundp 'font-lock-mode) font-lock-mode)
6192 (font-lock-mode -1)
6193 (font-lock-mode 1)))
6195 (defun org-activate-tags (limit)
6196 (when (re-search-forward
6197 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6198 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6199 (add-text-properties (match-beginning 1) (match-end 1)
6200 (list 'mouse-face 'highlight
6201 'keymap org-mouse-map))
6202 (org-rear-nonsticky-at (match-end 1))
6205 (defun org-outline-level ()
6206 "Compute the outline level of the heading at point.
6208 If this is called at a normal headline, the level is the number
6209 of stars. Use `org-reduced-level' to remove the effect of
6210 `org-odd-levels'. Unlike to `org-current-level', this function
6211 takes into consideration inlinetasks."
6212 (org-with-wide-buffer
6213 (end-of-line)
6214 (if (re-search-backward org-outline-regexp-bol nil t)
6215 (1- (- (match-end 0) (match-beginning 0)))
6216 0)))
6218 (defvar org-font-lock-keywords nil)
6220 (defsubst org-re-property (property &optional literal allow-null value)
6221 "Return a regexp matching a PROPERTY line.
6223 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6224 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6225 non-nil, match properties even without a value.
6227 Match group 3 is set to the value when it exists. If there is no
6228 value and ALLOW-NULL is non-nil, it is set to the empty string.
6230 With optional argument VALUE, match only property lines with
6231 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6232 unless LITERAL is non-nil."
6233 (concat
6234 "^\\(?4:[ \t]*\\)"
6235 (format "\\(?1::\\(?2:%s\\):\\)"
6236 (if literal property (regexp-quote property)))
6237 (cond (value
6238 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6239 (if literal value (regexp-quote value))))
6240 (allow-null
6241 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6243 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6245 (defconst org-property-re
6246 (org-re-property "\\S-+" 'literal t)
6247 "Regular expression matching a property line.
6248 There are four matching groups:
6249 1: :PROPKEY: including the leading and trailing colon,
6250 2: PROPKEY without the leading and trailing colon,
6251 3: PROPVAL without leading or trailing spaces,
6252 4: the indentation of the current line,
6253 5: trailing whitespace.")
6255 (defvar org-font-lock-hook nil
6256 "Functions to be called for special font lock stuff.")
6258 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6260 (defvar org-font-lock-set-keywords-hook nil
6261 "Functions that can manipulate `org-font-lock-extra-keywords'.
6262 This is called after `org-font-lock-extra-keywords' is defined, but before
6263 it is installed to be used by font lock. This can be useful if something
6264 needs to be inserted at a specific position in the font-lock sequence.")
6266 (defun org-font-lock-hook (limit)
6267 "Run `org-font-lock-hook' within LIMIT."
6268 (run-hook-with-args 'org-font-lock-hook limit))
6270 (defun org-set-font-lock-defaults ()
6271 "Set font lock defaults for the current buffer."
6272 (let* ((em org-fontify-emphasized-text)
6273 (lk org-highlight-links)
6274 (org-font-lock-extra-keywords
6275 (list
6276 ;; Call the hook
6277 '(org-font-lock-hook)
6278 ;; Headlines
6279 `(,(if org-fontify-whole-heading-line
6280 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6282 (1 (org-get-level-face 1))
6283 (2 (org-get-level-face 2))
6284 (3 (org-get-level-face 3)))
6285 ;; Table lines
6286 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6287 (1 'org-table t))
6288 ;; Table internals
6289 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6290 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6291 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6292 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6293 ;; Drawers
6294 '(org-fontify-drawers)
6295 ;; Properties
6296 (list org-property-re
6297 '(1 'org-special-keyword t)
6298 '(3 'org-property-value t))
6299 ;; Link related fontification.
6300 '(org-activate-links)
6301 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6302 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6303 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6304 (when (memq 'footnote lk) '(org-activate-footnote-links))
6305 ;; Targets.
6306 (list org-any-target-regexp '(0 'org-target t))
6307 ;; Diary sexps.
6308 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6309 ;; Macro
6310 '(org-fontify-macros)
6311 ;; TODO keyword
6312 (list (format org-heading-keyword-regexp-format
6313 org-todo-regexp)
6314 '(2 (org-get-todo-face 2) t))
6315 ;; DONE
6316 (if org-fontify-done-headline
6317 (list (format org-heading-keyword-regexp-format
6318 (concat
6319 "\\(?:"
6320 (mapconcat 'regexp-quote org-done-keywords "\\|")
6321 "\\)"))
6322 '(2 'org-headline-done t))
6323 nil)
6324 ;; Priorities
6325 '(org-font-lock-add-priority-faces)
6326 ;; Tags
6327 '(org-font-lock-add-tag-faces)
6328 ;; Tags groups
6329 (when (and org-group-tags org-tag-groups-alist)
6330 (list (concat org-outline-regexp-bol ".+\\(:"
6331 (regexp-opt (mapcar 'car org-tag-groups-alist))
6332 ":\\).*$")
6333 '(1 'org-tag-group prepend)))
6334 ;; Special keywords
6335 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6336 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6337 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6338 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6339 ;; Emphasis
6340 (when em '(org-do-emphasis-faces))
6341 ;; Checkboxes
6342 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6343 1 'org-checkbox prepend)
6344 (when (cdr (assq 'checkbox org-list-automatic-rules))
6345 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6346 (0 (org-get-checkbox-statistics-face) t)))
6347 ;; Description list items
6348 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6349 1 'org-list-dt prepend)
6350 ;; ARCHIVEd headings
6351 (list (concat
6352 org-outline-regexp-bol
6353 "\\(.*:" org-archive-tag ":.*\\)")
6354 '(1 'org-archived prepend))
6355 ;; Specials
6356 '(org-do-latex-and-related)
6357 '(org-fontify-entities)
6358 '(org-raise-scripts)
6359 ;; Code
6360 '(org-activate-code (1 'org-code t))
6361 ;; COMMENT
6362 (list (format
6363 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6364 org-todo-regexp
6365 org-comment-string)
6366 '(9 'org-special-keyword t))
6367 ;; Blocks and meta lines
6368 '(org-fontify-meta-lines-and-blocks))))
6369 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6370 (run-hooks 'org-font-lock-set-keywords-hook)
6371 ;; Now set the full font-lock-keywords
6372 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6373 (setq-local font-lock-defaults
6374 '(org-font-lock-keywords t nil nil backward-paragraph))
6375 (kill-local-variable 'font-lock-keywords)
6376 nil))
6378 (defun org-toggle-pretty-entities ()
6379 "Toggle the composition display of entities as UTF8 characters."
6380 (interactive)
6381 (setq-local org-pretty-entities (not org-pretty-entities))
6382 (org-restart-font-lock)
6383 (if org-pretty-entities
6384 (message "Entities are now displayed as UTF8 characters")
6385 (save-restriction
6386 (widen)
6387 (decompose-region (point-min) (point-max))
6388 (message "Entities are now displayed as plain text"))))
6390 (defvar-local org-custom-properties-overlays nil
6391 "List of overlays used for custom properties.")
6393 (defun org-toggle-custom-properties-visibility ()
6394 "Display or hide properties in `org-custom-properties'."
6395 (interactive)
6396 (if org-custom-properties-overlays
6397 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6398 (setq org-custom-properties-overlays nil))
6399 (when org-custom-properties
6400 (org-with-wide-buffer
6401 (goto-char (point-min))
6402 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6403 (while (re-search-forward regexp nil t)
6404 (let ((end (cdr (save-match-data (org-get-property-block)))))
6405 (when (and end (< (point) end))
6406 ;; Hide first custom property in current drawer.
6407 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6408 (overlay-put o 'invisible t)
6409 (overlay-put o 'org-custom-property t)
6410 (push o org-custom-properties-overlays))
6411 ;; Hide additional custom properties in the same drawer.
6412 (while (re-search-forward regexp end t)
6413 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6414 (overlay-put o 'invisible t)
6415 (overlay-put o 'org-custom-property t)
6416 (push o org-custom-properties-overlays)))))
6417 ;; Each entry is limited to a single property drawer.
6418 (outline-next-heading)))))))
6420 (defun org-fontify-entities (limit)
6421 "Find an entity to fontify."
6422 (let (ee)
6423 (when org-pretty-entities
6424 (catch 'match
6425 ;; "\_ "-family is left out on purpose. Only the first one,
6426 ;; i.e., "\_ ", could be fontified anyway, and it would be
6427 ;; confusing when adding a second white space character.
6428 (while (re-search-forward
6429 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6430 limit t)
6431 (when (and (not (org-at-comment-p))
6432 (setq ee (org-entity-get (match-string 1)))
6433 (= (length (nth 6 ee)) 1))
6434 (let* ((end (if (equal (match-string 2) "{}")
6435 (match-end 2)
6436 (match-end 1))))
6437 (add-text-properties
6438 (match-beginning 0) end
6439 (list 'font-lock-fontified t))
6440 (compose-region (match-beginning 0) end
6441 (nth 6 ee) nil)
6442 (backward-char 1)
6443 (throw 'match t))))
6444 nil))))
6446 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6447 "Fontify string S like in Org mode."
6448 (with-temp-buffer
6449 (insert s)
6450 (let ((org-odd-levels-only odd-levels))
6451 (org-mode)
6452 (org-font-lock-ensure)
6453 (buffer-string))))
6455 (defvar org-m nil)
6456 (defvar org-l nil)
6457 (defvar org-f nil)
6458 (defun org-get-level-face (n)
6459 "Get the right face for match N in font-lock matching of headlines."
6460 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6461 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6462 (if org-cycle-level-faces
6463 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6464 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6465 (cond
6466 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6467 ((eq n 2) org-f)
6468 (t (unless org-level-color-stars-only org-f))))
6470 (defun org-face-from-face-or-color (context inherit face-or-color)
6471 "Create a face list that inherits INHERIT, but sets the foreground color.
6472 When FACE-OR-COLOR is not a string, just return it."
6473 (if (stringp face-or-color)
6474 (list :inherit inherit
6475 (cdr (assoc context org-faces-easy-properties))
6476 face-or-color)
6477 face-or-color))
6479 (defun org-get-todo-face (kwd)
6480 "Get the right face for a TODO keyword KWD.
6481 If KWD is a number, get the corresponding match group."
6482 (when (numberp kwd) (setq kwd (match-string kwd)))
6483 (or (org-face-from-face-or-color
6484 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6485 (and (member kwd org-done-keywords) 'org-done)
6486 'org-todo))
6488 (defun org-get-priority-face (priority)
6489 "Get the right face for PRIORITY.
6490 PRIORITY is a character."
6491 (or (org-face-from-face-or-color
6492 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6493 'org-priority))
6495 (defun org-get-tag-face (tag)
6496 "Get the right face for TAG.
6497 If TAG is a number, get the corresponding match group."
6498 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6499 (or (org-face-from-face-or-color
6500 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6501 'org-tag)))
6503 (defun org-font-lock-add-priority-faces (limit)
6504 "Add the special priority faces."
6505 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6506 (add-text-properties
6507 (match-beginning 1) (match-end 1)
6508 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6509 'font-lock-fontified t))))
6511 (defun org-font-lock-add-tag-faces (limit)
6512 "Add the special tag faces."
6513 (when (and org-tag-faces org-tags-special-faces-re)
6514 (while (re-search-forward org-tags-special-faces-re limit t)
6515 (add-text-properties (match-beginning 1) (match-end 1)
6516 (list 'face (org-get-tag-face 1)
6517 'font-lock-fontified t))
6518 (backward-char 1))))
6520 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6521 "Remove fontification and activation overlays from links."
6522 (font-lock-default-unfontify-region beg end)
6523 (let* ((buffer-undo-list t)
6524 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6525 (inhibit-modification-hooks t)
6526 deactivate-mark buffer-file-name buffer-file-truename)
6527 (decompose-region beg end)
6528 (remove-text-properties beg end
6529 '(mouse-face t keymap t org-linked-text t
6530 invisible t intangible t
6531 org-emphasis t))
6532 (org-remove-font-lock-display-properties beg end)))
6534 (defconst org-script-display '(((raise -0.3) (height 0.7))
6535 ((raise 0.3) (height 0.7))
6536 ((raise -0.5))
6537 ((raise 0.5)))
6538 "Display properties for showing superscripts and subscripts.")
6540 (defun org-remove-font-lock-display-properties (beg end)
6541 "Remove specific display properties that have been added by font lock.
6542 The will remove the raise properties that are used to show superscripts
6543 and subscripts."
6544 (let (next prop)
6545 (while (< beg end)
6546 (setq next (next-single-property-change beg 'display nil end)
6547 prop (get-text-property beg 'display))
6548 (when (member prop org-script-display)
6549 (put-text-property beg next 'display nil))
6550 (setq beg next))))
6552 (defun org-raise-scripts (limit)
6553 "Add raise properties to sub/superscripts."
6554 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6555 (re-search-forward
6556 (if (eq org-use-sub-superscripts t)
6557 org-match-substring-regexp
6558 org-match-substring-with-braces-regexp)
6559 limit t))
6560 (let* ((pos (point)) table-p comment-p
6561 (mpos (match-beginning 3))
6562 (emph-p (get-text-property mpos 'org-emphasis))
6563 (link-p (get-text-property mpos 'mouse-face))
6564 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6565 (goto-char (point-at-bol))
6566 (setq table-p (looking-at-p org-table-dataline-regexp)
6567 comment-p (looking-at-p "^[ \t]*#[ +]"))
6568 (goto-char pos)
6569 ;; Handle a_b^c
6570 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6571 (unless (or comment-p emph-p link-p keyw-p)
6572 (put-text-property (match-beginning 3) (match-end 0)
6573 'display
6574 (if (equal (char-after (match-beginning 2)) ?^)
6575 (nth (if table-p 3 1) org-script-display)
6576 (nth (if table-p 2 0) org-script-display)))
6577 (add-text-properties (match-beginning 2) (match-end 2)
6578 (list 'invisible t))
6579 (when (and (eq (char-after (match-beginning 3)) ?{)
6580 (eq (char-before (match-end 3)) ?}))
6581 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6582 (list 'invisible t))
6583 (add-text-properties (1- (match-end 3)) (match-end 3)
6584 (list 'invisible t))))
6585 t)))
6587 ;;;; Visibility cycling, including org-goto and indirect buffer
6589 ;;; Cycling
6591 (defvar-local org-cycle-global-status nil)
6592 (put 'org-cycle-global-status 'org-state t)
6593 (defvar-local org-cycle-subtree-status nil)
6594 (put 'org-cycle-subtree-status 'org-state t)
6596 (defvar org-inlinetask-min-level)
6598 ;;;###autoload
6599 (defun org-cycle (&optional arg)
6600 "TAB-action and visibility cycling for Org mode.
6602 This is the command invoked in Org mode by the `TAB' key. Its main
6603 purpose is outline visibility cycling, but it also invokes other actions
6604 in special contexts.
6606 When this function is called with a `\\[universal-argument]' prefix, rotate \
6607 the entire
6608 buffer through 3 states (global cycling)
6609 1. OVERVIEW: Show only top-level headlines.
6610 2. CONTENTS: Show all headlines of all levels, but no body text.
6611 3. SHOW ALL: Show everything.
6613 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6614 switch to the startup visibility,
6615 determined by the variable `org-startup-folded', and by any VISIBILITY
6616 properties in the buffer.
6618 With a `\\[universal-argument] \\[universal-argument] \
6619 \\[universal-argument]' prefix argument, show the entire buffer, including
6620 any drawers.
6622 When inside a table, re-align the table and move to the next field.
6624 When point is at the beginning of a headline, rotate the subtree started
6625 by this line through 3 different states (local cycling)
6626 1. FOLDED: Only the main headline is shown.
6627 2. CHILDREN: The main headline and the direct children are shown.
6628 From this state, you can move to one of the children
6629 and zoom in further.
6630 3. SUBTREE: Show the entire subtree, including body text.
6631 If there is no subtree, switch directly from CHILDREN to FOLDED.
6633 When point is at the beginning of an empty headline and the variable
6634 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6635 of the headline by demoting and promoting it to likely levels. This
6636 speeds up creation document structure by pressing `TAB' once or several
6637 times right after creating a new headline.
6639 When there is a numeric prefix, go up to a heading with level ARG, do
6640 a `show-subtree' and return to the previous cursor position. If ARG
6641 is negative, go up that many levels.
6643 When point is not at the beginning of a headline, execute the global
6644 binding for `TAB', which is re-indenting the line. See the option
6645 `org-cycle-emulate-tab' for details.
6647 As a special case, if point is at the beginning of the buffer and there is
6648 no headline in line 1, this function will act as if called with prefix arg
6649 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6650 prefix arg, but only
6651 if the variable `org-cycle-global-at-bob' is t."
6652 (interactive "P")
6653 (org-load-modules-maybe)
6654 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6655 (and org-cycle-level-after-item/entry-creation
6656 (or (org-cycle-level)
6657 (org-cycle-item-indentation))))
6658 (let* ((limit-level
6659 (or org-cycle-max-level
6660 (and (boundp 'org-inlinetask-min-level)
6661 org-inlinetask-min-level
6662 (1- org-inlinetask-min-level))))
6663 (nstars (and limit-level
6664 (if org-odd-levels-only
6665 (and limit-level (1- (* limit-level 2)))
6666 limit-level)))
6667 (org-outline-regexp
6668 (if (not (derived-mode-p 'org-mode))
6669 outline-regexp
6670 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6671 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6672 (not (looking-at org-outline-regexp))))
6673 (org-cycle-hook
6674 (if bob-special
6675 (delq 'org-optimize-window-after-visibility-change
6676 (copy-sequence org-cycle-hook))
6677 org-cycle-hook))
6678 (pos (point)))
6680 (cond
6682 ((equal arg '(16))
6683 (setq last-command 'dummy)
6684 (org-set-startup-visibility)
6685 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6687 ((equal arg '(64))
6688 (outline-show-all)
6689 (org-unlogged-message "Entire buffer visible, including drawers"))
6691 ((equal arg '(4)) (org-cycle-internal-global))
6693 ;; Try hiding block at point.
6694 ((org-hide-block-toggle-maybe))
6696 ;; Try cdlatex TAB completion
6697 ((org-try-cdlatex-tab))
6699 ;; Table: enter it or move to the next field.
6700 ((org-at-table-p 'any)
6701 (if (org-at-table.el-p)
6702 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6703 Use `\\[org-edit-special]' to edit table.el tables"))
6704 (if arg (org-table-edit-field t)
6705 (org-table-justify-field-maybe)
6706 (call-interactively 'org-table-next-field))))
6708 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6710 ;; Global cycling: delegate to `org-cycle-internal-global'.
6711 (bob-special (org-cycle-internal-global))
6713 ;; Drawers: delegate to `org-flag-drawer'.
6714 ((save-excursion
6715 (beginning-of-line 1)
6716 (looking-at org-drawer-regexp))
6717 (org-flag-drawer ; toggle block visibility
6718 (not (get-char-property (match-end 0) 'invisible))))
6720 ;; Show-subtree, ARG levels up from here.
6721 ((integerp arg)
6722 (save-excursion
6723 (org-back-to-heading)
6724 (outline-up-heading (if (< arg 0) (- arg)
6725 (- (funcall outline-level) arg)))
6726 (org-show-subtree)))
6728 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6729 ((and (featurep 'org-inlinetask)
6730 (org-inlinetask-at-task-p)
6731 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6732 (org-inlinetask-toggle-visibility))
6734 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6735 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6736 (save-excursion (move-beginning-of-line 1)
6737 (looking-at org-outline-regexp)))
6738 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6739 (org-cycle-internal-local))
6741 ;; From there: TAB emulation and template completion.
6742 (buffer-read-only (org-back-to-heading))
6744 ((run-hook-with-args-until-success
6745 'org-tab-after-check-for-cycling-hook))
6747 ((run-hook-with-args-until-success
6748 'org-tab-before-tab-emulation-hook))
6750 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6751 (or (not (bolp))
6752 (not (looking-at org-outline-regexp))))
6753 (call-interactively (global-key-binding "\t")))
6755 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6756 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6757 (or (and (eq org-cycle-emulate-tab 'white)
6758 (= (match-end 0) (point-at-eol)))
6759 (and (eq org-cycle-emulate-tab 'whitestart)
6760 (>= (match-end 0) pos))))
6762 (eq org-cycle-emulate-tab t))
6763 (call-interactively (global-key-binding "\t")))
6765 (t (save-excursion
6766 (org-back-to-heading)
6767 (org-cycle)))))))
6769 (defun org-cycle-internal-global ()
6770 "Do the global cycling action."
6771 ;; Hack to avoid display of messages for .org attachments in Gnus
6772 (let ((ga (string-match "\\*fontification" (buffer-name))))
6773 (cond
6774 ((and (eq last-command this-command)
6775 (eq org-cycle-global-status 'overview))
6776 ;; We just created the overview - now do table of contents
6777 ;; This can be slow in very large buffers, so indicate action
6778 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6779 (unless ga (org-unlogged-message "CONTENTS..."))
6780 (org-content)
6781 (unless ga (org-unlogged-message "CONTENTS...done"))
6782 (setq org-cycle-global-status 'contents)
6783 (run-hook-with-args 'org-cycle-hook 'contents))
6785 ((and (eq last-command this-command)
6786 (eq org-cycle-global-status 'contents))
6787 ;; We just showed the table of contents - now show everything
6788 (run-hook-with-args 'org-pre-cycle-hook 'all)
6789 (outline-show-all)
6790 (unless ga (org-unlogged-message "SHOW ALL"))
6791 (setq org-cycle-global-status 'all)
6792 (run-hook-with-args 'org-cycle-hook 'all))
6795 ;; Default action: go to overview
6796 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6797 (org-overview)
6798 (unless ga (org-unlogged-message "OVERVIEW"))
6799 (setq org-cycle-global-status 'overview)
6800 (run-hook-with-args 'org-cycle-hook 'overview)))))
6802 (defvar org-called-with-limited-levels nil
6803 "Non-nil when `org-with-limited-levels' is currently active.")
6805 (defun org-cycle-internal-local ()
6806 "Do the local cycling action."
6807 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6808 ;; First, determine end of headline (EOH), end of subtree or item
6809 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6810 (save-excursion
6811 (if (org-at-item-p)
6812 (progn
6813 (beginning-of-line)
6814 (setq struct (org-list-struct))
6815 (setq eoh (point-at-eol))
6816 (setq eos (org-list-get-item-end-before-blank (point) struct))
6817 (setq has-children (org-list-has-child-p (point) struct)))
6818 (org-back-to-heading)
6819 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6820 (setq eos (save-excursion (org-end-of-subtree t t)
6821 (when (bolp) (backward-char)) (point)))
6822 (setq has-children
6823 (or (save-excursion
6824 (let ((level (funcall outline-level)))
6825 (outline-next-heading)
6826 (and (org-at-heading-p t)
6827 (> (funcall outline-level) level))))
6828 (save-excursion
6829 (org-list-search-forward (org-item-beginning-re) eos t)))))
6830 ;; Determine end invisible part of buffer (EOL)
6831 (beginning-of-line 2)
6832 (while (and (not (eobp)) ;This is like `next-line'.
6833 (get-char-property (1- (point)) 'invisible))
6834 (goto-char (next-single-char-property-change (point) 'invisible))
6835 (and (eolp) (beginning-of-line 2)))
6836 (setq eol (point)))
6837 ;; Find out what to do next and set `this-command'
6838 (cond
6839 ((= eos eoh)
6840 ;; Nothing is hidden behind this heading
6841 (unless (org-before-first-heading-p)
6842 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6843 (org-unlogged-message "EMPTY ENTRY")
6844 (setq org-cycle-subtree-status nil)
6845 (save-excursion
6846 (goto-char eos)
6847 (outline-next-heading)
6848 (when (org-invisible-p) (org-flag-heading nil))))
6849 ((and (or (>= eol eos)
6850 (not (string-match "\\S-" (buffer-substring eol eos))))
6851 (or has-children
6852 (not (setq children-skipped
6853 org-cycle-skip-children-state-if-no-children))))
6854 ;; Entire subtree is hidden in one line: children view
6855 (unless (org-before-first-heading-p)
6856 (run-hook-with-args 'org-pre-cycle-hook 'children))
6857 (if (org-at-item-p)
6858 (org-list-set-item-visibility (point-at-bol) struct 'children)
6859 (org-show-entry)
6860 (org-with-limited-levels (org-show-children))
6861 (org-show-set-visibility 'canonical)
6862 ;; FIXME: This slows down the func way too much.
6863 ;; How keep drawers hidden in subtree anyway?
6864 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6865 ;; (org-cycle-hide-drawers 'subtree))
6867 ;; Fold every list in subtree to top-level items.
6868 (when (eq org-cycle-include-plain-lists 'integrate)
6869 (save-excursion
6870 (org-back-to-heading)
6871 (while (org-list-search-forward (org-item-beginning-re) eos t)
6872 (beginning-of-line 1)
6873 (let* ((struct (org-list-struct))
6874 (prevs (org-list-prevs-alist struct))
6875 (end (org-list-get-bottom-point struct)))
6876 (dolist (e (org-list-get-all-items (point) struct prevs))
6877 (org-list-set-item-visibility e struct 'folded))
6878 (goto-char (if (< end eos) end eos)))))))
6879 (org-unlogged-message "CHILDREN")
6880 (save-excursion
6881 (goto-char eos)
6882 (outline-next-heading)
6883 (when (org-invisible-p) (org-flag-heading nil)))
6884 (setq org-cycle-subtree-status 'children)
6885 (unless (org-before-first-heading-p)
6886 (run-hook-with-args 'org-cycle-hook 'children)))
6887 ((or children-skipped
6888 (and (eq last-command this-command)
6889 (eq org-cycle-subtree-status 'children)))
6890 ;; We just showed the children, or no children are there,
6891 ;; now show everything.
6892 (unless (org-before-first-heading-p)
6893 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6894 (outline-flag-region eoh eos nil)
6895 (org-unlogged-message
6896 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6897 (setq org-cycle-subtree-status 'subtree)
6898 (unless (org-before-first-heading-p)
6899 (run-hook-with-args 'org-cycle-hook 'subtree)))
6901 ;; Default action: hide the subtree.
6902 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6903 (outline-flag-region eoh eos t)
6904 (org-unlogged-message "FOLDED")
6905 (setq org-cycle-subtree-status 'folded)
6906 (unless (org-before-first-heading-p)
6907 (run-hook-with-args 'org-cycle-hook 'folded))))))
6909 ;;;###autoload
6910 (defun org-global-cycle (&optional arg)
6911 "Cycle the global visibility. For details see `org-cycle'.
6912 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6913 With a numeric prefix, show all headlines up to that level."
6914 (interactive "P")
6915 (let ((org-cycle-include-plain-lists
6916 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6917 (cond
6918 ((integerp arg)
6919 (outline-show-all)
6920 (outline-hide-sublevels arg)
6921 (setq org-cycle-global-status 'contents))
6922 ((equal arg '(4))
6923 (org-set-startup-visibility)
6924 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6926 (org-cycle '(4))))))
6928 (defun org-set-startup-visibility ()
6929 "Set the visibility required by startup options and properties."
6930 (cond
6931 ((eq org-startup-folded t)
6932 (org-overview))
6933 ((eq org-startup-folded 'content)
6934 (org-content))
6935 ((or (eq org-startup-folded 'showeverything)
6936 (eq org-startup-folded nil))
6937 (outline-show-all)))
6938 (unless (eq org-startup-folded 'showeverything)
6939 (when org-hide-block-startup (org-hide-block-all))
6940 (org-set-visibility-according-to-property 'no-cleanup)
6941 (org-cycle-hide-archived-subtrees 'all)
6942 (org-cycle-hide-drawers 'all)
6943 (org-cycle-show-empty-lines t)))
6945 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6946 "Switch subtree visibilities according to :VISIBILITY: property."
6947 (interactive)
6948 (org-with-wide-buffer
6949 (goto-char (point-min))
6950 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6951 (if (not (org-at-property-p)) (outline-next-heading)
6952 (let ((state (match-string 3)))
6953 (save-excursion
6954 (org-back-to-heading t)
6955 (outline-hide-subtree)
6956 (org-reveal)
6957 (cond
6958 ((equal state "folded")
6959 (outline-hide-subtree))
6960 ((equal state "children")
6961 (org-show-hidden-entry)
6962 (org-show-children))
6963 ((equal state "content")
6964 (save-excursion
6965 (save-restriction
6966 (org-narrow-to-subtree)
6967 (org-content))))
6968 ((member state '("all" "showall"))
6969 (outline-show-subtree)))))))
6970 (unless no-cleanup
6971 (org-cycle-hide-archived-subtrees 'all)
6972 (org-cycle-hide-drawers 'all)
6973 (org-cycle-show-empty-lines 'all))))
6975 (defun org-overview ()
6976 "Switch to overview mode, showing only top-level headlines.
6977 This shows all headlines with a level equal or greater than the level
6978 of the first headline in the buffer. This is important, because if the
6979 first headline is not level one, then (hide-sublevels 1) gives confusing
6980 results."
6981 (interactive)
6982 (save-excursion
6983 (let ((level
6984 (save-excursion
6985 (goto-char (point-min))
6986 (when (re-search-forward org-outline-regexp-bol nil t)
6987 (goto-char (match-beginning 0))
6988 (funcall outline-level)))))
6989 (and level (outline-hide-sublevels level)))))
6991 (defun org-content (&optional arg)
6992 "Show all headlines in the buffer, like a table of contents.
6993 With numerical argument N, show content up to level N."
6994 (interactive "P")
6995 (org-overview)
6996 (save-excursion
6997 ;; Visit all headings and show their offspring
6998 (and (integerp arg) (org-overview))
6999 (goto-char (point-max))
7000 (catch 'exit
7001 (while (and (progn (condition-case nil
7002 (outline-previous-visible-heading 1)
7003 (error (goto-char (point-min))))
7005 (looking-at org-outline-regexp))
7006 (if (integerp arg)
7007 (org-show-children (1- arg))
7008 (outline-show-branches))
7009 (when (bobp) (throw 'exit nil))))))
7011 (defun org-optimize-window-after-visibility-change (state)
7012 "Adjust the window after a change in outline visibility.
7013 This function is the default value of the hook `org-cycle-hook'."
7014 (when (get-buffer-window (current-buffer))
7015 (cond
7016 ((eq state 'content) nil)
7017 ((eq state 'all) nil)
7018 ((eq state 'folded) nil)
7019 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7020 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7022 (defun org-remove-empty-overlays-at (pos)
7023 "Remove outline overlays that do not contain non-white stuff."
7024 (dolist (o (overlays-at pos))
7025 (and (eq 'outline (overlay-get o 'invisible))
7026 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7027 (overlay-end o))))
7028 (delete-overlay o))))
7030 (defun org-clean-visibility-after-subtree-move ()
7031 "Fix visibility issues after moving a subtree."
7032 ;; First, find a reasonable region to look at:
7033 ;; Start two siblings above, end three below
7034 (let* ((beg (save-excursion
7035 (and (org-get-last-sibling)
7036 (org-get-last-sibling))
7037 (point)))
7038 (end (save-excursion
7039 (and (org-get-next-sibling)
7040 (org-get-next-sibling)
7041 (org-get-next-sibling))
7042 (if (org-at-heading-p)
7043 (point-at-eol)
7044 (point))))
7045 (level (looking-at "\\*+"))
7046 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7047 (save-excursion
7048 (save-restriction
7049 (narrow-to-region beg end)
7050 (when re
7051 ;; Properly fold already folded siblings
7052 (goto-char (point-min))
7053 (while (re-search-forward re nil t)
7054 (when (and (not (org-invisible-p))
7055 (save-excursion
7056 (goto-char (point-at-eol)) (org-invisible-p)))
7057 (outline-hide-entry))))
7058 (org-cycle-show-empty-lines 'overview)
7059 (org-cycle-hide-drawers 'overview)))))
7061 (defun org-cycle-show-empty-lines (state)
7062 "Show empty lines above all visible headlines.
7063 The region to be covered depends on STATE when called through
7064 `org-cycle-hook'. Lisp program can use t for STATE to get the
7065 entire buffer covered. Note that an empty line is only shown if there
7066 are at least `org-cycle-separator-lines' empty lines before the headline."
7067 (when (/= org-cycle-separator-lines 0)
7068 (save-excursion
7069 (let* ((n (abs org-cycle-separator-lines))
7070 (re (cond
7071 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7072 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7073 (t (let ((ns (number-to-string (- n 2))))
7074 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7075 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7076 beg end)
7077 (cond
7078 ((memq state '(overview contents t))
7079 (setq beg (point-min) end (point-max)))
7080 ((memq state '(children folded))
7081 (setq beg (point)
7082 end (progn (org-end-of-subtree t t)
7083 (line-beginning-position 2)))))
7084 (when beg
7085 (goto-char beg)
7086 (while (re-search-forward re end t)
7087 (unless (get-char-property (match-end 1) 'invisible)
7088 (let ((e (match-end 1))
7089 (b (if (>= org-cycle-separator-lines 0)
7090 (match-beginning 1)
7091 (save-excursion
7092 (goto-char (match-beginning 0))
7093 (skip-chars-backward " \t\n")
7094 (line-end-position)))))
7095 (outline-flag-region b e nil))))))))
7096 ;; Never hide empty lines at the end of the file.
7097 (save-excursion
7098 (goto-char (point-max))
7099 (outline-previous-heading)
7100 (outline-end-of-heading)
7101 (when (and (looking-at "[ \t\n]+")
7102 (= (match-end 0) (point-max)))
7103 (outline-flag-region (point) (match-end 0) nil))))
7105 (defun org-show-empty-lines-in-parent ()
7106 "Move to the parent and re-show empty lines before visible headlines."
7107 (save-excursion
7108 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7109 (org-cycle-show-empty-lines context))))
7111 (defun org-files-list ()
7112 "Return `org-agenda-files' list, plus all open Org files.
7113 This is useful for operations that need to scan all of a user's
7114 open and agenda-wise Org files."
7115 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7116 (dolist (buf (buffer-list))
7117 (with-current-buffer buf
7118 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7119 (cl-pushnew (expand-file-name (buffer-file-name)) files
7120 :test #'equal))))
7121 files))
7123 (defsubst org-entry-beginning-position ()
7124 "Return the beginning position of the current entry."
7125 (save-excursion (org-back-to-heading t) (point)))
7127 (defsubst org-entry-end-position ()
7128 "Return the end position of the current entry."
7129 (save-excursion (outline-next-heading) (point)))
7131 (defun org-cycle-hide-drawers (state &optional exceptions)
7132 "Re-hide all drawers after a visibility state change.
7133 STATE should be one of the symbols listed in the docstring of
7134 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7135 a list of strings specifying which drawers should not be hidden."
7136 (when (and (derived-mode-p 'org-mode)
7137 (not (memq state '(overview folded contents))))
7138 (save-excursion
7139 (let* ((globalp (eq state 'all))
7140 (beg (if globalp (point-min) (point)))
7141 (end (if globalp (point-max)
7142 (if (eq state 'children)
7143 (save-excursion (outline-next-heading) (point))
7144 (org-end-of-subtree t)))))
7145 (goto-char beg)
7146 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7147 (unless (member-ignore-case (match-string 1) exceptions)
7148 (let ((drawer (org-element-at-point)))
7149 (when (memq (org-element-type drawer) '(drawer property-drawer))
7150 (org-flag-drawer t drawer)
7151 ;; Make sure to skip drawer entirely or we might flag
7152 ;; it another time when matching its ending line with
7153 ;; `org-drawer-regexp'.
7154 (goto-char (org-element-property :end drawer))))))))))
7156 (defun org-flag-drawer (flag &optional element)
7157 "When FLAG is non-nil, hide the drawer we are at.
7158 Otherwise make it visible. When optional argument ELEMENT is
7159 a parsed drawer, as returned by `org-element-at-point', hide or
7160 show that drawer instead."
7161 (let ((drawer (or element
7162 (and (save-excursion
7163 (beginning-of-line)
7164 (looking-at-p org-drawer-regexp))
7165 (org-element-at-point)))))
7166 (when (memq (org-element-type drawer) '(drawer property-drawer))
7167 (let ((post (org-element-property :post-affiliated drawer)))
7168 (save-excursion
7169 (outline-flag-region
7170 (progn (goto-char post) (line-end-position))
7171 (progn (goto-char (org-element-property :end drawer))
7172 (skip-chars-backward " \r\t\n")
7173 (line-end-position))
7174 flag))
7175 ;; When the drawer is hidden away, make sure point lies in
7176 ;; a visible part of the buffer.
7177 (when (and flag (> (line-beginning-position) post))
7178 (goto-char post))))))
7180 (defun org-subtree-end-visible-p ()
7181 "Is the end of the current subtree visible?"
7182 (pos-visible-in-window-p
7183 (save-excursion (org-end-of-subtree t) (point))))
7185 (defun org-first-headline-recenter ()
7186 "Move cursor to the first headline and recenter the headline."
7187 (let ((window (get-buffer-window)))
7188 (when window
7189 (goto-char (point-min))
7190 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7191 (set-window-start window (line-beginning-position))))))
7193 ;;; Saving and restoring visibility
7195 (defun org-outline-overlay-data (&optional use-markers)
7196 "Return a list of the locations of all outline overlays.
7197 These are overlays with the `invisible' property value `outline'.
7198 The return value is a list of cons cells, with start and stop
7199 positions for each overlay.
7200 If USE-MARKERS is set, return the positions as markers."
7201 (let (beg end)
7202 (org-with-wide-buffer
7203 (delq nil
7204 (mapcar (lambda (o)
7205 (when (eq (overlay-get o 'invisible) 'outline)
7206 (setq beg (overlay-start o)
7207 end (overlay-end o))
7208 (and beg end (> end beg)
7209 (if use-markers
7210 (cons (copy-marker beg)
7211 (copy-marker end t))
7212 (cons beg end)))))
7213 (overlays-in (point-min) (point-max)))))))
7215 (defun org-set-outline-overlay-data (data)
7216 "Create visibility overlays for all positions in DATA.
7217 DATA should have been made by `org-outline-overlay-data'."
7218 (org-with-wide-buffer
7219 (outline-show-all)
7220 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7222 ;;; Folding of blocks
7224 (defvar-local org-hide-block-overlays nil
7225 "Overlays hiding blocks.")
7227 (defun org-block-map (function &optional start end)
7228 "Call FUNCTION at the head of all source blocks in the current buffer.
7229 Optional arguments START and END can be used to limit the range."
7230 (let ((start (or start (point-min)))
7231 (end (or end (point-max))))
7232 (save-excursion
7233 (goto-char start)
7234 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7235 (save-excursion
7236 (save-match-data
7237 (goto-char (match-beginning 0))
7238 (funcall function)))))))
7240 (defun org-hide-block-toggle-all ()
7241 "Toggle the visibility of all blocks in the current buffer."
7242 (org-block-map 'org-hide-block-toggle))
7244 (defun org-hide-block-all ()
7245 "Fold all blocks in the current buffer."
7246 (interactive)
7247 (org-show-block-all)
7248 (org-block-map 'org-hide-block-toggle-maybe))
7250 (defun org-show-block-all ()
7251 "Unfold all blocks in the current buffer."
7252 (interactive)
7253 (mapc #'delete-overlay org-hide-block-overlays)
7254 (setq org-hide-block-overlays nil))
7256 (defun org-hide-block-toggle-maybe ()
7257 "Toggle visibility of block at point.
7258 Unlike to `org-hide-block-toggle', this function does not throw
7259 an error. Return a non-nil value when toggling is successful."
7260 (interactive)
7261 (ignore-errors (org-hide-block-toggle)))
7263 (defun org-hide-block-toggle (&optional force)
7264 "Toggle the visibility of the current block.
7265 When optional argument FORCE is `off', make block visible. If it
7266 is non-nil, hide it unconditionally. Throw an error when not at
7267 a block. Return a non-nil value when toggling is successful."
7268 (interactive)
7269 (let ((element (org-element-at-point)))
7270 (unless (memq (org-element-type element)
7271 '(center-block comment-block dynamic-block example-block
7272 export-block quote-block special-block
7273 src-block verse-block))
7274 (user-error "Not at a block"))
7275 (let* ((start (save-excursion
7276 (goto-char (org-element-property :post-affiliated element))
7277 (line-end-position)))
7278 (end (save-excursion
7279 (goto-char (org-element-property :end element))
7280 (skip-chars-backward " \r\t\n")
7281 (line-end-position)))
7282 (overlays (overlays-at start)))
7283 (cond
7284 ;; Do nothing when not before or at the block opening line or
7285 ;; at the block closing line.
7286 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7287 ((and (not (eq force 'off))
7288 (not (memq t (mapcar
7289 (lambda (o)
7290 (eq (overlay-get o 'invisible) 'org-hide-block))
7291 overlays))))
7292 (let ((ov (make-overlay start end)))
7293 (overlay-put ov 'invisible 'org-hide-block)
7294 ;; Make the block accessible to `isearch'.
7295 (overlay-put
7296 ov 'isearch-open-invisible
7297 (lambda (ov)
7298 (when (memq ov org-hide-block-overlays)
7299 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7300 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7301 (delete-overlay ov))))
7302 (push ov org-hide-block-overlays)
7303 ;; When the block is hidden away, make sure point is left in
7304 ;; a visible part of the buffer.
7305 (when (> (line-beginning-position) start)
7306 (goto-char start)
7307 (beginning-of-line))
7308 ;; Signal successful toggling.
7310 ((or (not force) (eq force 'off))
7311 (dolist (ov overlays t)
7312 (when (memq ov org-hide-block-overlays)
7313 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7314 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7315 (delete-overlay ov))))))))
7317 ;; Remove overlays when changing major mode
7318 (add-hook 'org-mode-hook
7319 (lambda () (add-hook 'change-major-mode-hook
7320 'org-show-block-all 'append 'local)))
7322 ;;; Indirect buffer display of subtrees
7324 (defvar org-indirect-dedicated-frame nil
7325 "This is the frame being used for indirect tree display.")
7326 (defvar org-last-indirect-buffer nil)
7328 (defun org-tree-to-indirect-buffer (&optional arg)
7329 "Create indirect buffer and narrow it to current subtree.
7331 With a numerical prefix ARG, go up to this level and then take that tree.
7332 If ARG is negative, go up that many levels.
7334 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7335 indirect buffer previously made with this command, to avoid proliferation of
7336 indirect buffers. However, when you call the command with a \
7337 `\\[universal-argument]' prefix, or
7338 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7339 so that you can work with several indirect buffers at the same time. If
7340 `org-indirect-buffer-display' is `dedicated-frame', the \
7341 `\\[universal-argument]' prefix also
7342 requests that a new frame be made for the new buffer, so that the dedicated
7343 frame is not changed."
7344 (interactive "P")
7345 (let ((cbuf (current-buffer))
7346 (cwin (selected-window))
7347 (pos (point))
7348 beg end level heading ibuf)
7349 (save-excursion
7350 (org-back-to-heading t)
7351 (when (numberp arg)
7352 (setq level (org-outline-level))
7353 (when (< arg 0) (setq arg (+ level arg)))
7354 (while (> (setq level (org-outline-level)) arg)
7355 (org-up-heading-safe)))
7356 (setq beg (point)
7357 heading (org-get-heading 'no-tags))
7358 (org-end-of-subtree t t)
7359 (when (org-at-heading-p) (backward-char 1))
7360 (setq end (point)))
7361 (when (and (buffer-live-p org-last-indirect-buffer)
7362 (not (eq org-indirect-buffer-display 'new-frame))
7363 (not arg))
7364 (kill-buffer org-last-indirect-buffer))
7365 (setq ibuf (org-get-indirect-buffer cbuf heading)
7366 org-last-indirect-buffer ibuf)
7367 (cond
7368 ((or (eq org-indirect-buffer-display 'new-frame)
7369 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7370 (select-frame (make-frame))
7371 (delete-other-windows)
7372 (pop-to-buffer-same-window ibuf)
7373 (org-set-frame-title heading))
7374 ((eq org-indirect-buffer-display 'dedicated-frame)
7375 (raise-frame
7376 (select-frame (or (and org-indirect-dedicated-frame
7377 (frame-live-p org-indirect-dedicated-frame)
7378 org-indirect-dedicated-frame)
7379 (setq org-indirect-dedicated-frame (make-frame)))))
7380 (delete-other-windows)
7381 (pop-to-buffer-same-window ibuf)
7382 (org-set-frame-title (concat "Indirect: " heading)))
7383 ((eq org-indirect-buffer-display 'current-window)
7384 (pop-to-buffer-same-window ibuf))
7385 ((eq org-indirect-buffer-display 'other-window)
7386 (pop-to-buffer ibuf))
7387 (t (error "Invalid value")))
7388 (narrow-to-region beg end)
7389 (outline-show-all)
7390 (goto-char pos)
7391 (run-hook-with-args 'org-cycle-hook 'all)
7392 (and (window-live-p cwin) (select-window cwin))))
7394 (defun org-get-indirect-buffer (&optional buffer heading)
7395 (setq buffer (or buffer (current-buffer)))
7396 (let ((n 1) (base (buffer-name buffer)) bname)
7397 (while (buffer-live-p
7398 (get-buffer
7399 (setq bname
7400 (concat base "-"
7401 (if heading (concat heading "-" (number-to-string n))
7402 (number-to-string n))))))
7403 (setq n (1+ n)))
7404 (condition-case nil
7405 (make-indirect-buffer buffer bname 'clone)
7406 (error (make-indirect-buffer buffer bname)))))
7408 (defun org-set-frame-title (title)
7409 "Set the title of the current frame to the string TITLE."
7410 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7412 ;;;; Structure editing
7414 ;;; Inserting headlines
7416 (defun org--line-empty-p (n)
7417 "Is the Nth next line empty?
7419 Counts the current line as N = 1 and the previous line as N = 0;
7420 see `beginning-of-line'."
7421 (save-excursion
7422 (and (not (bobp))
7423 (or (beginning-of-line n) t)
7424 (save-match-data
7425 (looking-at "[ \t]*$")))))
7427 (defun org-previous-line-empty-p ()
7428 "Is the previous line a blank line?
7429 When NEXT is non-nil, check the next line instead."
7430 (org--line-empty-p 0))
7432 (defun org-next-line-empty-p ()
7433 "Is the previous line a blank line?
7434 When NEXT is non-nil, check the next line instead."
7435 (org--line-empty-p 2))
7437 (defun org--blank-before-heading-p (&optional parent)
7438 "Non-nil when an empty line should precede a new heading here.
7439 When optional argument PARENT is non-nil, consider parent
7440 headline instead of current one."
7441 (pcase (assq 'heading org-blank-before-new-entry)
7442 (`(heading . auto)
7443 (save-excursion
7444 (org-with-limited-levels
7445 (unless (and (org-before-first-heading-p)
7446 (not (outline-next-heading)))
7447 (org-back-to-heading t)
7448 (when parent (org-up-heading-safe))
7449 (cond ((not (bobp))
7450 (org-previous-line-empty-p))
7451 ((outline-next-heading)
7452 (org-previous-line-empty-p))
7453 ;; Ignore trailing spaces on last buffer line.
7454 ((progn (skip-chars-backward " \t") (bolp))
7455 (org-previous-line-empty-p))
7456 (t nil))))))
7457 (`(heading . ,value) value)
7458 (_ nil)))
7460 (defun org-insert-heading (&optional arg invisible-ok top)
7461 "Insert a new heading or an item with the same depth at point.
7463 If point is at the beginning of a heading, insert a new heading
7464 or a new headline above the current one. When at the beginning
7465 of a regular line of text, turn it into a heading.
7467 If point is in the middle of a line, split it and create a new
7468 headline with the text in the current line after point (see
7469 `org-M-RET-may-split-line' on how to modify this behavior). As
7470 a special case, on a headline, splitting can only happen on the
7471 title itself. E.g., this excludes breaking stars or tags.
7473 With a `\\[universal-argument]' prefix, set \
7474 `org-insert-heading-respect-content' to
7475 a non-nil value for the duration of the command. This forces the
7476 insertion of a heading after the current subtree, independently
7477 on the location of point.
7479 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7480 insert the heading at the end of the tree
7481 above the current heading. For example, if point is within a
7482 2nd-level heading, then it will insert a 2nd-level heading at
7483 the end of the 1st-level parent subtree.
7485 When INVISIBLE-OK is set, stop at invisible headlines when going
7486 back. This is important for non-interactive uses of the
7487 command.
7489 When optional argument TOP is non-nil, insert a level 1 heading,
7490 unconditionally."
7491 (interactive "P")
7492 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7493 (level (org-current-level))
7494 (stars (make-string (if (and level (not top)) level 1) ?*)))
7495 (cond
7496 ((or org-insert-heading-respect-content
7497 (member arg '((4) (16)))
7498 (and (not invisible-ok)
7499 (invisible-p (max (1- (point)) (point-min)))))
7500 ;; Position point at the location of insertion.
7501 (if (not level) ;before first headline
7502 (org-with-limited-levels (outline-next-heading))
7503 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7504 ;; is nil.
7505 (org-with-limited-levels (org-back-to-heading invisible-ok))
7506 (cond ((equal arg '(16))
7507 (org-up-heading-safe)
7508 (org-end-of-subtree t t))
7510 (org-end-of-subtree t t))))
7511 (unless (bolp) (insert "\n")) ;ensure final newline
7512 (unless (and blank? (org-previous-line-empty-p))
7513 (org-N-empty-lines-before-current (if blank? 1 0)))
7514 (insert stars " \n")
7515 (forward-char -1))
7516 ;; At a headline...
7517 ((org-at-heading-p)
7518 (cond ((bolp)
7519 (when blank? (save-excursion (insert "\n")))
7520 (save-excursion (insert stars " \n"))
7521 (unless (and blank? (org-previous-line-empty-p))
7522 (org-N-empty-lines-before-current (if blank? 1 0)))
7523 (end-of-line))
7524 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7525 (org-match-line org-complex-heading-regexp)
7526 (org-pos-in-match-range (point) 4))
7527 ;; Grab the text that should moved to the new headline.
7528 ;; Preserve tags.
7529 (let ((split (delete-and-extract-region (point) (match-end 4))))
7530 (if (looking-at "[ \t]*$") (replace-match "")
7531 (org-set-tags nil t))
7532 (end-of-line)
7533 (when blank? (insert "\n"))
7534 (insert "\n" stars " ")
7535 (when (org-string-nw-p split) (insert split))
7536 (when (eobp) (save-excursion (insert "\n")))))
7538 (end-of-line)
7539 (when blank? (insert "\n"))
7540 (insert "\n" stars " ")
7541 (when (eobp) (save-excursion (insert "\n"))))))
7542 ;; On regular text, turn line into a headline or split, if
7543 ;; appropriate.
7544 ((bolp)
7545 (insert stars " ")
7546 (unless (and blank? (org-previous-line-empty-p))
7547 (org-N-empty-lines-before-current (if blank? 1 0))))
7549 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7550 (end-of-line))
7551 (insert "\n" stars " ")
7552 (unless (and blank? (org-previous-line-empty-p))
7553 (org-N-empty-lines-before-current (if blank? 1 0))))))
7554 (run-hooks 'org-insert-heading-hook))
7556 (defun org-N-empty-lines-before-current (n)
7557 "Make the number of empty lines before current exactly N.
7558 So this will delete or add empty lines."
7559 (let ((column (current-column)))
7560 (beginning-of-line)
7561 (unless (bobp)
7562 (let ((start (save-excursion
7563 (skip-chars-backward " \r\t\n")
7564 (line-end-position))))
7565 (delete-region start (line-end-position 0))))
7566 (insert (make-string n ?\n))
7567 (move-to-column column)))
7569 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7570 "Return the heading of the current entry, without the stars.
7571 When NO-TAGS is non-nil, don't include tags.
7572 When NO-TODO is non-nil, don't include TODO keywords.
7573 When NO-PRIORITY is non-nil, don't include priority cookie.
7574 When NO-COMMENT is non-nil, don't include COMMENT string."
7575 (save-excursion
7576 (org-back-to-heading t)
7577 (let ((case-fold-search nil))
7578 (looking-at org-complex-heading-regexp)
7579 (let ((todo (and (not no-todo) (match-string 2)))
7580 (priority (and (not no-priority) (match-string 3)))
7581 (headline (pcase (match-string 4)
7582 (`nil "")
7583 ((and (guard no-comment) h)
7584 (replace-regexp-in-string
7585 (eval-when-compile
7586 (format "\\`%s[ \t]+" org-comment-string))
7587 "" h))
7588 (h h)))
7589 (tags (and (not no-tags) (match-string 5))))
7590 (mapconcat #'identity
7591 (delq nil (list todo priority headline tags))
7592 " ")))))
7594 (defun org-heading-components ()
7595 "Return the components of the current heading.
7596 This is a list with the following elements:
7597 - the level as an integer
7598 - the reduced level, different if `org-odd-levels-only' is set.
7599 - the TODO keyword, or nil
7600 - the priority character, like ?A, or nil if no priority is given
7601 - the headline text itself, or the tags string if no headline text
7602 - the tags string, or nil."
7603 (save-excursion
7604 (org-back-to-heading t)
7605 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7606 (list (length (match-string 1))
7607 (org-reduced-level (length (match-string 1)))
7608 (match-string-no-properties 2)
7609 (and (match-end 3) (aref (match-string 3) 2))
7610 (match-string-no-properties 4)
7611 (match-string-no-properties 5)))))
7613 (defun org-get-entry ()
7614 "Get the entry text, after heading, entire subtree."
7615 (save-excursion
7616 (org-back-to-heading t)
7617 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7619 (defun org-edit-headline (&optional heading)
7620 "Edit the current headline.
7621 Set it to HEADING when provided."
7622 (interactive)
7623 (org-with-wide-buffer
7624 (org-back-to-heading t)
7625 (let ((case-fold-search nil))
7626 (when (looking-at org-complex-heading-regexp)
7627 (let* ((old (match-string-no-properties 4))
7628 (new (save-match-data
7629 (org-trim (or heading (read-string "Edit: " old))))))
7630 (unless (equal old new)
7631 (if old (replace-match new t t nil 4)
7632 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7633 (insert " " new))
7634 (org-set-tags nil t)
7635 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7637 (defun org-insert-heading-after-current ()
7638 "Insert a new heading with same level as current, after current subtree."
7639 (interactive)
7640 (org-back-to-heading)
7641 (org-insert-heading)
7642 (org-move-subtree-down)
7643 (end-of-line 1))
7645 (defun org-insert-heading-respect-content (&optional invisible-ok)
7646 "Insert heading with `org-insert-heading-respect-content' set to t."
7647 (interactive)
7648 (org-insert-heading '(4) invisible-ok))
7650 (defun org-insert-todo-heading-respect-content (&optional force-state)
7651 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7652 (interactive)
7653 (org-insert-todo-heading force-state '(4)))
7655 (defun org-insert-todo-heading (arg &optional force-heading)
7656 "Insert a new heading with the same level and TODO state as current heading.
7658 If the heading has no TODO state, or if the state is DONE, use
7659 the first state (TODO by default). Also with one prefix arg,
7660 force first state. With two prefix args, force inserting at the
7661 end of the parent subtree.
7663 When called at a plain list item, insert a new item with an
7664 unchecked check box."
7665 (interactive "P")
7666 (when (or force-heading (not (org-insert-item 'checkbox)))
7667 (org-insert-heading (or (and (equal arg '(16)) '(16))
7668 force-heading))
7669 (save-excursion
7670 (org-forward-heading-same-level -1)
7671 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7672 (let* ((new-mark-x
7673 (if (or (equal arg '(4))
7674 (not (match-beginning 2))
7675 (member (match-string 2) org-done-keywords))
7676 (car org-todo-keywords-1)
7677 (match-string 2)))
7678 (new-mark
7680 (run-hook-with-args-until-success
7681 'org-todo-get-default-hook new-mark-x nil)
7682 new-mark-x)))
7683 (beginning-of-line 1)
7684 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7685 (if org-treat-insert-todo-heading-as-state-change
7686 (org-todo new-mark)
7687 (insert new-mark " "))))
7688 (when org-provide-todo-statistics
7689 (org-update-parent-todo-statistics))))
7691 (defun org-insert-subheading (arg)
7692 "Insert a new subheading and demote it.
7693 Works for outline headings and for plain lists alike."
7694 (interactive "P")
7695 (org-insert-heading arg)
7696 (cond
7697 ((org-at-heading-p) (org-do-demote))
7698 ((org-at-item-p) (org-indent-item))))
7700 (defun org-insert-todo-subheading (arg)
7701 "Insert a new subheading with TODO keyword or checkbox and demote it.
7702 Works for outline headings and for plain lists alike."
7703 (interactive "P")
7704 (org-insert-todo-heading arg)
7705 (cond
7706 ((org-at-heading-p) (org-do-demote))
7707 ((org-at-item-p) (org-indent-item))))
7709 ;;; Promotion and Demotion
7711 (defvar org-after-demote-entry-hook nil
7712 "Hook run after an entry has been demoted.
7713 The cursor will be at the beginning of the entry.
7714 When a subtree is being demoted, the hook will be called for each node.")
7716 (defvar org-after-promote-entry-hook nil
7717 "Hook run after an entry has been promoted.
7718 The cursor will be at the beginning of the entry.
7719 When a subtree is being promoted, the hook will be called for each node.")
7721 (defun org-promote-subtree ()
7722 "Promote the entire subtree.
7723 See also `org-promote'."
7724 (interactive)
7725 (save-excursion
7726 (org-with-limited-levels (org-map-tree 'org-promote)))
7727 (org-fix-position-after-promote))
7729 (defun org-demote-subtree ()
7730 "Demote the entire subtree.
7731 See `org-demote' and `org-promote'."
7732 (interactive)
7733 (save-excursion
7734 (org-with-limited-levels (org-map-tree 'org-demote)))
7735 (org-fix-position-after-promote))
7737 (defun org-do-promote ()
7738 "Promote the current heading higher up the tree.
7739 If the region is active in `transient-mark-mode', promote all
7740 headings in the region."
7741 (interactive)
7742 (save-excursion
7743 (if (org-region-active-p)
7744 (org-map-region 'org-promote (region-beginning) (region-end))
7745 (org-promote)))
7746 (org-fix-position-after-promote))
7748 (defun org-do-demote ()
7749 "Demote the current heading lower down the tree.
7750 If the region is active in `transient-mark-mode', demote all
7751 headings in the region."
7752 (interactive)
7753 (save-excursion
7754 (if (org-region-active-p)
7755 (org-map-region 'org-demote (region-beginning) (region-end))
7756 (org-demote)))
7757 (org-fix-position-after-promote))
7759 (defun org-fix-position-after-promote ()
7760 "Fix cursor position and indentation after demoting/promoting."
7761 (let ((pos (point)))
7762 (when (save-excursion
7763 (beginning-of-line)
7764 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7765 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7766 (cond ((eobp) (insert " "))
7767 ((eolp) (insert " "))
7768 ((equal (char-after) ?\s) (forward-char 1))))))
7770 (defun org-current-level ()
7771 "Return the level of the current entry, or nil if before the first headline.
7772 The level is the number of stars at the beginning of the
7773 headline. Use `org-reduced-level' to remove the effect of
7774 `org-odd-levels'. Unlike to `org-outline-level', this function
7775 ignores inlinetasks."
7776 (let ((level (org-with-limited-levels (org-outline-level))))
7777 (and (> level 0) level)))
7779 (defun org-get-previous-line-level ()
7780 "Return the outline depth of the last headline before the current line.
7781 Returns 0 for the first headline in the buffer, and nil if before the
7782 first headline."
7783 (and (org-current-level)
7784 (or (and (/= (line-beginning-position) (point-min))
7785 (save-excursion (beginning-of-line 0) (org-current-level)))
7786 0)))
7788 (defun org-reduced-level (l)
7789 "Compute the effective level of a heading.
7790 This takes into account the setting of `org-odd-levels-only'."
7791 (cond
7792 ((zerop l) 0)
7793 (org-odd-levels-only (1+ (floor (/ l 2))))
7794 (t l)))
7796 (defun org-level-increment ()
7797 "Return the number of stars that will be added or removed at a
7798 time to headlines when structure editing, based on the value of
7799 `org-odd-levels-only'."
7800 (if org-odd-levels-only 2 1))
7802 (defun org-get-valid-level (level &optional change)
7803 "Rectify a level change under the influence of `org-odd-levels-only'.
7804 LEVEL is a current level, CHANGE is by how much the level should
7805 be modified. Even if CHANGE is nil, LEVEL may be returned
7806 modified because even level numbers will become the next higher
7807 odd number. Returns values greater than 0."
7808 (if org-odd-levels-only
7809 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7810 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7811 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7812 (max 1 (+ level (or change 0)))))
7814 (defun org-promote ()
7815 "Promote the current heading higher up the tree."
7816 (org-with-wide-buffer
7817 (org-back-to-heading t)
7818 (let* ((after-change-functions (remq 'flyspell-after-change-function
7819 after-change-functions))
7820 (level (save-match-data (funcall outline-level)))
7821 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7822 (diff (abs (- level (length up-head) -1))))
7823 (cond
7824 ((and (= level 1) org-allow-promoting-top-level-subtree)
7825 (replace-match "# " nil t))
7826 ((= level 1)
7827 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7828 (t (replace-match up-head nil t)))
7829 (unless (= level 1)
7830 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7831 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7832 (run-hooks 'org-after-promote-entry-hook))))
7834 (defun org-demote ()
7835 "Demote the current heading lower down the tree."
7836 (org-with-wide-buffer
7837 (org-back-to-heading t)
7838 (let* ((after-change-functions (remq 'flyspell-after-change-function
7839 after-change-functions))
7840 (level (save-match-data (funcall outline-level)))
7841 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7842 (diff (abs (- level (length down-head) -1))))
7843 (replace-match down-head nil t)
7844 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7845 (when org-adapt-indentation (org-fixup-indentation diff))
7846 (run-hooks 'org-after-demote-entry-hook))))
7848 (defun org-cycle-level ()
7849 "Cycle the level of an empty headline through possible states.
7850 This goes first to child, then to parent, level, then up the hierarchy.
7851 After top level, it switches back to sibling level."
7852 (interactive)
7853 (let ((org-adapt-indentation nil))
7854 (when (org-point-at-end-of-empty-headline)
7855 (setq this-command 'org-cycle-level) ; Only needed for caching
7856 (let ((cur-level (org-current-level))
7857 (prev-level (org-get-previous-line-level)))
7858 (cond
7859 ;; If first headline in file, promote to top-level.
7860 ((= prev-level 0)
7861 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7862 do (org-do-promote)))
7863 ;; If same level as prev, demote one.
7864 ((= prev-level cur-level)
7865 (org-do-demote))
7866 ;; If parent is top-level, promote to top level if not already.
7867 ((= prev-level 1)
7868 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7869 do (org-do-promote)))
7870 ;; If top-level, return to prev-level.
7871 ((= cur-level 1)
7872 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7873 do (org-do-demote)))
7874 ;; If less than prev-level, promote one.
7875 ((< cur-level prev-level)
7876 (org-do-promote))
7877 ;; If deeper than prev-level, promote until higher than
7878 ;; prev-level.
7879 ((> cur-level prev-level)
7880 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7881 do (org-do-promote))))
7882 t))))
7884 (defun org-map-tree (fun)
7885 "Call FUN for every heading underneath the current one."
7886 (org-back-to-heading t)
7887 (let ((level (funcall outline-level)))
7888 (save-excursion
7889 (funcall fun)
7890 (while (and (progn
7891 (outline-next-heading)
7892 (> (funcall outline-level) level))
7893 (not (eobp)))
7894 (funcall fun)))))
7896 (defun org-map-region (fun beg end)
7897 "Call FUN for every heading between BEG and END."
7898 (let ((org-ignore-region t))
7899 (save-excursion
7900 (setq end (copy-marker end))
7901 (goto-char beg)
7902 (when (and (re-search-forward org-outline-regexp-bol nil t)
7903 (< (point) end))
7904 (funcall fun))
7905 (while (and (progn
7906 (outline-next-heading)
7907 (< (point) end))
7908 (not (eobp)))
7909 (funcall fun)))))
7911 (defun org-fixup-indentation (diff)
7912 "Change the indentation in the current entry by DIFF.
7914 DIFF is an integer. Indentation is done according to the
7915 following rules:
7917 - Planning information and property drawers are always indented
7918 according to the new level of the headline;
7920 - Footnote definitions and their contents are ignored;
7922 - Inlinetasks' boundaries are not shifted;
7924 - Empty lines are ignored;
7926 - Other lines' indentation are shifted by DIFF columns, unless
7927 it would introduce a structural change in the document, in
7928 which case no shifting is done at all.
7930 Assume point is at a heading or an inlinetask beginning."
7931 (org-with-wide-buffer
7932 (narrow-to-region (line-beginning-position)
7933 (save-excursion
7934 (if (org-with-limited-levels (org-at-heading-p))
7935 (org-with-limited-levels (outline-next-heading))
7936 (org-inlinetask-goto-end))
7937 (point)))
7938 (forward-line)
7939 ;; Indent properly planning info and property drawer.
7940 (when (looking-at-p org-planning-line-re)
7941 (org-indent-line)
7942 (forward-line))
7943 (when (looking-at org-property-drawer-re)
7944 (goto-char (match-end 0))
7945 (forward-line)
7946 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7947 (catch 'no-shift
7948 (when (zerop diff) (throw 'no-shift nil))
7949 ;; If DIFF is negative, first check if a shift is possible at all
7950 ;; (e.g., it doesn't break structure). This can only happen if
7951 ;; some contents are not properly indented.
7952 (let ((case-fold-search t))
7953 (when (< diff 0)
7954 (let ((diff (- diff))
7955 (forbidden-re (concat org-outline-regexp
7956 "\\|"
7957 (substring org-footnote-definition-re 1))))
7958 (save-excursion
7959 (while (not (eobp))
7960 (cond
7961 ((looking-at-p "[ \t]*$") (forward-line))
7962 ((and (looking-at-p org-footnote-definition-re)
7963 (let ((e (org-element-at-point)))
7964 (and (eq (org-element-type e) 'footnote-definition)
7965 (goto-char (org-element-property :end e))))))
7966 ((looking-at-p org-outline-regexp) (forward-line))
7967 ;; Give up if shifting would move before column 0 or
7968 ;; if it would introduce a headline or a footnote
7969 ;; definition.
7971 (skip-chars-forward " \t")
7972 (let ((ind (current-column)))
7973 (when (or (< ind diff)
7974 (and (= ind diff) (looking-at-p forbidden-re)))
7975 (throw 'no-shift nil)))
7976 ;; Ignore contents of example blocks and source
7977 ;; blocks if their indentation is meant to be
7978 ;; preserved. Jump to block's closing line.
7979 (beginning-of-line)
7980 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7981 (let ((e (org-element-at-point)))
7982 (and (memq (org-element-type e)
7983 '(example-block src-block))
7984 (or org-src-preserve-indentation
7985 (org-element-property :preserve-indent e))
7986 (goto-char (org-element-property :end e))
7987 (progn (skip-chars-backward " \r\t\n")
7988 (beginning-of-line)
7989 t))))
7990 (forward-line))))))))
7991 ;; Shift lines but footnote definitions, inlinetasks boundaries
7992 ;; by DIFF. Also skip contents of source or example blocks
7993 ;; when indentation is meant to be preserved.
7994 (while (not (eobp))
7995 (cond
7996 ((and (looking-at-p org-footnote-definition-re)
7997 (let ((e (org-element-at-point)))
7998 (and (eq (org-element-type e) 'footnote-definition)
7999 (goto-char (org-element-property :end e))))))
8000 ((looking-at-p org-outline-regexp) (forward-line))
8001 ((looking-at-p "[ \t]*$") (forward-line))
8003 (indent-line-to (+ (org-get-indentation) diff))
8004 (beginning-of-line)
8005 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8006 (let ((e (org-element-at-point)))
8007 (and (memq (org-element-type e)
8008 '(example-block src-block))
8009 (or org-src-preserve-indentation
8010 (org-element-property :preserve-indent e))
8011 (goto-char (org-element-property :end e))
8012 (progn (skip-chars-backward " \r\t\n")
8013 (beginning-of-line)
8014 t))))
8015 (forward-line)))))))))
8017 (defun org-convert-to-odd-levels ()
8018 "Convert an Org file with all levels allowed to one with odd levels.
8019 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8020 level 5 etc."
8021 (interactive)
8022 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8023 (let ((outline-level 'org-outline-level)
8024 (org-odd-levels-only nil) n)
8025 (save-excursion
8026 (goto-char (point-min))
8027 (while (re-search-forward "^\\*\\*+ " nil t)
8028 (setq n (- (length (match-string 0)) 2))
8029 (while (>= (setq n (1- n)) 0)
8030 (org-demote))
8031 (end-of-line 1))))))
8033 (defun org-convert-to-oddeven-levels ()
8034 "Convert an Org file with only odd levels to one with odd/even levels.
8035 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8036 file contains a section with an even level, conversion would
8037 destroy the structure of the file. An error is signaled in this
8038 case."
8039 (interactive)
8040 (goto-char (point-min))
8041 ;; First check if there are no even levels
8042 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8043 (org-show-set-visibility 'canonical)
8044 (error "Not all levels are odd in this file. Conversion not possible"))
8045 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8046 (let ((outline-regexp org-outline-regexp)
8047 (outline-level 'org-outline-level)
8048 (org-odd-levels-only nil) n)
8049 (save-excursion
8050 (goto-char (point-min))
8051 (while (re-search-forward "^\\*\\*+ " nil t)
8052 (setq n (/ (1- (length (match-string 0))) 2))
8053 (while (>= (setq n (1- n)) 0)
8054 (org-promote))
8055 (end-of-line 1))))))
8057 (defun org-tr-level (n)
8058 "Make N odd if required."
8059 (if org-odd-levels-only (1+ (/ n 2)) n))
8061 ;;; Vertical tree motion, cutting and pasting of subtrees
8063 (defun org-move-subtree-up (&optional arg)
8064 "Move the current subtree up past ARG headlines of the same level."
8065 (interactive "p")
8066 (org-move-subtree-down (- (prefix-numeric-value arg))))
8068 (defun org-move-subtree-down (&optional arg)
8069 "Move the current subtree down past ARG headlines of the same level."
8070 (interactive "p")
8071 (setq arg (prefix-numeric-value arg))
8072 (org-preserve-local-variables
8073 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8074 'org-get-last-sibling))
8075 (ins-point (make-marker))
8076 (cnt (abs arg))
8077 (col (current-column))
8078 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8079 ;; Select the tree
8080 (org-back-to-heading)
8081 (setq beg0 (point))
8082 (save-excursion
8083 (setq ne-beg (org-back-over-empty-lines))
8084 (setq beg (point)))
8085 (save-match-data
8086 (save-excursion (outline-end-of-heading)
8087 (setq folded (org-invisible-p)))
8088 (progn (org-end-of-subtree nil t)
8089 (unless (eobp) (backward-char))))
8090 (outline-next-heading)
8091 (setq ne-end (org-back-over-empty-lines))
8092 (setq end (point))
8093 (goto-char beg0)
8094 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8095 ;; include less whitespace
8096 (save-excursion
8097 (goto-char beg)
8098 (forward-line (- ne-beg ne-end))
8099 (setq beg (point))))
8100 ;; Find insertion point, with error handling
8101 (while (> cnt 0)
8102 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8103 (progn (goto-char beg0)
8104 (user-error "Cannot move past superior level or buffer limit")))
8105 (setq cnt (1- cnt)))
8106 (when (> arg 0)
8107 ;; Moving forward - still need to move over subtree
8108 (org-end-of-subtree t t)
8109 (save-excursion
8110 (org-back-over-empty-lines)
8111 (unless (bolp) (insert "\n"))))
8112 (setq ne-ins (org-back-over-empty-lines))
8113 (move-marker ins-point (point))
8114 (setq txt (buffer-substring beg end))
8115 (org-save-markers-in-region beg end)
8116 (delete-region beg end)
8117 (org-remove-empty-overlays-at beg)
8118 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8119 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8120 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8121 (let ((bbb (point)))
8122 (insert-before-markers txt)
8123 (org-reinstall-markers-in-region bbb)
8124 (move-marker ins-point bbb))
8125 (or (bolp) (insert "\n"))
8126 (setq ins-end (point))
8127 (goto-char ins-point)
8128 (org-skip-whitespace)
8129 (when (and (< arg 0)
8130 (org-first-sibling-p)
8131 (> ne-ins ne-beg))
8132 ;; Move whitespace back to beginning.
8133 (save-excursion
8134 (goto-char ins-end)
8135 (let ((kill-whole-line t))
8136 (kill-line (- ne-ins ne-beg)) (point)))
8137 (insert (make-string (- ne-ins ne-beg) ?\n)))
8138 (move-marker ins-point nil)
8139 (if folded
8140 (outline-hide-subtree)
8141 (org-show-entry)
8142 (org-show-children)
8143 (org-cycle-hide-drawers 'children))
8144 (org-clean-visibility-after-subtree-move)
8145 ;; Move back to the initial column we were at.
8146 (move-to-column col))))
8148 (defvar org-subtree-clip ""
8149 "Clipboard for cut and paste of subtrees.
8150 This is actually only a copy of the kill, because we use the normal kill
8151 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8153 (defvar org-subtree-clip-folded nil
8154 "Was the last copied subtree folded?
8155 This is used to fold the tree back after pasting.")
8157 (defun org-cut-subtree (&optional n)
8158 "Cut the current subtree into the clipboard.
8159 With prefix arg N, cut this many sequential subtrees.
8160 This is a short-hand for marking the subtree and then cutting it."
8161 (interactive "p")
8162 (org-copy-subtree n 'cut))
8164 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8165 "Copy the current subtree it in the clipboard.
8166 With prefix arg N, copy this many sequential subtrees.
8167 This is a short-hand for marking the subtree and then copying it.
8168 If CUT is non-nil, actually cut the subtree.
8169 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8170 of some markers in the region, even if CUT is non-nil. This is
8171 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8172 (interactive "p")
8173 (org-preserve-local-variables
8174 (let (beg end folded (beg0 (point)))
8175 (if (called-interactively-p 'any)
8176 (org-back-to-heading nil) ; take what looks like a subtree
8177 (org-back-to-heading t)) ; take what is really there
8178 (setq beg (point))
8179 (skip-chars-forward " \t\r\n")
8180 (save-match-data
8181 (if nosubtrees
8182 (outline-next-heading)
8183 (save-excursion (outline-end-of-heading)
8184 (setq folded (org-invisible-p)))
8185 (ignore-errors (org-forward-heading-same-level (1- n) t))
8186 (org-end-of-subtree t t)))
8187 ;; Include the end of an inlinetask
8188 (when (and (featurep 'org-inlinetask)
8189 (looking-at-p (concat (org-inlinetask-outline-regexp)
8190 "END[ \t]*$")))
8191 (end-of-line))
8192 (setq end (point))
8193 (goto-char beg0)
8194 (when (> end beg)
8195 (setq org-subtree-clip-folded folded)
8196 (when (or cut force-store-markers)
8197 (org-save-markers-in-region beg end))
8198 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8199 (setq org-subtree-clip (current-kill 0))
8200 (message "%s: Subtree(s) with %d characters"
8201 (if cut "Cut" "Copied")
8202 (length org-subtree-clip))))))
8204 (defun org-paste-subtree (&optional level tree for-yank remove)
8205 "Paste the clipboard as a subtree, with modification of headline level.
8206 The entire subtree is promoted or demoted in order to match a new headline
8207 level.
8209 If the cursor is at the beginning of a headline, the same level as
8210 that headline is used to paste the tree.
8212 If not, the new level is derived from the *visible* headings
8213 before and after the insertion point, and taken to be the inferior headline
8214 level of the two. So if the previous visible heading is level 3 and the
8215 next is level 4 (or vice versa), level 4 will be used for insertion.
8216 This makes sure that the subtree remains an independent subtree and does
8217 not swallow low level entries.
8219 You can also force a different level, either by using a numeric prefix
8220 argument, or by inserting the heading marker by hand. For example, if the
8221 cursor is after \"*****\", then the tree will be shifted to level 5.
8223 If optional TREE is given, use this text instead of the kill ring.
8225 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8226 move back over whitespace before inserting, and move point to the end of
8227 the inserted text when done.
8229 When REMOVE is non-nil, remove the subtree from the clipboard."
8230 (interactive "P")
8231 (setq tree (or tree (and kill-ring (current-kill 0))))
8232 (unless (org-kill-is-subtree-p tree)
8233 (user-error "%s"
8234 (substitute-command-keys
8235 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8236 (org-with-limited-levels
8237 (let* ((visp (not (org-invisible-p)))
8238 (txt tree)
8239 (^re_ "\\(\\*+\\)[ \t]*")
8240 (old-level (if (string-match org-outline-regexp-bol txt)
8241 (- (match-end 0) (match-beginning 0) 1)
8242 -1))
8243 (force-level (cond (level (prefix-numeric-value level))
8244 ((and (looking-at "[ \t]*$")
8245 (string-match
8246 "^\\*+$" (buffer-substring
8247 (point-at-bol) (point))))
8248 (- (match-end 0) (match-beginning 0)))
8249 ((and (bolp)
8250 (looking-at org-outline-regexp))
8251 (- (match-end 0) (point) 1))))
8252 (previous-level (save-excursion
8253 (condition-case nil
8254 (progn
8255 (outline-previous-visible-heading 1)
8256 (if (looking-at ^re_)
8257 (- (match-end 0) (match-beginning 0) 1)
8259 (error 1))))
8260 (next-level (save-excursion
8261 (condition-case nil
8262 (progn
8263 (or (looking-at org-outline-regexp)
8264 (outline-next-visible-heading 1))
8265 (if (looking-at ^re_)
8266 (- (match-end 0) (match-beginning 0) 1)
8268 (error 1))))
8269 (new-level (or force-level (max previous-level next-level)))
8270 (shift (if (or (= old-level -1)
8271 (= new-level -1)
8272 (= old-level new-level))
8274 (- new-level old-level)))
8275 (delta (if (> shift 0) -1 1))
8276 (func (if (> shift 0) 'org-demote 'org-promote))
8277 (org-odd-levels-only nil)
8278 beg end newend)
8279 ;; Remove the forced level indicator
8280 (when force-level
8281 (delete-region (point-at-bol) (point)))
8282 ;; Paste
8283 (beginning-of-line (if (bolp) 1 2))
8284 (setq beg (point))
8285 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8286 (insert-before-markers txt)
8287 (unless (string-suffix-p "\n" txt) (insert "\n"))
8288 (setq newend (point))
8289 (org-reinstall-markers-in-region beg)
8290 (setq end (point))
8291 (goto-char beg)
8292 (skip-chars-forward " \t\n\r")
8293 (setq beg (point))
8294 (when (and (org-invisible-p) visp)
8295 (save-excursion (outline-show-heading)))
8296 ;; Shift if necessary
8297 (unless (= shift 0)
8298 (save-restriction
8299 (narrow-to-region beg end)
8300 (while (not (= shift 0))
8301 (org-map-region func (point-min) (point-max))
8302 (setq shift (+ delta shift)))
8303 (goto-char (point-min))
8304 (setq newend (point-max))))
8305 (when (or (called-interactively-p 'interactive) for-yank)
8306 (message "Clipboard pasted as level %d subtree" new-level))
8307 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8308 kill-ring
8309 (eq org-subtree-clip (current-kill 0))
8310 org-subtree-clip-folded)
8311 ;; The tree was folded before it was killed/copied
8312 (outline-hide-subtree))
8313 (and for-yank (goto-char newend))
8314 (and remove (setq kill-ring (cdr kill-ring))))))
8316 (defun org-kill-is-subtree-p (&optional txt)
8317 "Check if the current kill is an outline subtree, or a set of trees.
8318 Returns nil if kill does not start with a headline, or if the first
8319 headline level is not the largest headline level in the tree.
8320 So this will actually accept several entries of equal levels as well,
8321 which is OK for `org-paste-subtree'.
8322 If optional TXT is given, check this string instead of the current kill."
8323 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8324 (re (org-get-limited-outline-regexp))
8325 (^re (concat "^" re))
8326 (start-level (and kill
8327 (string-match
8328 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8329 kill)
8330 (- (match-end 2) (match-beginning 2) 1)))
8331 (start (1+ (or (match-beginning 2) -1))))
8332 (if (not start-level)
8333 (progn
8334 nil) ;; does not even start with a heading
8335 (catch 'exit
8336 (while (setq start (string-match ^re kill (1+ start)))
8337 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8338 (throw 'exit nil)))
8339 t))))
8341 (defvar org-markers-to-move nil
8342 "Markers that should be moved with a cut-and-paste operation.
8343 Those markers are stored together with their positions relative to
8344 the start of the region.")
8346 (defun org-save-markers-in-region (beg end)
8347 "Check markers in region.
8348 If these markers are between BEG and END, record their position relative
8349 to BEG, so that after moving the block of text, we can put the markers back
8350 into place.
8351 This function gets called just before an entry or tree gets cut from the
8352 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8353 called immediately, to move the markers with the entries."
8354 (setq org-markers-to-move nil)
8355 (when (featurep 'org-clock)
8356 (org-clock-save-markers-for-cut-and-paste beg end))
8357 (when (featurep 'org-agenda)
8358 (org-agenda-save-markers-for-cut-and-paste beg end)))
8360 (defun org-check-and-save-marker (marker beg end)
8361 "Check if MARKER is between BEG and END.
8362 If yes, remember the marker and the distance to BEG."
8363 (when (and (marker-buffer marker)
8364 (equal (marker-buffer marker) (current-buffer))
8365 (>= marker beg) (< marker end))
8366 (push (cons marker (- marker beg)) org-markers-to-move)))
8368 (defun org-reinstall-markers-in-region (beg)
8369 "Move all remembered markers to their position relative to BEG."
8370 (dolist (x org-markers-to-move)
8371 (move-marker (car x) (+ beg (cdr x))))
8372 (setq org-markers-to-move nil))
8374 (defun org-narrow-to-subtree ()
8375 "Narrow buffer to the current subtree."
8376 (interactive)
8377 (save-excursion
8378 (save-match-data
8379 (org-with-limited-levels
8380 (narrow-to-region
8381 (progn (org-back-to-heading t) (point))
8382 (progn (org-end-of-subtree t t)
8383 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8384 (point)))))))
8386 (defun org-narrow-to-block ()
8387 "Narrow buffer to the current block."
8388 (interactive)
8389 (let* ((case-fold-search t)
8390 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8391 "^[ \t]*#\\+end_.*")))
8392 (if blockp
8393 (narrow-to-region (car blockp) (cdr blockp))
8394 (user-error "Not in a block"))))
8396 (defun org-clone-subtree-with-time-shift (n &optional shift)
8397 "Clone the task (subtree) at point N times.
8398 The clones will be inserted as siblings.
8400 In interactive use, the user will be prompted for the number of
8401 clones to be produced. If the entry has a timestamp, the user
8402 will also be prompted for a time shift, which may be a repeater
8403 as used in time stamps, for example `+3d'. To disable this,
8404 you can call the function with a universal prefix argument.
8406 When a valid repeater is given and the entry contains any time
8407 stamps, the clones will become a sequence in time, with time
8408 stamps in the subtree shifted for each clone produced. If SHIFT
8409 is nil or the empty string, time stamps will be left alone. The
8410 ID property of the original subtree is removed.
8412 In each clone, all the CLOCK entries will be removed. This
8413 prevents Org from considering that the clocked times overlap.
8415 If the original subtree did contain time stamps with a repeater,
8416 the following will happen:
8417 - the repeater will be removed in each clone
8418 - an additional clone will be produced, with the current, unshifted
8419 date(s) in the entry.
8420 - the original entry will be placed *after* all the clones, with
8421 repeater intact.
8422 - the start days in the repeater in the original entry will be shifted
8423 to past the last clone.
8424 In this way you can spell out a number of instances of a repeating task,
8425 and still retain the repeater to cover future instances of the task.
8427 As described above, N+1 clones are produced when the original
8428 subtree has a repeater. Setting N to 0, then, can be used to
8429 remove the repeater from a subtree and create a shifted clone
8430 with the original repeater."
8431 (interactive "nNumber of clones to produce: ")
8432 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8433 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8434 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8435 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8436 (shift
8437 (or shift
8438 (if (and (not (equal current-prefix-arg '(4)))
8439 (save-excursion
8440 (goto-char beg)
8441 (re-search-forward org-ts-regexp-both end-of-tree t)))
8442 (read-from-minibuffer
8443 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8444 ""))) ;No time shift
8445 (doshift
8446 (and (org-string-nw-p shift)
8447 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8448 shift)
8449 (user-error "Invalid shift specification %s" shift)))))
8450 (goto-char end-of-tree)
8451 (unless (bolp) (insert "\n"))
8452 (let* ((end (point))
8453 (template (buffer-substring beg end))
8454 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8455 (shift-what (pcase (and doshift (match-string 2 shift))
8456 (`nil nil)
8457 ("d" 'day)
8458 ("w" (setq shift-n (* 7 shift-n)) 'day)
8459 ("m" 'month)
8460 ("y" 'year)
8461 (_ (error "Unsupported time unit"))))
8462 (nmin 1)
8463 (nmax n)
8464 (n-no-remove -1)
8465 (idprop (org-entry-get nil "ID")))
8466 (when (and doshift
8467 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8468 template))
8469 (delete-region beg end)
8470 (setq end beg)
8471 (setq nmin 0)
8472 (setq nmax (1+ nmax))
8473 (setq n-no-remove nmax))
8474 (goto-char end)
8475 (cl-loop for n from nmin to nmax do
8476 (insert
8477 ;; Prepare clone.
8478 (with-temp-buffer
8479 (insert template)
8480 (org-mode)
8481 (goto-char (point-min))
8482 (org-show-subtree)
8483 (and idprop (if org-clone-delete-id
8484 (org-entry-delete nil "ID")
8485 (org-id-get-create t)))
8486 (unless (= n 0)
8487 (while (re-search-forward org-clock-line-re nil t)
8488 (delete-region (line-beginning-position)
8489 (line-beginning-position 2)))
8490 (goto-char (point-min))
8491 (while (re-search-forward org-drawer-regexp nil t)
8492 (org-remove-empty-drawer-at (point))))
8493 (goto-char (point-min))
8494 (when doshift
8495 (while (re-search-forward org-ts-regexp-both nil t)
8496 (org-timestamp-change (* n shift-n) shift-what))
8497 (unless (= n n-no-remove)
8498 (goto-char (point-min))
8499 (while (re-search-forward org-ts-regexp nil t)
8500 (save-excursion
8501 (goto-char (match-beginning 0))
8502 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8503 (delete-region (match-beginning 1) (match-end 1)))))))
8504 (buffer-string)))))
8505 (goto-char beg)))
8507 ;;; Outline Sorting
8509 (defun org-sort (&optional with-case)
8510 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8511 Optional argument WITH-CASE means sort case-sensitively."
8512 (interactive "P")
8513 (org-call-with-arg
8514 (cond ((org-at-table-p) #'org-table-sort-lines)
8515 ((org-at-item-p) #'org-sort-list)
8516 (t #'org-sort-entries))
8517 with-case))
8519 (defun org-sort-remove-invisible (s)
8520 "Remove invisible part of links and emphasis markers from string S."
8521 (remove-text-properties 0 (length s) org-rm-props s)
8522 (replace-regexp-in-string
8523 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8524 (replace-regexp-in-string
8525 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8526 (org-link-display-format s)
8527 t t) t t))
8529 (defvar org-priority-regexp) ; defined later in the file
8531 (defvar org-after-sorting-entries-or-items-hook nil
8532 "Hook that is run after a bunch of entries or items have been sorted.
8533 When children are sorted, the cursor is in the parent line when this
8534 hook gets called. When a region or a plain list is sorted, the cursor
8535 will be in the first entry of the sorted region/list.")
8537 (defun org-sort-entries
8538 (&optional with-case sorting-type getkey-func compare-func property
8539 interactive?)
8540 "Sort entries on a certain level of an outline tree.
8541 If there is an active region, the entries in the region are sorted.
8542 Else, if the cursor is before the first entry, sort the top-level items.
8543 Else, the children of the entry at point are sorted.
8545 Sorting can be alphabetically, numerically, by date/time as given by
8546 a time stamp, by a property, by priority order, or by a custom function.
8548 The command prompts for the sorting type unless it has been given to the
8549 function through the SORTING-TYPE argument, which needs to be a character,
8550 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8551 the precise meaning of each character:
8553 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8554 c By creation time, which is assumed to be the first inactive time stamp
8555 at the beginning of a line.
8556 d By deadline date/time.
8557 k By clocking time.
8558 n Numerically, by converting the beginning of the entry/item to a number.
8559 o By order of TODO keywords.
8560 p By priority according to the cookie.
8561 r By the value of a property.
8562 s By scheduled date/time.
8563 t By date/time, either the first active time stamp in the entry, or, if
8564 none exist, by the first inactive one.
8566 Capital letters will reverse the sort order.
8568 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8569 called with point at the beginning of the record. It must return a
8570 value that is compatible with COMPARE-FUNC, the function used to
8571 compare entries.
8573 Comparing entries ignores case by default. However, with an optional argument
8574 WITH-CASE, the sorting considers case as well.
8576 Sorting is done against the visible part of the headlines, it ignores hidden
8577 links.
8579 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8581 A non-nil value for INTERACTIVE? is used to signal that this
8582 function is being called interactively."
8583 (interactive (list current-prefix-arg nil nil nil nil t))
8584 (let ((case-func (if with-case 'identity 'downcase))
8585 start beg end stars re re2
8586 txt what tmp)
8587 ;; Find beginning and end of region to sort
8588 (cond
8589 ((org-region-active-p)
8590 ;; we will sort the region
8591 (setq end (region-end)
8592 what "region")
8593 (goto-char (region-beginning))
8594 (unless (org-at-heading-p) (outline-next-heading))
8595 (setq start (point)))
8596 ((or (org-at-heading-p)
8597 (ignore-errors (progn (org-back-to-heading) t)))
8598 ;; we will sort the children of the current headline
8599 (org-back-to-heading)
8600 (setq start (point)
8601 end (progn (org-end-of-subtree t t)
8602 (or (bolp) (insert "\n"))
8603 (when (>= (org-back-over-empty-lines) 1)
8604 (forward-line 1))
8605 (point))
8606 what "children")
8607 (goto-char start)
8608 (outline-show-subtree)
8609 (outline-next-heading))
8611 ;; we will sort the top-level entries in this file
8612 (goto-char (point-min))
8613 (or (org-at-heading-p) (outline-next-heading))
8614 (setq start (point))
8615 (goto-char (point-max))
8616 (beginning-of-line 1)
8617 (when (looking-at ".*?\\S-")
8618 ;; File ends in a non-white line
8619 (end-of-line 1)
8620 (insert "\n"))
8621 (setq end (point-max))
8622 (setq what "top-level")
8623 (goto-char start)
8624 (outline-show-all)))
8626 (setq beg (point))
8627 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8629 (looking-at "\\(\\*+\\)")
8630 (setq stars (match-string 1)
8631 re (concat "^" (regexp-quote stars) " +")
8632 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8633 txt (buffer-substring beg end))
8634 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8635 (when (and (not (equal stars "*")) (string-match re2 txt))
8636 (user-error "Region to sort contains a level above the first entry"))
8638 (unless sorting-type
8639 (message
8640 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8641 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8642 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8643 what)
8644 (setq sorting-type (read-char-exclusive)))
8646 (unless getkey-func
8647 (and (= (downcase sorting-type) ?f)
8648 (setq getkey-func
8649 (or (and interactive?
8650 (org-read-function
8651 "Function for extracting keys: "))
8652 (error "Missing key extractor")))))
8654 (and (= (downcase sorting-type) ?r)
8655 (not property)
8656 (setq property
8657 (completing-read "Property: "
8658 (mapcar #'list (org-buffer-property-keys t))
8659 nil t)))
8661 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8662 (message "Sorting entries...")
8664 (save-restriction
8665 (narrow-to-region start end)
8666 (let ((restore-clock?
8667 ;; The clock marker is lost when using `sort-subr'; mark
8668 ;; the clock with temporary `:org-clock-marker-backup'
8669 ;; text property.
8670 (when (and (eq (org-clock-is-active) (current-buffer))
8671 (<= start (marker-position org-clock-marker))
8672 (>= end (marker-position org-clock-marker)))
8673 (org-with-silent-modifications
8674 (put-text-property (1- org-clock-marker) org-clock-marker
8675 :org-clock-marker-backup t))
8677 (dcst (downcase sorting-type))
8678 (case-fold-search nil)
8679 (now (current-time)))
8680 (org-preserve-local-variables
8681 (sort-subr
8682 (/= dcst sorting-type)
8683 ;; This function moves to the beginning character of the
8684 ;; "record" to be sorted.
8685 (lambda nil
8686 (if (re-search-forward re nil t)
8687 (goto-char (match-beginning 0))
8688 (goto-char (point-max))))
8689 ;; This function moves to the last character of the "record" being
8690 ;; sorted.
8691 (lambda nil
8692 (save-match-data
8693 (condition-case nil
8694 (outline-forward-same-level 1)
8695 (error
8696 (goto-char (point-max))))))
8697 ;; This function returns the value that gets sorted against.
8698 (lambda ()
8699 (cond
8700 ((= dcst ?n)
8701 (if (looking-at org-complex-heading-regexp)
8702 (string-to-number
8703 (org-sort-remove-invisible (match-string 4)))
8704 nil))
8705 ((= dcst ?a)
8706 (if (looking-at org-complex-heading-regexp)
8707 (funcall case-func
8708 (org-sort-remove-invisible (match-string 4)))
8709 nil))
8710 ((= dcst ?k)
8711 (or (get-text-property (point) :org-clock-minutes) 0))
8712 ((= dcst ?t)
8713 (let ((end (save-excursion (outline-next-heading) (point))))
8714 (if (or (re-search-forward org-ts-regexp end t)
8715 (re-search-forward org-ts-regexp-both end t))
8716 (org-time-string-to-seconds (match-string 0))
8717 (float-time now))))
8718 ((= dcst ?c)
8719 (let ((end (save-excursion (outline-next-heading) (point))))
8720 (if (re-search-forward
8721 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8722 end t)
8723 (org-time-string-to-seconds (match-string 0))
8724 (float-time now))))
8725 ((= dcst ?s)
8726 (let ((end (save-excursion (outline-next-heading) (point))))
8727 (if (re-search-forward org-scheduled-time-regexp end t)
8728 (org-time-string-to-seconds (match-string 1))
8729 (float-time now))))
8730 ((= dcst ?d)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (re-search-forward org-deadline-time-regexp end t)
8733 (org-time-string-to-seconds (match-string 1))
8734 (float-time now))))
8735 ((= dcst ?p)
8736 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8737 (string-to-char (match-string 2))
8738 org-default-priority))
8739 ((= dcst ?r)
8740 (or (org-entry-get nil property) ""))
8741 ((= dcst ?o)
8742 (when (looking-at org-complex-heading-regexp)
8743 (let* ((m (match-string 2))
8744 (s (if (member m org-done-keywords) '- '+)))
8745 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8746 ((= dcst ?f)
8747 (if getkey-func
8748 (progn
8749 (setq tmp (funcall getkey-func))
8750 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8751 tmp)
8752 (error "Invalid key function `%s'" getkey-func)))
8753 (t (error "Invalid sorting type `%c'" sorting-type))))
8755 (cond
8756 ((= dcst ?a) 'string<)
8757 ((= dcst ?f)
8758 (or compare-func
8759 (and interactive?
8760 (org-read-function
8761 (concat "Function for comparing keys "
8762 "(empty for default `sort-subr' predicate): ")
8763 'allow-empty))))
8764 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8765 (when restore-clock?
8766 (move-marker org-clock-marker
8767 (1+ (next-single-property-change
8768 start :org-clock-marker-backup)))
8769 (remove-text-properties (1- org-clock-marker) org-clock-marker
8770 '(:org-clock-marker-backup t)))))
8771 (run-hooks 'org-after-sorting-entries-or-items-hook)
8772 (message "Sorting entries...done")))
8774 (defun org-contextualize-keys (alist contexts)
8775 "Return valid elements in ALIST depending on CONTEXTS.
8777 `org-agenda-custom-commands' or `org-capture-templates' are the
8778 values used for ALIST, and `org-agenda-custom-commands-contexts'
8779 or `org-capture-templates-contexts' are the associated contexts
8780 definitions."
8781 (let ((contexts
8782 ;; normalize contexts
8783 (mapcar
8784 (lambda(c) (cond ((listp (cadr c))
8785 (list (car c) (car c) (nth 1 c)))
8786 ((string= "" (cadr c))
8787 (list (car c) (car c) (nth 2 c)))
8788 (t c)))
8789 contexts))
8790 (a alist) r s)
8791 ;; loop over all commands or templates
8792 (dolist (c a)
8793 (let (vrules repl)
8794 (cond
8795 ((not (assoc (car c) contexts))
8796 (push c r))
8797 ((and (assoc (car c) contexts)
8798 (setq vrules (org-contextualize-validate-key
8799 (car c) contexts)))
8800 (mapc (lambda (vr)
8801 (unless (equal (car vr) (cadr vr))
8802 (setq repl vr)))
8803 vrules)
8804 (if (not repl) (push c r)
8805 (push (cadr repl) s)
8806 (push
8807 (cons (car c)
8808 (cdr (or (assoc (cadr repl) alist)
8809 (error "Undefined key `%s' as contextual replacement for `%s'"
8810 (cadr repl) (car c)))))
8811 r))))))
8812 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8813 (delq
8815 (delete-dups
8816 (mapcar (lambda (x)
8817 (let ((tpl (car x)))
8818 (unless (delq
8820 (mapcar (lambda (y)
8821 (equal y tpl))
8823 x)))
8824 (reverse r))))))
8826 (defun org-contextualize-validate-key (key contexts)
8827 "Check CONTEXTS for agenda or capture KEY."
8828 (let (res)
8829 (dolist (r contexts)
8830 (dolist (rr (car (last r)))
8831 (when
8832 (and (equal key (car r))
8833 (if (functionp rr) (funcall rr)
8834 (or (and (eq (car rr) 'in-file)
8835 (buffer-file-name)
8836 (string-match (cdr rr) (buffer-file-name)))
8837 (and (eq (car rr) 'in-mode)
8838 (string-match (cdr rr) (symbol-name major-mode)))
8839 (and (eq (car rr) 'in-buffer)
8840 (string-match (cdr rr) (buffer-name)))
8841 (when (and (eq (car rr) 'not-in-file)
8842 (buffer-file-name))
8843 (not (string-match (cdr rr) (buffer-file-name))))
8844 (when (eq (car rr) 'not-in-mode)
8845 (not (string-match (cdr rr) (symbol-name major-mode))))
8846 (when (eq (car rr) 'not-in-buffer)
8847 (not (string-match (cdr rr) (buffer-name)))))))
8848 (push r res))))
8849 (delete-dups (delq nil res))))
8851 (defun org-context-p (&rest contexts)
8852 "Check if local context is any of CONTEXTS.
8853 Possible values in the list of contexts are `table', `headline', and `item'."
8854 (let ((pos (point)))
8855 (goto-char (point-at-bol))
8856 (prog1 (or (and (memq 'table contexts)
8857 (looking-at "[ \t]*|"))
8858 (and (memq 'headline contexts)
8859 (looking-at org-outline-regexp))
8860 (and (memq 'item contexts)
8861 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8862 (and (memq 'item-body contexts)
8863 (org-in-item-p)))
8864 (goto-char pos))))
8866 ;;;###autoload
8867 (defun org-run-like-in-org-mode (cmd)
8868 "Run a command, pretending that the current buffer is in Org mode.
8869 This will temporarily bind local variables that are typically bound in
8870 Org mode to the values they have in Org mode, and then interactively
8871 call CMD."
8872 (org-load-modules-maybe)
8873 (let (binds)
8874 (dolist (var (org-get-local-variables))
8875 (when (or (not (boundp (car var)))
8876 (eq (symbol-value (car var))
8877 (default-value (car var))))
8878 (push (list (car var) `(quote ,(cadr var))) binds)))
8879 (eval `(let ,binds
8880 (call-interactively (quote ,cmd))))))
8882 (defun org-get-category (&optional pos force-refresh)
8883 "Get the category applying to position POS."
8884 (save-match-data
8885 (when force-refresh (org-refresh-category-properties))
8886 (let ((pos (or pos (point))))
8887 (or (get-text-property pos 'org-category)
8888 (progn (org-refresh-category-properties)
8889 (get-text-property pos 'org-category))))))
8891 ;;; Refresh properties
8893 (defun org-refresh-properties (dprop tprop)
8894 "Refresh buffer text properties.
8895 DPROP is the drawer property and TPROP is either the
8896 corresponding text property to set, or an alist with each element
8897 being a text property (as a symbol) and a function to apply to
8898 the value of the drawer property."
8899 (let* ((case-fold-search t)
8900 (inhibit-read-only t)
8901 (inherit? (org-property-inherit-p dprop))
8902 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8903 (global (and inherit? (org--property-global-value dprop nil))))
8904 (org-with-silent-modifications
8905 (org-with-point-at 1
8906 ;; Set global values (e.g., values defined through
8907 ;; "#+PROPERTY:" keywords) to the whole buffer.
8908 (when global (put-text-property (point-min) (point-max) tprop global))
8909 ;; Set local values.
8910 (while (re-search-forward property-re nil t)
8911 (when (org-at-property-p)
8912 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8913 (outline-next-heading))))))
8915 (defun org-refresh-property (tprop p &optional inherit)
8916 "Refresh the buffer text property TPROP from the drawer property P.
8917 The refresh happens only for the current headline, or the whole
8918 sub-tree if optional argument INHERIT is non-nil."
8919 (unless (org-before-first-heading-p)
8920 (save-excursion
8921 (org-back-to-heading t)
8922 (let ((start (point))
8923 (end (save-excursion
8924 (if inherit (org-end-of-subtree t t)
8925 (or (outline-next-heading) (point-max))))))
8926 (if (symbolp tprop)
8927 ;; TPROP is a text property symbol.
8928 (put-text-property start end tprop p)
8929 ;; TPROP is an alist with (property . function) elements.
8930 (pcase-dolist (`(,prop . ,f) tprop)
8931 (put-text-property start end prop (funcall f p))))))))
8933 (defun org-refresh-category-properties ()
8934 "Refresh category text properties in the buffer."
8935 (let ((case-fold-search t)
8936 (inhibit-read-only t)
8937 (default-category
8938 (cond ((null org-category)
8939 (if buffer-file-name
8940 (file-name-sans-extension
8941 (file-name-nondirectory buffer-file-name))
8942 "???"))
8943 ((symbolp org-category) (symbol-name org-category))
8944 (t org-category))))
8945 (org-with-silent-modifications
8946 (org-with-wide-buffer
8947 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8948 ;; This is the default category for the buffer. If none is
8949 ;; found, fall-back to `org-category' or buffer file name.
8950 (put-text-property
8951 (point-min) (point-max)
8952 'org-category
8953 (catch 'buffer-category
8954 (goto-char (point-max))
8955 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8956 (let ((element (org-element-at-point)))
8957 (when (eq (org-element-type element) 'keyword)
8958 (throw 'buffer-category
8959 (org-element-property :value element)))))
8960 default-category))
8961 ;; Set sub-tree specific categories.
8962 (goto-char (point-min))
8963 (let ((regexp (org-re-property "CATEGORY")))
8964 (while (re-search-forward regexp nil t)
8965 (let ((value (match-string-no-properties 3)))
8966 (when (org-at-property-p)
8967 (put-text-property
8968 (save-excursion (org-back-to-heading t) (point))
8969 (save-excursion (org-end-of-subtree t t) (point))
8970 'org-category
8971 value)))))))))
8973 (defun org-refresh-stats-properties ()
8974 "Refresh stats text properties in the buffer."
8975 (org-with-silent-modifications
8976 (org-with-point-at 1
8977 (let ((regexp (concat org-outline-regexp-bol
8978 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
8979 (while (re-search-forward regexp nil t)
8980 (let* ((numerator (string-to-number (match-string 1)))
8981 (denominator (and (match-end 2)
8982 (string-to-number (match-string 2))))
8983 (stats (cond ((not denominator) numerator) ;percent
8984 ((= denominator 0) 0)
8985 (t (/ (* numerator 100) denominator)))))
8986 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
8987 'org-stats stats)))))))
8989 (defun org-refresh-effort-properties ()
8990 "Refresh effort properties"
8991 (org-refresh-properties
8992 org-effort-property
8993 '((effort . identity)
8994 (effort-minutes . org-duration-to-minutes))))
8996 ;;;; Link Stuff
8998 ;;; Link abbreviations
9000 (defun org-link-expand-abbrev (link)
9001 "Apply replacements as defined in `org-link-abbrev-alist'."
9002 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9003 (let* ((key (match-string 1 link))
9004 (as (or (assoc key org-link-abbrev-alist-local)
9005 (assoc key org-link-abbrev-alist)))
9006 (tag (and (match-end 2) (match-string 3 link)))
9007 rpl)
9008 (if (not as)
9009 link
9010 (setq rpl (cdr as))
9011 (cond
9012 ((symbolp rpl) (funcall rpl tag))
9013 ((string-match "%(\\([^)]+\\))" rpl)
9014 (replace-match
9015 (save-match-data
9016 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9017 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9018 ((string-match "%h" rpl)
9019 (replace-match (url-hexify-string (or tag "")) t t rpl))
9020 (t (concat rpl tag)))))
9021 link))
9023 ;;; Storing and inserting links
9025 (defvar org-insert-link-history nil
9026 "Minibuffer history for links inserted with `org-insert-link'.")
9028 (defvar org-stored-links nil
9029 "Contains the links stored with `org-store-link'.")
9031 (defvar org-store-link-plist nil
9032 "Plist with info about the most recently link created with `org-store-link'.")
9034 (defun org-store-link-functions ()
9035 "Return a list of functions that are called to create and store a link.
9036 The functions defined in the :store property of
9037 `org-link-parameters'.
9039 Each function will be called in turn until one returns a non-nil
9040 value. Each function should check if it is responsible for
9041 creating this link (for example by looking at the major mode).
9042 If not, it must exit and return nil. If yes, it should return
9043 a non-nil value after calling `org-store-link-props' with a list
9044 of properties and values. Special properties are:
9046 :type The link prefix, like \"http\". This must be given.
9047 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9048 This is obligatory as well.
9049 :description Optional default description for the second pair
9050 of brackets in an Org mode link. The user can still change
9051 this when inserting this link into an Org mode buffer.
9053 In addition to these, any additional properties can be specified
9054 and then used in capture templates."
9055 (cl-loop for link in org-link-parameters
9056 with store-func
9057 do (setq store-func (org-link-get-parameter (car link) :store))
9058 if store-func
9059 collect store-func))
9061 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9062 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9064 ;;;###autoload
9065 (defun org-store-link (arg)
9066 "Store an org-link to the current location.
9067 \\<org-mode-map>
9068 This link is added to `org-stored-links' and can later be inserted
9069 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9071 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9072 A single
9073 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9074 `org-gnus-prefer-web-links' for links to Usenet articles.
9076 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9077 skipping storing functions that are not
9078 part of Org core.
9080 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9081 prefix ARG forces storing a link for each line in the
9082 active region."
9083 (interactive "P")
9084 (org-load-modules-maybe)
9085 (if (and (equal arg '(64)) (org-region-active-p))
9086 (save-excursion
9087 (let ((end (region-end)))
9088 (goto-char (region-beginning))
9089 (set-mark (point))
9090 (while (< (point-at-eol) end)
9091 (move-end-of-line 1) (activate-mark)
9092 (let (current-prefix-arg)
9093 (call-interactively 'org-store-link))
9094 (move-beginning-of-line 2)
9095 (set-mark (point)))))
9096 (setq org-store-link-plist nil)
9097 (let (link cpltxt desc description search txt custom-id agenda-link)
9098 (cond
9099 ;; Store a link using an external link type, if any function is
9100 ;; available. If more than one can generate a link from current
9101 ;; location, ask which one to use.
9102 ((and (not (equal arg '(16)))
9103 (let ((results-alist nil))
9104 (dolist (f (org-store-link-functions))
9105 (when (funcall f)
9106 ;; XXX: return value is not link's plist, so we
9107 ;; store the new value before it is modified. It
9108 ;; would be cleaner to ask store link functions to
9109 ;; return the plist instead.
9110 (push (cons f (copy-sequence org-store-link-plist))
9111 results-alist)))
9112 (pcase results-alist
9113 (`nil nil)
9114 (`((,_ . ,_)) t) ;single choice: nothing to do
9115 (`((,name . ,_) . ,_)
9116 ;; Reinstate link plist associated to the chosen
9117 ;; function.
9118 (apply #'org-store-link-props
9119 (cdr (assoc-string
9120 (completing-read
9121 "Which function for creating the link? "
9122 (mapcar #'car results-alist) nil t name)
9123 results-alist)))
9124 t))))
9125 (setq link (plist-get org-store-link-plist :link))
9126 (setq desc (or (plist-get org-store-link-plist :description)
9127 link)))
9129 ;; Store a link from a source code buffer.
9130 ((org-src-edit-buffer-p)
9131 (let ((coderef-format (org-src-coderef-format)))
9132 (cond ((save-excursion
9133 (beginning-of-line)
9134 (looking-at (org-src-coderef-regexp coderef-format)))
9135 (setq link (format "(%s)" (match-string-no-properties 3))))
9136 ((called-interactively-p 'any)
9137 (let ((label (read-string "Code line label: ")))
9138 (end-of-line)
9139 (setq link (format coderef-format label))
9140 (let ((gc (- 79 (length link))))
9141 (if (< (current-column) gc)
9142 (org-move-to-column gc t)
9143 (insert " ")))
9144 (insert link)
9145 (setq link (concat "(" label ")"))
9146 (setq desc nil)))
9147 (t (setq link nil)))))
9149 ;; We are in the agenda, link to referenced location
9150 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9151 (let ((m (or (get-text-property (point) 'org-hd-marker)
9152 (get-text-property (point) 'org-marker))))
9153 (when m
9154 (org-with-point-at m
9155 (setq agenda-link
9156 (if (called-interactively-p 'any)
9157 (call-interactively 'org-store-link)
9158 (org-store-link nil)))))))
9160 ((eq major-mode 'calendar-mode)
9161 (let ((cd (calendar-cursor-to-date)))
9162 (setq link
9163 (format-time-string
9164 (car org-time-stamp-formats)
9165 (apply 'encode-time
9166 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9167 nil nil nil))))
9168 (org-store-link-props :type "calendar" :date cd)))
9170 ((eq major-mode 'help-mode)
9171 (setq link (concat "help:" (save-excursion
9172 (goto-char (point-min))
9173 (looking-at "^[^ ]+")
9174 (match-string 0))))
9175 (org-store-link-props :type "help"))
9177 ((eq major-mode 'w3-mode)
9178 (setq cpltxt (if (and (buffer-name)
9179 (not (string-match "Untitled" (buffer-name))))
9180 (buffer-name)
9181 (url-view-url t))
9182 link (url-view-url t))
9183 (org-store-link-props :type "w3" :url (url-view-url t)))
9185 ((eq major-mode 'image-mode)
9186 (setq cpltxt (concat "file:"
9187 (abbreviate-file-name buffer-file-name))
9188 link cpltxt)
9189 (org-store-link-props :type "image" :file buffer-file-name))
9191 ;; In dired, store a link to the file of the current line
9192 ((derived-mode-p 'dired-mode)
9193 (let ((file (dired-get-filename nil t)))
9194 (setq file (if file
9195 (abbreviate-file-name
9196 (expand-file-name (dired-get-filename nil t)))
9197 ;; otherwise, no file so use current directory.
9198 default-directory))
9199 (setq cpltxt (concat "file:" file)
9200 link cpltxt)))
9202 ((setq search (run-hook-with-args-until-success
9203 'org-create-file-search-functions))
9204 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9205 "::" search))
9206 (setq cpltxt (or description link)))
9208 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9209 (org-with-limited-levels
9210 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9211 (cond
9212 ;; Store a link using the target at point
9213 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9214 (setq cpltxt
9215 (concat "file:"
9216 (abbreviate-file-name
9217 (buffer-file-name (buffer-base-buffer)))
9218 "::" (match-string 1))
9219 link cpltxt))
9220 ((and (featurep 'org-id)
9221 (or (eq org-id-link-to-org-use-id t)
9222 (and (called-interactively-p 'any)
9223 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9224 (and (eq org-id-link-to-org-use-id
9225 'create-if-interactive-and-no-custom-id)
9226 (not custom-id))))
9227 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9228 ;; Store a link using the ID at point
9229 (setq link (condition-case nil
9230 (prog1 (org-id-store-link)
9231 (setq desc (or (plist-get org-store-link-plist
9232 :description)
9233 "")))
9234 (error
9235 ;; Probably before first headline, link only to file
9236 (concat "file:"
9237 (abbreviate-file-name
9238 (buffer-file-name (buffer-base-buffer))))))))
9240 ;; Just link to current headline
9241 (setq cpltxt (concat "file:"
9242 (abbreviate-file-name
9243 (buffer-file-name (buffer-base-buffer)))))
9244 ;; Add a context search string
9245 (when (org-xor org-context-in-file-links
9246 (equal arg '(4)))
9247 (let* ((element (org-element-at-point))
9248 (name (org-element-property :name element)))
9249 (setq txt (cond
9250 ((org-at-heading-p) nil)
9251 (name)
9252 ((org-region-active-p)
9253 (buffer-substring (region-beginning) (region-end)))))
9254 (when (or (null txt) (string-match "\\S-" txt))
9255 (setq cpltxt
9256 (concat cpltxt "::"
9257 (condition-case nil
9258 (org-make-org-heading-search-string txt)
9259 (error "")))
9260 desc (or name
9261 (nth 4 (ignore-errors (org-heading-components)))
9262 "NONE")))))
9263 (when (string-match "::\\'" cpltxt)
9264 (setq cpltxt (substring cpltxt 0 -2)))
9265 (setq link cpltxt)))))
9267 ((buffer-file-name (buffer-base-buffer))
9268 ;; Just link to this file here.
9269 (setq cpltxt (concat "file:"
9270 (abbreviate-file-name
9271 (buffer-file-name (buffer-base-buffer)))))
9272 ;; Add a context string.
9273 (when (org-xor org-context-in-file-links
9274 (equal arg '(4)))
9275 (setq txt (if (org-region-active-p)
9276 (buffer-substring (region-beginning) (region-end))
9277 (buffer-substring (point-at-bol) (point-at-eol))))
9278 ;; Only use search option if there is some text.
9279 (when (string-match "\\S-" txt)
9280 (setq cpltxt
9281 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9282 desc "NONE")))
9283 (setq link cpltxt))
9285 ((called-interactively-p 'interactive)
9286 (user-error "No method for storing a link from this buffer"))
9288 (t (setq link nil)))
9290 ;; We're done setting link and desc, clean up
9291 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9292 (setq link (or link cpltxt)
9293 desc (or desc cpltxt))
9294 (cond ((not desc))
9295 ((equal desc "NONE") (setq desc nil))
9296 (t (setq desc
9297 (replace-regexp-in-string
9298 org-bracket-link-analytic-regexp
9299 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9300 desc))))
9301 ;; Return the link
9302 (if (not (and (or (called-interactively-p 'any)
9303 executing-kbd-macro)
9304 link))
9305 (or agenda-link (and link (org-make-link-string link desc)))
9306 (push (list link desc) org-stored-links)
9307 (message "Stored: %s" (or desc link))
9308 (when custom-id
9309 (setq link (concat "file:" (abbreviate-file-name
9310 (buffer-file-name)) "::#" custom-id))
9311 (push (list link desc) org-stored-links))
9312 (car org-stored-links)))))
9314 (defun org-store-link-props (&rest plist)
9315 "Store link properties.
9316 The properties are pre-processed by extracting names, addresses
9317 and dates."
9318 (let ((x (plist-get plist :from)))
9319 (when x
9320 (let ((adr (mail-extract-address-components x)))
9321 (setq plist (plist-put plist :fromname (car adr)))
9322 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9323 (let ((x (plist-get plist :to)))
9324 (when x
9325 (let ((adr (mail-extract-address-components x)))
9326 (setq plist (plist-put plist :toname (car adr)))
9327 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9328 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9329 (when x
9330 (setq plist (plist-put plist :date-timestamp
9331 (format-time-string
9332 (org-time-stamp-format t) x)))
9333 (setq plist (plist-put plist :date-timestamp-inactive
9334 (format-time-string
9335 (org-time-stamp-format t t) x)))))
9336 (let ((from (plist-get plist :from))
9337 (to (plist-get plist :to)))
9338 (when (and from to org-from-is-user-regexp)
9339 (setq plist
9340 (plist-put plist :fromto
9341 (if (string-match org-from-is-user-regexp from)
9342 (concat "to %t")
9343 (concat "from %f"))))))
9344 (setq org-store-link-plist plist))
9346 (defun org-add-link-props (&rest plist)
9347 "Add these properties to the link property list."
9348 (let (key value)
9349 (while plist
9350 (setq key (pop plist) value (pop plist))
9351 (setq org-store-link-plist
9352 (plist-put org-store-link-plist key value)))))
9354 (defun org-email-link-description (&optional fmt)
9355 "Return the description part of an email link.
9356 This takes information from `org-store-link-plist' and formats it
9357 according to FMT (default from `org-email-link-description-format')."
9358 (setq fmt (or fmt org-email-link-description-format))
9359 (let* ((p org-store-link-plist)
9360 (to (plist-get p :toaddress))
9361 (from (plist-get p :fromaddress))
9362 (table
9363 (list
9364 (cons "%c" (plist-get p :fromto))
9365 (cons "%F" (plist-get p :from))
9366 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9367 (cons "%T" (plist-get p :to))
9368 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9369 (cons "%s" (plist-get p :subject))
9370 (cons "%d" (plist-get p :date))
9371 (cons "%m" (plist-get p :message-id)))))
9372 (when (string-match "%c" fmt)
9373 ;; Check if the user wrote this message
9374 (if (and org-from-is-user-regexp from to
9375 (save-match-data (string-match org-from-is-user-regexp from)))
9376 (setq fmt (replace-match "to %t" t t fmt))
9377 (setq fmt (replace-match "from %f" t t fmt))))
9378 (org-replace-escapes fmt table)))
9380 (defun org-make-org-heading-search-string (&optional string)
9381 "Make search string for the current headline or STRING."
9382 (let ((s (or string
9383 (and (derived-mode-p 'org-mode)
9384 (save-excursion
9385 (org-back-to-heading t)
9386 (org-element-property :raw-value (org-element-at-point))))))
9387 (lines org-context-in-file-links))
9388 (unless string (setq s (concat "*" s))) ;Add * for headlines
9389 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9390 (when (and string (integerp lines) (> lines 0))
9391 (let ((slines (org-split-string s "\n")))
9392 (when (< lines (length slines))
9393 (setq s (mapconcat
9394 'identity
9395 (reverse (nthcdr (- (length slines) lines)
9396 (reverse slines))) "\n")))))
9397 (mapconcat #'identity (split-string s) " ")))
9399 (defconst org-link-escape-chars
9400 ;;%20 %5B %5D %25
9401 '(?\s ?\[ ?\] ?%)
9402 "List of characters that should be escaped in a link when stored to Org.
9403 This is the list that is used for internal purposes.")
9405 (defun org-make-link-string (link &optional description)
9406 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9407 (unless (org-string-nw-p link) (error "Empty link"))
9408 (let ((uri (cond ((string-match org-link-types-re link)
9409 (concat (match-string 1 link)
9410 (org-link-escape (substring link (match-end 1)))))
9411 ((or (file-name-absolute-p link)
9412 (string-match-p "\\`\\.\\.?/" link))
9413 (org-link-escape link))
9414 ;; For readability, do not encode space characters
9415 ;; in fuzzy links.
9416 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9417 (description
9418 (and (org-string-nw-p description)
9419 ;; Remove brackets from description, as they are fatal.
9420 (replace-regexp-in-string
9421 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9422 (org-trim description)))))
9423 (format "[[%s]%s]"
9425 (if description (format "[%s]" description) ""))))
9427 (defun org-link-escape (text &optional table merge)
9428 "Return percent escaped representation of TEXT.
9429 TEXT is a string with the text to escape.
9430 Optional argument TABLE is a list with characters that should be
9431 escaped. When nil, `org-link-escape-chars' is used.
9432 If optional argument MERGE is set, merge TABLE into
9433 `org-link-escape-chars'."
9434 (let ((characters-to-encode
9435 (cond ((null table) org-link-escape-chars)
9436 (merge (append org-link-escape-chars table))
9437 (t table))))
9438 (mapconcat
9439 (lambda (c)
9440 (if (or (memq c characters-to-encode)
9441 (and org-url-hexify-p (or (< c 32) (> c 126))))
9442 (mapconcat (lambda (e) (format "%%%.2X" e))
9443 (or (encode-coding-char c 'utf-8)
9444 (error "Unable to percent escape character: %c" c))
9446 (char-to-string c)))
9447 text "")))
9449 (defun org-link-unescape (str)
9450 "Unhex hexified Unicode parts in string STR.
9451 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9452 reciprocal of `org-link-escape', which see."
9453 (if (org-string-nw-p str)
9454 (replace-regexp-in-string
9455 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9456 str))
9458 (defun org-link-unescape-compound (hex)
9459 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9460 Note: this function also decodes single byte encodings like
9461 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9462 (save-match-data
9463 (let* ((bytes (cdr (split-string hex "%")))
9464 (ret "")
9465 (eat 0)
9466 (sum 0))
9467 (while bytes
9468 (let* ((val (string-to-number (pop bytes) 16))
9469 (shift-xor
9470 (if (= 0 eat)
9471 (cond
9472 ((>= val 252) (cons 6 252))
9473 ((>= val 248) (cons 5 248))
9474 ((>= val 240) (cons 4 240))
9475 ((>= val 224) (cons 3 224))
9476 ((>= val 192) (cons 2 192))
9477 (t (cons 0 0)))
9478 (cons 6 128))))
9479 (when (>= val 192) (setq eat (car shift-xor)))
9480 (setq val (logxor val (cdr shift-xor)))
9481 (setq sum (+ (lsh sum (car shift-xor)) val))
9482 (when (> eat 0) (setq eat (- eat 1)))
9483 (cond
9484 ((= 0 eat) ;multi byte
9485 (setq ret (concat ret (char-to-string sum)))
9486 (setq sum 0))
9487 ((not bytes) ; single byte(s)
9488 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9489 ret)))
9491 (defun org-link-unescape-single-byte-sequence (hex)
9492 "Unhexify hex-encoded single byte character sequences."
9493 (mapconcat (lambda (byte)
9494 (char-to-string (string-to-number byte 16)))
9495 (cdr (split-string hex "%")) ""))
9497 (defun org-fixup-message-id-for-http (s)
9498 "Replace special characters in a message id, so it can be used in an http query."
9499 (when (string-match "%" s)
9500 (setq s (mapconcat (lambda (c)
9501 (if (eq c ?%)
9502 "%25"
9503 (char-to-string c)))
9504 s "")))
9505 (while (string-match "<" s)
9506 (setq s (replace-match "%3C" t t s)))
9507 (while (string-match ">" s)
9508 (setq s (replace-match "%3E" t t s)))
9509 (while (string-match "@" s)
9510 (setq s (replace-match "%40" t t s)))
9513 (defun org-link-prettify (link)
9514 "Return a human-readable representation of LINK.
9515 The car of LINK must be a raw link.
9516 The cdr of LINK must be either a link description or nil."
9517 (let ((desc (or (cadr link) "<no description>")))
9518 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9519 "<" (car link) ">")))
9521 ;;;###autoload
9522 (defun org-insert-link-global ()
9523 "Insert a link like Org mode does.
9524 This command can be called in any mode to insert a link in Org syntax."
9525 (interactive)
9526 (org-load-modules-maybe)
9527 (org-run-like-in-org-mode 'org-insert-link))
9529 (defun org-insert-all-links (arg &optional pre post)
9530 "Insert all links in `org-stored-links'.
9531 When a universal prefix, do not delete the links from `org-stored-links'.
9532 When `ARG' is a number, insert the last N link(s).
9533 `PRE' and `POST' are optional arguments to define a string to
9534 prepend or to append."
9535 (interactive "P")
9536 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9537 (links (copy-sequence org-stored-links))
9538 (pr (or pre "- "))
9539 (po (or post "\n"))
9540 (cnt 1) l)
9541 (if (null org-stored-links)
9542 (message "No link to insert")
9543 (while (and (or (listp arg) (>= arg cnt))
9544 (setq l (if (listp arg)
9545 (pop links)
9546 (pop org-stored-links))))
9547 (setq cnt (1+ cnt))
9548 (insert pr)
9549 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9550 (insert po)))))
9552 (defun org-insert-last-stored-link (arg)
9553 "Insert the last link stored in `org-stored-links'."
9554 (interactive "p")
9555 (org-insert-all-links arg "" "\n"))
9557 (defun org-link-fontify-links-to-this-file ()
9558 "Fontify links to the current file in `org-stored-links'."
9559 (let ((f (buffer-file-name)) a b)
9560 (setq a (mapcar (lambda(l)
9561 (let ((ll (car l)))
9562 (when (and (string-match "^file:\\(.+\\)::" ll)
9563 (equal f (expand-file-name (match-string 1 ll))))
9564 ll)))
9565 org-stored-links))
9566 (when (featurep 'org-id)
9567 (setq b (mapcar (lambda(l)
9568 (let ((ll (car l)))
9569 (when (and (string-match "^id:\\(.+\\)$" ll)
9570 (equal f (expand-file-name
9571 (or (org-id-find-id-file
9572 (match-string 1 ll)) ""))))
9573 ll)))
9574 org-stored-links)))
9575 (mapcar (lambda(l)
9576 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9577 (delq nil (append a b)))))
9579 (defvar org--links-history nil)
9580 (defun org-insert-link (&optional complete-file link-location default-description)
9581 "Insert a link. At the prompt, enter the link.
9583 Completion can be used to insert any of the link protocol prefixes in use.
9585 The history can be used to select a link previously stored with
9586 `org-store-link'. When the empty string is entered (i.e. if you just
9587 press `RET' at the prompt), the link defaults to the most recently
9588 stored link. As `SPC' triggers completion in the minibuffer, you need to
9589 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9591 You will also be prompted for a description, and if one is given, it will
9592 be displayed in the buffer instead of the link.
9594 If there is already a link at point, this command will allow you to edit
9595 link and description parts.
9597 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9598 file name can be
9599 selected using completion. The path to the file will be relative to the
9600 current directory if the file is in the current directory or a subdirectory.
9601 Otherwise, the link will be the absolute path as completed in the minibuffer
9602 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9603 option `org-link-file-path-type'.
9605 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9606 absolute path even if the file is in
9607 the current directory or below.
9609 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9610 prefix negates `org-keep-stored-link-after-insertion'.
9612 If the LINK-LOCATION parameter is non-nil, this value will be used as
9613 the link location instead of reading one interactively.
9615 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9616 be used as the default description. Otherwise, if
9617 `org-make-link-description-function' is non-nil, this function
9618 will be called with the link target, and the result will be the
9619 default link description. When called non-interactivily, don't
9620 allow to edit the default description."
9621 (interactive "P")
9622 (let* ((wcf (current-window-configuration))
9623 (origbuf (current-buffer))
9624 (region (when (org-region-active-p)
9625 (buffer-substring (region-beginning) (region-end))))
9626 (remove (and region (list (region-beginning) (region-end))))
9627 (desc region)
9628 (link link-location)
9629 (abbrevs org-link-abbrev-alist-local)
9630 entry all-prefixes auto-desc)
9631 (cond
9632 (link-location) ; specified by arg, just use it.
9633 ((org-in-regexp org-bracket-link-regexp 1)
9634 ;; We do have a link at point, and we are going to edit it.
9635 (setq remove (list (match-beginning 0) (match-end 0)))
9636 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9637 (setq link (read-string "Link: "
9638 (org-link-unescape
9639 (match-string-no-properties 1)))))
9640 ((or (org-in-regexp org-angle-link-re)
9641 (org-in-regexp org-plain-link-re))
9642 ;; Convert to bracket link
9643 (setq remove (list (match-beginning 0) (match-end 0))
9644 link (read-string "Link: "
9645 (org-unbracket-string "<" ">" (match-string 0)))))
9646 ((member complete-file '((4) (16)))
9647 ;; Completing read for file names.
9648 (setq link (org-file-complete-link complete-file)))
9650 ;; Read link, with completion for stored links.
9651 (org-link-fontify-links-to-this-file)
9652 (org-switch-to-buffer-other-window "*Org Links*")
9653 (with-current-buffer "*Org Links*"
9654 (erase-buffer)
9655 (insert "Insert a link.
9656 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9657 (when org-stored-links
9658 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9659 (insert (mapconcat 'org-link-prettify
9660 (reverse org-stored-links) "\n")))
9661 (goto-char (point-min)))
9662 (let ((cw (selected-window)))
9663 (select-window (get-buffer-window "*Org Links*" 'visible))
9664 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9665 (unless (pos-visible-in-window-p (point-max))
9666 (org-fit-window-to-buffer))
9667 (and (window-live-p cw) (select-window cw)))
9668 (setq all-prefixes (append (mapcar 'car abbrevs)
9669 (mapcar 'car org-link-abbrev-alist)
9670 (org-link-types)))
9671 (unwind-protect
9672 ;; Fake a link history, containing the stored links.
9673 (let ((org--links-history
9674 (append (mapcar #'car org-stored-links)
9675 org-insert-link-history)))
9676 (setq link
9677 (org-completing-read
9678 "Link: "
9679 (append
9680 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9681 (mapcar #'car org-stored-links))
9682 nil nil nil
9683 'org--links-history
9684 (caar org-stored-links)))
9685 (unless (org-string-nw-p link) (user-error "No link selected"))
9686 (dolist (l org-stored-links)
9687 (when (equal link (cadr l))
9688 (setq link (car l))
9689 (setq auto-desc t)))
9690 (when (or (member link all-prefixes)
9691 (and (equal ":" (substring link -1))
9692 (member (substring link 0 -1) all-prefixes)
9693 (setq link (substring link 0 -1))))
9694 (setq link (with-current-buffer origbuf
9695 (org-link-try-special-completion link)))))
9696 (set-window-configuration wcf)
9697 (kill-buffer "*Org Links*"))
9698 (setq entry (assoc link org-stored-links))
9699 (or entry (push link org-insert-link-history))
9700 (setq desc (or desc (nth 1 entry)))))
9702 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9703 (not org-keep-stored-link-after-insertion))
9704 (setq org-stored-links (delq (assoc link org-stored-links)
9705 org-stored-links)))
9707 (when (and (string-match org-plain-link-re link)
9708 (not (string-match org-ts-regexp link)))
9709 ;; URL-like link, normalize the use of angular brackets.
9710 (setq link (org-unbracket-string "<" ">" link)))
9712 ;; Check if we are linking to the current file with a search
9713 ;; option If yes, simplify the link by using only the search
9714 ;; option.
9715 (when (and buffer-file-name
9716 (let ((case-fold-search nil))
9717 (string-match "\\`file:\\(.+?\\)::" link)))
9718 (let ((path (match-string-no-properties 1 link))
9719 (search (substring-no-properties link (match-end 0))))
9720 (save-match-data
9721 (when (equal (file-truename buffer-file-name) (file-truename path))
9722 ;; We are linking to this same file, with a search option
9723 (setq link search)))))
9725 ;; Check if we can/should use a relative path. If yes, simplify
9726 ;; the link.
9727 (let ((case-fold-search nil))
9728 (when (string-match "\\`\\(file\\|docview\\):" link)
9729 (let* ((type (match-string-no-properties 0 link))
9730 (path-start (match-end 0))
9731 (search (and (string-match "::\\(.*\\)\\'" link)
9732 (match-string 1 link)))
9733 (path
9734 (if search
9735 (substring-no-properties
9736 link path-start (match-beginning 0))
9737 (substring-no-properties link (match-end 0))))
9738 (origpath path))
9739 (cond
9740 ((or (eq org-link-file-path-type 'absolute)
9741 (equal complete-file '(16)))
9742 (setq path (abbreviate-file-name (expand-file-name path))))
9743 ((eq org-link-file-path-type 'noabbrev)
9744 (setq path (expand-file-name path)))
9745 ((eq org-link-file-path-type 'relative)
9746 (setq path (file-relative-name path)))
9748 (save-match-data
9749 (if (string-match (concat "^" (regexp-quote
9750 (expand-file-name
9751 (file-name-as-directory
9752 default-directory))))
9753 (expand-file-name path))
9754 ;; We are linking a file with relative path name.
9755 (setq path (substring (expand-file-name path)
9756 (match-end 0)))
9757 (setq path (abbreviate-file-name (expand-file-name path)))))))
9758 (setq link (concat type path (and search (concat "::" search))))
9759 (when (equal desc origpath)
9760 (setq desc path)))))
9762 (unless auto-desc
9763 (let ((initial-input
9764 (cond
9765 (default-description)
9766 ((not org-make-link-description-function) desc)
9767 (t (condition-case nil
9768 (funcall org-make-link-description-function link desc)
9769 (error
9770 (message "Can't get link description from `%s'"
9771 (symbol-name org-make-link-description-function))
9772 (sit-for 2)
9773 nil))))))
9774 (setq desc (if (called-interactively-p 'any)
9775 (read-string "Description: " initial-input)
9776 initial-input))))
9778 (unless (string-match "\\S-" desc) (setq desc nil))
9779 (when remove (apply 'delete-region remove))
9780 (insert (org-make-link-string link desc))
9781 ;; Redisplay so as the new link has proper invisible characters.
9782 (sit-for 0)))
9784 (defun org-link-try-special-completion (type)
9785 "If there is completion support for link type TYPE, offer it."
9786 (let ((fun (org-link-get-parameter type :complete)))
9787 (if (functionp fun)
9788 (funcall fun)
9789 (read-string "Link (no completion support): " (concat type ":")))))
9791 (defun org-file-complete-link (&optional arg)
9792 "Create a file link using completion."
9793 (let ((file (read-file-name "File: "))
9794 (pwd (file-name-as-directory (expand-file-name ".")))
9795 (pwd1 (file-name-as-directory (abbreviate-file-name
9796 (expand-file-name ".")))))
9797 (cond ((equal arg '(16))
9798 (concat "file:"
9799 (abbreviate-file-name (expand-file-name file))))
9800 ((string-match
9801 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9802 (concat "file:" (match-string 1 file)))
9803 ((string-match
9804 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9805 (expand-file-name file))
9806 (concat "file:"
9807 (match-string 1 (expand-file-name file))))
9808 (t (concat "file:" file)))))
9811 ;;; Opening/following a link
9813 (defvar org-link-search-failed nil)
9815 (defvar org-open-link-functions nil
9816 "Hook for functions finding a plain text link.
9817 These functions must take a single argument, the link content.
9818 They will be called for links that look like [[link text][description]]
9819 when LINK TEXT does not have a protocol like \"http:\" and does not look
9820 like a filename (e.g. \"./blue.png\").
9822 These functions will be called *before* Org attempts to resolve the
9823 link by doing text searches in the current buffer - so if you want a
9824 link \"[[target]]\" to still find \"<<target>>\", your function should
9825 handle this as a special case.
9827 When the function does handle the link, it must return a non-nil value.
9828 If it decides that it is not responsible for this link, it must return
9829 nil to indicate that that Org can continue with other options like
9830 exact and fuzzy text search.")
9832 (defun org-next-link (&optional search-backward)
9833 "Move forward to the next link.
9834 If the link is in hidden text, expose it."
9835 (interactive "P")
9836 (when (and org-link-search-failed (eq this-command last-command))
9837 (goto-char (point-min))
9838 (message "Link search wrapped back to beginning of buffer"))
9839 (setq org-link-search-failed nil)
9840 (let* ((pos (point))
9841 (ct (org-context))
9842 (a (assq :link ct))
9843 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9844 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9845 ((looking-at org-any-link-re)
9846 ;; Don't stay stuck at link without an org-link face
9847 (forward-char (if search-backward -1 1))))
9848 (if (funcall srch-fun org-any-link-re nil t)
9849 (progn
9850 (goto-char (match-beginning 0))
9851 (when (org-invisible-p) (org-show-context)))
9852 (goto-char pos)
9853 (setq org-link-search-failed t)
9854 (message "No further link found"))))
9856 (defun org-previous-link ()
9857 "Move backward to the previous link.
9858 If the link is in hidden text, expose it."
9859 (interactive)
9860 (funcall 'org-next-link t))
9862 (defun org-translate-link (s)
9863 "Translate a link string if a translation function has been defined."
9864 (with-temp-buffer
9865 (insert (org-trim s))
9866 (org-trim (org-element-interpret-data (org-element-context)))))
9868 (defun org-translate-link-from-planner (type path)
9869 "Translate a link from Emacs Planner syntax so that Org can follow it.
9870 This is still an experimental function, your mileage may vary."
9871 (cond
9872 ((member type '("http" "https" "news" "ftp"))
9873 ;; standard Internet links are the same.
9874 nil)
9875 ((and (equal type "irc") (string-match "^//" path))
9876 ;; Planner has two / at the beginning of an irc link, we have 1.
9877 ;; We should have zero, actually....
9878 (setq path (substring path 1)))
9879 ((and (equal type "lisp") (string-match "^/" path))
9880 ;; Planner has a slash, we do not.
9881 (setq type "elisp" path (substring path 1)))
9882 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9883 ;; A typical message link. Planner has the id after the final slash,
9884 ;; we separate it with a hash mark
9885 (setq path (concat (match-string 1 path) "#"
9886 (org-unbracket-string "<" ">" (match-string 2 path))))))
9887 (cons type path))
9889 (defun org-find-file-at-mouse (ev)
9890 "Open file link or URL at mouse."
9891 (interactive "e")
9892 (mouse-set-point ev)
9893 (org-open-at-point 'in-emacs))
9895 (defun org-open-at-mouse (ev)
9896 "Open file link or URL at mouse.
9897 See the docstring of `org-open-file' for details."
9898 (interactive "e")
9899 (mouse-set-point ev)
9900 (when (eq major-mode 'org-agenda-mode)
9901 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9902 (org-open-at-point))
9904 (defvar org-window-config-before-follow-link nil
9905 "The window configuration before following a link.
9906 This is saved in case the need arises to restore it.")
9908 ;;;###autoload
9909 (defun org-open-at-point-global ()
9910 "Follow a link or time-stamp like Org mode does.
9911 This command can be called in any mode to follow an external link
9912 or a time-stamp that has Org mode syntax. Its behavior is
9913 undefined when called on internal links (e.g., fuzzy links).
9914 Raise an error when there is nothing to follow. "
9915 (interactive)
9916 (cond ((org-in-regexp org-any-link-re)
9917 (org-open-link-from-string (match-string-no-properties 0)))
9918 ((or (org-in-regexp org-ts-regexp-both nil t)
9919 (org-in-regexp org-tsr-regexp-both nil t))
9920 (org-follow-timestamp-link))
9921 (t (user-error "No link found"))))
9923 ;;;###autoload
9924 (defun org-open-link-from-string (s &optional arg reference-buffer)
9925 "Open a link in the string S, as if it was in Org mode."
9926 (interactive "sLink: \nP")
9927 (let ((reference-buffer (or reference-buffer (current-buffer))))
9928 (with-temp-buffer
9929 (let ((org-inhibit-startup (not reference-buffer)))
9930 (org-mode)
9931 (insert s)
9932 (goto-char (point-min))
9933 (when reference-buffer
9934 (setq org-link-abbrev-alist-local
9935 (with-current-buffer reference-buffer
9936 org-link-abbrev-alist-local)))
9937 (org-open-at-point arg reference-buffer)))))
9939 (defvar org-open-at-point-functions nil
9940 "Hook that is run when following a link at point.
9942 Functions in this hook must return t if they identify and follow
9943 a link at point. If they don't find anything interesting at point,
9944 they must return nil.")
9946 (defvar org-link-search-inhibit-query nil)
9947 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9948 (defun org--open-doi-link (path)
9949 "Open a \"doi\" type link.
9950 PATH is a the path to search for, as a string."
9951 (browse-url (url-encode-url (concat org-doi-server-url path))))
9953 (defun org--open-elisp-link (path)
9954 "Open a \"elisp\" type link.
9955 PATH is the sexp to evaluate, as a string."
9956 (let ((cmd path))
9957 (if (or (and (org-string-nw-p
9958 org-confirm-elisp-link-not-regexp)
9959 (string-match-p org-confirm-elisp-link-not-regexp cmd))
9960 (not org-confirm-elisp-link-function)
9961 (funcall org-confirm-elisp-link-function
9962 (format "Execute \"%s\" as elisp? "
9963 (org-add-props cmd nil 'face 'org-warning))))
9964 (message "%s => %s" cmd
9965 (if (eq (string-to-char cmd) ?\()
9966 (eval (read cmd))
9967 (call-interactively (read cmd))))
9968 (user-error "Abort"))))
9970 (defun org--open-help-link (path)
9971 "Open a \"help\" type link.
9972 PATH is a symbol name, as a string."
9973 (pcase (intern path)
9974 ((and (pred fboundp) variable) (describe-function variable))
9975 ((and (pred boundp) function) (describe-variable function))
9976 (name (user-error "Unknown function or variable: %s" name))))
9978 (defun org--open-shell-link (path)
9979 "Open a \"shell\" type link.
9980 PATH is the command to execute, as a string."
9981 (let ((buf (generate-new-buffer "*Org Shell Output*"))
9982 (cmd path))
9983 (if (or (and (org-string-nw-p
9984 org-confirm-shell-link-not-regexp)
9985 (string-match
9986 org-confirm-shell-link-not-regexp cmd))
9987 (not org-confirm-shell-link-function)
9988 (funcall org-confirm-shell-link-function
9989 (format "Execute \"%s\" in shell? "
9990 (org-add-props cmd nil
9991 'face 'org-warning))))
9992 (progn
9993 (message "Executing %s" cmd)
9994 (shell-command cmd buf)
9995 (when (featurep 'midnight)
9996 (setq clean-buffer-list-kill-buffer-names
9997 (cons (buffer-name buf)
9998 clean-buffer-list-kill-buffer-names))))
9999 (user-error "Abort"))))
10001 (defun org-open-at-point (&optional arg reference-buffer)
10002 "Open link, timestamp, footnote or tags at point.
10004 When point is on a link, follow it. Normally, files will be
10005 opened by an appropriate application. If the optional prefix
10006 argument ARG is non-nil, Emacs will visit the file. With
10007 a double prefix argument, try to open outside of Emacs, in the
10008 application the system uses for this file type.
10010 When point is on a timestamp, open the agenda at the day
10011 specified.
10013 When point is a footnote definition, move to the first reference
10014 found. If it is on a reference, move to the associated
10015 definition.
10017 When point is on a headline, display a list of every link in the
10018 entry, so it is possible to pick one, or all, of them. If point
10019 is on a tag, call `org-tags-view' instead.
10021 When optional argument REFERENCE-BUFFER is non-nil, it should
10022 specify a buffer from where the link search should happen. This
10023 is used internally by `org-open-link-from-string'.
10025 On top of syntactically correct links, this function will also
10026 try to open links and time-stamps in comments, example
10027 blocks... i.e., whenever point is on something looking like
10028 a timestamp or a link."
10029 (interactive "P")
10030 ;; On a code block, open block's results.
10031 (unless (call-interactively 'org-babel-open-src-block-result)
10032 (org-load-modules-maybe)
10033 (setq org-window-config-before-follow-link (current-window-configuration))
10034 (org-remove-occur-highlights nil nil t)
10035 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10036 (let* ((context
10037 ;; Only consider supported types, even if they are not
10038 ;; the closest one.
10039 (org-element-lineage
10040 (org-element-context)
10041 '(clock footnote-definition footnote-reference headline
10042 inlinetask link timestamp)
10044 (type (org-element-type context))
10045 (value (org-element-property :value context)))
10046 (cond
10047 ;; On a headline or an inlinetask, but not on a timestamp,
10048 ;; a link, a footnote reference.
10049 ((memq type '(headline inlinetask))
10050 (org-match-line org-complex-heading-regexp)
10051 (if (and (match-beginning 5)
10052 (>= (point) (match-beginning 5))
10053 (< (point) (match-end 5)))
10054 ;; On tags.
10055 (org-tags-view arg (substring (match-string 5) 0 -1))
10056 ;; Not on tags.
10057 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10058 (`(nil . ,_)
10059 (require 'org-attach)
10060 (org-attach-reveal 'if-exists))
10061 (`(,links . ,links-end)
10062 (dolist (link (if (stringp links) (list links) links))
10063 (search-forward link nil links-end)
10064 (goto-char (match-beginning 0))
10065 (org-open-at-point))))))
10066 ;; On a footnote reference or at definition's label.
10067 ((or (eq type 'footnote-reference)
10068 (and (eq type 'footnote-definition)
10069 (save-excursion
10070 ;; Do not validate action when point is on the
10071 ;; spaces right after the footnote label, in
10072 ;; order to be on par with behaviour on links.
10073 (skip-chars-forward " \t")
10074 (let ((begin
10075 (org-element-property :contents-begin context)))
10076 (if begin (< (point) begin)
10077 (= (org-element-property :post-affiliated context)
10078 (line-beginning-position)))))))
10079 (org-footnote-action))
10080 ;; No valid context. Ignore catch-all types like `headline'.
10081 ;; If point is on something looking like a link or
10082 ;; a time-stamp, try opening it. It may be useful in
10083 ;; comments, example blocks...
10084 ((memq type '(footnote-definition headline inlinetask nil))
10085 (call-interactively #'org-open-at-point-global))
10086 ;; On a clock line, make sure point is on the timestamp
10087 ;; before opening it.
10088 ((and (eq type 'clock)
10089 value
10090 (>= (point) (org-element-property :begin value))
10091 (<= (point) (org-element-property :end value)))
10092 (org-follow-timestamp-link))
10093 ;; Do nothing on white spaces after an object.
10094 ((>= (point)
10095 (save-excursion
10096 (goto-char (org-element-property :end context))
10097 (skip-chars-backward " \t")
10098 (point)))
10099 (user-error "No link found"))
10100 ((eq type 'timestamp) (org-follow-timestamp-link))
10101 ((eq type 'link)
10102 (let ((type (org-element-property :type context))
10103 (path (org-link-unescape (org-element-property :path context))))
10104 ;; Switch back to REFERENCE-BUFFER needed when called in
10105 ;; a temporary buffer through `org-open-link-from-string'.
10106 (with-current-buffer (or reference-buffer (current-buffer))
10107 (cond
10108 ((equal type "file")
10109 (if (string-match "[*?{]" (file-name-nondirectory path))
10110 (dired path)
10111 ;; Look into `org-link-parameters' in order to find
10112 ;; a DEDICATED-FUNCTION to open file. The function
10113 ;; will be applied on raw link instead of parsed
10114 ;; link due to the limitation in `org-add-link-type'
10115 ;; ("open" function called with a single argument).
10116 ;; If no such function is found, fallback to
10117 ;; `org-open-file'.
10118 (let* ((option (org-element-property :search-option context))
10119 (app (org-element-property :application context))
10120 (dedicated-function
10121 (org-link-get-parameter
10122 (if app (concat type "+" app) type)
10123 :follow)))
10124 (if dedicated-function
10125 (funcall dedicated-function
10126 (concat path
10127 (and option (concat "::" option))))
10128 (apply #'org-open-file
10129 path
10130 (cond (arg)
10131 ((equal app "emacs") 'emacs)
10132 ((equal app "sys") 'system))
10133 (cond ((not option) nil)
10134 ((string-match-p "\\`[0-9]+\\'" option)
10135 (list (string-to-number option)))
10136 (t (list nil
10137 (org-link-unescape option)))))))))
10138 ((functionp (org-link-get-parameter type :follow))
10139 (funcall (org-link-get-parameter type :follow) path))
10140 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10141 (unless (run-hook-with-args-until-success
10142 'org-open-link-functions path)
10143 (if (not arg) (org-mark-ring-push)
10144 (switch-to-buffer-other-window
10145 (org-get-buffer-for-internal-link (current-buffer))))
10146 (let ((destination
10147 (org-with-wide-buffer
10148 (if (equal type "radio")
10149 (org-search-radio-target
10150 (org-element-property :path context))
10151 (org-link-search
10152 (if (member type '("custom-id" "coderef"))
10153 (org-element-property :raw-link context)
10154 path)
10155 ;; Prevent fuzzy links from matching
10156 ;; themselves.
10157 (and (equal type "fuzzy")
10158 (+ 2 (org-element-property :begin context)))))
10159 (point))))
10160 (unless (and (<= (point-min) destination)
10161 (>= (point-max) destination))
10162 (widen))
10163 (goto-char destination))))
10164 (t (browse-url-at-point))))))
10165 (t (user-error "No link found")))))
10166 (run-hook-with-args 'org-follow-link-hook)))
10168 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10169 "Offer links in the current entry and return the selected link.
10170 If there is only one link, return it.
10171 If NTH is an integer, return the NTH link found.
10172 If ZERO is a string, check also this string for a link, and if
10173 there is one, return it."
10174 (with-current-buffer buffer
10175 (org-with-wide-buffer
10176 (goto-char marker)
10177 (let ((cnt ?0)
10178 have-zero end links link c)
10179 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10180 (push (match-string 0 zero) links)
10181 (setq cnt (1- cnt) have-zero t))
10182 (save-excursion
10183 (org-back-to-heading t)
10184 (setq end (save-excursion (outline-next-heading) (point)))
10185 (while (re-search-forward org-any-link-re end t)
10186 (push (match-string 0) links))
10187 (setq links (org-uniquify (reverse links))))
10188 (cond
10189 ((null links)
10190 (message "No links"))
10191 ((equal (length links) 1)
10192 (setq link (car links)))
10193 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10194 (setq link (nth (if have-zero nth (1- nth)) links)))
10195 (t ; we have to select a link
10196 (save-excursion
10197 (save-window-excursion
10198 (delete-other-windows)
10199 (with-output-to-temp-buffer "*Select Link*"
10200 (dolist (l links)
10201 (cond
10202 ((not (string-match org-bracket-link-regexp l))
10203 (princ (format "[%c] %s\n" (cl-incf cnt)
10204 (org-unbracket-string "<" ">" l))))
10205 ((match-end 3)
10206 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10207 (match-string 3 l) (match-string 1 l))))
10208 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10209 (match-string 1 l)))))))
10210 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10211 (message "Select link to open, RET to open all:")
10212 (setq c (read-char-exclusive))
10213 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10214 (when (equal c ?q) (user-error "Abort"))
10215 (if (equal c ?\C-m)
10216 (setq link links)
10217 (setq nth (- c ?0))
10218 (when have-zero (setq nth (1+ nth)))
10219 (unless (and (integerp nth) (>= (length links) nth))
10220 (user-error "Invalid link selection"))
10221 (setq link (nth (1- nth) links)))))
10222 (cons link end)))))
10224 ;; TODO: These functions are deprecated since `org-open-at-point'
10225 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10226 (defun org-open-file-with-system (path)
10227 "Open file at PATH using the system way of opening it."
10228 (org-open-file path 'system))
10229 (defun org-open-file-with-emacs (path)
10230 "Open file at PATH in Emacs."
10231 (org-open-file path 'emacs))
10234 ;;; File search
10236 (defvar org-create-file-search-functions nil
10237 "List of functions to construct the right search string for a file link.
10238 These functions are called in turn with point at the location to
10239 which the link should point.
10241 A function in the hook should first test if it would like to
10242 handle this file type, for example by checking the `major-mode'
10243 or the file extension. If it decides not to handle this file, it
10244 should just return nil to give other functions a chance. If it
10245 does handle the file, it must return the search string to be used
10246 when following the link. The search string will be part of the
10247 file link, given after a double colon, and `org-open-at-point'
10248 will automatically search for it. If special measures must be
10249 taken to make the search successful, another function should be
10250 added to the companion hook `org-execute-file-search-functions',
10251 which see.
10253 A function in this hook may also use `setq' to set the variable
10254 `description' to provide a suggestion for the descriptive text to
10255 be used for this link when it gets inserted into an Org buffer
10256 with \\[org-insert-link].")
10258 (defvar org-execute-file-search-functions nil
10259 "List of functions to execute a file search triggered by a link.
10261 Functions added to this hook must accept a single argument, the
10262 search string that was part of the file link, the part after the
10263 double colon. The function must first check if it would like to
10264 handle this search, for example by checking the `major-mode' or
10265 the file extension. If it decides not to handle this search, it
10266 should just return nil to give other functions a chance. If it
10267 does handle the search, it must return a non-nil value to keep
10268 other functions from trying.
10270 Each function can access the current prefix argument through the
10271 variable `current-prefix-arg'. Note that a single prefix is used
10272 to force opening a link in Emacs, so it may be good to only use a
10273 numeric or double prefix to guide the search function.
10275 In case this is needed, a function in this hook can also restore
10276 the window configuration before `org-open-at-point' was called using:
10278 (set-window-configuration org-window-config-before-follow-link)")
10280 (defun org-search-radio-target (target)
10281 "Search a radio target matching TARGET in current buffer.
10282 White spaces are not significant."
10283 (let ((re (format "<<<%s>>>"
10284 (mapconcat #'regexp-quote
10285 (split-string target)
10286 "[ \t]+\\(?:\n[ \t]*\\)?")))
10287 (origin (point)))
10288 (goto-char (point-min))
10289 (catch :radio-match
10290 (while (re-search-forward re nil t)
10291 (backward-char)
10292 (let ((object (org-element-context)))
10293 (when (eq (org-element-type object) 'radio-target)
10294 (goto-char (org-element-property :begin object))
10295 (org-show-context 'link-search)
10296 (throw :radio-match nil))))
10297 (goto-char origin)
10298 (user-error "No match for radio target: %s" target))))
10300 (defun org-link-search (s &optional avoid-pos stealth)
10301 "Search for a search string S.
10303 If S starts with \"#\", it triggers a custom ID search.
10305 If S is enclosed within parenthesis, it initiates a coderef
10306 search.
10308 If S is surrounded by forward slashes, it is interpreted as
10309 a regular expression. In Org mode files, this will create an
10310 `org-occur' sparse tree. In ordinary files, `occur' will be used
10311 to list matches. If the current buffer is in `dired-mode', grep
10312 will be used to search in all files.
10314 When AVOID-POS is given, ignore matches near that position.
10316 When optional argument STEALTH is non-nil, do not modify
10317 visibility around point, thus ignoring `org-show-context-detail'
10318 variable.
10320 Search is case-insensitive and ignores white spaces. Return type
10321 of matched result, which is either `dedicated' or `fuzzy'."
10322 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10323 (let* ((case-fold-search t)
10324 (origin (point))
10325 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10326 (starred (eq (string-to-char normalized) ?*))
10327 (words (split-string (if starred (substring s 1) s)))
10328 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10329 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10330 type)
10331 (cond
10332 ;; Check if there are any special search functions.
10333 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10334 ((eq (string-to-char s) ?#)
10335 ;; Look for a custom ID S if S starts with "#".
10336 (let* ((id (substring normalized 1))
10337 (match (org-find-property "CUSTOM_ID" id)))
10338 (if match (progn (goto-char match) (setf type 'dedicated))
10339 (error "No match for custom ID: %s" id))))
10340 ((string-match "\\`(\\(.*\\))\\'" normalized)
10341 ;; Look for coderef targets if S is enclosed within parenthesis.
10342 (let ((coderef (match-string-no-properties 1 normalized))
10343 (re (substring s-single-re 1 -1)))
10344 (goto-char (point-min))
10345 (catch :coderef-match
10346 (while (re-search-forward re nil t)
10347 (let ((element (org-element-at-point)))
10348 (when (and (memq (org-element-type element)
10349 '(example-block src-block))
10350 ;; Build proper regexp according to current
10351 ;; block's label format.
10352 (let ((label-fmt
10353 (regexp-quote
10354 (or (org-element-property :label-fmt element)
10355 org-coderef-label-format))))
10356 (save-excursion
10357 (beginning-of-line)
10358 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10359 (format label-fmt coderef))))))
10360 (setq type 'dedicated)
10361 (goto-char (match-beginning 1))
10362 (throw :coderef-match nil))))
10363 (goto-char origin)
10364 (error "No match for coderef: %s" coderef))))
10365 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10366 ;; Look for a regular expression.
10367 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10368 (match-string 1 s)))
10369 ;; From here, we handle fuzzy links.
10371 ;; Look for targets, only if not in a headline search.
10372 ((and (not starred)
10373 (let ((target (format "<<%s>>" s-multi-re)))
10374 (catch :target-match
10375 (goto-char (point-min))
10376 (while (re-search-forward target nil t)
10377 (backward-char)
10378 (let ((context (org-element-context)))
10379 (when (eq (org-element-type context) 'target)
10380 (setq type 'dedicated)
10381 (goto-char (org-element-property :begin context))
10382 (throw :target-match t))))
10383 nil))))
10384 ;; Look for elements named after S, only if not in a headline
10385 ;; search.
10386 ((and (not starred)
10387 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10388 (catch :name-match
10389 (goto-char (point-min))
10390 (while (re-search-forward name nil t)
10391 (let ((element (org-element-at-point)))
10392 (when (equal words
10393 (split-string
10394 (org-element-property :name element)))
10395 (setq type 'dedicated)
10396 (beginning-of-line)
10397 (throw :name-match t))))
10398 nil))))
10399 ;; Regular text search. Prefer headlines in Org mode buffers.
10400 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10401 ;; statistics cookies and tags.
10402 ((and (derived-mode-p 'org-mode)
10403 (let ((title-re
10404 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10405 org-outline-regexp-bol
10406 org-comment-string
10407 (mapconcat #'regexp-quote words ".+")))
10408 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10409 (comment-re (eval-when-compile
10410 (format "\\`%s[ \t]+" org-comment-string))))
10411 (goto-char (point-min))
10412 (catch :found
10413 (while (re-search-forward title-re nil t)
10414 (when (equal words
10415 (split-string
10416 (replace-regexp-in-string
10417 cookie-re ""
10418 (replace-regexp-in-string
10419 comment-re "" (org-get-heading t t t)))))
10420 (throw :found t)))
10421 nil)))
10422 (beginning-of-line)
10423 (setq type 'dedicated))
10424 ;; Offer to create non-existent headline depending on
10425 ;; `org-link-search-must-match-exact-headline'.
10426 ((and (derived-mode-p 'org-mode)
10427 (not org-link-search-inhibit-query)
10428 (eq org-link-search-must-match-exact-headline 'query-to-create)
10429 (yes-or-no-p "No match - create this as a new heading? "))
10430 (goto-char (point-max))
10431 (unless (bolp) (newline))
10432 (org-insert-heading nil t t)
10433 (insert s "\n")
10434 (beginning-of-line 0))
10435 ;; Only headlines are looked after. No need to process
10436 ;; further: throw an error.
10437 ((and (derived-mode-p 'org-mode)
10438 (or starred org-link-search-must-match-exact-headline))
10439 (goto-char origin)
10440 (error "No match for fuzzy expression: %s" normalized))
10441 ;; Regular text search.
10442 ((catch :fuzzy-match
10443 (goto-char (point-min))
10444 (while (re-search-forward s-multi-re nil t)
10445 ;; Skip match if it contains AVOID-POS or it is included in
10446 ;; a link with a description but outside the description.
10447 (unless (or (and avoid-pos
10448 (<= (match-beginning 0) avoid-pos)
10449 (> (match-end 0) avoid-pos))
10450 (and (save-match-data
10451 (org-in-regexp org-bracket-link-regexp))
10452 (match-beginning 3)
10453 (or (> (match-beginning 3) (point))
10454 (<= (match-end 3) (point)))
10455 (org-element-lineage
10456 (save-match-data (org-element-context))
10457 '(link) t)))
10458 (goto-char (match-beginning 0))
10459 (setq type 'fuzzy)
10460 (throw :fuzzy-match t)))
10461 nil))
10462 ;; All failed. Throw an error.
10463 (t (goto-char origin)
10464 (error "No match for fuzzy expression: %s" normalized)))
10465 ;; Disclose surroundings of match, if appropriate.
10466 (when (and (derived-mode-p 'org-mode) (not stealth))
10467 (org-show-context 'link-search))
10468 type))
10470 (defun org-get-buffer-for-internal-link (buffer)
10471 "Return a buffer to be used for displaying the link target of internal links."
10472 (cond
10473 ((not org-display-internal-link-with-indirect-buffer)
10474 buffer)
10475 ((string-suffix-p "(Clone)" (buffer-name buffer))
10476 (message "Buffer is already a clone, not making another one")
10477 ;; we also do not modify visibility in this case
10478 buffer)
10479 (t ; make a new indirect buffer for displaying the link
10480 (let* ((bn (buffer-name buffer))
10481 (ibn (concat bn "(Clone)"))
10482 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10483 (with-current-buffer ib (org-overview))
10484 ib))))
10486 (defun org-do-occur (regexp &optional cleanup)
10487 "Call the Emacs command `occur'.
10488 If CLEANUP is non-nil, remove the printout of the regular expression
10489 in the *Occur* buffer. This is useful if the regex is long and not useful
10490 to read."
10491 (occur regexp)
10492 (when cleanup
10493 (let ((cwin (selected-window)) win beg end)
10494 (when (setq win (get-buffer-window "*Occur*"))
10495 (select-window win))
10496 (goto-char (point-min))
10497 (when (re-search-forward "match[a-z]+" nil t)
10498 (setq beg (match-end 0))
10499 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10500 (setq end (1- (match-beginning 0)))))
10501 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10502 (goto-char (point-min))
10503 (select-window cwin))))
10505 ;;; The mark ring for links jumps
10507 (defvar org-mark-ring nil
10508 "Mark ring for positions before jumps in Org mode.")
10509 (defvar org-mark-ring-last-goto nil
10510 "Last position in the mark ring used to go back.")
10511 ;; Fill and close the ring
10512 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10513 (dotimes (_ org-mark-ring-length)
10514 (push (make-marker) org-mark-ring))
10515 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10516 org-mark-ring)
10518 (defun org-mark-ring-push (&optional pos buffer)
10519 "Put the current position or POS into the mark ring and rotate it."
10520 (interactive)
10521 (setq pos (or pos (point)))
10522 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10523 (move-marker (car org-mark-ring)
10524 (or pos (point))
10525 (or buffer (current-buffer)))
10526 (message "%s"
10527 (substitute-command-keys
10528 "Position saved to mark ring, go back with \
10529 `\\[org-mark-ring-goto]'.")))
10531 (defun org-mark-ring-goto (&optional n)
10532 "Jump to the previous position in the mark ring.
10533 With prefix arg N, jump back that many stored positions. When
10534 called several times in succession, walk through the entire ring.
10535 Org mode commands jumping to a different position in the current file,
10536 or to another Org file, automatically push the old position onto the ring."
10537 (interactive "p")
10538 (let (p m)
10539 (if (eq last-command this-command)
10540 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10541 (setq p org-mark-ring))
10542 (setq org-mark-ring-last-goto p)
10543 (setq m (car p))
10544 (pop-to-buffer-same-window (marker-buffer m))
10545 (goto-char m)
10546 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10548 (defun org-add-angle-brackets (s)
10549 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10550 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10553 ;;; Following specific links
10555 (defvar org-agenda-buffer-tmp-name)
10556 (defvar org-agenda-start-on-weekday)
10557 (defun org-follow-timestamp-link ()
10558 "Open an agenda view for the time-stamp date/range at point."
10559 (cond
10560 ((org-at-date-range-p t)
10561 (let ((org-agenda-start-on-weekday)
10562 (t1 (match-string 1))
10563 (t2 (match-string 2)) tt1 tt2)
10564 (setq tt1 (time-to-days (org-time-string-to-time t1))
10565 tt2 (time-to-days (org-time-string-to-time t2)))
10566 (let ((org-agenda-buffer-tmp-name
10567 (format "*Org Agenda(a:%s)"
10568 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10569 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10570 ((org-at-timestamp-p 'lax)
10571 (let ((org-agenda-buffer-tmp-name
10572 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10573 (org-agenda-list nil (time-to-days (org-time-string-to-time
10574 (substring (match-string 1) 0 10)))
10575 1)))
10576 (t (error "This should not happen"))))
10579 ;;; Following file links
10580 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10581 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10582 (declare-function mailcap-mime-info
10583 "mailcap" (string &optional request no-decode))
10584 (defvar org-wait nil)
10585 (defun org-open-file (path &optional in-emacs line search)
10586 "Open the file at PATH.
10587 First, this expands any special file name abbreviations. Then the
10588 configuration variable `org-file-apps' is checked if it contains an
10589 entry for this file type, and if yes, the corresponding command is launched.
10591 If no application is found, Emacs simply visits the file.
10593 With optional prefix argument IN-EMACS, Emacs will visit the file.
10594 With a double \\[universal-argument] \\[universal-argument] \
10595 prefix arg, Org tries to avoid opening in Emacs
10596 and to use an external application to visit the file.
10598 Optional LINE specifies a line to go to, optional SEARCH a string
10599 to search for. If LINE or SEARCH is given, the file will be
10600 opened in Emacs, unless an entry from org-file-apps that makes
10601 use of groups in a regexp matches.
10603 If you want to change the way frames are used when following a
10604 link, please customize `org-link-frame-setup'.
10606 If the file does not exist, an error is thrown."
10607 (let* ((file (if (equal path "")
10608 buffer-file-name
10609 (substitute-in-file-name (expand-file-name path))))
10610 (file-apps (append org-file-apps (org-default-apps)))
10611 (apps (cl-remove-if
10612 'org-file-apps-entry-match-against-dlink-p file-apps))
10613 (apps-dlink (cl-remove-if-not
10614 'org-file-apps-entry-match-against-dlink-p file-apps))
10615 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10616 (dirp (unless remp (file-directory-p file)))
10617 (file (if (and dirp org-open-directory-means-index-dot-org)
10618 (concat (file-name-as-directory file) "index.org")
10619 file))
10620 (a-m-a-p (assq 'auto-mode apps))
10621 (dfile (downcase file))
10622 ;; Reconstruct the original link from the PATH, LINE and
10623 ;; SEARCH args.
10624 (link (cond (line (concat file "::" (number-to-string line)))
10625 (search (concat file "::" search))
10626 (t file)))
10627 (dlink (downcase link))
10628 (ext
10629 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10630 (match-string 1 dfile)))
10631 (save-position-maybe
10632 (let ((old-buffer (current-buffer))
10633 (old-pos (point))
10634 (old-mode major-mode))
10635 (lambda ()
10636 (and (derived-mode-p 'org-mode)
10637 (eq old-mode 'org-mode)
10638 (or (not (eq old-buffer (current-buffer)))
10639 (not (eq old-pos (point))))
10640 (org-mark-ring-push old-pos old-buffer)))))
10641 cmd link-match-data)
10642 (cond
10643 ((member in-emacs '((16) system))
10644 (setq cmd (cdr (assq 'system apps))))
10645 (in-emacs (setq cmd 'emacs))
10647 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10648 (and dirp (cdr (assq 'directory apps)))
10649 ;; First, try matching against apps-dlink if we
10650 ;; get a match here, store the match data for
10651 ;; later.
10652 (let ((match (assoc-default dlink apps-dlink
10653 'string-match)))
10654 (if match
10655 (progn (setq link-match-data (match-data))
10656 match)
10657 (progn (setq in-emacs (or in-emacs line search))
10658 nil))) ; if we have no match in apps-dlink,
10659 ; always open the file in emacs if line or search
10660 ; is given (for backwards compatibility)
10661 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10662 'string-match)
10663 (cdr (assoc ext apps))
10664 (cdr (assq t apps))))))
10665 (when (eq cmd 'system)
10666 (setq cmd (cdr (assq 'system apps))))
10667 (when (eq cmd 'default)
10668 (setq cmd (cdr (assoc t apps))))
10669 (when (eq cmd 'mailcap)
10670 (require 'mailcap)
10671 (mailcap-parse-mailcaps)
10672 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10673 (command (mailcap-mime-info mime-type)))
10674 (if (stringp command)
10675 (setq cmd command)
10676 (setq cmd 'emacs))))
10677 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10678 (not (file-exists-p file))
10679 (not org-open-non-existing-files))
10680 (user-error "No such file: %s" file))
10681 (cond
10682 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10683 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10684 (while (string-match "['\"]%s['\"]" cmd)
10685 (setq cmd (replace-match "%s" t t cmd)))
10686 (setq cmd (replace-regexp-in-string
10687 "%s"
10688 (shell-quote-argument (convert-standard-filename file))
10690 nil t))
10692 ;; Replace "%1", "%2" etc. in command with group matches from regex
10693 (save-match-data
10694 (let ((match-index 1)
10695 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10696 (set-match-data link-match-data)
10697 (while (<= match-index number-of-groups)
10698 (let ((regex (concat "%" (number-to-string match-index)))
10699 (replace-with (match-string match-index dlink)))
10700 (while (string-match regex cmd)
10701 (setq cmd (replace-match replace-with t t cmd))))
10702 (setq match-index (+ match-index 1)))))
10704 (save-window-excursion
10705 (message "Running %s...done" cmd)
10706 (start-process-shell-command cmd nil cmd)
10707 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10708 ((or (stringp cmd)
10709 (eq cmd 'emacs))
10710 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10711 (widen)
10712 (cond (line (org-goto-line line)
10713 (when (derived-mode-p 'org-mode) (org-reveal)))
10714 (search (condition-case err
10715 (org-link-search search)
10716 ;; Save position before error-ing out so user
10717 ;; can easily move back to the original buffer.
10718 (error (funcall save-position-maybe)
10719 (error (nth 1 err)))))))
10720 ((functionp cmd)
10721 (save-match-data
10722 (set-match-data link-match-data)
10723 (condition-case nil
10724 (funcall cmd file link)
10725 ;; FIXME: Remove this check when most default installations
10726 ;; of Emacs have at least Org 9.0.
10727 ((debug wrong-number-of-arguments wrong-type-argument
10728 invalid-function)
10729 (user-error "Please see Org News for version 9.0 about \
10730 `org-file-apps'--Lisp error: %S" cmd)))))
10731 ((consp cmd)
10732 ;; FIXME: Remove this check when most default installations of
10733 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10734 ;; fall back to `org-link-frame-setup' for an old usage of
10735 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10736 (user-error "Please see Org News for version 9.0 about \
10737 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10738 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10739 (funcall save-position-maybe)))
10741 (defun org-file-apps-entry-match-against-dlink-p (entry)
10742 "This function returns non-nil if `entry' uses a regular
10743 expression which should be matched against the whole link by
10744 org-open-file.
10746 It assumes that is the case when the entry uses a regular
10747 expression which has at least one grouping construct and the
10748 action is either a lisp form or a command string containing
10749 `%1', i.e. using at least one subexpression match as a
10750 parameter."
10751 (let ((selector (car entry))
10752 (action (cdr entry)))
10753 (if (stringp selector)
10754 (and (> (regexp-opt-depth selector) 0)
10755 (or (and (stringp action)
10756 (string-match "%[0-9]" action))
10757 (consp action)))
10758 nil)))
10760 (defun org-default-apps ()
10761 "Return the default applications for this operating system."
10762 (cond
10763 ((eq system-type 'darwin)
10764 org-file-apps-defaults-macosx)
10765 ((eq system-type 'windows-nt)
10766 org-file-apps-defaults-windowsnt)
10767 (t org-file-apps-defaults-gnu)))
10769 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10770 "Convert extensions to regular expressions in the cars of LIST.
10771 Also, weed out any non-string entries, because the return value is used
10772 only for regexp matching.
10773 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10774 point to the symbol `emacs', indicating that the file should
10775 be opened in Emacs."
10776 (append
10777 (delq nil
10778 (mapcar (lambda (x)
10779 (unless (not (stringp (car x)))
10780 (if (string-match "\\W" (car x))
10782 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10783 list))
10784 (when add-auto-mode
10785 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10787 (defvar ange-ftp-name-format)
10788 (defun org-file-remote-p (file)
10789 "Test whether FILE specifies a location on a remote system.
10790 Return non-nil if the location is indeed remote.
10792 For example, the filename \"/user@host:/foo\" specifies a location
10793 on the system \"/user@host:\"."
10794 (cond ((fboundp 'file-remote-p)
10795 (file-remote-p file))
10796 ((fboundp 'tramp-handle-file-remote-p)
10797 (tramp-handle-file-remote-p file))
10798 ((and (boundp 'ange-ftp-name-format)
10799 (string-match (car ange-ftp-name-format) file))
10800 t)))
10803 ;;;; Refiling
10805 (defun org-get-org-file ()
10806 "Read a filename, with default directory `org-directory'."
10807 (let ((default (or org-default-notes-file remember-data-file)))
10808 (read-file-name (format "File name [%s]: " default)
10809 (file-name-as-directory org-directory)
10810 default)))
10812 (defun org-notes-order-reversed-p ()
10813 "Check if the current file should receive notes in reversed order."
10814 (cond
10815 ((not org-reverse-note-order) nil)
10816 ((eq t org-reverse-note-order) t)
10817 ((not (listp org-reverse-note-order)) nil)
10818 (t (catch 'exit
10819 (dolist (entry org-reverse-note-order)
10820 (when (string-match (car entry) buffer-file-name)
10821 (throw 'exit (cdr entry))))))))
10823 (defvar org-refile-target-table nil
10824 "The list of refile targets, created by `org-refile'.")
10826 (defvar org-agenda-new-buffers nil
10827 "Buffers created to visit agenda files.")
10829 (defvar org-refile-cache nil
10830 "Cache for refile targets.")
10832 (defvar org-refile-markers nil
10833 "All the markers used for caching refile locations.")
10835 (defun org-refile-marker (pos)
10836 "Get a new refile marker, but only if caching is in use."
10837 (if (not org-refile-use-cache)
10839 (let ((m (make-marker)))
10840 (move-marker m pos)
10841 (push m org-refile-markers)
10842 m)))
10844 (defun org-refile-cache-clear ()
10845 "Clear the refile cache and disable all the markers."
10846 (dolist (m org-refile-markers) (move-marker m nil))
10847 (setq org-refile-markers nil)
10848 (setq org-refile-cache nil)
10849 (message "Refile cache has been cleared"))
10851 (defun org-refile-cache-check-set (set)
10852 "Check if all the markers in the cache still have live buffers."
10853 (let (marker)
10854 (catch 'exit
10855 (while (and set (setq marker (nth 3 (pop set))))
10856 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10857 (when (and marker (null (marker-buffer marker)))
10858 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10859 (sit-for 3)
10860 (throw 'exit nil)))
10861 t)))
10863 (defun org-refile-cache-put (set &rest identifiers)
10864 "Push the refile targets SET into the cache, under IDENTIFIERS."
10865 (let* ((key (sha1 (prin1-to-string identifiers)))
10866 (entry (assoc key org-refile-cache)))
10867 (if entry
10868 (setcdr entry set)
10869 (push (cons key set) org-refile-cache))))
10871 (defun org-refile-cache-get (&rest identifiers)
10872 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10873 (cond
10874 ((not org-refile-cache) nil)
10875 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10877 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10878 org-refile-cache))))
10879 (and set (org-refile-cache-check-set set) set)))))
10881 (defvar org-outline-path-cache nil
10882 "Alist between buffer positions and outline paths.
10883 It value is an alist (POSITION . PATH) where POSITION is the
10884 buffer position at the beginning of an entry and PATH is a list
10885 of strings describing the outline path for that entry, in reverse
10886 order.")
10888 (defun org-refile-get-targets (&optional default-buffer)
10889 "Produce a table with refile targets."
10890 (let ((case-fold-search nil)
10891 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10892 (entries (or org-refile-targets '((nil . (:level . 1)))))
10893 targets tgs files desc descre)
10894 (message "Getting targets...")
10895 (with-current-buffer (or default-buffer (current-buffer))
10896 (dolist (entry entries)
10897 (setq files (car entry) desc (cdr entry))
10898 (cond
10899 ((null files) (setq files (list (current-buffer))))
10900 ((eq files 'org-agenda-files)
10901 (setq files (org-agenda-files 'unrestricted)))
10902 ((and (symbolp files) (fboundp files))
10903 (setq files (funcall files)))
10904 ((and (symbolp files) (boundp files))
10905 (setq files (symbol-value files))))
10906 (when (stringp files) (setq files (list files)))
10907 (cond
10908 ((eq (car desc) :tag)
10909 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10910 ((eq (car desc) :todo)
10911 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10912 ((eq (car desc) :regexp)
10913 (setq descre (cdr desc)))
10914 ((eq (car desc) :level)
10915 (setq descre (concat "^\\*\\{" (number-to-string
10916 (if org-odd-levels-only
10917 (1- (* 2 (cdr desc)))
10918 (cdr desc)))
10919 "\\}[ \t]")))
10920 ((eq (car desc) :maxlevel)
10921 (setq descre (concat "^\\*\\{1," (number-to-string
10922 (if org-odd-levels-only
10923 (1- (* 2 (cdr desc)))
10924 (cdr desc)))
10925 "\\}[ \t]")))
10926 (t (error "Bad refiling target description %s" desc)))
10927 (dolist (f files)
10928 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10930 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10931 (progn
10932 (when (bufferp f)
10933 (setq f (buffer-file-name (buffer-base-buffer f))))
10934 (setq f (and f (expand-file-name f)))
10935 (when (eq org-refile-use-outline-path 'file)
10936 (push (list (file-name-nondirectory f) f nil nil) tgs))
10937 (when (eq org-refile-use-outline-path 'buffer-name)
10938 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10939 (when (eq org-refile-use-outline-path 'full-file-path)
10940 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10941 (org-with-wide-buffer
10942 (goto-char (point-min))
10943 (setq org-outline-path-cache nil)
10944 (while (re-search-forward descre nil t)
10945 (beginning-of-line)
10946 (let ((case-fold-search nil))
10947 (looking-at org-complex-heading-regexp))
10948 (let ((begin (point))
10949 (heading (match-string-no-properties 4)))
10950 (unless (or (and
10951 org-refile-target-verify-function
10952 (not
10953 (funcall org-refile-target-verify-function)))
10954 (not heading))
10955 (let ((re (format org-complex-heading-regexp-format
10956 (regexp-quote heading)))
10957 (target
10958 (if (not org-refile-use-outline-path) heading
10959 (mapconcat
10960 #'identity
10961 (append
10962 (pcase org-refile-use-outline-path
10963 (`file (list (file-name-nondirectory
10964 (buffer-file-name
10965 (buffer-base-buffer)))))
10966 (`full-file-path
10967 (list (buffer-file-name
10968 (buffer-base-buffer))))
10969 (`buffer-name
10970 (list (buffer-name
10971 (buffer-base-buffer))))
10972 (_ nil))
10973 (mapcar (lambda (s) (replace-regexp-in-string
10974 "/" "\\/" s nil t))
10975 (org-get-outline-path t t)))
10976 "/"))))
10977 (push (list target f re (org-refile-marker (point)))
10978 tgs)))
10979 (when (= (point) begin)
10980 ;; Verification function has not moved point.
10981 (end-of-line)))))))
10982 (when org-refile-use-cache
10983 (org-refile-cache-put tgs (buffer-file-name) descre))
10984 (setq targets (append tgs targets))))))
10985 (message "Getting targets...done")
10986 (delete-dups (nreverse targets))))
10988 (defun org--get-outline-path-1 (&optional use-cache)
10989 "Return outline path to current headline.
10991 Outline path is a list of strings, in reverse order. When
10992 optional argument USE-CACHE is non-nil, make use of a cache. See
10993 `org-get-outline-path' for details.
10995 Assume buffer is widened and point is on a headline."
10996 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
10997 (let ((p (point))
10998 (heading (let ((case-fold-search nil))
10999 (looking-at org-complex-heading-regexp)
11000 (if (not (match-end 4)) ""
11001 ;; Remove statistics cookies.
11002 (org-trim
11003 (org-link-display-format
11004 (replace-regexp-in-string
11005 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11006 (match-string-no-properties 4))))))))
11007 (if (org-up-heading-safe)
11008 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11009 (when use-cache
11010 (push (cons p path) org-outline-path-cache))
11011 path)
11012 ;; This is a new root node. Since we assume we are moving
11013 ;; forward, we can drop previous cache so as to limit number
11014 ;; of associations there.
11015 (let ((path (list heading)))
11016 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11017 path)))))
11019 (defun org-get-outline-path (&optional with-self use-cache)
11020 "Return the outline path to the current entry.
11022 An outline path is a list of ancestors for current headline, as
11023 a list of strings. Statistics cookies are removed and links are
11024 replaced with their description, if any, or their path otherwise.
11026 When optional argument WITH-SELF is non-nil, the path also
11027 includes the current headline.
11029 When optional argument USE-CACHE is non-nil, cache outline paths
11030 between calls to this function so as to avoid backtracking. This
11031 argument is useful when planning to find more than one outline
11032 path in the same document. In that case, there are two
11033 conditions to satisfy:
11034 - `org-outline-path-cache' is set to nil before starting the
11035 process;
11036 - outline paths are computed by increasing buffer positions."
11037 (org-with-wide-buffer
11038 (and (or (and with-self (org-back-to-heading t))
11039 (org-up-heading-safe))
11040 (reverse (org--get-outline-path-1 use-cache)))))
11042 (defun org-format-outline-path (path &optional width prefix separator)
11043 "Format the outline path PATH for display.
11044 WIDTH is the maximum number of characters that is available.
11045 PREFIX is a prefix to be included in the returned string,
11046 such as the file name.
11047 SEPARATOR is inserted between the different parts of the path,
11048 the default is \"/\"."
11049 (setq width (or width 79))
11050 (setq path (delq nil path))
11051 (unless (> width 0)
11052 (user-error "Argument `width' must be positive"))
11053 (setq separator (or separator "/"))
11054 (let* ((org-odd-levels-only nil)
11055 (fpath (concat
11056 prefix (and prefix path separator)
11057 (mapconcat
11058 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11059 (cl-loop for head in path
11060 for n from 0
11061 collect (org-add-props
11062 head nil 'face
11063 (nth (% n org-n-level-faces) org-level-faces)))
11064 separator))))
11065 (when (> (length fpath) width)
11066 (if (< width 7)
11067 ;; It's unlikely that `width' will be this small, but don't
11068 ;; waste characters by adding ".." if it is.
11069 (setq fpath (substring fpath 0 width))
11070 (setf (substring fpath (- width 2)) "..")))
11071 fpath))
11073 (defun org-display-outline-path (&optional file current separator just-return-string)
11074 "Display the current outline path in the echo area.
11076 If FILE is non-nil, prepend the output with the file name.
11077 If CURRENT is non-nil, append the current heading to the output.
11078 SEPARATOR is passed through to `org-format-outline-path'. It separates
11079 the different parts of the path and defaults to \"/\".
11080 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11081 (interactive "P")
11082 (let* (case-fold-search
11083 (bfn (buffer-file-name (buffer-base-buffer)))
11084 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11085 res)
11086 (when current (setq path (append path
11087 (save-excursion
11088 (org-back-to-heading t)
11089 (when (looking-at org-complex-heading-regexp)
11090 (list (match-string 4)))))))
11091 (setq res
11092 (org-format-outline-path
11093 path
11094 (1- (frame-width))
11095 (and file bfn (concat (file-name-nondirectory bfn) separator))
11096 separator))
11097 (if just-return-string
11098 (org-no-properties res)
11099 (org-unlogged-message "%s" res))))
11101 (defvar org-refile-history nil
11102 "History for refiling operations.")
11104 (defvar org-after-refile-insert-hook nil
11105 "Hook run after `org-refile' has inserted its stuff at the new location.
11106 Note that this is still *before* the stuff will be removed from
11107 the *old* location.")
11109 (defvar org-capture-last-stored-marker)
11110 (defvar org-refile-keep nil
11111 "Non-nil means `org-refile' will copy instead of refile.")
11113 (defun org-copy ()
11114 "Like `org-refile', but copy."
11115 (interactive)
11116 (let ((org-refile-keep t))
11117 (funcall 'org-refile nil nil nil "Copy")))
11119 (defun org-refile (&optional arg default-buffer rfloc msg)
11120 "Move the entry or entries at point to another heading.
11122 The list of target headings is compiled using the information in
11123 `org-refile-targets', which see.
11125 At the target location, the entry is filed as a subitem of the
11126 target heading. Depending on `org-reverse-note-order', the new
11127 subitem will either be the first or the last subitem.
11129 If there is an active region, all entries in that region will be
11130 refiled. However, the region must fulfill the requirement that
11131 the first heading sets the top-level of the moved text.
11133 With a `\\[universal-argument]' ARG, the command will only visit the target \
11134 location
11135 and not actually move anything.
11137 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11138 location where the last
11139 refiling operation has put the subtree.
11141 With a numeric prefix argument of `2', refile to the running clock.
11143 With a numeric prefix argument of `3', emulate `org-refile-keep'
11144 being set to t and copy to the target location, don't move it.
11145 Beware that keeping refiled entries may result in duplicated ID
11146 properties.
11148 RFLOC can be a refile location obtained in a different way.
11150 MSG is a string to replace \"Refile\" in the default prompt with
11151 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11153 See also `org-refile-use-outline-path'.
11155 If you are using target caching (see `org-refile-use-cache'), you
11156 have to clear the target cache in order to find new targets.
11157 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11158 prefix argument (`C-u C-u C-u C-c C-w')."
11159 (interactive "P")
11160 (if (member arg '(0 (64)))
11161 (org-refile-cache-clear)
11162 (let* ((actionmsg (cond (msg msg)
11163 ((equal arg 3) "Refile (and keep)")
11164 (t "Refile")))
11165 (regionp (org-region-active-p))
11166 (region-start (and regionp (region-beginning)))
11167 (region-end (and regionp (region-end)))
11168 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11169 pos it nbuf file level reversed)
11170 (setq last-command nil)
11171 (when regionp
11172 (goto-char region-start)
11173 (or (bolp) (goto-char (point-at-bol)))
11174 (setq region-start (point))
11175 (unless (or (org-kill-is-subtree-p
11176 (buffer-substring region-start region-end))
11177 (prog1 org-refile-active-region-within-subtree
11178 (let ((s (point-at-eol)))
11179 (org-toggle-heading)
11180 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11181 (user-error "The region is not a (sequence of) subtree(s)")))
11182 (if (equal arg '(16))
11183 (org-refile-goto-last-stored)
11184 (when (or
11185 (and (equal arg 2)
11186 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11187 (prog1
11188 (setq it (list (or org-clock-heading "running clock")
11189 (buffer-file-name
11190 (marker-buffer org-clock-hd-marker))
11192 (marker-position org-clock-hd-marker)))
11193 (setq arg nil)))
11194 (setq it
11195 (or rfloc
11196 (let (heading-text)
11197 (save-excursion
11198 (unless (and arg (listp arg))
11199 (org-back-to-heading t)
11200 (setq heading-text
11201 (replace-regexp-in-string
11202 org-bracket-link-regexp
11203 "\\3"
11204 (or (nth 4 (org-heading-components))
11205 ""))))
11206 (org-refile-get-location
11207 (cond ((and arg (listp arg)) "Goto")
11208 (regionp (concat actionmsg " region to"))
11209 (t (concat actionmsg " subtree \""
11210 heading-text "\" to")))
11211 default-buffer
11212 (and (not (equal '(4) arg))
11213 org-refile-allow-creating-parent-nodes)))))))
11214 (setq file (nth 1 it)
11215 pos (nth 3 it))
11216 (when (and (not arg)
11218 (equal (buffer-file-name) file)
11219 (if regionp
11220 (and (>= pos region-start)
11221 (<= pos region-end))
11222 (and (>= pos (point))
11223 (< pos (save-excursion
11224 (org-end-of-subtree t t))))))
11225 (error "Cannot refile to position inside the tree or region"))
11226 (setq nbuf (or (find-buffer-visiting file)
11227 (find-file-noselect file)))
11228 (if (and arg (not (equal arg 3)))
11229 (progn
11230 (pop-to-buffer-same-window nbuf)
11231 (goto-char (cond (pos)
11232 ((org-notes-order-reversed-p) (point-min))
11233 (t (point-max))))
11234 (org-show-context 'org-goto))
11235 (if regionp
11236 (progn
11237 (org-kill-new (buffer-substring region-start region-end))
11238 (org-save-markers-in-region region-start region-end))
11239 (org-copy-subtree 1 nil t))
11240 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11241 (find-file-noselect file)))
11242 (setq reversed (org-notes-order-reversed-p))
11243 (org-with-wide-buffer
11244 (if pos
11245 (progn
11246 (goto-char pos)
11247 (setq level (org-get-valid-level (funcall outline-level) 1))
11248 (goto-char
11249 (if reversed
11250 (or (outline-next-heading) (point-max))
11251 (or (save-excursion (org-get-next-sibling))
11252 (org-end-of-subtree t t)
11253 (point-max)))))
11254 (setq level 1)
11255 (if (not reversed)
11256 (goto-char (point-max))
11257 (goto-char (point-min))
11258 (or (outline-next-heading) (goto-char (point-max)))))
11259 (unless (bolp) (newline))
11260 (org-paste-subtree level nil nil t)
11261 (when org-log-refile
11262 (org-add-log-setup 'refile nil nil org-log-refile)
11263 (unless (eq org-log-refile 'note)
11264 (save-excursion (org-add-log-note))))
11265 (and org-auto-align-tags
11266 (let ((org-loop-over-headlines-in-active-region nil))
11267 (org-set-tags nil t)))
11268 (let ((bookmark-name (plist-get org-bookmark-names-plist
11269 :last-refile)))
11270 (when bookmark-name
11271 (with-demoted-errors
11272 (bookmark-set bookmark-name))))
11273 ;; If we are refiling for capture, make sure that the
11274 ;; last-capture pointers point here
11275 (when (bound-and-true-p org-capture-is-refiling)
11276 (let ((bookmark-name (plist-get org-bookmark-names-plist
11277 :last-capture-marker)))
11278 (when bookmark-name
11279 (with-demoted-errors
11280 (bookmark-set bookmark-name))))
11281 (move-marker org-capture-last-stored-marker (point)))
11282 (when (fboundp 'deactivate-mark) (deactivate-mark))
11283 (run-hooks 'org-after-refile-insert-hook)))
11284 (unless org-refile-keep
11285 (if regionp
11286 (delete-region (point) (+ (point) (- region-end region-start)))
11287 (org-preserve-local-variables
11288 (delete-region
11289 (and (org-back-to-heading t) (point))
11290 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11291 (when (featurep 'org-inlinetask)
11292 (org-inlinetask-remove-END-maybe))
11293 (setq org-markers-to-move nil)
11294 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11296 (defun org-refile-goto-last-stored ()
11297 "Go to the location where the last refile was stored."
11298 (interactive)
11299 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11300 (message "This is the location of the last refile"))
11302 (defun org-refile--get-location (refloc tbl)
11303 "When user refile to REFLOC, find the associated target in TBL.
11304 Also check `org-refile-target-table'."
11305 (car (delq
11307 (mapcar
11308 (lambda (r) (or (assoc r tbl)
11309 (assoc r org-refile-target-table)))
11310 (list (replace-regexp-in-string "/$" "" refloc)
11311 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11313 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11314 "Prompt the user for a refile location, using PROMPT.
11315 PROMPT should not be suffixed with a colon and a space, because
11316 this function appends the default value from
11317 `org-refile-history' automatically, if that is not empty."
11318 (let ((org-refile-targets org-refile-targets)
11319 (org-refile-use-outline-path org-refile-use-outline-path))
11320 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11321 (unless org-refile-target-table
11322 (user-error "No refile targets"))
11323 (let* ((cbuf (current-buffer))
11324 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11325 (cfunc (if (and org-refile-use-outline-path
11326 org-outline-path-complete-in-steps)
11327 #'org-olpath-completing-read
11328 #'completing-read))
11329 (extra (if org-refile-use-outline-path "/" ""))
11330 (cbnex (concat (buffer-name) extra))
11331 (filename (and cfn (expand-file-name cfn)))
11332 (tbl (mapcar
11333 (lambda (x)
11334 (if (and (not (member org-refile-use-outline-path
11335 '(file full-file-path)))
11336 (not (equal filename (nth 1 x))))
11337 (cons (concat (car x) extra " ("
11338 (file-name-nondirectory (nth 1 x)) ")")
11339 (cdr x))
11340 (cons (concat (car x) extra) (cdr x))))
11341 org-refile-target-table))
11342 (completion-ignore-case t)
11343 cdef
11344 (prompt (concat prompt
11345 (or (and (car org-refile-history)
11346 (concat " (default " (car org-refile-history) ")"))
11347 (and (assoc cbnex tbl) (setq cdef cbnex)
11348 (concat " (default " cbnex ")"))) ": "))
11349 pa answ parent-target child parent old-hist)
11350 (setq old-hist org-refile-history)
11351 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11352 nil 'org-refile-history (or cdef (car org-refile-history))))
11353 (if (setq pa (org-refile--get-location answ tbl))
11354 (progn
11355 (org-refile-check-position pa)
11356 (when (or (not org-refile-history)
11357 (not (eq old-hist org-refile-history))
11358 (not (equal (car pa) (car org-refile-history))))
11359 (setq org-refile-history
11360 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11361 org-refile-history
11362 (cdr org-refile-history))))
11363 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11364 (pop org-refile-history)))
11366 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11367 (progn
11368 (setq parent (match-string 1 answ)
11369 child (match-string 2 answ))
11370 (setq parent-target (org-refile--get-location parent tbl))
11371 (when (and parent-target
11372 (or (eq new-nodes t)
11373 (and (eq new-nodes 'confirm)
11374 (y-or-n-p (format "Create new node \"%s\"? "
11375 child)))))
11376 (org-refile-new-child parent-target child)))
11377 (user-error "Invalid target location")))))
11379 (declare-function org-string-nw-p "org-macs" (s))
11380 (defun org-refile-check-position (refile-pointer)
11381 "Check if the refile pointer matches the headline to which it points."
11382 (let* ((file (nth 1 refile-pointer))
11383 (re (nth 2 refile-pointer))
11384 (pos (nth 3 refile-pointer))
11385 buffer)
11386 (if (and (not (markerp pos)) (not file))
11387 (user-error "Please indicate a target file in the refile path")
11388 (when (org-string-nw-p re)
11389 (setq buffer (if (markerp pos)
11390 (marker-buffer pos)
11391 (or (find-buffer-visiting file)
11392 (find-file-noselect file))))
11393 (with-current-buffer buffer
11394 (org-with-wide-buffer
11395 (goto-char pos)
11396 (beginning-of-line 1)
11397 (unless (looking-at-p re)
11398 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11400 (defun org-refile-new-child (parent-target child)
11401 "Use refile target PARENT-TARGET to add new CHILD below it."
11402 (unless parent-target
11403 (error "Cannot find parent for new node"))
11404 (let ((file (nth 1 parent-target))
11405 (pos (nth 3 parent-target))
11406 level)
11407 (with-current-buffer (or (find-buffer-visiting file)
11408 (find-file-noselect file))
11409 (org-with-wide-buffer
11410 (if pos
11411 (goto-char pos)
11412 (goto-char (point-max))
11413 (unless (bolp) (newline)))
11414 (when (looking-at org-outline-regexp)
11415 (setq level (funcall outline-level))
11416 (org-end-of-subtree t t))
11417 (org-back-over-empty-lines)
11418 (insert "\n" (make-string
11419 (if pos (org-get-valid-level level 1) 1) ?*)
11420 " " child "\n")
11421 (beginning-of-line 0)
11422 (list (concat (car parent-target) "/" child) file "" (point))))))
11424 (defun org-olpath-completing-read (prompt collection &rest args)
11425 "Read an outline path like a file name."
11426 (let ((thetable collection))
11427 (apply #'completing-read
11428 prompt
11429 (lambda (string predicate &optional flag)
11430 (cond
11431 ((eq flag nil) (try-completion string thetable))
11432 ((eq flag t)
11433 (let ((l (length string)))
11434 (mapcar (lambda (x)
11435 (let ((r (substring x l))
11436 (f (if (string-match " ([^)]*)$" x)
11437 (match-string 0 x)
11438 "")))
11439 (if (string-match "/" r)
11440 (concat string (substring r 0 (match-end 0)) f)
11441 x)))
11442 (all-completions string thetable predicate))))
11443 ;; Exact match?
11444 ((eq flag 'lambda) (assoc string thetable))))
11445 args)))
11447 ;;;; Dynamic blocks
11449 (defun org-find-dblock (name)
11450 "Find the first dynamic block with name NAME in the buffer.
11451 If not found, stay at current position and return nil."
11452 (let ((case-fold-search t) pos)
11453 (save-excursion
11454 (goto-char (point-min))
11455 (setq pos (and (re-search-forward
11456 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11457 (match-beginning 0))))
11458 (when pos (goto-char pos))
11459 pos))
11461 (defun org-create-dblock (plist)
11462 "Create a dynamic block section, with parameters taken from PLIST.
11463 PLIST must contain a :name entry which is used as the name of the block."
11464 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11465 (end-of-line 1)
11466 (newline))
11467 (let ((col (current-column))
11468 (name (plist-get plist :name)))
11469 (insert "#+BEGIN: " name)
11470 (while plist
11471 (if (eq (car plist) :name)
11472 (setq plist (cddr plist))
11473 (insert " " (prin1-to-string (pop plist)))))
11474 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11475 (beginning-of-line -2)))
11477 (defun org-prepare-dblock ()
11478 "Prepare dynamic block for refresh.
11479 This empties the block, puts the cursor at the insert position and returns
11480 the property list including an extra property :name with the block name."
11481 (unless (looking-at org-dblock-start-re)
11482 (user-error "Not at a dynamic block"))
11483 (let* ((begdel (1+ (match-end 0)))
11484 (name (org-no-properties (match-string 1)))
11485 (params (append (list :name name)
11486 (read (concat "(" (match-string 3) ")")))))
11487 (save-excursion
11488 (beginning-of-line 1)
11489 (skip-chars-forward " \t")
11490 (setq params (plist-put params :indentation-column (current-column))))
11491 (unless (re-search-forward org-dblock-end-re nil t)
11492 (error "Dynamic block not terminated"))
11493 (setq params
11494 (append params
11495 (list :content (buffer-substring
11496 begdel (match-beginning 0)))))
11497 (delete-region begdel (match-beginning 0))
11498 (goto-char begdel)
11499 (open-line 1)
11500 params))
11502 (defun org-map-dblocks (&optional command)
11503 "Apply COMMAND to all dynamic blocks in the current buffer.
11504 If COMMAND is not given, use `org-update-dblock'."
11505 (let ((cmd (or command 'org-update-dblock)))
11506 (save-excursion
11507 (goto-char (point-min))
11508 (while (re-search-forward org-dblock-start-re nil t)
11509 (goto-char (match-beginning 0))
11510 (save-excursion
11511 (condition-case nil
11512 (funcall cmd)
11513 (error (message "Error during update of dynamic block"))))
11514 (unless (re-search-forward org-dblock-end-re nil t)
11515 (error "Dynamic block not terminated"))))))
11517 (defun org-dblock-update (&optional arg)
11518 "User command for updating dynamic blocks.
11519 Update the dynamic block at point. With prefix ARG, update all dynamic
11520 blocks in the buffer."
11521 (interactive "P")
11522 (if arg
11523 (org-update-all-dblocks)
11524 (or (looking-at org-dblock-start-re)
11525 (org-beginning-of-dblock))
11526 (org-update-dblock)))
11528 (defun org-update-dblock ()
11529 "Update the dynamic block at point.
11530 This means to empty the block, parse for parameters and then call
11531 the correct writing function."
11532 (interactive)
11533 (save-excursion
11534 (let* ((win (selected-window))
11535 (pos (point))
11536 (line (org-current-line))
11537 (params (org-prepare-dblock))
11538 (name (plist-get params :name))
11539 (indent (plist-get params :indentation-column))
11540 (cmd (intern (concat "org-dblock-write:" name))))
11541 (message "Updating dynamic block `%s' at line %d..." name line)
11542 (funcall cmd params)
11543 (message "Updating dynamic block `%s' at line %d...done" name line)
11544 (goto-char pos)
11545 (when (and indent (> indent 0))
11546 (setq indent (make-string indent ?\ ))
11547 (save-excursion
11548 (select-window win)
11549 (org-beginning-of-dblock)
11550 (forward-line 1)
11551 (while (not (looking-at org-dblock-end-re))
11552 (insert indent)
11553 (beginning-of-line 2))
11554 (when (looking-at org-dblock-end-re)
11555 (and (looking-at "[ \t]+")
11556 (replace-match ""))
11557 (insert indent)))))))
11559 (defun org-beginning-of-dblock ()
11560 "Find the beginning of the dynamic block at point.
11561 Error if there is no such block at point."
11562 (let ((pos (point))
11563 beg)
11564 (end-of-line 1)
11565 (if (and (re-search-backward org-dblock-start-re nil t)
11566 (setq beg (match-beginning 0))
11567 (re-search-forward org-dblock-end-re nil t)
11568 (> (match-end 0) pos))
11569 (goto-char beg)
11570 (goto-char pos)
11571 (error "Not in a dynamic block"))))
11573 (defun org-update-all-dblocks ()
11574 "Update all dynamic blocks in the buffer.
11575 This function can be used in a hook."
11576 (interactive)
11577 (when (derived-mode-p 'org-mode)
11578 (org-map-dblocks 'org-update-dblock)))
11581 ;;;; Completion
11583 (declare-function org-export-backend-options "ox" (cl-x) t)
11584 (defun org-get-export-keywords ()
11585 "Return a list of all currently understood export keywords.
11586 Export keywords include options, block names, attributes and
11587 keywords relative to each registered export back-end."
11588 (let (keywords)
11589 (dolist (backend
11590 (bound-and-true-p org-export-registered-backends)
11591 (delq nil keywords))
11592 ;; Back-end name (for keywords, like #+LATEX:)
11593 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11594 (dolist (option-entry (org-export-backend-options backend))
11595 ;; Back-end options.
11596 (push (nth 1 option-entry) keywords)))))
11598 (defconst org-options-keywords
11599 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11600 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11601 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11602 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11603 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11605 (defcustom org-structure-template-alist
11606 '((?a . "export ascii")
11607 (?c . "center")
11608 (?C . "comment")
11609 (?e . "example")
11610 (?E . "export")
11611 (?h . "export html")
11612 (?l . "export latex")
11613 (?q . "quote")
11614 (?s . "src")
11615 (?v . "verse"))
11616 "Structure completion elements.
11617 This is an alist of characters and values. When
11618 `org-insert-structure-template' is called, an additional key is
11619 read. The key is first looked up in this alist, and the
11620 corresponding structure is inserted, with \"#+BEGIN_\" and
11621 \"#+END_\" added automatically."
11622 :group 'org-edit-structure
11623 :type '(repeat
11624 (cons (character :tag "Key")
11625 (string :tag "Template")))
11626 :package-version '(Org . "9.2"))
11628 (defun org-insert-structure-template (type)
11629 "Insert a block structure of the type #+begin_foo/#+end_foo.
11630 First read a character, which can be one of the keys in
11631 `org-structure-template-alist'. When it is <TAB>, prompt the
11632 user for a string to use. With an active region, wrap the region
11633 in the block. Otherwise, insert an empty block."
11634 (interactive
11635 (list
11636 (let* ((key (read-key "Key: "))
11637 (struct-string
11638 (or (cdr (assq key org-structure-template-alist))
11639 (and (= key ?\t)
11640 (read-string "Structure type: "))
11641 (user-error "`%c' has no structure definition" key))))
11642 struct-string)))
11643 (let* ((region? (use-region-p))
11644 (s (if region? (region-beginning) (point)))
11645 (e (copy-marker (if region? (region-end) (point)) t))
11646 column)
11647 (when (string-match-p
11648 (concat "\\`" (regexp-opt '("example" "export" "src")))
11649 type)
11650 (org-escape-code-in-region s e))
11651 (goto-char s)
11652 (setq column (current-indentation))
11653 (beginning-of-line)
11654 (indent-to column)
11655 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11656 (goto-char e)
11657 (if (bolp)
11658 (progn
11659 (skip-chars-backward " \n\t")
11660 (forward-line))
11661 (end-of-line)
11662 (insert "\n"))
11663 (indent-to column)
11664 (insert (format "#+end_%s\n"
11665 (car (split-string type))))
11666 (when (or (not region?)
11667 (string-match-p "src\\|\\`export\\'" type))
11668 (goto-char s)
11669 (end-of-line))
11670 (set-marker e nil)))
11672 ;;;; TODO, DEADLINE, Comments
11674 (defun org-toggle-comment ()
11675 "Change the COMMENT state of an entry."
11676 (interactive)
11677 (save-excursion
11678 (org-back-to-heading)
11679 (let ((case-fold-search nil))
11680 (looking-at org-complex-heading-regexp))
11681 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11682 (skip-chars-forward " \t")
11683 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11684 (if (org-in-commented-heading-p t)
11685 (delete-region (point)
11686 (progn (search-forward " " (line-end-position) 'move)
11687 (skip-chars-forward " \t")
11688 (point)))
11689 (insert org-comment-string)
11690 (unless (eolp) (insert " ")))))
11692 (defvar org-last-todo-state-is-todo nil
11693 "This is non-nil when the last TODO state change led to a TODO state.
11694 If the last change removed the TODO tag or switched to DONE, then
11695 this is nil.")
11697 (defvar org-setting-tags nil) ; dynamically skipped
11699 (defvar org-todo-setup-filter-hook nil
11700 "Hook for functions that pre-filter todo specs.
11701 Each function takes a todo spec and returns either nil or the spec
11702 transformed into canonical form." )
11704 (defvar org-todo-get-default-hook nil
11705 "Hook for functions that get a default item for todo.
11706 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11707 nil or a string to be used for the todo mark." )
11709 (defvar org-agenda-headline-snapshot-before-repeat)
11711 (defun org-current-effective-time ()
11712 "Return current time adjusted for `org-extend-today-until' variable."
11713 (let* ((ct (org-current-time))
11714 (dct (decode-time ct))
11715 (ct1
11716 (cond
11717 (org-use-last-clock-out-time-as-effective-time
11718 (or (org-clock-get-last-clock-out-time) ct))
11719 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11720 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11721 (t ct))))
11722 ct1))
11724 (defun org-todo-yesterday (&optional arg)
11725 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11726 (interactive "P")
11727 (if (eq major-mode 'org-agenda-mode)
11728 (apply 'org-agenda-todo-yesterday arg)
11729 (let* ((org-use-effective-time t)
11730 (hour (nth 2 (decode-time (org-current-time))))
11731 (org-extend-today-until (1+ hour)))
11732 (org-todo arg))))
11734 (defvar org-block-entry-blocking ""
11735 "First entry preventing the TODO state change.")
11737 (defun org-cancel-repeater ()
11738 "Cancel a repeater by setting its numeric value to zero."
11739 (interactive)
11740 (save-excursion
11741 (org-back-to-heading t)
11742 (let ((bound1 (point))
11743 (bound0 (save-excursion (outline-next-heading) (point))))
11744 (when (and (re-search-forward
11745 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11746 org-deadline-time-regexp "\\)\\|\\("
11747 org-ts-regexp "\\)")
11748 bound0 t)
11749 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11750 bound1 t))
11751 (replace-match "0" t nil nil 1)))))
11753 (defvar org-state)
11754 (defvar org-blocked-by-checkboxes)
11755 (defun org-todo (&optional arg)
11756 "Change the TODO state of an item.
11758 The state of an item is given by a keyword at the start of the heading,
11759 like
11760 *** TODO Write paper
11761 *** DONE Call mom
11763 The different keywords are specified in the variable `org-todo-keywords'.
11764 By default the available states are \"TODO\" and \"DONE\". So, for this
11765 example: when the item starts with TODO, it is changed to DONE.
11766 When it starts with DONE, the DONE is removed. And when neither TODO nor
11767 DONE are present, add TODO at the beginning of the heading.
11769 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11770 state.
11771 With numeric prefix ARG, switch to that state.
11772 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11773 next set of TODO \
11774 keywords (nextset).
11775 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11776 prefix, circumvent any state blocking.
11777 With a numeric prefix arg of 0, inhibit note taking for the change.
11778 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11780 When called through ELisp, arg is also interpreted in the following way:
11781 `none' -> empty state
11782 \"\" -> switch to empty state
11783 `done' -> switch to DONE
11784 `nextset' -> switch to the next set of keywords
11785 `previousset' -> switch to the previous set of keywords
11786 \"WAITING\" -> switch to the specified keyword, but only if it
11787 really is a member of `org-todo-keywords'."
11788 (interactive "P")
11789 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11790 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11791 'region-start-level 'region))
11792 org-loop-over-headlines-in-active-region)
11793 (org-map-entries
11794 `(org-todo ,arg)
11795 org-loop-over-headlines-in-active-region
11796 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11797 (when (equal arg '(16)) (setq arg 'nextset))
11798 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11799 (let ((org-blocker-hook org-blocker-hook)
11800 commentp
11801 case-fold-search)
11802 (when (equal arg '(64))
11803 (setq arg nil org-blocker-hook nil))
11804 (when (and org-blocker-hook
11805 (or org-inhibit-blocking
11806 (org-entry-get nil "NOBLOCKING")))
11807 (setq org-blocker-hook nil))
11808 (save-excursion
11809 (catch 'exit
11810 (org-back-to-heading t)
11811 (when (org-in-commented-heading-p t)
11812 (org-toggle-comment)
11813 (setq commentp t))
11814 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11815 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11816 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11817 (let* ((match-data (match-data))
11818 (startpos (copy-marker (line-beginning-position)))
11819 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11820 (org-log-done org-log-done)
11821 (org-log-repeat org-log-repeat)
11822 (org-todo-log-states org-todo-log-states)
11823 (org-inhibit-logging
11824 (if (equal arg 0)
11825 (progn (setq arg nil) 'note) org-inhibit-logging))
11826 (this (match-string 1))
11827 (hl-pos (match-beginning 0))
11828 (head (org-get-todo-sequence-head this))
11829 (ass (assoc head org-todo-kwd-alist))
11830 (interpret (nth 1 ass))
11831 (done-word (nth 3 ass))
11832 (final-done-word (nth 4 ass))
11833 (org-last-state (or this ""))
11834 (completion-ignore-case t)
11835 (member (member this org-todo-keywords-1))
11836 (tail (cdr member))
11837 (org-state (cond
11838 ((and org-todo-key-trigger
11839 (or (and (equal arg '(4))
11840 (eq org-use-fast-todo-selection 'prefix))
11841 (and (not arg) org-use-fast-todo-selection
11842 (not (eq org-use-fast-todo-selection
11843 'prefix)))))
11844 ;; Use fast selection.
11845 (org-fast-todo-selection))
11846 ((and (equal arg '(4))
11847 (or (not org-use-fast-todo-selection)
11848 (not org-todo-key-trigger)))
11849 ;; Read a state with completion.
11850 (completing-read
11851 "State: " (mapcar #'list org-todo-keywords-1)
11852 nil t))
11853 ((eq arg 'right)
11854 (if this
11855 (if tail (car tail) nil)
11856 (car org-todo-keywords-1)))
11857 ((eq arg 'left)
11858 (unless (equal member org-todo-keywords-1)
11859 (if this
11860 (nth (- (length org-todo-keywords-1)
11861 (length tail) 2)
11862 org-todo-keywords-1)
11863 (org-last org-todo-keywords-1))))
11864 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11865 (setq arg nil))) ;hack to fall back to cycling
11866 (arg
11867 ;; User or caller requests a specific state.
11868 (cond
11869 ((equal arg "") nil)
11870 ((eq arg 'none) nil)
11871 ((eq arg 'done) (or done-word (car org-done-keywords)))
11872 ((eq arg 'nextset)
11873 (or (car (cdr (member head org-todo-heads)))
11874 (car org-todo-heads)))
11875 ((eq arg 'previousset)
11876 (let ((org-todo-heads (reverse org-todo-heads)))
11877 (or (car (cdr (member head org-todo-heads)))
11878 (car org-todo-heads))))
11879 ((car (member arg org-todo-keywords-1)))
11880 ((stringp arg)
11881 (user-error "State `%s' not valid in this file" arg))
11882 ((nth (1- (prefix-numeric-value arg))
11883 org-todo-keywords-1))))
11884 ((null member) (or head (car org-todo-keywords-1)))
11885 ((equal this final-done-word) nil) ;-> make empty
11886 ((null tail) nil) ;-> first entry
11887 ((memq interpret '(type priority))
11888 (if (eq this-command last-command)
11889 (car tail)
11890 (if (> (length tail) 0)
11891 (or done-word (car org-done-keywords))
11892 nil)))
11894 (car tail))))
11895 (org-state (or
11896 (run-hook-with-args-until-success
11897 'org-todo-get-default-hook org-state org-last-state)
11898 org-state))
11899 (next (if org-state (concat " " org-state " ") " "))
11900 (change-plist (list :type 'todo-state-change :from this :to org-state
11901 :position startpos))
11902 dolog now-done-p)
11903 (when org-blocker-hook
11904 (let (org-blocked-by-checkboxes block-reason)
11905 (setq org-last-todo-state-is-todo
11906 (not (member this org-done-keywords)))
11907 (unless (save-excursion
11908 (save-match-data
11909 (org-with-wide-buffer
11910 (run-hook-with-args-until-failure
11911 'org-blocker-hook change-plist))))
11912 (setq block-reason (if org-blocked-by-checkboxes
11913 "contained checkboxes"
11914 (format "\"%s\"" org-block-entry-blocking)))
11915 (if (called-interactively-p 'interactive)
11916 (user-error "TODO state change from %s to %s blocked (by %s)"
11917 this org-state block-reason)
11918 ;; Fail silently.
11919 (message "TODO state change from %s to %s blocked (by %s)"
11920 this org-state block-reason)
11921 (throw 'exit nil)))))
11922 (store-match-data match-data)
11923 (replace-match next t t)
11924 (cond ((equal this org-state)
11925 (message "TODO state was already %s" (org-trim next)))
11926 ((not (pos-visible-in-window-p hl-pos))
11927 (message "TODO state changed to %s" (org-trim next))))
11928 (unless head
11929 (setq head (org-get-todo-sequence-head org-state)
11930 ass (assoc head org-todo-kwd-alist)
11931 interpret (nth 1 ass)
11932 done-word (nth 3 ass)
11933 final-done-word (nth 4 ass)))
11934 (when (memq arg '(nextset previousset))
11935 (message "Keyword-Set %d/%d: %s"
11936 (- (length org-todo-sets) -1
11937 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11938 (length org-todo-sets)
11939 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11940 (setq org-last-todo-state-is-todo
11941 (not (member org-state org-done-keywords)))
11942 (setq now-done-p (and (member org-state org-done-keywords)
11943 (not (member this org-done-keywords))))
11944 (and logging (org-local-logging logging))
11945 (when (and (or org-todo-log-states org-log-done)
11946 (not (eq org-inhibit-logging t))
11947 (not (memq arg '(nextset previousset))))
11948 ;; We need to look at recording a time and note.
11949 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11950 (nth 2 (assoc this org-todo-log-states))))
11951 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11952 (setq dolog 'time))
11953 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
11954 (and org-state
11955 (member org-state org-not-done-keywords)
11956 (not (member this org-not-done-keywords))))
11957 ;; This is now a todo state and was not one before
11958 ;; If there was a CLOSED time stamp, get rid of it.
11959 (org-add-planning-info nil nil 'closed))
11960 (when (and now-done-p org-log-done)
11961 ;; It is now done, and it was not done before.
11962 (org-add-planning-info 'closed (org-current-effective-time))
11963 (when (and (not dolog) (eq 'note org-log-done))
11964 (org-add-log-setup 'done org-state this 'note)))
11965 (when (and org-state dolog)
11966 ;; This is a non-nil state, and we need to log it.
11967 (org-add-log-setup 'state org-state this dolog)))
11968 ;; Fixup tag positioning.
11969 (org-todo-trigger-tag-changes org-state)
11970 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11971 (when org-provide-todo-statistics
11972 (org-update-parent-todo-statistics))
11973 (run-hooks 'org-after-todo-state-change-hook)
11974 (when (and arg (not (member org-state org-done-keywords)))
11975 (setq head (org-get-todo-sequence-head org-state)))
11976 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11977 ;; Do we need to trigger a repeat?
11978 (when now-done-p
11979 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11980 ;; This is for the agenda, take a snapshot of the headline.
11981 (save-match-data
11982 (setq org-agenda-headline-snapshot-before-repeat
11983 (org-get-heading))))
11984 (org-auto-repeat-maybe org-state))
11985 ;; Fixup cursor location if close to the keyword.
11986 (when (and (outline-on-heading-p)
11987 (not (bolp))
11988 (save-excursion (beginning-of-line 1)
11989 (looking-at org-todo-line-regexp))
11990 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11991 (goto-char (or (match-end 2) (match-end 1)))
11992 (and (looking-at " ") (just-one-space)))
11993 (when org-trigger-hook
11994 (save-excursion
11995 (run-hook-with-args 'org-trigger-hook change-plist)))
11996 (when commentp (org-toggle-comment))))))))
11998 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11999 "Block turning an entry into a TODO, using the hierarchy.
12000 This checks whether the current task should be blocked from state
12001 changes. Such blocking occurs when:
12003 1. The task has children which are not all in a completed state.
12005 2. A task has a parent with the property :ORDERED:, and there
12006 are siblings prior to the current task with incomplete
12007 status.
12009 3. The parent of the task is blocked because it has siblings that should
12010 be done first, or is child of a block grandparent TODO entry."
12012 (if (not org-enforce-todo-dependencies)
12013 t ; if locally turned off don't block
12014 (catch 'dont-block
12015 ;; If this is not a todo state change, or if this entry is already DONE,
12016 ;; do not block
12017 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12018 (member (plist-get change-plist :from)
12019 (cons 'done org-done-keywords))
12020 (member (plist-get change-plist :to)
12021 (cons 'todo org-not-done-keywords))
12022 (not (plist-get change-plist :to)))
12023 (throw 'dont-block t))
12024 ;; If this task has children, and any are undone, it's blocked
12025 (save-excursion
12026 (org-back-to-heading t)
12027 (let ((this-level (funcall outline-level)))
12028 (outline-next-heading)
12029 (let ((child-level (funcall outline-level)))
12030 (while (and (not (eobp))
12031 (> child-level this-level))
12032 ;; this todo has children, check whether they are all
12033 ;; completed
12034 (when (and (not (org-entry-is-done-p))
12035 (org-entry-is-todo-p))
12036 (setq org-block-entry-blocking (org-get-heading))
12037 (throw 'dont-block nil))
12038 (outline-next-heading)
12039 (setq child-level (funcall outline-level))))))
12040 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12041 ;; any previous siblings are undone, it's blocked
12042 (save-excursion
12043 (org-back-to-heading t)
12044 (let* ((pos (point))
12045 (parent-pos (and (org-up-heading-safe) (point)))
12046 (case-fold-search nil))
12047 (unless parent-pos (throw 'dont-block t)) ; no parent
12048 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12049 (forward-line 1)
12050 (re-search-forward org-not-done-heading-regexp pos t))
12051 (setq org-block-entry-blocking (match-string 0))
12052 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12053 ;; Search further up the hierarchy, to see if an ancestor is blocked
12054 (while t
12055 (goto-char parent-pos)
12056 (unless (looking-at org-not-done-heading-regexp)
12057 (throw 'dont-block t)) ; do not block, parent is not a TODO
12058 (setq pos (point))
12059 (setq parent-pos (and (org-up-heading-safe) (point)))
12060 (unless parent-pos (throw 'dont-block t)) ; no parent
12061 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12062 (forward-line 1)
12063 (re-search-forward org-not-done-heading-regexp pos t)
12064 (setq org-block-entry-blocking (org-get-heading)))
12065 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12067 (defcustom org-track-ordered-property-with-tag nil
12068 "Should the ORDERED property also be shown as a tag?
12069 The ORDERED property decides if an entry should require subtasks to be
12070 completed in sequence. Since a property is not very visible, setting
12071 this option means that toggling the ORDERED property with the command
12072 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12073 not relevant for the behavior, but it makes things more visible.
12075 Note that toggling the tag with tags commands will not change the property
12076 and therefore not influence behavior!
12078 This can be t, meaning the tag ORDERED should be used, It can also be a
12079 string to select a different tag for this task."
12080 :group 'org-todo
12081 :type '(choice
12082 (const :tag "No tracking" nil)
12083 (const :tag "Track with ORDERED tag" t)
12084 (string :tag "Use other tag")))
12086 (defun org-toggle-ordered-property ()
12087 "Toggle the ORDERED property of the current entry.
12088 For better visibility, you can track the value of this property with a tag.
12089 See variable `org-track-ordered-property-with-tag'."
12090 (interactive)
12091 (let* ((t1 org-track-ordered-property-with-tag)
12092 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12093 (save-excursion
12094 (org-back-to-heading)
12095 (if (org-entry-get nil "ORDERED")
12096 (progn
12097 (org-delete-property "ORDERED")
12098 (and tag (org-toggle-tag tag 'off))
12099 (message "Subtasks can be completed in arbitrary order"))
12100 (org-entry-put nil "ORDERED" "t")
12101 (and tag (org-toggle-tag tag 'on))
12102 (message "Subtasks must be completed in sequence")))))
12104 (defun org-block-todo-from-checkboxes (change-plist)
12105 "Block turning an entry into a TODO, using checkboxes.
12106 This checks whether the current task should be blocked from state
12107 changes because there are unchecked boxes in this entry."
12108 (if (not org-enforce-todo-checkbox-dependencies)
12109 t ; if locally turned off don't block
12110 (catch 'dont-block
12111 ;; If this is not a todo state change, or if this entry is already DONE,
12112 ;; do not block
12113 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12114 (member (plist-get change-plist :from)
12115 (cons 'done org-done-keywords))
12116 (member (plist-get change-plist :to)
12117 (cons 'todo org-not-done-keywords))
12118 (not (plist-get change-plist :to)))
12119 (throw 'dont-block t))
12120 ;; If this task has checkboxes that are not checked, it's blocked
12121 (save-excursion
12122 (org-back-to-heading t)
12123 (let ((beg (point)) end)
12124 (outline-next-heading)
12125 (setq end (point))
12126 (goto-char beg)
12127 (when (org-list-search-forward
12128 (concat (org-item-beginning-re)
12129 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12130 "\\[[- ]\\]")
12131 end t)
12132 (when (boundp 'org-blocked-by-checkboxes)
12133 (setq org-blocked-by-checkboxes t))
12134 (throw 'dont-block nil))))
12135 t))) ; do not block
12137 (defun org-entry-blocked-p ()
12138 "Non-nil if entry at point is blocked."
12139 (and (not (org-entry-get nil "NOBLOCKING"))
12140 (member (org-entry-get nil "TODO") org-not-done-keywords)
12141 (not (run-hook-with-args-until-failure
12142 'org-blocker-hook
12143 (list :type 'todo-state-change
12144 :position (point)
12145 :from 'todo
12146 :to 'done)))))
12148 (defun org-update-statistics-cookies (all)
12149 "Update the statistics cookie, either from TODO or from checkboxes.
12150 This should be called with the cursor in a line with a statistics
12151 cookie. When called with a \\[universal-argument] prefix, update
12152 all statistics cookies in the buffer."
12153 (interactive "P")
12154 (if all
12155 (progn
12156 (org-update-checkbox-count 'all)
12157 (org-map-entries 'org-update-parent-todo-statistics))
12158 (if (not (org-at-heading-p))
12159 (org-update-checkbox-count)
12160 (let ((pos (point-marker))
12161 end l1 l2)
12162 (ignore-errors (org-back-to-heading t))
12163 (if (not (org-at-heading-p))
12164 (org-update-checkbox-count)
12165 (setq l1 (org-outline-level))
12166 (setq end (save-excursion
12167 (outline-next-heading)
12168 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12169 (point)))
12170 (if (and (save-excursion
12171 (re-search-forward
12172 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12173 (not (save-excursion (re-search-forward
12174 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12175 (org-update-checkbox-count)
12176 (if (and l2 (> l2 l1))
12177 (progn
12178 (goto-char end)
12179 (org-update-parent-todo-statistics))
12180 (goto-char pos)
12181 (beginning-of-line 1)
12182 (while (re-search-forward
12183 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12184 (point-at-eol) t)
12185 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12186 (goto-char pos)
12187 (move-marker pos nil)))))
12189 (defvar org-entry-property-inherited-from) ;; defined below
12190 (defun org-update-parent-todo-statistics ()
12191 "Update any statistics cookie in the parent of the current headline.
12192 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12193 the entire subtree and this will travel up the hierarchy and update
12194 statistics everywhere."
12195 (let* ((prop (save-excursion (org-up-heading-safe)
12196 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12197 (recursive (or (not org-hierarchical-todo-statistics)
12198 (and prop (string-match "\\<recursive\\>" prop))))
12199 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12201 (first t)
12202 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12203 level ltoggle l1 new ndel
12204 (cnt-all 0) (cnt-done 0) is-percent kwd
12205 checkbox-beg cookie-present)
12206 (catch 'exit
12207 (save-excursion
12208 (beginning-of-line 1)
12209 (setq ltoggle (funcall outline-level))
12210 ;; Three situations are to consider:
12212 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12213 ;; to the top-level ancestor on the headline;
12215 ;; 2. If parent has "recursive" property, repeat up to the
12216 ;; headline setting that property, taking inheritance into
12217 ;; account;
12219 ;; 3. Else, move up to direct parent and proceed only once.
12220 (while (and (setq level (org-up-heading-safe))
12221 (or recursive first)
12222 (>= (point) lim))
12223 (setq first nil cookie-present nil)
12224 (unless (and level
12225 (not (string-match
12226 "\\<checkbox\\>"
12227 (downcase (or (org-entry-get nil "COOKIE_DATA")
12228 "")))))
12229 (throw 'exit nil))
12230 (while (re-search-forward box-re (point-at-eol) t)
12231 (setq cnt-all 0 cnt-done 0 cookie-present t)
12232 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12233 (save-match-data
12234 (unless (outline-next-heading) (throw 'exit nil))
12235 (while (and (looking-at org-complex-heading-regexp)
12236 (> (setq l1 (length (match-string 1))) level))
12237 (setq kwd (and (or recursive (= l1 ltoggle))
12238 (match-string 2)))
12239 (if (or (eq org-provide-todo-statistics 'all-headlines)
12240 (and (eq org-provide-todo-statistics t)
12241 (or (member kwd org-done-keywords)))
12242 (and (listp org-provide-todo-statistics)
12243 (stringp (car org-provide-todo-statistics))
12244 (or (member kwd org-provide-todo-statistics)
12245 (member kwd org-done-keywords)))
12246 (and (listp org-provide-todo-statistics)
12247 (listp (car org-provide-todo-statistics))
12248 (or (member kwd (car org-provide-todo-statistics))
12249 (and (member kwd org-done-keywords)
12250 (member kwd (cadr org-provide-todo-statistics))))))
12251 (setq cnt-all (1+ cnt-all))
12252 (and (eq org-provide-todo-statistics t)
12254 (setq cnt-all (1+ cnt-all))))
12255 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12256 (member kwd org-done-keywords))
12257 (and (listp org-provide-todo-statistics)
12258 (listp (car org-provide-todo-statistics))
12259 (member kwd org-done-keywords)
12260 (member kwd (cadr org-provide-todo-statistics)))
12261 (and (listp org-provide-todo-statistics)
12262 (stringp (car org-provide-todo-statistics))
12263 (member kwd org-done-keywords)))
12264 (setq cnt-done (1+ cnt-done)))
12265 (outline-next-heading)))
12266 (setq new
12267 (if is-percent
12268 (format "[%d%%]" (floor (* 100.0 cnt-done)
12269 (max 1 cnt-all)))
12270 (format "[%d/%d]" cnt-done cnt-all))
12271 ndel (- (match-end 0) checkbox-beg))
12272 (goto-char checkbox-beg)
12273 (insert new)
12274 (delete-region (point) (+ (point) ndel))
12275 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12276 (when cookie-present
12277 (run-hook-with-args 'org-after-todo-statistics-hook
12278 cnt-done (- cnt-all cnt-done))))))
12279 (run-hooks 'org-todo-statistics-hook)))
12281 (defvar org-after-todo-statistics-hook nil
12282 "Hook that is called after a TODO statistics cookie has been updated.
12283 Each function is called with two arguments: the number of not-done entries
12284 and the number of done entries.
12286 For example, the following function, when added to this hook, will switch
12287 an entry to DONE when all children are done, and back to TODO when new
12288 entries are set to a TODO status. Note that this hook is only called
12289 when there is a statistics cookie in the headline!
12291 (defun org-summary-todo (n-done n-not-done)
12292 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12293 (let (org-log-done org-log-states) ; turn off logging
12294 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12297 (defvar org-todo-statistics-hook nil
12298 "Hook that is run whenever Org thinks TODO statistics should be updated.
12299 This hook runs even if there is no statistics cookie present, in which case
12300 `org-after-todo-statistics-hook' would not run.")
12302 (defun org-todo-trigger-tag-changes (state)
12303 "Apply the changes defined in `org-todo-state-tags-triggers'."
12304 (let ((l org-todo-state-tags-triggers)
12305 changes)
12306 (when (or (not state) (equal state ""))
12307 (setq changes (append changes (cdr (assoc "" l)))))
12308 (when (and (stringp state) (> (length state) 0))
12309 (setq changes (append changes (cdr (assoc state l)))))
12310 (when (member state org-not-done-keywords)
12311 (setq changes (append changes (cdr (assq 'todo l)))))
12312 (when (member state org-done-keywords)
12313 (setq changes (append changes (cdr (assq 'done l)))))
12314 (dolist (c changes)
12315 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12317 (defun org-local-logging (value)
12318 "Get logging settings from a property VALUE."
12319 ;; Directly set the variables, they are already local.
12320 (setq org-log-done nil
12321 org-log-repeat nil
12322 org-todo-log-states nil)
12323 (dolist (w (split-string value))
12324 (let (a)
12325 (cond
12326 ((setq a (assoc w org-startup-options))
12327 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12328 (set (nth 1 a) (nth 2 a))))
12329 ((setq a (org-extract-log-state-settings w))
12330 (and (member (car a) org-todo-keywords-1)
12331 (push a org-todo-log-states)))))))
12333 (defun org-get-todo-sequence-head (kwd)
12334 "Return the head of the TODO sequence to which KWD belongs.
12335 If KWD is not set, check if there is a text property remembering the
12336 right sequence."
12337 (let (p)
12338 (cond
12339 ((not kwd)
12340 (or (get-text-property (point-at-bol) 'org-todo-head)
12341 (progn
12342 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12343 nil (point-at-eol)))
12344 (get-text-property p 'org-todo-head))))
12345 ((not (member kwd org-todo-keywords-1))
12346 (car org-todo-keywords-1))
12347 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12349 (defun org-fast-todo-selection ()
12350 "Fast TODO keyword selection with single keys.
12351 Returns the new TODO keyword, or nil if no state change should occur."
12352 (let* ((fulltable org-todo-key-alist)
12353 (done-keywords org-done-keywords) ;; needed for the faces.
12354 (maxlen (apply 'max (mapcar
12355 (lambda (x)
12356 (if (stringp (car x)) (string-width (car x)) 0))
12357 fulltable)))
12358 (expert nil)
12359 (fwidth (+ maxlen 3 1 3))
12360 (ncol (/ (- (window-width) 4) fwidth))
12361 tg cnt e c tbl
12362 groups ingroup)
12363 (save-excursion
12364 (save-window-excursion
12365 (if expert
12366 (set-buffer (get-buffer-create " *Org todo*"))
12367 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12368 (erase-buffer)
12369 (setq-local org-done-keywords done-keywords)
12370 (setq tbl fulltable cnt 0)
12371 (while (setq e (pop tbl))
12372 (cond
12373 ((equal e '(:startgroup))
12374 (push '() groups) (setq ingroup t)
12375 (unless (= cnt 0)
12376 (setq cnt 0)
12377 (insert "\n"))
12378 (insert "{ "))
12379 ((equal e '(:endgroup))
12380 (setq ingroup nil cnt 0)
12381 (insert "}\n"))
12382 ((equal e '(:newline))
12383 (unless (= cnt 0)
12384 (setq cnt 0)
12385 (insert "\n")
12386 (setq e (car tbl))
12387 (while (equal (car tbl) '(:newline))
12388 (insert "\n")
12389 (setq tbl (cdr tbl)))))
12391 (setq tg (car e) c (cdr e))
12392 (when ingroup (push tg (car groups)))
12393 (setq tg (org-add-props tg nil 'face
12394 (org-get-todo-face tg)))
12395 (when (and (= cnt 0) (not ingroup)) (insert " "))
12396 (insert "[" c "] " tg (make-string
12397 (- fwidth 4 (length tg)) ?\ ))
12398 (when (= (setq cnt (1+ cnt)) ncol)
12399 (insert "\n")
12400 (when ingroup (insert " "))
12401 (setq cnt 0)))))
12402 (insert "\n")
12403 (goto-char (point-min))
12404 (unless expert (org-fit-window-to-buffer))
12405 (message "[a-z..]:Set [SPC]:clear")
12406 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12407 (cond
12408 ((or (= c ?\C-g)
12409 (and (= c ?q) (not (rassoc c fulltable))))
12410 (setq quit-flag t))
12411 ((= c ?\ ) nil)
12412 ((setq e (rassoc c fulltable) tg (car e))
12414 (t (setq quit-flag t)))))))
12416 (defun org-entry-is-todo-p ()
12417 (member (org-get-todo-state) org-not-done-keywords))
12419 (defun org-entry-is-done-p ()
12420 (member (org-get-todo-state) org-done-keywords))
12422 (defun org-get-todo-state ()
12423 "Return the TODO keyword of the current subtree."
12424 (save-excursion
12425 (org-back-to-heading t)
12426 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12427 (match-end 2)
12428 (match-string 2))))
12430 (defun org-at-date-range-p (&optional inactive-ok)
12431 "Non-nil if point is inside a date range.
12433 When optional argument INACTIVE-OK is non-nil, also consider
12434 inactive time ranges.
12436 When this function returns a non-nil value, match data is set
12437 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12438 on INACTIVE-OK."
12439 (interactive)
12440 (save-excursion
12441 (catch 'exit
12442 (let ((pos (point)))
12443 (skip-chars-backward "^[<\r\n")
12444 (skip-chars-backward "<[")
12445 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12446 (>= (match-end 0) pos)
12447 (throw 'exit t))
12448 (skip-chars-backward "^<[\r\n")
12449 (skip-chars-backward "<[")
12450 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12451 (>= (match-end 0) pos)
12452 (throw 'exit t)))
12453 nil)))
12455 (defun org-get-repeat (&optional timestamp)
12456 "Check if there is a time-stamp with repeater in this entry.
12458 Return the repeater, as a string, or nil. Also return nil when
12459 this function is called before first heading.
12461 When optional argument TIMESTAMP is a string, extract the
12462 repeater from there instead."
12463 (save-match-data
12464 (cond (timestamp
12465 (and (string-match org-repeat-re timestamp)
12466 (match-string-no-properties 1 timestamp)))
12467 ((org-before-first-heading-p) nil)
12469 (save-excursion
12470 (org-back-to-heading t)
12471 (let ((end (org-entry-end-position)))
12472 (catch :repeat
12473 (while (re-search-forward org-repeat-re end t)
12474 (when (save-match-data (org-at-timestamp-p 'agenda))
12475 (throw :repeat (match-string-no-properties 1)))))))))))
12477 (defvar org-last-changed-timestamp)
12478 (defvar org-last-inserted-timestamp)
12479 (defvar org-log-post-message)
12480 (defvar org-log-note-purpose)
12481 (defvar org-log-note-how nil)
12482 (defvar org-log-note-extra)
12483 (defun org-auto-repeat-maybe (done-word)
12484 "Check if the current headline contains a repeated time-stamp.
12486 If yes, set TODO state back to what it was and change the base date
12487 of repeating deadline/scheduled time stamps to new date.
12489 This function is run automatically after each state change to a DONE state."
12490 (let* ((repeat (org-get-repeat))
12491 (aa (assoc org-last-state org-todo-kwd-alist))
12492 (interpret (nth 1 aa))
12493 (head (nth 2 aa))
12494 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12495 (msg "Entry repeats: ")
12496 (org-log-done nil)
12497 (org-todo-log-states nil)
12498 (end (copy-marker (org-entry-end-position))))
12499 (unwind-protect
12500 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12501 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12502 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12503 (and (stringp org-todo-repeat-to-state)
12504 org-todo-repeat-to-state)
12505 (and org-todo-repeat-to-state org-last-state))))
12506 (org-todo (cond
12507 ((and to-state (member to-state org-todo-keywords-1))
12508 to-state)
12509 ((eq interpret 'type) org-last-state)
12510 (head)
12511 (t 'none))))
12512 (org-back-to-heading t)
12513 (org-add-planning-info nil nil 'closed)
12514 ;; When `org-log-repeat' is non-nil or entry contains
12515 ;; a clock, set LAST_REPEAT property.
12516 (when (or org-log-repeat
12517 (catch :clock
12518 (save-excursion
12519 (while (re-search-forward org-clock-line-re end t)
12520 (when (org-at-clock-log-p) (throw :clock t))))))
12521 (org-entry-put nil "LAST_REPEAT" (format-time-string
12522 (org-time-stamp-format t t)
12523 (current-time))))
12524 (when org-log-repeat
12525 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12526 (memq 'org-add-log-note post-command-hook))
12527 ;; We are already setup for some record.
12528 (when (eq org-log-repeat 'note)
12529 ;; Make sure we take a note, not only a time stamp.
12530 (setq org-log-note-how 'note))
12531 ;; Set up for taking a record.
12532 (org-add-log-setup 'state
12533 (or done-word (car org-done-keywords))
12534 org-last-state
12535 org-log-repeat)))
12536 (let ((planning-re (regexp-opt
12537 (list org-scheduled-string org-deadline-string))))
12538 (while (re-search-forward org-ts-regexp end t)
12539 (let* ((ts (match-string 0))
12540 (planning? (org-at-planning-p))
12541 (type (if (not planning?) "Plain:"
12542 (save-excursion
12543 (re-search-backward
12544 planning-re (line-beginning-position) t)
12545 (match-string 0)))))
12546 (cond
12547 ;; Ignore fake time-stamps (e.g., within comments).
12548 ((not (org-at-timestamp-p 'agenda)))
12549 ;; Time-stamps without a repeater are usually
12550 ;; skipped. However, a SCHEDULED time-stamp without
12551 ;; one is removed, as they are no longer relevant.
12552 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12553 ts))
12554 (when (equal type org-scheduled-string)
12555 (org-remove-timestamp-with-keyword type)))
12557 (let ((n (string-to-number (match-string 2 ts)))
12558 (what (match-string 3 ts)))
12559 (when (equal what "w") (setq n (* n 7) what "d"))
12560 (when (and (equal what "h")
12561 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12562 ts)))
12563 (user-error
12564 "Cannot repeat in Repeat in %d hour(s) because no hour \
12565 has been set"
12567 ;; Preparation, see if we need to modify the start
12568 ;; date for the change.
12569 (when (match-end 1)
12570 (let ((time (save-match-data
12571 (org-time-string-to-time ts))))
12572 (cond
12573 ((equal (match-string 1 ts) ".")
12574 ;; Shift starting date to today
12575 (org-timestamp-change
12576 (- (org-today) (time-to-days time))
12577 'day))
12578 ((equal (match-string 1 ts) "+")
12579 (let ((nshiftmax 10)
12580 (nshift 0))
12581 (while (or (= nshift 0)
12582 (not (time-less-p (current-time) time)))
12583 (when (= (cl-incf nshift) nshiftmax)
12584 (or (y-or-n-p
12585 (format "%d repeater intervals were not \
12586 enough to shift date past today. Continue? "
12587 nshift))
12588 (user-error "Abort")))
12589 (org-timestamp-change n (cdr (assoc what whata)))
12590 (org-in-regexp org-ts-regexp3)
12591 (setq ts (match-string 1))
12592 (setq time
12593 (save-match-data
12594 (org-time-string-to-time ts)))))
12595 (org-timestamp-change (- n) (cdr (assoc what whata)))
12596 ;; Rematch, so that we have everything in place
12597 ;; for the real shift.
12598 (org-in-regexp org-ts-regexp3)
12599 (setq ts (match-string 1))
12600 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12601 ts)))))
12602 (save-excursion
12603 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12604 (setq msg
12605 (concat
12606 msg type " " org-last-changed-timestamp " "))))))))
12607 (setq org-log-post-message msg)
12608 (message "%s" msg))
12609 (set-marker end nil))))
12611 (defun org-show-todo-tree (arg)
12612 "Make a compact tree which shows all headlines marked with TODO.
12613 The tree will show the lines where the regexp matches, and all higher
12614 headlines above the match.
12615 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12616 With a numeric prefix N, construct a sparse tree for the Nth element
12617 of `org-todo-keywords-1'."
12618 (interactive "P")
12619 (let ((case-fold-search nil)
12620 (kwd-re
12621 (cond ((null arg) org-not-done-regexp)
12622 ((equal arg '(4))
12623 (let ((kwd
12624 (completing-read "Keyword (or KWD1|KWD2|...): "
12625 (mapcar #'list org-todo-keywords-1))))
12626 (concat "\\("
12627 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12628 "\\)\\>")))
12629 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12630 (regexp-quote (nth (1- (prefix-numeric-value arg))
12631 org-todo-keywords-1)))
12632 (t (user-error "Invalid prefix argument: %s" arg)))))
12633 (message "%d TODO entries found"
12634 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12636 (defun org--deadline-or-schedule (arg type time)
12637 "Insert DEADLINE or SCHEDULE information in current entry.
12638 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12639 `org-schedule' for information about ARG and TIME arguments."
12640 (let* ((deadline? (eq type 'deadline))
12641 (keyword (if deadline? org-deadline-string org-scheduled-string))
12642 (log (if deadline? org-log-redeadline org-log-reschedule))
12643 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12644 (old-date-time (and old-date (org-time-string-to-time old-date)))
12645 ;; Save repeater cookie from either TIME or current scheduled
12646 ;; time stamp. We are going to insert it back at the end of
12647 ;; the process.
12648 (repeater (or (and (org-string-nw-p time)
12649 ;; We use `org-repeat-re' because we need
12650 ;; to tell the difference between a real
12651 ;; repeater and a time delta, e.g. "+2d".
12652 (string-match org-repeat-re time)
12653 (match-string 1 time))
12654 (and (org-string-nw-p old-date)
12655 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12656 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12657 old-date)
12658 (match-string 1 old-date)))))
12659 (pcase arg
12660 (`(4)
12661 (when (and old-date log)
12662 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12663 nil old-date log))
12664 (org-remove-timestamp-with-keyword keyword)
12665 (message (if deadline? "Item no longer has a deadline."
12666 "Item is no longer scheduled.")))
12667 (`(16)
12668 (save-excursion
12669 (org-back-to-heading t)
12670 (let ((regexp (if deadline? org-deadline-time-regexp
12671 org-scheduled-time-regexp)))
12672 (if (not (re-search-forward regexp (line-end-position 2) t))
12673 (user-error (if deadline? "No deadline information to update"
12674 "No scheduled information to update"))
12675 (let* ((rpl0 (match-string 1))
12676 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12677 (msg (if deadline? "Warn starting from" "Delay until")))
12678 (replace-match
12679 (concat keyword
12680 " <" rpl
12681 (format " -%dd"
12682 (abs (- (time-to-days
12683 (save-match-data
12684 (org-read-date
12685 nil t nil msg old-date-time)))
12686 (time-to-days old-date-time))))
12687 ">") t t))))))
12689 (org-add-planning-info type time 'closed)
12690 (when (and old-date
12692 (not (equal old-date org-last-inserted-timestamp)))
12693 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12694 org-last-inserted-timestamp
12695 old-date
12696 log))
12697 (when repeater
12698 (save-excursion
12699 (org-back-to-heading t)
12700 (when (re-search-forward
12701 (concat keyword " " org-last-inserted-timestamp)
12702 (line-end-position 2)
12704 (goto-char (1- (match-end 0)))
12705 (insert " " repeater)
12706 (setq org-last-inserted-timestamp
12707 (concat (substring org-last-inserted-timestamp 0 -1)
12708 " " repeater
12709 (substring org-last-inserted-timestamp -1))))))
12710 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12711 org-last-inserted-timestamp)))))
12713 (defun org-deadline (arg &optional time)
12714 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12715 With one universal prefix argument, remove any deadline from the item.
12716 With two universal prefix arguments, prompt for a warning delay.
12717 With argument TIME, set the deadline at the corresponding date. TIME
12718 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12719 (interactive "P")
12720 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12721 (org-map-entries
12722 (lambda () (org--deadline-or-schedule arg 'deadline time))
12724 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12725 'region-start-level
12726 'region)
12727 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12728 (org--deadline-or-schedule arg 'deadline time)))
12730 (defun org-schedule (arg &optional time)
12731 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12732 With one universal prefix argument, remove any scheduling date from the item.
12733 With two universal prefix arguments, prompt for a delay cookie.
12734 With argument TIME, scheduled at the corresponding date. TIME can
12735 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12736 (interactive "P")
12737 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12738 (org-map-entries
12739 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12741 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12742 'region-start-level
12743 'region)
12744 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12745 (org--deadline-or-schedule arg 'scheduled time)))
12747 (defun org-get-scheduled-time (pom &optional inherit)
12748 "Get the scheduled time as a time tuple, of a format suitable
12749 for calling org-schedule with, or if there is no scheduling,
12750 returns nil."
12751 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12752 (when time
12753 (apply 'encode-time (org-parse-time-string time)))))
12755 (defun org-get-deadline-time (pom &optional inherit)
12756 "Get the deadline as a time tuple, of a format suitable for
12757 calling org-deadline with, or if there is no scheduling, returns
12758 nil."
12759 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12760 (when time
12761 (apply 'encode-time (org-parse-time-string time)))))
12763 (defun org-remove-timestamp-with-keyword (keyword)
12764 "Remove all time stamps with KEYWORD in the current entry."
12765 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12766 beg)
12767 (save-excursion
12768 (org-back-to-heading t)
12769 (setq beg (point))
12770 (outline-next-heading)
12771 (while (re-search-backward re beg t)
12772 (replace-match "")
12773 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12774 (equal (char-before) ?\ ))
12775 (backward-delete-char 1)
12776 (when (string-match "^[ \t]*$" (buffer-substring
12777 (point-at-bol) (point-at-eol)))
12778 (delete-region (point-at-bol)
12779 (min (point-max) (1+ (point-at-eol))))))))))
12781 (defvar org-time-was-given) ; dynamically scoped parameter
12782 (defvar org-end-time-was-given) ; dynamically scoped parameter
12784 (defun org-at-planning-p ()
12785 "Non-nil when point is on a planning info line."
12786 ;; This is as accurate and faster than `org-element-at-point' since
12787 ;; planning info location is fixed in the section.
12788 (org-with-wide-buffer
12789 (beginning-of-line)
12790 (and (looking-at-p org-planning-line-re)
12791 (eq (point)
12792 (ignore-errors
12793 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12794 (org-back-to-heading t)
12795 (org-with-limited-levels (org-back-to-heading t)))
12796 (line-beginning-position 2))))))
12798 (defun org-add-planning-info (what &optional time &rest remove)
12799 "Insert new timestamp with keyword in the planning line.
12800 WHAT indicates what kind of time stamp to add. It is a symbol
12801 among `closed', `deadline', `scheduled' and nil. TIME indicates
12802 the time to use. If none is given, the user is prompted for
12803 a date. REMOVE indicates what kind of entries to remove. An old
12804 WHAT entry will also be removed."
12805 (let (org-time-was-given org-end-time-was-given default-time default-input)
12806 (catch 'exit
12807 (when (and (memq what '(scheduled deadline))
12808 (or (not time)
12809 (and (stringp time)
12810 (string-match "^[-+]+[0-9]" time))))
12811 ;; Try to get a default date/time from existing timestamp
12812 (save-excursion
12813 (org-back-to-heading t)
12814 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12815 (when (re-search-forward (if (eq what 'scheduled)
12816 org-scheduled-time-regexp
12817 org-deadline-time-regexp)
12818 end t)
12819 (setq ts (match-string 1)
12820 default-time (apply 'encode-time (org-parse-time-string ts))
12821 default-input (and ts (org-get-compact-tod ts)))))))
12822 (when what
12823 (setq time
12824 (if (stringp time)
12825 ;; This is a string (relative or absolute), set
12826 ;; proper date.
12827 (apply #'encode-time
12828 (org-read-date-analyze
12829 time default-time (decode-time default-time)))
12830 ;; If necessary, get the time from the user
12831 (or time (org-read-date nil 'to-time nil nil
12832 default-time default-input)))))
12834 (org-with-wide-buffer
12835 (org-back-to-heading t)
12836 (forward-line)
12837 (unless (bolp) (insert "\n"))
12838 (cond ((looking-at-p org-planning-line-re)
12839 ;; Move to current indentation.
12840 (skip-chars-forward " \t")
12841 ;; Check if we have to remove something.
12842 (dolist (type (if what (cons what remove) remove))
12843 (save-excursion
12844 (when (re-search-forward
12845 (cl-case type
12846 (closed org-closed-time-regexp)
12847 (deadline org-deadline-time-regexp)
12848 (scheduled org-scheduled-time-regexp)
12849 (otherwise
12850 (error "Invalid planning type: %s" type)))
12851 (line-end-position) t)
12852 ;; Delete until next keyword or end of line.
12853 (delete-region
12854 (match-beginning 0)
12855 (if (re-search-forward org-keyword-time-not-clock-regexp
12856 (line-end-position)
12858 (match-beginning 0)
12859 (line-end-position))))))
12860 ;; If there is nothing more to add and no more keyword
12861 ;; is left, remove the line completely.
12862 (if (and (looking-at-p "[ \t]*$") (not what))
12863 (delete-region (line-beginning-position)
12864 (line-beginning-position 2))
12865 ;; If we removed last keyword, do not leave trailing
12866 ;; white space at the end of line.
12867 (let ((p (point)))
12868 (save-excursion
12869 (end-of-line)
12870 (unless (= (skip-chars-backward " \t" p) 0)
12871 (delete-region (point) (line-end-position)))))))
12872 ((not what) (throw 'exit nil)) ; Nothing to do.
12873 (t (insert-before-markers "\n")
12874 (backward-char 1)
12875 (when org-adapt-indentation
12876 (indent-to-column (1+ (org-outline-level))))))
12877 (when what
12878 ;; Insert planning keyword.
12879 (insert (cl-case what
12880 (closed org-closed-string)
12881 (deadline org-deadline-string)
12882 (scheduled org-scheduled-string)
12883 (otherwise (error "Invalid planning type: %s" what)))
12884 " ")
12885 ;; Insert associated timestamp.
12886 (let ((ts (org-insert-time-stamp
12887 time
12888 (or org-time-was-given
12889 (and (eq what 'closed) org-log-done-with-time))
12890 (eq what 'closed)
12891 nil nil (list org-end-time-was-given))))
12892 (unless (eolp) (insert " "))
12893 ts))))))
12895 (defvar org-log-note-marker (make-marker)
12896 "Marker pointing at the entry where the note is to be inserted.")
12897 (defvar org-log-note-purpose nil)
12898 (defvar org-log-note-state nil)
12899 (defvar org-log-note-previous-state nil)
12900 (defvar org-log-note-extra nil)
12901 (defvar org-log-note-window-configuration nil)
12902 (defvar org-log-note-return-to (make-marker))
12903 (defvar org-log-note-effective-time nil
12904 "Remembered current time so that dynamically scoped
12905 `org-extend-today-until' affects timestamps in state change log")
12907 (defvar org-log-post-message nil
12908 "Message to be displayed after a log note has been stored.
12909 The auto-repeater uses this.")
12911 (defun org-add-note ()
12912 "Add a note to the current entry.
12913 This is done in the same way as adding a state change note."
12914 (interactive)
12915 (org-add-log-setup 'note))
12917 (defun org-log-beginning (&optional create)
12918 "Return expected start of log notes in current entry.
12919 When optional argument CREATE is non-nil, the function creates
12920 a drawer to store notes, if necessary. Returned position ignores
12921 narrowing."
12922 (org-with-wide-buffer
12923 (let ((drawer (org-log-into-drawer)))
12924 (cond
12925 (drawer
12926 (org-end-of-meta-data)
12927 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12928 (end (if (org-at-heading-p) (point)
12929 (save-excursion (outline-next-heading) (point))))
12930 (case-fold-search t))
12931 (catch 'exit
12932 ;; Try to find existing drawer.
12933 (while (re-search-forward regexp end t)
12934 (let ((element (org-element-at-point)))
12935 (when (eq (org-element-type element) 'drawer)
12936 (let ((cend (org-element-property :contents-end element)))
12937 (when (and (not org-log-states-order-reversed) cend)
12938 (goto-char cend)))
12939 (throw 'exit nil))))
12940 ;; No drawer found. Create one, if permitted.
12941 (when create
12942 (unless (bolp) (insert "\n"))
12943 (let ((beg (point)))
12944 (insert ":" drawer ":\n:END:\n")
12945 (org-indent-region beg (point)))
12946 (end-of-line -1)))))
12948 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12949 (skip-chars-forward " \t\n")
12950 (beginning-of-line)
12951 (unless org-log-states-order-reversed
12952 (org-skip-over-state-notes)
12953 (skip-chars-backward " \t\n")
12954 (forward-line)))))
12955 (if (bolp) (point) (line-beginning-position 2))))
12957 (defun org-add-log-setup (&optional purpose state prev-state how extra)
12958 "Set up the post command hook to take a note.
12959 If this is about to TODO state change, the new state is expected in STATE.
12960 HOW is an indicator what kind of note should be created.
12961 EXTRA is additional text that will be inserted into the notes buffer."
12962 (move-marker org-log-note-marker (point))
12963 (setq org-log-note-purpose purpose
12964 org-log-note-state state
12965 org-log-note-previous-state prev-state
12966 org-log-note-how how
12967 org-log-note-extra extra
12968 org-log-note-effective-time (org-current-effective-time))
12969 (add-hook 'post-command-hook 'org-add-log-note 'append))
12971 (defun org-skip-over-state-notes ()
12972 "Skip past the list of State notes in an entry."
12973 (when (ignore-errors (goto-char (org-in-item-p)))
12974 (let* ((struct (org-list-struct))
12975 (prevs (org-list-prevs-alist struct))
12976 (regexp
12977 (concat "[ \t]*- +"
12978 (replace-regexp-in-string
12979 " +" " +"
12980 (org-replace-escapes
12981 (regexp-quote (cdr (assq 'state org-log-note-headings)))
12982 `(("%d" . ,org-ts-regexp-inactive)
12983 ("%D" . ,org-ts-regexp)
12984 ("%s" . "\"\\S-+\"")
12985 ("%S" . "\"\\S-+\"")
12986 ("%t" . ,org-ts-regexp-inactive)
12987 ("%T" . ,org-ts-regexp)
12988 ("%u" . ".*?")
12989 ("%U" . ".*?")))))))
12990 (while (looking-at-p regexp)
12991 (goto-char (or (org-list-get-next-item (point) struct prevs)
12992 (org-list-get-item-end (point) struct)))))))
12994 (defun org-add-log-note (&optional _purpose)
12995 "Pop up a window for taking a note, and add this note later."
12996 (remove-hook 'post-command-hook 'org-add-log-note)
12997 (setq org-log-note-window-configuration (current-window-configuration))
12998 (delete-other-windows)
12999 (move-marker org-log-note-return-to (point))
13000 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13001 (goto-char org-log-note-marker)
13002 (org-switch-to-buffer-other-window "*Org Note*")
13003 (erase-buffer)
13004 (if (memq org-log-note-how '(time state))
13005 (org-store-log-note)
13006 (let ((org-inhibit-startup t)) (org-mode))
13007 (insert (format "# Insert note for %s.
13008 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13009 (cond
13010 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13011 ((eq org-log-note-purpose 'done) "closed todo item")
13012 ((eq org-log-note-purpose 'state)
13013 (format "state change from \"%s\" to \"%s\""
13014 (or org-log-note-previous-state "")
13015 (or org-log-note-state "")))
13016 ((eq org-log-note-purpose 'reschedule)
13017 "rescheduling")
13018 ((eq org-log-note-purpose 'delschedule)
13019 "no longer scheduled")
13020 ((eq org-log-note-purpose 'redeadline)
13021 "changing deadline")
13022 ((eq org-log-note-purpose 'deldeadline)
13023 "removing deadline")
13024 ((eq org-log-note-purpose 'refile)
13025 "refiling")
13026 ((eq org-log-note-purpose 'note)
13027 "this entry")
13028 (t (error "This should not happen")))))
13029 (when org-log-note-extra (insert org-log-note-extra))
13030 (setq-local org-finish-function 'org-store-log-note)
13031 (run-hooks 'org-log-buffer-setup-hook)))
13033 (defvar org-note-abort nil) ; dynamically scoped
13034 (defun org-store-log-note ()
13035 "Finish taking a log note, and insert it to where it belongs."
13036 (let ((txt (prog1 (buffer-string)
13037 (kill-buffer)))
13038 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13039 lines)
13040 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13041 (setq txt (replace-match "" t t txt)))
13042 (when (string-match "\\s-+\\'" txt)
13043 (setq txt (replace-match "" t t txt)))
13044 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13045 (when (org-string-nw-p note)
13046 (setq note
13047 (org-replace-escapes
13048 note
13049 (list (cons "%u" (user-login-name))
13050 (cons "%U" user-full-name)
13051 (cons "%t" (format-time-string
13052 (org-time-stamp-format 'long 'inactive)
13053 org-log-note-effective-time))
13054 (cons "%T" (format-time-string
13055 (org-time-stamp-format 'long nil)
13056 org-log-note-effective-time))
13057 (cons "%d" (format-time-string
13058 (org-time-stamp-format nil 'inactive)
13059 org-log-note-effective-time))
13060 (cons "%D" (format-time-string
13061 (org-time-stamp-format nil nil)
13062 org-log-note-effective-time))
13063 (cons "%s" (cond
13064 ((not org-log-note-state) "")
13065 ((string-match-p org-ts-regexp
13066 org-log-note-state)
13067 (format "\"[%s]\""
13068 (substring org-log-note-state 1 -1)))
13069 (t (format "\"%s\"" org-log-note-state))))
13070 (cons "%S"
13071 (cond
13072 ((not org-log-note-previous-state) "")
13073 ((string-match-p org-ts-regexp
13074 org-log-note-previous-state)
13075 (format "\"[%s]\""
13076 (substring
13077 org-log-note-previous-state 1 -1)))
13078 (t (format "\"%s\""
13079 org-log-note-previous-state)))))))
13080 (when lines (setq note (concat note " \\\\")))
13081 (push note lines))
13082 (when (and lines (not org-note-abort))
13083 (with-current-buffer (marker-buffer org-log-note-marker)
13084 (org-with-wide-buffer
13085 ;; Find location for the new note.
13086 (goto-char org-log-note-marker)
13087 (set-marker org-log-note-marker nil)
13088 ;; Note associated to a clock is to be located right after
13089 ;; the clock. Do not move point.
13090 (unless (eq org-log-note-purpose 'clock-out)
13091 (goto-char (org-log-beginning t)))
13092 ;; Make sure point is at the beginning of an empty line.
13093 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13094 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13095 ;; In an existing list, add a new item at the top level.
13096 ;; Otherwise, indent line like a regular one.
13097 (let ((itemp (org-in-item-p)))
13098 (if itemp
13099 (indent-line-to
13100 (let ((struct (save-excursion
13101 (goto-char itemp) (org-list-struct))))
13102 (org-list-get-ind (org-list-get-top-point struct) struct)))
13103 (org-indent-line)))
13104 (insert (org-list-bullet-string "-") (pop lines))
13105 (let ((ind (org-list-item-body-column (line-beginning-position))))
13106 (dolist (line lines)
13107 (insert "\n")
13108 (indent-line-to ind)
13109 (insert line)))
13110 (message "Note stored")
13111 (org-back-to-heading t)
13112 (org-cycle-hide-drawers 'children))
13113 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13114 ;; from within `org-add-log-note' because `buffer-undo-list'
13115 ;; is then modified outside of `org-with-remote-undo'.
13116 (when (eq this-command 'org-agenda-todo)
13117 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13118 ;; Don't add undo information when called from `org-agenda-todo'.
13119 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13120 (set-window-configuration org-log-note-window-configuration)
13121 (with-current-buffer (marker-buffer org-log-note-return-to)
13122 (goto-char org-log-note-return-to))
13123 (move-marker org-log-note-return-to nil)
13124 (when org-log-post-message (message "%s" org-log-post-message))))
13126 (defun org-remove-empty-drawer-at (pos)
13127 "Remove an empty drawer at position POS.
13128 POS may also be a marker."
13129 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13130 (org-with-wide-buffer
13131 (goto-char pos)
13132 (let ((drawer (org-element-at-point)))
13133 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13134 (not (org-element-property :contents-begin drawer)))
13135 (delete-region (org-element-property :begin drawer)
13136 (progn (goto-char (org-element-property :end drawer))
13137 (skip-chars-backward " \r\t\n")
13138 (forward-line)
13139 (point))))))))
13141 (defvar org-ts-type nil)
13142 (defun org-sparse-tree (&optional arg type)
13143 "Create a sparse tree, prompt for the details.
13144 This command can create sparse trees. You first need to select the type
13145 of match used to create the tree:
13147 t Show all TODO entries.
13148 T Show entries with a specific TODO keyword.
13149 m Show entries selected by a tags/property match.
13150 p Enter a property name and its value (both with completion on existing
13151 names/values) and show entries with that property.
13152 r Show entries matching a regular expression (`/' can be used as well).
13153 b Show deadlines and scheduled items before a date.
13154 a Show deadlines and scheduled items after a date.
13155 d Show deadlines due within `org-deadline-warning-days'.
13156 D Show deadlines and scheduled items between a date range."
13157 (interactive "P")
13158 (setq type (or type org-sparse-tree-default-date-type))
13159 (setq org-ts-type type)
13160 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13161 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13162 \[c]ycle through date types: %s"
13163 (cl-case type
13164 (all "all timestamps")
13165 (scheduled "only scheduled")
13166 (deadline "only deadline")
13167 (active "only active timestamps")
13168 (inactive "only inactive timestamps")
13169 (closed "with a closed time-stamp")
13170 (otherwise "scheduled/deadline")))
13171 (let ((answer (read-char-exclusive)))
13172 (cl-case answer
13174 (org-sparse-tree
13176 (cadr
13177 (memq type '(nil all scheduled deadline active inactive closed)))))
13178 (?d (call-interactively 'org-check-deadlines))
13179 (?b (call-interactively 'org-check-before-date))
13180 (?a (call-interactively 'org-check-after-date))
13181 (?D (call-interactively 'org-check-dates-range))
13182 (?t (call-interactively 'org-show-todo-tree))
13183 (?T (org-show-todo-tree '(4)))
13184 (?m (call-interactively 'org-match-sparse-tree))
13185 ((?p ?P)
13186 (let* ((kwd (completing-read
13187 "Property: " (mapcar #'list (org-buffer-property-keys))))
13188 (value (completing-read
13189 "Value: " (mapcar #'list (org-property-values kwd)))))
13190 (unless (string-match "\\`{.*}\\'" value)
13191 (setq value (concat "\"" value "\"")))
13192 (org-match-sparse-tree arg (concat kwd "=" value))))
13193 ((?r ?R ?/) (call-interactively 'org-occur))
13194 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13196 (defvar-local org-occur-highlights nil
13197 "List of overlays used for occur matches.")
13198 (defvar-local org-occur-parameters nil
13199 "Parameters of the active org-occur calls.
13200 This is a list, each call to org-occur pushes as cons cell,
13201 containing the regular expression and the callback, onto the list.
13202 The list can contain several entries if `org-occur' has been called
13203 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13204 will only contain one set of parameters. When the highlights are
13205 removed (for example with `C-c C-c', or with the next edit (depending
13206 on `org-remove-highlights-with-change'), this variable is emptied
13207 as well.")
13209 (defun org-occur (regexp &optional keep-previous callback)
13210 "Make a compact tree which shows all matches of REGEXP.
13212 The tree will show the lines where the regexp matches, and any other context
13213 defined in `org-show-context-detail', which see.
13215 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13216 done by a previous call to `org-occur' will be kept, to allow stacking of
13217 calls to this command.
13219 Optional argument CALLBACK can be a function of no argument. In this case,
13220 it is called with point at the end of the match, match data being set
13221 accordingly. Current match is shown only if the return value is non-nil.
13222 The function must neither move point nor alter narrowing."
13223 (interactive "sRegexp: \nP")
13224 (when (equal regexp "")
13225 (user-error "Regexp cannot be empty"))
13226 (unless keep-previous
13227 (org-remove-occur-highlights nil nil t))
13228 (push (cons regexp callback) org-occur-parameters)
13229 (let ((cnt 0))
13230 (save-excursion
13231 (goto-char (point-min))
13232 (when (or (not keep-previous) ; do not want to keep
13233 (not org-occur-highlights)) ; no previous matches
13234 ;; hide everything
13235 (org-overview))
13236 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13237 (isearch-no-upper-case-p regexp t)
13238 org-occur-case-fold-search)))
13239 (while (re-search-forward regexp nil t)
13240 (when (or (not callback)
13241 (save-match-data (funcall callback)))
13242 (setq cnt (1+ cnt))
13243 (when org-highlight-sparse-tree-matches
13244 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13245 (org-show-context 'occur-tree)))))
13246 (when org-remove-highlights-with-change
13247 (add-hook 'before-change-functions 'org-remove-occur-highlights
13248 nil 'local))
13249 (unless org-sparse-tree-open-archived-trees
13250 (org-hide-archived-subtrees (point-min) (point-max)))
13251 (run-hooks 'org-occur-hook)
13252 (when (called-interactively-p 'interactive)
13253 (message "%d match(es) for regexp %s" cnt regexp))
13254 cnt))
13256 (defun org-occur-next-match (&optional n _reset)
13257 "Function for `next-error-function' to find sparse tree matches.
13258 N is the number of matches to move, when negative move backwards.
13259 This function always goes back to the starting point when no
13260 match is found."
13261 (let* ((limit (if (< n 0) (point-min) (point-max)))
13262 (search-func (if (< n 0)
13263 'previous-single-char-property-change
13264 'next-single-char-property-change))
13265 (n (abs n))
13266 (pos (point))
13268 (catch 'exit
13269 (while (setq p1 (funcall search-func (point) 'org-type))
13270 (when (equal p1 limit)
13271 (goto-char pos)
13272 (user-error "No more matches"))
13273 (when (equal (get-char-property p1 'org-type) 'org-occur)
13274 (setq n (1- n))
13275 (when (= n 0)
13276 (goto-char p1)
13277 (throw 'exit (point))))
13278 (goto-char p1))
13279 (goto-char p1)
13280 (user-error "No more matches"))))
13282 (defun org-show-context (&optional key)
13283 "Make sure point and context are visible.
13284 Optional argument KEY, when non-nil, is a symbol. See
13285 `org-show-context-detail' for allowed values and how much is to
13286 be shown."
13287 (org-show-set-visibility
13288 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13289 ((cdr (assq key org-show-context-detail)))
13290 (t (cdr (assq 'default org-show-context-detail))))))
13292 (defun org-show-set-visibility (detail)
13293 "Set visibility around point according to DETAIL.
13294 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13295 `tree', `canonical' or t. See `org-show-context-detail' for more
13296 information."
13297 ;; Show current heading and possibly its entry, following headline
13298 ;; or all children.
13299 (if (and (org-at-heading-p) (not (eq detail 'local)))
13300 (org-flag-heading nil)
13301 (org-show-entry)
13302 ;; If point is hidden within a drawer or a block, make sure to
13303 ;; expose it.
13304 (dolist (o (overlays-at (point)))
13305 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13306 (delete-overlay o)))
13307 (unless (org-before-first-heading-p)
13308 (org-with-limited-levels
13309 (cl-case detail
13310 ((tree canonical t) (org-show-children))
13311 ((nil minimal ancestors))
13312 (t (save-excursion
13313 (outline-next-heading)
13314 (org-flag-heading nil)))))))
13315 ;; Show all siblings.
13316 (when (eq detail 'lineage) (org-show-siblings))
13317 ;; Show ancestors, possibly with their children.
13318 (when (memq detail '(ancestors lineage tree canonical t))
13319 (save-excursion
13320 (while (org-up-heading-safe)
13321 (org-flag-heading nil)
13322 (when (memq detail '(canonical t)) (org-show-entry))
13323 (when (memq detail '(tree canonical t)) (org-show-children))))))
13325 (defvar org-reveal-start-hook nil
13326 "Hook run before revealing a location.")
13328 (defun org-reveal (&optional siblings)
13329 "Show current entry, hierarchy above it, and the following headline.
13331 This can be used to show a consistent set of context around
13332 locations exposed with `org-show-context'.
13334 With optional argument SIBLINGS, on each level of the hierarchy all
13335 siblings are shown. This repairs the tree structure to what it would
13336 look like when opened with hierarchical calls to `org-cycle'.
13338 With a \\[universal-argument] \\[universal-argument] prefix, \
13339 go to the parent and show the entire tree."
13340 (interactive "P")
13341 (run-hooks 'org-reveal-start-hook)
13342 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13343 ((equal siblings '(16))
13344 (save-excursion
13345 (when (org-up-heading-safe)
13346 (org-show-subtree)
13347 (run-hook-with-args 'org-cycle-hook 'subtree))))
13348 (t (org-show-set-visibility 'lineage))))
13350 (defun org-highlight-new-match (beg end)
13351 "Highlight from BEG to END and mark the highlight is an occur headline."
13352 (let ((ov (make-overlay beg end)))
13353 (overlay-put ov 'face 'secondary-selection)
13354 (overlay-put ov 'org-type 'org-occur)
13355 (push ov org-occur-highlights)))
13357 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13358 "Remove the occur highlights from the buffer.
13359 BEG and END are ignored. If NOREMOVE is nil, remove this function
13360 from the `before-change-functions' in the current buffer."
13361 (interactive)
13362 (unless org-inhibit-highlight-removal
13363 (mapc #'delete-overlay org-occur-highlights)
13364 (setq org-occur-highlights nil)
13365 (setq org-occur-parameters nil)
13366 (unless noremove
13367 (remove-hook 'before-change-functions
13368 'org-remove-occur-highlights 'local))))
13370 ;;;; Priorities
13372 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13373 "Regular expression matching the priority indicator.")
13375 (defvar org-remove-priority-next-time nil)
13377 (defun org-priority-up ()
13378 "Increase the priority of the current item."
13379 (interactive)
13380 (org-priority 'up))
13382 (defun org-priority-down ()
13383 "Decrease the priority of the current item."
13384 (interactive)
13385 (org-priority 'down))
13387 (defun org-priority (&optional action _show)
13388 "Change the priority of an item.
13389 ACTION can be `set', `up', `down', or a character."
13390 (interactive "P")
13391 (if (equal action '(4))
13392 (org-show-priority)
13393 (unless org-enable-priority-commands
13394 (user-error "Priority commands are disabled"))
13395 (setq action (or action 'set))
13396 (let (current new news have remove)
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (when (looking-at org-priority-regexp)
13400 (setq current (string-to-char (match-string 2))
13401 have t))
13402 (cond
13403 ((eq action 'remove)
13404 (setq remove t new ?\ ))
13405 ((or (eq action 'set)
13406 (integerp action))
13407 (if (not (eq action 'set))
13408 (setq new action)
13409 (message "Priority %c-%c, SPC to remove: "
13410 org-highest-priority org-lowest-priority)
13411 (save-match-data
13412 (setq new (read-char-exclusive))))
13413 (when (and (= (upcase org-highest-priority) org-highest-priority)
13414 (= (upcase org-lowest-priority) org-lowest-priority))
13415 (setq new (upcase new)))
13416 (cond ((equal new ?\ ) (setq remove t))
13417 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13418 (user-error "Priority must be between `%c' and `%c'"
13419 org-highest-priority org-lowest-priority))))
13420 ((eq action 'up)
13421 (setq new (if have
13422 (1- current) ; normal cycling
13423 ;; last priority was empty
13424 (if (eq last-command this-command)
13425 org-lowest-priority ; wrap around empty to lowest
13426 ;; default
13427 (if org-priority-start-cycle-with-default
13428 org-default-priority
13429 (1- org-default-priority))))))
13430 ((eq action 'down)
13431 (setq new (if have
13432 (1+ current) ; normal cycling
13433 ;; last priority was empty
13434 (if (eq last-command this-command)
13435 org-highest-priority ; wrap around empty to highest
13436 ;; default
13437 (if org-priority-start-cycle-with-default
13438 org-default-priority
13439 (1+ org-default-priority))))))
13440 (t (user-error "Invalid action")))
13441 (when (or (< (upcase new) org-highest-priority)
13442 (> (upcase new) org-lowest-priority))
13443 (if (and (memq action '(up down))
13444 (not have) (not (eq last-command this-command)))
13445 ;; `new' is from default priority
13446 (error
13447 "The default can not be set, see `org-default-priority' why")
13448 ;; normal cycling: `new' is beyond highest/lowest priority
13449 ;; and is wrapped around to the empty priority
13450 (setq remove t)))
13451 (setq news (format "%c" new))
13452 (if have
13453 (if remove
13454 (replace-match "" t t nil 1)
13455 (replace-match news t t nil 2))
13456 (if remove
13457 (user-error "No priority cookie found in line")
13458 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13459 (if (match-end 2)
13460 (progn
13461 (goto-char (match-end 2))
13462 (insert " [#" news "]"))
13463 (goto-char (match-beginning 3))
13464 (insert "[#" news "] "))))
13465 (org-set-tags nil 'align))
13466 (if remove
13467 (message "Priority removed")
13468 (message "Priority of current item set to %s" news)))))
13470 (defun org-show-priority ()
13471 "Show the priority of the current item.
13472 This priority is composed of the main priority given with the [#A] cookies,
13473 and by additional input from the age of a schedules or deadline entry."
13474 (interactive)
13475 (let ((pri (if (eq major-mode 'org-agenda-mode)
13476 (org-get-at-bol 'priority)
13477 (save-excursion
13478 (save-match-data
13479 (beginning-of-line)
13480 (and (looking-at org-heading-regexp)
13481 (org-get-priority (match-string 0))))))))
13482 (message "Priority is %d" (if pri pri -1000))))
13484 (defun org-get-priority (s)
13485 "Find priority cookie and return priority."
13486 (save-match-data
13487 (if (functionp org-get-priority-function)
13488 (funcall org-get-priority-function)
13489 (if (not (string-match org-priority-regexp s))
13490 (* 1000 (- org-lowest-priority org-default-priority))
13491 (* 1000 (- org-lowest-priority
13492 (string-to-char (match-string 2 s))))))))
13494 ;;;; Tags
13496 (defvar org-agenda-archives-mode)
13497 (defvar org-map-continue-from nil
13498 "Position from where mapping should continue.
13499 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13501 (defvar org-scanner-tags nil
13502 "The current tag list while the tags scanner is running.")
13504 (defvar org-trust-scanner-tags nil
13505 "Should `org-get-tags-at' use the tags for the scanner.
13506 This is for internal dynamical scoping only.
13507 When this is non-nil, the function `org-get-tags-at' will return the value
13508 of `org-scanner-tags' instead of building the list by itself. This
13509 can lead to large speed-ups when the tags scanner is used in a file with
13510 many entries, and when the list of tags is retrieved, for example to
13511 obtain a list of properties. Building the tags list for each entry in such
13512 a file becomes an N^2 operation - but with this variable set, it scales
13513 as N.")
13515 (defvar org--matcher-tags-todo-only nil)
13517 (defun org-scan-tags (action matcher todo-only &optional start-level)
13518 "Scan headline tags with inheritance and produce output ACTION.
13520 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13521 or `agenda' to produce an entry list for an agenda view. It can also be
13522 a Lisp form or a function that should be called at each matched headline, in
13523 this case the return value is a list of all return values from these calls.
13525 MATCHER is a function accepting three arguments, returning
13526 a non-nil value whenever a given set of tags qualifies a headline
13527 for inclusion. See `org-make-tags-matcher' for more information.
13528 As a special case, it can also be set to t (respectively nil) in
13529 order to match all (respectively none) headline.
13531 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13532 included in the output.
13534 START-LEVEL can be a string with asterisks, reducing the scope to
13535 headlines matching this string."
13536 (require 'org-agenda)
13537 (let* ((re (concat "^"
13538 (if start-level
13539 ;; Get the correct level to match
13540 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13541 org-outline-regexp)
13542 " *\\(\\<\\("
13543 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13544 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13545 (props (list 'face 'default
13546 'done-face 'org-agenda-done
13547 'undone-face 'default
13548 'mouse-face 'highlight
13549 'org-not-done-regexp org-not-done-regexp
13550 'org-todo-regexp org-todo-regexp
13551 'org-complex-heading-regexp org-complex-heading-regexp
13552 'help-echo
13553 (format "mouse-2 or RET jump to org file %s"
13554 (abbreviate-file-name
13555 (or (buffer-file-name (buffer-base-buffer))
13556 (buffer-name (buffer-base-buffer)))))))
13557 (org-map-continue-from nil)
13558 lspos tags tags-list
13559 (tags-alist (list (cons 0 org-file-tags)))
13560 (llast 0) rtn rtn1 level category i txt
13561 todo marker entry priority
13562 ts-date ts-date-type ts-date-pair)
13563 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13564 (setq action (list 'lambda nil action)))
13565 (save-excursion
13566 (goto-char (point-min))
13567 (when (eq action 'sparse-tree)
13568 (org-overview)
13569 (org-remove-occur-highlights))
13570 (while (let (case-fold-search)
13571 (re-search-forward re nil t))
13572 (setq org-map-continue-from nil)
13573 (catch :skip
13574 (setq todo
13575 ;; TODO: is the 1-2 difference a bug?
13576 (when (match-end 1) (match-string-no-properties 2))
13577 tags (when (match-end 4) (match-string-no-properties 4)))
13578 (goto-char (setq lspos (match-beginning 0)))
13579 (setq level (org-reduced-level (org-outline-level))
13580 category (org-get-category))
13581 (when (eq action 'agenda)
13582 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13583 ts-date (car ts-date-pair)
13584 ts-date-type (cdr ts-date-pair)))
13585 (setq i llast llast level)
13586 ;; remove tag lists from same and sublevels
13587 (while (>= i level)
13588 (when (setq entry (assoc i tags-alist))
13589 (setq tags-alist (delete entry tags-alist)))
13590 (setq i (1- i)))
13591 ;; add the next tags
13592 (when tags
13593 (setq tags (org-split-string tags ":")
13594 tags-alist
13595 (cons (cons level tags) tags-alist)))
13596 ;; compile tags for current headline
13597 (setq tags-list
13598 (if org-use-tag-inheritance
13599 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13600 tags)
13601 org-scanner-tags tags-list)
13602 (when org-use-tag-inheritance
13603 (setcdr (car tags-alist)
13604 (mapcar (lambda (x)
13605 (setq x (copy-sequence x))
13606 (org-add-prop-inherited x))
13607 (cdar tags-alist))))
13608 (when (and tags org-use-tag-inheritance
13609 (or (not (eq t org-use-tag-inheritance))
13610 org-tags-exclude-from-inheritance))
13611 ;; Selective inheritance, remove uninherited ones.
13612 (setcdr (car tags-alist)
13613 (org-remove-uninherited-tags (cdar tags-alist))))
13614 (when (and
13616 ;; eval matcher only when the todo condition is OK
13617 (and (or (not todo-only) (member todo org-todo-keywords-1))
13618 (if (functionp matcher)
13619 (let ((case-fold-search t) (org-trust-scanner-tags t))
13620 (funcall matcher todo tags-list level))
13621 matcher))
13623 ;; Call the skipper, but return t if it does not
13624 ;; skip, so that the `and' form continues evaluating.
13625 (progn
13626 (unless (eq action 'sparse-tree) (org-agenda-skip))
13629 ;; Check if timestamps are deselecting this entry
13630 (or (not todo-only)
13631 (and (member todo org-todo-keywords-1)
13632 (or (not org-agenda-tags-todo-honor-ignore-options)
13633 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13635 ;; select this headline
13636 (cond
13637 ((eq action 'sparse-tree)
13638 (and org-highlight-sparse-tree-matches
13639 (org-get-heading) (match-end 0)
13640 (org-highlight-new-match
13641 (match-beginning 1) (match-end 1)))
13642 (org-show-context 'tags-tree))
13643 ((eq action 'agenda)
13644 (setq txt (org-agenda-format-item
13646 (concat
13647 (if (eq org-tags-match-list-sublevels 'indented)
13648 (make-string (1- level) ?.) "")
13649 (org-get-heading))
13650 (make-string level ?\s)
13651 category
13652 tags-list)
13653 priority (org-get-priority txt))
13654 (goto-char lspos)
13655 (setq marker (org-agenda-new-marker))
13656 (org-add-props txt props
13657 'org-marker marker 'org-hd-marker marker 'org-category category
13658 'todo-state todo
13659 'ts-date ts-date
13660 'priority priority
13661 'type (concat "tagsmatch" ts-date-type))
13662 (push txt rtn))
13663 ((functionp action)
13664 (setq org-map-continue-from nil)
13665 (save-excursion
13666 (setq rtn1 (funcall action))
13667 (push rtn1 rtn)))
13668 (t (user-error "Invalid action")))
13670 ;; if we are to skip sublevels, jump to end of subtree
13671 (unless org-tags-match-list-sublevels
13672 (org-end-of-subtree t)
13673 (backward-char 1))))
13674 ;; Get the correct position from where to continue
13675 (if org-map-continue-from
13676 (goto-char org-map-continue-from)
13677 (and (= (point) lspos) (end-of-line 1)))))
13678 (when (and (eq action 'sparse-tree)
13679 (not org-sparse-tree-open-archived-trees))
13680 (org-hide-archived-subtrees (point-min) (point-max)))
13681 (nreverse rtn)))
13683 (defun org-remove-uninherited-tags (tags)
13684 "Remove all tags that are not inherited from the list TAGS."
13685 (cond
13686 ((eq org-use-tag-inheritance t)
13687 (if org-tags-exclude-from-inheritance
13688 (org-delete-all org-tags-exclude-from-inheritance tags)
13689 tags))
13690 ((not org-use-tag-inheritance) nil)
13691 ((stringp org-use-tag-inheritance)
13692 (delq nil (mapcar
13693 (lambda (x)
13694 (if (and (string-match org-use-tag-inheritance x)
13695 (not (member x org-tags-exclude-from-inheritance)))
13696 x nil))
13697 tags)))
13698 ((listp org-use-tag-inheritance)
13699 (delq nil (mapcar
13700 (lambda (x)
13701 (if (member x org-use-tag-inheritance) x nil))
13702 tags)))))
13704 (defun org-match-sparse-tree (&optional todo-only match)
13705 "Create a sparse tree according to tags string MATCH.
13707 MATCH is a string with match syntax. It can contain a selection
13708 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13709 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13710 those. See the manual for details.
13712 If optional argument TODO-ONLY is non-nil, only select lines that
13713 are also TODO tasks."
13714 (interactive "P")
13715 (org-agenda-prepare-buffers (list (current-buffer)))
13716 (let ((org--matcher-tags-todo-only todo-only))
13717 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13718 org--matcher-tags-todo-only)))
13720 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13722 (defvar org-cached-props nil)
13723 (defun org-cached-entry-get (pom property)
13724 (if (or (eq t org-use-property-inheritance)
13725 (and (stringp org-use-property-inheritance)
13726 (let ((case-fold-search t))
13727 (string-match-p org-use-property-inheritance property)))
13728 (and (listp org-use-property-inheritance)
13729 (member-ignore-case property org-use-property-inheritance)))
13730 ;; Caching is not possible, check it directly.
13731 (org-entry-get pom property 'inherit)
13732 ;; Get all properties, so we can do complicated checks easily.
13733 (cdr (assoc-string property
13734 (or org-cached-props
13735 (setq org-cached-props (org-entry-properties pom)))
13736 t))))
13738 (defun org-global-tags-completion-table (&optional files)
13739 "Return the list of all tags in all agenda buffer/files.
13740 Optional FILES argument is a list of files which can be used
13741 instead of the agenda files."
13742 (save-excursion
13743 (org-uniquify
13744 (delq nil
13745 (apply #'append
13746 (mapcar
13747 (lambda (file)
13748 (set-buffer (find-file-noselect file))
13749 (mapcar (lambda (x)
13750 (and (stringp (car-safe x))
13751 (list (car-safe x))))
13752 (or org-current-tag-alist (org-get-buffer-tags))))
13753 (if (car-safe files) files
13754 (org-agenda-files))))))))
13756 (defun org-make-tags-matcher (match)
13757 "Create the TAGS/TODO matcher form for the selection string MATCH.
13759 Returns a cons of the selection string MATCH and a function
13760 implementing the matcher.
13762 The matcher is to be called at an Org entry, with point on the
13763 headline, and returns non-nil if the entry matches the selection
13764 string MATCH. It must be called with three arguments: the TODO
13765 keyword at the entry (or nil if none), the list of all tags at
13766 the entry including inherited ones and the reduced level of the
13767 headline. Additionally, the category of the entry, if any, must
13768 be specified as the text property `org-category' on the headline.
13770 This function sets the variable `org--matcher-tags-todo-only' to
13771 a non-nil value if the matcher restricts matching to TODO
13772 entries, otherwise it is not touched.
13774 See also `org-scan-tags'."
13775 (unless match
13776 ;; Get a new match request, with completion against the global
13777 ;; tags table and the local tags in current buffer.
13778 (let ((org-last-tags-completion-table
13779 (org-uniquify
13780 (delq nil (append (org-get-buffer-tags)
13781 (org-global-tags-completion-table))))))
13782 (setq match
13783 (completing-read
13784 "Match: "
13785 'org-tags-completion-function nil nil nil 'org-tags-history))))
13787 (let ((match0 match)
13788 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13789 (start 0)
13790 tagsmatch todomatch tagsmatcher todomatcher)
13792 ;; Expand group tags.
13793 (setq match (org-tags-expand match))
13795 ;; Check if there is a TODO part of this match, which would be the
13796 ;; part after a "/". To make sure that this slash is not part of
13797 ;; a property value to be matched against, we also check that
13798 ;; there is no / after that slash. First, find the last slash.
13799 (let ((s 0))
13800 (while (string-match "/+" match s)
13801 (setq start (match-beginning 0))
13802 (setq s (match-end 0))))
13803 (if (and (string-match "/+" match start)
13804 (not (string-match-p "\"" match start)))
13805 ;; Match contains also a TODO-matching request.
13806 (progn
13807 (setq tagsmatch (substring match 0 (match-beginning 0)))
13808 (setq todomatch (substring match (match-end 0)))
13809 (when (string-prefix-p "!" todomatch)
13810 (setq org--matcher-tags-todo-only t)
13811 (setq todomatch (substring todomatch 1)))
13812 (when (string-match "\\`\\s-*\\'" todomatch)
13813 (setq todomatch nil)))
13814 ;; Only matching tags.
13815 (setq tagsmatch match)
13816 (setq todomatch nil))
13818 ;; Make the tags matcher.
13819 (when (org-string-nw-p tagsmatch)
13820 (let ((orlist nil)
13821 (orterms (org-split-string tagsmatch "|"))
13822 term)
13823 (while (setq term (pop orterms))
13824 (while (and (equal (substring term -1) "\\") orterms)
13825 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13826 (while (string-match re term)
13827 (let* ((rest (substring term (match-end 0)))
13828 (minus (and (match-end 1)
13829 (equal (match-string 1 term) "-")))
13830 (tag (save-match-data
13831 (replace-regexp-in-string
13832 "\\\\-" "-" (match-string 2 term))))
13833 (regexp (eq (string-to-char tag) ?{))
13834 (levelp (match-end 4))
13835 (propp (match-end 5))
13837 (cond
13838 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13839 (levelp
13840 `(,(org-op-to-function (match-string 3 term))
13841 level
13842 ,(string-to-number (match-string 4 term))))
13843 (propp
13844 (let* ((gv (pcase (upcase (match-string 5 term))
13845 ("CATEGORY"
13846 '(get-text-property (point) 'org-category))
13847 ("TODO" 'todo)
13848 (p `(org-cached-entry-get nil ,p))))
13849 (pv (match-string 7 term))
13850 (regexp (eq (string-to-char pv) ?{))
13851 (strp (eq (string-to-char pv) ?\"))
13852 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13853 (po (org-op-to-function (match-string 6 term)
13854 (if timep 'time strp))))
13855 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13856 (when timep (setq pv (org-matcher-time pv)))
13857 (cond ((and regexp (eq po 'org<>))
13858 `(not (string-match ,pv (or ,gv ""))))
13859 (regexp `(string-match ,pv (or ,gv "")))
13860 (strp `(,po (or ,gv "") ,pv))
13862 `(,po
13863 (string-to-number (or ,gv ""))
13864 ,(string-to-number pv))))))
13865 (t `(member ,tag tags-list)))))
13866 (push (if minus `(not ,mm) mm) tagsmatcher)
13867 (setq term rest)))
13868 (push `(and ,@tagsmatcher) orlist)
13869 (setq tagsmatcher nil))
13870 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13872 ;; Make the TODO matcher.
13873 (when (org-string-nw-p todomatch)
13874 (let ((orlist nil))
13875 (dolist (term (org-split-string todomatch "|"))
13876 (while (string-match re term)
13877 (let* ((minus (and (match-end 1)
13878 (equal (match-string 1 term) "-")))
13879 (kwd (match-string 2 term))
13880 (regexp (eq (string-to-char kwd) ?{))
13881 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13882 `(equal todo ,kwd))))
13883 (push (if minus `(not ,mm) mm) todomatcher))
13884 (setq term (substring term (match-end 0))))
13885 (push (if (> (length todomatcher) 1)
13886 (cons 'and todomatcher)
13887 (car todomatcher))
13888 orlist)
13889 (setq todomatcher nil))
13890 (setq todomatcher (cons 'or orlist))))
13892 ;; Return the string and function of the matcher. If no
13893 ;; tags-specific or todo-specific matcher exists, match
13894 ;; everything.
13895 (let ((matcher (if (and tagsmatcher todomatcher)
13896 `(and ,tagsmatcher ,todomatcher)
13897 (or tagsmatcher todomatcher t))))
13898 (when org--matcher-tags-todo-only
13899 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13900 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13902 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13903 "Expand group tags in MATCH.
13905 This replaces every group tag in MATCH with a regexp tag search.
13906 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13907 will be replaced like this:
13909 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13910 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13911 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13913 Replacing by a regexp preserves the structure of the match.
13914 E.g., this expansion
13916 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13918 will match anything tagged with \"Lab\" and \"Home\", or tagged
13919 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13921 A group tag in MATCH can contain regular expressions of its own.
13922 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13923 will be replaced like this:
13925 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13927 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13928 assumed to be a single group tag, and the function will return
13929 the list of tags in this group.
13931 When DOWNCASE is non-nil, expand downcased TAGS."
13932 (if org-group-tags
13933 (let* ((case-fold-search t)
13934 (stable org-mode-syntax-table)
13935 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13936 (taggroups (if downcased
13937 (mapcar (lambda (tg) (mapcar #'downcase tg))
13938 taggroups)
13939 taggroups))
13940 (taggroups-keys (mapcar #'car taggroups))
13941 (return-match (if downcased (downcase match) match))
13942 (count 0)
13943 (work-already-expanded tags-already-expanded)
13944 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13945 ;; @ and _ are allowed as word-components in tags.
13946 (modify-syntax-entry ?@ "w" stable)
13947 (modify-syntax-entry ?_ "w" stable)
13948 ;; Temporarily replace regexp-expressions in the match-expression.
13949 (while (string-match "{.+?}" return-match)
13950 (cl-incf count)
13951 (push (match-string 0 return-match) regexps-in-match)
13952 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13953 (while (and taggroups-keys
13954 (with-syntax-table stable
13955 (string-match
13956 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13957 (regexp-opt taggroups-keys) "\\>\\)")
13958 return-match)))
13959 (let* ((dir (match-string 1 return-match))
13960 (tag (match-string 2 return-match))
13961 (tag (if downcased (downcase tag) tag)))
13962 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13963 (member tag work-already-expanded))
13964 (setq tags-in-group (assoc tag taggroups))
13965 (push tag work-already-expanded)
13966 ;; Recursively expand each tag in the group, if the tag hasn't
13967 ;; already been expanded. Restore the match-data after all recursive calls.
13968 (save-match-data
13969 (let (tags-expanded)
13970 (dolist (x (cdr tags-in-group))
13971 (if (and (member x taggroups-keys)
13972 (not (member x work-already-expanded)))
13973 (setq tags-expanded
13974 (delete-dups
13975 (append
13976 (org-tags-expand x t downcased
13977 work-already-expanded)
13978 tags-expanded)))
13979 (setq tags-expanded
13980 (append (list x) tags-expanded)))
13981 (setq work-already-expanded
13982 (delete-dups
13983 (append tags-expanded
13984 work-already-expanded))))
13985 (setq tags-in-group
13986 (delete-dups (cons (car tags-in-group)
13987 tags-expanded)))))
13988 ;; Filter tag-regexps from tags.
13989 (setq regexp-in-group-escaped
13990 (delq nil (mapcar (lambda (x)
13991 (if (stringp x)
13992 (and (equal "{" (substring x 0 1))
13993 (equal "}" (substring x -1))
13996 tags-in-group))
13997 regexp-in-group
13998 (mapcar (lambda (x)
13999 (substring x 1 -1))
14000 regexp-in-group-escaped)
14001 tags-in-group
14002 (delq nil (mapcar (lambda (x)
14003 (if (stringp x)
14004 (and (not (equal "{" (substring x 0 1)))
14005 (not (equal "}" (substring x -1)))
14008 tags-in-group)))
14009 ;; If single-as-list, do no more in the while-loop.
14010 (if (not single-as-list)
14011 (progn
14012 (when regexp-in-group
14013 (setq regexp-in-group
14014 (concat "\\|"
14015 (mapconcat 'identity regexp-in-group
14016 "\\|"))))
14017 (setq tags-in-group
14018 (concat dir
14019 "{\\<"
14020 (regexp-opt tags-in-group)
14021 "\\>"
14022 regexp-in-group
14023 "}"))
14024 (when (stringp tags-in-group)
14025 (org-add-props tags-in-group '(grouptag t)))
14026 (setq return-match
14027 (replace-match tags-in-group t t return-match)))
14028 (setq tags-in-group
14029 (append regexp-in-group-escaped tags-in-group))))
14030 (setq taggroups-keys (delete tag taggroups-keys))))
14031 ;; Add the regular expressions back into the match-expression again.
14032 (while regexps-in-match
14033 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14034 (pop regexps-in-match)
14035 return-match t t))
14036 (cl-decf count))
14037 (if single-as-list
14038 (if tags-in-group tags-in-group (list return-match))
14039 return-match))
14040 (if single-as-list
14041 (list (if downcased (downcase match) match))
14042 match)))
14044 (defun org-op-to-function (op &optional stringp)
14045 "Turn an operator into the appropriate function."
14046 (setq op
14047 (cond
14048 ((equal op "<" ) '(< string< org-time<))
14049 ((equal op ">" ) '(> org-string> org-time>))
14050 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14051 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14052 ((member op '("=" "==")) '(= string= org-time=))
14053 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14054 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14056 (defun org<> (a b) (not (= a b)))
14057 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14058 (defun org-string>= (a b) (not (string< a b)))
14059 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14060 (defun org-string<> (a b) (not (string= a b)))
14061 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14062 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14063 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14064 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14065 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14066 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14067 (defun org-2ft (s)
14068 "Convert S to a floating point time.
14069 If S is already a number, just return it. If it is a string, parse
14070 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14071 (cond
14072 ((numberp s) s)
14073 ((stringp s)
14074 (condition-case nil
14075 (float-time (apply #'encode-time (org-parse-time-string s)))
14076 (error 0.)))
14077 (t 0.)))
14079 (defun org-time-today ()
14080 "Time in seconds today at 0:00.
14081 Returns the float number of seconds since the beginning of the
14082 epoch to the beginning of today (00:00)."
14083 (float-time (apply 'encode-time
14084 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14086 (defun org-matcher-time (s)
14087 "Interpret a time comparison value."
14088 (save-match-data
14089 (cond
14090 ((string= s "<now>") (float-time))
14091 ((string= s "<today>") (org-time-today))
14092 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14093 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14094 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14095 (+ (org-time-today)
14096 (* (string-to-number (match-string 1 s))
14097 (cdr (assoc (match-string 2 s)
14098 '(("d" . 86400.0) ("w" . 604800.0)
14099 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14100 (t (org-2ft s)))))
14102 (defun org-match-any-p (re list)
14103 "Does re match any element of list?"
14104 (setq list (mapcar (lambda (x) (string-match re x)) list))
14105 (delq nil list))
14107 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14108 (defvar org-tags-overlay (make-overlay 1 1))
14109 (delete-overlay org-tags-overlay)
14111 (defun org-get-local-tags-at (&optional pos)
14112 "Get a list of tags defined in the current headline."
14113 (org-get-tags-at pos 'local))
14115 (defun org-get-local-tags ()
14116 "Get a list of tags defined in the current headline."
14117 (org-get-tags-at nil 'local))
14119 (defun org-get-tags-at (&optional pos local)
14120 "Get a list of all headline tags applicable at POS.
14121 POS defaults to point. If tags are inherited, the list contains
14122 the targets in the same sequence as the headlines appear, i.e.
14123 the tags of the current headline come last.
14124 When LOCAL is non-nil, only return tags from the current headline,
14125 ignore inherited ones."
14126 (interactive)
14127 (if (and org-trust-scanner-tags
14128 (or (not pos) (equal pos (point)))
14129 (not local))
14130 org-scanner-tags
14131 (let (tags ltags lastpos parent)
14132 (save-excursion
14133 (save-restriction
14134 (widen)
14135 (goto-char (or pos (point)))
14136 (save-match-data
14137 (catch 'done
14138 (condition-case nil
14139 (progn
14140 (org-back-to-heading t)
14141 (while (not (equal lastpos (point)))
14142 (setq lastpos (point))
14143 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14144 (setq ltags (org-split-string
14145 (match-string-no-properties 1) ":"))
14146 (when parent
14147 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14148 (setq tags (append
14149 (if parent
14150 (org-remove-uninherited-tags ltags)
14151 ltags)
14152 tags)))
14153 (or org-use-tag-inheritance (throw 'done t))
14154 (when local (throw 'done t))
14155 (or (org-up-heading-safe) (error nil))
14156 (setq parent t)))
14157 (error nil)))))
14158 (if local
14159 tags
14160 (reverse (delete-dups
14161 (reverse (append
14162 (org-remove-uninherited-tags
14163 org-file-tags)
14164 tags)))))))))
14166 (defun org-add-prop-inherited (s)
14167 (add-text-properties 0 (length s) '(inherited t) s)
14170 (defun org-toggle-tag (tag &optional onoff)
14171 "Toggle the tag TAG for the current line.
14172 If ONOFF is `on' or `off', don't toggle but set to this state."
14173 (save-excursion
14174 (org-back-to-heading t)
14175 (let ((current
14176 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14177 (line-end-position) t)
14178 (let ((tags (match-string 1)))
14179 ;; Clear current tags.
14180 (replace-match "")
14181 ;; Reverse the tags list so any new tag is appended to
14182 ;; the current list of tags.
14183 (nreverse (org-split-string tags ":")))))
14184 res)
14185 (pcase onoff
14186 (`off (setq current (delete tag current)))
14187 ((or `on (guard (not (member tag current))))
14188 (setq res t)
14189 (cl-pushnew tag current :test #'equal))
14190 (_ (setq current (delete tag current))))
14191 (end-of-line)
14192 (if current
14193 (progn
14194 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14195 (org-set-tags nil t))
14196 (delete-horizontal-space))
14197 (run-hooks 'org-after-tags-change-hook)
14198 res)))
14200 (defun org--align-tags-here (to-col)
14201 "Align tags on the current headline to TO-COL.
14202 Assume point is on a headline."
14203 (let ((pos (point)))
14204 (beginning-of-line)
14205 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14206 (>= pos (match-beginning 2)))
14207 ;; No tags or point within tags: do not align.
14208 (goto-char pos)
14209 (goto-char (match-beginning 1))
14210 (let ((shift (max (- (if (>= to-col 0) to-col
14211 (- (abs to-col) (string-width (match-string 2))))
14212 (current-column))
14213 1)))
14214 (replace-match (make-string shift ?\s) nil nil nil 1)
14215 ;; Preserve initial position, if possible. In any case, stop
14216 ;; before tags.
14217 (when (< pos (point)) (goto-char pos))))))
14219 (defun org-set-tags-command (&optional arg just-align)
14220 "Call the set-tags command for the current entry."
14221 (interactive "P")
14222 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14223 (org-set-tags arg just-align)
14224 (save-excursion
14225 (unless (and (org-region-active-p)
14226 org-loop-over-headlines-in-active-region)
14227 (org-back-to-heading t))
14228 (org-set-tags arg just-align))))
14230 (defun org-set-tags-to (data)
14231 "Set the tags of the current entry to DATA, replacing the current tags.
14232 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14233 If DATA is nil or the empty string, any tags will be removed."
14234 (interactive "sTags: ")
14235 (setq data
14236 (cond
14237 ((eq data nil) "")
14238 ((equal data "") "")
14239 ((stringp data)
14240 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14241 ":"))
14242 ((listp data)
14243 (concat ":" (mapconcat 'identity data ":") ":"))))
14244 (when data
14245 (save-excursion
14246 (org-back-to-heading t)
14247 (when (let ((case-fold-search nil))
14248 (looking-at org-complex-heading-regexp))
14249 (if (match-end 5)
14250 (progn
14251 (goto-char (match-beginning 5))
14252 (insert data)
14253 (delete-region (point) (point-at-eol))
14254 (org-set-tags nil 'align))
14255 (goto-char (point-at-eol))
14256 (insert " " data)
14257 (org-set-tags nil 'align)))
14258 (beginning-of-line 1)
14259 (when (looking-at ".*?\\([ \t]+\\)$")
14260 (delete-region (match-beginning 1) (match-end 1))))))
14262 (defun org-align-all-tags ()
14263 "Align the tags in all headings."
14264 (interactive)
14265 (save-excursion
14266 (or (ignore-errors (org-back-to-heading t))
14267 (outline-next-heading))
14268 (if (org-at-heading-p)
14269 (org-set-tags t)
14270 (message "No headings"))))
14272 (defvar org-indent-indentation-per-level)
14273 (defun org-set-tags (&optional arg just-align)
14274 "Set the tags for the current headline.
14275 With prefix ARG, realign all tags in headings in the current buffer.
14276 When JUST-ALIGN is non-nil, only align tags."
14277 (interactive "P")
14278 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14279 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14280 'region-start-level
14281 'region))
14282 org-loop-over-headlines-in-active-region)
14283 (org-map-entries
14284 ;; We don't use ARG and JUST-ALIGN here because these args
14285 ;; are not useful when looping over headlines.
14286 #'org-set-tags
14287 org-loop-over-headlines-in-active-region
14289 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14290 (let ((org-setting-tags t))
14291 (if arg
14292 (save-excursion
14293 (goto-char (point-min))
14294 (while (re-search-forward org-outline-regexp-bol nil t)
14295 (org-set-tags nil t)
14296 (end-of-line))
14297 (message "All tags realigned to column %d" org-tags-column))
14298 (let* ((current (org-get-tags-string))
14299 (tags
14300 (if just-align current
14301 ;; Get a new set of tags from the user.
14302 (save-excursion
14303 (let* ((seen)
14304 (table
14305 (setq
14306 org-last-tags-completion-table
14307 ;; Uniquify tags in alists, yet preserve
14308 ;; structure (i.e., keywords).
14309 (delq nil
14310 (mapcar
14311 (lambda (pair)
14312 (let ((head (car pair)))
14313 (cond ((symbolp head) pair)
14314 ((member head seen) nil)
14315 (t (push head seen)
14316 pair))))
14317 (append
14318 (or org-current-tag-alist
14319 (org-get-buffer-tags))
14320 (and
14321 org-complete-tags-always-offer-all-agenda-tags
14322 (org-global-tags-completion-table
14323 (org-agenda-files))))))))
14324 (current-tags (org-split-string current ":"))
14325 (inherited-tags
14326 (nreverse (nthcdr (length current-tags)
14327 (nreverse (org-get-tags-at))))))
14328 (replace-regexp-in-string
14329 "\\([-+&]+\\|,\\)"
14331 (if (or (eq t org-use-fast-tag-selection)
14332 (and org-use-fast-tag-selection
14333 (delq nil (mapcar #'cdr table))))
14334 (org-fast-tag-selection
14335 current-tags inherited-tags table
14336 (and org-fast-tag-selection-include-todo
14337 org-todo-key-alist))
14338 (let ((org-add-colon-after-tag-completion
14339 (< 1 (length table))))
14340 (org-trim
14341 (completing-read
14342 "Tags: "
14343 #'org-tags-completion-function
14344 nil nil current 'org-tags-history))))))))))
14346 (when org-tags-sort-function
14347 (setq tags
14348 (mapconcat
14349 #'identity
14350 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14351 org-tags-sort-function)
14352 ":")))
14354 (if (or (string= ":" tags)
14355 (string= "::" tags))
14356 (setq tags ""))
14357 (if (not (org-string-nw-p tags)) (setq tags "")
14358 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14359 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14361 ;; Insert new tags at the correct column.
14362 (unless (equal current tags)
14363 (save-excursion
14364 (beginning-of-line)
14365 (let ((case-fold-search nil))
14366 (looking-at org-complex-heading-regexp))
14367 ;; Remove current tags, if any.
14368 (when (match-end 5) (replace-match "" nil nil nil 5))
14369 ;; Insert new tags, if any. Otherwise, remove trailing
14370 ;; white spaces.
14371 (end-of-line)
14372 (if (not (equal tags ""))
14373 ;; When text is being inserted on an invisible
14374 ;; region boundary, it can be inadvertently sucked
14375 ;; into invisibility.
14376 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14377 (skip-chars-backward " \t")
14378 (delete-region (point) (line-end-position)))))
14379 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14380 ;; is on.
14381 (unless (equal tags "")
14382 (let* ((level (save-excursion
14383 (beginning-of-line)
14384 (skip-chars-forward "\\*")))
14385 (offset (if (bound-and-true-p org-indent-mode)
14386 (* (1- org-indent-indentation-per-level)
14387 (1- level))
14389 (tags-column
14390 (+ org-tags-column
14391 (if (> org-tags-column 0) (- offset) offset))))
14392 (org--align-tags-here tags-column))))
14393 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14395 (defun org-change-tag-in-region (beg end tag off)
14396 "Add or remove TAG for each entry in the region.
14397 This works in the agenda, and also in an Org buffer."
14398 (interactive
14399 (list (region-beginning) (region-end)
14400 (let ((org-last-tags-completion-table
14401 (if (derived-mode-p 'org-mode)
14402 (org-uniquify
14403 (delq nil (append (org-get-buffer-tags)
14404 (org-global-tags-completion-table))))
14405 (org-global-tags-completion-table))))
14406 (completing-read
14407 "Tag: " 'org-tags-completion-function nil nil nil
14408 'org-tags-history))
14409 (progn
14410 (message "[s]et or [r]emove? ")
14411 (equal (read-char-exclusive) ?r))))
14412 (when (fboundp 'deactivate-mark) (deactivate-mark))
14413 (let ((agendap (equal major-mode 'org-agenda-mode))
14414 l1 l2 m buf pos newhead (cnt 0))
14415 (goto-char end)
14416 (setq l2 (1- (org-current-line)))
14417 (goto-char beg)
14418 (setq l1 (org-current-line))
14419 (cl-loop for l from l1 to l2 do
14420 (org-goto-line l)
14421 (setq m (get-text-property (point) 'org-hd-marker))
14422 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14423 (and agendap m))
14424 (setq buf (if agendap (marker-buffer m) (current-buffer))
14425 pos (if agendap m (point)))
14426 (with-current-buffer buf
14427 (save-excursion
14428 (save-restriction
14429 (goto-char pos)
14430 (setq cnt (1+ cnt))
14431 (org-toggle-tag tag (if off 'off 'on))
14432 (setq newhead (org-get-heading)))))
14433 (and agendap (org-agenda-change-all-lines newhead m))))
14434 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14436 (defun org-tags-completion-function (string _predicate &optional flag)
14437 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14438 (confirm (lambda (x) (stringp (car x)))))
14439 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14440 (setq s1 (match-string 1 string)
14441 s2 (match-string 2 string))
14442 (setq s1 "" s2 string))
14443 (cond
14444 ((eq flag nil)
14445 ;; try completion
14446 (setq rtn (try-completion s2 ctable confirm))
14447 (when (stringp rtn)
14448 (setq rtn
14449 (concat s1 s2 (substring rtn (length s2))
14450 (if (and org-add-colon-after-tag-completion
14451 (assoc rtn ctable))
14452 ":" ""))))
14453 rtn)
14454 ((eq flag t)
14455 ;; all-completions
14456 (all-completions s2 ctable confirm))
14457 ((eq flag 'lambda)
14458 ;; exact match?
14459 (assoc s2 ctable)))))
14461 (defun org-fast-tag-insert (kwd tags face &optional end)
14462 "Insert KDW, and the TAGS, the latter with face FACE.
14463 Also insert END."
14464 (insert (format "%-12s" (concat kwd ":"))
14465 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14466 (or end "")))
14468 (defun org-fast-tag-show-exit (flag)
14469 (save-excursion
14470 (org-goto-line 3)
14471 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14472 (replace-match ""))
14473 (when flag
14474 (end-of-line 1)
14475 (org-move-to-column (- (window-width) 19) t)
14476 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14478 (defun org-set-current-tags-overlay (current prefix)
14479 "Add an overlay to CURRENT tag with PREFIX."
14480 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14481 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14482 (org-overlay-display org-tags-overlay (concat prefix s))))
14484 (defvar org-last-tag-selection-key nil)
14485 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14486 "Fast tag selection with single keys.
14487 CURRENT is the current list of tags in the headline, INHERITED is the
14488 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14489 possibly with grouping information. TODO-TABLE is a similar table with
14490 TODO keywords, should these have keys assigned to them.
14491 If the keys are nil, a-z are automatically assigned.
14492 Returns the new tags string, or nil to not change the current settings."
14493 (let* ((fulltable (append table todo-table))
14494 (maxlen (apply 'max (mapcar
14495 (lambda (x)
14496 (if (stringp (car x)) (string-width (car x)) 0))
14497 fulltable)))
14498 (buf (current-buffer))
14499 (expert (eq org-fast-tag-selection-single-key 'expert))
14500 (buffer-tags nil)
14501 (fwidth (+ maxlen 3 1 3))
14502 (ncol (/ (- (window-width) 4) fwidth))
14503 (i-face 'org-done)
14504 (c-face 'org-todo)
14505 tg cnt e c char c1 c2 ntable tbl rtn
14506 ov-start ov-end ov-prefix
14507 (exit-after-next org-fast-tag-selection-single-key)
14508 (done-keywords org-done-keywords)
14509 groups ingroup intaggroup)
14510 (save-excursion
14511 (beginning-of-line 1)
14512 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14513 (setq ov-start (match-beginning 1)
14514 ov-end (match-end 1)
14515 ov-prefix "")
14516 (setq ov-start (1- (point-at-eol))
14517 ov-end (1+ ov-start))
14518 (skip-chars-forward "^\n\r")
14519 (setq ov-prefix
14520 (concat
14521 (buffer-substring (1- (point)) (point))
14522 (if (> (current-column) org-tags-column)
14524 (make-string (- org-tags-column (current-column)) ?\ ))))))
14525 (move-overlay org-tags-overlay ov-start ov-end)
14526 (save-window-excursion
14527 (if expert
14528 (set-buffer (get-buffer-create " *Org tags*"))
14529 (delete-other-windows)
14530 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14531 (org-switch-to-buffer-other-window " *Org tags*"))
14532 (erase-buffer)
14533 (setq-local org-done-keywords done-keywords)
14534 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14535 (org-fast-tag-insert "Current" current c-face "\n\n")
14536 (org-fast-tag-show-exit exit-after-next)
14537 (org-set-current-tags-overlay current ov-prefix)
14538 (setq tbl fulltable char ?a cnt 0)
14539 (while (setq e (pop tbl))
14540 (cond
14541 ((eq (car e) :startgroup)
14542 (push '() groups) (setq ingroup t)
14543 (unless (zerop cnt)
14544 (setq cnt 0)
14545 (insert "\n"))
14546 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14547 ((eq (car e) :endgroup)
14548 (setq ingroup nil cnt 0)
14549 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14550 ((eq (car e) :startgrouptag)
14551 (setq intaggroup t)
14552 (unless (zerop cnt)
14553 (setq cnt 0)
14554 (insert "\n"))
14555 (insert "[ "))
14556 ((eq (car e) :endgrouptag)
14557 (setq intaggroup nil cnt 0)
14558 (insert "]\n"))
14559 ((equal e '(:newline))
14560 (unless (zerop cnt)
14561 (setq cnt 0)
14562 (insert "\n")
14563 (setq e (car tbl))
14564 (while (equal (car tbl) '(:newline))
14565 (insert "\n")
14566 (setq tbl (cdr tbl)))))
14567 ((equal e '(:grouptags)) (insert " : "))
14569 (setq tg (copy-sequence (car e)) c2 nil)
14570 (if (cdr e)
14571 (setq c (cdr e))
14572 ;; automatically assign a character.
14573 (setq c1 (string-to-char
14574 (downcase (substring
14575 tg (if (= (string-to-char tg) ?@) 1 0)))))
14576 (if (or (rassoc c1 ntable) (rassoc c1 table))
14577 (while (or (rassoc char ntable) (rassoc char table))
14578 (setq char (1+ char)))
14579 (setq c2 c1))
14580 (setq c (or c2 char)))
14581 (when ingroup (push tg (car groups)))
14582 (setq tg (org-add-props tg nil 'face
14583 (cond
14584 ((not (assoc tg table))
14585 (org-get-todo-face tg))
14586 ((member tg current) c-face)
14587 ((member tg inherited) i-face))))
14588 (when (equal (caar tbl) :grouptags)
14589 (org-add-props tg nil 'face 'org-tag-group))
14590 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14591 (insert "[" c "] " tg (make-string
14592 (- fwidth 4 (length tg)) ?\ ))
14593 (push (cons tg c) ntable)
14594 (when (= (cl-incf cnt) ncol)
14595 (insert "\n")
14596 (when (or ingroup intaggroup) (insert " "))
14597 (setq cnt 0)))))
14598 (setq ntable (nreverse ntable))
14599 (insert "\n")
14600 (goto-char (point-min))
14601 (unless expert (org-fit-window-to-buffer))
14602 (setq rtn
14603 (catch 'exit
14604 (while t
14605 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14606 (if (not groups) "no " "")
14607 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14608 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14609 (setq org-last-tag-selection-key c)
14610 (cond
14611 ((= c ?\r) (throw 'exit t))
14612 ((= c ?!)
14613 (setq groups (not groups))
14614 (goto-char (point-min))
14615 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14616 ((= c ?\C-c)
14617 (if (not expert)
14618 (org-fast-tag-show-exit
14619 (setq exit-after-next (not exit-after-next)))
14620 (setq expert nil)
14621 (delete-other-windows)
14622 (set-window-buffer (split-window-vertically) " *Org tags*")
14623 (org-switch-to-buffer-other-window " *Org tags*")
14624 (org-fit-window-to-buffer)))
14625 ((or (= c ?\C-g)
14626 (and (= c ?q) (not (rassoc c ntable))))
14627 (delete-overlay org-tags-overlay)
14628 (setq quit-flag t))
14629 ((= c ?\ )
14630 (setq current nil)
14631 (when exit-after-next (setq exit-after-next 'now)))
14632 ((= c ?\t)
14633 (condition-case nil
14634 (setq tg (completing-read
14635 "Tag: "
14636 (or buffer-tags
14637 (with-current-buffer buf
14638 (setq buffer-tags
14639 (org-get-buffer-tags))))))
14640 (quit (setq tg "")))
14641 (when (string-match "\\S-" tg)
14642 (cl-pushnew (list tg) buffer-tags :test #'equal)
14643 (if (member tg current)
14644 (setq current (delete tg current))
14645 (push tg current)))
14646 (when exit-after-next (setq exit-after-next 'now)))
14647 ((setq e (rassoc c todo-table) tg (car e))
14648 (with-current-buffer buf
14649 (save-excursion (org-todo tg)))
14650 (when exit-after-next (setq exit-after-next 'now)))
14651 ((setq e (rassoc c ntable) tg (car e))
14652 (if (member tg current)
14653 (setq current (delete tg current))
14654 (cl-loop for g in groups do
14655 (when (member tg g)
14656 (dolist (x g) (setq current (delete x current)))))
14657 (push tg current))
14658 (when exit-after-next (setq exit-after-next 'now))))
14660 ;; Create a sorted list
14661 (setq current
14662 (sort current
14663 (lambda (a b)
14664 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14665 (when (eq exit-after-next 'now) (throw 'exit t))
14666 (goto-char (point-min))
14667 (beginning-of-line 2)
14668 (delete-region (point) (point-at-eol))
14669 (org-fast-tag-insert "Current" current c-face)
14670 (org-set-current-tags-overlay current ov-prefix)
14671 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14672 (setq tg (match-string 1))
14673 (add-text-properties
14674 (match-beginning 1) (match-end 1)
14675 (list 'face
14676 (cond
14677 ((member tg current) c-face)
14678 ((member tg inherited) i-face)
14679 (t (get-text-property (match-beginning 1) 'face))))))
14680 (goto-char (point-min)))))
14681 (delete-overlay org-tags-overlay)
14682 (if rtn
14683 (mapconcat 'identity current ":")
14684 nil))))
14686 (defun org-get-tags-string ()
14687 "Get the TAGS string in the current headline."
14688 (unless (org-at-heading-p t)
14689 (user-error "Not on a heading"))
14690 (save-excursion
14691 (beginning-of-line 1)
14692 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14693 (match-string-no-properties 1)
14694 "")))
14696 (defun org-get-tags ()
14697 "Get the list of tags specified in the current headline."
14698 (org-split-string (org-get-tags-string) ":"))
14700 (defun org-get-buffer-tags ()
14701 "Get a table of all tags used in the buffer, for completion."
14702 (org-with-wide-buffer
14703 (goto-char (point-min))
14704 (let ((tag-re (concat org-outline-regexp-bol
14705 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14706 tags)
14707 (while (re-search-forward tag-re nil t)
14708 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14709 (push tag tags)))
14710 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14712 ;;;; The mapping API
14714 (defvar org-agenda-skip-comment-trees)
14715 (defvar org-agenda-skip-function)
14716 (defun org-map-entries (func &optional match scope &rest skip)
14717 "Call FUNC at each headline selected by MATCH in SCOPE.
14719 FUNC is a function or a lisp form. The function will be called without
14720 arguments, with the cursor positioned at the beginning of the headline.
14721 The return values of all calls to the function will be collected and
14722 returned as a list.
14724 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14725 does not need to preserve point. After evaluation, the cursor will be
14726 moved to the end of the line (presumably of the headline of the
14727 processed entry) and search continues from there. Under some
14728 circumstances, this may not produce the wanted results. For example,
14729 if you have removed (e.g. archived) the current (sub)tree it could
14730 mean that the next entry will be skipped entirely. In such cases, you
14731 can specify the position from where search should continue by making
14732 FUNC set the variable `org-map-continue-from' to the desired buffer
14733 position.
14735 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14736 Only headlines that are matched by this query will be considered during
14737 the iteration. When MATCH is nil or t, all headlines will be
14738 visited by the iteration.
14740 SCOPE determines the scope of this command. It can be any of:
14742 nil The current buffer, respecting the restriction if any
14743 tree The subtree started with the entry at point
14744 region The entries within the active region, if any
14745 region-start-level
14746 The entries within the active region, but only those at
14747 the same level than the first one.
14748 file The current buffer, without restriction
14749 file-with-archives
14750 The current buffer, and any archives associated with it
14751 agenda All agenda files
14752 agenda-with-archives
14753 All agenda files with any archive files associated with them
14754 \(file1 file2 ...)
14755 If this is a list, all files in the list will be scanned
14757 The remaining args are treated as settings for the skipping facilities of
14758 the scanner. The following items can be given here:
14760 archive skip trees with the archive tag
14761 comment skip trees with the COMMENT keyword
14762 function or Emacs Lisp form:
14763 will be used as value for `org-agenda-skip-function', so
14764 whenever the function returns a position, FUNC will not be
14765 called for that entry and search will continue from the
14766 position returned
14768 If your function needs to retrieve the tags including inherited tags
14769 at the *current* entry, you can use the value of the variable
14770 `org-scanner-tags' which will be much faster than getting the value
14771 with `org-get-tags-at'. If your function gets properties with
14772 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14773 to t around the call to `org-entry-properties' to get the same speedup.
14774 Note that if your function moves around to retrieve tags and properties at
14775 a *different* entry, you cannot use these techniques."
14776 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14777 (not (org-region-active-p)))
14778 (let* ((org-agenda-archives-mode nil) ; just to make sure
14779 (org-agenda-skip-archived-trees (memq 'archive skip))
14780 (org-agenda-skip-comment-trees (memq 'comment skip))
14781 (org-agenda-skip-function
14782 (car (org-delete-all '(comment archive) skip)))
14783 (org-tags-match-list-sublevels t)
14784 (start-level (eq scope 'region-start-level))
14785 matcher res
14786 org-todo-keywords-for-agenda
14787 org-done-keywords-for-agenda
14788 org-todo-keyword-alist-for-agenda
14789 org-tag-alist-for-agenda
14790 org--matcher-tags-todo-only)
14792 (cond
14793 ((eq match t) (setq matcher t))
14794 ((eq match nil) (setq matcher t))
14795 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14797 (save-excursion
14798 (save-restriction
14799 (cond ((eq scope 'tree)
14800 (org-back-to-heading t)
14801 (org-narrow-to-subtree)
14802 (setq scope nil))
14803 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14804 (org-region-active-p))
14805 ;; If needed, set start-level to a string like "2"
14806 (when start-level
14807 (save-excursion
14808 (goto-char (region-beginning))
14809 (unless (org-at-heading-p) (outline-next-heading))
14810 (setq start-level (org-current-level))))
14811 (narrow-to-region (region-beginning)
14812 (save-excursion
14813 (goto-char (region-end))
14814 (unless (and (bolp) (org-at-heading-p))
14815 (outline-next-heading))
14816 (point)))
14817 (setq scope nil)))
14819 (if (not scope)
14820 (progn
14821 (org-agenda-prepare-buffers
14822 (and buffer-file-name (list buffer-file-name)))
14823 (setq res
14824 (org-scan-tags
14825 func matcher org--matcher-tags-todo-only start-level)))
14826 ;; Get the right scope
14827 (cond
14828 ((and scope (listp scope) (symbolp (car scope)))
14829 (setq scope (eval scope)))
14830 ((eq scope 'agenda)
14831 (setq scope (org-agenda-files t)))
14832 ((eq scope 'agenda-with-archives)
14833 (setq scope (org-agenda-files t))
14834 (setq scope (org-add-archive-files scope)))
14835 ((eq scope 'file)
14836 (setq scope (and buffer-file-name (list buffer-file-name))))
14837 ((eq scope 'file-with-archives)
14838 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14839 (org-agenda-prepare-buffers scope)
14840 (dolist (file scope)
14841 (with-current-buffer (org-find-base-buffer-visiting file)
14842 (org-with-wide-buffer
14843 (goto-char (point-min))
14844 (setq res
14845 (append
14847 (org-scan-tags
14848 func matcher org--matcher-tags-todo-only)))))))))
14849 res)))
14851 ;;; Properties API
14853 (defconst org-special-properties
14854 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14855 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14856 "The special properties valid in Org mode.
14857 These are properties that are not defined in the property drawer,
14858 but in some other way.")
14860 (defconst org-default-properties
14861 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14862 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14863 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14864 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14865 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14866 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14867 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14868 "Some properties that are used by Org mode for various purposes.
14869 Being in this list makes sure that they are offered for completion.")
14871 (defun org--valid-property-p (property)
14872 "Non nil when string PROPERTY is a valid property name."
14873 (not
14874 (or (equal property "")
14875 (string-match-p "\\s-" property))))
14877 (defun org--update-property-plist (key val props)
14878 "Associate KEY to VAL in alist PROPS.
14879 Modifications are made by side-effect. Return new alist."
14880 (let* ((appending (string= (substring key -1) "+"))
14881 (key (if appending (substring key 0 -1) key))
14882 (old (assoc-string key props t)))
14883 (if (not old) (cons (cons key val) props)
14884 (setcdr old (if appending (concat (cdr old) " " val) val))
14885 props)))
14887 (defun org-get-property-block (&optional beg force)
14888 "Return the (beg . end) range of the body of the property drawer.
14889 BEG is the beginning of the current subtree, or of the part
14890 before the first headline. If it is not given, it will be found.
14891 If the drawer does not exist, create it if FORCE is non-nil, or
14892 return nil."
14893 (org-with-wide-buffer
14894 (when beg (goto-char beg))
14895 (unless (org-before-first-heading-p)
14896 (let ((beg (cond (beg)
14897 ((or (not (featurep 'org-inlinetask))
14898 (org-inlinetask-in-task-p))
14899 (org-back-to-heading t))
14900 (t (org-with-limited-levels (org-back-to-heading t))))))
14901 (forward-line)
14902 (when (looking-at-p org-planning-line-re) (forward-line))
14903 (cond ((looking-at org-property-drawer-re)
14904 (forward-line)
14905 (cons (point) (progn (goto-char (match-end 0))
14906 (line-beginning-position))))
14907 (force
14908 (goto-char beg)
14909 (org-insert-property-drawer)
14910 (let ((pos (save-excursion (search-forward ":END:")
14911 (line-beginning-position))))
14912 (cons pos pos))))))))
14914 (defun org-at-property-p ()
14915 "Non-nil when point is inside a property drawer.
14916 See `org-property-re' for match data, if applicable."
14917 (save-excursion
14918 (beginning-of-line)
14919 (and (looking-at org-property-re)
14920 (let ((property-drawer (save-match-data (org-get-property-block))))
14921 (and property-drawer
14922 (>= (point) (car property-drawer))
14923 (< (point) (cdr property-drawer)))))))
14925 (defun org-property-action ()
14926 "Do an action on properties."
14927 (interactive)
14928 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14929 (let ((c (read-char-exclusive)))
14930 (cl-case c
14931 (?s (call-interactively #'org-set-property))
14932 (?d (call-interactively #'org-delete-property))
14933 (?D (call-interactively #'org-delete-property-globally))
14934 (?c (call-interactively #'org-compute-property-at-point))
14935 (otherwise (user-error "No such property action %c" c)))))
14937 (defun org-inc-effort ()
14938 "Increment the value of the effort property in the current entry."
14939 (interactive)
14940 (org-set-effort nil t))
14942 (defvar org-clock-effort) ; Defined in org-clock.el.
14943 (defvar org-clock-current-task) ; Defined in org-clock.el.
14944 (defun org-set-effort (&optional value increment)
14945 "Set the effort property of the current entry.
14946 With numerical prefix arg, use the nth allowed value, 0 stands for the
14947 10th allowed value.
14949 When INCREMENT is non-nil, set the property to the next allowed value."
14950 (interactive "P")
14951 (when (equal value 0) (setq value 10))
14952 (let* ((completion-ignore-case t)
14953 (prop org-effort-property)
14954 (cur (org-entry-get nil prop))
14955 (allowed (org-property-get-allowed-values nil prop 'table))
14956 (existing (mapcar 'list (org-property-values prop)))
14957 (heading (nth 4 (org-heading-components)))
14959 (val (cond
14960 ((stringp value) value)
14961 ((and allowed (integerp value))
14962 (or (car (nth (1- value) allowed))
14963 (car (org-last allowed))))
14964 ((and allowed increment)
14965 (or (cl-caadr (member (list cur) allowed))
14966 (user-error "Allowed effort values are not set")))
14967 (allowed
14968 (message "Select 1-9,0, [RET%s]: %s"
14969 (if cur (concat "=" cur) "")
14970 (mapconcat 'car allowed " "))
14971 (setq rpl (read-char-exclusive))
14972 (if (equal rpl ?\r)
14974 (setq rpl (- rpl ?0))
14975 (when (equal rpl 0) (setq rpl 10))
14976 (if (and (> rpl 0) (<= rpl (length allowed)))
14977 (car (nth (1- rpl) allowed))
14978 (org-completing-read "Effort: " allowed nil))))
14980 (org-completing-read
14981 (concat "Effort" (and cur (string-match "\\S-" cur)
14982 (concat " [" cur "]"))
14983 ": ")
14984 existing nil nil "" nil cur)))))
14985 (unless (equal (org-entry-get nil prop) val)
14986 (org-entry-put nil prop val))
14987 (org-refresh-property
14988 '((effort . identity)
14989 (effort-minutes . org-duration-to-minutes))
14990 val)
14991 (when (equal heading (bound-and-true-p org-clock-current-task))
14992 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
14993 (org-clock-update-mode-line))
14994 (message "%s is now %s" prop val)))
14996 (defun org-entry-properties (&optional pom which)
14997 "Get all properties of the current entry.
14999 When POM is a buffer position, get all properties from the entry
15000 there instead.
15002 This includes the TODO keyword, the tags, time strings for
15003 deadline, scheduled, and clocking, and any additional properties
15004 defined in the entry.
15006 If WHICH is nil or `all', get all properties. If WHICH is
15007 `special' or `standard', only get that subclass. If WHICH is
15008 a string, only get that property.
15010 Return value is an alist. Keys are properties, as upcased
15011 strings."
15012 (org-with-point-at pom
15013 (when (and (derived-mode-p 'org-mode)
15014 (ignore-errors (org-back-to-heading t)))
15015 (catch 'exit
15016 (let* ((beg (point))
15017 (specific (and (stringp which) (upcase which)))
15018 (which (cond ((not specific) which)
15019 ((member specific org-special-properties) 'special)
15020 (t 'standard)))
15021 props)
15022 ;; Get the special properties, like TODO and TAGS.
15023 (when (memq which '(nil all special))
15024 (when (or (not specific) (string= specific "CLOCKSUM"))
15025 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15026 (when clocksum
15027 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15028 props)))
15029 (when specific (throw 'exit props)))
15030 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15031 (let ((clocksumt (get-text-property (point)
15032 :org-clock-minutes-today)))
15033 (when clocksumt
15034 (push (cons "CLOCKSUM_T"
15035 (org-duration-from-minutes clocksumt))
15036 props)))
15037 (when specific (throw 'exit props)))
15038 (when (or (not specific) (string= specific "ITEM"))
15039 (let ((case-fold-search nil))
15040 (when (looking-at org-complex-heading-regexp)
15041 (push (cons "ITEM"
15042 (let ((title (match-string-no-properties 4)))
15043 (if (org-string-nw-p title)
15044 (org-remove-tabs title)
15045 "")))
15046 props)))
15047 (when specific (throw 'exit props)))
15048 (when (or (not specific) (string= specific "TODO"))
15049 (let ((case-fold-search nil))
15050 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15051 (push (cons "TODO" (match-string-no-properties 2)) props)))
15052 (when specific (throw 'exit props)))
15053 (when (or (not specific) (string= specific "PRIORITY"))
15054 (push (cons "PRIORITY"
15055 (if (looking-at org-priority-regexp)
15056 (match-string-no-properties 2)
15057 (char-to-string org-default-priority)))
15058 props)
15059 (when specific (throw 'exit props)))
15060 (when (or (not specific) (string= specific "FILE"))
15061 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15062 props)
15063 (when specific (throw 'exit props)))
15064 (when (or (not specific) (string= specific "TAGS"))
15065 (let ((value (org-string-nw-p (org-get-tags-string))))
15066 (when value (push (cons "TAGS" value) props)))
15067 (when specific (throw 'exit props)))
15068 (when (or (not specific) (string= specific "ALLTAGS"))
15069 (let ((value (org-get-tags-at)))
15070 (when value
15071 (push (cons "ALLTAGS"
15072 (format ":%s:" (mapconcat #'identity value ":")))
15073 props)))
15074 (when specific (throw 'exit props)))
15075 (when (or (not specific) (string= specific "BLOCKED"))
15076 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15077 (when specific (throw 'exit props)))
15078 (when (or (not specific)
15079 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15080 (forward-line)
15081 (when (looking-at-p org-planning-line-re)
15082 (end-of-line)
15083 (let ((bol (line-beginning-position))
15084 ;; Backward compatibility: time keywords used to
15085 ;; be configurable (before 8.3). Make sure we
15086 ;; get the correct keyword.
15087 (key-assoc `(("CLOSED" . ,org-closed-string)
15088 ("DEADLINE" . ,org-deadline-string)
15089 ("SCHEDULED" . ,org-scheduled-string))))
15090 (dolist (pair (if specific (list (assoc specific key-assoc))
15091 key-assoc))
15092 (save-excursion
15093 (when (search-backward (cdr pair) bol t)
15094 (goto-char (match-end 0))
15095 (skip-chars-forward " \t")
15096 (and (looking-at org-ts-regexp-both)
15097 (push (cons (car pair)
15098 (match-string-no-properties 0))
15099 props)))))))
15100 (when specific (throw 'exit props)))
15101 (when (or (not specific)
15102 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15103 (let ((find-ts
15104 (lambda (end ts)
15105 ;; Fix next time-stamp before END. TS is the
15106 ;; list of time-stamps found so far.
15107 (let ((ts ts)
15108 (regexp (cond
15109 ((string= specific "TIMESTAMP")
15110 org-ts-regexp)
15111 ((string= specific "TIMESTAMP_IA")
15112 org-ts-regexp-inactive)
15113 ((assoc "TIMESTAMP_IA" ts)
15114 org-ts-regexp)
15115 ((assoc "TIMESTAMP" ts)
15116 org-ts-regexp-inactive)
15117 (t org-ts-regexp-both))))
15118 (catch 'next
15119 (while (re-search-forward regexp end t)
15120 (backward-char)
15121 (let ((object (org-element-context)))
15122 ;; Accept to match timestamps in node
15123 ;; properties, too.
15124 (when (memq (org-element-type object)
15125 '(node-property timestamp))
15126 (let ((type
15127 (org-element-property :type object)))
15128 (cond
15129 ((and (memq type '(active active-range))
15130 (not (equal specific "TIMESTAMP_IA")))
15131 (unless (assoc "TIMESTAMP" ts)
15132 (push (cons "TIMESTAMP"
15133 (org-element-property
15134 :raw-value object))
15136 (when specific (throw 'exit ts))))
15137 ((and (memq type '(inactive inactive-range))
15138 (not (string= specific "TIMESTAMP")))
15139 (unless (assoc "TIMESTAMP_IA" ts)
15140 (push (cons "TIMESTAMP_IA"
15141 (org-element-property
15142 :raw-value object))
15144 (when specific (throw 'exit ts))))))
15145 ;; Both timestamp types are found,
15146 ;; move to next part.
15147 (when (= (length ts) 2) (throw 'next ts)))))
15148 ts)))))
15149 (goto-char beg)
15150 ;; First look for timestamps within headline.
15151 (let ((ts (funcall find-ts (line-end-position) nil)))
15152 (if (= (length ts) 2) (setq props (nconc ts props))
15153 ;; Then find timestamps in the section, skipping
15154 ;; planning line.
15155 (let ((end (save-excursion (outline-next-heading))))
15156 (forward-line)
15157 (when (looking-at-p org-planning-line-re) (forward-line))
15158 (setq props (nconc (funcall find-ts end ts) props))))))))
15159 ;; Get the standard properties, like :PROP:.
15160 (when (memq which '(nil all standard))
15161 ;; If we are looking after a specific property, delegate
15162 ;; to `org-entry-get', which is faster. However, make an
15163 ;; exception for "CATEGORY", since it can be also set
15164 ;; through keywords (i.e. #+CATEGORY).
15165 (if (and specific (not (equal specific "CATEGORY")))
15166 (let ((value (org-entry-get beg specific nil t)))
15167 (throw 'exit (and value (list (cons specific value)))))
15168 (let ((range (org-get-property-block beg)))
15169 (when range
15170 (let ((end (cdr range)) seen-base)
15171 (goto-char (car range))
15172 ;; Unlike to `org--update-property-plist', we
15173 ;; handle the case where base values is found
15174 ;; after its extension. We also forbid standard
15175 ;; properties to be named as special properties.
15176 (while (re-search-forward org-property-re end t)
15177 (let* ((key (upcase (match-string-no-properties 2)))
15178 (extendp (string-match-p "\\+\\'" key))
15179 (key-base (if extendp (substring key 0 -1) key))
15180 (value (match-string-no-properties 3)))
15181 (cond
15182 ((member-ignore-case key-base org-special-properties))
15183 (extendp
15184 (setq props
15185 (org--update-property-plist key value props)))
15186 ((member key seen-base))
15187 (t (push key seen-base)
15188 (let ((p (assoc-string key props t)))
15189 (if p (setcdr p (concat value " " (cdr p)))
15190 (push (cons key value) props))))))))))))
15191 (unless (assoc "CATEGORY" props)
15192 (push (cons "CATEGORY" (org-get-category beg)) props)
15193 (when (string= specific "CATEGORY") (throw 'exit props)))
15194 ;; Return value.
15195 props)))))
15197 (defun org--property-local-values (property literal-nil)
15198 "Return value for PROPERTY in current entry.
15199 Value is a list whose car is the base value for PROPERTY and cdr
15200 a list of accumulated values. Return nil if neither is found in
15201 the entry. Also return nil when PROPERTY is set to \"nil\",
15202 unless LITERAL-NIL is non-nil."
15203 (let ((range (org-get-property-block)))
15204 (when range
15205 (goto-char (car range))
15206 (let* ((case-fold-search t)
15207 (end (cdr range))
15208 (value
15209 ;; Base value.
15210 (save-excursion
15211 (let ((v (and (re-search-forward
15212 (org-re-property property nil t) end t)
15213 (match-string-no-properties 3))))
15214 (list (if literal-nil v (org-not-nil v)))))))
15215 ;; Find additional values.
15216 (let* ((property+ (org-re-property (concat property "+") nil t)))
15217 (while (re-search-forward property+ end t)
15218 (push (match-string-no-properties 3) value)))
15219 ;; Return final values.
15220 (and (not (equal value '(nil))) (nreverse value))))))
15222 (defun org--property-global-value (property literal-nil)
15223 "Return value for PROPERTY in current buffer.
15224 Return value is a string. Return nil if property is not set
15225 globally. Also return nil when PROPERTY is set to \"nil\",
15226 unless LITERAL-NIL is non-nil."
15227 (let ((global
15228 (cdr (or (assoc-string property org-file-properties t)
15229 (assoc-string property org-global-properties t)
15230 (assoc-string property org-global-properties-fixed t)))))
15231 (if literal-nil global (org-not-nil global))))
15233 (defun org-entry-get (pom property &optional inherit literal-nil)
15234 "Get value of PROPERTY for entry or content at point-or-marker POM.
15236 If INHERIT is non-nil and the entry does not have the property,
15237 then also check higher levels of the hierarchy. If INHERIT is
15238 the symbol `selective', use inheritance only if the setting in
15239 `org-use-property-inheritance' selects PROPERTY for inheritance.
15241 If the property is present but empty, the return value is the
15242 empty string. If the property is not present at all, nil is
15243 returned. In any other case, return the value as a string.
15244 Search is case-insensitive.
15246 If LITERAL-NIL is set, return the string value \"nil\" as
15247 a string, do not interpret it as the list atom nil. This is used
15248 for inheritance when a \"nil\" value can supersede a non-nil
15249 value higher up the hierarchy."
15250 (org-with-point-at pom
15251 (cond
15252 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15253 ;; We need a special property. Use `org-entry-properties' to
15254 ;; retrieve it, but specify the wanted property.
15255 (cdr (assoc-string property (org-entry-properties nil property))))
15256 ((and inherit
15257 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15258 (org-entry-get-with-inheritance property literal-nil))
15260 (let* ((local (org--property-local-values property literal-nil))
15261 (value (and local (mapconcat #'identity (delq nil local) " "))))
15262 (if literal-nil value (org-not-nil value)))))))
15264 (defun org-property-or-variable-value (var &optional inherit)
15265 "Check if there is a property fixing the value of VAR.
15266 If yes, return this value. If not, return the current value of the variable."
15267 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15268 (if (and prop (stringp prop) (string-match "\\S-" prop))
15269 (read prop)
15270 (symbol-value var))))
15272 (defun org-entry-delete (pom property)
15273 "Delete PROPERTY from entry at point-or-marker POM.
15274 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15275 non-nil when a property was removed."
15276 (org-with-point-at pom
15277 (pcase (org-get-property-block)
15278 (`(,begin . ,origin)
15279 (let* ((end (copy-marker origin))
15280 (re (org-re-property
15281 (concat (regexp-quote property) "\\+?") t t)))
15282 (goto-char begin)
15283 (while (re-search-forward re end t)
15284 (delete-region (match-beginning 0) (line-beginning-position 2)))
15285 ;; If drawer is empty, remove it altogether.
15286 (when (= begin end)
15287 (delete-region (line-beginning-position 0)
15288 (line-beginning-position 2)))
15289 ;; Return non-nil if some property was removed.
15290 (prog1 (/= end origin) (set-marker end nil))))
15291 (_ nil))))
15293 ;; Multi-values properties are properties that contain multiple values
15294 ;; These values are assumed to be single words, separated by whitespace.
15295 (defun org-entry-add-to-multivalued-property (pom property value)
15296 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15297 (let* ((old (org-entry-get pom property))
15298 (values (and old (split-string old))))
15299 (setq value (org-entry-protect-space value))
15300 (unless (member value values)
15301 (setq values (append values (list value)))
15302 (org-entry-put pom property (mapconcat #'identity values " ")))))
15304 (defun org-entry-remove-from-multivalued-property (pom property value)
15305 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15306 (let* ((old (org-entry-get pom property))
15307 (values (and old (split-string old))))
15308 (setq value (org-entry-protect-space value))
15309 (when (member value values)
15310 (setq values (delete value values))
15311 (org-entry-put pom property (mapconcat #'identity values " ")))))
15313 (defun org-entry-member-in-multivalued-property (pom property value)
15314 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15315 (let* ((old (org-entry-get pom property))
15316 (values (and old (split-string old))))
15317 (setq value (org-entry-protect-space value))
15318 (member value values)))
15320 (defun org-entry-get-multivalued-property (pom property)
15321 "Return a list of values in a multivalued property."
15322 (let* ((value (org-entry-get pom property))
15323 (values (and value (split-string value))))
15324 (mapcar #'org-entry-restore-space values)))
15326 (defun org-entry-put-multivalued-property (pom property &rest values)
15327 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15328 VALUES should be a list of strings. Spaces will be protected."
15329 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15330 (let* ((value (org-entry-get pom property))
15331 (values (and value (split-string value))))
15332 (mapcar #'org-entry-restore-space values)))
15334 (defun org-entry-protect-space (s)
15335 "Protect spaces and newline in string S."
15336 (while (string-match " " s)
15337 (setq s (replace-match "%20" t t s)))
15338 (while (string-match "\n" s)
15339 (setq s (replace-match "%0A" t t s)))
15342 (defun org-entry-restore-space (s)
15343 "Restore spaces and newline in string S."
15344 (while (string-match "%20" s)
15345 (setq s (replace-match " " t t s)))
15346 (while (string-match "%0A" s)
15347 (setq s (replace-match "\n" t t s)))
15350 (defvar org-entry-property-inherited-from (make-marker)
15351 "Marker pointing to the entry from where a property was inherited.
15352 Each call to `org-entry-get-with-inheritance' will set this marker to the
15353 location of the entry where the inheritance search matched. If there was
15354 no match, the marker will point nowhere.
15355 Note that also `org-entry-get' calls this function, if the INHERIT flag
15356 is set.")
15358 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15359 "Get PROPERTY of entry or content at point, search higher levels if needed.
15360 The search will stop at the first ancestor which has the property defined.
15361 If the value found is \"nil\", return nil to show that the property
15362 should be considered as undefined (this is the meaning of nil here).
15363 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15364 (move-marker org-entry-property-inherited-from nil)
15365 (org-with-wide-buffer
15366 (let (value)
15367 (catch 'exit
15368 (while t
15369 (let ((v (org--property-local-values property literal-nil)))
15370 (when v
15371 (setq value
15372 (concat (mapconcat #'identity (delq nil v) " ")
15373 (and value " ")
15374 value)))
15375 (cond
15376 ((car v)
15377 (org-back-to-heading t)
15378 (move-marker org-entry-property-inherited-from (point))
15379 (throw 'exit nil))
15380 ((org-up-heading-safe))
15382 (let ((global (org--property-global-value property literal-nil)))
15383 (cond ((not global))
15384 (value (setq value (concat global " " value)))
15385 (t (setq value global))))
15386 (throw 'exit nil))))))
15387 (if literal-nil value (org-not-nil value)))))
15389 (defvar org-property-changed-functions nil
15390 "Hook called when the value of a property has changed.
15391 Each hook function should accept two arguments, the name of the property
15392 and the new value.")
15394 (defun org-entry-put (pom property value)
15395 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15397 If the value is nil, it is converted to the empty string. If it
15398 is not a string, an error is raised. Also raise an error on
15399 invalid property names.
15401 PROPERTY can be any regular property (see
15402 `org-special-properties'). It can also be \"TODO\",
15403 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15405 For the last two properties, VALUE may have any of the special
15406 values \"earlier\" and \"later\". The function then increases or
15407 decreases scheduled or deadline date by one day."
15408 (cond ((null value) (setq value ""))
15409 ((not (stringp value)) (error "Properties values should be strings"))
15410 ((not (org--valid-property-p property))
15411 (user-error "Invalid property name: \"%s\"" property)))
15412 (org-with-point-at pom
15413 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15414 (org-back-to-heading t)
15415 (org-with-limited-levels (org-back-to-heading t)))
15416 (let ((beg (point)))
15417 (cond
15418 ((equal property "TODO")
15419 (cond ((not (org-string-nw-p value)) (setq value 'none))
15420 ((not (member value org-todo-keywords-1))
15421 (user-error "\"%s\" is not a valid TODO state" value)))
15422 (org-todo value)
15423 (org-set-tags nil 'align))
15424 ((equal property "PRIORITY")
15425 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15426 (org-set-tags nil 'align))
15427 ((equal property "SCHEDULED")
15428 (forward-line)
15429 (if (and (looking-at-p org-planning-line-re)
15430 (re-search-forward
15431 org-scheduled-time-regexp (line-end-position) t))
15432 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15433 ((string= value "later") (org-timestamp-change 1 'day))
15434 ((string= value "") (org-schedule '(4)))
15435 (t (org-schedule nil value)))
15436 (if (member value '("earlier" "later" ""))
15437 (call-interactively #'org-schedule)
15438 (org-schedule nil value))))
15439 ((equal property "DEADLINE")
15440 (forward-line)
15441 (if (and (looking-at-p org-planning-line-re)
15442 (re-search-forward
15443 org-deadline-time-regexp (line-end-position) t))
15444 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15445 ((string= value "later") (org-timestamp-change 1 'day))
15446 ((string= value "") (org-deadline '(4)))
15447 (t (org-deadline nil value)))
15448 (if (member value '("earlier" "later" ""))
15449 (call-interactively #'org-deadline)
15450 (org-deadline nil value))))
15451 ((member property org-special-properties)
15452 (error "The %s property cannot be set with `org-entry-put'" property))
15454 (let* ((range (org-get-property-block beg 'force))
15455 (end (cdr range))
15456 (case-fold-search t))
15457 (goto-char (car range))
15458 (if (re-search-forward (org-re-property property nil t) end t)
15459 (progn (delete-region (match-beginning 0) (match-end 0))
15460 (goto-char (match-beginning 0)))
15461 (goto-char end)
15462 (insert "\n")
15463 (backward-char))
15464 (insert ":" property ":")
15465 (when value (insert " " value))
15466 (org-indent-line)))))
15467 (run-hook-with-args 'org-property-changed-functions property value)))
15469 (defun org-buffer-property-keys (&optional specials defaults columns)
15470 "Get all property keys in the current buffer.
15472 When SPECIALS is non-nil, also list the special properties that
15473 reflect things like tags and TODO state.
15475 When DEFAULTS is non-nil, also include properties that has
15476 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15477 DESCRIPTION, LOCATION, and LOGGING and others.
15479 When COLUMNS in non-nil, also include property names given in
15480 COLUMN formats in the current buffer."
15481 (let ((case-fold-search t)
15482 (props (append
15483 (and specials org-special-properties)
15484 (and defaults (cons org-effort-property org-default-properties))
15485 nil)))
15486 (org-with-wide-buffer
15487 (goto-char (point-min))
15488 (while (re-search-forward org-property-start-re nil t)
15489 (catch :skip
15490 (let ((range (org-get-property-block)))
15491 (unless range (throw :skip nil))
15492 (goto-char (car range))
15493 (let ((begin (car range))
15494 (end (cdr range)))
15495 ;; Make sure that found property block is not located
15496 ;; before current point, as it would generate an infloop.
15497 ;; It can happen, for example, in the following
15498 ;; situation:
15500 ;; * Headline
15501 ;; :PROPERTIES:
15502 ;; ...
15503 ;; :END:
15504 ;; *************** Inlinetask
15505 ;; #+BEGIN_EXAMPLE
15506 ;; :PROPERTIES:
15507 ;; #+END_EXAMPLE
15509 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15510 (while (< (point) end)
15511 (let ((p (progn (looking-at org-property-re)
15512 (match-string-no-properties 2))))
15513 ;; Only add true property name, not extension symbol.
15514 (push (if (not (string-match-p "\\+\\'" p)) p
15515 (substring p 0 -1))
15516 props))
15517 (forward-line))))
15518 (outline-next-heading)))
15519 (when columns
15520 (goto-char (point-min))
15521 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15522 (let ((element (org-element-at-point)))
15523 (when (memq (org-element-type element) '(keyword node-property))
15524 (let ((value (org-element-property :value element))
15525 (start 0))
15526 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15527 \\(?:{[^}]+}\\)?"
15528 value start)
15529 (setq start (match-end 0))
15530 (let ((p (match-string-no-properties 1 value)))
15531 (unless (member-ignore-case p org-special-properties)
15532 (push p props))))))))))
15533 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15535 (defun org-property-values (key)
15536 "List all non-nil values of property KEY in current buffer."
15537 (org-with-wide-buffer
15538 (goto-char (point-min))
15539 (let ((case-fold-search t)
15540 (re (org-re-property key))
15541 values)
15542 (while (re-search-forward re nil t)
15543 (push (org-entry-get (point) key) values))
15544 (delete-dups values))))
15546 (defun org-insert-property-drawer ()
15547 "Insert a property drawer into the current entry."
15548 (org-with-wide-buffer
15549 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15550 (org-back-to-heading t)
15551 (org-with-limited-levels (org-back-to-heading t)))
15552 (forward-line)
15553 (when (looking-at-p org-planning-line-re) (forward-line))
15554 (unless (looking-at-p org-property-drawer-re)
15555 ;; Make sure we start editing a line from current entry, not from
15556 ;; next one. It prevents extending text properties or overlays
15557 ;; belonging to the latter.
15558 (when (bolp) (backward-char))
15559 (let ((begin (1+ (point)))
15560 (inhibit-read-only t))
15561 (insert "\n:PROPERTIES:\n:END:")
15562 (when (eobp) (insert "\n"))
15563 (org-indent-region begin (point))))))
15565 (defun org-insert-drawer (&optional arg drawer)
15566 "Insert a drawer at point.
15568 When optional argument ARG is non-nil, insert a property drawer.
15570 Optional argument DRAWER, when non-nil, is a string representing
15571 drawer's name. Otherwise, the user is prompted for a name.
15573 If a region is active, insert the drawer around that region
15574 instead.
15576 Point is left between drawer's boundaries."
15577 (interactive "P")
15578 (let* ((drawer (if arg "PROPERTIES"
15579 (or drawer (read-from-minibuffer "Drawer: ")))))
15580 (cond
15581 ;; With C-u, fall back on `org-insert-property-drawer'
15582 (arg (org-insert-property-drawer))
15583 ;; Check validity of suggested drawer's name.
15584 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15585 (user-error "Invalid drawer name"))
15586 ;; With an active region, insert a drawer at point.
15587 ((not (org-region-active-p))
15588 (progn
15589 (unless (bolp) (insert "\n"))
15590 (insert (format ":%s:\n\n:END:\n" drawer))
15591 (forward-line -2)))
15592 ;; Otherwise, insert the drawer at point
15594 (let ((rbeg (region-beginning))
15595 (rend (copy-marker (region-end))))
15596 (unwind-protect
15597 (progn
15598 (goto-char rbeg)
15599 (beginning-of-line)
15600 (when (save-excursion
15601 (re-search-forward org-outline-regexp-bol rend t))
15602 (user-error "Drawers cannot contain headlines"))
15603 ;; Position point at the beginning of the first
15604 ;; non-blank line in region. Insert drawer's opening
15605 ;; there, then indent it.
15606 (org-skip-whitespace)
15607 (beginning-of-line)
15608 (insert ":" drawer ":\n")
15609 (forward-line -1)
15610 (indent-for-tab-command)
15611 ;; Move point to the beginning of the first blank line
15612 ;; after the last non-blank line in region. Insert
15613 ;; drawer's closing, then indent it.
15614 (goto-char rend)
15615 (skip-chars-backward " \r\t\n")
15616 (insert "\n:END:")
15617 (deactivate-mark t)
15618 (indent-for-tab-command)
15619 (unless (eolp) (insert "\n")))
15620 ;; Clear marker, whatever the outcome of insertion is.
15621 (set-marker rend nil)))))))
15623 (defvar org-property-set-functions-alist nil
15624 "Property set function alist.
15625 Each entry should have the following format:
15627 (PROPERTY . READ-FUNCTION)
15629 The read function will be called with the same argument as
15630 `org-completing-read'.")
15632 (defun org-set-property-function (property)
15633 "Get the function that should be used to set PROPERTY.
15634 This is computed according to `org-property-set-functions-alist'."
15635 (or (cdr (assoc property org-property-set-functions-alist))
15636 'org-completing-read))
15638 (defun org-read-property-value (property)
15639 "Read PROPERTY value from user."
15640 (let* ((completion-ignore-case t)
15641 (allowed (org-property-get-allowed-values nil property 'table))
15642 (cur (org-entry-get nil property))
15643 (prompt (concat property " value"
15644 (if (and cur (string-match "\\S-" cur))
15645 (concat " [" cur "]") "") ": "))
15646 (set-function (org-set-property-function property))
15647 (val (if allowed
15648 (funcall set-function prompt allowed nil
15649 (not (get-text-property 0 'org-unrestricted
15650 (caar allowed))))
15651 (funcall set-function prompt
15652 (mapcar 'list (org-property-values property))
15653 nil nil "" nil cur))))
15654 (org-trim val)))
15656 (defvar org-last-set-property nil)
15657 (defvar org-last-set-property-value nil)
15658 (defun org-read-property-name ()
15659 "Read a property name."
15660 (let ((completion-ignore-case t)
15661 (default-prop (or (and (org-at-property-p)
15662 (match-string-no-properties 2))
15663 org-last-set-property)))
15664 (org-completing-read
15665 (concat "Property"
15666 (if default-prop (concat " [" default-prop "]") "")
15667 ": ")
15668 (mapcar #'list (org-buffer-property-keys nil t t))
15669 nil nil nil nil default-prop)))
15671 (defun org-set-property-and-value (use-last)
15672 "Allow to set [PROPERTY]: [value] direction from prompt.
15673 When use-default, don't even ask, just use the last
15674 \"[PROPERTY]: [value]\" string from the history."
15675 (interactive "P")
15676 (let* ((completion-ignore-case t)
15677 (pv (or (and use-last org-last-set-property-value)
15678 (org-completing-read
15679 "Enter a \"[Property]: [value]\" pair: "
15680 nil nil nil nil nil
15681 org-last-set-property-value)))
15682 prop val)
15683 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15684 (setq prop (match-string 1 pv)
15685 val (match-string 2 pv))
15686 (org-set-property prop val))))
15688 (defun org-set-property (property value)
15689 "In the current entry, set PROPERTY to VALUE.
15691 When called interactively, this will prompt for a property name, offering
15692 completion on existing and default properties. And then it will prompt
15693 for a value, offering completion either on allowed values (via an inherited
15694 xxx_ALL property) or on existing values in other instances of this property
15695 in the current file.
15697 Throw an error when trying to set a property with an invalid name."
15698 (interactive (list nil nil))
15699 (let ((property (or property (org-read-property-name))))
15700 ;; `org-entry-put' also makes the following check, but this one
15701 ;; avoids polluting `org-last-set-property' and
15702 ;; `org-last-set-property-value' needlessly.
15703 (unless (org--valid-property-p property)
15704 (user-error "Invalid property name: \"%s\"" property))
15705 (let ((value (or value (org-read-property-value property)))
15706 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15707 (setq org-last-set-property property)
15708 (setq org-last-set-property-value (concat property ": " value))
15709 ;; Possibly postprocess the inserted value:
15710 (when fn (setq value (funcall fn value)))
15711 (unless (equal (org-entry-get nil property) value)
15712 (org-entry-put nil property value)))))
15714 (defun org-find-property (property &optional value)
15715 "Find first entry in buffer that sets PROPERTY.
15717 When optional argument VALUE is non-nil, only consider an entry
15718 if it contains PROPERTY set to this value. If PROPERTY should be
15719 explicitly set to nil, use string \"nil\" for VALUE.
15721 Return position where the entry begins, or nil if there is no
15722 such entry. If narrowing is in effect, only search the visible
15723 part of the buffer."
15724 (save-excursion
15725 (goto-char (point-min))
15726 (let ((case-fold-search t)
15727 (re (org-re-property property nil (not value) value)))
15728 (catch 'exit
15729 (while (re-search-forward re nil t)
15730 (when (if value (org-at-property-p)
15731 (org-entry-get (point) property nil t))
15732 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15734 (defun org-delete-property (property)
15735 "In the current entry, delete PROPERTY."
15736 (interactive
15737 (let* ((completion-ignore-case t)
15738 (cat (org-entry-get (point) "CATEGORY"))
15739 (props0 (org-entry-properties nil 'standard))
15740 (props (if cat props0
15741 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15742 (prop (if (< 1 (length props))
15743 (completing-read "Property: " props nil t)
15744 (caar props))))
15745 (list prop)))
15746 (if (not property)
15747 (message "No property to delete in this entry")
15748 (org-entry-delete nil property)
15749 (message "Property \"%s\" deleted" property)))
15751 (defun org-delete-property-globally (property)
15752 "Remove PROPERTY globally, from all entries.
15753 This function ignores narrowing, if any."
15754 (interactive
15755 (let* ((completion-ignore-case t)
15756 (prop (completing-read
15757 "Globally remove property: "
15758 (mapcar #'list (org-buffer-property-keys)))))
15759 (list prop)))
15760 (org-with-wide-buffer
15761 (goto-char (point-min))
15762 (let ((count 0)
15763 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15764 (while (re-search-forward re nil t)
15765 (when (org-entry-delete (point) property) (cl-incf count)))
15766 (message "Property \"%s\" removed from %d entries" property count))))
15768 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15770 (defun org-compute-property-at-point ()
15771 "Compute the property at point.
15772 This looks for an enclosing column format, extracts the operator and
15773 then applies it to the property in the column format's scope."
15774 (interactive)
15775 (unless (org-at-property-p)
15776 (user-error "Not at a property"))
15777 (let ((prop (match-string-no-properties 2)))
15778 (org-columns-get-format-and-top-level)
15779 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15780 (user-error "No operator defined for property %s" prop))
15781 (org-columns-compute prop)))
15783 (defvar org-property-allowed-value-functions nil
15784 "Hook for functions supplying allowed values for a specific property.
15785 The functions must take a single argument, the name of the property, and
15786 return a flat list of allowed values. If \":ETC\" is one of
15787 the values, this means that these values are intended as defaults for
15788 completion, but that other values should be allowed too.
15789 The functions must return nil if they are not responsible for this
15790 property.")
15792 (defun org-property-get-allowed-values (pom property &optional table)
15793 "Get allowed values for the property PROPERTY.
15794 When TABLE is non-nil, return an alist that can directly be used for
15795 completion."
15796 (let (vals)
15797 (cond
15798 ((equal property "TODO")
15799 (setq vals (org-with-point-at pom
15800 (append org-todo-keywords-1 '("")))))
15801 ((equal property "PRIORITY")
15802 (let ((n org-lowest-priority))
15803 (while (>= n org-highest-priority)
15804 (push (char-to-string n) vals)
15805 (setq n (1- n)))))
15806 ((equal property "CATEGORY"))
15807 ((member property org-special-properties))
15808 ((setq vals (run-hook-with-args-until-success
15809 'org-property-allowed-value-functions property)))
15811 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15812 (when (and vals (string-match "\\S-" vals))
15813 (setq vals (car (read-from-string (concat "(" vals ")"))))
15814 (setq vals (mapcar (lambda (x)
15815 (cond ((stringp x) x)
15816 ((numberp x) (number-to-string x))
15817 ((symbolp x) (symbol-name x))
15818 (t "???")))
15819 vals)))))
15820 (when (member ":ETC" vals)
15821 (setq vals (remove ":ETC" vals))
15822 (org-add-props (car vals) '(org-unrestricted t)))
15823 (if table (mapcar 'list vals) vals)))
15825 (defun org-property-previous-allowed-value (&optional _previous)
15826 "Switch to the next allowed value for this property."
15827 (interactive)
15828 (org-property-next-allowed-value t))
15830 (defun org-property-next-allowed-value (&optional previous)
15831 "Switch to the next allowed value for this property."
15832 (interactive)
15833 (unless (org-at-property-p)
15834 (user-error "Not at a property"))
15835 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15836 (key (match-string 2))
15837 (value (match-string 3))
15838 (allowed (or (org-property-get-allowed-values (point) key)
15839 (and (member value '("[ ]" "[-]" "[X]"))
15840 '("[ ]" "[X]"))))
15841 (heading (save-match-data (nth 4 (org-heading-components))))
15842 nval)
15843 (unless allowed
15844 (user-error "Allowed values for this property have not been defined"))
15845 (when previous (setq allowed (reverse allowed)))
15846 (when (member value allowed)
15847 (setq nval (car (cdr (member value allowed)))))
15848 (setq nval (or nval (car allowed)))
15849 (when (equal nval value)
15850 (user-error "Only one allowed value for this property"))
15851 (org-at-property-p)
15852 (replace-match (concat " :" key ": " nval) t t)
15853 (org-indent-line)
15854 (beginning-of-line 1)
15855 (skip-chars-forward " \t")
15856 (when (equal prop org-effort-property)
15857 (org-refresh-property
15858 '((effort . identity)
15859 (effort-minutes . org-duration-to-minutes))
15860 nval)
15861 (when (string= org-clock-current-task heading)
15862 (setq org-clock-effort nval)
15863 (org-clock-update-mode-line)))
15864 (run-hook-with-args 'org-property-changed-functions key nval)))
15866 (defun org-find-olp (path &optional this-buffer)
15867 "Return a marker pointing to the entry at outline path OLP.
15868 If anything goes wrong, throw an error.
15869 You can wrap this call to catch the error like this:
15871 (condition-case msg
15872 (org-mobile-locate-entry (match-string 4))
15873 (error (nth 1 msg)))
15875 The return value will then be either a string with the error message,
15876 or a marker if everything is OK.
15878 If THIS-BUFFER is set, the outline path does not contain a file,
15879 only headings."
15880 (let* ((file (if this-buffer buffer-file-name (pop path)))
15881 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15882 (level 1)
15883 (lmin 1)
15884 (lmax 1)
15885 end found flevel)
15886 (unless buffer (error "File not found :%s" file))
15887 (with-current-buffer buffer
15888 (unless (derived-mode-p 'org-mode)
15889 (error "Buffer %s needs to be in Org mode" buffer))
15890 (org-with-wide-buffer
15891 (goto-char (point-min))
15892 (dolist (heading path)
15893 (let ((re (format org-complex-heading-regexp-format
15894 (regexp-quote heading)))
15895 (cnt 0))
15896 (while (re-search-forward re end t)
15897 (setq level (- (match-end 1) (match-beginning 1)))
15898 (when (and (>= level lmin) (<= level lmax))
15899 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15900 (when (= cnt 0)
15901 (error "Heading not found on level %d: %s" lmax heading))
15902 (when (> cnt 1)
15903 (error "Heading not unique on level %d: %s" lmax heading))
15904 (goto-char found)
15905 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15906 (setq end (save-excursion (org-end-of-subtree t t)))))
15907 (when (org-at-heading-p)
15908 (point-marker))))))
15910 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15911 "Find node HEADING in BUFFER.
15912 Return a marker to the heading if it was found, or nil if not.
15913 If POS-ONLY is set, return just the position instead of a marker.
15915 The heading text must match exact, but it may have a TODO keyword,
15916 a priority cookie and tags in the standard locations."
15917 (with-current-buffer (or buffer (current-buffer))
15918 (org-with-wide-buffer
15919 (goto-char (point-min))
15920 (let (case-fold-search)
15921 (when (re-search-forward
15922 (format org-complex-heading-regexp-format
15923 (regexp-quote heading)) nil t)
15924 (if pos-only
15925 (match-beginning 0)
15926 (move-marker (make-marker) (match-beginning 0))))))))
15928 (defun org-find-exact-heading-in-directory (heading &optional dir)
15929 "Find Org node headline HEADING in all .org files in directory DIR.
15930 When the target headline is found, return a marker to this location."
15931 (let ((files (directory-files (or dir default-directory)
15932 t "\\`[^.#].*\\.org\\'"))
15933 visiting m buffer)
15934 (catch 'found
15935 (dolist (file files)
15936 (message "trying %s" file)
15937 (setq visiting (org-find-base-buffer-visiting file))
15938 (setq buffer (or visiting (find-file-noselect file)))
15939 (setq m (org-find-exact-headline-in-buffer
15940 heading buffer))
15941 (when (and (not m) (not visiting)) (kill-buffer buffer))
15942 (and m (throw 'found m))))))
15944 (defun org-find-entry-with-id (ident)
15945 "Locate the entry that contains the ID property with exact value IDENT.
15946 IDENT can be a string, a symbol or a number, this function will search for
15947 the string representation of it.
15948 Return the position where this entry starts, or nil if there is no such entry."
15949 (interactive "sID: ")
15950 (let ((id (cond
15951 ((stringp ident) ident)
15952 ((symbolp ident) (symbol-name ident))
15953 ((numberp ident) (number-to-string ident))
15954 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15955 (org-with-wide-buffer (org-find-property "ID" id))))
15957 ;;;; Timestamps
15959 (defvar org-last-changed-timestamp nil)
15960 (defvar org-last-inserted-timestamp nil
15961 "The last time stamp inserted with `org-insert-time-stamp'.")
15963 (defun org-time-stamp (arg &optional inactive)
15964 "Prompt for a date/time and insert a time stamp.
15966 If the user specifies a time like HH:MM or if this command is
15967 called with at least one prefix argument, the time stamp contains
15968 the date and the time. Otherwise, only the date is included.
15970 All parts of a date not specified by the user are filled in from
15971 the timestamp at point, if any, or the current date/time
15972 otherwise.
15974 If there is already a timestamp at the cursor, it is replaced.
15976 With two universal prefix arguments, insert an active timestamp
15977 with the current time without prompting the user.
15979 When called from lisp, the timestamp is inactive if INACTIVE is
15980 non-nil."
15981 (interactive "P")
15982 (let* ((ts (cond
15983 ((org-at-date-range-p t)
15984 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15985 ((org-at-timestamp-p 'lax) (match-string 0))))
15986 ;; Default time is either the timestamp at point or today.
15987 ;; When entering a range, only the range start is considered.
15988 (default-time (if (not ts) (current-time)
15989 (apply #'encode-time (org-parse-time-string ts))))
15990 (default-input (and ts (org-get-compact-tod ts)))
15991 (repeater (and ts
15992 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15993 (match-string 0 ts)))
15994 org-time-was-given
15995 org-end-time-was-given
15996 (time
15997 (and (if (equal arg '(16)) (current-time)
15998 ;; Preserve `this-command' and `last-command'.
15999 (let ((this-command this-command)
16000 (last-command last-command))
16001 (org-read-date
16002 arg 'totime nil nil default-time default-input
16003 inactive))))))
16004 (cond
16005 ((and ts
16006 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16007 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16008 (insert "--")
16009 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16011 ;; Make sure we're on a timestamp. When in the middle of a date
16012 ;; range, move arbitrarily to range end.
16013 (unless (org-at-timestamp-p 'lax)
16014 (skip-chars-forward "-")
16015 (org-at-timestamp-p 'lax))
16016 (replace-match "")
16017 (setq org-last-changed-timestamp
16018 (org-insert-time-stamp
16019 time (or org-time-was-given arg)
16020 inactive nil nil (list org-end-time-was-given)))
16021 (when repeater
16022 (backward-char)
16023 (insert " " repeater)
16024 (setq org-last-changed-timestamp
16025 (concat (substring org-last-inserted-timestamp 0 -1)
16026 " " repeater ">")))
16027 (message "Timestamp updated"))
16028 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16029 (t (org-insert-time-stamp
16030 time (or org-time-was-given arg) inactive nil nil
16031 (list org-end-time-was-given))))))
16033 ;; FIXME: can we use this for something else, like computing time differences?
16034 (defun org-get-compact-tod (s)
16035 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16036 (let* ((t1 (match-string 1 s))
16037 (h1 (string-to-number (match-string 2 s)))
16038 (m1 (string-to-number (match-string 3 s)))
16039 (t2 (and (match-end 4) (match-string 5 s)))
16040 (h2 (and t2 (string-to-number (match-string 6 s))))
16041 (m2 (and t2 (string-to-number (match-string 7 s))))
16042 dh dm)
16043 (if (not t2)
16045 (setq dh (- h2 h1) dm (- m2 m1))
16046 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16047 (concat t1 "+" (number-to-string dh)
16048 (and (/= 0 dm) (format ":%02d" dm)))))))
16050 (defun org-time-stamp-inactive (&optional arg)
16051 "Insert an inactive time stamp.
16052 An inactive time stamp is enclosed in square brackets instead of angle
16053 brackets. It is inactive in the sense that it does not trigger agenda entries,
16054 does not link to the calendar and cannot be changed with the S-cursor keys.
16055 So these are more for recording a certain time/date."
16056 (interactive "P")
16057 (org-time-stamp arg 'inactive))
16059 (defvar org-date-ovl (make-overlay 1 1))
16060 (overlay-put org-date-ovl 'face 'org-date-selected)
16061 (delete-overlay org-date-ovl)
16063 (defvar org-ans1) ; dynamically scoped parameter
16064 (defvar org-ans2) ; dynamically scoped parameter
16066 (defvar org-plain-time-of-day-regexp) ; defined below
16068 (defvar org-overriding-default-time nil) ; dynamically scoped
16069 (defvar org-read-date-overlay nil)
16070 (defvar org-dcst nil) ; dynamically scoped
16071 (defvar org-read-date-history nil)
16072 (defvar org-read-date-final-answer nil)
16073 (defvar org-read-date-analyze-futurep nil)
16074 (defvar org-read-date-analyze-forced-year nil)
16075 (defvar org-read-date-inactive)
16077 (defvar org-read-date-minibuffer-local-map
16078 (let* ((map (make-sparse-keymap)))
16079 (set-keymap-parent map minibuffer-local-map)
16080 (org-defkey map (kbd ".")
16081 (lambda () (interactive)
16082 ;; Are we at the beginning of the prompt?
16083 (if (looking-back "^[^:]+: "
16084 (let ((inhibit-field-text-motion t))
16085 (line-beginning-position)))
16086 (org-eval-in-calendar '(calendar-goto-today))
16087 (insert "."))))
16088 (org-defkey map (kbd "C-.")
16089 (lambda () (interactive)
16090 (org-eval-in-calendar '(calendar-goto-today))))
16091 (org-defkey map [(meta shift left)]
16092 (lambda () (interactive)
16093 (org-eval-in-calendar '(calendar-backward-month 1))))
16094 (org-defkey map [(meta shift right)]
16095 (lambda () (interactive)
16096 (org-eval-in-calendar '(calendar-forward-month 1))))
16097 (org-defkey map [(meta shift up)]
16098 (lambda () (interactive)
16099 (org-eval-in-calendar '(calendar-backward-year 1))))
16100 (org-defkey map [(meta shift down)]
16101 (lambda () (interactive)
16102 (org-eval-in-calendar '(calendar-forward-year 1))))
16103 (org-defkey map [?\e (shift left)]
16104 (lambda () (interactive)
16105 (org-eval-in-calendar '(calendar-backward-month 1))))
16106 (org-defkey map [?\e (shift right)]
16107 (lambda () (interactive)
16108 (org-eval-in-calendar '(calendar-forward-month 1))))
16109 (org-defkey map [?\e (shift up)]
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(calendar-backward-year 1))))
16112 (org-defkey map [?\e (shift down)]
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(calendar-forward-year 1))))
16115 (org-defkey map [(shift up)]
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(calendar-backward-week 1))))
16118 (org-defkey map [(shift down)]
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-forward-week 1))))
16121 (org-defkey map [(shift left)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-backward-day 1))))
16124 (org-defkey map [(shift right)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-forward-day 1))))
16127 (org-defkey map "!"
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(diary-view-entries))
16130 (message "")))
16131 (org-defkey map ">"
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-scroll-left 1))))
16134 (org-defkey map "<"
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-scroll-right 1))))
16137 (org-defkey map "\C-v"
16138 (lambda () (interactive)
16139 (org-eval-in-calendar
16140 '(calendar-scroll-left-three-months 1))))
16141 (org-defkey map "\M-v"
16142 (lambda () (interactive)
16143 (org-eval-in-calendar
16144 '(calendar-scroll-right-three-months 1))))
16145 map)
16146 "Keymap for minibuffer commands when using `org-read-date'.")
16148 (defvar org-def)
16149 (defvar org-defdecode)
16150 (defvar org-with-time)
16152 (defvar calendar-setup) ; Dynamically scoped.
16153 (defun org-read-date (&optional with-time to-time from-string prompt
16154 default-time default-input inactive)
16155 "Read a date, possibly a time, and make things smooth for the user.
16156 The prompt will suggest to enter an ISO date, but you can also enter anything
16157 which will at least partially be understood by `parse-time-string'.
16158 Unrecognized parts of the date will default to the current day, month, year,
16159 hour and minute. If this command is called to replace a timestamp at point,
16160 or to enter the second timestamp of a range, the default time is taken
16161 from the existing stamp. Furthermore, the command prefers the future,
16162 so if you are giving a date where the year is not given, and the day-month
16163 combination is already past in the current year, it will assume you
16164 mean next year. For details, see the manual. A few examples:
16166 3-2-5 --> 2003-02-05
16167 feb 15 --> currentyear-02-15
16168 2/15 --> currentyear-02-15
16169 sep 12 9 --> 2009-09-12
16170 12:45 --> today 12:45
16171 22 sept 0:34 --> currentyear-09-22 0:34
16172 12 --> currentyear-currentmonth-12
16173 Fri --> nearest Friday after today
16174 -Tue --> last Tuesday
16175 etc.
16177 Furthermore you can specify a relative date by giving, as the *first* thing
16178 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16179 change in days weeks, months, years.
16180 With a single plus or minus, the date is relative to today. With a double
16181 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16182 +4d --> four days from today
16183 +4 --> same as above
16184 +2w --> two weeks from today
16185 ++5 --> five days from default date
16187 The function understands only English month and weekday abbreviations.
16189 While prompting, a calendar is popped up - you can also select the
16190 date with the mouse (button 1). The calendar shows a period of three
16191 months. To scroll it to other months, use the keys `>' and `<'.
16192 If you don't like the calendar, turn it off with
16193 (setq org-read-date-popup-calendar nil)
16195 With optional argument TO-TIME, the date will immediately be converted
16196 to an internal time.
16197 With an optional argument WITH-TIME, the prompt will suggest to
16198 also insert a time. Note that when WITH-TIME is not set, you can
16199 still enter a time, and this function will inform the calling routine
16200 about this change. The calling routine may then choose to change the
16201 format used to insert the time stamp into the buffer to include the time.
16202 With optional argument FROM-STRING, read from this string instead from
16203 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16204 the time/date that is used for everything that is not specified by the
16205 user."
16206 (require 'parse-time)
16207 (let* ((org-with-time with-time)
16208 (org-time-stamp-rounding-minutes
16209 (if (equal org-with-time '(16))
16210 '(0 0)
16211 org-time-stamp-rounding-minutes))
16212 (org-dcst org-display-custom-times)
16213 (ct (org-current-time))
16214 (org-def (or org-overriding-default-time default-time ct))
16215 (org-defdecode (decode-time org-def))
16216 (cur-frame (selected-frame))
16217 (mouse-autoselect-window nil) ; Don't let the mouse jump
16218 (calendar-setup
16219 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16220 (calendar-move-hook nil)
16221 (calendar-view-diary-initially-flag nil)
16222 (calendar-view-holidays-initially-flag nil)
16223 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16224 ;; Rationalize `org-def' and `org-defdecode', if required.
16225 (when (< (nth 2 org-defdecode) org-extend-today-until)
16226 (setf (nth 2 org-defdecode) -1)
16227 (setf (nth 1 org-defdecode) 59)
16228 (setq org-def (apply #'encode-time org-defdecode))
16229 (setq org-defdecode (decode-time org-def)))
16230 (let* ((timestr (format-time-string
16231 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16232 org-def))
16233 (prompt (concat (if prompt (concat prompt " ") "")
16234 (format "Date+time [%s]: " timestr))))
16235 (cond
16236 (from-string (setq ans from-string))
16237 (org-read-date-popup-calendar
16238 (save-excursion
16239 (save-window-excursion
16240 (calendar)
16241 (when (eq calendar-setup 'calendar-only)
16242 (setq cal-frame
16243 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16244 (select-frame cal-frame))
16245 (org-eval-in-calendar '(setq cursor-type nil) t)
16246 (unwind-protect
16247 (progn
16248 (calendar-forward-day (- (time-to-days org-def)
16249 (calendar-absolute-from-gregorian
16250 (calendar-current-date))))
16251 (org-eval-in-calendar nil t)
16252 (let* ((old-map (current-local-map))
16253 (map (copy-keymap calendar-mode-map))
16254 (minibuffer-local-map
16255 (copy-keymap org-read-date-minibuffer-local-map)))
16256 (org-defkey map (kbd "RET") 'org-calendar-select)
16257 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16258 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16259 (unwind-protect
16260 (progn
16261 (use-local-map map)
16262 (setq org-read-date-inactive inactive)
16263 (add-hook 'post-command-hook 'org-read-date-display)
16264 (setq org-ans0
16265 (read-string prompt
16266 default-input
16267 'org-read-date-history
16268 nil))
16269 ;; org-ans0: from prompt
16270 ;; org-ans1: from mouse click
16271 ;; org-ans2: from calendar motion
16272 (setq ans
16273 (concat org-ans0 " " (or org-ans1 org-ans2))))
16274 (remove-hook 'post-command-hook 'org-read-date-display)
16275 (use-local-map old-map)
16276 (when org-read-date-overlay
16277 (delete-overlay org-read-date-overlay)
16278 (setq org-read-date-overlay nil)))))
16279 (bury-buffer "*Calendar*")
16280 (when cal-frame
16281 (delete-frame cal-frame)
16282 (select-frame-set-input-focus cur-frame))))))
16284 (t ; Naked prompt only
16285 (unwind-protect
16286 (setq ans (read-string prompt default-input
16287 'org-read-date-history timestr))
16288 (when org-read-date-overlay
16289 (delete-overlay org-read-date-overlay)
16290 (setq org-read-date-overlay nil))))))
16292 (setq final (org-read-date-analyze ans org-def org-defdecode))
16294 (when org-read-date-analyze-forced-year
16295 (message "Year was forced into %s"
16296 (if org-read-date-force-compatible-dates
16297 "compatible range (1970-2037)"
16298 "range representable on this machine"))
16299 (ding))
16301 ;; One round trip to get rid of 34th of August and stuff like that....
16302 (setq final (decode-time (apply 'encode-time final)))
16304 (setq org-read-date-final-answer ans)
16306 (if to-time
16307 (apply 'encode-time final)
16308 (if (and (boundp 'org-time-was-given) org-time-was-given)
16309 (format "%04d-%02d-%02d %02d:%02d"
16310 (nth 5 final) (nth 4 final) (nth 3 final)
16311 (nth 2 final) (nth 1 final))
16312 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16314 (defun org-read-date-display ()
16315 "Display the current date prompt interpretation in the minibuffer."
16316 (when org-read-date-display-live
16317 (when org-read-date-overlay
16318 (delete-overlay org-read-date-overlay))
16319 (when (minibufferp (current-buffer))
16320 (save-excursion
16321 (end-of-line 1)
16322 (while (not (equal (buffer-substring
16323 (max (point-min) (- (point) 4)) (point))
16324 " "))
16325 (insert " ")))
16326 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16327 " " (or org-ans1 org-ans2)))
16328 (org-end-time-was-given nil)
16329 (f (org-read-date-analyze ans org-def org-defdecode))
16330 (fmts (if org-dcst
16331 org-time-stamp-custom-formats
16332 org-time-stamp-formats))
16333 (fmt (if (or org-with-time
16334 (and (boundp 'org-time-was-given) org-time-was-given))
16335 (cdr fmts)
16336 (car fmts)))
16337 (txt (format-time-string fmt (apply 'encode-time f)))
16338 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16339 (txt (concat "=> " txt)))
16340 (when (and org-end-time-was-given
16341 (string-match org-plain-time-of-day-regexp txt))
16342 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16343 org-end-time-was-given
16344 (substring txt (match-end 0)))))
16345 (when org-read-date-analyze-futurep
16346 (setq txt (concat txt " (=>F)")))
16347 (setq org-read-date-overlay
16348 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16349 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16351 (defun org-read-date-analyze (ans def defdecode)
16352 "Analyze the combined answer of the date prompt."
16353 ;; FIXME: cleanup and comment
16354 ;; Pass `current-time' result to `decode-time' (instead of calling
16355 ;; without arguments) so that only `current-time' has to be
16356 ;; overridden in tests.
16357 (let ((org-def def)
16358 (org-defdecode defdecode)
16359 (nowdecode (decode-time (current-time)))
16360 delta deltan deltaw deltadef year month day
16361 hour minute second wday pm h2 m2 tl wday1
16362 iso-year iso-weekday iso-week iso-date futurep kill-year)
16363 (setq org-read-date-analyze-futurep nil
16364 org-read-date-analyze-forced-year nil)
16365 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16366 (setq ans "+0"))
16368 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16369 (setq ans (replace-match "" t t ans)
16370 deltan (car delta)
16371 deltaw (nth 1 delta)
16372 deltadef (nth 2 delta)))
16374 ;; Check if there is an iso week date in there. If yes, store the
16375 ;; info and postpone interpreting it until the rest of the parsing
16376 ;; is done.
16377 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16378 (setq iso-year (when (match-end 1)
16379 (org-small-year-to-year
16380 (string-to-number (match-string 1 ans))))
16381 iso-weekday (when (match-end 3)
16382 (string-to-number (match-string 3 ans)))
16383 iso-week (string-to-number (match-string 2 ans)))
16384 (setq ans (replace-match "" t t ans)))
16386 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16387 (when (string-match
16388 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16389 (setq year (if (match-end 2)
16390 (string-to-number (match-string 2 ans))
16391 (progn (setq kill-year t)
16392 (string-to-number (format-time-string "%Y"))))
16393 month (string-to-number (match-string 3 ans))
16394 day (string-to-number (match-string 4 ans)))
16395 (setq year (org-small-year-to-year year))
16396 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16397 t nil ans)))
16399 ;; Help matching dotted european dates
16400 (when (string-match
16401 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16402 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16403 (setq kill-year t)
16404 (string-to-number (format-time-string "%Y")))
16405 day (string-to-number (match-string 1 ans))
16406 month (string-to-number (match-string 2 ans))
16407 ans (replace-match (format "%04d-%02d-%02d" year month day)
16408 t nil ans)))
16410 ;; Help matching american dates, like 5/30 or 5/30/7
16411 (when (string-match
16412 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16413 (setq year (if (match-end 4)
16414 (string-to-number (match-string 4 ans))
16415 (progn (setq kill-year t)
16416 (string-to-number (format-time-string "%Y"))))
16417 month (string-to-number (match-string 1 ans))
16418 day (string-to-number (match-string 2 ans)))
16419 (setq year (org-small-year-to-year year))
16420 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16421 t nil ans)))
16422 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16423 ;; If there is a time with am/pm, and *no* time without it, we convert
16424 ;; so that matching will be successful.
16425 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16426 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16427 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16428 (setq hour (string-to-number (match-string 1 ans))
16429 minute (if (match-end 3)
16430 (string-to-number (match-string 3 ans))
16432 pm (equal ?p
16433 (string-to-char (downcase (match-string 4 ans)))))
16434 (if (and (= hour 12) (not pm))
16435 (setq hour 0)
16436 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16437 (setq ans (replace-match (format "%02d:%02d" hour minute)
16438 t t ans))))
16440 ;; Check if a time range is given as a duration
16441 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16442 (setq hour (string-to-number (match-string 1 ans))
16443 h2 (+ hour (string-to-number (match-string 3 ans)))
16444 minute (string-to-number (match-string 2 ans))
16445 m2 (+ minute (if (match-end 5) (string-to-number
16446 (match-string 5 ans))0)))
16447 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16448 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16449 t t ans)))
16451 ;; Check if there is a time range
16452 (when (boundp 'org-end-time-was-given)
16453 (setq org-time-was-given nil)
16454 (when (and (string-match org-plain-time-of-day-regexp ans)
16455 (match-end 8))
16456 (setq org-end-time-was-given (match-string 8 ans))
16457 (setq ans (concat (substring ans 0 (match-beginning 7))
16458 (substring ans (match-end 7))))))
16460 (setq tl (parse-time-string ans)
16461 day (or (nth 3 tl) (nth 3 org-defdecode))
16462 month
16463 (cond ((nth 4 tl))
16464 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16465 ;; Day was specified. Make sure DAY+MONTH
16466 ;; combination happens in the future.
16467 ((nth 3 tl)
16468 (setq futurep t)
16469 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16470 (nth 4 nowdecode)))
16471 (t (nth 4 org-defdecode)))
16472 year
16473 (cond ((and (not kill-year) (nth 5 tl)))
16474 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16475 ;; Month was guessed in the future and is at least
16476 ;; equal to NOWDECODE's. Fix year accordingly.
16477 (futurep
16478 (if (or (> month (nth 4 nowdecode))
16479 (>= day (nth 3 nowdecode)))
16480 (nth 5 nowdecode)
16481 (1+ (nth 5 nowdecode))))
16482 ;; Month was specified. Make sure MONTH+YEAR
16483 ;; combination happens in the future.
16484 ((nth 4 tl)
16485 (setq futurep t)
16486 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16487 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16488 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16489 (t (nth 5 nowdecode))))
16490 (t (nth 5 org-defdecode)))
16491 hour (or (nth 2 tl) (nth 2 org-defdecode))
16492 minute (or (nth 1 tl) (nth 1 org-defdecode))
16493 second (or (nth 0 tl) 0)
16494 wday (nth 6 tl))
16496 (when (and (eq org-read-date-prefer-future 'time)
16497 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16498 (equal day (nth 3 nowdecode))
16499 (equal month (nth 4 nowdecode))
16500 (equal year (nth 5 nowdecode))
16501 (nth 2 tl)
16502 (or (< (nth 2 tl) (nth 2 nowdecode))
16503 (and (= (nth 2 tl) (nth 2 nowdecode))
16504 (nth 1 tl)
16505 (< (nth 1 tl) (nth 1 nowdecode)))))
16506 (setq day (1+ day)
16507 futurep t))
16509 ;; Special date definitions below
16510 (cond
16511 (iso-week
16512 ;; There was an iso week
16513 (require 'cal-iso)
16514 (setq futurep nil)
16515 (setq year (or iso-year year)
16516 day (or iso-weekday wday 1)
16517 wday nil ; to make sure that the trigger below does not match
16518 iso-date (calendar-gregorian-from-absolute
16519 (calendar-iso-to-absolute
16520 (list iso-week day year))))
16521 ; FIXME: Should we also push ISO weeks into the future?
16522 ; (when (and org-read-date-prefer-future
16523 ; (not iso-year)
16524 ; (< (calendar-absolute-from-gregorian iso-date)
16525 ; (time-to-days (current-time))))
16526 ; (setq year (1+ year)
16527 ; iso-date (calendar-gregorian-from-absolute
16528 ; (calendar-iso-to-absolute
16529 ; (list iso-week day year)))))
16530 (setq month (car iso-date)
16531 year (nth 2 iso-date)
16532 day (nth 1 iso-date)))
16533 (deltan
16534 (setq futurep nil)
16535 (unless deltadef
16536 ;; Pass `current-time' result to `decode-time' (instead of
16537 ;; calling without arguments) so that only `current-time' has
16538 ;; to be overridden in tests.
16539 (let ((now (decode-time (current-time))))
16540 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16541 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16542 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16543 ((equal deltaw "m") (setq month (+ month deltan)))
16544 ((equal deltaw "y") (setq year (+ year deltan)))))
16545 ((and wday (not (nth 3 tl)))
16546 ;; Weekday was given, but no day, so pick that day in the week
16547 ;; on or after the derived date.
16548 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16549 (unless (equal wday wday1)
16550 (setq day (+ day (% (- wday wday1 -7) 7))))))
16551 (when (and (boundp 'org-time-was-given)
16552 (nth 2 tl))
16553 (setq org-time-was-given t))
16554 (when (< year 100) (setq year (+ 2000 year)))
16555 ;; Check of the date is representable
16556 (if org-read-date-force-compatible-dates
16557 (progn
16558 (when (< year 1970)
16559 (setq year 1970 org-read-date-analyze-forced-year t))
16560 (when (> year 2037)
16561 (setq year 2037 org-read-date-analyze-forced-year t)))
16562 (condition-case nil
16563 (ignore (encode-time second minute hour day month year))
16564 (error
16565 (setq year (nth 5 org-defdecode))
16566 (setq org-read-date-analyze-forced-year t))))
16567 (setq org-read-date-analyze-futurep futurep)
16568 (list second minute hour day month year)))
16570 (defvar parse-time-weekdays)
16571 (defun org-read-date-get-relative (s today default)
16572 "Check string S for special relative date string.
16573 TODAY and DEFAULT are internal times, for today and for a default.
16574 Return shift list (N what def-flag)
16575 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16576 N is the number of WHATs to shift.
16577 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16578 the DEFAULT date rather than TODAY."
16579 (require 'parse-time)
16580 (when (and
16581 (string-match
16582 (concat
16583 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16584 "\\([0-9]+\\)?"
16585 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16586 "\\([ \t]\\|$\\)") s)
16587 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16588 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16589 (string-to-char (substring (match-string 1 s) -1))
16590 ?+))
16591 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16592 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16593 (what (if (match-end 3) (match-string 3 s) "d"))
16594 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16595 (date (if rel default today))
16596 (wday (nth 6 (decode-time date)))
16597 delta)
16598 (if wday1
16599 (progn
16600 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16601 (when (= delta 0) (setq delta 7))
16602 (when (= dir ?-)
16603 (setq delta (- delta 7))
16604 (when (= delta 0) (setq delta -7)))
16605 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16606 (list delta "d" rel))
16607 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16609 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16610 "Turn a user-specified date into the internal representation.
16611 The internal representation needed by the calendar is (month day year).
16612 This is a wrapper to handle the brain-dead convention in calendar that
16613 user function argument order change dependent on argument order."
16614 (pcase calendar-date-style
16615 (`american (list arg1 arg2 arg3))
16616 (`european (list arg2 arg1 arg3))
16617 (`iso (list arg2 arg3 arg1))))
16619 (defun org-eval-in-calendar (form &optional keepdate)
16620 "Eval FORM in the calendar window and return to current window.
16621 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16622 (let ((sf (selected-frame))
16623 (sw (selected-window)))
16624 (select-window (get-buffer-window "*Calendar*" t))
16625 (eval form)
16626 (when (and (not keepdate) (calendar-cursor-to-date))
16627 (let* ((date (calendar-cursor-to-date))
16628 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16629 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16630 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16631 (select-window sw)
16632 (select-frame-set-input-focus sf)))
16634 (defun org-calendar-select ()
16635 "Return to `org-read-date' with the date currently selected.
16636 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16637 (interactive)
16638 (when (calendar-cursor-to-date)
16639 (let* ((date (calendar-cursor-to-date))
16640 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16641 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16642 (when (active-minibuffer-window) (exit-minibuffer))))
16644 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16645 "Insert a date stamp for the date given by the internal TIME.
16646 See `format-time-string' for the format of TIME.
16647 WITH-HM means use the stamp format that includes the time of the day.
16648 INACTIVE means use square brackets instead of angular ones, so that the
16649 stamp will not contribute to the agenda.
16650 PRE and POST are optional strings to be inserted before and after the
16651 stamp.
16652 The command returns the inserted time stamp."
16653 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16654 stamp)
16655 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16656 (insert-before-markers (or pre ""))
16657 (when (listp extra)
16658 (setq extra (car extra))
16659 (if (and (stringp extra)
16660 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16661 (setq extra (format "-%02d:%02d"
16662 (string-to-number (match-string 1 extra))
16663 (string-to-number (match-string 2 extra))))
16664 (setq extra nil)))
16665 (when extra
16666 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16667 (insert-before-markers (setq stamp (format-time-string fmt time)))
16668 (insert-before-markers (or post ""))
16669 (setq org-last-inserted-timestamp stamp)))
16671 (defun org-toggle-time-stamp-overlays ()
16672 "Toggle the use of custom time stamp formats."
16673 (interactive)
16674 (setq org-display-custom-times (not org-display-custom-times))
16675 (unless org-display-custom-times
16676 (let ((p (point-min)) (bmp (buffer-modified-p)))
16677 (while (setq p (next-single-property-change p 'display))
16678 (when (and (get-text-property p 'display)
16679 (eq (get-text-property p 'face) 'org-date))
16680 (remove-text-properties
16681 p (setq p (next-single-property-change p 'display))
16682 '(display t))))
16683 (set-buffer-modified-p bmp)))
16684 (org-restart-font-lock)
16685 (setq org-table-may-need-update t)
16686 (if org-display-custom-times
16687 (message "Time stamps are overlaid with custom format")
16688 (message "Time stamp overlays removed")))
16690 (defun org-display-custom-time (beg end)
16691 "Overlay modified time stamp format over timestamp between BEG and END."
16692 (let* ((ts (buffer-substring beg end))
16693 t1 with-hm tf time str (off 0))
16694 (save-match-data
16695 (setq t1 (org-parse-time-string ts t))
16696 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16697 (setq off (- (match-end 0) (match-beginning 0)))))
16698 (setq end (- end off))
16699 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16700 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16701 time (org-fix-decoded-time t1)
16702 str (org-add-props
16703 (format-time-string
16704 (substring tf 1 -1) (apply 'encode-time time))
16705 nil 'mouse-face 'highlight))
16706 (put-text-property beg end 'display str)))
16708 (defun org-fix-decoded-time (time)
16709 "Set 0 instead of nil for the first 6 elements of time.
16710 Don't touch the rest."
16711 (let ((n 0))
16712 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16714 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16715 "Difference between TIMESTAMP-STRING and now in days.
16716 If SECONDS is non-nil, return the difference in seconds."
16717 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16718 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16719 (funcall fdiff (current-time)))))
16721 (defun org-deadline-close-p (timestamp-string &optional ndays)
16722 "Is the time in TIMESTAMP-STRING close to the current date?"
16723 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16724 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16725 (not (org-entry-is-done-p))))
16727 (defun org-get-wdays (ts &optional delay zero-delay)
16728 "Get the deadline lead time appropriate for timestring TS.
16729 When DELAY is non-nil, get the delay time for scheduled items
16730 instead of the deadline lead time. When ZERO-DELAY is non-nil
16731 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16732 don't try to find the delay cookie in the scheduled timestamp."
16733 (let ((tv (if delay org-scheduled-delay-days
16734 org-deadline-warning-days)))
16735 (cond
16736 ((or (and delay (< tv 0))
16737 (and delay zero-delay (<= tv 0))
16738 (and (not delay) (<= tv 0)))
16739 ;; Enforce this value no matter what
16740 (- tv))
16741 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16742 ;; lead time is specified.
16743 (floor (* (string-to-number (match-string 1 ts))
16744 (cdr (assoc (match-string 2 ts)
16745 '(("d" . 1) ("w" . 7)
16746 ("m" . 30.4) ("y" . 365.25)
16747 ("h" . 0.041667)))))))
16748 ;; go for the default.
16749 (t tv))))
16751 (defun org-calendar-select-mouse (ev)
16752 "Return to `org-read-date' with the date currently selected.
16753 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16754 (interactive "e")
16755 (mouse-set-point ev)
16756 (when (calendar-cursor-to-date)
16757 (let* ((date (calendar-cursor-to-date))
16758 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16759 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16760 (when (active-minibuffer-window) (exit-minibuffer))))
16762 (defun org-check-deadlines (ndays)
16763 "Check if there are any deadlines due or past due.
16764 A deadline is considered due if it happens within `org-deadline-warning-days'
16765 days from today's date. If the deadline appears in an entry marked DONE,
16766 it is not shown. A numeric prefix argument NDAYS can be used to test that
16767 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16768 are shown."
16769 (interactive "P")
16770 (let* ((org-warn-days
16771 (cond
16772 ((equal ndays '(4)) 100000)
16773 (ndays (prefix-numeric-value ndays))
16774 (t (abs org-deadline-warning-days))))
16775 (case-fold-search nil)
16776 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16777 (callback
16778 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16779 (message "%d deadlines past-due or due within %d days"
16780 (org-occur regexp nil callback)
16781 org-warn-days)))
16783 (defsubst org-re-timestamp (type)
16784 "Return a regexp for timestamp TYPE.
16785 Allowed values for TYPE are:
16787 all: all timestamps
16788 active: only active timestamps (<...>)
16789 inactive: only inactive timestamps ([...])
16790 scheduled: only scheduled timestamps
16791 deadline: only deadline timestamps
16792 closed: only closed time-stamps
16794 When TYPE is nil, fall back on returning a regexp that matches
16795 both scheduled and deadline timestamps."
16796 (cl-case type
16797 (all org-ts-regexp-both)
16798 (active org-ts-regexp)
16799 (inactive org-ts-regexp-inactive)
16800 (scheduled org-scheduled-time-regexp)
16801 (deadline org-deadline-time-regexp)
16802 (closed org-closed-time-regexp)
16803 (otherwise
16804 (concat "\\<"
16805 (regexp-opt (list org-deadline-string org-scheduled-string))
16806 " *<\\([^>]+\\)>"))))
16808 (defun org-check-before-date (d)
16809 "Check if there are deadlines or scheduled entries before date D."
16810 (interactive (list (org-read-date)))
16811 (let* ((case-fold-search nil)
16812 (regexp (org-re-timestamp org-ts-type))
16813 (ts-type org-ts-type)
16814 (callback
16815 (lambda ()
16816 (let ((match (match-string 1)))
16817 (and (if (memq ts-type '(active inactive all))
16818 (eq (org-element-type (save-excursion
16819 (backward-char)
16820 (org-element-context)))
16821 'timestamp)
16822 (org-at-planning-p))
16823 (time-less-p
16824 (org-time-string-to-time match)
16825 (org-time-string-to-time d)))))))
16826 (message "%d entries before %s"
16827 (org-occur regexp nil callback)
16828 d)))
16830 (defun org-check-after-date (d)
16831 "Check if there are deadlines or scheduled entries after date D."
16832 (interactive (list (org-read-date)))
16833 (let* ((case-fold-search nil)
16834 (regexp (org-re-timestamp org-ts-type))
16835 (ts-type org-ts-type)
16836 (callback
16837 (lambda ()
16838 (let ((match (match-string 1)))
16839 (and (if (memq ts-type '(active inactive all))
16840 (eq (org-element-type (save-excursion
16841 (backward-char)
16842 (org-element-context)))
16843 'timestamp)
16844 (org-at-planning-p))
16845 (not (time-less-p
16846 (org-time-string-to-time match)
16847 (org-time-string-to-time d))))))))
16848 (message "%d entries after %s"
16849 (org-occur regexp nil callback)
16850 d)))
16852 (defun org-check-dates-range (start-date end-date)
16853 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16854 (interactive (list (org-read-date nil nil nil "Range starts")
16855 (org-read-date nil nil nil "Range end")))
16856 (let ((case-fold-search nil)
16857 (regexp (org-re-timestamp org-ts-type))
16858 (callback
16859 (let ((type org-ts-type))
16860 (lambda ()
16861 (let ((match (match-string 1)))
16862 (and
16863 (if (memq type '(active inactive all))
16864 (eq (org-element-type (save-excursion
16865 (backward-char)
16866 (org-element-context)))
16867 'timestamp)
16868 (org-at-planning-p))
16869 (not (time-less-p
16870 (org-time-string-to-time match)
16871 (org-time-string-to-time start-date)))
16872 (time-less-p
16873 (org-time-string-to-time match)
16874 (org-time-string-to-time end-date))))))))
16875 (message "%d entries between %s and %s"
16876 (org-occur regexp nil callback) start-date end-date)))
16878 (defun org-evaluate-time-range (&optional to-buffer)
16879 "Evaluate a time range by computing the difference between start and end.
16880 Normally the result is just printed in the echo area, but with prefix arg
16881 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16882 If the time range is actually in a table, the result is inserted into the
16883 next column.
16884 For time difference computation, a year is assumed to be exactly 365
16885 days in order to avoid rounding problems."
16886 (interactive "P")
16888 (org-clock-update-time-maybe)
16889 (save-excursion
16890 (unless (org-at-date-range-p t)
16891 (goto-char (point-at-bol))
16892 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16893 (unless (org-at-date-range-p t)
16894 (user-error "Not at a time-stamp range, and none found in current line")))
16895 (let* ((ts1 (match-string 1))
16896 (ts2 (match-string 2))
16897 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16898 (match-end (match-end 0))
16899 (time1 (org-time-string-to-time ts1))
16900 (time2 (org-time-string-to-time ts2))
16901 (t1 (float-time time1))
16902 (t2 (float-time time2))
16903 (diff (abs (- t2 t1)))
16904 (negative (< (- t2 t1) 0))
16905 ;; (ys (floor (* 365 24 60 60)))
16906 (ds (* 24 60 60))
16907 (hs (* 60 60))
16908 (fy "%dy %dd %02d:%02d")
16909 (fy1 "%dy %dd")
16910 (fd "%dd %02d:%02d")
16911 (fd1 "%dd")
16912 (fh "%02d:%02d")
16913 y d h m align)
16914 (if havetime
16915 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16917 d (floor (/ diff ds)) diff (mod diff ds)
16918 h (floor (/ diff hs)) diff (mod diff hs)
16919 m (floor (/ diff 60)))
16920 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16922 d (floor (+ (/ diff ds) 0.5))
16923 h 0 m 0))
16924 (if (not to-buffer)
16925 (message "%s" (org-make-tdiff-string y d h m))
16926 (if (org-at-table-p)
16927 (progn
16928 (goto-char match-end)
16929 (setq align t)
16930 (and (looking-at " *|") (goto-char (match-end 0))))
16931 (goto-char match-end))
16932 (when (looking-at
16933 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16934 (replace-match ""))
16935 (when negative (insert " -"))
16936 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16937 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16938 (insert " " (format fh h m))))
16939 (when align (org-table-align))
16940 (message "Time difference inserted")))))
16942 (defun org-make-tdiff-string (y d h m)
16943 (let ((fmt "")
16944 (l nil))
16945 (when (> y 0)
16946 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16947 (push y l))
16948 (when (> d 0)
16949 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16950 (push d l))
16951 (when (> h 0)
16952 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16953 (push h l))
16954 (when (> m 0)
16955 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16956 (push m l))
16957 (apply 'format fmt (nreverse l))))
16959 (defun org-time-string-to-time (s)
16960 "Convert timestamp string S into internal time."
16961 (apply #'encode-time (org-parse-time-string s)))
16963 (defun org-time-string-to-seconds (s)
16964 "Convert a timestamp string S into a number of seconds."
16965 (float-time (org-time-string-to-time s)))
16967 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16969 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16970 "Convert time stamp S to an absolute day number.
16972 If DAYNR in non-nil, and there is a specifier for a cyclic time
16973 stamp, get the closest date to DAYNR. If PREFER is
16974 `past' (respectively `future') return a date past (respectively
16975 after) or equal to DAYNR.
16977 POS is the location of time stamp S, as a buffer position in
16978 BUFFER.
16980 Diary sexp timestamps are matched against DAYNR, when non-nil.
16981 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16982 signaled."
16983 (cond
16984 ((string-match "\\`%%\\((.*)\\)" s)
16985 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16986 ;; only able to match individual dates. If it fails, raise an
16987 ;; error.
16988 (if (and daynr
16989 (org-diary-sexp-entry
16990 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16991 daynr
16992 (signal 'org-diary-sexp-no-match (list s))))
16993 (daynr (org-closest-date s daynr prefer))
16994 (t (time-to-days
16995 (condition-case errdata
16996 (apply #'encode-time (org-parse-time-string s))
16997 (error (error "Bad timestamp `%s'%s\nError was: %s"
16999 (if (not (and buffer pos)) ""
17000 (format-message " at %d in buffer `%s'" pos buffer))
17001 (cdr errdata))))))))
17003 (defun org-days-to-iso-week (days)
17004 "Return the iso week number."
17005 (require 'cal-iso)
17006 (car (calendar-iso-from-absolute days)))
17008 (defun org-small-year-to-year (year)
17009 "Convert 2-digit years into 4-digit years.
17010 YEAR is expanded into one of the 30 next years, if possible, or
17011 into a past one. Any year larger than 99 is returned unchanged."
17012 (if (>= year 100) year
17013 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17014 (century (/ current 100))
17015 (offset (- year (% current 100))))
17016 (cond ((> offset 30) (+ (* (1- century) 100) year))
17017 ((> offset -70) (+ (* century 100) year))
17018 (t (+ (* (1+ century) 100) year))))))
17020 (defun org-time-from-absolute (d)
17021 "Return the time corresponding to date D.
17022 D may be an absolute day number, or a calendar-type list (month day year)."
17023 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17024 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17026 (defvar org-agenda-current-date)
17027 (defun org-calendar-holiday ()
17028 "List of holidays, for Diary display in Org mode."
17029 (require 'holidays)
17030 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17031 (and hl (mapconcat #'identity hl "; "))))
17033 (defun org-diary-sexp-entry (sexp entry d)
17034 "Process a SEXP diary ENTRY for date D."
17035 (require 'diary-lib)
17036 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17037 ;; dynamically.
17038 (let* ((sexp `(let ((entry ,entry)
17039 (date ',d))
17040 ,(car (read-from-string sexp))))
17041 (result (if calendar-debug-sexp (eval sexp)
17042 (condition-case nil
17043 (eval sexp)
17044 (error
17045 (beep)
17046 (message "Bad sexp at line %d in %s: %s"
17047 (org-current-line)
17048 (buffer-file-name) sexp)
17049 (sleep-for 2))))))
17050 (cond ((stringp result) (split-string result "; "))
17051 ((and (consp result)
17052 (not (consp (cdr result)))
17053 (stringp (cdr result))) (cdr result))
17054 ((and (consp result)
17055 (stringp (car result))) result)
17056 (result entry))))
17058 (defun org-diary-to-ical-string (frombuf)
17059 "Get iCalendar entries from diary entries in buffer FROMBUF.
17060 This uses the icalendar.el library."
17061 (let* ((tmpdir temporary-file-directory)
17062 (tmpfile (make-temp-name
17063 (expand-file-name "orgics" tmpdir)))
17064 buf rtn b e)
17065 (with-current-buffer frombuf
17066 (icalendar-export-region (point-min) (point-max) tmpfile)
17067 (setq buf (find-buffer-visiting tmpfile))
17068 (set-buffer buf)
17069 (goto-char (point-min))
17070 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17071 (setq b (match-beginning 0)))
17072 (goto-char (point-max))
17073 (when (re-search-backward "^END:VEVENT" nil t)
17074 (setq e (match-end 0)))
17075 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17076 (kill-buffer buf)
17077 (delete-file tmpfile)
17078 rtn))
17080 (defun org-closest-date (start current prefer)
17081 "Return closest date to CURRENT starting from START.
17083 CURRENT and START are both time stamps.
17085 When PREFER is `past', return a date that is either CURRENT or
17086 past. When PREFER is `future', return a date that is either
17087 CURRENT or future.
17089 Only time stamps with a repeater are modified. Any other time
17090 stamp stay unchanged. In any case, return value is an absolute
17091 day number."
17092 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17093 ;; No repeater. Do not shift time stamp.
17094 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17095 (let ((value (string-to-number (match-string 1 start)))
17096 (type (match-string 2 start)))
17097 (if (= 0 value)
17098 ;; Repeater with a 0-value is considered as void.
17099 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17100 (let* ((base (org-date-to-gregorian start))
17101 (target (org-date-to-gregorian current))
17102 (sday (calendar-absolute-from-gregorian base))
17103 (cday (calendar-absolute-from-gregorian target))
17104 n1 n2)
17105 ;; If START is already past CURRENT, just return START.
17106 (if (<= cday sday) sday
17107 ;; Compute closest date before (N1) and closest date past
17108 ;; (N2) CURRENT.
17109 (pcase type
17110 ("h"
17111 (let ((missing-hours
17112 (mod (+ (- (* 24 (- cday sday))
17113 (nth 2 (org-parse-time-string start)))
17114 org-extend-today-until)
17115 value)))
17116 (setf n1 (if (= missing-hours 0) cday
17117 (- cday (1+ (/ missing-hours 24)))))
17118 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17119 ((or "d" "w")
17120 (let ((value (if (equal type "w") (* 7 value) value)))
17121 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17122 (setf n2 (+ n1 value))))
17123 ("m"
17124 (let* ((add-months
17125 (lambda (d n)
17126 ;; Add N months to gregorian date D, i.e.,
17127 ;; a list (MONTH DAY YEAR). Return a valid
17128 ;; gregorian date.
17129 (let ((m (+ (nth 0 d) n)))
17130 (list (mod m 12)
17131 (nth 1 d)
17132 (+ (/ m 12) (nth 2 d))))))
17133 (months ; Complete months to TARGET.
17134 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17135 (- (nth 0 target) (nth 0 base))
17136 ;; If START's day is greater than
17137 ;; TARGET's, remove incomplete month.
17138 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17139 value)
17140 value))
17141 (before (funcall add-months base months)))
17142 (setf n1 (calendar-absolute-from-gregorian before))
17143 (setf n2
17144 (calendar-absolute-from-gregorian
17145 (funcall add-months before value)))))
17147 (let* ((d (nth 1 base))
17148 (m (nth 0 base))
17149 (y (nth 2 base))
17150 (years ; Complete years to TARGET.
17151 (* (/ (- (nth 2 target)
17153 ;; If START's month and day are
17154 ;; greater than TARGET's, remove
17155 ;; incomplete year.
17156 (if (or (> (nth 0 target) m)
17157 (and (= (nth 0 target) m)
17158 (> (nth 1 target) d)))
17161 value)
17162 value))
17163 (before (list m d (+ y years))))
17164 (setf n1 (calendar-absolute-from-gregorian before))
17165 (setf n2 (calendar-absolute-from-gregorian
17166 (list m d (+ (nth 2 before) value)))))))
17167 ;; Handle PREFER parameter, if any.
17168 (cond
17169 ((eq prefer 'past) (if (= cday n2) n2 n1))
17170 ((eq prefer 'future) (if (= cday n1) n1 n2))
17171 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17173 (defun org-date-to-gregorian (d)
17174 "Turn any specification of date D into a Gregorian date for the calendar."
17175 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17176 ((and (listp d) (= (length d) 3)) d)
17177 ((stringp d)
17178 (let ((d (org-parse-time-string d)))
17179 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17180 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17182 (defun org-parse-time-string (s &optional nodefault)
17183 "Parse the standard Org time string.
17185 This should be a lot faster than the normal `parse-time-string'.
17187 If time is not given, defaults to 0:00. However, with optional
17188 NODEFAULT, hour and minute fields will be nil if not given."
17189 (cond ((string-match org-ts-regexp0 s)
17190 (list 0
17191 (when (or (match-beginning 8) (not nodefault))
17192 (string-to-number (or (match-string 8 s) "0")))
17193 (when (or (match-beginning 7) (not nodefault))
17194 (string-to-number (or (match-string 7 s) "0")))
17195 (string-to-number (match-string 4 s))
17196 (string-to-number (match-string 3 s))
17197 (string-to-number (match-string 2 s))
17198 nil nil nil))
17199 ((string-match "^<[^>]+>$" s)
17200 ;; FIXME: `decode-time' needs to be called with ZONE as its
17201 ;; second argument. However, this requires at least Emacs
17202 ;; 25.1. We can do it when we switch to this version as our
17203 ;; minimal requirement.
17204 (decode-time (seconds-to-time (org-matcher-time s))))
17205 (t (error "Not a standard Org time string: %s" s))))
17207 (defun org-timestamp-up (&optional arg)
17208 "Increase the date item at the cursor by one.
17209 If the cursor is on the year, change the year. If it is on the month,
17210 the day or the time, change that.
17211 With prefix ARG, change by that many units."
17212 (interactive "p")
17213 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17215 (defun org-timestamp-down (&optional arg)
17216 "Decrease the date item at the cursor by one.
17217 If the cursor is on the year, change the year. If it is on the month,
17218 the day or the time, change that.
17219 With prefix ARG, change by that many units."
17220 (interactive "p")
17221 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17223 (defun org-timestamp-up-day (&optional arg)
17224 "Increase the date in the time stamp by one day.
17225 With prefix ARG, change that many days."
17226 (interactive "p")
17227 (if (and (not (org-at-timestamp-p 'lax))
17228 (org-at-heading-p))
17229 (org-todo 'up)
17230 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17232 (defun org-timestamp-down-day (&optional arg)
17233 "Decrease the date in the time stamp by one day.
17234 With prefix ARG, change that many days."
17235 (interactive "p")
17236 (if (and (not (org-at-timestamp-p 'lax))
17237 (org-at-heading-p))
17238 (org-todo 'down)
17239 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17241 (defun org-at-timestamp-p (&optional extended)
17242 "Non-nil if point is inside a timestamp.
17244 By default, the function only consider syntactically valid active
17245 timestamps. However, the caller may have a broader definition
17246 for timestamps. As a consequence, optional argument EXTENDED can
17247 be set to the following values
17249 `inactive'
17251 Include also syntactically valid inactive timestamps.
17253 `agenda'
17255 Include timestamps allowed in Agenda, i.e., those in
17256 properties drawers, planning lines and clock lines.
17258 `lax'
17260 Ignore context. The function matches any part of the
17261 document looking like a timestamp. This includes comments,
17262 example blocks...
17264 For backward-compatibility with Org 9.0, every other non-nil
17265 value is equivalent to `inactive'.
17267 When at a timestamp, return the position of the point as a symbol
17268 among `bracket', `after', `year', `month', `hour', `minute',
17269 `day' or a number of character from the last know part of the
17270 time stamp.
17272 When matching, the match groups are the following:
17273 group 1: year
17274 group 2: month
17275 group 3: day number
17276 group 4: day name
17277 group 5: hours, if any
17278 group 6: minutes, if any"
17279 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17280 (pos (point))
17281 (match?
17282 (let ((boundaries (org-in-regexp regexp)))
17283 (save-match-data
17284 (cond ((null boundaries) nil)
17285 ((eq extended 'lax) t)
17287 (or (and (eq extended 'agenda)
17288 (or (org-at-planning-p)
17289 (org-at-property-p)
17290 (and (bound-and-true-p
17291 org-agenda-include-inactive-timestamps)
17292 (org-at-clock-log-p))))
17293 (eq 'timestamp
17294 (save-excursion
17295 (when (= pos (cdr boundaries)) (forward-char -1))
17296 (org-element-type (org-element-context)))))))))))
17297 (cond
17298 ((not match?) nil)
17299 ((= pos (match-beginning 0)) 'bracket)
17300 ;; Distinguish location right before the closing bracket from
17301 ;; right after it.
17302 ((= pos (1- (match-end 0))) 'bracket)
17303 ((= pos (match-end 0)) 'after)
17304 ((org-pos-in-match-range pos 2) 'year)
17305 ((org-pos-in-match-range pos 3) 'month)
17306 ((org-pos-in-match-range pos 7) 'hour)
17307 ((org-pos-in-match-range pos 8) 'minute)
17308 ((or (org-pos-in-match-range pos 4)
17309 (org-pos-in-match-range pos 5)) 'day)
17310 ((and (> pos (or (match-end 8) (match-end 5)))
17311 (< pos (match-end 0)))
17312 (- pos (or (match-end 8) (match-end 5))))
17313 (t 'day))))
17315 (defun org-toggle-timestamp-type ()
17316 "Toggle the type (<active> or [inactive]) of a time stamp."
17317 (interactive)
17318 (when (org-at-timestamp-p 'lax)
17319 (let ((beg (match-beginning 0)) (end (match-end 0))
17320 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17321 (save-excursion
17322 (goto-char beg)
17323 (while (re-search-forward "[][<>]" end t)
17324 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17325 t t)))
17326 (message "Timestamp is now %sactive"
17327 (if (equal (char-after beg) ?<) "" "in")))))
17329 (defun org-at-clock-log-p ()
17330 "Non-nil if point is on a clock log line."
17331 (and (org-match-line org-clock-line-re)
17332 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17334 (defvar org-clock-history) ; defined in org-clock.el
17335 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17336 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17337 "Change the date in the time stamp at point.
17338 The date will be changed by N times WHAT. WHAT can be `day', `month',
17339 `year', `minute', `second'. If WHAT is not given, the cursor position
17340 in the timestamp determines what will be changed.
17341 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17342 (let ((origin (point))
17343 (timestamp? (org-at-timestamp-p 'lax))
17344 origin-cat
17345 with-hm inactive
17346 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17347 extra rem
17348 ts time time0 fixnext clrgx)
17349 (unless timestamp? (user-error "Not at a timestamp"))
17350 (if (and (not what) (eq timestamp? 'bracket))
17351 (org-toggle-timestamp-type)
17352 ;; Point isn't on brackets. Remember the part of the time-stamp
17353 ;; the point was in. Indeed, size of time-stamps may change,
17354 ;; but point must be kept in the same category nonetheless.
17355 (setq origin-cat timestamp?)
17356 (when (and (not what) (not (eq timestamp? 'day))
17357 org-display-custom-times
17358 (get-text-property (point) 'display)
17359 (not (get-text-property (1- (point)) 'display)))
17360 (setq timestamp? 'day))
17361 (setq timestamp? (or what timestamp?)
17362 inactive (= (char-after (match-beginning 0)) ?\[)
17363 ts (match-string 0))
17364 (replace-match "")
17365 (when (string-match
17366 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17368 (setq extra (match-string 1 ts))
17369 (when suppress-tmp-delay
17370 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17371 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17372 (setq with-hm t))
17373 (setq time0 (org-parse-time-string ts))
17374 (when (and updown
17375 (eq timestamp? 'minute)
17376 (not current-prefix-arg))
17377 ;; This looks like s-up and s-down. Change by one rounding step.
17378 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17379 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17380 (setcar (cdr time0) (+ (nth 1 time0)
17381 (if (> n 0) (- rem) (- dm rem))))))
17382 (setq time
17383 (apply #'encode-time
17384 (or (car time0) 0)
17385 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17386 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17387 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17388 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17389 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17390 (nthcdr 6 time0)))
17391 (when (and (memq timestamp? '(hour minute))
17392 extra
17393 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17394 (setq extra (org-modify-ts-extra
17395 extra
17396 (if (eq timestamp? 'hour) 2 5)
17397 n dm)))
17398 (when (integerp timestamp?)
17399 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17400 (when (eq what 'calendar)
17401 (let ((cal-date (org-get-date-from-calendar)))
17402 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17403 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17404 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17405 (setcar time0 (or (car time0) 0))
17406 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17407 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17408 (setq time (apply 'encode-time time0))))
17409 ;; Insert the new time-stamp, and ensure point stays in the same
17410 ;; category as before (i.e. not after the last position in that
17411 ;; category).
17412 (let ((pos (point)))
17413 ;; Stay before inserted string. `save-excursion' is of no use.
17414 (setq org-last-changed-timestamp
17415 (org-insert-time-stamp time with-hm inactive nil nil extra))
17416 (goto-char pos))
17417 (save-match-data
17418 (looking-at org-ts-regexp3)
17419 (goto-char
17420 (pcase origin-cat
17421 ;; `day' category ends before `hour' if any, or at the end
17422 ;; of the day name.
17423 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17424 (`hour (min (match-end 7) origin))
17425 (`minute (min (1- (match-end 8)) origin))
17426 ((pred integerp) (min (1- (match-end 0)) origin))
17427 ;; Point was right after the time-stamp. However, the
17428 ;; time-stamp length might have changed, so refer to
17429 ;; (match-end 0) instead.
17430 (`after (match-end 0))
17431 ;; `year' and `month' have both fixed size: point couldn't
17432 ;; have moved into another part.
17433 (_ origin))))
17434 ;; Update clock if on a CLOCK line.
17435 (org-clock-update-time-maybe)
17436 ;; Maybe adjust the closest clock in `org-clock-history'
17437 (when org-clock-adjust-closest
17438 (if (not (and (org-at-clock-log-p)
17439 (< 1 (length (delq nil (mapcar 'marker-position
17440 org-clock-history))))))
17441 (message "No clock to adjust")
17442 (cond ((save-excursion ; fix previous clock?
17443 (re-search-backward org-ts-regexp0 nil t)
17444 (looking-back (concat org-clock-string " \\[")
17445 (line-beginning-position)))
17446 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17447 ((save-excursion ; fix next clock?
17448 (re-search-backward org-ts-regexp0 nil t)
17449 (looking-at (concat org-ts-regexp0 "\\] =>")))
17450 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17451 (save-window-excursion
17452 ;; Find closest clock to point, adjust the previous/next one in history
17453 (let* ((p (save-excursion (org-back-to-heading t)))
17454 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17455 (clfixnth
17456 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17457 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17458 (if (not clfixpos)
17459 (message "No clock to adjust")
17460 (save-excursion
17461 (org-goto-marker-or-bmk clfixpos)
17462 (org-show-subtree)
17463 (when (re-search-forward clrgx nil t)
17464 (goto-char (match-beginning 1))
17465 (let (org-clock-adjust-closest)
17466 (org-timestamp-change n timestamp? updown))
17467 (message "Clock adjusted in %s for heading: %s"
17468 (file-name-nondirectory (buffer-file-name))
17469 (org-get-heading t t)))))))))
17470 ;; Try to recenter the calendar window, if any.
17471 (when (and org-calendar-follow-timestamp-change
17472 (get-buffer-window "*Calendar*" t)
17473 (memq timestamp? '(day month year)))
17474 (org-recenter-calendar (time-to-days time))))))
17476 (defun org-modify-ts-extra (s pos n dm)
17477 "Change the different parts of the lead-time and repeat fields in timestamp."
17478 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17479 ng h m new rem)
17480 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17481 (cond
17482 ((or (org-pos-in-match-range pos 2)
17483 (org-pos-in-match-range pos 3))
17484 (setq m (string-to-number (match-string 3 s))
17485 h (string-to-number (match-string 2 s)))
17486 (if (org-pos-in-match-range pos 2)
17487 (setq h (+ h n))
17488 (setq n (* dm (with-no-warnings (signum n))))
17489 (unless (= 0 (setq rem (% m dm)))
17490 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17491 (setq m (+ m n)))
17492 (when (< m 0) (setq m (+ m 60) h (1- h)))
17493 (when (> m 59) (setq m (- m 60) h (1+ h)))
17494 (setq h (mod h 24))
17495 (setq ng 1 new (format "-%02d:%02d" h m)))
17496 ((org-pos-in-match-range pos 6)
17497 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17498 ((org-pos-in-match-range pos 5)
17499 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17501 ((org-pos-in-match-range pos 9)
17502 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17503 ((org-pos-in-match-range pos 8)
17504 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17506 (when ng
17507 (setq s (concat
17508 (substring s 0 (match-beginning ng))
17510 (substring s (match-end ng))))))
17513 (defun org-recenter-calendar (d)
17514 "If the calendar is visible, recenter it to date D."
17515 (let ((cwin (get-buffer-window "*Calendar*" t)))
17516 (when cwin
17517 (let ((calendar-move-hook nil))
17518 (with-selected-window cwin
17519 (calendar-goto-date
17520 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17522 (defun org-goto-calendar (&optional arg)
17523 "Go to the Emacs calendar at the current date.
17524 If there is a time stamp in the current line, go to that date.
17525 A prefix ARG can be used to force the current date."
17526 (interactive "P")
17527 (let ((calendar-move-hook nil)
17528 (calendar-view-holidays-initially-flag nil)
17529 (calendar-view-diary-initially-flag nil)
17530 diff)
17531 (when (or (org-at-timestamp-p 'lax)
17532 (org-match-line (concat ".*" org-ts-regexp)))
17533 (let ((d1 (time-to-days (current-time)))
17534 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17535 (setq diff (- d2 d1))))
17536 (calendar)
17537 (calendar-goto-today)
17538 (when (and diff (not arg)) (calendar-forward-day diff))))
17540 (defun org-get-date-from-calendar ()
17541 "Return a list (month day year) of date at point in calendar."
17542 (with-current-buffer "*Calendar*"
17543 (save-match-data
17544 (calendar-cursor-to-date))))
17546 (defun org-date-from-calendar ()
17547 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17548 If there is already a time stamp at the cursor position, update it."
17549 (interactive)
17550 (if (org-at-timestamp-p 'lax)
17551 (org-timestamp-change 0 'calendar)
17552 (let ((cal-date (org-get-date-from-calendar)))
17553 (org-insert-time-stamp
17554 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17556 (defcustom org-effort-durations
17557 `(("min" . 1)
17558 ("h" . 60)
17559 ("d" . ,(* 60 8))
17560 ("w" . ,(* 60 8 5))
17561 ("m" . ,(* 60 8 5 4))
17562 ("y" . ,(* 60 8 5 40)))
17563 "Conversion factor to minutes for an effort modifier.
17565 Each entry has the form (MODIFIER . MINUTES).
17567 In an effort string, a number followed by MODIFIER is multiplied
17568 by the specified number of MINUTES to obtain an effort in
17569 minutes.
17571 For example, if the value of this variable is ((\"hours\" . 60)), then an
17572 effort string \"2hours\" is equivalent to 120 minutes."
17573 :group 'org-agenda
17574 :version "26.1"
17575 :package-version '(Org . "8.3")
17576 :type '(alist :key-type (string :tag "Modifier")
17577 :value-type (number :tag "Minutes")))
17579 (defcustom org-image-actual-width t
17580 "Should we use the actual width of images when inlining them?
17582 When set to t, always use the image width.
17584 When set to a number, use imagemagick (when available) to set
17585 the image's width to this value.
17587 When set to a number in a list, try to get the width from any
17588 #+ATTR.* keyword if it matches a width specification like
17590 #+ATTR_HTML: :width 300px
17592 and fall back on that number if none is found.
17594 When set to nil, try to get the width from an #+ATTR.* keyword
17595 and fall back on the original width if none is found.
17597 This requires Emacs >= 24.1, build with imagemagick support."
17598 :group 'org-appearance
17599 :version "24.4"
17600 :package-version '(Org . "8.0")
17601 :type '(choice
17602 (const :tag "Use the image width" t)
17603 (integer :tag "Use a number of pixels")
17604 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17605 (const :tag "Use #+ATTR* or don't resize" nil)))
17607 (defcustom org-agenda-inhibit-startup nil
17608 "Inhibit startup when preparing agenda buffers.
17609 When this variable is t, the initialization of the Org agenda
17610 buffers is inhibited: e.g. the visibility state is not set, the
17611 tables are not re-aligned, etc."
17612 :type 'boolean
17613 :version "24.3"
17614 :group 'org-agenda)
17616 (defcustom org-agenda-ignore-properties nil
17617 "Avoid updating text properties when building the agenda.
17618 Properties are used to prepare buffers for effort estimates,
17619 appointments, statistics and subtree-local categories.
17620 If you don't use these in the agenda, you can add them to this
17621 list and agenda building will be a bit faster.
17622 The value is a list, with zero or more of the symbols `effort', `appt',
17623 `stats' or `category'."
17624 :type '(set :greedy t
17625 (const effort)
17626 (const appt)
17627 (const stats)
17628 (const category))
17629 :version "26.1"
17630 :package-version '(Org . "8.3")
17631 :group 'org-agenda)
17633 ;;;; Files
17635 (defun org-save-all-org-buffers ()
17636 "Save all Org buffers without user confirmation."
17637 (interactive)
17638 (message "Saving all Org buffers...")
17639 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17640 (when (featurep 'org-id) (org-id-locations-save))
17641 (message "Saving all Org buffers... done"))
17643 (defun org-revert-all-org-buffers ()
17644 "Revert all Org buffers.
17645 Prompt for confirmation when there are unsaved changes.
17646 Be sure you know what you are doing before letting this function
17647 overwrite your changes.
17649 This function is useful in a setup where one tracks org files
17650 with a version control system, to revert on one machine after pulling
17651 changes from another. I believe the procedure must be like this:
17653 1. M-x org-save-all-org-buffers
17654 2. Pull changes from the other machine, resolve conflicts
17655 3. M-x org-revert-all-org-buffers"
17656 (interactive)
17657 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17658 (user-error "Abort"))
17659 (save-excursion
17660 (save-window-excursion
17661 (dolist (b (buffer-list))
17662 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17663 (with-current-buffer b buffer-file-name))
17664 (pop-to-buffer-same-window b)
17665 (revert-buffer t 'no-confirm)))
17666 (when (and (featurep 'org-id) org-id-track-globally)
17667 (org-id-locations-load)))))
17669 ;;;; Agenda files
17671 ;;;###autoload
17672 (defun org-switchb (&optional arg)
17673 "Switch between Org buffers.
17675 With `\\[universal-argument]' prefix, restrict available buffers to files.
17677 With `\\[universal-argument] \\[universal-argument]' \
17678 prefix, restrict available buffers to agenda files."
17679 (interactive "P")
17680 (let ((blist (org-buffer-list
17681 (cond ((equal arg '(4)) 'files)
17682 ((equal arg '(16)) 'agenda)))))
17683 (pop-to-buffer-same-window
17684 (completing-read "Org buffer: "
17685 (mapcar #'list (mapcar #'buffer-name blist))
17686 nil t))))
17688 (defun org-buffer-list (&optional predicate exclude-tmp)
17689 "Return a list of Org buffers.
17690 PREDICATE can be `export', `files' or `agenda'.
17692 export restrict the list to Export buffers.
17693 files restrict the list to buffers visiting Org files.
17694 agenda restrict the list to buffers visiting agenda files.
17696 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17697 (let* ((bfn nil)
17698 (agenda-files (and (eq predicate 'agenda)
17699 (mapcar 'file-truename (org-agenda-files t))))
17700 (filter
17701 (cond
17702 ((eq predicate 'files)
17703 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17704 ((eq predicate 'export)
17705 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17706 ((eq predicate 'agenda)
17707 (lambda (b)
17708 (with-current-buffer b
17709 (and (derived-mode-p 'org-mode)
17710 (setq bfn (buffer-file-name b))
17711 (member (file-truename bfn) agenda-files)))))
17712 (t (lambda (b) (with-current-buffer b
17713 (or (derived-mode-p 'org-mode)
17714 (string-match "\\*Org .*Export"
17715 (buffer-name b)))))))))
17716 (delq nil
17717 (mapcar
17718 (lambda(b)
17719 (if (and (funcall filter b)
17720 (or (not exclude-tmp)
17721 (not (string-match "tmp" (buffer-name b)))))
17723 nil))
17724 (buffer-list)))))
17726 (defun org-agenda-files (&optional unrestricted archives)
17727 "Get the list of agenda files.
17728 Optional UNRESTRICTED means return the full list even if a restriction
17729 is currently in place.
17730 When ARCHIVES is t, include all archive files that are really being
17731 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17732 `org-agenda-archives-mode' is t."
17733 (let ((files
17734 (cond
17735 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17736 ((stringp org-agenda-files) (org-read-agenda-file-list))
17737 ((listp org-agenda-files) org-agenda-files)
17738 (t (error "Invalid value of `org-agenda-files'")))))
17739 (setq files (apply 'append
17740 (mapcar (lambda (f)
17741 (if (file-directory-p f)
17742 (directory-files
17743 f t org-agenda-file-regexp)
17744 (list f)))
17745 files)))
17746 (when org-agenda-skip-unavailable-files
17747 (setq files (delq nil
17748 (mapcar (function
17749 (lambda (file)
17750 (and (file-readable-p file) file)))
17751 files))))
17752 (when (or (eq archives t)
17753 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17754 (setq files (org-add-archive-files files)))
17755 files))
17757 (defun org-agenda-file-p (&optional file)
17758 "Return non-nil, if FILE is an agenda file.
17759 If FILE is omitted, use the file associated with the current
17760 buffer."
17761 (let ((fname (or file (buffer-file-name))))
17762 (and fname
17763 (member (file-truename fname)
17764 (mapcar #'file-truename (org-agenda-files t))))))
17766 (defun org-edit-agenda-file-list ()
17767 "Edit the list of agenda files.
17768 Depending on setup, this either uses customize to edit the variable
17769 `org-agenda-files', or it visits the file that is holding the list. In the
17770 latter case, the buffer is set up in a way that saving it automatically kills
17771 the buffer and restores the previous window configuration."
17772 (interactive)
17773 (if (stringp org-agenda-files)
17774 (let ((cw (current-window-configuration)))
17775 (find-file org-agenda-files)
17776 (setq-local org-window-configuration cw)
17777 (add-hook 'after-save-hook
17778 (lambda ()
17779 (set-window-configuration
17780 (prog1 org-window-configuration
17781 (kill-buffer (current-buffer))))
17782 (org-install-agenda-files-menu)
17783 (message "New agenda file list installed"))
17784 nil 'local)
17785 (message "%s" (substitute-command-keys
17786 "Edit list and finish with \\[save-buffer]")))
17787 (customize-variable 'org-agenda-files)))
17789 (defun org-store-new-agenda-file-list (list)
17790 "Set new value for the agenda file list and save it correctly."
17791 (if (stringp org-agenda-files)
17792 (let ((fe (org-read-agenda-file-list t)) b u)
17793 (while (setq b (find-buffer-visiting org-agenda-files))
17794 (kill-buffer b))
17795 (with-temp-file org-agenda-files
17796 (insert
17797 (mapconcat
17798 (lambda (f) ;; Keep un-expanded entries.
17799 (if (setq u (assoc f fe))
17800 (cdr u)
17802 list "\n")
17803 "\n")))
17804 (let ((org-mode-hook nil) (org-inhibit-startup t)
17805 (org-insert-mode-line-in-empty-file nil))
17806 (setq org-agenda-files list)
17807 (customize-save-variable 'org-agenda-files org-agenda-files))))
17809 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17810 "Read the list of agenda files from a file.
17811 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17812 filenames, used by `org-store-new-agenda-file-list' to write back
17813 un-expanded file names."
17814 (when (file-directory-p org-agenda-files)
17815 (error "`org-agenda-files' cannot be a single directory"))
17816 (when (stringp org-agenda-files)
17817 (with-temp-buffer
17818 (insert-file-contents org-agenda-files)
17819 (mapcar
17820 (lambda (f)
17821 (let ((e (expand-file-name (substitute-in-file-name f)
17822 org-directory)))
17823 (if pair-with-expansion
17824 (cons e f)
17825 e)))
17826 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17828 ;;;###autoload
17829 (defun org-cycle-agenda-files ()
17830 "Cycle through the files in `org-agenda-files'.
17831 If the current buffer visits an agenda file, find the next one in the list.
17832 If the current buffer does not, find the first agenda file."
17833 (interactive)
17834 (let* ((fs (or (org-agenda-files t)
17835 (user-error "No agenda files")))
17836 (files (copy-sequence fs))
17837 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17838 file)
17839 (when tcf
17840 (while (and (setq file (pop files))
17841 (not (equal (file-truename file) tcf)))))
17842 (find-file (car (or files fs)))
17843 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17845 (defun org-agenda-file-to-front (&optional to-end)
17846 "Move/add the current file to the top of the agenda file list.
17847 If the file is not present in the list, it is added to the front. If it is
17848 present, it is moved there. With optional argument TO-END, add/move to the
17849 end of the list."
17850 (interactive "P")
17851 (let ((org-agenda-skip-unavailable-files nil)
17852 (file-alist (mapcar (lambda (x)
17853 (cons (file-truename x) x))
17854 (org-agenda-files t)))
17855 (ctf (file-truename
17856 (or buffer-file-name
17857 (user-error "Please save the current buffer to a file"))))
17858 x had)
17859 (setq x (assoc ctf file-alist) had x)
17861 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17862 (if to-end
17863 (setq file-alist (append (delq x file-alist) (list x)))
17864 (setq file-alist (cons x (delq x file-alist))))
17865 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17866 (org-install-agenda-files-menu)
17867 (message "File %s to %s of agenda file list"
17868 (if had "moved" "added") (if to-end "end" "front"))))
17870 (defun org-remove-file (&optional file)
17871 "Remove current file from the list of files in variable `org-agenda-files'.
17872 These are the files which are being checked for agenda entries.
17873 Optional argument FILE means use this file instead of the current."
17874 (interactive)
17875 (let* ((org-agenda-skip-unavailable-files nil)
17876 (file (or file buffer-file-name
17877 (user-error "Current buffer does not visit a file")))
17878 (true-file (file-truename file))
17879 (afile (abbreviate-file-name file))
17880 (files (delq nil (mapcar
17881 (lambda (x)
17882 (unless (equal true-file
17883 (file-truename x))
17885 (org-agenda-files t)))))
17886 (if (not (= (length files) (length (org-agenda-files t))))
17887 (progn
17888 (org-store-new-agenda-file-list files)
17889 (org-install-agenda-files-menu)
17890 (message "Removed from Org Agenda list: %s" afile))
17891 (message "File was not in list: %s (not removed)" afile))))
17893 (defun org-file-menu-entry (file)
17894 (vector file (list 'find-file file) t))
17896 (defun org-check-agenda-file (file)
17897 "Make sure FILE exists. If not, ask user what to do."
17898 (unless (file-exists-p file)
17899 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17900 (abbreviate-file-name file))
17901 (let ((r (downcase (read-char-exclusive))))
17902 (cond
17903 ((equal r ?r)
17904 (org-remove-file file)
17905 (throw 'nextfile t))
17906 (t (user-error "Abort"))))))
17908 (defun org-get-agenda-file-buffer (file)
17909 "Get an agenda buffer visiting FILE.
17910 If the buffer needs to be created, add it to the list of buffers
17911 which might be released later."
17912 (let ((buf (org-find-base-buffer-visiting file)))
17913 (if buf
17914 buf ; just return it
17915 ;; Make a new buffer and remember it
17916 (setq buf (find-file-noselect file))
17917 (when buf (push buf org-agenda-new-buffers))
17918 buf)))
17920 (defun org-release-buffers (blist)
17921 "Release all buffers in list, asking the user for confirmation when needed.
17922 When a buffer is unmodified, it is just killed. When modified, it is saved
17923 \(if the user agrees) and then killed."
17924 (let (file)
17925 (dolist (buf blist)
17926 (setq file (buffer-file-name buf))
17927 (when (and (buffer-modified-p buf)
17928 file
17929 (y-or-n-p (format "Save file %s? " file)))
17930 (with-current-buffer buf (save-buffer)))
17931 (kill-buffer buf))))
17933 (defun org-agenda-prepare-buffers (files)
17934 "Create buffers for all agenda files, protect archived trees and comments."
17935 (interactive)
17936 (let ((pa '(:org-archived t))
17937 (pc '(:org-comment t))
17938 (pall '(:org-archived t :org-comment t))
17939 (inhibit-read-only t)
17940 (org-inhibit-startup org-agenda-inhibit-startup)
17941 (rea (concat ":" org-archive-tag ":"))
17942 re pos)
17943 (setq org-tag-alist-for-agenda nil
17944 org-tag-groups-alist-for-agenda nil)
17945 (save-excursion
17946 (save-restriction
17947 (dolist (file files)
17948 (catch 'nextfile
17949 (if (bufferp file)
17950 (set-buffer file)
17951 (org-check-agenda-file file)
17952 (set-buffer (org-get-agenda-file-buffer file)))
17953 (widen)
17954 (org-set-regexps-and-options 'tags-only)
17955 (setq pos (point))
17956 (or (memq 'category org-agenda-ignore-properties)
17957 (org-refresh-category-properties))
17958 (or (memq 'stats org-agenda-ignore-properties)
17959 (org-refresh-stats-properties))
17960 (or (memq 'effort org-agenda-ignore-properties)
17961 (org-refresh-effort-properties))
17962 (or (memq 'appt org-agenda-ignore-properties)
17963 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17964 (setq org-todo-keywords-for-agenda
17965 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17966 (setq org-done-keywords-for-agenda
17967 (append org-done-keywords-for-agenda org-done-keywords))
17968 (setq org-todo-keyword-alist-for-agenda
17969 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17970 (setq org-tag-alist-for-agenda
17971 (org-uniquify
17972 (append org-tag-alist-for-agenda
17973 org-current-tag-alist)))
17974 ;; Merge current file's tag groups into global
17975 ;; `org-tag-groups-alist-for-agenda'.
17976 (when org-group-tags
17977 (dolist (alist org-tag-groups-alist)
17978 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17979 (if old
17980 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17981 (push alist org-tag-groups-alist-for-agenda)))))
17982 (org-with-silent-modifications
17983 (save-excursion
17984 (remove-text-properties (point-min) (point-max) pall)
17985 (when org-agenda-skip-archived-trees
17986 (goto-char (point-min))
17987 (while (re-search-forward rea nil t)
17988 (when (org-at-heading-p t)
17989 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17990 (goto-char (point-min))
17991 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17992 (while (re-search-forward re nil t)
17993 (when (save-match-data (org-in-commented-heading-p t))
17994 (add-text-properties
17995 (match-beginning 0) (org-end-of-subtree t) pc)))))
17996 (goto-char pos)))))
17997 (setq org-todo-keywords-for-agenda
17998 (org-uniquify org-todo-keywords-for-agenda))
17999 (setq org-todo-keyword-alist-for-agenda
18000 (org-uniquify org-todo-keyword-alist-for-agenda))))
18003 ;;;; CDLaTeX minor mode
18005 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18006 "Keymap for the minor `org-cdlatex-mode'.")
18008 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18009 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18010 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18011 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18012 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18014 (defvar org-cdlatex-texmathp-advice-is-done nil
18015 "Flag remembering if we have applied the advice to texmathp already.")
18017 (define-minor-mode org-cdlatex-mode
18018 "Toggle the minor `org-cdlatex-mode'.
18019 This mode supports entering LaTeX environment and math in LaTeX fragments
18020 in Org mode.
18021 \\{org-cdlatex-mode-map}"
18022 nil " OCDL" nil
18023 (when org-cdlatex-mode
18024 (require 'cdlatex)
18025 (run-hooks 'cdlatex-mode-hook)
18026 (cdlatex-compute-tables))
18027 (unless org-cdlatex-texmathp-advice-is-done
18028 (setq org-cdlatex-texmathp-advice-is-done t)
18029 (defadvice texmathp (around org-math-always-on activate)
18030 "Always return t in Org buffers.
18031 This is because we want to insert math symbols without dollars even outside
18032 the LaTeX math segments. If Org mode thinks that point is actually inside
18033 an embedded LaTeX fragment, let `texmathp' do its job.
18034 `\\[org-cdlatex-mode-map]'"
18035 (interactive)
18036 (let (p)
18037 (cond
18038 ((not (derived-mode-p 'org-mode)) ad-do-it)
18039 ((eq this-command 'cdlatex-math-symbol)
18040 (setq ad-return-value t
18041 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18043 (let ((p (org-inside-LaTeX-fragment-p)))
18044 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18045 (setq ad-return-value t
18046 texmathp-why '("Org mode embedded math" . 0))
18047 (when p ad-do-it)))))))))
18049 (defun turn-on-org-cdlatex ()
18050 "Unconditionally turn on `org-cdlatex-mode'."
18051 (org-cdlatex-mode 1))
18053 (defun org-try-cdlatex-tab ()
18054 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18055 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18056 - inside a LaTeX fragment, or
18057 - after the first word in a line, where an abbreviation expansion could
18058 insert a LaTeX environment."
18059 (when org-cdlatex-mode
18060 (cond
18061 ;; Before any word on the line: No expansion possible.
18062 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18063 ;; Just after first word on the line: Expand it. Make sure it
18064 ;; cannot happen on headlines, though.
18065 ((save-excursion
18066 (skip-chars-backward "a-zA-Z0-9*")
18067 (skip-chars-backward " \t")
18068 (and (bolp) (not (org-at-heading-p))))
18069 (cdlatex-tab) t)
18070 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18072 (defun org-cdlatex-underscore-caret (&optional _arg)
18073 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18074 Revert to the normal definition outside of these fragments."
18075 (interactive "P")
18076 (if (org-inside-LaTeX-fragment-p)
18077 (call-interactively 'cdlatex-sub-superscript)
18078 (let (org-cdlatex-mode)
18079 (call-interactively (key-binding (vector last-input-event))))))
18081 (defun org-cdlatex-math-modify (&optional _arg)
18082 "Execute `cdlatex-math-modify' in LaTeX fragments.
18083 Revert to the normal definition outside of these fragments."
18084 (interactive "P")
18085 (if (org-inside-LaTeX-fragment-p)
18086 (call-interactively 'cdlatex-math-modify)
18087 (let (org-cdlatex-mode)
18088 (call-interactively (key-binding (vector last-input-event))))))
18090 (defun org-cdlatex-environment-indent (&optional environment item)
18091 "Execute `cdlatex-environment' and indent the inserted environment.
18093 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18095 The inserted environment is indented to current indentation
18096 unless point is at the beginning of the line, in which the
18097 environment remains unintended."
18098 (interactive)
18099 ;; cdlatex-environment always return nil. Therefore, capture output
18100 ;; first and determine if an environment was selected.
18101 (let* ((beg (point-marker))
18102 (end (copy-marker (point) t))
18103 (inserted (progn
18104 (ignore-errors (cdlatex-environment environment item))
18105 (< beg end)))
18106 ;; Figure out how many lines to move forward after the
18107 ;; environment has been inserted.
18108 (lines (when inserted
18109 (save-excursion
18110 (- (cl-loop while (< beg (point))
18111 with x = 0
18112 do (forward-line -1)
18113 (cl-incf x)
18114 finally return x)
18115 (if (progn (goto-char beg)
18116 (and (progn (skip-chars-forward " \t") (eolp))
18117 (progn (skip-chars-backward " \t") (bolp))))
18118 1 0)))))
18119 (env (org-trim (delete-and-extract-region beg end))))
18120 (when inserted
18121 ;; Get indentation of next line unless at column 0.
18122 (let ((ind (if (bolp) 0
18123 (save-excursion
18124 (org-return-indent)
18125 (prog1 (org-get-indentation)
18126 (when (progn (skip-chars-forward " \t") (eolp))
18127 (delete-region beg (point)))))))
18128 (bol (progn (skip-chars-backward " \t") (bolp))))
18129 ;; Insert a newline before environment unless at column zero
18130 ;; to "escape" the current line. Insert a newline if
18131 ;; something is one the same line as \end{ENVIRONMENT}.
18132 (insert
18133 (concat (unless bol "\n") env
18134 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18135 (unless (zerop ind)
18136 (save-excursion
18137 (goto-char beg)
18138 (while (< (point) end)
18139 (unless (eolp) (indent-line-to ind))
18140 (forward-line))))
18141 (goto-char beg)
18142 (forward-line lines)
18143 (indent-line-to ind)))
18144 (set-marker beg nil)
18145 (set-marker end nil)))
18148 ;;;; LaTeX fragments
18150 (defun org-inside-LaTeX-fragment-p ()
18151 "Test if point is inside a LaTeX fragment.
18152 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18153 sequence appearing also before point.
18154 Even though the matchers for math are configurable, this function assumes
18155 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18156 delimiters are skipped when they have been removed by customization.
18157 The return value is nil, or a cons cell with the delimiter and the
18158 position of this delimiter.
18160 This function does a reasonably good job, but can locally be fooled by
18161 for example currency specifications. For example it will assume being in
18162 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18163 fragments that are properly closed, but during editing, we have to live
18164 with the uncertainty caused by missing closing delimiters. This function
18165 looks only before point, not after."
18166 (catch 'exit
18167 (let ((pos (point))
18168 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18169 (lim (save-excursion (org-backward-paragraph) (point)))
18170 dd-on str (start 0) m re)
18171 (goto-char pos)
18172 (when dodollar
18173 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18174 re (nth 1 (assoc "$" org-latex-regexps)))
18175 (while (string-match re str start)
18176 (cond
18177 ((= (match-end 0) (length str))
18178 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18179 ((= (match-end 0) (- (length str) 5))
18180 (throw 'exit nil))
18181 (t (setq start (match-end 0))))))
18182 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18183 (goto-char pos)
18184 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18185 (and (match-beginning 2) (throw 'exit nil))
18186 ;; count $$
18187 (while (re-search-backward "\\$\\$" lim t)
18188 (setq dd-on (not dd-on)))
18189 (goto-char pos)
18190 (when dd-on (cons "$$" m))))))
18192 (defun org-inside-latex-macro-p ()
18193 "Is point inside a LaTeX macro or its arguments?"
18194 (save-match-data
18195 (org-in-regexp
18196 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18198 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18199 "Build an overlay between BEG and END using IMAGE file.
18200 Argument IMAGETYPE is the extension of the displayed image,
18201 as a string. It defaults to \"png\"."
18202 (let ((ov (make-overlay beg end))
18203 (imagetype (or (intern imagetype) 'png)))
18204 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18205 (overlay-put ov 'evaporate t)
18206 (overlay-put ov
18207 'modification-hooks
18208 (list (lambda (o _flag _beg _end &optional _l)
18209 (delete-overlay o))))
18210 (overlay-put ov
18211 'display
18212 (list 'image :type imagetype :file image :ascent 'center))))
18214 (defun org--list-latex-overlays (&optional beg end)
18215 "List all Org LaTeX overlays in current buffer.
18216 Limit to overlays between BEG and END when those are provided."
18217 (cl-remove-if-not
18218 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18219 (overlays-in (or beg (point-min)) (or end (point-max)))))
18221 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18222 "Remove all overlays with LaTeX fragment images in current buffer.
18223 When optional arguments BEG and END are non-nil, remove all
18224 overlays between them instead. Return a non-nil value when some
18225 overlays were removed, nil otherwise."
18226 (let ((overlays (org--list-latex-overlays beg end)))
18227 (mapc #'delete-overlay overlays)
18228 overlays))
18230 (defun org-toggle-latex-fragment (&optional arg)
18231 "Preview the LaTeX fragment at point, or all locally or globally.
18233 If the cursor is on a LaTeX fragment, create the image and overlay
18234 it over the source code, if there is none. Remove it otherwise.
18235 If there is no fragment at point, display all fragments in the
18236 current section.
18238 With prefix ARG, preview or clear image for all fragments in the
18239 current subtree or in the whole buffer when used before the first
18240 headline. With a prefix ARG `\\[universal-argument] \
18241 \\[universal-argument]' preview or clear images
18242 for all fragments in the buffer."
18243 (interactive "P")
18244 (when (display-graphic-p)
18245 (catch 'exit
18246 (save-excursion
18247 (let (beg end msg)
18248 (cond
18249 ((or (equal arg '(16))
18250 (and (equal arg '(4))
18251 (org-with-limited-levels (org-before-first-heading-p))))
18252 (if (org-remove-latex-fragment-image-overlays)
18253 (progn (message "LaTeX fragments images removed from buffer")
18254 (throw 'exit nil))
18255 (setq msg "Creating images for buffer...")))
18256 ((equal arg '(4))
18257 (org-with-limited-levels (org-back-to-heading t))
18258 (setq beg (point))
18259 (setq end (progn (org-end-of-subtree t) (point)))
18260 (if (org-remove-latex-fragment-image-overlays beg end)
18261 (progn
18262 (message "LaTeX fragment images removed from subtree")
18263 (throw 'exit nil))
18264 (setq msg "Creating images for subtree...")))
18265 ((let ((datum (org-element-context)))
18266 (when (memq (org-element-type datum)
18267 '(latex-environment latex-fragment))
18268 (setq beg (org-element-property :begin datum))
18269 (setq end (org-element-property :end datum))
18270 (if (org-remove-latex-fragment-image-overlays beg end)
18271 (progn (message "LaTeX fragment image removed")
18272 (throw 'exit nil))
18273 (setq msg "Creating image...")))))
18275 (org-with-limited-levels
18276 (setq beg (if (org-at-heading-p) (line-beginning-position)
18277 (outline-previous-heading)
18278 (point)))
18279 (setq end (progn (outline-next-heading) (point)))
18280 (if (org-remove-latex-fragment-image-overlays beg end)
18281 (progn
18282 (message "LaTeX fragment images removed from section")
18283 (throw 'exit nil))
18284 (setq msg "Creating images for section...")))))
18285 (let ((file (buffer-file-name (buffer-base-buffer))))
18286 (org-format-latex
18287 (concat org-preview-latex-image-directory "org-ltximg")
18288 beg end
18289 ;; Emacs cannot overlay images from remote hosts. Create
18290 ;; it in `temporary-file-directory' instead.
18291 (if (or (not file) (file-remote-p file))
18292 temporary-file-directory
18293 default-directory)
18294 'overlays msg 'forbuffer org-preview-latex-default-process))
18295 (message (concat msg "done")))))))
18297 (defun org-format-latex
18298 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18299 "Replace LaTeX fragments with links to an image.
18301 The function takes care of creating the replacement image.
18303 Only consider fragments between BEG and END when those are
18304 provided.
18306 When optional argument OVERLAYS is non-nil, display the image on
18307 top of the fragment instead of replacing it.
18309 PROCESSING-TYPE is the conversion method to use, as a symbol.
18311 Some of the options can be changed using the variable
18312 `org-format-latex-options', which see."
18313 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18314 (unless (eq processing-type 'verbatim)
18315 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18316 (cnt 0)
18317 checkdir-flag)
18318 (goto-char (or beg (point-min)))
18319 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18320 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18321 (overlay-recenter (or end (point-max))))
18322 (while (re-search-forward math-regexp end t)
18323 (unless (and overlays
18324 (eq (get-char-property (point) 'org-overlay-type)
18325 'org-latex-overlay))
18326 (let* ((context (org-element-context))
18327 (type (org-element-type context)))
18328 (when (memq type '(latex-environment latex-fragment))
18329 (let ((block-type (eq type 'latex-environment))
18330 (value (org-element-property :value context))
18331 (beg (org-element-property :begin context))
18332 (end (save-excursion
18333 (goto-char (org-element-property :end context))
18334 (skip-chars-backward " \r\t\n")
18335 (point))))
18336 (cond
18337 ((eq processing-type 'mathjax)
18338 ;; Prepare for MathJax processing.
18339 (if (not (string-match "\\`\\$\\$?" value))
18340 (goto-char end)
18341 (delete-region beg end)
18342 (if (string= (match-string 0 value) "$$")
18343 (insert "\\[" (substring value 2 -2) "\\]")
18344 (insert "\\(" (substring value 1 -1) "\\)"))))
18345 ((assq processing-type org-preview-latex-process-alist)
18346 ;; Process to an image.
18347 (cl-incf cnt)
18348 (goto-char beg)
18349 (let* ((processing-info
18350 (cdr (assq processing-type org-preview-latex-process-alist)))
18351 (face (face-at-point))
18352 ;; Get the colors from the face at point.
18354 (let ((color (plist-get org-format-latex-options
18355 :foreground)))
18356 (if (and forbuffer (eq color 'auto))
18357 (face-attribute face :foreground nil 'default)
18358 color)))
18360 (let ((color (plist-get org-format-latex-options
18361 :background)))
18362 (if (and forbuffer (eq color 'auto))
18363 (face-attribute face :background nil 'default)
18364 color)))
18365 (hash (sha1 (prin1-to-string
18366 (list org-format-latex-header
18367 org-latex-default-packages-alist
18368 org-latex-packages-alist
18369 org-format-latex-options
18370 forbuffer value fg bg))))
18371 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18372 (absprefix (expand-file-name prefix dir))
18373 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18374 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18375 (sep (and block-type "\n\n"))
18376 (link (concat sep "[[file:" linkfile "]]" sep))
18377 (options
18378 (org-combine-plists
18379 org-format-latex-options
18380 `(:foreground ,fg :background ,bg))))
18381 (when msg (message msg cnt))
18382 (unless checkdir-flag ; Ensure the directory exists.
18383 (setq checkdir-flag t)
18384 (let ((todir (file-name-directory absprefix)))
18385 (unless (file-directory-p todir)
18386 (make-directory todir t))))
18387 (unless (file-exists-p movefile)
18388 (org-create-formula-image
18389 value movefile options forbuffer processing-type))
18390 (if overlays
18391 (progn
18392 (dolist (o (overlays-in beg end))
18393 (when (eq (overlay-get o 'org-overlay-type)
18394 'org-latex-overlay)
18395 (delete-overlay o)))
18396 (org--format-latex-make-overlay beg end movefile imagetype)
18397 (goto-char end))
18398 (delete-region beg end)
18399 (insert
18400 (org-add-props link
18401 (list 'org-latex-src
18402 (replace-regexp-in-string "\"" "" value)
18403 'org-latex-src-embed-type
18404 (if block-type 'paragraph 'character)))))))
18405 ((eq processing-type 'mathml)
18406 ;; Process to MathML.
18407 (unless (org-format-latex-mathml-available-p)
18408 (user-error "LaTeX to MathML converter not configured"))
18409 (cl-incf cnt)
18410 (when msg (message msg cnt))
18411 (goto-char beg)
18412 (delete-region beg end)
18413 (insert (org-format-latex-as-mathml
18414 value block-type prefix dir)))
18416 (error "Unknown conversion process %s for LaTeX fragments"
18417 processing-type)))))))))))
18419 (defun org-create-math-formula (latex-frag &optional mathml-file)
18420 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18421 Use `org-latex-to-mathml-convert-command'. If the conversion is
18422 sucessful, return the portion between \"<math...> </math>\"
18423 elements otherwise return nil. When MATHML-FILE is specified,
18424 write the results in to that file. When invoked as an
18425 interactive command, prompt for LATEX-FRAG, with initial value
18426 set to the current active region and echo the results for user
18427 inspection."
18428 (interactive (list (let ((frag (when (org-region-active-p)
18429 (buffer-substring-no-properties
18430 (region-beginning) (region-end)))))
18431 (read-string "LaTeX Fragment: " frag nil frag))))
18432 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18433 (let* ((tmp-in-file
18434 (let ((file (file-relative-name
18435 (make-temp-name (expand-file-name "ltxmathml-in")))))
18436 (write-region latex-frag nil file)
18437 file))
18438 (tmp-out-file (file-relative-name
18439 (make-temp-name (expand-file-name "ltxmathml-out"))))
18440 (cmd (format-spec
18441 org-latex-to-mathml-convert-command
18442 `((?j . ,(and org-latex-to-mathml-jar-file
18443 (shell-quote-argument
18444 (expand-file-name
18445 org-latex-to-mathml-jar-file))))
18446 (?I . ,(shell-quote-argument tmp-in-file))
18447 (?i . ,latex-frag)
18448 (?o . ,(shell-quote-argument tmp-out-file)))))
18449 mathml shell-command-output)
18450 (when (called-interactively-p 'any)
18451 (unless (org-format-latex-mathml-available-p)
18452 (user-error "LaTeX to MathML converter not configured")))
18453 (message "Running %s" cmd)
18454 (setq shell-command-output (shell-command-to-string cmd))
18455 (setq mathml
18456 (when (file-readable-p tmp-out-file)
18457 (with-current-buffer (find-file-noselect tmp-out-file t)
18458 (goto-char (point-min))
18459 (when (re-search-forward
18460 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18461 (regexp-quote
18462 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18463 nil t)
18464 (prog1 (match-string 0) (kill-buffer))))))
18465 (cond
18466 (mathml
18467 (setq mathml
18468 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18469 (when mathml-file
18470 (write-region mathml nil mathml-file))
18471 (when (called-interactively-p 'any)
18472 (message mathml)))
18473 ((message "LaTeX to MathML conversion failed")
18474 (message shell-command-output)))
18475 (delete-file tmp-in-file)
18476 (when (file-exists-p tmp-out-file)
18477 (delete-file tmp-out-file))
18478 mathml))
18480 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18481 prefix &optional dir)
18482 "Use `org-create-math-formula' but check local cache first."
18483 (let* ((absprefix (expand-file-name prefix dir))
18484 (print-length nil) (print-level nil)
18485 (formula-id (concat
18486 "formula-"
18487 (sha1
18488 (prin1-to-string
18489 (list latex-frag
18490 org-latex-to-mathml-convert-command)))))
18491 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18492 (formula-cache-dir (file-name-directory formula-cache)))
18494 (unless (file-directory-p formula-cache-dir)
18495 (make-directory formula-cache-dir t))
18497 (unless (file-exists-p formula-cache)
18498 (org-create-math-formula latex-frag formula-cache))
18500 (if (file-exists-p formula-cache)
18501 ;; Successful conversion. Return the link to MathML file.
18502 (org-add-props
18503 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18504 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18505 'org-latex-src-embed-type (if latex-frag-type
18506 'paragraph 'character)))
18507 ;; Failed conversion. Return the LaTeX fragment verbatim
18508 latex-frag)))
18510 (defun org--get-display-dpi ()
18511 "Get the DPI of the display.
18512 The function assumes that the display has the same pixel width in
18513 the horizontal and vertical directions."
18514 (if (display-graphic-p)
18515 (round (/ (display-pixel-height)
18516 (/ (display-mm-height) 25.4)))
18517 (error "Attempt to calculate the dpi of a non-graphic display")))
18519 (defun org-create-formula-image
18520 (string tofile options buffer &optional processing-type)
18521 "Create an image from LaTeX source using external processes.
18523 The LaTeX STRING is saved to a temporary LaTeX file, then
18524 converted to an image file by process PROCESSING-TYPE defined in
18525 `org-preview-latex-process-alist'. A nil value defaults to
18526 `org-preview-latex-default-process'.
18528 The generated image file is eventually moved to TOFILE.
18530 The OPTIONS argument controls the size, foreground color and
18531 background color of the generated image.
18533 When BUFFER non-nil, this function is used for LaTeX previewing.
18534 Otherwise, it is used to deal with LaTeX snippets showed in
18535 a HTML file."
18536 (let* ((processing-type (or processing-type
18537 org-preview-latex-default-process))
18538 (processing-info
18539 (cdr (assq processing-type org-preview-latex-process-alist)))
18540 (programs (plist-get processing-info :programs))
18541 (error-message (or (plist-get processing-info :message) ""))
18542 (use-xcolor (plist-get processing-info :use-xcolor))
18543 (image-input-type (plist-get processing-info :image-input-type))
18544 (image-output-type (plist-get processing-info :image-output-type))
18545 (post-clean (or (plist-get processing-info :post-clean)
18546 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18547 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18548 (latex-header
18549 (or (plist-get processing-info :latex-header)
18550 (org-latex-make-preamble
18551 (org-export-get-environment (org-export-get-backend 'latex))
18552 org-format-latex-header
18553 'snippet)))
18554 (latex-compiler (plist-get processing-info :latex-compiler))
18555 (image-converter (plist-get processing-info :image-converter))
18556 (tmpdir temporary-file-directory)
18557 (texfilebase (make-temp-name
18558 (expand-file-name "orgtex" tmpdir)))
18559 (texfile (concat texfilebase ".tex"))
18560 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18561 '(1.0 . 1.0)))
18562 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18563 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18564 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18565 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18566 "Black"))
18567 (bg (or (plist-get options (if buffer :background :html-background))
18568 "Transparent"))
18569 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18570 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18571 (dolist (program programs)
18572 (org-check-external-command program error-message))
18573 (if use-xcolor
18574 (progn (if (eq fg 'default)
18575 (setq fg (org-latex-color :foreground))
18576 (setq fg (org-latex-color-format fg)))
18577 (if (eq bg 'default)
18578 (setq bg (org-latex-color :background))
18579 (setq bg (org-latex-color-format
18580 (if (string= bg "Transparent") "white" bg))))
18581 (with-temp-file texfile
18582 (insert latex-header)
18583 (insert "\n\\begin{document}\n"
18584 "\\definecolor{fg}{rgb}{" fg "}\n"
18585 "\\definecolor{bg}{rgb}{" bg "}\n"
18586 "\n\\pagecolor{bg}\n"
18587 "\n{\\color{fg}\n"
18588 string
18589 "\n}\n"
18590 "\n\\end{document}\n")))
18591 (if (eq fg 'default)
18592 (setq fg (org-dvipng-color :foreground))
18593 (unless (string= fg "Transparent")
18594 (setq fg (org-dvipng-color-format fg))))
18595 (if (eq bg 'default)
18596 (setq bg (org-dvipng-color :background))
18597 (unless (string= bg "Transparent")
18598 (setq bg (org-dvipng-color-format bg))))
18599 (with-temp-file texfile
18600 (insert latex-header)
18601 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18603 (let* ((err-msg (format "Please adjust `%s' part of \
18604 `org-preview-latex-process-alist'."
18605 processing-type))
18606 (image-input-file
18607 (org-compile-file
18608 texfile latex-compiler image-input-type err-msg log-buf))
18609 (image-output-file
18610 (org-compile-file
18611 image-input-file image-converter image-output-type err-msg log-buf
18612 `((?F . ,(shell-quote-argument fg))
18613 (?B . ,(shell-quote-argument bg))
18614 (?D . ,(shell-quote-argument (format "%s" dpi)))
18615 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18616 (copy-file image-output-file tofile 'replace)
18617 (dolist (e post-clean)
18618 (when (file-exists-p (concat texfilebase e))
18619 (delete-file (concat texfilebase e))))
18620 image-output-file)))
18622 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18623 "Fill a LaTeX header template TPL.
18624 In the template, the following place holders will be recognized:
18626 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18627 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18628 [PACKAGES] \\usepackage statements for PKG
18629 [NO-PACKAGES] do not include PKG
18630 [EXTRA] the string EXTRA
18631 [NO-EXTRA] do not include EXTRA
18633 For backward compatibility, if both the positive and the negative place
18634 holder is missing, the positive one (without the \"NO-\") will be
18635 assumed to be present at the end of the template.
18636 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18637 EXTRA is a string.
18638 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18639 (let (rpl (end ""))
18640 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18641 (setq rpl (if (or (match-end 1) (not def-pkg))
18642 "" (org-latex-packages-to-string def-pkg snippets-p t))
18643 tpl (replace-match rpl t t tpl))
18644 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18646 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18647 (setq rpl (if (or (match-end 1) (not pkg))
18648 "" (org-latex-packages-to-string pkg snippets-p t))
18649 tpl (replace-match rpl t t tpl))
18650 (when pkg (setq end
18651 (concat end "\n"
18652 (org-latex-packages-to-string pkg snippets-p)))))
18654 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18655 (setq rpl (if (or (match-end 1) (not extra))
18656 "" (concat extra "\n"))
18657 tpl (replace-match rpl t t tpl))
18658 (when (and extra (string-match "\\S-" extra))
18659 (setq end (concat end "\n" extra))))
18661 (if (string-match "\\S-" end)
18662 (concat tpl "\n" end)
18663 tpl)))
18665 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18666 "Turn an alist of packages into a string with the \\usepackage macros."
18667 (setq pkg (mapconcat (lambda(p)
18668 (cond
18669 ((stringp p) p)
18670 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18671 (format "%% Package %s omitted" (cadr p)))
18672 ((equal "" (car p))
18673 (format "\\usepackage{%s}" (cadr p)))
18675 (format "\\usepackage[%s]{%s}"
18676 (car p) (cadr p)))))
18678 "\n"))
18679 (if newline (concat pkg "\n") pkg))
18681 (defun org-dvipng-color (attr)
18682 "Return a RGB color specification for dvipng."
18683 (org-dvipng-color-format (face-attribute 'default attr nil)))
18685 (defun org-dvipng-color-format (color-name)
18686 "Convert COLOR-NAME to a RGB color value for dvipng."
18687 (apply #'format "rgb %s %s %s"
18688 (mapcar 'org-normalize-color
18689 (color-values color-name))))
18691 (defun org-latex-color (attr)
18692 "Return a RGB color for the LaTeX color package."
18693 (org-latex-color-format (face-attribute 'default attr nil)))
18695 (defun org-latex-color-format (color-name)
18696 "Convert COLOR-NAME to a RGB color value."
18697 (apply #'format "%s,%s,%s"
18698 (mapcar 'org-normalize-color
18699 (color-values color-name))))
18701 (defun org-normalize-color (value)
18702 "Return string to be used as color value for an RGB component."
18703 (format "%g" (/ value 65535.0)))
18707 ;; Image display
18709 (defvar-local org-inline-image-overlays nil)
18711 (defun org-toggle-inline-images (&optional include-linked)
18712 "Toggle the display of inline images.
18713 INCLUDE-LINKED is passed to `org-display-inline-images'."
18714 (interactive "P")
18715 (if org-inline-image-overlays
18716 (progn
18717 (org-remove-inline-images)
18718 (when (called-interactively-p 'interactive)
18719 (message "Inline image display turned off")))
18720 (org-display-inline-images include-linked)
18721 (when (called-interactively-p 'interactive)
18722 (message (if org-inline-image-overlays
18723 (format "%d images displayed inline"
18724 (length org-inline-image-overlays))
18725 "No images to display inline")))))
18727 (defun org-redisplay-inline-images ()
18728 "Refresh the display of inline images."
18729 (interactive)
18730 (if (not org-inline-image-overlays)
18731 (org-toggle-inline-images)
18732 (org-toggle-inline-images)
18733 (org-toggle-inline-images)))
18735 (defun org-display-inline-images (&optional include-linked refresh beg end)
18736 "Display inline images.
18738 An inline image is a link which follows either of these
18739 conventions:
18741 1. Its path is a file with an extension matching return value
18742 from `image-file-name-regexp' and it has no contents.
18744 2. Its description consists in a single link of the previous
18745 type.
18747 When optional argument INCLUDE-LINKED is non-nil, also links with
18748 a text description part will be inlined. This can be nice for
18749 a quick look at those images, but it does not reflect what
18750 exported files will look like.
18752 When optional argument REFRESH is non-nil, refresh existing
18753 images between BEG and END. This will create new image displays
18754 only if necessary. BEG and END default to the buffer
18755 boundaries."
18756 (interactive "P")
18757 (when (display-graphic-p)
18758 (unless refresh
18759 (org-remove-inline-images)
18760 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18761 (org-with-wide-buffer
18762 (goto-char (or beg (point-min)))
18763 (let* ((case-fold-search t)
18764 (file-extension-re (image-file-name-regexp))
18765 (link-abbrevs (mapcar #'car
18766 (append org-link-abbrev-alist-local
18767 org-link-abbrev-alist)))
18768 ;; Check absolute, relative file names and explicit
18769 ;; "file:" links. Also check link abbreviations since
18770 ;; some might expand to "file" links.
18771 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18772 (if (not link-abbrevs) ""
18773 (format "\\|\\(?:%s:\\)"
18774 (regexp-opt link-abbrevs))))))
18775 (while (re-search-forward file-types-re end t)
18776 (let ((link (save-match-data (org-element-context))))
18777 ;; Check if we're at an inline image, i.e., an image file
18778 ;; link without a description (unless INCLUDE-LINKED is
18779 ;; non-nil).
18780 (when (and (equal "file" (org-element-property :type link))
18781 (or include-linked
18782 (null (org-element-contents link)))
18783 (string-match-p file-extension-re
18784 (org-element-property :path link)))
18785 (let ((file (expand-file-name
18786 (org-link-unescape
18787 (org-element-property :path link)))))
18788 (when (file-exists-p file)
18789 (let ((width
18790 ;; Apply `org-image-actual-width' specifications.
18791 (cond
18792 ((not (image-type-available-p 'imagemagick)) nil)
18793 ((eq org-image-actual-width t) nil)
18794 ((listp org-image-actual-width)
18796 ;; First try to find a width among
18797 ;; attributes associated to the paragraph
18798 ;; containing link.
18799 (let ((paragraph
18800 (let ((e link))
18801 (while (and (setq e (org-element-property
18802 :parent e))
18803 (not (eq (org-element-type e)
18804 'paragraph))))
18805 e)))
18806 (when paragraph
18807 (save-excursion
18808 (goto-char (org-element-property :begin paragraph))
18809 (when
18810 (re-search-forward
18811 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18812 (org-element-property
18813 :post-affiliated paragraph)
18815 (string-to-number (match-string 1))))))
18816 ;; Otherwise, fall-back to provided number.
18817 (car org-image-actual-width)))
18818 ((numberp org-image-actual-width)
18819 org-image-actual-width)))
18820 (old (get-char-property-and-overlay
18821 (org-element-property :begin link)
18822 'org-image-overlay)))
18823 (if (and (car-safe old) refresh)
18824 (image-refresh (overlay-get (cdr old) 'display))
18825 (let ((image (create-image file
18826 (and width 'imagemagick)
18828 :width width)))
18829 (when image
18830 (let ((ov (make-overlay
18831 (org-element-property :begin link)
18832 (progn
18833 (goto-char
18834 (org-element-property :end link))
18835 (skip-chars-backward " \t")
18836 (point)))))
18837 (overlay-put ov 'display image)
18838 (overlay-put ov 'face 'default)
18839 (overlay-put ov 'org-image-overlay t)
18840 (overlay-put
18841 ov 'modification-hooks
18842 (list 'org-display-inline-remove-overlay))
18843 (push ov org-inline-image-overlays)))))))))))))))
18845 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18846 "Remove inline-display overlay if a corresponding region is modified."
18847 (let ((inhibit-modification-hooks t))
18848 (when (and ov after)
18849 (delete ov org-inline-image-overlays)
18850 (delete-overlay ov))))
18852 (defun org-remove-inline-images ()
18853 "Remove inline display of images."
18854 (interactive)
18855 (mapc #'delete-overlay org-inline-image-overlays)
18856 (setq org-inline-image-overlays nil))
18858 ;;;; Key bindings
18860 (defun org-remap (map &rest commands)
18861 "In MAP, remap the functions given in COMMANDS.
18862 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18863 (let (new old)
18864 (while commands
18865 (setq old (pop commands) new (pop commands))
18866 (org-defkey map (vector 'remap old) new))))
18868 ;; Outline functions from `outline-mode-prefix-map'
18869 ;; that can be remapped in Org:
18870 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18871 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
18872 (define-key org-mode-map [remap outline-forward-same-level]
18873 'org-forward-heading-same-level)
18874 (define-key org-mode-map [remap outline-backward-same-level]
18875 'org-backward-heading-same-level)
18876 (define-key org-mode-map [remap outline-show-branches]
18877 'org-kill-note-or-show-branches)
18878 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18879 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18880 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18881 (define-key org-mode-map [remap outline-next-visible-heading]
18882 'org-next-visible-heading)
18883 (define-key org-mode-map [remap outline-previous-visible-heading]
18884 'org-previous-visible-heading)
18885 (define-key org-mode-map [remap show-children] 'org-show-children)
18887 ;; Outline functions from `outline-mode-prefix-map' that can not
18888 ;; be remapped in Org:
18890 ;; - the column "key binding" shows whether the Outline function is still
18891 ;; available in Org mode on the same key that it has been bound to in
18892 ;; Outline mode:
18893 ;; - "overridden": key used for a different functionality in Org mode
18894 ;; - else: key still bound to the same Outline function in Org mode
18896 ;; | Outline function | key binding | Org replacement |
18897 ;; |------------------------------------+-------------+--------------------------|
18898 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18899 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18900 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18901 ;; | `show-entry' | overridden | no replacement |
18902 ;; | `show-branches' | `C-c C-k' | still same function |
18903 ;; | `show-subtree' | overridden | visibility cycling |
18904 ;; | `show-all' | overridden | no replacement |
18905 ;; | `hide-subtree' | overridden | visibility cycling |
18906 ;; | `hide-body' | overridden | no replacement |
18907 ;; | `hide-entry' | overridden | visibility cycling |
18908 ;; | `hide-leaves' | overridden | no replacement |
18909 ;; | `hide-sublevels' | overridden | no replacement |
18910 ;; | `hide-other' | overridden | no replacement |
18912 ;; Make `C-c C-x' a prefix key
18913 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18915 ;; TAB key with modifiers
18916 (org-defkey org-mode-map "\C-i" 'org-cycle)
18917 (org-defkey org-mode-map [(tab)] 'org-cycle)
18918 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18919 (org-defkey org-mode-map "\M-\t" #'pcomplete)
18921 ;; The following line is necessary under Suse GNU/Linux
18922 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
18923 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18924 (define-key org-mode-map [backtab] 'org-shifttab)
18926 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18927 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18928 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18930 ;; Cursor keys with modifiers
18931 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18932 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18933 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18934 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18936 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
18937 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
18938 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18939 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18940 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18941 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18943 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18944 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18945 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18946 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18948 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18949 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18950 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18951 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18953 ;; Babel keys
18954 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18955 (dolist (pair org-babel-key-bindings)
18956 (define-key org-babel-map (car pair) (cdr pair)))
18958 ;;; Extra keys for tty access.
18959 ;; We only set them when really needed because otherwise the
18960 ;; menus don't show the simple keys
18962 (when (or org-use-extra-keys (not window-system))
18963 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18964 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18965 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18966 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18967 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18968 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18969 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18970 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18971 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18972 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18973 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18974 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18975 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18976 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18977 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18978 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18979 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18980 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18981 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18982 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18983 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18984 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18985 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
18986 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18987 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18988 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18989 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18990 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18992 ;; All the other keys
18993 (org-remap org-mode-map
18994 'self-insert-command 'org-self-insert-command
18995 'delete-char 'org-delete-char
18996 'delete-backward-char 'org-delete-backward-char)
18997 (org-defkey org-mode-map "|" 'org-force-self-insert)
18999 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19000 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19001 (if (boundp 'narrow-map)
19002 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19003 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19004 (if (boundp 'narrow-map)
19005 (org-defkey narrow-map "b" 'org-narrow-to-block)
19006 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19007 (if (boundp 'narrow-map)
19008 (org-defkey narrow-map "e" 'org-narrow-to-element)
19009 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19010 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19011 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19012 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19013 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19014 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19015 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19016 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19017 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19018 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19019 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19020 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19021 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19022 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19023 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19024 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19025 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19026 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19027 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19028 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19029 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19030 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19031 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19032 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19033 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19034 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19035 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19036 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19037 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19038 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19039 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19040 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19041 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19042 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19043 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19044 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19045 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19046 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19047 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19048 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19049 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19050 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19051 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19052 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19053 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19054 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19055 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19056 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19057 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19058 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19059 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19060 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19061 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19062 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19063 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19064 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19065 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19066 (org-defkey org-mode-map "\C-c^" 'org-sort)
19067 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19068 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19069 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19070 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19071 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19072 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19073 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19074 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19075 (org-defkey org-mode-map "\C-m" 'org-return)
19076 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19077 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19078 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19079 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19080 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19081 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19082 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19083 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19084 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19085 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19086 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19087 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19088 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19089 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19090 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19091 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19092 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19093 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19094 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19095 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19096 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19097 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19098 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19099 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19100 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19102 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19103 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19104 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19106 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19107 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19108 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19109 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19110 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19111 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19112 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19113 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19114 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19115 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19116 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19117 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19118 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19119 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19120 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19121 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19122 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19123 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19124 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19125 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19126 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19127 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19128 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19130 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19131 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19132 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19133 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19134 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19136 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19138 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19140 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19141 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19143 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19146 (defconst org-speed-commands-default
19148 ("Outline Navigation")
19149 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19150 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19151 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19152 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19153 ("F" . org-next-block)
19154 ("B" . org-previous-block)
19155 ("u" . (org-speed-move-safe 'outline-up-heading))
19156 ("j" . org-goto)
19157 ("g" . (org-refile t))
19158 ("Outline Visibility")
19159 ("c" . org-cycle)
19160 ("C" . org-shifttab)
19161 (" " . org-display-outline-path)
19162 ("s" . org-narrow-to-subtree)
19163 ("=" . org-columns)
19164 ("Outline Structure Editing")
19165 ("U" . org-metaup)
19166 ("D" . org-metadown)
19167 ("r" . org-metaright)
19168 ("l" . org-metaleft)
19169 ("R" . org-shiftmetaright)
19170 ("L" . org-shiftmetaleft)
19171 ("i" . (progn (forward-char 1) (call-interactively
19172 'org-insert-heading-respect-content)))
19173 ("^" . org-sort)
19174 ("w" . org-refile)
19175 ("a" . org-archive-subtree-default-with-confirmation)
19176 ("@" . org-mark-subtree)
19177 ("#" . org-toggle-comment)
19178 ("Clock Commands")
19179 ("I" . org-clock-in)
19180 ("O" . org-clock-out)
19181 ("Meta Data Editing")
19182 ("t" . org-todo)
19183 ("," . (org-priority))
19184 ("0" . (org-priority ?\ ))
19185 ("1" . (org-priority ?A))
19186 ("2" . (org-priority ?B))
19187 ("3" . (org-priority ?C))
19188 (":" . org-set-tags-command)
19189 ("e" . org-set-effort)
19190 ("E" . org-inc-effort)
19191 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19192 (org-entry-put (point) "APPT_WARNTIME" m)))
19193 ("Agenda Views etc")
19194 ("v" . org-agenda)
19195 ("/" . org-sparse-tree)
19196 ("Misc")
19197 ("o" . org-open-at-point)
19198 ("?" . org-speed-command-help)
19199 ("<" . (org-agenda-set-restriction-lock 'subtree))
19200 (">" . (org-agenda-remove-restriction-lock))
19202 "The default speed commands.")
19204 (defun org-print-speed-command (e)
19205 (if (> (length (car e)) 1)
19206 (progn
19207 (princ "\n")
19208 (princ (car e))
19209 (princ "\n")
19210 (princ (make-string (length (car e)) ?-))
19211 (princ "\n"))
19212 (princ (car e))
19213 (princ " ")
19214 (if (symbolp (cdr e))
19215 (princ (symbol-name (cdr e)))
19216 (prin1 (cdr e)))
19217 (princ "\n")))
19219 (defun org-speed-command-help ()
19220 "Show the available speed commands."
19221 (interactive)
19222 (if (not org-use-speed-commands)
19223 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19224 (with-output-to-temp-buffer "*Help*"
19225 (princ "User-defined Speed commands\n===========================\n")
19226 (mapc #'org-print-speed-command org-speed-commands-user)
19227 (princ "\n")
19228 (princ "Built-in Speed commands\n=======================\n")
19229 (mapc #'org-print-speed-command org-speed-commands-default))
19230 (with-current-buffer "*Help*"
19231 (setq truncate-lines t))))
19233 (defun org-speed-move-safe (cmd)
19234 "Execute CMD, but make sure that the cursor always ends up in a headline.
19235 If not, return to the original position and throw an error."
19236 (interactive)
19237 (let ((pos (point)))
19238 (call-interactively cmd)
19239 (unless (and (bolp) (org-at-heading-p))
19240 (goto-char pos)
19241 (error "Boundary reached while executing %s" cmd))))
19243 (defvar org-self-insert-command-undo-counter 0)
19245 (defvar org-table-auto-blank-field) ; defined in org-table.el
19246 (defvar org-speed-command nil)
19248 (defun org-speed-command-activate (keys)
19249 "Hook for activating single-letter speed commands.
19250 `org-speed-commands-default' specifies a minimal command set.
19251 Use `org-speed-commands-user' for further customization."
19252 (when (or (and (bolp) (looking-at org-outline-regexp))
19253 (and (functionp org-use-speed-commands)
19254 (funcall org-use-speed-commands)))
19255 (cdr (assoc keys (append org-speed-commands-user
19256 org-speed-commands-default)))))
19258 (defun org-babel-speed-command-activate (keys)
19259 "Hook for activating single-letter code block commands."
19260 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19261 (cdr (assoc keys org-babel-key-bindings))))
19263 (defcustom org-speed-command-hook
19264 '(org-speed-command-activate org-babel-speed-command-activate)
19265 "Hook for activating speed commands at strategic locations.
19266 Hook functions are called in sequence until a valid handler is
19267 found.
19269 Each hook takes a single argument, a user-pressed command key
19270 which is also a `self-insert-command' from the global map.
19272 Within the hook, examine the cursor position and the command key
19273 and return nil or a valid handler as appropriate. Handler could
19274 be one of an interactive command, a function, or a form.
19276 Set `org-use-speed-commands' to non-nil value to enable this
19277 hook. The default setting is `org-speed-command-activate'."
19278 :group 'org-structure
19279 :version "24.1"
19280 :type 'hook)
19282 (defun org-self-insert-command (N)
19283 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19284 If the cursor is in a table looking at whitespace, the whitespace is
19285 overwritten, and the table is not marked as requiring realignment."
19286 (interactive "p")
19287 (org-check-before-invisible-edit 'insert)
19288 (cond
19289 ((and org-use-speed-commands
19290 (let ((kv (this-command-keys-vector)))
19291 (setq org-speed-command
19292 (run-hook-with-args-until-success
19293 'org-speed-command-hook
19294 (make-string 1 (aref kv (1- (length kv))))))))
19295 (cond
19296 ((commandp org-speed-command)
19297 (setq this-command org-speed-command)
19298 (call-interactively org-speed-command))
19299 ((functionp org-speed-command)
19300 (funcall org-speed-command))
19301 ((and org-speed-command (listp org-speed-command))
19302 (eval org-speed-command))
19303 (t (let (org-use-speed-commands)
19304 (call-interactively 'org-self-insert-command)))))
19305 ((and
19306 (org-at-table-p)
19307 (eq N 1)
19308 (not (org-region-active-p))
19309 (progn
19310 ;; Check if we blank the field, and if that triggers align.
19311 (and (featurep 'org-table) org-table-auto-blank-field
19312 (memq last-command
19313 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19314 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19315 ;; Got extra space, this field does not determine
19316 ;; column width.
19317 (let (org-table-may-need-update) (org-table-blank-field))
19318 ;; No extra space, this field may determine column
19319 ;; width.
19320 (org-table-blank-field)))
19322 (looking-at "[^|\n]* \\( \\)|"))
19323 ;; There is room for insertion without re-aligning the table.
19324 (delete-region (match-beginning 1) (match-end 1))
19325 (self-insert-command N))
19327 (setq org-table-may-need-update t)
19328 (self-insert-command N)
19329 (org-fix-tags-on-the-fly)
19330 (when org-self-insert-cluster-for-undo
19331 (if (not (eq last-command 'org-self-insert-command))
19332 (setq org-self-insert-command-undo-counter 1)
19333 (if (>= org-self-insert-command-undo-counter 20)
19334 (setq org-self-insert-command-undo-counter 1)
19335 (and (> org-self-insert-command-undo-counter 0)
19336 buffer-undo-list (listp buffer-undo-list)
19337 (not (cadr buffer-undo-list)) ; remove nil entry
19338 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19339 (setq org-self-insert-command-undo-counter
19340 (1+ org-self-insert-command-undo-counter))))))))
19342 (defun org-check-before-invisible-edit (kind)
19343 "Check is editing if kind KIND would be dangerous with invisible text around.
19344 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19345 ;; First, try to get out of here as quickly as possible, to reduce overhead
19346 (when (and org-catch-invisible-edits
19347 (or (not (boundp 'visible-mode)) (not visible-mode))
19348 (or (get-char-property (point) 'invisible)
19349 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19350 ;; OK, we need to take a closer look. Do not consider
19351 ;; invisibility obtained through text properties (e.g., link
19352 ;; fontification), as it cannot be toggled.
19353 (let* ((invisible-at-point
19354 (pcase (get-char-property-and-overlay (point) 'invisible)
19355 (`(,_ . ,(and (pred overlayp) o)) o)))
19356 ;; Assume that point cannot land in the middle of an
19357 ;; overlay, or between two overlays.
19358 (invisible-before-point
19359 (and (not invisible-at-point)
19360 (not (bobp))
19361 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19362 (`(,_ . ,(and (pred overlayp) o)) o))))
19363 (border-and-ok-direction
19365 ;; Check if we are acting predictably before invisible
19366 ;; text.
19367 (and invisible-at-point
19368 (memq kind '(insert delete-backward)))
19369 ;; Check if we are acting predictably after invisible text
19370 ;; This works not well, and I have turned it off. It seems
19371 ;; better to always show and stop after invisible text.
19372 ;; (and (not invisible-at-point) invisible-before-point
19373 ;; (memq kind '(insert delete)))
19375 (when (or invisible-at-point invisible-before-point)
19376 (when (eq org-catch-invisible-edits 'error)
19377 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19378 (if (and org-custom-properties-overlays
19379 (y-or-n-p "Display invisible properties in this buffer? "))
19380 (org-toggle-custom-properties-visibility)
19381 ;; Make the area visible
19382 (save-excursion
19383 (when invisible-before-point
19384 (goto-char
19385 (previous-single-char-property-change (point) 'invisible)))
19386 ;; Remove whatever overlay is currently making yet-to-be
19387 ;; edited text invisible. Also remove nested invisibility
19388 ;; related overlays.
19389 (delete-overlay (or invisible-at-point invisible-before-point))
19390 (let ((origin (if invisible-at-point (point) (1- (point)))))
19391 (while (pcase (get-char-property-and-overlay origin 'invisible)
19392 (`(,_ . ,(and (pred overlayp) o))
19393 (delete-overlay o)
19394 t)))))
19395 (cond
19396 ((eq org-catch-invisible-edits 'show)
19397 ;; That's it, we do the edit after showing
19398 (message
19399 "Unfolding invisible region around point before editing")
19400 (sit-for 1))
19401 ((and (eq org-catch-invisible-edits 'smart)
19402 border-and-ok-direction)
19403 (message "Unfolding invisible region around point before editing"))
19405 ;; Don't do the edit, make the user repeat it in full visibility
19406 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19408 (defun org-fix-tags-on-the-fly ()
19409 "Align tags in headline at point.
19410 Unlike to `org-set-tags', it ignores region and sorting."
19411 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19412 (org-at-heading-p))
19413 (let ((org-ignore-region t)
19414 (org-tags-sort-function nil))
19415 (org-set-tags nil t))))
19417 (defun org-delete-backward-char (N)
19418 "Like `delete-backward-char', insert whitespace at field end in tables.
19419 When deleting backwards, in tables this function will insert whitespace in
19420 front of the next \"|\" separator, to keep the table aligned. The table will
19421 still be marked for re-alignment if the field did fill the entire column,
19422 because, in this case the deletion might narrow the column."
19423 (interactive "p")
19424 (save-match-data
19425 (org-check-before-invisible-edit 'delete-backward)
19426 (if (and (org-at-table-p)
19427 (eq N 1)
19428 (not (org-region-active-p))
19429 (string-match "|" (buffer-substring (point-at-bol) (point)))
19430 (looking-at ".*?|"))
19431 (let ((pos (point))
19432 (noalign (looking-at "[^|\n\r]* |"))
19433 (c org-table-may-need-update))
19434 (backward-delete-char N)
19435 (unless overwrite-mode
19436 (skip-chars-forward "^|")
19437 (insert " ")
19438 (goto-char (1- pos)))
19439 ;; noalign: if there were two spaces at the end, this field
19440 ;; does not determine the width of the column.
19441 (when noalign (setq org-table-may-need-update c)))
19442 (backward-delete-char N)
19443 (org-fix-tags-on-the-fly))))
19445 (defun org-delete-char (N)
19446 "Like `delete-char', but insert whitespace at field end in tables.
19447 When deleting characters, in tables this function will insert whitespace in
19448 front of the next \"|\" separator, to keep the table aligned. The table will
19449 still be marked for re-alignment if the field did fill the entire column,
19450 because, in this case the deletion might narrow the column."
19451 (interactive "p")
19452 (save-match-data
19453 (org-check-before-invisible-edit 'delete)
19454 (if (and (org-at-table-p)
19455 (not (bolp))
19456 (not (= (char-after) ?|))
19457 (eq N 1))
19458 (if (looking-at ".*?|")
19459 (let ((pos (point))
19460 (noalign (looking-at "[^|\n\r]* |"))
19461 (c org-table-may-need-update))
19462 (replace-match
19463 (concat (substring (match-string 0) 1 -1) " |") nil t)
19464 (goto-char pos)
19465 ;; noalign: if there were two spaces at the end, this field
19466 ;; does not determine the width of the column.
19467 (when noalign (setq org-table-may-need-update c)))
19468 (delete-char N))
19469 (delete-char N)
19470 (org-fix-tags-on-the-fly))))
19472 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19473 (put 'org-self-insert-command 'delete-selection
19474 (lambda ()
19475 (not (run-hook-with-args-until-success
19476 'self-insert-uses-region-functions))))
19477 (put 'orgtbl-self-insert-command 'delete-selection
19478 (lambda ()
19479 (not (run-hook-with-args-until-success
19480 'self-insert-uses-region-functions))))
19481 (put 'org-delete-char 'delete-selection 'supersede)
19482 (put 'org-delete-backward-char 'delete-selection 'supersede)
19483 (put 'org-yank 'delete-selection 'yank)
19485 ;; Make `flyspell-mode' delay after some commands
19486 (put 'org-self-insert-command 'flyspell-delayed t)
19487 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19488 (put 'org-delete-char 'flyspell-delayed t)
19489 (put 'org-delete-backward-char 'flyspell-delayed t)
19491 ;; Make pabbrev-mode expand after Org mode commands
19492 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19493 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19495 (defun org-transpose-words ()
19496 "Transpose words for Org.
19497 This uses the `org-mode-transpose-word-syntax-table' syntax
19498 table, which interprets characters in `org-emphasis-alist' as
19499 word constituents."
19500 (interactive)
19501 (with-syntax-table org-mode-transpose-word-syntax-table
19502 (call-interactively 'transpose-words)))
19503 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19505 (defvar org-ctrl-c-ctrl-c-hook nil
19506 "Hook for functions attaching themselves to `C-c C-c'.
19508 This can be used to add additional functionality to the C-c C-c
19509 key which executes context-dependent commands. This hook is run
19510 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19511 run after the last test.
19513 Each function will be called with no arguments. The function
19514 must check if the context is appropriate for it to act. If yes,
19515 it should do its thing and then return a non-nil value. If the
19516 context is wrong, just do nothing and return nil.")
19518 (defvar org-ctrl-c-ctrl-c-final-hook nil
19519 "Hook for functions attaching themselves to `C-c C-c'.
19521 This can be used to add additional functionality to the C-c C-c
19522 key which executes context-dependent commands. This hook is run
19523 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19524 before the first test.
19526 Each function will be called with no arguments. The function
19527 must check if the context is appropriate for it to act. If yes,
19528 it should do its thing and then return a non-nil value. If the
19529 context is wrong, just do nothing and return nil.")
19531 (defvar org-tab-first-hook nil
19532 "Hook for functions to attach themselves to TAB.
19533 See `org-ctrl-c-ctrl-c-hook' for more information.
19534 This hook runs as the first action when TAB is pressed, even before
19535 `org-cycle' messes around with the `outline-regexp' to cater for
19536 inline tasks and plain list item folding.
19537 If any function in this hook returns t, any other actions that
19538 would have been caused by TAB (such as table field motion or visibility
19539 cycling) will not occur.")
19541 (defvar org-tab-after-check-for-table-hook nil
19542 "Hook for functions to attach themselves to TAB.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.
19544 This hook runs after it has been established that the cursor is not in a
19545 table, but before checking if the cursor is in a headline or if global cycling
19546 should be done.
19547 If any function in this hook returns t, not other actions like visibility
19548 cycling will be done.")
19550 (defvar org-tab-after-check-for-cycling-hook nil
19551 "Hook for functions to attach themselves to TAB.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.
19553 This hook runs after it has been established that not table field motion and
19554 not visibility should be done because of current context. This is probably
19555 the place where a package like yasnippets can hook in.")
19557 (defvar org-tab-before-tab-emulation-hook nil
19558 "Hook for functions to attach themselves to TAB.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.
19560 This hook runs after every other options for TAB have been exhausted, but
19561 before indentation and \t insertion takes place.")
19563 (defvar org-metaleft-hook nil
19564 "Hook for functions attaching themselves to `M-left'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-metaright-hook nil
19567 "Hook for functions attaching themselves to `M-right'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-metaup-hook nil
19570 "Hook for functions attaching themselves to `M-up'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-metadown-hook nil
19573 "Hook for functions attaching themselves to `M-down'.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftmetaleft-hook nil
19576 "Hook for functions attaching themselves to `M-S-left'.
19577 See `org-ctrl-c-ctrl-c-hook' for more information.")
19578 (defvar org-shiftmetaright-hook nil
19579 "Hook for functions attaching themselves to `M-S-right'.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.")
19581 (defvar org-shiftmetaup-hook nil
19582 "Hook for functions attaching themselves to `M-S-up'.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftmetadown-hook nil
19585 "Hook for functions attaching themselves to `M-S-down'.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19587 (defvar org-metareturn-hook nil
19588 "Hook for functions attaching themselves to `M-RET'.
19589 See `org-ctrl-c-ctrl-c-hook' for more information.")
19590 (defvar org-shiftup-hook nil
19591 "Hook for functions attaching themselves to `S-up'.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.")
19593 (defvar org-shiftup-final-hook nil
19594 "Hook for functions attaching themselves to `S-up'.
19595 This one runs after all other options except shift-select have been excluded.
19596 See `org-ctrl-c-ctrl-c-hook' for more information.")
19597 (defvar org-shiftdown-hook nil
19598 "Hook for functions attaching themselves to `S-down'.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.")
19600 (defvar org-shiftdown-final-hook nil
19601 "Hook for functions attaching themselves to `S-down'.
19602 This one runs after all other options except shift-select have been excluded.
19603 See `org-ctrl-c-ctrl-c-hook' for more information.")
19604 (defvar org-shiftleft-hook nil
19605 "Hook for functions attaching themselves to `S-left'.
19606 See `org-ctrl-c-ctrl-c-hook' for more information.")
19607 (defvar org-shiftleft-final-hook nil
19608 "Hook for functions attaching themselves to `S-left'.
19609 This one runs after all other options except shift-select have been excluded.
19610 See `org-ctrl-c-ctrl-c-hook' for more information.")
19611 (defvar org-shiftright-hook nil
19612 "Hook for functions attaching themselves to `S-right'.
19613 See `org-ctrl-c-ctrl-c-hook' for more information.")
19614 (defvar org-shiftright-final-hook nil
19615 "Hook for functions attaching themselves to `S-right'.
19616 This one runs after all other options except shift-select have been excluded.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19619 (defun org-modifier-cursor-error ()
19620 "Throw an error, a modified cursor command was applied in wrong context."
19621 (user-error "This command is active in special context like tables, headlines or items"))
19623 (defun org-shiftselect-error ()
19624 "Throw an error because Shift-Cursor command was applied in wrong context."
19625 (if (and (boundp 'shift-select-mode) shift-select-mode)
19626 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19627 (user-error "This command works only in special context like headlines or timestamps")))
19629 (defun org-call-for-shift-select (cmd)
19630 (let ((this-command-keys-shift-translated t))
19631 (call-interactively cmd)))
19633 (defun org-shifttab (&optional arg)
19634 "Global visibility cycling or move to previous table field.
19635 Call `org-table-previous-field' within a table.
19636 When ARG is nil, cycle globally through visibility states.
19637 When ARG is a numeric prefix, show contents of this level."
19638 (interactive "P")
19639 (cond
19640 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19641 ((integerp arg)
19642 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19643 (message "Content view to level: %d" arg)
19644 (org-content (prefix-numeric-value arg2))
19645 (org-cycle-show-empty-lines t)
19646 (setq org-cycle-global-status 'overview)))
19647 (t (call-interactively 'org-global-cycle))))
19649 (defun org-shiftmetaleft ()
19650 "Promote subtree or delete table column.
19651 Calls `org-promote-subtree', `org-outdent-item-tree', or
19652 `org-table-delete-column', depending on context. See the
19653 individual commands for more information."
19654 (interactive)
19655 (cond
19656 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19657 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19658 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19659 ((if (not (org-region-active-p)) (org-at-item-p)
19660 (save-excursion (goto-char (region-beginning))
19661 (org-at-item-p)))
19662 (call-interactively 'org-outdent-item-tree))
19663 (t (org-modifier-cursor-error))))
19665 (defun org-shiftmetaright ()
19666 "Demote subtree or insert table column.
19667 Calls `org-demote-subtree', `org-indent-item-tree', or
19668 `org-table-insert-column', depending on context. See the
19669 individual commands for more information."
19670 (interactive)
19671 (cond
19672 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19673 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19674 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19675 ((if (not (org-region-active-p)) (org-at-item-p)
19676 (save-excursion (goto-char (region-beginning))
19677 (org-at-item-p)))
19678 (call-interactively 'org-indent-item-tree))
19679 (t (org-modifier-cursor-error))))
19681 (defun org-shiftmetaup (&optional _arg)
19682 "Drag the line at point up.
19683 In a table, kill the current row.
19684 On a clock timestamp, update the value of the timestamp like `S-<up>'
19685 but also adjust the previous clocked item in the clock history.
19686 Everywhere else, drag the line at point up."
19687 (interactive "P")
19688 (cond
19689 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19690 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19691 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19692 (call-interactively 'org-timestamp-up)))
19693 (t (call-interactively 'org-drag-line-backward))))
19695 (defun org-shiftmetadown (&optional _arg)
19696 "Drag the line at point down.
19697 In a table, insert an empty row at the current line.
19698 On a clock timestamp, update the value of the timestamp like `S-<down>'
19699 but also adjust the previous clocked item in the clock history.
19700 Everywhere else, drag the line at point down."
19701 (interactive "P")
19702 (cond
19703 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19704 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19705 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19706 (call-interactively 'org-timestamp-down)))
19707 (t (call-interactively 'org-drag-line-forward))))
19709 (defsubst org-hidden-tree-error ()
19710 (user-error
19711 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19713 (defun org-metaleft (&optional _arg)
19714 "Promote heading, list item at point or move table column left.
19716 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19717 depending on context. With no specific context, calls the Emacs
19718 default `backward-word'. See the individual commands for more
19719 information.
19721 This function runs the hook `org-metaleft-hook' as a first step,
19722 and returns at first non-nil value."
19723 (interactive "P")
19724 (cond
19725 ((run-hook-with-args-until-success 'org-metaleft-hook))
19726 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19727 ((org-with-limited-levels
19728 (or (org-at-heading-p)
19729 (and (org-region-active-p)
19730 (save-excursion
19731 (goto-char (region-beginning))
19732 (org-at-heading-p)))))
19733 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19734 (call-interactively 'org-do-promote))
19735 ;; At an inline task.
19736 ((org-at-heading-p)
19737 (call-interactively 'org-inlinetask-promote))
19738 ((or (org-at-item-p)
19739 (and (org-region-active-p)
19740 (save-excursion
19741 (goto-char (region-beginning))
19742 (org-at-item-p))))
19743 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19744 (call-interactively 'org-outdent-item))
19745 (t (call-interactively 'backward-word))))
19747 (defun org-metaright (&optional _arg)
19748 "Demote heading, list item at point or move table column right.
19750 In front of a drawer or a block keyword, indent it correctly.
19752 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19753 `org-indent-drawer' or `org-indent-block' depending on context.
19754 With no specific context, calls the Emacs default `forward-word'.
19755 See the individual commands for more information.
19757 This function runs the hook `org-metaright-hook' as a first step,
19758 and returns at first non-nil value."
19759 (interactive "P")
19760 (cond
19761 ((run-hook-with-args-until-success 'org-metaright-hook))
19762 ((org-at-table-p) (call-interactively 'org-table-move-column))
19763 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19764 ((org-at-block-p) (call-interactively 'org-indent-block))
19765 ((org-with-limited-levels
19766 (or (org-at-heading-p)
19767 (and (org-region-active-p)
19768 (save-excursion
19769 (goto-char (region-beginning))
19770 (org-at-heading-p)))))
19771 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19772 (call-interactively 'org-do-demote))
19773 ;; At an inline task.
19774 ((org-at-heading-p)
19775 (call-interactively 'org-inlinetask-demote))
19776 ((or (org-at-item-p)
19777 (and (org-region-active-p)
19778 (save-excursion
19779 (goto-char (region-beginning))
19780 (org-at-item-p))))
19781 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19782 (call-interactively 'org-indent-item))
19783 (t (call-interactively 'forward-word))))
19785 (defun org-check-for-hidden (what)
19786 "Check if there are hidden headlines/items in the current visual line.
19787 WHAT can be either `headlines' or `items'. If the current line is
19788 an outline or item heading and it has a folded subtree below it,
19789 this function returns t, nil otherwise."
19790 (let ((re (cond
19791 ((eq what 'headlines) org-outline-regexp-bol)
19792 ((eq what 'items) (org-item-beginning-re))
19793 (t (error "This should not happen"))))
19794 beg end)
19795 (save-excursion
19796 (catch 'exit
19797 (unless (org-region-active-p)
19798 (setq beg (point-at-bol))
19799 (beginning-of-line 2)
19800 (while (and (not (eobp)) ;; this is like `next-line'
19801 (get-char-property (1- (point)) 'invisible))
19802 (beginning-of-line 2))
19803 (setq end (point))
19804 (goto-char beg)
19805 (goto-char (point-at-eol))
19806 (setq end (max end (point)))
19807 (while (re-search-forward re end t)
19808 (when (get-char-property (match-beginning 0) 'invisible)
19809 (throw 'exit t))))
19810 nil))))
19812 (defun org-metaup (&optional _arg)
19813 "Move subtree up or move table row up.
19814 Calls `org-move-subtree-up' or `org-table-move-row' or
19815 `org-move-item-up', depending on context. See the individual commands
19816 for more information."
19817 (interactive "P")
19818 (cond
19819 ((run-hook-with-args-until-success 'org-metaup-hook))
19820 ((org-region-active-p)
19821 (let* ((a (min (region-beginning) (region-end)))
19822 (b (1- (max (region-beginning) (region-end))))
19823 (c (save-excursion (goto-char a)
19824 (move-beginning-of-line 0)))
19825 (d (save-excursion (goto-char a)
19826 (move-end-of-line 0) (point))))
19827 (transpose-regions a b c d)
19828 (goto-char c)))
19829 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19830 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19831 ((org-at-item-p) (call-interactively 'org-move-item-up))
19832 (t (org-drag-element-backward))))
19834 (defun org-metadown (&optional _arg)
19835 "Move subtree down or move table row down.
19836 Calls `org-move-subtree-down' or `org-table-move-row' or
19837 `org-move-item-down', depending on context. See the individual
19838 commands for more information."
19839 (interactive "P")
19840 (cond
19841 ((run-hook-with-args-until-success 'org-metadown-hook))
19842 ((org-region-active-p)
19843 (let* ((a (min (region-beginning) (region-end)))
19844 (b (max (region-beginning) (region-end)))
19845 (c (save-excursion (goto-char b)
19846 (move-beginning-of-line 1)))
19847 (d (save-excursion (goto-char b)
19848 (move-end-of-line 1) (1+ (point)))))
19849 (transpose-regions a b c d)
19850 (goto-char d)))
19851 ((org-at-table-p) (call-interactively 'org-table-move-row))
19852 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19853 ((org-at-item-p) (call-interactively 'org-move-item-down))
19854 (t (org-drag-element-forward))))
19856 (defun org-shiftup (&optional arg)
19857 "Increase item in timestamp or increase priority of current headline.
19858 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19859 depending on context. See the individual commands for more information."
19860 (interactive "P")
19861 (cond
19862 ((run-hook-with-args-until-success 'org-shiftup-hook))
19863 ((and org-support-shift-select (org-region-active-p))
19864 (org-call-for-shift-select 'previous-line))
19865 ((org-at-timestamp-p 'lax)
19866 (call-interactively (if org-edit-timestamp-down-means-later
19867 'org-timestamp-down 'org-timestamp-up)))
19868 ((and (not (eq org-support-shift-select 'always))
19869 org-enable-priority-commands
19870 (org-at-heading-p))
19871 (call-interactively 'org-priority-up))
19872 ((and (not org-support-shift-select) (org-at-item-p))
19873 (call-interactively 'org-previous-item))
19874 ((org-clocktable-try-shift 'up arg))
19875 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19876 (org-support-shift-select
19877 (org-call-for-shift-select 'previous-line))
19878 (t (org-shiftselect-error))))
19880 (defun org-shiftdown (&optional arg)
19881 "Decrease item in timestamp or decrease priority of current headline.
19882 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19883 depending on context. See the individual commands for more information."
19884 (interactive "P")
19885 (cond
19886 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19887 ((and org-support-shift-select (org-region-active-p))
19888 (org-call-for-shift-select 'next-line))
19889 ((org-at-timestamp-p 'lax)
19890 (call-interactively (if org-edit-timestamp-down-means-later
19891 'org-timestamp-up 'org-timestamp-down)))
19892 ((and (not (eq org-support-shift-select 'always))
19893 org-enable-priority-commands
19894 (org-at-heading-p))
19895 (call-interactively 'org-priority-down))
19896 ((and (not org-support-shift-select) (org-at-item-p))
19897 (call-interactively 'org-next-item))
19898 ((org-clocktable-try-shift 'down arg))
19899 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19900 (org-support-shift-select
19901 (org-call-for-shift-select 'next-line))
19902 (t (org-shiftselect-error))))
19904 (defun org-shiftright (&optional arg)
19905 "Cycle the thing at point or in the current line, depending on context.
19906 Depending on context, this does one of the following:
19908 - switch a timestamp at point one day into the future
19909 - on a headline, switch to the next TODO keyword.
19910 - on an item, switch entire list to the next bullet type
19911 - on a property line, switch to the next allowed value
19912 - on a clocktable definition line, move time block into the future"
19913 (interactive "P")
19914 (cond
19915 ((run-hook-with-args-until-success 'org-shiftright-hook))
19916 ((and org-support-shift-select (org-region-active-p))
19917 (org-call-for-shift-select 'forward-char))
19918 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19919 ((and (not (eq org-support-shift-select 'always))
19920 (org-at-heading-p))
19921 (let ((org-inhibit-logging
19922 (not org-treat-S-cursor-todo-selection-as-state-change))
19923 (org-inhibit-blocking
19924 (not org-treat-S-cursor-todo-selection-as-state-change)))
19925 (org-call-with-arg 'org-todo 'right)))
19926 ((or (and org-support-shift-select
19927 (not (eq org-support-shift-select 'always))
19928 (org-at-item-bullet-p))
19929 (and (not org-support-shift-select) (org-at-item-p)))
19930 (org-call-with-arg 'org-cycle-list-bullet nil))
19931 ((and (not (eq org-support-shift-select 'always))
19932 (org-at-property-p))
19933 (call-interactively 'org-property-next-allowed-value))
19934 ((org-clocktable-try-shift 'right arg))
19935 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19936 (org-support-shift-select
19937 (org-call-for-shift-select 'forward-char))
19938 (t (org-shiftselect-error))))
19940 (defun org-shiftleft (&optional arg)
19941 "Cycle the thing at point or in the current line, depending on context.
19942 Depending on context, this does one of the following:
19944 - switch a timestamp at point one day into the past
19945 - on a headline, switch to the previous TODO keyword.
19946 - on an item, switch entire list to the previous bullet type
19947 - on a property line, switch to the previous allowed value
19948 - on a clocktable definition line, move time block into the past"
19949 (interactive "P")
19950 (cond
19951 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19952 ((and org-support-shift-select (org-region-active-p))
19953 (org-call-for-shift-select 'backward-char))
19954 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19955 ((and (not (eq org-support-shift-select 'always))
19956 (org-at-heading-p))
19957 (let ((org-inhibit-logging
19958 (not org-treat-S-cursor-todo-selection-as-state-change))
19959 (org-inhibit-blocking
19960 (not org-treat-S-cursor-todo-selection-as-state-change)))
19961 (org-call-with-arg 'org-todo 'left)))
19962 ((or (and org-support-shift-select
19963 (not (eq org-support-shift-select 'always))
19964 (org-at-item-bullet-p))
19965 (and (not org-support-shift-select) (org-at-item-p)))
19966 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19967 ((and (not (eq org-support-shift-select 'always))
19968 (org-at-property-p))
19969 (call-interactively 'org-property-previous-allowed-value))
19970 ((org-clocktable-try-shift 'left arg))
19971 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19972 (org-support-shift-select
19973 (org-call-for-shift-select 'backward-char))
19974 (t (org-shiftselect-error))))
19976 (defun org-shiftcontrolright ()
19977 "Switch to next TODO set."
19978 (interactive)
19979 (cond
19980 ((and org-support-shift-select (org-region-active-p))
19981 (org-call-for-shift-select 'forward-word))
19982 ((and (not (eq org-support-shift-select 'always))
19983 (org-at-heading-p))
19984 (org-call-with-arg 'org-todo 'nextset))
19985 (org-support-shift-select
19986 (org-call-for-shift-select 'forward-word))
19987 (t (org-shiftselect-error))))
19989 (defun org-shiftcontrolleft ()
19990 "Switch to previous TODO set."
19991 (interactive)
19992 (cond
19993 ((and org-support-shift-select (org-region-active-p))
19994 (org-call-for-shift-select 'backward-word))
19995 ((and (not (eq org-support-shift-select 'always))
19996 (org-at-heading-p))
19997 (org-call-with-arg 'org-todo 'previousset))
19998 (org-support-shift-select
19999 (org-call-for-shift-select 'backward-word))
20000 (t (org-shiftselect-error))))
20002 (defun org-shiftcontrolup (&optional n)
20003 "Change timestamps synchronously up in CLOCK log lines.
20004 Optional argument N tells to change by that many units."
20005 (interactive "P")
20006 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20007 (let (org-support-shift-select)
20008 (org-clock-timestamps-up n))
20009 (user-error "Not at a clock log")))
20011 (defun org-shiftcontroldown (&optional n)
20012 "Change timestamps synchronously down in CLOCK log lines.
20013 Optional argument N tells to change by that many units."
20014 (interactive "P")
20015 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20016 (let (org-support-shift-select)
20017 (org-clock-timestamps-down n))
20018 (user-error "Not at a clock log")))
20020 (defun org-increase-number-at-point (&optional inc)
20021 "Increment the number at point.
20022 With an optional prefix numeric argument INC, increment using
20023 this numeric value."
20024 (interactive "p")
20025 (if (not (number-at-point))
20026 (user-error "Not on a number")
20027 (unless inc (setq inc 1))
20028 (let ((pos (point))
20029 (beg (skip-chars-backward "-+^/*0-9eE."))
20030 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20031 (setq nap (buffer-substring-no-properties
20032 (+ pos beg) (+ pos beg end)))
20033 (delete-region (+ pos beg) (+ pos beg end))
20034 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20035 (when (org-at-table-p)
20036 (org-table-align)
20037 (org-table-end-of-field 1))))
20039 (defun org-decrease-number-at-point (&optional inc)
20040 "Decrement the number at point.
20041 With an optional prefix numeric argument INC, decrement using
20042 this numeric value."
20043 (interactive "p")
20044 (org-increase-number-at-point (- (or inc 1))))
20046 (defun org-ctrl-c-ret ()
20047 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20048 (interactive)
20049 (cond
20050 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20051 (t (call-interactively 'org-insert-heading))))
20053 (defun org-find-visible ()
20054 (let ((s (point)))
20055 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20056 (get-char-property s 'invisible)))
20058 (defun org-find-invisible ()
20059 (let ((s (point)))
20060 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20061 (not (get-char-property s 'invisible))))
20064 (defun org-copy-visible (beg end)
20065 "Copy the visible parts of the region."
20066 (interactive "r")
20067 (let ((result ""))
20068 (while (/= beg end)
20069 (when (get-char-property beg 'invisible)
20070 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20071 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20072 (setq result (concat result (buffer-substring beg next)))
20073 (setq beg next)))
20074 (kill-new result)))
20076 (defun org-copy-special ()
20077 "Copy region in table or copy current subtree.
20078 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20079 context. See the individual commands for more information."
20080 (interactive)
20081 (call-interactively
20082 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20084 (defun org-cut-special ()
20085 "Cut region in table or cut current subtree.
20086 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20087 context. See the individual commands for more information."
20088 (interactive)
20089 (call-interactively
20090 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20092 (defun org-paste-special (arg)
20093 "Paste rectangular region into table, or past subtree relative to level.
20094 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20095 See the individual commands for more information."
20096 (interactive "P")
20097 (if (org-at-table-p)
20098 (org-table-paste-rectangle)
20099 (org-paste-subtree arg)))
20101 (defun org-edit-special (&optional arg)
20102 "Call a special editor for the element at point.
20103 When at a table, call the formula editor with `org-table-edit-formulas'.
20104 When in a source code block, call `org-edit-src-code'.
20105 When in a fixed-width region, call `org-edit-fixed-width-region'.
20106 When in an export block, call `org-edit-export-block'.
20107 When in a LaTeX environment, call `org-edit-latex-environment'.
20108 When at an #+INCLUDE keyword, visit the included file.
20109 When at a footnote reference, call `org-edit-footnote-reference'
20110 On a link, call `ffap' to visit the link at point.
20111 Otherwise, return a user error."
20112 (interactive "P")
20113 (let ((element (org-element-at-point)))
20114 (barf-if-buffer-read-only)
20115 (pcase (org-element-type element)
20116 (`src-block
20117 (if (not arg) (org-edit-src-code)
20118 (let* ((info (org-babel-get-src-block-info))
20119 (lang (nth 0 info))
20120 (params (nth 2 info))
20121 (session (cdr (assq :session params))))
20122 (if (not session) (org-edit-src-code)
20123 ;; At a src-block with a session and function called with
20124 ;; an ARG: switch to the buffer related to the inferior
20125 ;; process.
20126 (switch-to-buffer
20127 (funcall (intern (concat "org-babel-prep-session:" lang))
20128 session params))))))
20129 (`keyword
20130 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20131 (org-open-link-from-string
20132 (format "[[%s]]"
20133 (expand-file-name
20134 (let ((value (org-element-property :value element)))
20135 (cond ((org-file-url-p value)
20136 (user-error "The file is specified as a URL, cannot be edited"))
20137 ((not (org-string-nw-p value))
20138 (user-error "No file to edit"))
20139 ((string-match "\\`\"\\(.*?\\)\"" value)
20140 (match-string 1 value))
20141 ((string-match "\\`[^ \t\"]\\S-*" value)
20142 (match-string 0 value))
20143 (t (user-error "No valid file specified")))))))
20144 (user-error "No special environment to edit here")))
20145 (`table
20146 (if (eq (org-element-property :type element) 'table.el)
20147 (org-edit-table.el)
20148 (call-interactively 'org-table-edit-formulas)))
20149 ;; Only Org tables contain `table-row' type elements.
20150 (`table-row (call-interactively 'org-table-edit-formulas))
20151 (`example-block (org-edit-src-code))
20152 (`export-block (org-edit-export-block))
20153 (`fixed-width (org-edit-fixed-width-region))
20154 (`latex-environment (org-edit-latex-environment))
20156 ;; No notable element at point. Though, we may be at a link or
20157 ;; a footnote reference, which are objects. Thus, scan deeper.
20158 (let ((context (org-element-context element)))
20159 (pcase (org-element-type context)
20160 (`footnote-reference (org-edit-footnote-reference))
20161 (`inline-src-block (org-edit-inline-src-code))
20162 (`link (call-interactively #'ffap))
20163 (_ (user-error "No special environment to edit here"))))))))
20165 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20166 (defun org-ctrl-c-ctrl-c (&optional arg)
20167 "Set tags in headline, or update according to changed information at point.
20169 This command does many different things, depending on context:
20171 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20172 this is what we do.
20174 - If the cursor is on a statistics cookie, update it.
20176 - If the cursor is in a headline, prompt for tags and insert them
20177 into the current line, aligned to `org-tags-column'. When called
20178 with prefix arg, realign all tags in the current buffer.
20180 - If the cursor is in one of the special #+KEYWORD lines, this
20181 triggers scanning the buffer for these lines and updating the
20182 information.
20184 - If the cursor is inside a table, realign the table. This command
20185 works even if the automatic table editor has been turned off.
20187 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20188 the entire table.
20190 - If the cursor is at a footnote reference or definition, jump to
20191 the corresponding definition or references, respectively.
20193 - If the cursor is a the beginning of a dynamic block, update it.
20195 - If the current buffer is a capture buffer, close note and file it.
20197 - If the cursor is on a <<<target>>>, update radio targets and
20198 corresponding links in this buffer.
20200 - If the cursor is on a numbered item in a plain list, renumber the
20201 ordered list.
20203 - If the cursor is on a checkbox, toggle it.
20205 - If the cursor is on a code block, evaluate it. The variable
20206 `org-confirm-babel-evaluate' can be used to control prompting
20207 before code block evaluation, by default every code block
20208 evaluation requires confirmation. Code block evaluation can be
20209 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20210 (interactive "P")
20211 (cond
20212 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20213 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20214 (org-remove-occur-highlights)
20215 (message "Temporary highlights/overlays removed from current buffer"))
20216 ((and (local-variable-p 'org-finish-function)
20217 (fboundp org-finish-function))
20218 (funcall org-finish-function))
20219 ((org-babel-hash-at-point))
20220 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20222 (let* ((context
20223 (org-element-lineage
20224 (org-element-context)
20225 ;; Limit to supported contexts.
20226 '(babel-call clock dynamic-block footnote-definition
20227 footnote-reference inline-babel-call inline-src-block
20228 inlinetask item keyword node-property paragraph
20229 plain-list planning property-drawer radio-target
20230 src-block statistics-cookie table table-cell table-row
20231 timestamp)
20233 (type (org-element-type context)))
20234 ;; For convenience: at the first line of a paragraph on the same
20235 ;; line as an item, apply function on that item instead.
20236 (when (eq type 'paragraph)
20237 (let ((parent (org-element-property :parent context)))
20238 (when (and (eq (org-element-type parent) 'item)
20239 (= (line-beginning-position)
20240 (org-element-property :begin parent)))
20241 (setq context parent)
20242 (setq type 'item))))
20243 ;; Act according to type of element or object at point.
20245 ;; Do nothing on a blank line, except if it is contained in
20246 ;; a src block. Hence, we first check if point is in such
20247 ;; a block and then if it is at a blank line.
20248 (pcase type
20249 ((or `inline-src-block `src-block)
20250 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20251 (org-babel-eval-wipe-error-buffer)
20252 (org-babel-execute-src-block
20253 current-prefix-arg (org-babel-get-src-block-info nil context))))
20254 ((guard (org-match-line "[ \t]*$"))
20255 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20256 (user-error
20257 (substitute-command-keys
20258 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20259 ((or `babel-call `inline-babel-call)
20260 (let ((info (org-babel-lob-get-info context)))
20261 (when info (org-babel-execute-src-block nil info))))
20262 (`clock (org-clock-update-time-maybe))
20263 (`dynamic-block
20264 (save-excursion
20265 (goto-char (org-element-property :post-affiliated context))
20266 (org-update-dblock)))
20267 (`footnote-definition
20268 (goto-char (org-element-property :post-affiliated context))
20269 (call-interactively 'org-footnote-action))
20270 (`footnote-reference (call-interactively #'org-footnote-action))
20271 ((or `headline `inlinetask)
20272 (save-excursion (goto-char (org-element-property :begin context))
20273 (call-interactively #'org-set-tags)))
20274 (`item
20275 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20276 ;; unconditionally, whereas `C-u' will toggle its presence.
20277 ;; Without a universal argument, if the item has a checkbox,
20278 ;; toggle it. Otherwise repair the list.
20279 (let* ((box (org-element-property :checkbox context))
20280 (struct (org-element-property :structure context))
20281 (old-struct (copy-tree struct))
20282 (parents (org-list-parents-alist struct))
20283 (prevs (org-list-prevs-alist struct))
20284 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20285 (org-list-set-checkbox
20286 (org-element-property :begin context) struct
20287 (cond ((equal arg '(16)) "[-]")
20288 ((and (not box) (equal arg '(4))) "[ ]")
20289 ((or (not box) (equal arg '(4))) nil)
20290 ((eq box 'on) "[ ]")
20291 (t "[X]")))
20292 ;; Mimic `org-list-write-struct' but with grabbing a return
20293 ;; value from `org-list-struct-fix-box'.
20294 (org-list-struct-fix-ind struct parents 2)
20295 (org-list-struct-fix-item-end struct)
20296 (org-list-struct-fix-bul struct prevs)
20297 (org-list-struct-fix-ind struct parents)
20298 (let ((block-item
20299 (org-list-struct-fix-box struct parents prevs orderedp)))
20300 (if (and box (equal struct old-struct))
20301 (if (equal arg '(16))
20302 (message "Checkboxes already reset")
20303 (user-error "Cannot toggle this checkbox: %s"
20304 (if (eq box 'on)
20305 "all subitems checked"
20306 "unchecked subitems")))
20307 (org-list-struct-apply-struct struct old-struct)
20308 (org-update-checkbox-count-maybe))
20309 (when block-item
20310 (message "Checkboxes were removed due to empty box at line %d"
20311 (org-current-line block-item))))))
20312 (`keyword
20313 (let ((org-inhibit-startup-visibility-stuff t)
20314 (org-startup-align-all-tables nil))
20315 (when (boundp 'org-table-coordinate-overlays)
20316 (mapc #'delete-overlay org-table-coordinate-overlays)
20317 (setq org-table-coordinate-overlays nil))
20318 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20319 (message "Local setup has been refreshed"))
20320 (`plain-list
20321 ;; At a plain list, with a double C-u argument, set
20322 ;; checkboxes of each item to "[-]", whereas a single one
20323 ;; will toggle their presence according to the state of the
20324 ;; first item in the list. Without an argument, repair the
20325 ;; list.
20326 (let* ((begin (org-element-property :contents-begin context))
20327 (beginm (move-marker (make-marker) begin))
20328 (struct (org-element-property :structure context))
20329 (old-struct (copy-tree struct))
20330 (first-box (save-excursion
20331 (goto-char begin)
20332 (looking-at org-list-full-item-re)
20333 (match-string-no-properties 3)))
20334 (new-box (cond ((equal arg '(16)) "[-]")
20335 ((equal arg '(4)) (unless first-box "[ ]"))
20336 ((equal first-box "[X]") "[ ]")
20337 (t "[X]"))))
20338 (cond
20339 (arg
20340 (dolist (pos
20341 (org-list-get-all-items
20342 begin struct (org-list-prevs-alist struct)))
20343 (org-list-set-checkbox pos struct new-box)))
20344 ((and first-box (eq (point) begin))
20345 ;; For convenience, when point is at bol on the first
20346 ;; item of the list and no argument is provided, simply
20347 ;; toggle checkbox of that item, if any.
20348 (org-list-set-checkbox begin struct new-box)))
20349 (org-list-write-struct
20350 struct (org-list-parents-alist struct) old-struct)
20351 (org-update-checkbox-count-maybe)
20352 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20353 ((or `property-drawer `node-property)
20354 (call-interactively #'org-property-action))
20355 (`radio-target
20356 (call-interactively #'org-update-radio-target-regexp))
20357 (`statistics-cookie
20358 (call-interactively #'org-update-statistics-cookies))
20359 ((or `table `table-cell `table-row)
20360 ;; At a table, recalculate every field and align it. Also
20361 ;; send the table if necessary. If the table has
20362 ;; a `table.el' type, just give up. At a table row or cell,
20363 ;; maybe recalculate line but always align table.
20364 (if (eq (org-element-property :type context) 'table.el)
20365 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20366 Use `\\[org-edit-special]' to edit table.el tables"))
20367 (if (or (eq type 'table)
20368 ;; Check if point is at a TBLFM line.
20369 (and (eq type 'table-row)
20370 (= (point) (org-element-property :end context))))
20371 (save-excursion
20372 (if (org-at-TBLFM-p)
20373 (progn (require 'org-table)
20374 (org-table-calc-current-TBLFM))
20375 (goto-char (org-element-property :contents-begin context))
20376 (org-call-with-arg 'org-table-recalculate (or arg t))
20377 (orgtbl-send-table 'maybe)))
20378 (org-table-maybe-eval-formula)
20379 (cond (arg (call-interactively #'org-table-recalculate))
20380 ((org-table-maybe-recalculate-line))
20381 (t (org-table-align))))))
20382 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20383 (org-timestamp-change 0 'day))
20384 ((and `nil (guard (org-at-heading-p)))
20385 ;; When point is on an unsupported object type, we can miss
20386 ;; the fact that it also is at a heading. Handle it here.
20387 (call-interactively #'org-set-tags))
20388 ((guard
20389 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20391 (user-error
20392 (substitute-command-keys
20393 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20395 (defun org-mode-restart ()
20396 (interactive)
20397 (let ((indent-status (bound-and-true-p org-indent-mode)))
20398 (funcall major-mode)
20399 (hack-local-variables)
20400 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20401 (org-indent-mode -1))
20402 (org-reset-file-cache))
20403 (message "%s restarted" major-mode))
20405 (defun org-kill-note-or-show-branches ()
20406 "Abort storing current note, or call `outline-show-branches'."
20407 (interactive)
20408 (if (not org-finish-function)
20409 (progn
20410 (outline-hide-subtree)
20411 (call-interactively 'outline-show-branches))
20412 (let ((org-note-abort t))
20413 (funcall org-finish-function))))
20415 (defun org-delete-indentation (&optional arg)
20416 "Join current line to previous and fix whitespace at join.
20418 If previous line is a headline add to headline title. Otherwise
20419 the function calls `delete-indentation'.
20421 With a non-nil optional argument, join it to the following one."
20422 (interactive "*P")
20423 (if (save-excursion
20424 (beginning-of-line (if arg 1 0))
20425 (let ((case-fold-search nil))
20426 (looking-at org-complex-heading-regexp)))
20427 ;; At headline.
20428 (let ((tags-column (when (match-beginning 5)
20429 (save-excursion (goto-char (match-beginning 5))
20430 (current-column))))
20431 (string (concat " " (progn (when arg (forward-line 1))
20432 (org-trim (delete-and-extract-region
20433 (line-beginning-position)
20434 (line-end-position)))))))
20435 (unless (bobp) (delete-region (point) (1- (point))))
20436 (goto-char (or (match-end 4)
20437 (match-beginning 5)
20438 (match-end 0)))
20439 (skip-chars-backward " \t")
20440 (save-excursion (insert string))
20441 ;; Adjust alignment of tags.
20442 (cond
20443 ((not tags-column)) ;no tags
20444 (org-auto-align-tags (org-set-tags nil t))
20445 (t (org--align-tags-here tags-column)))) ;preserve tags column
20446 (delete-indentation arg)))
20448 (defun org-open-line (n)
20449 "Insert a new row in tables, call `open-line' elsewhere.
20450 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20451 As a special case, when a document starts with a table, allow to
20452 call `open-line' on the very first character."
20453 (interactive "*p")
20454 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20455 (org-table-insert-row)
20456 (open-line n)))
20458 (defun org-return (&optional indent)
20459 "Goto next table row or insert a newline.
20461 Calls `org-table-next-row' or `newline', depending on context.
20463 When optional INDENT argument is non-nil, call
20464 `newline-and-indent' instead of `newline'.
20466 When `org-return-follows-link' is non-nil and point is on
20467 a timestamp or a link, call `org-open-at-point'. However, it
20468 will not happen if point is in a table or on a \"dead\"
20469 object (e.g., within a comment). In these case, you need to use
20470 `org-open-at-point' directly."
20471 (interactive)
20472 (let ((context (if org-return-follows-link (org-element-context)
20473 (org-element-at-point))))
20474 (cond
20475 ;; In a table, call `org-table-next-row'. However, before first
20476 ;; column or after last one, split the table.
20477 ((or (and (eq (org-element-type context) 'table)
20478 (>= (point) (org-element-property :contents-begin context))
20479 (< (point) (org-element-property :contents-end context)))
20480 (org-element-lineage context '(table-row table-cell) t))
20481 (if (or (looking-at-p "[ \t]*$")
20482 (save-excursion (skip-chars-backward " \t") (bolp)))
20483 (insert "\n")
20484 (org-table-justify-field-maybe)
20485 (call-interactively #'org-table-next-row)))
20486 ;; On a link or a timestamp, call `org-open-at-point' if
20487 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20488 ;; locations, e.g., in a comment, as `org-open-at-point'.
20489 ((and org-return-follows-link
20490 (or (org-in-regexp org-ts-regexp-both nil t)
20491 (org-in-regexp org-tsr-regexp-both nil t)
20492 (org-in-regexp org-any-link-re nil t)))
20493 (call-interactively #'org-open-at-point))
20494 ;; Insert newline in heading, but preserve tags.
20495 ((and (not (bolp))
20496 (save-excursion (beginning-of-line)
20497 (let ((case-fold-search nil))
20498 (looking-at org-complex-heading-regexp))))
20499 ;; At headline. Split line. However, if point is on keyword,
20500 ;; priority cookie or tags, do not break any of them: add
20501 ;; a newline after the headline instead.
20502 (let ((tags-column (and (match-beginning 5)
20503 (save-excursion (goto-char (match-beginning 5))
20504 (current-column))))
20505 (string
20506 (when (and (match-end 4) (org-point-in-group (point) 4))
20507 (delete-and-extract-region (point) (match-end 4)))))
20508 ;; Adjust tag alignment.
20509 (cond
20510 ((not (and tags-column string)))
20511 (org-auto-align-tags (org-set-tags nil t))
20512 (t (org--align-tags-here tags-column))) ;preserve tags column
20513 (end-of-line)
20514 (org-show-entry)
20515 (if indent (newline-and-indent) (newline))
20516 (when string (save-excursion (insert (org-trim string))))))
20517 ;; In a list, make sure indenting keeps trailing text within.
20518 ((and indent
20519 (not (eolp))
20520 (org-element-lineage context '(item)))
20521 (let ((trailing-data
20522 (delete-and-extract-region (point) (line-end-position))))
20523 (newline-and-indent)
20524 (save-excursion (insert trailing-data))))
20525 (t (if indent (newline-and-indent) (newline))))))
20527 (defun org-return-indent ()
20528 "Goto next table row or insert a newline and indent.
20529 Calls `org-table-next-row' or `newline-and-indent', depending on
20530 context. See the individual commands for more information."
20531 (interactive)
20532 (org-return t))
20534 (defun org-ctrl-c-tab (&optional _arg)
20535 "Toggle columns width in a table, or show children.
20536 Call `org-table-toggle-column-width' if point is in a table.
20537 Otherwise, call `org-show-children'."
20538 (interactive "p")
20539 (call-interactively
20540 (if (org-at-table-p) #'org-table-toggle-column-width
20541 #'org-show-children)))
20543 (defun org-ctrl-c-star ()
20544 "Compute table, or change heading status of lines.
20545 Calls `org-table-recalculate' or `org-toggle-heading',
20546 depending on context."
20547 (interactive)
20548 (cond
20549 ((org-at-table-p)
20550 (call-interactively 'org-table-recalculate))
20552 ;; Convert all lines in region to list items
20553 (call-interactively 'org-toggle-heading))))
20555 (defun org-ctrl-c-minus ()
20556 "Insert separator line in table or modify bullet status of line.
20557 Also turns a plain line or a region of lines into list items.
20558 Calls `org-table-insert-hline', `org-toggle-item', or
20559 `org-cycle-list-bullet', depending on context."
20560 (interactive)
20561 (cond
20562 ((org-at-table-p)
20563 (call-interactively 'org-table-insert-hline))
20564 ((org-region-active-p)
20565 (call-interactively 'org-toggle-item))
20566 ((org-in-item-p)
20567 (call-interactively 'org-cycle-list-bullet))
20569 (call-interactively 'org-toggle-item))))
20571 (defun org-toggle-heading (&optional nstars)
20572 "Convert headings to normal text, or items or text to headings.
20573 If there is no active region, only convert the current line.
20575 With a `\\[universal-argument]' prefix, convert the whole list at
20576 point into heading.
20578 In a region:
20580 - If the first non blank line is a headline, remove the stars
20581 from all headlines in the region.
20583 - If it is a normal line, turn each and every normal line (i.e.,
20584 not an heading or an item) in the region into headings. If you
20585 want to convert only the first line of this region, use one
20586 universal prefix argument.
20588 - If it is a plain list item, turn all plain list items into headings.
20590 When converting a line into a heading, the number of stars is chosen
20591 such that the lines become children of the current entry. However,
20592 when a numeric prefix argument is given, its value determines the
20593 number of stars to add."
20594 (interactive "P")
20595 (let ((skip-blanks
20596 (function
20597 ;; Return beginning of first non-blank line, starting from
20598 ;; line at POS.
20599 (lambda (pos)
20600 (save-excursion
20601 (goto-char pos)
20602 (while (org-at-comment-p) (forward-line))
20603 (skip-chars-forward " \r\t\n")
20604 (point-at-bol)))))
20605 beg end toggled)
20606 ;; Determine boundaries of changes. If a universal prefix has
20607 ;; been given, put the list in a region. If region ends at a bol,
20608 ;; do not consider the last line to be in the region.
20610 (when (and current-prefix-arg (org-at-item-p))
20611 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20612 (org-mark-element))
20614 (if (org-region-active-p)
20615 (setq beg (funcall skip-blanks (region-beginning))
20616 end (copy-marker (save-excursion
20617 (goto-char (region-end))
20618 (if (bolp) (point) (point-at-eol)))))
20619 (setq beg (funcall skip-blanks (point-at-bol))
20620 end (copy-marker (point-at-eol))))
20621 ;; Ensure inline tasks don't count as headings.
20622 (org-with-limited-levels
20623 (save-excursion
20624 (goto-char beg)
20625 (cond
20626 ;; Case 1. Started at an heading: de-star headings.
20627 ((org-at-heading-p)
20628 (while (< (point) end)
20629 (when (org-at-heading-p t)
20630 (looking-at org-outline-regexp) (replace-match "")
20631 (setq toggled t))
20632 (forward-line)))
20633 ;; Case 2. Started at an item: change items into headlines.
20634 ;; One star will be added by `org-list-to-subtree'.
20635 ((org-at-item-p)
20636 (while (< (point) end)
20637 (when (org-at-item-p)
20638 ;; Pay attention to cases when region ends before list.
20639 (let* ((struct (org-list-struct))
20640 (list-end
20641 (min (org-list-get-bottom-point struct) (1+ end))))
20642 (save-restriction
20643 (narrow-to-region (point) list-end)
20644 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20645 (setq toggled t))
20646 (forward-line)))
20647 ;; Case 3. Started at normal text: make every line an heading,
20648 ;; skipping headlines and items.
20649 (t (let* ((stars
20650 (make-string
20651 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20652 (add-stars
20653 (cond (nstars "") ; stars from prefix only
20654 ((equal stars "") "*") ; before first heading
20655 (org-odd-levels-only "**") ; inside heading, odd
20656 (t "*"))) ; inside heading, oddeven
20657 (rpl (concat stars add-stars " "))
20658 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20659 (while (< (point) (if (equal nstars '(4)) lend end))
20660 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20661 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20662 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20663 (forward-line)))))))
20664 (unless toggled (message "Cannot toggle heading from here"))))
20666 (defun org-meta-return (&optional arg)
20667 "Insert a new heading or wrap a region in a table.
20668 Calls `org-insert-heading', `org-insert-item' or
20669 `org-table-wrap-region', depending on context. When called with
20670 an argument, unconditionally call `org-insert-heading'."
20671 (interactive "P")
20672 (org-check-before-invisible-edit 'insert)
20673 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20674 (call-interactively (cond (arg #'org-insert-heading)
20675 ((org-at-table-p) #'org-table-wrap-region)
20676 ((org-in-item-p) #'org-insert-item)
20677 (t #'org-insert-heading)))))
20679 ;;; Menu entries
20681 (defsubst org-in-subtree-not-table-p ()
20682 "Are we in a subtree and not in a table?"
20683 (and (not (org-before-first-heading-p))
20684 (not (org-at-table-p))))
20686 ;; Define the Org mode menus
20687 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20688 '("Tbl"
20689 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20690 ["Next Field" org-cycle (org-at-table-p)]
20691 ["Previous Field" org-shifttab (org-at-table-p)]
20692 ["Next Row" org-return (org-at-table-p)]
20693 "--"
20694 ["Blank Field" org-table-blank-field (org-at-table-p)]
20695 ["Edit Field" org-table-edit-field (org-at-table-p)]
20696 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20697 "--"
20698 ("Column"
20699 ["Move Column Left" org-metaleft (org-at-table-p)]
20700 ["Move Column Right" org-metaright (org-at-table-p)]
20701 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20702 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20703 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20704 ("Row"
20705 ["Move Row Up" org-metaup (org-at-table-p)]
20706 ["Move Row Down" org-metadown (org-at-table-p)]
20707 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20708 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20709 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20710 "--"
20711 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20712 ("Rectangle"
20713 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20714 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20715 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20716 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20717 "--"
20718 ("Calculate"
20719 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20720 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20721 ["Edit Formulas" org-edit-special (org-at-table-p)]
20722 "--"
20723 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20724 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20725 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20726 "--"
20727 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20728 "--"
20729 ["Sum Column/Rectangle" org-table-sum
20730 (or (org-at-table-p) (org-region-active-p))]
20731 ["Which Column?" org-table-current-column (org-at-table-p)])
20732 ["Debug Formulas"
20733 org-table-toggle-formula-debugger
20734 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20735 ["Show Col/Row Numbers"
20736 org-table-toggle-coordinate-overlays
20737 :style toggle
20738 :selected (bound-and-true-p org-table-overlay-coordinates)]
20739 "--"
20740 ["Create" org-table-create (not (org-at-table-p))]
20741 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20742 ["Import from File" org-table-import (not (org-at-table-p))]
20743 ["Export to File" org-table-export (org-at-table-p)]
20744 "--"
20745 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20746 "--"
20747 ("Plot"
20748 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20749 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20751 (easy-menu-define org-org-menu org-mode-map "Org menu"
20752 '("Org"
20753 ("Show/Hide"
20754 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20755 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20756 ["Sparse Tree..." org-sparse-tree t]
20757 ["Reveal Context" org-reveal t]
20758 ["Show All" outline-show-all t]
20759 "--"
20760 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20761 "--"
20762 ["New Heading" org-insert-heading t]
20763 ("Navigate Headings"
20764 ["Up" outline-up-heading t]
20765 ["Next" outline-next-visible-heading t]
20766 ["Previous" outline-previous-visible-heading t]
20767 ["Next Same Level" outline-forward-same-level t]
20768 ["Previous Same Level" outline-backward-same-level t]
20769 "--"
20770 ["Jump" org-goto t])
20771 ("Edit Structure"
20772 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20773 "--"
20774 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20775 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20776 "--"
20777 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20778 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20779 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20780 "--"
20781 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20782 "--"
20783 ["Copy visible text" org-copy-visible t]
20784 "--"
20785 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20786 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20787 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20788 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20789 "--"
20790 ["Sort Region/Children" org-sort t]
20791 "--"
20792 ["Convert to odd levels" org-convert-to-odd-levels t]
20793 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20794 ("Editing"
20795 ["Emphasis..." org-emphasize t]
20796 ["Edit Source Example" org-edit-special t]
20797 "--"
20798 ["Footnote new/jump" org-footnote-action t]
20799 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20800 ("Archive"
20801 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20802 "--"
20803 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20804 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20805 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20807 "--"
20808 ("Hyperlinks"
20809 ["Store Link (Global)" org-store-link t]
20810 ["Find existing link to here" org-occur-link-in-agenda-files t]
20811 ["Insert Link" org-insert-link t]
20812 ["Follow Link" org-open-at-point t]
20813 "--"
20814 ["Next link" org-next-link t]
20815 ["Previous link" org-previous-link t]
20816 "--"
20817 ["Descriptive Links"
20818 org-toggle-link-display
20819 :style radio
20820 :selected org-descriptive-links
20822 ["Literal Links"
20823 org-toggle-link-display
20824 :style radio
20825 :selected (not org-descriptive-links)])
20826 "--"
20827 ("TODO Lists"
20828 ["TODO/DONE/-" org-todo t]
20829 ("Select keyword"
20830 ["Next keyword" org-shiftright (org-at-heading-p)]
20831 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20832 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20833 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20834 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20835 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20836 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20837 "--"
20838 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20839 :selected org-enforce-todo-dependencies :style toggle :active t]
20840 "Settings for tree at point"
20841 ["Do Children sequentially" org-toggle-ordered-property :style radio
20842 :selected (org-entry-get nil "ORDERED")
20843 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20844 ["Do Children parallel" org-toggle-ordered-property :style radio
20845 :selected (not (org-entry-get nil "ORDERED"))
20846 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20847 "--"
20848 ["Set Priority" org-priority t]
20849 ["Priority Up" org-shiftup t]
20850 ["Priority Down" org-shiftdown t]
20851 "--"
20852 ["Get news from all feeds" org-feed-update-all t]
20853 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20854 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20855 ("TAGS and Properties"
20856 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20857 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20858 "--"
20859 ["Set property" org-set-property (not (org-before-first-heading-p))]
20860 ["Column view of properties" org-columns t]
20861 ["Insert Column View DBlock" org-columns-insert-dblock t])
20862 ("Dates and Scheduling"
20863 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20864 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20865 ("Change Date"
20866 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20867 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20868 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20869 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20870 ["Compute Time Range" org-evaluate-time-range t]
20871 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20872 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20873 "--"
20874 ["Custom time format" org-toggle-time-stamp-overlays
20875 :style radio :selected org-display-custom-times]
20876 "--"
20877 ["Goto Calendar" org-goto-calendar t]
20878 ["Date from Calendar" org-date-from-calendar t]
20879 "--"
20880 ["Start/Restart Timer" org-timer-start t]
20881 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20882 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20883 ["Insert Timer String" org-timer t]
20884 ["Insert Timer Item" org-timer-item t])
20885 ("Logging work"
20886 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20887 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20888 ["Clock out" org-clock-out t]
20889 ["Clock cancel" org-clock-cancel t]
20890 "--"
20891 ["Mark as default task" org-clock-mark-default-task t]
20892 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20893 ["Goto running clock" org-clock-goto t]
20894 "--"
20895 ["Display times" org-clock-display t]
20896 ["Create clock table" org-clock-report t]
20897 "--"
20898 ["Record DONE time"
20899 (progn (setq org-log-done (not org-log-done))
20900 (message "Switching to %s will %s record a timestamp"
20901 (car org-done-keywords)
20902 (if org-log-done "automatically" "not")))
20903 :style toggle :selected org-log-done])
20904 "--"
20905 ["Agenda Command..." org-agenda t]
20906 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20907 ("File List for Agenda")
20908 ("Special views current file"
20909 ["TODO Tree" org-show-todo-tree t]
20910 ["Check Deadlines" org-check-deadlines t]
20911 ["Tags/Property tree" org-match-sparse-tree t])
20912 "--"
20913 ["Export/Publish..." org-export-dispatch t]
20914 ("LaTeX"
20915 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20916 :style toggle :selected org-cdlatex-mode]
20917 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20918 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20919 ["Modify math symbol" org-cdlatex-math-modify
20920 (org-inside-LaTeX-fragment-p)]
20921 ["Insert citation" org-reftex-citation t])
20922 "--"
20923 ("MobileOrg"
20924 ["Push Files and Views" org-mobile-push t]
20925 ["Get Captured and Flagged" org-mobile-pull t]
20926 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20927 "--"
20928 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20929 "--"
20930 ("Documentation"
20931 ["Show Version" org-version t]
20932 ["Info Documentation" org-info t])
20933 ("Customize"
20934 ["Browse Org Group" org-customize t]
20935 "--"
20936 ["Expand This Menu" org-create-customize-menu
20937 (fboundp 'customize-menu-create)])
20938 ["Send bug report" org-submit-bug-report t]
20939 "--"
20940 ("Refresh/Reload"
20941 ["Refresh setup current buffer" org-mode-restart t]
20942 ["Reload Org (after update)" org-reload t]
20943 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20946 (defun org-info (&optional node)
20947 "Read documentation for Org in the info system.
20948 With optional NODE, go directly to that node."
20949 (interactive)
20950 (info (format "(org)%s" (or node ""))))
20952 ;;;###autoload
20953 (defun org-submit-bug-report ()
20954 "Submit a bug report on Org via mail.
20956 Don't hesitate to report any problems or inaccurate documentation.
20958 If you don't have setup sending mail from (X)Emacs, please copy the
20959 output buffer into your mail program, as it gives us important
20960 information about your Org version and configuration."
20961 (interactive)
20962 (require 'reporter)
20963 (defvar reporter-prompt-for-summary-p)
20964 (org-load-modules-maybe)
20965 (org-require-autoloaded-modules)
20966 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20967 (reporter-submit-bug-report
20968 "emacs-orgmode@gnu.org"
20969 (org-version nil 'full)
20970 (let (list)
20971 (save-window-excursion
20972 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20973 (delete-other-windows)
20974 (erase-buffer)
20975 (insert "You are about to submit a bug report to the Org mailing list.
20977 We would like to add your full Org and Outline configuration to the
20978 bug report. This greatly simplifies the work of the maintainer and
20979 other experts on the mailing list.
20981 HOWEVER, some variables you have customized may contain private
20982 information. The names of customers, colleagues, or friends, might
20983 appear in the form of file names, tags, todo states, or search strings.
20984 If you answer yes to the prompt, you might want to check and remove
20985 such private information before sending the email.")
20986 (add-text-properties (point-min) (point-max) '(face org-warning))
20987 (when (yes-or-no-p "Include your Org configuration ")
20988 (mapatoms
20989 (lambda (v)
20990 (and (boundp v)
20991 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20992 (or (and (symbol-value v)
20993 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20994 (and
20995 (get v 'custom-type) (get v 'standard-value)
20996 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20997 (push v list)))))
20998 (kill-buffer (get-buffer "*Warn about privacy*"))
20999 list))
21000 nil nil
21001 "Remember to cover the basics, that is, what you expected to happen and
21002 what in fact did happen. You don't know how to make a good report? See
21004 http://orgmode.org/manual/Feedback.html#Feedback
21006 Your bug report will be posted to the Org mailing list.
21007 ------------------------------------------------------------------------")
21008 (save-excursion
21009 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21010 (replace-match "\\1Bug: \\3 [\\2]")))))
21013 (defun org-install-agenda-files-menu ()
21014 (let ((bl (buffer-list)))
21015 (save-excursion
21016 (while bl
21017 (set-buffer (pop bl))
21018 (when (derived-mode-p 'org-mode) (setq bl nil)))
21019 (when (derived-mode-p 'org-mode)
21020 (easy-menu-change
21021 '("Org") "File List for Agenda"
21022 (append
21023 (list
21024 ["Edit File List" (org-edit-agenda-file-list) t]
21025 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21026 ["Remove Current File from List" org-remove-file t]
21027 ["Cycle through agenda files" org-cycle-agenda-files t]
21028 ["Occur in all agenda files" org-occur-in-agenda-files t]
21029 "--")
21030 (mapcar 'org-file-menu-entry
21031 ;; Prevent initialization from failing.
21032 (ignore-errors (org-agenda-files t)))))))))
21034 ;;;; Documentation
21036 (defun org-require-autoloaded-modules ()
21037 (interactive)
21038 (mapc #'require
21039 '(org-agenda org-archive org-attach org-clock org-colview org-id
21040 org-table org-timer)))
21042 ;;;###autoload
21043 (defun org-reload (&optional uncompiled)
21044 "Reload all org lisp files.
21045 With prefix arg UNCOMPILED, load the uncompiled versions."
21046 (interactive "P")
21047 (require 'loadhist)
21048 (let* ((org-dir (org-find-library-dir "org"))
21049 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21050 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21051 (remove-re (format "\\`%s\\'"
21052 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21053 (feats (delete-dups
21054 (mapcar 'file-name-sans-extension
21055 (mapcar 'file-name-nondirectory
21056 (delq nil
21057 (mapcar 'feature-file
21058 features))))))
21059 (lfeat (append
21060 (sort
21061 (setq feats
21062 (delq nil (mapcar
21063 (lambda (f)
21064 (if (and (string-match feature-re f)
21065 (not (string-match remove-re f)))
21066 f nil))
21067 feats)))
21068 'string-lessp)
21069 (list "org-version" "org")))
21070 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21071 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21072 load-uncore load-misses)
21073 (setq load-misses
21074 (delq 't
21075 (mapcar (lambda (f)
21076 (or (org-load-noerror-mustsuffix (concat org-dir f))
21077 (and (string= org-dir contrib-dir)
21078 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21079 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21080 (add-to-list 'load-uncore f 'append)
21083 lfeat)))
21084 (when load-uncore
21085 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21086 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21087 (if load-misses
21088 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21089 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21090 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21092 ;;;###autoload
21093 (defun org-customize ()
21094 "Call the customize function with org as argument."
21095 (interactive)
21096 (org-load-modules-maybe)
21097 (org-require-autoloaded-modules)
21098 (customize-browse 'org))
21100 (defun org-create-customize-menu ()
21101 "Create a full customization menu for Org mode, insert it into the menu."
21102 (interactive)
21103 (org-load-modules-maybe)
21104 (org-require-autoloaded-modules)
21105 (if (fboundp 'customize-menu-create)
21106 (progn
21107 (easy-menu-change
21108 '("Org") "Customize"
21109 `(["Browse Org group" org-customize t]
21110 "--"
21111 ,(customize-menu-create 'org)
21112 ["Set" Custom-set t]
21113 ["Save" Custom-save t]
21114 ["Reset to Current" Custom-reset-current t]
21115 ["Reset to Saved" Custom-reset-saved t]
21116 ["Reset to Standard Settings" Custom-reset-standard t]))
21117 (message "\"Org\"-menu now contains full customization menu"))
21118 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21120 ;;;; Miscellaneous stuff
21122 ;;; Generally useful functions
21124 (defun org-link-display-format (s)
21125 "Replace links in string S with their description.
21126 If there is no description, use the link target."
21127 (save-match-data
21128 (replace-regexp-in-string
21129 org-bracket-link-analytic-regexp
21130 (lambda (m)
21131 (if (match-end 5) (match-string 5 m)
21132 (concat (match-string 1 m) (match-string 3 m))))
21133 s nil t)))
21135 (defun org-toggle-link-display ()
21136 "Toggle the literal or descriptive display of links."
21137 (interactive)
21138 (if org-descriptive-links
21139 (progn (org-remove-from-invisibility-spec '(org-link))
21140 (org-restart-font-lock)
21141 (setq org-descriptive-links nil))
21142 (progn (add-to-invisibility-spec '(org-link))
21143 (org-restart-font-lock)
21144 (setq org-descriptive-links t))))
21146 (defun org-in-clocktable-p ()
21147 "Check if the cursor is in a clocktable."
21148 (let ((pos (point)) start)
21149 (save-excursion
21150 (end-of-line 1)
21151 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21152 (setq start (match-beginning 0))
21153 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21154 (>= (match-end 0) pos)
21155 start))))
21157 (defun org-in-verbatim-emphasis ()
21158 (save-match-data
21159 (and (org-in-regexp org-verbatim-re 2)
21160 (>= (point) (match-beginning 3))
21161 (<= (point) (match-end 4)))))
21163 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21164 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21165 (if (and marker (marker-buffer marker)
21166 (buffer-live-p (marker-buffer marker)))
21167 (progn
21168 (pop-to-buffer-same-window (marker-buffer marker))
21169 (when (or (> marker (point-max)) (< marker (point-min)))
21170 (widen))
21171 (goto-char marker)
21172 (org-show-context 'org-goto))
21173 (if bookmark
21174 (bookmark-jump bookmark)
21175 (error "Cannot find location"))))
21177 (defun org-quote-csv-field (s)
21178 "Quote field for inclusion in CSV material."
21179 (if (string-match "[\",]" s)
21180 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21183 (defun org-force-self-insert (N)
21184 "Needed to enforce self-insert under remapping."
21185 (interactive "p")
21186 (self-insert-command N))
21188 (defun org-get-indentation (&optional line)
21189 "Get the indentation of the current line, interpreting tabs.
21190 When LINE is given, assume it represents a line and compute its indentation."
21191 (if line
21192 (when (string-match "^ *" (org-remove-tabs line))
21193 (match-end 0))
21194 (save-excursion
21195 (beginning-of-line 1)
21196 (skip-chars-forward " \t")
21197 (current-column))))
21199 (defun org-get-string-indentation (s)
21200 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21201 (let ((n -1) (i 0) (w tab-width) c)
21202 (catch 'exit
21203 (while (< (setq n (1+ n)) (length s))
21204 (setq c (aref s n))
21205 (cond ((= c ?\ ) (setq i (1+ i)))
21206 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21207 (t (throw 'exit t)))))
21210 (defun org-fix-indentation (line ind)
21211 "Fix indentation in LINE.
21212 IND is a cons cell with target and minimum indentation.
21213 If the current indentation in LINE is smaller than the minimum,
21214 leave it alone. If it is larger than ind, set it to the target."
21215 (let* ((l (org-remove-tabs line))
21216 (i (org-get-indentation l))
21217 (i1 (car ind)) (i2 (cdr ind)))
21218 (when (>= i i2) (setq l (substring line i2)))
21219 (if (> i1 0)
21220 (concat (make-string i1 ?\ ) l)
21221 l)))
21223 (defun org-fill-template (template alist)
21224 "Find each %key of ALIST in TEMPLATE and replace it."
21225 (let ((case-fold-search nil))
21226 (dolist (entry (sort (copy-sequence alist)
21227 (lambda (a b) (< (length (car a)) (length (car b))))))
21228 (setq template
21229 (replace-regexp-in-string
21230 (concat "%" (regexp-quote (car entry)))
21231 (or (cdr entry) "") template t t)))
21232 template))
21234 (defun org-quote-vert (s)
21235 "Replace \"|\" with \"\\vert\"."
21236 (while (string-match "|" s)
21237 (setq s (replace-match "\\vert" t t s)))
21240 (defun org-uuidgen-p (s)
21241 "Is S an ID created by UUIDGEN?"
21242 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21244 (defun org-in-src-block-p (&optional inside)
21245 "Whether point is in a code source block.
21246 When INSIDE is non-nil, don't consider we are within a src block
21247 when point is at #+BEGIN_SRC or #+END_SRC."
21248 (let ((case-fold-search t))
21249 (or (and (eq (get-char-property (point) 'src-block) t))
21250 (and (not inside)
21251 (save-match-data
21252 (save-excursion
21253 (beginning-of-line)
21254 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21256 (defun org-context ()
21257 "Return a list of contexts of the current cursor position.
21258 If several contexts apply, all are returned.
21259 Each context entry is a list with a symbol naming the context, and
21260 two positions indicating start and end of the context. Possible
21261 contexts are:
21263 :headline anywhere in a headline
21264 :headline-stars on the leading stars in a headline
21265 :todo-keyword on a TODO keyword (including DONE) in a headline
21266 :tags on the TAGS in a headline
21267 :priority on the priority cookie in a headline
21268 :item on the first line of a plain list item
21269 :item-bullet on the bullet/number of a plain list item
21270 :checkbox on the checkbox in a plain list item
21271 :table in an Org table
21272 :table-special on a special filed in a table
21273 :table-table in a table.el table
21274 :clocktable in a clocktable
21275 :src-block in a source block
21276 :link on a hyperlink
21277 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21278 :target on a <<target>>
21279 :radio-target on a <<<radio-target>>>
21280 :latex-fragment on a LaTeX fragment
21281 :latex-preview on a LaTeX fragment with overlaid preview image
21283 This function expects the position to be visible because it uses font-lock
21284 faces as a help to recognize the following contexts: :table-special, :link,
21285 and :keyword."
21286 (let* ((f (get-text-property (point) 'face))
21287 (faces (if (listp f) f (list f)))
21288 (case-fold-search t)
21289 (p (point)) clist o)
21290 ;; First the large context
21291 (cond
21292 ((org-at-heading-p t)
21293 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21294 (when (progn
21295 (beginning-of-line 1)
21296 (looking-at org-todo-line-tags-regexp))
21297 (push (org-point-in-group p 1 :headline-stars) clist)
21298 (push (org-point-in-group p 2 :todo-keyword) clist)
21299 (push (org-point-in-group p 4 :tags) clist))
21300 (goto-char p)
21301 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21302 (when (looking-at "\\[#[A-Z0-9]\\]")
21303 (push (org-point-in-group p 0 :priority) clist)))
21305 ((org-at-item-p)
21306 (push (org-point-in-group p 2 :item-bullet) clist)
21307 (push (list :item (point-at-bol)
21308 (save-excursion (org-end-of-item) (point)))
21309 clist)
21310 (and (org-at-item-checkbox-p)
21311 (push (org-point-in-group p 0 :checkbox) clist)))
21313 ((org-at-table-p)
21314 (push (list :table (org-table-begin) (org-table-end)) clist)
21315 (when (memq 'org-formula faces)
21316 (push (list :table-special
21317 (previous-single-property-change p 'face)
21318 (next-single-property-change p 'face)) clist)))
21319 ((org-at-table-p 'any)
21320 (push (list :table-table) clist)))
21321 (goto-char p)
21323 (let ((case-fold-search t))
21324 ;; New the "medium" contexts: clocktables, source blocks
21325 (cond ((org-in-clocktable-p)
21326 (push (list :clocktable
21327 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21328 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21329 (match-beginning 1))
21330 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21331 (match-end 0))) clist))
21332 ((org-in-src-block-p)
21333 (push (list :src-block
21334 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21335 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21336 (match-beginning 1))
21337 (and (search-forward "#+END_SRC" nil t)
21338 (match-beginning 0))) clist))))
21339 (goto-char p)
21341 ;; Now the small context
21342 (cond
21343 ((org-at-timestamp-p)
21344 (push (org-point-in-group p 0 :timestamp) clist))
21345 ((memq 'org-link faces)
21346 (push (list :link
21347 (previous-single-property-change p 'face)
21348 (next-single-property-change p 'face)) clist))
21349 ((memq 'org-special-keyword faces)
21350 (push (list :keyword
21351 (previous-single-property-change p 'face)
21352 (next-single-property-change p 'face)) clist))
21353 ((org-at-target-p)
21354 (push (org-point-in-group p 0 :target) clist)
21355 (goto-char (1- (match-beginning 0)))
21356 (when (looking-at org-radio-target-regexp)
21357 (push (org-point-in-group p 0 :radio-target) clist))
21358 (goto-char p))
21359 ((setq o (cl-some
21360 (lambda (o)
21361 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21363 (overlays-at (point))))
21364 (push (list :latex-fragment
21365 (overlay-start o) (overlay-end o)) clist)
21366 (push (list :latex-preview
21367 (overlay-start o) (overlay-end o)) clist))
21368 ((org-inside-LaTeX-fragment-p)
21369 ;; FIXME: positions wrong.
21370 (push (list :latex-fragment (point) (point)) clist)))
21372 (setq clist (nreverse (delq nil clist)))
21373 clist))
21375 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21376 "Non-nil when point is between matches of START-RE and END-RE.
21378 Also return a non-nil value when point is on one of the matches.
21380 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21381 buffer positions. Default values are the positions of headlines
21382 surrounding the point.
21384 The functions returns a cons cell whose car (resp. cdr) is the
21385 position before START-RE (resp. after END-RE)."
21386 (save-match-data
21387 (let ((pos (point))
21388 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21389 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21390 beg end)
21391 (save-excursion
21392 ;; Point is on a block when on START-RE or if START-RE can be
21393 ;; found before it...
21394 (and (or (org-in-regexp start-re)
21395 (re-search-backward start-re limit-up t))
21396 (setq beg (match-beginning 0))
21397 ;; ... and END-RE after it...
21398 (goto-char (match-end 0))
21399 (re-search-forward end-re limit-down t)
21400 (> (setq end (match-end 0)) pos)
21401 ;; ... without another START-RE in-between.
21402 (goto-char (match-beginning 0))
21403 (not (re-search-backward start-re (1+ beg) t))
21404 ;; Return value.
21405 (cons beg end))))))
21407 (defun org-in-block-p (names)
21408 "Non-nil when point belongs to a block whose name belongs to NAMES.
21410 NAMES is a list of strings containing names of blocks.
21412 Return first block name matched, or nil. Beware that in case of
21413 nested blocks, the returned name may not belong to the closest
21414 block from point."
21415 (save-match-data
21416 (catch 'exit
21417 (let ((case-fold-search t)
21418 (lim-up (save-excursion (outline-previous-heading)))
21419 (lim-down (save-excursion (outline-next-heading))))
21420 (dolist (name names)
21421 (let ((n (regexp-quote name)))
21422 (when (org-between-regexps-p
21423 (concat "^[ \t]*#\\+begin_" n)
21424 (concat "^[ \t]*#\\+end_" n)
21425 lim-up lim-down)
21426 (throw 'exit n)))))
21427 nil)))
21429 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21430 "Call `multi-occur' with buffers for all agenda files."
21431 (interactive "sOrg-files matching: ")
21432 (let* ((files (org-agenda-files))
21433 (tnames (mapcar #'file-truename files))
21434 (extra org-agenda-text-search-extra-files))
21435 (when (eq (car extra) 'agenda-archives)
21436 (setq extra (cdr extra))
21437 (setq files (org-add-archive-files files)))
21438 (dolist (f extra)
21439 (unless (member (file-truename f) tnames)
21440 (unless (member f files) (setq files (append files (list f))))
21441 (setq tnames (append tnames (list (file-truename f))))))
21442 (multi-occur
21443 (mapcar (lambda (x)
21444 (with-current-buffer
21445 ;; FIXME: Why not just (find-file-noselect x)?
21446 ;; Is it to avoid the "revert buffer" prompt?
21447 (or (get-file-buffer x) (find-file-noselect x))
21448 (widen)
21449 (current-buffer)))
21450 files)
21451 regexp)))
21453 (add-hook 'occur-mode-find-occurrence-hook
21454 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21456 (defun org-occur-link-in-agenda-files ()
21457 "Create a link and search for it in the agendas.
21458 The link is not stored in `org-stored-links', it is just created
21459 for the search purpose."
21460 (interactive)
21461 (let ((link (condition-case nil
21462 (org-store-link nil)
21463 (error "Unable to create a link to here"))))
21464 (org-occur-in-agenda-files (regexp-quote link))))
21466 (defun org-back-over-empty-lines ()
21467 "Move backwards over whitespace, to the beginning of the first empty line.
21468 Returns the number of empty lines passed."
21469 (let ((pos (point)))
21470 (if (cdr (assq 'heading org-blank-before-new-entry))
21471 (skip-chars-backward " \t\n\r")
21472 (unless (eobp)
21473 (forward-line -1)))
21474 (beginning-of-line 2)
21475 (goto-char (min (point) pos))
21476 (count-lines (point) pos)))
21478 (defun org-switch-to-buffer-other-window (&rest args)
21479 "Switch to buffer in a second window on the current frame.
21480 In particular, do not allow pop-up frames.
21481 Returns the newly created buffer."
21482 (org-no-popups
21483 (apply 'switch-to-buffer-other-window args)))
21485 (defun org-replace-escapes (string table)
21486 "Replace %-escapes in STRING with values in TABLE.
21487 TABLE is an association list with keys like \"%a\" and string values.
21488 The sequences in STRING may contain normal field width and padding information,
21489 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21490 so values can contain further %-escapes if they are define later in TABLE."
21491 (let ((tbl (copy-alist table))
21492 (case-fold-search nil)
21493 (pchg 0)
21494 re rpl)
21495 (dolist (e tbl)
21496 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21497 (when (and (cdr e) (string-match re (cdr e)))
21498 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21499 (safe "SREF"))
21500 (add-text-properties 0 3 (list 'sref sref) safe)
21501 (setcdr e (replace-match safe t t (cdr e)))))
21502 (while (string-match re string)
21503 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21504 (cdr e)))
21505 (setq string (replace-match rpl t t string))))
21506 (while (setq pchg (next-property-change pchg string))
21507 (let ((sref (get-text-property pchg 'sref string)))
21508 (when (and sref (string-match "SREF" string pchg))
21509 (setq string (replace-match sref t t string)))))
21510 string))
21512 ;;; TODO: Only called once, from ox-odt which should probably use
21513 ;;; org-export-inline-image-p or something.
21514 (defun org-file-image-p (file)
21515 "Return non-nil if FILE is an image."
21516 (save-match-data
21517 (string-match (image-file-name-regexp) file)))
21519 (defun org-get-cursor-date (&optional with-time)
21520 "Return the date at cursor in as a time.
21521 This works in the calendar and in the agenda, anywhere else it just
21522 returns the current time.
21523 If WITH-TIME is non-nil, returns the time of the event at point (in
21524 the agenda) or the current time of the day."
21525 (let (date day defd tp hod mod)
21526 (when with-time
21527 (setq tp (get-text-property (point) 'time))
21528 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21529 (setq hod (string-to-number (match-string 1 tp))
21530 mod (string-to-number (match-string 2 tp))))
21531 (or tp (let ((now (decode-time)))
21532 (setq hod (nth 2 now)
21533 mod (nth 1 now)))))
21534 (cond
21535 ((eq major-mode 'calendar-mode)
21536 (setq date (calendar-cursor-to-date)
21537 defd (encode-time 0 (or mod 0) (or hod 0)
21538 (nth 1 date) (nth 0 date) (nth 2 date))))
21539 ((eq major-mode 'org-agenda-mode)
21540 (setq day (get-text-property (point) 'day))
21541 (when day
21542 (setq date (calendar-gregorian-from-absolute day)
21543 defd (encode-time 0 (or mod 0) (or hod 0)
21544 (nth 1 date) (nth 0 date) (nth 2 date))))))
21545 (or defd (current-time))))
21547 (defun org-mark-subtree (&optional up)
21548 "Mark the current subtree.
21549 This puts point at the start of the current subtree, and mark at
21550 the end. If a numeric prefix UP is given, move up into the
21551 hierarchy of headlines by UP levels before marking the subtree."
21552 (interactive "P")
21553 (org-with-limited-levels
21554 (cond ((org-at-heading-p) (beginning-of-line))
21555 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21556 (t (outline-previous-visible-heading 1))))
21557 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21558 (if (called-interactively-p 'any)
21559 (call-interactively 'org-mark-element)
21560 (org-mark-element)))
21562 (defun org-file-newer-than-p (file time)
21563 "Non-nil if FILE is newer than TIME.
21564 FILE is a filename, as a string, TIME is a list of integers, as
21565 returned by, e.g., `current-time'."
21566 (and (file-exists-p file)
21567 ;; Only compare times up to whole seconds as some file-systems
21568 ;; (e.g. HFS+) do not retain any finer granularity. As
21569 ;; a consequence, make sure we return non-nil when the two
21570 ;; times are equal.
21571 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21572 (cl-subseq time 0 2)))))
21574 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21575 "Compile a SOURCE file using PROCESS.
21577 PROCESS is either a function or a list of shell commands, as
21578 strings. EXT is a file extension, without the leading dot, as
21579 a string. It is used to check if the process actually succeeded.
21581 PROCESS must create a file with the same base name and directory
21582 as SOURCE, but ending with EXT. The function then returns its
21583 filename. Otherwise, it raises an error. The error message can
21584 then be refined by providing string ERR-MSG, which is appended to
21585 the standard message.
21587 If PROCESS is a function, it is called with a single argument:
21588 the SOURCE file.
21590 If it is a list of commands, each of them is called using
21591 `shell-command'. By default, in each command, %b, %f, %F, %o and
21592 %O are replaced with, respectively, SOURCE base name, name, full
21593 name, directory and absolute output file name. It is possible,
21594 however, to use more place-holders by specifying them in optional
21595 argument SPEC, as an alist following the pattern
21597 (CHARACTER . REPLACEMENT-STRING).
21599 When PROCESS is a list of commands, optional argument LOG-BUF can
21600 be set to a buffer or a buffer name. `shell-command' then uses
21601 it for output."
21602 (let* ((base-name (file-name-base source))
21603 (full-name (file-truename source))
21604 (out-dir (or (file-name-directory source) "./"))
21605 (output (expand-file-name (concat base-name "." ext) out-dir))
21606 (time (current-time))
21607 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21608 (save-window-excursion
21609 (pcase process
21610 ((pred functionp) (funcall process (shell-quote-argument source)))
21611 ((pred consp)
21612 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21613 (spec (append spec
21614 `((?b . ,(shell-quote-argument base-name))
21615 (?f . ,(shell-quote-argument source))
21616 (?F . ,(shell-quote-argument full-name))
21617 (?o . ,(shell-quote-argument out-dir))
21618 (?O . ,(shell-quote-argument output))))))
21619 (dolist (command process)
21620 (shell-command (format-spec command spec) log-buf))
21621 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21622 (_ (error "No valid command to process %S%s" source err-msg))))
21623 ;; Check for process failure. Output file is expected to be
21624 ;; located in the same directory as SOURCE.
21625 (unless (org-file-newer-than-p output time)
21626 (error (format "File %S wasn't produced%s" output err-msg)))
21627 output))
21629 ;;; Indentation
21631 (defvar org-element-greater-elements)
21632 (defun org--get-expected-indentation (element contentsp)
21633 "Expected indentation column for current line, according to ELEMENT.
21634 ELEMENT is an element containing point. CONTENTSP is non-nil
21635 when indentation is to be computed according to contents of
21636 ELEMENT."
21637 (let ((type (org-element-type element))
21638 (start (org-element-property :begin element))
21639 (post-affiliated (org-element-property :post-affiliated element)))
21640 (org-with-wide-buffer
21641 (cond
21642 (contentsp
21643 (cl-case type
21644 ((diary-sexp footnote-definition) 0)
21645 ((headline inlinetask nil)
21646 (if (not org-adapt-indentation) 0
21647 (let ((level (org-current-level)))
21648 (if level (1+ level) 0))))
21649 ((item plain-list) (org-list-item-body-column post-affiliated))
21651 (goto-char start)
21652 (org-get-indentation))))
21653 ((memq type '(headline inlinetask nil))
21654 (if (org-match-line "[ \t]*$")
21655 (org--get-expected-indentation element t)
21657 ((memq type '(diary-sexp footnote-definition)) 0)
21658 ;; First paragraph of a footnote definition or an item.
21659 ;; Indent like parent.
21660 ((< (line-beginning-position) start)
21661 (org--get-expected-indentation
21662 (org-element-property :parent element) t))
21663 ;; At first line: indent according to previous sibling, if any,
21664 ;; ignoring footnote definitions and inline tasks, or parent's
21665 ;; contents.
21666 ((= (line-beginning-position) start)
21667 (catch 'exit
21668 (while t
21669 (if (= (point-min) start) (throw 'exit 0)
21670 (goto-char (1- start))
21671 (let* ((previous (org-element-at-point))
21672 (parent previous))
21673 (while (and parent (<= (org-element-property :end parent) start))
21674 (setq previous parent
21675 parent (org-element-property :parent parent)))
21676 (cond
21677 ((not previous) (throw 'exit 0))
21678 ((> (org-element-property :end previous) start)
21679 (throw 'exit (org--get-expected-indentation previous t)))
21680 ((memq (org-element-type previous)
21681 '(footnote-definition inlinetask))
21682 (setq start (org-element-property :begin previous)))
21683 (t (goto-char (org-element-property :begin previous))
21684 (throw 'exit
21685 (if (bolp) (org-get-indentation)
21686 ;; At first paragraph in an item or
21687 ;; a footnote definition.
21688 (org--get-expected-indentation
21689 (org-element-property :parent previous) t))))))))))
21690 ;; Otherwise, move to the first non-blank line above.
21692 (beginning-of-line)
21693 (let ((pos (point)))
21694 (skip-chars-backward " \r\t\n")
21695 (cond
21696 ;; Two blank lines end a footnote definition or a plain
21697 ;; list. When we indent an empty line after them, the
21698 ;; containing list or footnote definition is over, so it
21699 ;; qualifies as a previous sibling. Therefore, we indent
21700 ;; like its first line.
21701 ((and (memq type '(footnote-definition plain-list))
21702 (> (count-lines (point) pos) 2))
21703 (goto-char start)
21704 (org-get-indentation))
21705 ;; Line above is the first one of a paragraph at the
21706 ;; beginning of an item or a footnote definition. Indent
21707 ;; like parent.
21708 ((< (line-beginning-position) start)
21709 (org--get-expected-indentation
21710 (org-element-property :parent element) t))
21711 ;; Line above is the beginning of an element, i.e., point
21712 ;; was originally on the blank lines between element's start
21713 ;; and contents.
21714 ((= (line-beginning-position) post-affiliated)
21715 (org--get-expected-indentation element t))
21716 ;; POS is after contents in a greater element. Indent like
21717 ;; the beginning of the element.
21718 ((and (memq type org-element-greater-elements)
21719 (let ((cend (org-element-property :contents-end element)))
21720 (and cend (<= cend pos))))
21721 ;; As a special case, if point is at the end of a footnote
21722 ;; definition or an item, indent like the very last element
21723 ;; within. If that last element is an item, indent like
21724 ;; its contents.
21725 (if (memq type '(footnote-definition item plain-list))
21726 (let ((last (org-element-at-point)))
21727 (goto-char pos)
21728 (org--get-expected-indentation
21729 last (eq (org-element-type last) 'item)))
21730 (goto-char start)
21731 (org-get-indentation)))
21732 ;; In any other case, indent like the current line.
21733 (t (org-get-indentation)))))))))
21735 (defun org--align-node-property ()
21736 "Align node property at point.
21737 Alignment is done according to `org-property-format', which see."
21738 (when (save-excursion
21739 (beginning-of-line)
21740 (looking-at org-property-re))
21741 (replace-match
21742 (concat (match-string 4)
21743 (org-trim
21744 (format org-property-format (match-string 1) (match-string 3))))
21745 t t)))
21747 (defun org-indent-line ()
21748 "Indent line depending on context.
21750 Indentation is done according to the following rules:
21752 - Footnote definitions, diary sexps, headlines and inline tasks
21753 have to start at column 0.
21755 - On the very first line of an element, consider, in order, the
21756 next rules until one matches:
21758 1. If there's a sibling element before, ignoring footnote
21759 definitions and inline tasks, indent like its first line.
21761 2. If element has a parent, indent like its contents. More
21762 precisely, if parent is an item, indent after the
21763 description part, if any, or the bullet (see
21764 `org-list-description-max-indent'). Else, indent like
21765 parent's first line.
21767 3. Otherwise, indent relatively to current level, if
21768 `org-adapt-indentation' is non-nil, or to left margin.
21770 - On a blank line at the end of an element, indent according to
21771 the type of the element. More precisely
21773 1. If element is a plain list, an item, or a footnote
21774 definition, indent like the very last element within.
21776 2. If element is a paragraph, indent like its last non blank
21777 line.
21779 3. Otherwise, indent like its very first line.
21781 - In the code part of a source block, use language major mode
21782 to indent current line if `org-src-tab-acts-natively' is
21783 non-nil. If it is nil, do nothing.
21785 - Otherwise, indent like the first non-blank line above.
21787 The function doesn't indent an item as it could break the whole
21788 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21789 `\\[org-shiftmetaright]'.
21791 Also align node properties according to `org-property-format'."
21792 (interactive)
21793 (cond
21794 ((org-at-heading-p) 'noindent)
21796 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21797 (type (org-element-type element)))
21798 (cond ((and (memq type '(plain-list item))
21799 (= (line-beginning-position)
21800 (org-element-property :post-affiliated element)))
21801 'noindent)
21802 ((and (eq type 'latex-environment)
21803 (>= (point) (org-element-property :post-affiliated element))
21804 (< (point) (org-with-wide-buffer
21805 (goto-char (org-element-property :end element))
21806 (skip-chars-backward " \r\t\n")
21807 (line-beginning-position 2))))
21808 'noindent)
21809 ((and (eq type 'src-block)
21810 org-src-tab-acts-natively
21811 (> (line-beginning-position)
21812 (org-element-property :post-affiliated element))
21813 (< (line-beginning-position)
21814 (org-with-wide-buffer
21815 (goto-char (org-element-property :end element))
21816 (skip-chars-backward " \r\t\n")
21817 (line-beginning-position))))
21818 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21820 (let ((column (org--get-expected-indentation element nil)))
21821 ;; Preserve current column.
21822 (if (<= (current-column) (current-indentation))
21823 (indent-line-to column)
21824 (save-excursion (indent-line-to column))))
21825 ;; Align node property. Also preserve current column.
21826 (when (eq type 'node-property)
21827 (let ((column (current-column)))
21828 (org--align-node-property)
21829 (org-move-to-column column)))))))))
21831 (defun org-indent-region (start end)
21832 "Indent each non-blank line in the region.
21833 Called from a program, START and END specify the region to
21834 indent. The function will not indent contents of example blocks,
21835 verse blocks and export blocks as leading white spaces are
21836 assumed to be significant there."
21837 (interactive "r")
21838 (save-excursion
21839 (goto-char start)
21840 (skip-chars-forward " \r\t\n")
21841 (unless (eobp) (beginning-of-line))
21842 (let ((indent-to
21843 (lambda (ind pos)
21844 ;; Set IND as indentation for all lines between point and
21845 ;; POS. Blank lines are ignored. Leave point after POS
21846 ;; once done.
21847 (let ((limit (copy-marker pos)))
21848 (while (< (point) limit)
21849 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21850 (forward-line))
21851 (set-marker limit nil))))
21852 (end (copy-marker end)))
21853 (while (< (point) end)
21854 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21855 (let* ((element (org-element-at-point))
21856 (type (org-element-type element))
21857 (element-end (copy-marker (org-element-property :end element)))
21858 (ind (org--get-expected-indentation element nil)))
21859 (cond
21860 ;; Element indented as a single block. Example blocks
21861 ;; preserving indentation are a special case since the
21862 ;; "contents" must not be indented whereas the block
21863 ;; boundaries can.
21864 ((or (memq type '(export-block latex-environment))
21865 (and (eq type 'example-block)
21866 (not
21867 (or org-src-preserve-indentation
21868 (org-element-property :preserve-indent element)))))
21869 (let ((offset (- ind (org-get-indentation))))
21870 (unless (zerop offset)
21871 (indent-rigidly (org-element-property :begin element)
21872 (org-element-property :end element)
21873 offset)))
21874 (goto-char element-end))
21875 ;; Elements indented line wise. Be sure to exclude
21876 ;; example blocks (preserving indentation) and source
21877 ;; blocks from this category as they are treated
21878 ;; specially later.
21879 ((or (memq type '(paragraph table table-row))
21880 (not (or (org-element-property :contents-begin element)
21881 (memq type '(example-block src-block)))))
21882 (when (eq type 'node-property)
21883 (org--align-node-property)
21884 (beginning-of-line))
21885 (funcall indent-to ind (min element-end end)))
21886 ;; Elements consisting of three parts: before the
21887 ;; contents, the contents, and after the contents. The
21888 ;; contents are treated specially, according to the
21889 ;; element type, or not indented at all. Other parts are
21890 ;; indented as a single block.
21892 (let* ((post (copy-marker
21893 (org-element-property :post-affiliated element)))
21894 (cbeg
21895 (copy-marker
21896 (cond
21897 ((not (org-element-property :contents-begin element))
21898 ;; Fake contents for source blocks.
21899 (org-with-wide-buffer
21900 (goto-char post)
21901 (line-beginning-position 2)))
21902 ((memq type '(footnote-definition item plain-list))
21903 ;; Contents in these elements could start on
21904 ;; the same line as the beginning of the
21905 ;; element. Make sure we start indenting
21906 ;; from the second line.
21907 (org-with-wide-buffer
21908 (goto-char post)
21909 (end-of-line)
21910 (skip-chars-forward " \r\t\n")
21911 (if (eobp) (point) (line-beginning-position))))
21912 (t (org-element-property :contents-begin element)))))
21913 (cend (copy-marker
21914 (or (org-element-property :contents-end element)
21915 ;; Fake contents for source blocks.
21916 (org-with-wide-buffer
21917 (goto-char element-end)
21918 (skip-chars-backward " \r\t\n")
21919 (line-beginning-position)))
21920 t)))
21921 ;; Do not change items indentation individually as it
21922 ;; might break the list as a whole. On the other
21923 ;; hand, when at a plain list, indent it as a whole.
21924 (cond ((eq type 'plain-list)
21925 (let ((offset (- ind (org-get-indentation))))
21926 (unless (zerop offset)
21927 (indent-rigidly (org-element-property :begin element)
21928 (org-element-property :end element)
21929 offset))
21930 (goto-char cbeg)))
21931 ((eq type 'item) (goto-char cbeg))
21932 (t (funcall indent-to ind (min cbeg end))))
21933 (when (< (point) end)
21934 (cl-case type
21935 ((example-block verse-block))
21936 (src-block
21937 ;; In a source block, indent source code
21938 ;; according to language major mode, but only if
21939 ;; `org-src-tab-acts-natively' is non-nil.
21940 (when (and (< (point) end) org-src-tab-acts-natively)
21941 (ignore-errors
21942 (org-babel-do-in-edit-buffer
21943 (indent-region (point-min) (point-max))))))
21944 (t (org-indent-region (point) (min cend end))))
21945 (goto-char (min cend end))
21946 (when (< (point) end)
21947 (funcall indent-to ind (min element-end end))))
21948 (set-marker post nil)
21949 (set-marker cbeg nil)
21950 (set-marker cend nil))))
21951 (set-marker element-end nil))))
21952 (set-marker end nil))))
21954 (defun org-indent-drawer ()
21955 "Indent the drawer at point."
21956 (interactive)
21957 (unless (save-excursion
21958 (beginning-of-line)
21959 (looking-at-p org-drawer-regexp))
21960 (user-error "Not at a drawer"))
21961 (let ((element (org-element-at-point)))
21962 (unless (memq (org-element-type element) '(drawer property-drawer))
21963 (user-error "Not at a drawer"))
21964 (org-with-wide-buffer
21965 (org-indent-region (org-element-property :begin element)
21966 (org-element-property :end element))))
21967 (message "Drawer at point indented"))
21969 (defun org-indent-block ()
21970 "Indent the block at point."
21971 (interactive)
21972 (unless (save-excursion
21973 (beginning-of-line)
21974 (let ((case-fold-search t))
21975 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21976 (user-error "Not at a block"))
21977 (let ((element (org-element-at-point)))
21978 (unless (memq (org-element-type element)
21979 '(comment-block center-block dynamic-block example-block
21980 export-block quote-block special-block
21981 src-block verse-block))
21982 (user-error "Not at a block"))
21983 (org-with-wide-buffer
21984 (org-indent-region (org-element-property :begin element)
21985 (org-element-property :end element))))
21986 (message "Block at point indented"))
21989 ;;; Filling
21991 ;; We use our own fill-paragraph and auto-fill functions.
21993 ;; `org-fill-paragraph' relies on adaptive filling and context
21994 ;; checking. Appropriate `fill-prefix' is computed with
21995 ;; `org-adaptive-fill-function'.
21997 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21998 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21999 ;; `org-adaptive-fill-function' value. Internally,
22000 ;; `org-comment-line-break-function' breaks the line.
22002 ;; `org-setup-filling' installs filling and auto-filling related
22003 ;; variables during `org-mode' initialization.
22005 (defun org-setup-filling ()
22006 (require 'org-element)
22007 ;; Prevent auto-fill from inserting unwanted new items.
22008 (when (boundp 'fill-nobreak-predicate)
22009 (setq-local
22010 fill-nobreak-predicate
22011 (org-uniquify
22012 (append fill-nobreak-predicate
22013 '(org-fill-line-break-nobreak-p
22014 org-fill-n-macro-as-item-nobreak-p
22015 org-fill-paragraph-with-timestamp-nobreak-p)))))
22016 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22017 (setq-local paragraph-start paragraph-ending)
22018 (setq-local paragraph-separate paragraph-ending))
22019 (setq-local fill-paragraph-function 'org-fill-paragraph)
22020 (setq-local auto-fill-inhibit-regexp nil)
22021 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22022 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22023 (setq-local comment-line-break-function 'org-comment-line-break-function))
22025 (defun org-fill-line-break-nobreak-p ()
22026 "Non-nil when a new line at point would create an Org line break."
22027 (save-excursion
22028 (skip-chars-backward "[ \t]")
22029 (skip-chars-backward "\\\\")
22030 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22032 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22033 "Non-nil when a new line at point would split a timestamp."
22034 (and (org-at-timestamp-p 'lax)
22035 (not (looking-at org-ts-regexp-both))))
22037 (defun org-fill-n-macro-as-item-nobreak-p ()
22038 "Non-nil when a new line at point would create a new list."
22039 ;; During export, a "n" macro followed by a dot or a closing
22040 ;; parenthesis can end up being parsed as a new list item.
22041 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22043 (declare-function message-in-body-p "message" ())
22044 (defvar orgtbl-line-start-regexp) ; From org-table.el
22045 (defun org-adaptive-fill-function ()
22046 "Compute a fill prefix for the current line.
22047 Return fill prefix, as a string, or nil if current line isn't
22048 meant to be filled. For convenience, if `adaptive-fill-regexp'
22049 matches in paragraphs or comments, use it."
22050 (org-with-wide-buffer
22051 (unless (org-at-heading-p)
22052 (let* ((p (line-beginning-position))
22053 (element (save-excursion
22054 (beginning-of-line)
22055 (org-element-at-point)))
22056 (type (org-element-type element))
22057 (post-affiliated (org-element-property :post-affiliated element)))
22058 (unless (< p post-affiliated)
22059 (cl-case type
22060 (comment
22061 (save-excursion
22062 (beginning-of-line)
22063 (looking-at "[ \t]*")
22064 (concat (match-string 0) "# ")))
22065 (footnote-definition "")
22066 ((item plain-list)
22067 (make-string (org-list-item-body-column post-affiliated) ?\s))
22068 (paragraph
22069 ;; Fill prefix is usually the same as the current line,
22070 ;; unless the paragraph is at the beginning of an item.
22071 (let ((parent (org-element-property :parent element)))
22072 (save-excursion
22073 (beginning-of-line)
22074 (cond ((eq (org-element-type parent) 'item)
22075 (make-string (org-list-item-body-column
22076 (org-element-property :begin parent))
22077 ?\s))
22078 ((and adaptive-fill-regexp
22079 ;; Locally disable
22080 ;; `adaptive-fill-function' to let
22081 ;; `fill-context-prefix' handle
22082 ;; `adaptive-fill-regexp' variable.
22083 (let (adaptive-fill-function)
22084 (fill-context-prefix
22085 post-affiliated
22086 (org-element-property :end element)))))
22087 ((looking-at "[ \t]+") (match-string 0))
22088 (t "")))))
22089 (comment-block
22090 ;; Only fill contents if P is within block boundaries.
22091 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22092 (forward-line)
22093 (point)))
22094 (cend (save-excursion
22095 (goto-char (org-element-property :end element))
22096 (skip-chars-backward " \r\t\n")
22097 (line-beginning-position))))
22098 (when (and (>= p cbeg) (< p cend))
22099 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22100 (match-string 0)
22101 ""))))))))))
22103 (declare-function message-goto-body "message" ())
22104 (defvar message-cite-prefix-regexp) ; From message.el
22106 (defun org-fill-element (&optional justify)
22107 "Fill element at point, when applicable.
22109 This function only applies to comment blocks, comments, example
22110 blocks and paragraphs. Also, as a special case, re-align table
22111 when point is at one.
22113 If JUSTIFY is non-nil (interactively, with prefix argument),
22114 justify as well. If `sentence-end-double-space' is non-nil, then
22115 period followed by one space does not end a sentence, so don't
22116 break a line there. The variable `fill-column' controls the
22117 width for filling.
22119 For convenience, when point is at a plain list, an item or
22120 a footnote definition, try to fill the first paragraph within."
22121 (with-syntax-table org-mode-transpose-word-syntax-table
22122 ;; Move to end of line in order to get the first paragraph within
22123 ;; a plain list or a footnote definition.
22124 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22125 ;; First check if point is in a blank line at the beginning of
22126 ;; the buffer. In that case, ignore filling.
22127 (cl-case (org-element-type element)
22128 ;; Use major mode filling function is src blocks.
22129 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22130 ;; Align Org tables, leave table.el tables as-is.
22131 (table-row (org-table-align) t)
22132 (table
22133 (when (eq (org-element-property :type element) 'org)
22134 (save-excursion
22135 (goto-char (org-element-property :post-affiliated element))
22136 (org-table-align)))
22138 (paragraph
22139 ;; Paragraphs may contain `line-break' type objects.
22140 (let ((beg (max (point-min)
22141 (org-element-property :contents-begin element)))
22142 (end (min (point-max)
22143 (org-element-property :contents-end element))))
22144 ;; Do nothing if point is at an affiliated keyword.
22145 (if (< (line-end-position) beg) t
22146 ;; Fill paragraph, taking line breaks into account.
22147 (save-excursion
22148 (goto-char beg)
22149 (let ((cuts (list beg)))
22150 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22151 (when (eq 'line-break
22152 (org-element-type
22153 (save-excursion (backward-char)
22154 (org-element-context))))
22155 (push (point) cuts)))
22156 (dolist (c (delq end cuts))
22157 (fill-region-as-paragraph c end justify)
22158 (setq end c))))
22159 t)))
22160 ;; Contents of `comment-block' type elements should be
22161 ;; filled as plain text, but only if point is within block
22162 ;; markers.
22163 (comment-block
22164 (let* ((case-fold-search t)
22165 (beg (save-excursion
22166 (goto-char (org-element-property :begin element))
22167 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22168 (forward-line)
22169 (point)))
22170 (end (save-excursion
22171 (goto-char (org-element-property :end element))
22172 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22173 (line-beginning-position))))
22174 (if (or (< (point) beg) (> (point) end)) t
22175 (fill-region-as-paragraph
22176 (save-excursion (end-of-line)
22177 (re-search-backward "^[ \t]*$" beg 'move)
22178 (line-beginning-position))
22179 (save-excursion (beginning-of-line)
22180 (re-search-forward "^[ \t]*$" end 'move)
22181 (line-beginning-position))
22182 justify))))
22183 ;; Fill comments.
22184 (comment
22185 (let ((begin (org-element-property :post-affiliated element))
22186 (end (org-element-property :end element)))
22187 (when (and (>= (point) begin) (<= (point) end))
22188 (let ((begin (save-excursion
22189 (end-of-line)
22190 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22191 (progn (forward-line) (point))
22192 begin)))
22193 (end (save-excursion
22194 (end-of-line)
22195 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22196 (1- (line-beginning-position))
22197 (skip-chars-backward " \r\t\n")
22198 (line-end-position)))))
22199 ;; Do not fill comments when at a blank line.
22200 (when (> end begin)
22201 (let ((fill-prefix
22202 (save-excursion
22203 (beginning-of-line)
22204 (looking-at "[ \t]*#")
22205 (let ((comment-prefix (match-string 0)))
22206 (goto-char (match-end 0))
22207 (if (looking-at adaptive-fill-regexp)
22208 (concat comment-prefix (match-string 0))
22209 (concat comment-prefix " "))))))
22210 (save-excursion
22211 (fill-region-as-paragraph begin end justify))))))
22213 ;; Ignore every other element.
22214 (otherwise t)))))
22216 (defun org-fill-paragraph (&optional justify region)
22217 "Fill element at point, when applicable.
22219 This function only applies to comment blocks, comments, example
22220 blocks and paragraphs. Also, as a special case, re-align table
22221 when point is at one.
22223 For convenience, when point is at a plain list, an item or
22224 a footnote definition, try to fill the first paragraph within.
22226 If JUSTIFY is non-nil (interactively, with prefix argument),
22227 justify as well. If `sentence-end-double-space' is non-nil, then
22228 period followed by one space does not end a sentence, so don't
22229 break a line there. The variable `fill-column' controls the
22230 width for filling.
22232 The REGION argument is non-nil if called interactively; in that
22233 case, if Transient Mark mode is enabled and the mark is active,
22234 fill each of the elements in the active region, instead of just
22235 filling the current element."
22236 (interactive (progn
22237 (barf-if-buffer-read-only)
22238 (list (if current-prefix-arg 'full) t)))
22239 (cond
22240 ((and region transient-mark-mode mark-active
22241 (not (eq (region-beginning) (region-end))))
22242 (let ((origin (point-marker))
22243 (start (region-beginning)))
22244 (unwind-protect
22245 (progn
22246 (goto-char (region-end))
22247 (while (> (point) start)
22248 (org-backward-paragraph)
22249 (org-fill-element justify)))
22250 (goto-char origin)
22251 (set-marker origin nil))))
22252 (t (org-fill-element justify))))
22253 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22255 (defun org-auto-fill-function ()
22256 "Auto-fill function."
22257 ;; Check if auto-filling is meaningful.
22258 (let ((fc (current-fill-column)))
22259 (when (and fc (> (current-column) fc))
22260 (let* ((fill-prefix (org-adaptive-fill-function))
22261 ;; Enforce empty fill prefix, if required. Otherwise, it
22262 ;; will be computed again.
22263 (adaptive-fill-mode (not (equal fill-prefix ""))))
22264 (when fill-prefix (do-auto-fill))))))
22266 (defun org-comment-line-break-function (&optional soft)
22267 "Break line at point and indent, continuing comment if within one.
22268 The inserted newline is marked hard if variable
22269 `use-hard-newlines' is true, unless optional argument SOFT is
22270 non-nil."
22271 (if soft (insert-and-inherit ?\n) (newline 1))
22272 (save-excursion (forward-char -1) (delete-horizontal-space))
22273 (delete-horizontal-space)
22274 (indent-to-left-margin)
22275 (insert-before-markers-and-inherit fill-prefix))
22278 ;;; Fixed Width Areas
22280 (defun org-toggle-fixed-width ()
22281 "Toggle fixed-width markup.
22283 Add or remove fixed-width markup on current line, whenever it
22284 makes sense. Return an error otherwise.
22286 If a region is active and if it contains only fixed-width areas
22287 or blank lines, remove all fixed-width markup in it. If the
22288 region contains anything else, convert all non-fixed-width lines
22289 to fixed-width ones.
22291 Blank lines at the end of the region are ignored unless the
22292 region only contains such lines."
22293 (interactive)
22294 (if (not (org-region-active-p))
22295 ;; No region:
22297 ;; Remove fixed width marker only in a fixed-with element.
22299 ;; Add fixed width maker in paragraphs, in blank lines after
22300 ;; elements or at the beginning of a headline or an inlinetask,
22301 ;; and before any one-line elements (e.g., a clock).
22302 (progn
22303 (beginning-of-line)
22304 (let* ((element (org-element-at-point))
22305 (type (org-element-type element)))
22306 (cond
22307 ((and (eq type 'fixed-width)
22308 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22309 (replace-match
22310 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22311 ((and (memq type '(babel-call clock comment diary-sexp headline
22312 horizontal-rule keyword paragraph
22313 planning))
22314 (<= (org-element-property :post-affiliated element) (point)))
22315 (skip-chars-forward " \t")
22316 (insert ": "))
22317 ((and (looking-at-p "[ \t]*$")
22318 (or (eq type 'inlinetask)
22319 (save-excursion
22320 (skip-chars-forward " \r\t\n")
22321 (<= (org-element-property :end element) (point)))))
22322 (delete-region (point) (line-end-position))
22323 (org-indent-line)
22324 (insert ": "))
22325 (t (user-error "Cannot insert a fixed-width line here")))))
22326 ;; Region active.
22327 (let* ((begin (save-excursion
22328 (goto-char (region-beginning))
22329 (line-beginning-position)))
22330 (end (copy-marker
22331 (save-excursion
22332 (goto-char (region-end))
22333 (unless (eolp) (beginning-of-line))
22334 (if (save-excursion (re-search-backward "\\S-" begin t))
22335 (progn (skip-chars-backward " \r\t\n") (point))
22336 (point)))))
22337 (all-fixed-width-p
22338 (catch 'not-all-p
22339 (save-excursion
22340 (goto-char begin)
22341 (skip-chars-forward " \r\t\n")
22342 (when (eobp) (throw 'not-all-p nil))
22343 (while (< (point) end)
22344 (let ((element (org-element-at-point)))
22345 (if (eq (org-element-type element) 'fixed-width)
22346 (goto-char (org-element-property :end element))
22347 (throw 'not-all-p nil))))
22348 t))))
22349 (if all-fixed-width-p
22350 (save-excursion
22351 (goto-char begin)
22352 (while (< (point) end)
22353 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22354 (replace-match
22355 "" nil nil nil
22356 (if (= (line-end-position) (match-end 0)) 0 1)))
22357 (forward-line)))
22358 (let ((min-ind (point-max)))
22359 ;; Find minimum indentation across all lines.
22360 (save-excursion
22361 (goto-char begin)
22362 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22363 (setq min-ind 0)
22364 (catch 'zerop
22365 (while (< (point) end)
22366 (unless (looking-at-p "[ \t]*$")
22367 (let ((ind (org-get-indentation)))
22368 (setq min-ind (min min-ind ind))
22369 (when (zerop ind) (throw 'zerop t))))
22370 (forward-line)))))
22371 ;; Loop over all lines and add fixed-width markup everywhere
22372 ;; but in fixed-width lines.
22373 (save-excursion
22374 (goto-char begin)
22375 (while (< (point) end)
22376 (cond
22377 ((org-at-heading-p)
22378 (insert ": ")
22379 (forward-line)
22380 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22381 (insert ":")
22382 (forward-line)))
22383 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22384 (let* ((element (org-element-at-point))
22385 (element-end (org-element-property :end element)))
22386 (if (eq (org-element-type element) 'fixed-width)
22387 (progn (goto-char element-end)
22388 (skip-chars-backward " \r\t\n")
22389 (forward-line))
22390 (let ((limit (min end element-end)))
22391 (while (< (point) limit)
22392 (org-move-to-column min-ind t)
22393 (insert ": ")
22394 (forward-line))))))
22396 (org-move-to-column min-ind t)
22397 (insert ": ")
22398 (forward-line)))))))
22399 (set-marker end nil))))
22402 ;;; Comments
22404 ;; Org comments syntax is quite complex. It requires the entire line
22405 ;; to be just a comment. Also, even with the right syntax at the
22406 ;; beginning of line, some elements (e.g., verse-block or
22407 ;; example-block) don't accept comments. Usual Emacs comment commands
22408 ;; cannot cope with those requirements. Therefore, Org replaces them.
22410 ;; Org still relies on `comment-dwim', but cannot trust
22411 ;; `comment-only-p'. So, `comment-region-function' and
22412 ;; `uncomment-region-function' both point
22413 ;; to`org-comment-or-uncomment-region'. Eventually,
22414 ;; `org-insert-comment' takes care of insertion of comments at the
22415 ;; beginning of line.
22417 ;; `org-setup-comments-handling' install comments related variables
22418 ;; during `org-mode' initialization.
22420 (defun org-setup-comments-handling ()
22421 (interactive)
22422 (setq-local comment-use-syntax nil)
22423 (setq-local comment-start "# ")
22424 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22425 (setq-local comment-insert-comment-function 'org-insert-comment)
22426 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22427 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22429 (defun org-insert-comment ()
22430 "Insert an empty comment above current line.
22431 If the line is empty, insert comment at its beginning. When
22432 point is within a source block, comment according to the related
22433 major mode."
22434 (if (let ((element (org-element-at-point)))
22435 (and (eq (org-element-type element) 'src-block)
22436 (< (save-excursion
22437 (goto-char (org-element-property :post-affiliated element))
22438 (line-end-position))
22439 (point))
22440 (> (save-excursion
22441 (goto-char (org-element-property :end element))
22442 (skip-chars-backward " \r\t\n")
22443 (line-beginning-position))
22444 (point))))
22445 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22446 (beginning-of-line)
22447 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22448 (open-line 1))
22449 (org-indent-line)
22450 (insert "# ")))
22452 (defvar comment-empty-lines) ; From newcomment.el.
22453 (defun org-comment-or-uncomment-region (beg end &rest _)
22454 "Comment or uncomment each non-blank line in the region.
22455 Uncomment each non-blank line between BEG and END if it only
22456 contains commented lines. Otherwise, comment them. If region is
22457 strictly within a source block, use appropriate comment syntax."
22458 (if (let ((element (org-element-at-point)))
22459 (and (eq (org-element-type element) 'src-block)
22460 (< (save-excursion
22461 (goto-char (org-element-property :post-affiliated element))
22462 (line-end-position))
22463 beg)
22464 (>= (save-excursion
22465 (goto-char (org-element-property :end element))
22466 (skip-chars-backward " \r\t\n")
22467 (line-beginning-position))
22468 end)))
22469 ;; Translate region boundaries for the Org buffer to the source
22470 ;; buffer.
22471 (let ((offset (- end beg)))
22472 (save-excursion
22473 (goto-char beg)
22474 (org-babel-do-in-edit-buffer
22475 (comment-or-uncomment-region (point) (+ offset (point))))))
22476 (save-restriction
22477 ;; Restrict region
22478 (narrow-to-region (save-excursion (goto-char beg)
22479 (skip-chars-forward " \r\t\n" end)
22480 (line-beginning-position))
22481 (save-excursion (goto-char end)
22482 (skip-chars-backward " \r\t\n" beg)
22483 (line-end-position)))
22484 (let ((uncommentp
22485 ;; UNCOMMENTP is non-nil when every non blank line between
22486 ;; BEG and END is a comment.
22487 (save-excursion
22488 (goto-char (point-min))
22489 (while (and (not (eobp))
22490 (let ((element (org-element-at-point)))
22491 (and (eq (org-element-type element) 'comment)
22492 (goto-char (min (point-max)
22493 (org-element-property
22494 :end element)))))))
22495 (eobp))))
22496 (if uncommentp
22497 ;; Only blank lines and comments in region: uncomment it.
22498 (save-excursion
22499 (goto-char (point-min))
22500 (while (not (eobp))
22501 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22502 (replace-match "" nil nil nil 1))
22503 (forward-line)))
22504 ;; Comment each line in region.
22505 (let ((min-indent (point-max)))
22506 ;; First find the minimum indentation across all lines.
22507 (save-excursion
22508 (goto-char (point-min))
22509 (while (and (not (eobp)) (not (zerop min-indent)))
22510 (unless (looking-at "[ \t]*$")
22511 (setq min-indent (min min-indent (current-indentation))))
22512 (forward-line)))
22513 ;; Then loop over all lines.
22514 (save-excursion
22515 (goto-char (point-min))
22516 (while (not (eobp))
22517 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22518 ;; Don't get fooled by invisible text (e.g. link path)
22519 ;; when moving to column MIN-INDENT.
22520 (let ((buffer-invisibility-spec nil))
22521 (org-move-to-column min-indent t))
22522 (insert comment-start))
22523 (forward-line)))))))))
22525 (defun org-comment-dwim (_arg)
22526 "Call the comment command you mean.
22527 Call `org-toggle-comment' if on a heading, otherwise call
22528 `comment-dwim', within a source edit buffer if needed."
22529 (interactive "*P")
22530 (cond ((org-at-heading-p)
22531 (call-interactively #'org-toggle-comment))
22532 ((org-in-src-block-p)
22533 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22534 (t (call-interactively #'comment-dwim))))
22537 ;;; Timestamps API
22539 ;; This section contains tools to operate on timestamp objects, as
22540 ;; returned by, e.g. `org-element-context'.
22542 (defun org-timestamp--to-internal-time (timestamp &optional end)
22543 "Encode TIMESTAMP object into Emacs internal time.
22544 Use end of date range or time range when END is non-nil."
22545 (apply #'encode-time
22546 (cons 0
22547 (mapcar
22548 (lambda (prop) (or (org-element-property prop timestamp) 0))
22549 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22550 '(:minute-start :hour-start :day-start :month-start
22551 :year-start))))))
22553 (defun org-timestamp-has-time-p (timestamp)
22554 "Non-nil when TIMESTAMP has a time specified."
22555 (org-element-property :hour-start timestamp))
22557 (defun org-timestamp-format (timestamp format &optional end utc)
22558 "Format a TIMESTAMP object into a string.
22560 FORMAT is a format specifier to be passed to
22561 `format-time-string'.
22563 When optional argument END is non-nil, use end of date-range or
22564 time-range, if possible.
22566 When optional argument UTC is non-nil, time will be expressed as
22567 Universal Time."
22568 (format-time-string
22569 format (org-timestamp--to-internal-time timestamp end)
22570 (and utc t)))
22572 (defun org-timestamp-split-range (timestamp &optional end)
22573 "Extract a TIMESTAMP object from a date or time range.
22575 END, when non-nil, means extract the end of the range.
22576 Otherwise, extract its start.
22578 Return a new timestamp object."
22579 (let ((type (org-element-property :type timestamp)))
22580 (if (memq type '(active inactive diary)) timestamp
22581 (let ((split-ts (org-element-copy timestamp)))
22582 ;; Set new type.
22583 (org-element-put-property
22584 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22585 ;; Copy start properties over end properties if END is
22586 ;; non-nil. Otherwise, copy end properties over `start' ones.
22587 (let ((p-alist '((:minute-start . :minute-end)
22588 (:hour-start . :hour-end)
22589 (:day-start . :day-end)
22590 (:month-start . :month-end)
22591 (:year-start . :year-end))))
22592 (dolist (p-cell p-alist)
22593 (org-element-put-property
22594 split-ts
22595 (funcall (if end #'car #'cdr) p-cell)
22596 (org-element-property
22597 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22598 ;; Eventually refresh `:raw-value'.
22599 (org-element-put-property split-ts :raw-value nil)
22600 (org-element-put-property
22601 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22603 (defun org-timestamp-translate (timestamp &optional boundary)
22604 "Translate TIMESTAMP object to custom format.
22606 Format string is defined in `org-time-stamp-custom-formats',
22607 which see.
22609 When optional argument BOUNDARY is non-nil, it is either the
22610 symbol `start' or `end'. In this case, only translate the
22611 starting or ending part of TIMESTAMP if it is a date or time
22612 range. Otherwise, translate both parts.
22614 Return timestamp as-is if `org-display-custom-times' is nil or if
22615 it has a `diary' type."
22616 (let ((type (org-element-property :type timestamp)))
22617 (if (or (not org-display-custom-times) (eq type 'diary))
22618 (org-element-interpret-data timestamp)
22619 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22620 org-time-stamp-custom-formats)))
22621 (if (and (not boundary) (memq type '(active-range inactive-range)))
22622 (concat (org-timestamp-format timestamp fmt)
22623 "--"
22624 (org-timestamp-format timestamp fmt t))
22625 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22629 ;;; Other stuff.
22631 (defvar reftex-docstruct-symbol)
22632 (defvar org--rds)
22634 (defun org-reftex-citation ()
22635 "Use reftex-citation to insert a citation into the buffer.
22636 This looks for a line like
22638 #+BIBLIOGRAPHY: foo plain option:-d
22640 and derives from it that foo.bib is the bibliography file relevant
22641 for this document. It then installs the necessary environment for RefTeX
22642 to work in this buffer and calls `reftex-citation' to insert a citation
22643 into the buffer.
22645 Export of such citations to both LaTeX and HTML is handled by the contributed
22646 package ox-bibtex by Taru Karttunen."
22647 (interactive)
22648 (let ((reftex-docstruct-symbol 'org--rds)
22649 org--rds bib)
22650 (org-with-wide-buffer
22651 (let ((case-fold-search t)
22652 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22653 (if (not (save-excursion
22654 (or (re-search-forward re nil t)
22655 (re-search-backward re nil t))))
22656 (user-error "No bibliography defined in file")
22657 (setq bib (concat (match-string 1) ".bib")
22658 org--rds (list (list 'bib bib))))))
22659 (call-interactively 'reftex-citation)))
22661 ;;;; Functions extending outline functionality
22663 (defun org-beginning-of-line (&optional n)
22664 "Go to the beginning of the current visible line.
22666 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22667 tags on the first attempt, and only move to after the tags when
22668 the cursor is already beyond the end of the headline.
22670 With argument N not nil or 1, move forward N - 1 lines first."
22671 (interactive "^p")
22672 (let ((origin (point))
22673 (special (pcase org-special-ctrl-a/e
22674 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22675 deactivate-mark)
22676 ;; First move to a visible line.
22677 (if (bound-and-true-p visual-line-mode)
22678 (beginning-of-visual-line n)
22679 (move-beginning-of-line n)
22680 ;; `move-beginning-of-line' may leave point after invisible
22681 ;; characters if line starts with such of these (e.g., with
22682 ;; a link at column 0). Really move to the beginning of the
22683 ;; current visible line.
22684 (beginning-of-line))
22685 (cond
22686 ;; No special behavior. Point is already at the beginning of
22687 ;; a line, logical or visual.
22688 ((not special))
22689 ;; `beginning-of-visual-line' left point before logical beginning
22690 ;; of line: point is at the beginning of a visual line. Bail
22691 ;; out.
22692 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22693 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22694 ;; At a headline, special position is before the title, but
22695 ;; after any TODO keyword or priority cookie.
22696 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22697 (line-end-position)))
22698 (bol (point)))
22699 (if (eq special 'reversed)
22700 (when (and (= origin bol) (eq last-command this-command))
22701 (goto-char refpos))
22702 (when (or (> origin refpos) (= origin bol))
22703 (goto-char refpos)))))
22704 ((and (looking-at org-list-full-item-re)
22705 (memq (org-element-type (save-match-data (org-element-at-point)))
22706 '(item plain-list)))
22707 ;; Set special position at first white space character after
22708 ;; bullet, and check-box, if any.
22709 (let ((after-bullet
22710 (let ((box (match-end 3)))
22711 (cond ((not box) (match-end 1))
22712 ((eq (char-after box) ?\s) (1+ box))
22713 (t box)))))
22714 (if (eq special 'reversed)
22715 (when (and (= (point) origin) (eq last-command this-command))
22716 (goto-char after-bullet))
22717 (when (or (> origin after-bullet) (= (point) origin))
22718 (goto-char after-bullet)))))
22719 ;; No special context. Point is already at beginning of line.
22720 (t nil))))
22722 (defun org-end-of-line (&optional n)
22723 "Go to the end of the line, but before ellipsis, if any.
22725 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22726 tags on the first attempt, and only move to after the tags when
22727 the cursor is already beyond the end of the headline.
22729 With argument N not nil or 1, move forward N - 1 lines first."
22730 (interactive "^p")
22731 (let ((origin (point))
22732 (special (pcase org-special-ctrl-a/e
22733 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22734 deactivate-mark)
22735 ;; First move to a visible line.
22736 (if (bound-and-true-p visual-line-mode)
22737 (beginning-of-visual-line n)
22738 (move-beginning-of-line n))
22739 (cond
22740 ;; At a headline, with tags.
22741 ((and special
22742 (save-excursion
22743 (beginning-of-line)
22744 (let ((case-fold-search nil))
22745 (looking-at org-complex-heading-regexp)))
22746 (match-end 5))
22747 (let ((tags (save-excursion
22748 (goto-char (match-beginning 5))
22749 (skip-chars-backward " \t")
22750 (point)))
22751 (visual-end (and (bound-and-true-p visual-line-mode)
22752 (save-excursion
22753 (end-of-visual-line)
22754 (point)))))
22755 ;; If `end-of-visual-line' brings us before end of line or
22756 ;; even tags, i.e., the headline spans over multiple visual
22757 ;; lines, move there.
22758 (cond ((and visual-end
22759 (< visual-end tags)
22760 (<= origin visual-end))
22761 (goto-char visual-end))
22762 ((eq special 'reversed)
22763 (if (and (= origin (line-end-position))
22764 (eq this-command last-command))
22765 (goto-char tags)
22766 (end-of-line)))
22768 (if (or (< origin tags) (= origin (line-end-position)))
22769 (goto-char tags)
22770 (end-of-line))))))
22771 ((bound-and-true-p visual-line-mode)
22772 (let ((bol (line-beginning-position)))
22773 (end-of-visual-line)
22774 ;; If `end-of-visual-line' gets us past the ellipsis at the
22775 ;; end of a line, backtrack and use `end-of-line' instead.
22776 (when (/= bol (line-beginning-position))
22777 (goto-char bol)
22778 (end-of-line))))
22779 (t (end-of-line)))))
22781 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22782 (define-key org-mode-map "\C-e" 'org-end-of-line)
22784 (defun org-backward-sentence (&optional _arg)
22785 "Go to beginning of sentence, or beginning of table field.
22786 This will call `backward-sentence' or `org-table-beginning-of-field',
22787 depending on context."
22788 (interactive)
22789 (let* ((element (org-element-at-point))
22790 (contents-begin (org-element-property :contents-begin element))
22791 (table (org-element-lineage element '(table) t)))
22792 (if (and table
22793 (> (point) contents-begin)
22794 (<= (point) (org-element-property :contents-end table)))
22795 (call-interactively #'org-table-beginning-of-field)
22796 (save-restriction
22797 (when (and contents-begin
22798 (< (point-min) contents-begin)
22799 (> (point) contents-begin))
22800 (narrow-to-region contents-begin
22801 (org-element-property :contents-end element)))
22802 (call-interactively #'backward-sentence)))))
22804 (defun org-forward-sentence (&optional _arg)
22805 "Go to end of sentence, or end of table field.
22806 This will call `forward-sentence' or `org-table-end-of-field',
22807 depending on context."
22808 (interactive)
22809 (if (and (org-at-heading-p)
22810 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22811 (save-restriction
22812 (narrow-to-region (line-beginning-position) (line-end-position))
22813 (call-interactively #'forward-sentence))
22814 (let* ((element (org-element-at-point))
22815 (contents-end (org-element-property :contents-end element))
22816 (table (org-element-lineage element '(table) t)))
22817 (if (and table
22818 (>= (point) (org-element-property :contents-begin table))
22819 (< (point) contents-end))
22820 (call-interactively #'org-table-end-of-field)
22821 (save-restriction
22822 (when (and contents-end
22823 (> (point-max) contents-end)
22824 ;; Skip blank lines between elements.
22825 (< (org-element-property :end element)
22826 (save-excursion (goto-char contents-end)
22827 (skip-chars-forward " \r\t\n"))))
22828 (narrow-to-region (org-element-property :contents-begin element)
22829 contents-end))
22830 ;; End of heading is considered as the end of a sentence.
22831 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22832 (call-interactively #'forward-sentence)))))))
22834 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22835 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22837 (defun org-kill-line (&optional _arg)
22838 "Kill line, to tags or end of line."
22839 (interactive)
22840 (cond
22841 ((or (not org-special-ctrl-k)
22842 (bolp)
22843 (not (org-at-heading-p)))
22844 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22845 org-ctrl-k-protect-subtree
22846 (or (eq org-ctrl-k-protect-subtree 'error)
22847 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22848 (user-error "C-k aborted as it would kill a hidden subtree"))
22849 (call-interactively
22850 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22851 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22852 (kill-region (point) (match-beginning 1))
22853 (org-set-tags nil t))
22854 (t (kill-region (point) (point-at-eol)))))
22856 (define-key org-mode-map "\C-k" 'org-kill-line)
22858 (defun org-yank (&optional arg)
22859 "Yank. If the kill is a subtree, treat it specially.
22860 This command will look at the current kill and check if is a single
22861 subtree, or a series of subtrees[1]. If it passes the test, and if the
22862 cursor is at the beginning of a line or after the stars of a currently
22863 empty headline, then the yank is handled specially. How exactly depends
22864 on the value of the following variables.
22866 `org-yank-folded-subtrees'
22867 By default, this variable is non-nil, which results in
22868 subtree(s) being folded after insertion, except if doing so
22869 would swallow text after the yanked text.
22871 `org-yank-adjusted-subtrees'
22872 When non-nil (the default value is nil), the subtree will be
22873 promoted or demoted in order to fit into the local outline tree
22874 structure, which means that the level will be adjusted so that it
22875 becomes the smaller one of the two *visible* surrounding headings.
22877 Any prefix to this command will cause `yank' to be called directly with
22878 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22879 will just
22880 plainly yank the text as it is.
22882 \[1] The test checks if the first non-white line is a heading
22883 and if there are no other headings with fewer stars."
22884 (interactive "P")
22885 (org-yank-generic 'yank arg))
22887 (defun org-yank-generic (command arg)
22888 "Perform some yank-like command.
22890 This function implements the behavior described in the `org-yank'
22891 documentation. However, it has been generalized to work for any
22892 interactive command with similar behavior."
22894 ;; pretend to be command COMMAND
22895 (setq this-command command)
22897 (if arg
22898 (call-interactively command)
22900 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22901 (and (org-kill-is-subtree-p)
22902 (or (bolp)
22903 (and (looking-at "[ \t]*$")
22904 (string-match
22905 "\\`\\*+\\'"
22906 (buffer-substring (point-at-bol) (point)))))))
22907 swallowp)
22908 (cond
22909 ((and subtreep org-yank-folded-subtrees)
22910 (let ((beg (point))
22911 end)
22912 (if (and subtreep org-yank-adjusted-subtrees)
22913 (org-paste-subtree nil nil 'for-yank)
22914 (call-interactively command))
22916 (setq end (point))
22917 (goto-char beg)
22918 (when (and (bolp) subtreep
22919 (not (setq swallowp
22920 (org-yank-folding-would-swallow-text beg end))))
22921 (org-with-limited-levels
22922 (or (looking-at org-outline-regexp)
22923 (re-search-forward org-outline-regexp-bol end t))
22924 (while (and (< (point) end) (looking-at org-outline-regexp))
22925 (outline-hide-subtree)
22926 (org-cycle-show-empty-lines 'folded)
22927 (condition-case nil
22928 (outline-forward-same-level 1)
22929 (error (goto-char end))))))
22930 (when swallowp
22931 (message
22932 "Inserted text not folded because that would swallow text"))
22934 (goto-char end)
22935 (skip-chars-forward " \t\n\r")
22936 (beginning-of-line 1)
22937 (push-mark beg 'nomsg)))
22938 ((and subtreep org-yank-adjusted-subtrees)
22939 (let ((beg (point-at-bol)))
22940 (org-paste-subtree nil nil 'for-yank)
22941 (push-mark beg 'nomsg)))
22943 (call-interactively command))))))
22945 (defun org-yank-folding-would-swallow-text (beg end)
22946 "Would hide-subtree at BEG swallow any text after END?"
22947 (let (level)
22948 (org-with-limited-levels
22949 (save-excursion
22950 (goto-char beg)
22951 (when (or (looking-at org-outline-regexp)
22952 (re-search-forward org-outline-regexp-bol end t))
22953 (setq level (org-outline-level)))
22954 (goto-char end)
22955 (skip-chars-forward " \t\r\n\v\f")
22956 (not (or (eobp)
22957 (and (bolp) (looking-at-p org-outline-regexp)
22958 (<= (org-outline-level) level))))))))
22960 (define-key org-mode-map "\C-y" 'org-yank)
22962 (defun org-back-to-heading (&optional invisible-ok)
22963 "Call `outline-back-to-heading', but provide a better error message."
22964 (condition-case nil
22965 (outline-back-to-heading invisible-ok)
22966 (error (error "Before first headline at position %d in buffer %s"
22967 (point) (current-buffer)))))
22969 (defun org-before-first-heading-p ()
22970 "Before first heading?"
22971 (save-excursion
22972 (end-of-line)
22973 (null (re-search-backward org-outline-regexp-bol nil t))))
22975 (defun org-at-heading-p (&optional ignored)
22976 (outline-on-heading-p t))
22978 (defun org-in-commented-heading-p (&optional no-inheritance)
22979 "Non-nil if point is under a commented heading.
22980 This function also checks ancestors of the current headline,
22981 unless optional argument NO-INHERITANCE is non-nil."
22982 (cond
22983 ((org-before-first-heading-p) nil)
22984 ((let ((headline (nth 4 (org-heading-components))))
22985 (and headline
22986 (let ((case-fold-search nil))
22987 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22988 headline)))))
22989 (no-inheritance nil)
22991 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22993 (defun org-at-comment-p nil
22994 "Is cursor in a commented line?"
22995 (save-excursion
22996 (save-match-data
22997 (beginning-of-line)
22998 (looking-at "^[ \t]*# "))))
23000 (defun org-at-drawer-p nil
23001 "Is cursor at a drawer keyword?"
23002 (save-excursion
23003 (move-beginning-of-line 1)
23004 (looking-at org-drawer-regexp)))
23006 (defun org-at-block-p nil
23007 "Is cursor at a block keyword?"
23008 (save-excursion
23009 (move-beginning-of-line 1)
23010 (looking-at org-block-regexp)))
23012 (defun org-point-at-end-of-empty-headline ()
23013 "If point is at the end of an empty headline, return t, else nil.
23014 If the heading only contains a TODO keyword, it is still still considered
23015 empty."
23016 (let ((case-fold-search nil))
23017 (and (looking-at "[ \t]*$")
23018 org-todo-line-regexp
23019 (save-excursion
23020 (beginning-of-line)
23021 (looking-at org-todo-line-regexp)
23022 (string= (match-string 3) "")))))
23024 (defun org-at-heading-or-item-p ()
23025 (or (org-at-heading-p) (org-at-item-p)))
23027 (defun org-at-target-p ()
23028 (or (org-in-regexp org-radio-target-regexp)
23029 (org-in-regexp org-target-regexp)))
23030 ;; Compatibility alias with Org versions < 7.8.03
23031 (defalias 'org-on-target-p 'org-at-target-p)
23033 (defun org-up-heading-all (arg)
23034 "Move to the heading line of which the present line is a subheading.
23035 This function considers both visible and invisible heading lines.
23036 With argument, move up ARG levels."
23037 (outline-up-heading arg t))
23039 (defun org-up-heading-safe ()
23040 "Move to the heading line of which the present line is a subheading.
23041 This version will not throw an error. It will return the level of the
23042 headline found, or nil if no higher level is found.
23044 Also, this function will be a lot faster than `outline-up-heading',
23045 because it relies on stars being the outline starters. This can really
23046 make a significant difference in outlines with very many siblings."
23047 (when (ignore-errors (org-back-to-heading t))
23048 (let ((level-up (1- (funcall outline-level))))
23049 (and (> level-up 0)
23050 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23051 (funcall outline-level)))))
23053 (defun org-first-sibling-p ()
23054 "Is this heading the first child of its parents?"
23055 (interactive)
23056 (let ((re org-outline-regexp-bol)
23057 level l)
23058 (unless (org-at-heading-p t)
23059 (user-error "Not at a heading"))
23060 (setq level (funcall outline-level))
23061 (save-excursion
23062 (if (not (re-search-backward re nil t))
23064 (setq l (funcall outline-level))
23065 (< l level)))))
23067 (defun org-goto-sibling (&optional previous)
23068 "Goto the next sibling, even if it is invisible.
23069 When PREVIOUS is set, go to the previous sibling instead. Returns t
23070 when a sibling was found. When none is found, return nil and don't
23071 move point."
23072 (let ((fun (if previous 're-search-backward 're-search-forward))
23073 (pos (point))
23074 (re org-outline-regexp-bol)
23075 level l)
23076 (when (ignore-errors (org-back-to-heading t))
23077 (setq level (funcall outline-level))
23078 (catch 'exit
23079 (or previous (forward-char 1))
23080 (while (funcall fun re nil t)
23081 (setq l (funcall outline-level))
23082 (when (< l level) (goto-char pos) (throw 'exit nil))
23083 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23084 (goto-char pos)
23085 nil))))
23087 (defun org-show-siblings ()
23088 "Show all siblings of the current headline."
23089 (save-excursion
23090 (while (org-goto-sibling) (org-flag-heading nil)))
23091 (save-excursion
23092 (while (org-goto-sibling 'previous)
23093 (org-flag-heading nil))))
23095 (defun org-goto-first-child ()
23096 "Goto the first child, even if it is invisible.
23097 Return t when a child was found. Otherwise don't move point and
23098 return nil."
23099 (let (level (pos (point)) (re org-outline-regexp-bol))
23100 (when (ignore-errors (org-back-to-heading t))
23101 (setq level (outline-level))
23102 (forward-char 1)
23103 (if (and (re-search-forward re nil t) (> (outline-level) level))
23104 (progn (goto-char (match-beginning 0)) t)
23105 (goto-char pos) nil))))
23107 (defun org-show-hidden-entry ()
23108 "Show an entry where even the heading is hidden."
23109 (save-excursion
23110 (org-show-entry)))
23112 (defun org-flag-heading (flag &optional entry)
23113 "Flag the current heading. FLAG non-nil means make invisible.
23114 When ENTRY is non-nil, show the entire entry."
23115 (save-excursion
23116 (org-back-to-heading t)
23117 ;; Check if we should show the entire entry
23118 (if entry
23119 (progn
23120 (org-show-entry)
23121 (save-excursion
23122 (and (outline-next-heading)
23123 (org-flag-heading nil))))
23124 (outline-flag-region (max (point-min) (1- (point)))
23125 (save-excursion (outline-end-of-heading) (point))
23126 flag))))
23128 (defun org-get-next-sibling ()
23129 "Move to next heading of the same level, and return point.
23130 If there is no such heading, return nil.
23131 This is like outline-next-sibling, but invisible headings are ok."
23132 (let ((level (funcall outline-level)))
23133 (outline-next-heading)
23134 (while (and (not (eobp)) (> (funcall outline-level) level))
23135 (outline-next-heading))
23136 (unless (or (eobp) (< (funcall outline-level) level))
23137 (point))))
23139 (defun org-get-last-sibling ()
23140 "Move to previous heading of the same level, and return point.
23141 If there is no such heading, return nil."
23142 (let ((opoint (point))
23143 (level (funcall outline-level)))
23144 (outline-previous-heading)
23145 (when (and (/= (point) opoint) (outline-on-heading-p t))
23146 (while (and (> (funcall outline-level) level)
23147 (not (bobp)))
23148 (outline-previous-heading))
23149 (unless (< (funcall outline-level) level)
23150 (point)))))
23152 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23153 "Goto to the end of a subtree."
23154 ;; This contains an exact copy of the original function, but it uses
23155 ;; `org-back-to-heading', to make it work also in invisible
23156 ;; trees. And is uses an invisible-ok argument.
23157 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23158 ;; Furthermore, when used inside Org, finding the end of a large subtree
23159 ;; with many children and grandchildren etc, this can be much faster
23160 ;; than the outline version.
23161 (org-back-to-heading invisible-ok)
23162 (let ((first t)
23163 (level (funcall outline-level)))
23164 (if (and (derived-mode-p 'org-mode) (< level 1000))
23165 ;; A true heading (not a plain list item), in Org
23166 ;; This means we can easily find the end by looking
23167 ;; only for the right number of stars. Using a regexp to do
23168 ;; this is so much faster than using a Lisp loop.
23169 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23170 (forward-char 1)
23171 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23172 ;; something else, do it the slow way
23173 (while (and (not (eobp))
23174 (or first (> (funcall outline-level) level)))
23175 (setq first nil)
23176 (outline-next-heading)))
23177 (unless to-heading
23178 (when (memq (preceding-char) '(?\n ?\^M))
23179 ;; Go to end of line before heading
23180 (forward-char -1)
23181 (when (memq (preceding-char) '(?\n ?\^M))
23182 ;; leave blank line before heading
23183 (forward-char -1)))))
23184 (point))
23186 (defun org-end-of-meta-data (&optional full)
23187 "Skip planning line and properties drawer in current entry.
23188 When optional argument FULL is non-nil, also skip empty lines,
23189 clocking lines and regular drawers at the beginning of the
23190 entry."
23191 (org-back-to-heading t)
23192 (forward-line)
23193 (when (looking-at-p org-planning-line-re) (forward-line))
23194 (when (looking-at org-property-drawer-re)
23195 (goto-char (match-end 0))
23196 (forward-line))
23197 (when (and full (not (org-at-heading-p)))
23198 (catch 'exit
23199 (let ((end (save-excursion (outline-next-heading) (point)))
23200 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23201 (while (not (eobp))
23202 (cond ((looking-at-p org-drawer-regexp)
23203 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23204 (forward-line)
23205 (throw 'exit t)))
23206 ((looking-at-p re) (forward-line))
23207 (t (throw 'exit t))))))))
23209 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23210 "Move forward to the ARG'th subheading at same level as this one.
23211 Stop at the first and last subheadings of a superior heading.
23212 Normally this only looks at visible headings, but when INVISIBLE-OK is
23213 non-nil it will also look at invisible ones."
23214 (interactive "p")
23215 (let ((backward? (and arg (< arg 0))))
23216 (if (org-before-first-heading-p)
23217 (if backward? (goto-char (point-min)) (outline-next-heading))
23218 (org-back-to-heading invisible-ok)
23219 (unless backward? (end-of-line)) ;do not match current headline
23220 (let ((level (- (match-end 0) (match-beginning 0) 1))
23221 (f (if backward? #'re-search-backward #'re-search-forward))
23222 (count (if arg (abs arg) 1))
23223 (result (point)))
23224 (while (and (> count 0)
23225 (funcall f org-outline-regexp-bol nil 'move))
23226 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23227 (cond ((< l level) (setq count 0))
23228 ((and (= l level)
23229 (or invisible-ok
23230 (not (org-invisible-p
23231 (line-beginning-position)))))
23232 (cl-decf count)
23233 (when (= l level) (setq result (point)))))))
23234 (goto-char result))
23235 (beginning-of-line))))
23237 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23238 "Move backward to the ARG'th subheading at same level as this one.
23239 Stop at the first and last subheadings of a superior heading."
23240 (interactive "p")
23241 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23243 (defun org-next-visible-heading (arg)
23244 "Move to the next visible heading.
23246 This function wraps `outline-next-visible-heading' with
23247 `org-with-limited-levels' in order to skip over inline tasks and
23248 respect customization of `org-odd-levels-only'."
23249 (interactive "p")
23250 (org-with-limited-levels
23251 (outline-next-visible-heading arg)))
23253 (defun org-previous-visible-heading (arg)
23254 "Move to the previous visible heading.
23256 This function wraps `outline-previous-visible-heading' with
23257 `org-with-limited-levels' in order to skip over inline tasks and
23258 respect customization of `org-odd-levels-only'."
23259 (interactive "p")
23260 (org-with-limited-levels
23261 (outline-previous-visible-heading arg)))
23263 (defun org-next-block (arg &optional backward block-regexp)
23264 "Jump to the next block.
23266 With a prefix argument ARG, jump forward ARG many blocks.
23268 When BACKWARD is non-nil, jump to the previous block.
23270 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23271 Match data is set according to this regexp when the function
23272 returns.
23274 Return point at beginning of the opening line of found block.
23275 Throw an error if no block is found."
23276 (interactive "p")
23277 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23278 (case-fold-search t)
23279 (search-fn (if backward #'re-search-backward #'re-search-forward))
23280 (count (or arg 1))
23281 (origin (point))
23282 last-element)
23283 (if backward (beginning-of-line) (end-of-line))
23284 (while (and (> count 0) (funcall search-fn re nil t))
23285 (let ((element (save-excursion
23286 (goto-char (match-beginning 0))
23287 (save-match-data (org-element-at-point)))))
23288 (when (and (memq (org-element-type element)
23289 '(center-block comment-block dynamic-block
23290 example-block export-block quote-block
23291 special-block src-block verse-block))
23292 (<= (match-beginning 0)
23293 (org-element-property :post-affiliated element)))
23294 (setq last-element element)
23295 (cl-decf count))))
23296 (if (= count 0)
23297 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23298 (save-match-data (org-show-context)))
23299 (goto-char origin)
23300 (user-error "No %s code blocks" (if backward "previous" "further")))))
23302 (defun org-previous-block (arg &optional block-regexp)
23303 "Jump to the previous block.
23304 With a prefix argument ARG, jump backward ARG many source blocks.
23305 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23306 (interactive "p")
23307 (org-next-block arg t block-regexp))
23309 (defun org-forward-paragraph ()
23310 "Move forward to beginning of next paragraph or equivalent.
23312 The function moves point to the beginning of the next visible
23313 structural element, which can be a paragraph, a table, a list
23314 item, etc. It also provides some special moves for convenience:
23316 - On an affiliated keyword, jump to the beginning of the
23317 relative element.
23318 - On an item or a footnote definition, move to the second
23319 element inside, if any.
23320 - On a table or a property drawer, jump after it.
23321 - On a verse or source block, stop after blank lines."
23322 (interactive)
23323 (unless (eobp)
23324 (let* ((deactivate-mark nil)
23325 (element (org-element-at-point))
23326 (type (org-element-type element))
23327 (post-affiliated (org-element-property :post-affiliated element))
23328 (contents-begin (org-element-property :contents-begin element))
23329 (contents-end (org-element-property :contents-end element))
23330 (end (let ((end (org-element-property :end element)) (parent element))
23331 (while (and (setq parent (org-element-property :parent parent))
23332 (= (org-element-property :contents-end parent) end))
23333 (setq end (org-element-property :end parent)))
23334 end)))
23335 (cond ((not element)
23336 (skip-chars-forward " \r\t\n")
23337 (or (eobp) (beginning-of-line)))
23338 ;; On affiliated keywords, move to element's beginning.
23339 ((< (point) post-affiliated)
23340 (goto-char post-affiliated))
23341 ;; At a table row, move to the end of the table. Similarly,
23342 ;; at a node property, move to the end of the property
23343 ;; drawer.
23344 ((memq type '(node-property table-row))
23345 (goto-char (org-element-property
23346 :end (org-element-property :parent element))))
23347 ((memq type '(property-drawer table)) (goto-char end))
23348 ;; Consider blank lines as separators in verse and source
23349 ;; blocks to ease editing.
23350 ((memq type '(src-block verse-block))
23351 (when (eq type 'src-block)
23352 (setq contents-end
23353 (save-excursion (goto-char end)
23354 (skip-chars-backward " \r\t\n")
23355 (line-beginning-position))))
23356 (beginning-of-line)
23357 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23358 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23359 (goto-char end)
23360 (skip-chars-forward " \r\t\n")
23361 (if (= (point) contents-end) (goto-char end)
23362 (beginning-of-line))))
23363 ;; With no contents, just skip element.
23364 ((not contents-begin) (goto-char end))
23365 ;; If contents are invisible, skip the element altogether.
23366 ((org-invisible-p (line-end-position))
23367 (cl-case type
23368 (headline
23369 (org-with-limited-levels (outline-next-visible-heading 1)))
23370 ;; At a plain list, make sure we move to the next item
23371 ;; instead of skipping the whole list.
23372 (plain-list (forward-char)
23373 (org-forward-paragraph))
23374 (otherwise (goto-char end))))
23375 ((>= (point) contents-end) (goto-char end))
23376 ((>= (point) contents-begin)
23377 ;; This can only happen on paragraphs and plain lists.
23378 (cl-case type
23379 (paragraph (goto-char end))
23380 ;; At a plain list, try to move to second element in
23381 ;; first item, if possible.
23382 (plain-list (end-of-line)
23383 (org-forward-paragraph))))
23384 ;; When contents start on the middle of a line (e.g. in
23385 ;; items and footnote definitions), try to reach first
23386 ;; element starting after current line.
23387 ((> (line-end-position) contents-begin)
23388 (end-of-line)
23389 (org-forward-paragraph))
23390 (t (goto-char contents-begin))))))
23392 (defun org-backward-paragraph ()
23393 "Move backward to start of previous paragraph or equivalent.
23395 The function moves point to the beginning of the current
23396 structural element, which can be a paragraph, a table, a list
23397 item, etc., or to the beginning of the previous visible one if
23398 point is already there. It also provides some special moves for
23399 convenience:
23401 - On an affiliated keyword, jump to the first one.
23402 - On a table or a property drawer, move to its beginning.
23403 - On comment, example, export, src and verse blocks, stop
23404 before blank lines."
23405 (interactive)
23406 (unless (bobp)
23407 (let* ((deactivate-mark nil)
23408 (element (org-element-at-point))
23409 (type (org-element-type element))
23410 (contents-end (org-element-property :contents-end element))
23411 (post-affiliated (org-element-property :post-affiliated element))
23412 (begin (org-element-property :begin element))
23413 (special? ;blocks handled specially
23414 (memq type '(comment-block example-block export-block src-block
23415 verse-block)))
23416 (contents-begin
23417 (if special?
23418 ;; These types have no proper contents. Fake line
23419 ;; below the block opening line as contents beginning.
23420 (save-excursion (goto-char begin) (line-beginning-position 2))
23421 (org-element-property :contents-begin element))))
23422 (cond
23423 ((not element) (goto-char (point-min)))
23424 ((= (point) begin)
23425 (backward-char)
23426 (org-backward-paragraph))
23427 ((<= (point) post-affiliated) (goto-char begin))
23428 ;; Special behavior: on a table or a property drawer, move to
23429 ;; its beginning.
23430 ((memq type '(node-property table-row))
23431 (goto-char (org-element-property
23432 :post-affiliated (org-element-property :parent element))))
23433 (special?
23434 (if (<= (point) contents-begin) (goto-char post-affiliated)
23435 ;; Inside a verse block, see blank lines as paragraph
23436 ;; separators.
23437 (let ((origin (point)))
23438 (skip-chars-backward " \r\t\n" contents-begin)
23439 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23440 (skip-chars-forward " \r\t\n" origin)
23441 (if (= (point) origin) (goto-char contents-begin)
23442 (beginning-of-line))))))
23443 ((eq type 'paragraph) (goto-char contents-begin)
23444 ;; When at first paragraph in an item or a footnote definition,
23445 ;; move directly to beginning of line.
23446 (let ((parent-contents
23447 (org-element-property
23448 :contents-begin (org-element-property :parent element))))
23449 (when (and parent-contents (= parent-contents contents-begin))
23450 (beginning-of-line))))
23451 ;; At the end of a greater element, move to the beginning of
23452 ;; the last element within.
23453 ((and contents-end (>= (point) contents-end))
23454 (goto-char (1- contents-end))
23455 (org-backward-paragraph))
23456 (t (goto-char (or post-affiliated begin))))
23457 ;; Ensure we never leave point invisible.
23458 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23460 (defun org-forward-element ()
23461 "Move forward by one element.
23462 Move to the next element at the same level, when possible."
23463 (interactive)
23464 (cond ((eobp) (user-error "Cannot move further down"))
23465 ((org-with-limited-levels (org-at-heading-p))
23466 (let ((origin (point)))
23467 (goto-char (org-end-of-subtree nil t))
23468 (unless (org-with-limited-levels (org-at-heading-p))
23469 (goto-char origin)
23470 (user-error "Cannot move further down"))))
23472 (let* ((elem (org-element-at-point))
23473 (end (org-element-property :end elem))
23474 (parent (org-element-property :parent elem)))
23475 (cond ((and parent (= (org-element-property :contents-end parent) end))
23476 (goto-char (org-element-property :end parent)))
23477 ((integer-or-marker-p end) (goto-char end))
23478 (t (message "No element at point")))))))
23480 (defun org-backward-element ()
23481 "Move backward by one element.
23482 Move to the previous element at the same level, when possible."
23483 (interactive)
23484 (cond ((bobp) (user-error "Cannot move further up"))
23485 ((org-with-limited-levels (org-at-heading-p))
23486 ;; At a headline, move to the previous one, if any, or stay
23487 ;; here.
23488 (let ((origin (point)))
23489 (org-with-limited-levels (org-backward-heading-same-level 1))
23490 ;; When current headline has no sibling above, move to its
23491 ;; parent.
23492 (when (= (point) origin)
23493 (or (org-with-limited-levels (org-up-heading-safe))
23494 (progn (goto-char origin)
23495 (user-error "Cannot move further up"))))))
23497 (let* ((elem (org-element-at-point))
23498 (beg (org-element-property :begin elem)))
23499 (cond
23500 ;; Move to beginning of current element if point isn't
23501 ;; there already.
23502 ((null beg) (message "No element at point"))
23503 ((/= (point) beg) (goto-char beg))
23504 (t (goto-char beg)
23505 (skip-chars-backward " \r\t\n")
23506 (unless (bobp)
23507 (let ((prev (org-element-at-point)))
23508 (goto-char (org-element-property :begin prev))
23509 (while (and (setq prev (org-element-property :parent prev))
23510 (<= (org-element-property :end prev) beg))
23511 (goto-char (org-element-property :begin prev)))))))))))
23513 (defun org-up-element ()
23514 "Move to upper element."
23515 (interactive)
23516 (if (org-with-limited-levels (org-at-heading-p))
23517 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23518 (let* ((elem (org-element-at-point))
23519 (parent (org-element-property :parent elem)))
23520 (if parent (goto-char (org-element-property :begin parent))
23521 (if (org-with-limited-levels (org-before-first-heading-p))
23522 (user-error "No surrounding element")
23523 (org-with-limited-levels (org-back-to-heading)))))))
23525 (defun org-down-element ()
23526 "Move to inner element."
23527 (interactive)
23528 (let ((element (org-element-at-point)))
23529 (cond
23530 ((memq (org-element-type element) '(plain-list table))
23531 (goto-char (org-element-property :contents-begin element))
23532 (forward-char))
23533 ((memq (org-element-type element) org-element-greater-elements)
23534 ;; If contents are hidden, first disclose them.
23535 (when (org-invisible-p (line-end-position)) (org-cycle))
23536 (goto-char (or (org-element-property :contents-begin element)
23537 (user-error "No content for this element"))))
23538 (t (user-error "No inner element")))))
23540 (defun org-drag-element-backward ()
23541 "Move backward element at point."
23542 (interactive)
23543 (let ((elem (or (org-element-at-point)
23544 (user-error "No element at point"))))
23545 (if (eq (org-element-type elem) 'headline)
23546 ;; Preserve point when moving a whole tree, even if point was
23547 ;; on blank lines below the headline.
23548 (let ((offset (skip-chars-backward " \t\n")))
23549 (unwind-protect (org-move-subtree-up)
23550 (forward-char (- offset))))
23551 (let ((prev-elem
23552 (save-excursion
23553 (goto-char (org-element-property :begin elem))
23554 (skip-chars-backward " \r\t\n")
23555 (unless (bobp)
23556 (let* ((beg (org-element-property :begin elem))
23557 (prev (org-element-at-point))
23558 (up prev))
23559 (while (and (setq up (org-element-property :parent up))
23560 (<= (org-element-property :end up) beg))
23561 (setq prev up))
23562 prev)))))
23563 ;; Error out if no previous element or previous element is
23564 ;; a parent of the current one.
23565 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23566 (user-error "Cannot drag element backward")
23567 (let ((pos (point)))
23568 (org-element-swap-A-B prev-elem elem)
23569 (goto-char (+ (org-element-property :begin prev-elem)
23570 (- pos (org-element-property :begin elem))))))))))
23572 (defun org-drag-element-forward ()
23573 "Move forward element at point."
23574 (interactive)
23575 (let* ((pos (point))
23576 (elem (or (org-element-at-point)
23577 (user-error "No element at point"))))
23578 (when (= (point-max) (org-element-property :end elem))
23579 (user-error "Cannot drag element forward"))
23580 (goto-char (org-element-property :end elem))
23581 (let ((next-elem (org-element-at-point)))
23582 (when (or (org-element-nested-p elem next-elem)
23583 (and (eq (org-element-type next-elem) 'headline)
23584 (not (eq (org-element-type elem) 'headline))))
23585 (goto-char pos)
23586 (user-error "Cannot drag element forward"))
23587 ;; Compute new position of point: it's shifted by NEXT-ELEM
23588 ;; body's length (without final blanks) and by the length of
23589 ;; blanks between ELEM and NEXT-ELEM.
23590 (let ((size-next (- (save-excursion
23591 (goto-char (org-element-property :end next-elem))
23592 (skip-chars-backward " \r\t\n")
23593 (forward-line)
23594 ;; Small correction if buffer doesn't end
23595 ;; with a newline character.
23596 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23597 (org-element-property :begin next-elem)))
23598 (size-blank (- (org-element-property :end elem)
23599 (save-excursion
23600 (goto-char (org-element-property :end elem))
23601 (skip-chars-backward " \r\t\n")
23602 (forward-line)
23603 (point)))))
23604 (org-element-swap-A-B elem next-elem)
23605 (goto-char (+ pos size-next size-blank))))))
23607 (defun org-drag-line-forward (arg)
23608 "Drag the line at point ARG lines forward."
23609 (interactive "p")
23610 (dotimes (_ (abs arg))
23611 (let ((c (current-column)))
23612 (if (< 0 arg)
23613 (progn
23614 (beginning-of-line 2)
23615 (transpose-lines 1)
23616 (beginning-of-line 0))
23617 (transpose-lines 1)
23618 (beginning-of-line -1))
23619 (org-move-to-column c))))
23621 (defun org-drag-line-backward (arg)
23622 "Drag the line at point ARG lines backward."
23623 (interactive "p")
23624 (org-drag-line-forward (- arg)))
23626 (defun org-mark-element ()
23627 "Put point at beginning of this element, mark at end.
23629 Interactively, if this command is repeated or (in Transient Mark
23630 mode) if the mark is active, it marks the next element after the
23631 ones already marked."
23632 (interactive)
23633 (let (deactivate-mark)
23634 (if (and (called-interactively-p 'any)
23635 (or (and (eq last-command this-command) (mark t))
23636 (and transient-mark-mode mark-active)))
23637 (set-mark
23638 (save-excursion
23639 (goto-char (mark))
23640 (goto-char (org-element-property :end (org-element-at-point)))))
23641 (let ((element (org-element-at-point)))
23642 (end-of-line)
23643 (push-mark (org-element-property :end element) t t)
23644 (goto-char (org-element-property :begin element))))))
23646 (defun org-narrow-to-element ()
23647 "Narrow buffer to current element."
23648 (interactive)
23649 (let ((elem (org-element-at-point)))
23650 (cond
23651 ((eq (car elem) 'headline)
23652 (narrow-to-region
23653 (org-element-property :begin elem)
23654 (org-element-property :end elem)))
23655 ((memq (car elem) org-element-greater-elements)
23656 (narrow-to-region
23657 (org-element-property :contents-begin elem)
23658 (org-element-property :contents-end elem)))
23660 (narrow-to-region
23661 (org-element-property :begin elem)
23662 (org-element-property :end elem))))))
23664 (defun org-transpose-element ()
23665 "Transpose current and previous elements, keeping blank lines between.
23666 Point is moved after both elements."
23667 (interactive)
23668 (org-skip-whitespace)
23669 (let ((end (org-element-property :end (org-element-at-point))))
23670 (org-drag-element-backward)
23671 (goto-char end)))
23673 (defun org-unindent-buffer ()
23674 "Un-indent the visible part of the buffer.
23675 Relative indentation (between items, inside blocks, etc.) isn't
23676 modified."
23677 (interactive)
23678 (unless (eq major-mode 'org-mode)
23679 (user-error "Cannot un-indent a buffer not in Org mode"))
23680 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23681 (unindent-tree
23682 (lambda (contents)
23683 (dolist (element (reverse contents))
23684 (if (memq (org-element-type element) '(headline section))
23685 (funcall unindent-tree (org-element-contents element))
23686 (save-excursion
23687 (save-restriction
23688 (narrow-to-region
23689 (org-element-property :begin element)
23690 (org-element-property :end element))
23691 (org-do-remove-indentation))))))))
23692 (funcall unindent-tree (org-element-contents parse-tree))))
23694 (defun org-show-children (&optional level)
23695 "Show all direct subheadings of this heading.
23696 Prefix arg LEVEL is how many levels below the current level
23697 should be shown. Default is enough to cause the following
23698 heading to appear."
23699 (interactive "p")
23700 (save-excursion
23701 (org-back-to-heading t)
23702 (let* ((current-level (funcall outline-level))
23703 (max-level (org-get-valid-level
23704 current-level
23705 (if level (prefix-numeric-value level) 1)))
23706 (end (save-excursion (org-end-of-subtree t t)))
23707 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
23708 (past-first-child nil)
23709 ;; Make sure to skip inlinetasks.
23710 (re (format regexp-fmt
23711 current-level
23712 (cond
23713 ((not (featurep 'org-inlinetask)) "")
23714 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
23716 (t (1- org-inlinetask-min-level))))))
23717 ;; Display parent heading.
23718 (outline-flag-region (line-end-position 0) (line-end-position) nil)
23719 (forward-line)
23720 ;; Display children. First child may be deeper than expected
23721 ;; MAX-LEVEL. Since we want to display it anyway, adjust
23722 ;; MAX-LEVEL accordingly.
23723 (while (re-search-forward re end t)
23724 (unless past-first-child
23725 (setq re (format regexp-fmt
23726 current-level
23727 (max (funcall outline-level) max-level)))
23728 (setq past-first-child t))
23729 (outline-flag-region (line-end-position 0) (line-end-position) nil)))))
23731 (defun org-show-subtree ()
23732 "Show everything after this heading at deeper levels."
23733 (interactive)
23734 (outline-flag-region
23735 (point)
23736 (save-excursion
23737 (org-end-of-subtree t t))
23738 nil))
23740 (defun org-show-entry ()
23741 "Show the body directly following this heading.
23742 Show the heading too, if it is currently invisible."
23743 (interactive)
23744 (save-excursion
23745 (ignore-errors
23746 (org-back-to-heading t)
23747 (outline-flag-region
23748 (max (point-min) (1- (point)))
23749 (save-excursion
23750 (if (re-search-forward
23751 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23752 (match-beginning 1)
23753 (point-max)))
23754 nil)
23755 (org-cycle-hide-drawers 'children))))
23757 (defun org-make-options-regexp (kwds &optional extra)
23758 "Make a regular expression for keyword lines.
23759 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23760 when non-nil, is a regexp matching keywords names."
23761 (concat "^[ \t]*#\\+\\("
23762 (regexp-opt kwds)
23763 (and extra (concat (and kwds "\\|") extra))
23764 "\\):[ \t]*\\(.*\\)"))
23766 ;;;; Finish up
23768 (provide 'org)
23770 (run-hooks 'org-load-hook)
23772 ;;; org.el ends here