Use completion in `org-set-effort'
[org-mode/org-tableheadings.git] / lisp / org.el
blob3b36ead0ec3cdd6b63d72bb490cd1125f4c6c30c
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: 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" 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.
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 (org-end-of-subtree t t))
6961 ((equal state "children")
6962 (org-show-hidden-entry)
6963 (org-show-children))
6964 ((equal state "content")
6965 (save-excursion
6966 (save-restriction
6967 (org-narrow-to-subtree)
6968 (org-content)))
6969 (org-end-of-subtree t t))
6970 ((member state '("all" "showall"))
6971 (outline-show-subtree))))))
6972 (unless no-cleanup
6973 (org-cycle-hide-archived-subtrees 'all)
6974 (org-cycle-hide-drawers 'all)
6975 (org-cycle-show-empty-lines 'all))))
6977 (defun org-overview ()
6978 "Switch to overview mode, showing only top-level headlines.
6979 This shows all headlines with a level equal or greater than the level
6980 of the first headline in the buffer. This is important, because if the
6981 first headline is not level one, then (hide-sublevels 1) gives confusing
6982 results."
6983 (interactive)
6984 (save-excursion
6985 (let ((level
6986 (save-excursion
6987 (goto-char (point-min))
6988 (when (re-search-forward org-outline-regexp-bol nil t)
6989 (goto-char (match-beginning 0))
6990 (funcall outline-level)))))
6991 (and level (outline-hide-sublevels level)))))
6993 (defun org-content (&optional arg)
6994 "Show all headlines in the buffer, like a table of contents.
6995 With numerical argument N, show content up to level N."
6996 (interactive "P")
6997 (org-overview)
6998 (save-excursion
6999 ;; Visit all headings and show their offspring
7000 (and (integerp arg) (org-overview))
7001 (goto-char (point-max))
7002 (catch 'exit
7003 (while (and (progn (condition-case nil
7004 (outline-previous-visible-heading 1)
7005 (error (goto-char (point-min))))
7007 (looking-at org-outline-regexp))
7008 (if (integerp arg)
7009 (org-show-children (1- arg))
7010 (outline-show-branches))
7011 (when (bobp) (throw 'exit nil))))))
7013 (defun org-optimize-window-after-visibility-change (state)
7014 "Adjust the window after a change in outline visibility.
7015 This function is the default value of the hook `org-cycle-hook'."
7016 (when (get-buffer-window (current-buffer))
7017 (cond
7018 ((eq state 'content) nil)
7019 ((eq state 'all) nil)
7020 ((eq state 'folded) nil)
7021 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7022 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7024 (defun org-remove-empty-overlays-at (pos)
7025 "Remove outline overlays that do not contain non-white stuff."
7026 (dolist (o (overlays-at pos))
7027 (and (eq 'outline (overlay-get o 'invisible))
7028 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7029 (overlay-end o))))
7030 (delete-overlay o))))
7032 (defun org-clean-visibility-after-subtree-move ()
7033 "Fix visibility issues after moving a subtree."
7034 ;; First, find a reasonable region to look at:
7035 ;; Start two siblings above, end three below
7036 (let* ((beg (save-excursion
7037 (and (org-get-last-sibling)
7038 (org-get-last-sibling))
7039 (point)))
7040 (end (save-excursion
7041 (and (org-get-next-sibling)
7042 (org-get-next-sibling)
7043 (org-get-next-sibling))
7044 (if (org-at-heading-p)
7045 (point-at-eol)
7046 (point))))
7047 (level (looking-at "\\*+"))
7048 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7049 (save-excursion
7050 (save-restriction
7051 (narrow-to-region beg end)
7052 (when re
7053 ;; Properly fold already folded siblings
7054 (goto-char (point-min))
7055 (while (re-search-forward re nil t)
7056 (when (and (not (org-invisible-p))
7057 (save-excursion
7058 (goto-char (point-at-eol)) (org-invisible-p)))
7059 (outline-hide-entry))))
7060 (org-cycle-show-empty-lines 'overview)
7061 (org-cycle-hide-drawers 'overview)))))
7063 (defun org-cycle-show-empty-lines (state)
7064 "Show empty lines above all visible headlines.
7065 The region to be covered depends on STATE when called through
7066 `org-cycle-hook'. Lisp program can use t for STATE to get the
7067 entire buffer covered. Note that an empty line is only shown if there
7068 are at least `org-cycle-separator-lines' empty lines before the headline."
7069 (when (/= org-cycle-separator-lines 0)
7070 (save-excursion
7071 (let* ((n (abs org-cycle-separator-lines))
7072 (re (cond
7073 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7074 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7075 (t (let ((ns (number-to-string (- n 2))))
7076 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7077 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7078 beg end)
7079 (cond
7080 ((memq state '(overview contents t))
7081 (setq beg (point-min) end (point-max)))
7082 ((memq state '(children folded))
7083 (setq beg (point)
7084 end (progn (org-end-of-subtree t t)
7085 (line-beginning-position 2)))))
7086 (when beg
7087 (goto-char beg)
7088 (while (re-search-forward re end t)
7089 (unless (get-char-property (match-end 1) 'invisible)
7090 (let ((e (match-end 1))
7091 (b (if (>= org-cycle-separator-lines 0)
7092 (match-beginning 1)
7093 (save-excursion
7094 (goto-char (match-beginning 0))
7095 (skip-chars-backward " \t\n")
7096 (line-end-position)))))
7097 (outline-flag-region b e nil))))))))
7098 ;; Never hide empty lines at the end of the file.
7099 (save-excursion
7100 (goto-char (point-max))
7101 (outline-previous-heading)
7102 (outline-end-of-heading)
7103 (when (and (looking-at "[ \t\n]+")
7104 (= (match-end 0) (point-max)))
7105 (outline-flag-region (point) (match-end 0) nil))))
7107 (defun org-show-empty-lines-in-parent ()
7108 "Move to the parent and re-show empty lines before visible headlines."
7109 (save-excursion
7110 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7111 (org-cycle-show-empty-lines context))))
7113 (defun org-files-list ()
7114 "Return `org-agenda-files' list, plus all open Org files.
7115 This is useful for operations that need to scan all of a user's
7116 open and agenda-wise Org files."
7117 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7118 (dolist (buf (buffer-list))
7119 (with-current-buffer buf
7120 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7121 (cl-pushnew (expand-file-name (buffer-file-name)) files
7122 :test #'equal))))
7123 files))
7125 (defsubst org-entry-beginning-position ()
7126 "Return the beginning position of the current entry."
7127 (save-excursion (org-back-to-heading t) (point)))
7129 (defsubst org-entry-end-position ()
7130 "Return the end position of the current entry."
7131 (save-excursion (outline-next-heading) (point)))
7133 (defun org-cycle-hide-drawers (state &optional exceptions)
7134 "Re-hide all drawers after a visibility state change.
7135 STATE should be one of the symbols listed in the docstring of
7136 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7137 a list of strings specifying which drawers should not be hidden."
7138 (when (and (derived-mode-p 'org-mode)
7139 (not (memq state '(overview folded contents))))
7140 (save-excursion
7141 (let* ((globalp (eq state 'all))
7142 (beg (if globalp (point-min) (point)))
7143 (end (if globalp (point-max)
7144 (if (eq state 'children)
7145 (save-excursion (outline-next-heading) (point))
7146 (org-end-of-subtree t)))))
7147 (goto-char beg)
7148 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7149 (unless (member-ignore-case (match-string 1) exceptions)
7150 (let ((drawer (org-element-at-point)))
7151 (when (memq (org-element-type drawer) '(drawer property-drawer))
7152 (org-flag-drawer t drawer)
7153 ;; Make sure to skip drawer entirely or we might flag
7154 ;; it another time when matching its ending line with
7155 ;; `org-drawer-regexp'.
7156 (goto-char (org-element-property :end drawer))))))))))
7158 (defun org-flag-drawer (flag &optional element)
7159 "When FLAG is non-nil, hide the drawer we are at.
7160 Otherwise make it visible. When optional argument ELEMENT is
7161 a parsed drawer, as returned by `org-element-at-point', hide or
7162 show that drawer instead."
7163 (let ((drawer (or element
7164 (and (save-excursion
7165 (beginning-of-line)
7166 (looking-at-p org-drawer-regexp))
7167 (org-element-at-point)))))
7168 (when (memq (org-element-type drawer) '(drawer property-drawer))
7169 (let ((post (org-element-property :post-affiliated drawer)))
7170 (save-excursion
7171 (outline-flag-region
7172 (progn (goto-char post) (line-end-position))
7173 (progn (goto-char (org-element-property :end drawer))
7174 (skip-chars-backward " \r\t\n")
7175 (line-end-position))
7176 flag))
7177 ;; When the drawer is hidden away, make sure point lies in
7178 ;; a visible part of the buffer.
7179 (when (and flag (> (line-beginning-position) post))
7180 (goto-char post))))))
7182 (defun org-subtree-end-visible-p ()
7183 "Is the end of the current subtree visible?"
7184 (pos-visible-in-window-p
7185 (save-excursion (org-end-of-subtree t) (point))))
7187 (defun org-first-headline-recenter ()
7188 "Move cursor to the first headline and recenter the headline."
7189 (let ((window (get-buffer-window)))
7190 (when window
7191 (goto-char (point-min))
7192 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7193 (set-window-start window (line-beginning-position))))))
7195 ;;; Saving and restoring visibility
7197 (defun org-outline-overlay-data (&optional use-markers)
7198 "Return a list of the locations of all outline overlays.
7199 These are overlays with the `invisible' property value `outline'.
7200 The return value is a list of cons cells, with start and stop
7201 positions for each overlay.
7202 If USE-MARKERS is set, return the positions as markers."
7203 (let (beg end)
7204 (org-with-wide-buffer
7205 (delq nil
7206 (mapcar (lambda (o)
7207 (when (eq (overlay-get o 'invisible) 'outline)
7208 (setq beg (overlay-start o)
7209 end (overlay-end o))
7210 (and beg end (> end beg)
7211 (if use-markers
7212 (cons (copy-marker beg)
7213 (copy-marker end t))
7214 (cons beg end)))))
7215 (overlays-in (point-min) (point-max)))))))
7217 (defun org-set-outline-overlay-data (data)
7218 "Create visibility overlays for all positions in DATA.
7219 DATA should have been made by `org-outline-overlay-data'."
7220 (org-with-wide-buffer
7221 (outline-show-all)
7222 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7224 ;;; Folding of blocks
7226 (defvar-local org-hide-block-overlays nil
7227 "Overlays hiding blocks.")
7229 (defun org-block-map (function &optional start end)
7230 "Call FUNCTION at the head of all source blocks in the current buffer.
7231 Optional arguments START and END can be used to limit the range."
7232 (let ((start (or start (point-min)))
7233 (end (or end (point-max))))
7234 (save-excursion
7235 (goto-char start)
7236 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7237 (save-excursion
7238 (save-match-data
7239 (goto-char (match-beginning 0))
7240 (funcall function)))))))
7242 (defun org-hide-block-toggle-all ()
7243 "Toggle the visibility of all blocks in the current buffer."
7244 (org-block-map 'org-hide-block-toggle))
7246 (defun org-hide-block-all ()
7247 "Fold all blocks in the current buffer."
7248 (interactive)
7249 (org-show-block-all)
7250 (org-block-map 'org-hide-block-toggle-maybe))
7252 (defun org-show-block-all ()
7253 "Unfold all blocks in the current buffer."
7254 (interactive)
7255 (mapc #'delete-overlay org-hide-block-overlays)
7256 (setq org-hide-block-overlays nil))
7258 (defun org-hide-block-toggle-maybe ()
7259 "Toggle visibility of block at point.
7260 Unlike to `org-hide-block-toggle', this function does not throw
7261 an error. Return a non-nil value when toggling is successful."
7262 (interactive)
7263 (ignore-errors (org-hide-block-toggle)))
7265 (defun org-hide-block-toggle (&optional force)
7266 "Toggle the visibility of the current block.
7267 When optional argument FORCE is `off', make block visible. If it
7268 is non-nil, hide it unconditionally. Throw an error when not at
7269 a block. Return a non-nil value when toggling is successful."
7270 (interactive)
7271 (let ((element (org-element-at-point)))
7272 (unless (memq (org-element-type element)
7273 '(center-block comment-block dynamic-block example-block
7274 export-block quote-block special-block
7275 src-block verse-block))
7276 (user-error "Not at a block"))
7277 (let* ((start (save-excursion
7278 (goto-char (org-element-property :post-affiliated element))
7279 (line-end-position)))
7280 (end (save-excursion
7281 (goto-char (org-element-property :end element))
7282 (skip-chars-backward " \r\t\n")
7283 (line-end-position)))
7284 (overlays (overlays-at start)))
7285 (cond
7286 ;; Do nothing when not before or at the block opening line or
7287 ;; at the block closing line.
7288 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7289 ((and (not (eq force 'off))
7290 (not (memq t (mapcar
7291 (lambda (o)
7292 (eq (overlay-get o 'invisible) 'org-hide-block))
7293 overlays))))
7294 (let ((ov (make-overlay start end)))
7295 (overlay-put ov 'invisible 'org-hide-block)
7296 ;; Make the block accessible to `isearch'.
7297 (overlay-put
7298 ov 'isearch-open-invisible
7299 (lambda (ov)
7300 (when (memq ov org-hide-block-overlays)
7301 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7302 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7303 (delete-overlay ov))))
7304 (push ov org-hide-block-overlays)
7305 ;; When the block is hidden away, make sure point is left in
7306 ;; a visible part of the buffer.
7307 (when (> (line-beginning-position) start)
7308 (goto-char start)
7309 (beginning-of-line))
7310 ;; Signal successful toggling.
7312 ((or (not force) (eq force 'off))
7313 (dolist (ov overlays t)
7314 (when (memq ov org-hide-block-overlays)
7315 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7316 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7317 (delete-overlay ov))))))))
7319 ;; Remove overlays when changing major mode
7320 (add-hook 'org-mode-hook
7321 (lambda () (add-hook 'change-major-mode-hook
7322 'org-show-block-all 'append 'local)))
7324 ;;; Indirect buffer display of subtrees
7326 (defvar org-indirect-dedicated-frame nil
7327 "This is the frame being used for indirect tree display.")
7328 (defvar org-last-indirect-buffer nil)
7330 (defun org-tree-to-indirect-buffer (&optional arg)
7331 "Create indirect buffer and narrow it to current subtree.
7333 With a numerical prefix ARG, go up to this level and then take that tree.
7334 If ARG is negative, go up that many levels.
7336 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7337 indirect buffer previously made with this command, to avoid proliferation of
7338 indirect buffers. However, when you call the command with a \
7339 `\\[universal-argument]' prefix, or
7340 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7341 so that you can work with several indirect buffers at the same time. If
7342 `org-indirect-buffer-display' is `dedicated-frame', the \
7343 `\\[universal-argument]' prefix also
7344 requests that a new frame be made for the new buffer, so that the dedicated
7345 frame is not changed."
7346 (interactive "P")
7347 (let ((cbuf (current-buffer))
7348 (cwin (selected-window))
7349 (pos (point))
7350 beg end level heading ibuf)
7351 (save-excursion
7352 (org-back-to-heading t)
7353 (when (numberp arg)
7354 (setq level (org-outline-level))
7355 (when (< arg 0) (setq arg (+ level arg)))
7356 (while (> (setq level (org-outline-level)) arg)
7357 (org-up-heading-safe)))
7358 (setq beg (point)
7359 heading (org-get-heading 'no-tags))
7360 (org-end-of-subtree t t)
7361 (when (org-at-heading-p) (backward-char 1))
7362 (setq end (point)))
7363 (when (and (buffer-live-p org-last-indirect-buffer)
7364 (not (eq org-indirect-buffer-display 'new-frame))
7365 (not arg))
7366 (kill-buffer org-last-indirect-buffer))
7367 (setq ibuf (org-get-indirect-buffer cbuf heading)
7368 org-last-indirect-buffer ibuf)
7369 (cond
7370 ((or (eq org-indirect-buffer-display 'new-frame)
7371 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7372 (select-frame (make-frame))
7373 (delete-other-windows)
7374 (pop-to-buffer-same-window ibuf)
7375 (org-set-frame-title heading))
7376 ((eq org-indirect-buffer-display 'dedicated-frame)
7377 (raise-frame
7378 (select-frame (or (and org-indirect-dedicated-frame
7379 (frame-live-p org-indirect-dedicated-frame)
7380 org-indirect-dedicated-frame)
7381 (setq org-indirect-dedicated-frame (make-frame)))))
7382 (delete-other-windows)
7383 (pop-to-buffer-same-window ibuf)
7384 (org-set-frame-title (concat "Indirect: " heading)))
7385 ((eq org-indirect-buffer-display 'current-window)
7386 (pop-to-buffer-same-window ibuf))
7387 ((eq org-indirect-buffer-display 'other-window)
7388 (pop-to-buffer ibuf))
7389 (t (error "Invalid value")))
7390 (narrow-to-region beg end)
7391 (outline-show-all)
7392 (goto-char pos)
7393 (run-hook-with-args 'org-cycle-hook 'all)
7394 (and (window-live-p cwin) (select-window cwin))))
7396 (defun org-get-indirect-buffer (&optional buffer heading)
7397 (setq buffer (or buffer (current-buffer)))
7398 (let ((n 1) (base (buffer-name buffer)) bname)
7399 (while (buffer-live-p
7400 (get-buffer
7401 (setq bname
7402 (concat base "-"
7403 (if heading (concat heading "-" (number-to-string n))
7404 (number-to-string n))))))
7405 (setq n (1+ n)))
7406 (condition-case nil
7407 (make-indirect-buffer buffer bname 'clone)
7408 (error (make-indirect-buffer buffer bname)))))
7410 (defun org-set-frame-title (title)
7411 "Set the title of the current frame to the string TITLE."
7412 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7414 ;;;; Structure editing
7416 ;;; Inserting headlines
7418 (defun org--line-empty-p (n)
7419 "Is the Nth next line empty?
7421 Counts the current line as N = 1 and the previous line as N = 0;
7422 see `beginning-of-line'."
7423 (save-excursion
7424 (and (not (bobp))
7425 (or (beginning-of-line n) t)
7426 (save-match-data
7427 (looking-at "[ \t]*$")))))
7429 (defun org-previous-line-empty-p ()
7430 "Is the previous line a blank line?
7431 When NEXT is non-nil, check the next line instead."
7432 (org--line-empty-p 0))
7434 (defun org-next-line-empty-p ()
7435 "Is the previous line a blank line?
7436 When NEXT is non-nil, check the next line instead."
7437 (org--line-empty-p 2))
7439 (defun org--blank-before-heading-p (&optional parent)
7440 "Non-nil when an empty line should precede a new heading here.
7441 When optional argument PARENT is non-nil, consider parent
7442 headline instead of current one."
7443 (pcase (assq 'heading org-blank-before-new-entry)
7444 (`(heading . auto)
7445 (save-excursion
7446 (org-with-limited-levels
7447 (unless (and (org-before-first-heading-p)
7448 (not (outline-next-heading)))
7449 (org-back-to-heading t)
7450 (when parent (org-up-heading-safe))
7451 (cond ((not (bobp))
7452 (org-previous-line-empty-p))
7453 ((outline-next-heading)
7454 (org-previous-line-empty-p))
7455 ;; Ignore trailing spaces on last buffer line.
7456 ((progn (skip-chars-backward " \t") (bolp))
7457 (org-previous-line-empty-p))
7458 (t nil))))))
7459 (`(heading . ,value) value)
7460 (_ nil)))
7462 (defun org-insert-heading (&optional arg invisible-ok top)
7463 "Insert a new heading or an item with the same depth at point.
7465 If point is at the beginning of a heading, insert a new heading
7466 or a new headline above the current one. When at the beginning
7467 of a regular line of text, turn it into a heading.
7469 If point is in the middle of a line, split it and create a new
7470 headline with the text in the current line after point (see
7471 `org-M-RET-may-split-line' on how to modify this behavior). As
7472 a special case, on a headline, splitting can only happen on the
7473 title itself. E.g., this excludes breaking stars or tags.
7475 With a `\\[universal-argument]' prefix, set \
7476 `org-insert-heading-respect-content' to
7477 a non-nil value for the duration of the command. This forces the
7478 insertion of a heading after the current subtree, independently
7479 on the location of point.
7481 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7482 insert the heading at the end of the tree
7483 above the current heading. For example, if point is within a
7484 2nd-level heading, then it will insert a 2nd-level heading at
7485 the end of the 1st-level parent subtree.
7487 When INVISIBLE-OK is set, stop at invisible headlines when going
7488 back. This is important for non-interactive uses of the
7489 command.
7491 When optional argument TOP is non-nil, insert a level 1 heading,
7492 unconditionally."
7493 (interactive "P")
7494 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7495 (level (org-current-level))
7496 (stars (make-string (if (and level (not top)) level 1) ?*)))
7497 (cond
7498 ((or org-insert-heading-respect-content
7499 (member arg '((4) (16)))
7500 (and (not invisible-ok)
7501 (invisible-p (max (1- (point)) (point-min)))))
7502 ;; Position point at the location of insertion.
7503 (if (not level) ;before first headline
7504 (org-with-limited-levels (outline-next-heading))
7505 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7506 ;; is nil.
7507 (org-with-limited-levels (org-back-to-heading invisible-ok))
7508 (cond ((equal arg '(16))
7509 (org-up-heading-safe)
7510 (org-end-of-subtree t t))
7512 (org-end-of-subtree t t))))
7513 (unless (bolp) (insert "\n")) ;ensure final newline
7514 (unless (and blank? (org-previous-line-empty-p))
7515 (org-N-empty-lines-before-current (if blank? 1 0)))
7516 (insert stars " \n")
7517 (forward-char -1))
7518 ;; At a headline...
7519 ((org-at-heading-p)
7520 (cond ((bolp)
7521 (when blank? (save-excursion (insert "\n")))
7522 (save-excursion (insert stars " \n"))
7523 (unless (and blank? (org-previous-line-empty-p))
7524 (org-N-empty-lines-before-current (if blank? 1 0)))
7525 (end-of-line))
7526 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7527 (org-match-line org-complex-heading-regexp)
7528 (org-pos-in-match-range (point) 4))
7529 ;; Grab the text that should moved to the new headline.
7530 ;; Preserve tags.
7531 (let ((split (delete-and-extract-region (point) (match-end 4))))
7532 (if (looking-at "[ \t]*$") (replace-match "")
7533 (org-set-tags nil t))
7534 (end-of-line)
7535 (when blank? (insert "\n"))
7536 (insert "\n" stars " ")
7537 (when (org-string-nw-p split) (insert split))
7538 (when (eobp) (save-excursion (insert "\n")))))
7540 (end-of-line)
7541 (when blank? (insert "\n"))
7542 (insert "\n" stars " ")
7543 (when (eobp) (save-excursion (insert "\n"))))))
7544 ;; On regular text, turn line into a headline or split, if
7545 ;; appropriate.
7546 ((bolp)
7547 (insert stars " ")
7548 (unless (and blank? (org-previous-line-empty-p))
7549 (org-N-empty-lines-before-current (if blank? 1 0))))
7551 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7552 (end-of-line))
7553 (insert "\n" stars " ")
7554 (unless (and blank? (org-previous-line-empty-p))
7555 (org-N-empty-lines-before-current (if blank? 1 0))))))
7556 (run-hooks 'org-insert-heading-hook))
7558 (defun org-N-empty-lines-before-current (n)
7559 "Make the number of empty lines before current exactly N.
7560 So this will delete or add empty lines."
7561 (let ((column (current-column)))
7562 (beginning-of-line)
7563 (unless (bobp)
7564 (let ((start (save-excursion
7565 (skip-chars-backward " \r\t\n")
7566 (line-end-position))))
7567 (delete-region start (line-end-position 0))))
7568 (insert (make-string n ?\n))
7569 (move-to-column column)))
7571 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7572 "Return the heading of the current entry, without the stars.
7573 When NO-TAGS is non-nil, don't include tags.
7574 When NO-TODO is non-nil, don't include TODO keywords.
7575 When NO-PRIORITY is non-nil, don't include priority cookie.
7576 When NO-COMMENT is non-nil, don't include COMMENT string."
7577 (save-excursion
7578 (org-back-to-heading t)
7579 (let ((case-fold-search nil))
7580 (looking-at org-complex-heading-regexp)
7581 (let ((todo (and (not no-todo) (match-string 2)))
7582 (priority (and (not no-priority) (match-string 3)))
7583 (headline (pcase (match-string 4)
7584 (`nil "")
7585 ((and (guard no-comment) h)
7586 (replace-regexp-in-string
7587 (eval-when-compile
7588 (format "\\`%s[ \t]+" org-comment-string))
7589 "" h))
7590 (h h)))
7591 (tags (and (not no-tags) (match-string 5))))
7592 (mapconcat #'identity
7593 (delq nil (list todo priority headline tags))
7594 " ")))))
7596 (defun org-heading-components ()
7597 "Return the components of the current heading.
7598 This is a list with the following elements:
7599 - the level as an integer
7600 - the reduced level, different if `org-odd-levels-only' is set.
7601 - the TODO keyword, or nil
7602 - the priority character, like ?A, or nil if no priority is given
7603 - the headline text itself, or the tags string if no headline text
7604 - the tags string, or nil."
7605 (save-excursion
7606 (org-back-to-heading t)
7607 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7608 (list (length (match-string 1))
7609 (org-reduced-level (length (match-string 1)))
7610 (match-string-no-properties 2)
7611 (and (match-end 3) (aref (match-string 3) 2))
7612 (match-string-no-properties 4)
7613 (match-string-no-properties 5)))))
7615 (defun org-get-entry ()
7616 "Get the entry text, after heading, entire subtree."
7617 (save-excursion
7618 (org-back-to-heading t)
7619 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7621 (defun org-edit-headline (&optional heading)
7622 "Edit the current headline.
7623 Set it to HEADING when provided."
7624 (interactive)
7625 (org-with-wide-buffer
7626 (org-back-to-heading t)
7627 (let ((case-fold-search nil))
7628 (when (looking-at org-complex-heading-regexp)
7629 (let* ((old (match-string-no-properties 4))
7630 (new (save-match-data
7631 (org-trim (or heading (read-string "Edit: " old))))))
7632 (unless (equal old new)
7633 (if old (replace-match new t t nil 4)
7634 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7635 (insert " " new))
7636 (org-set-tags nil t)
7637 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7639 (defun org-insert-heading-after-current ()
7640 "Insert a new heading with same level as current, after current subtree."
7641 (interactive)
7642 (org-back-to-heading)
7643 (org-insert-heading)
7644 (org-move-subtree-down)
7645 (end-of-line 1))
7647 (defun org-insert-heading-respect-content (&optional invisible-ok)
7648 "Insert heading with `org-insert-heading-respect-content' set to t."
7649 (interactive)
7650 (org-insert-heading '(4) invisible-ok))
7652 (defun org-insert-todo-heading-respect-content (&optional force-state)
7653 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7654 (interactive)
7655 (org-insert-todo-heading force-state '(4)))
7657 (defun org-insert-todo-heading (arg &optional force-heading)
7658 "Insert a new heading with the same level and TODO state as current heading.
7660 If the heading has no TODO state, or if the state is DONE, use
7661 the first state (TODO by default). Also with one prefix arg,
7662 force first state. With two prefix args, force inserting at the
7663 end of the parent subtree.
7665 When called at a plain list item, insert a new item with an
7666 unchecked check box."
7667 (interactive "P")
7668 (when (or force-heading (not (org-insert-item 'checkbox)))
7669 (org-insert-heading (or (and (equal arg '(16)) '(16))
7670 force-heading))
7671 (save-excursion
7672 (org-forward-heading-same-level -1)
7673 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7674 (let* ((new-mark-x
7675 (if (or (equal arg '(4))
7676 (not (match-beginning 2))
7677 (member (match-string 2) org-done-keywords))
7678 (car org-todo-keywords-1)
7679 (match-string 2)))
7680 (new-mark
7682 (run-hook-with-args-until-success
7683 'org-todo-get-default-hook new-mark-x nil)
7684 new-mark-x)))
7685 (beginning-of-line 1)
7686 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7687 (if org-treat-insert-todo-heading-as-state-change
7688 (org-todo new-mark)
7689 (insert new-mark " "))))
7690 (when org-provide-todo-statistics
7691 (org-update-parent-todo-statistics))))
7693 (defun org-insert-subheading (arg)
7694 "Insert a new subheading and demote it.
7695 Works for outline headings and for plain lists alike."
7696 (interactive "P")
7697 (org-insert-heading arg)
7698 (cond
7699 ((org-at-heading-p) (org-do-demote))
7700 ((org-at-item-p) (org-indent-item))))
7702 (defun org-insert-todo-subheading (arg)
7703 "Insert a new subheading with TODO keyword or checkbox and demote it.
7704 Works for outline headings and for plain lists alike."
7705 (interactive "P")
7706 (org-insert-todo-heading arg)
7707 (cond
7708 ((org-at-heading-p) (org-do-demote))
7709 ((org-at-item-p) (org-indent-item))))
7711 ;;; Promotion and Demotion
7713 (defvar org-after-demote-entry-hook nil
7714 "Hook run after an entry has been demoted.
7715 The cursor will be at the beginning of the entry.
7716 When a subtree is being demoted, the hook will be called for each node.")
7718 (defvar org-after-promote-entry-hook nil
7719 "Hook run after an entry has been promoted.
7720 The cursor will be at the beginning of the entry.
7721 When a subtree is being promoted, the hook will be called for each node.")
7723 (defun org-promote-subtree ()
7724 "Promote the entire subtree.
7725 See also `org-promote'."
7726 (interactive)
7727 (save-excursion
7728 (org-with-limited-levels (org-map-tree 'org-promote)))
7729 (org-fix-position-after-promote))
7731 (defun org-demote-subtree ()
7732 "Demote the entire subtree.
7733 See `org-demote' and `org-promote'."
7734 (interactive)
7735 (save-excursion
7736 (org-with-limited-levels (org-map-tree 'org-demote)))
7737 (org-fix-position-after-promote))
7739 (defun org-do-promote ()
7740 "Promote the current heading higher up the tree.
7741 If the region is active in `transient-mark-mode', promote all
7742 headings in the region."
7743 (interactive)
7744 (save-excursion
7745 (if (org-region-active-p)
7746 (org-map-region 'org-promote (region-beginning) (region-end))
7747 (org-promote)))
7748 (org-fix-position-after-promote))
7750 (defun org-do-demote ()
7751 "Demote the current heading lower down the tree.
7752 If the region is active in `transient-mark-mode', demote all
7753 headings in the region."
7754 (interactive)
7755 (save-excursion
7756 (if (org-region-active-p)
7757 (org-map-region 'org-demote (region-beginning) (region-end))
7758 (org-demote)))
7759 (org-fix-position-after-promote))
7761 (defun org-fix-position-after-promote ()
7762 "Fix cursor position and indentation after demoting/promoting."
7763 (let ((pos (point)))
7764 (when (save-excursion
7765 (beginning-of-line)
7766 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7767 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7768 (cond ((eobp) (insert " "))
7769 ((eolp) (insert " "))
7770 ((equal (char-after) ?\s) (forward-char 1))))))
7772 (defun org-current-level ()
7773 "Return the level of the current entry, or nil if before the first headline.
7774 The level is the number of stars at the beginning of the
7775 headline. Use `org-reduced-level' to remove the effect of
7776 `org-odd-levels'. Unlike to `org-outline-level', this function
7777 ignores inlinetasks."
7778 (let ((level (org-with-limited-levels (org-outline-level))))
7779 (and (> level 0) level)))
7781 (defun org-get-previous-line-level ()
7782 "Return the outline depth of the last headline before the current line.
7783 Returns 0 for the first headline in the buffer, and nil if before the
7784 first headline."
7785 (and (org-current-level)
7786 (or (and (/= (line-beginning-position) (point-min))
7787 (save-excursion (beginning-of-line 0) (org-current-level)))
7788 0)))
7790 (defun org-reduced-level (l)
7791 "Compute the effective level of a heading.
7792 This takes into account the setting of `org-odd-levels-only'."
7793 (cond
7794 ((zerop l) 0)
7795 (org-odd-levels-only (1+ (floor (/ l 2))))
7796 (t l)))
7798 (defun org-level-increment ()
7799 "Return the number of stars that will be added or removed at a
7800 time to headlines when structure editing, based on the value of
7801 `org-odd-levels-only'."
7802 (if org-odd-levels-only 2 1))
7804 (defun org-get-valid-level (level &optional change)
7805 "Rectify a level change under the influence of `org-odd-levels-only'.
7806 LEVEL is a current level, CHANGE is by how much the level should
7807 be modified. Even if CHANGE is nil, LEVEL may be returned
7808 modified because even level numbers will become the next higher
7809 odd number. Returns values greater than 0."
7810 (if org-odd-levels-only
7811 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7812 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7813 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7814 (max 1 (+ level (or change 0)))))
7816 (defun org-promote ()
7817 "Promote the current heading higher up the tree."
7818 (org-with-wide-buffer
7819 (org-back-to-heading t)
7820 (let* ((after-change-functions (remq 'flyspell-after-change-function
7821 after-change-functions))
7822 (level (save-match-data (funcall outline-level)))
7823 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7824 (diff (abs (- level (length up-head) -1))))
7825 (cond
7826 ((and (= level 1) org-allow-promoting-top-level-subtree)
7827 (replace-match "# " nil t))
7828 ((= level 1)
7829 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7830 (t (replace-match up-head nil t)))
7831 (unless (= level 1)
7832 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7833 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7834 (run-hooks 'org-after-promote-entry-hook))))
7836 (defun org-demote ()
7837 "Demote the current heading lower down the tree."
7838 (org-with-wide-buffer
7839 (org-back-to-heading t)
7840 (let* ((after-change-functions (remq 'flyspell-after-change-function
7841 after-change-functions))
7842 (level (save-match-data (funcall outline-level)))
7843 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7844 (diff (abs (- level (length down-head) -1))))
7845 (replace-match down-head nil t)
7846 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7847 (when org-adapt-indentation (org-fixup-indentation diff))
7848 (run-hooks 'org-after-demote-entry-hook))))
7850 (defun org-cycle-level ()
7851 "Cycle the level of an empty headline through possible states.
7852 This goes first to child, then to parent, level, then up the hierarchy.
7853 After top level, it switches back to sibling level."
7854 (interactive)
7855 (let ((org-adapt-indentation nil))
7856 (when (org-point-at-end-of-empty-headline)
7857 (setq this-command 'org-cycle-level) ; Only needed for caching
7858 (let ((cur-level (org-current-level))
7859 (prev-level (org-get-previous-line-level)))
7860 (cond
7861 ;; If first headline in file, promote to top-level.
7862 ((= prev-level 0)
7863 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7864 do (org-do-promote)))
7865 ;; If same level as prev, demote one.
7866 ((= prev-level cur-level)
7867 (org-do-demote))
7868 ;; If parent is top-level, promote to top level if not already.
7869 ((= prev-level 1)
7870 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7871 do (org-do-promote)))
7872 ;; If top-level, return to prev-level.
7873 ((= cur-level 1)
7874 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7875 do (org-do-demote)))
7876 ;; If less than prev-level, promote one.
7877 ((< cur-level prev-level)
7878 (org-do-promote))
7879 ;; If deeper than prev-level, promote until higher than
7880 ;; prev-level.
7881 ((> cur-level prev-level)
7882 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7883 do (org-do-promote))))
7884 t))))
7886 (defun org-map-tree (fun)
7887 "Call FUN for every heading underneath the current one."
7888 (org-back-to-heading t)
7889 (let ((level (funcall outline-level)))
7890 (save-excursion
7891 (funcall fun)
7892 (while (and (progn
7893 (outline-next-heading)
7894 (> (funcall outline-level) level))
7895 (not (eobp)))
7896 (funcall fun)))))
7898 (defun org-map-region (fun beg end)
7899 "Call FUN for every heading between BEG and END."
7900 (let ((org-ignore-region t))
7901 (save-excursion
7902 (setq end (copy-marker end))
7903 (goto-char beg)
7904 (when (and (re-search-forward org-outline-regexp-bol nil t)
7905 (< (point) end))
7906 (funcall fun))
7907 (while (and (progn
7908 (outline-next-heading)
7909 (< (point) end))
7910 (not (eobp)))
7911 (funcall fun)))))
7913 (defun org-fixup-indentation (diff)
7914 "Change the indentation in the current entry by DIFF.
7916 DIFF is an integer. Indentation is done according to the
7917 following rules:
7919 - Planning information and property drawers are always indented
7920 according to the new level of the headline;
7922 - Footnote definitions and their contents are ignored;
7924 - Inlinetasks' boundaries are not shifted;
7926 - Empty lines are ignored;
7928 - Other lines' indentation are shifted by DIFF columns, unless
7929 it would introduce a structural change in the document, in
7930 which case no shifting is done at all.
7932 Assume point is at a heading or an inlinetask beginning."
7933 (org-with-wide-buffer
7934 (narrow-to-region (line-beginning-position)
7935 (save-excursion
7936 (if (org-with-limited-levels (org-at-heading-p))
7937 (org-with-limited-levels (outline-next-heading))
7938 (org-inlinetask-goto-end))
7939 (point)))
7940 (forward-line)
7941 ;; Indent properly planning info and property drawer.
7942 (when (looking-at-p org-planning-line-re)
7943 (org-indent-line)
7944 (forward-line))
7945 (when (looking-at org-property-drawer-re)
7946 (goto-char (match-end 0))
7947 (forward-line)
7948 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7949 (catch 'no-shift
7950 (when (zerop diff) (throw 'no-shift nil))
7951 ;; If DIFF is negative, first check if a shift is possible at all
7952 ;; (e.g., it doesn't break structure). This can only happen if
7953 ;; some contents are not properly indented.
7954 (let ((case-fold-search t))
7955 (when (< diff 0)
7956 (let ((diff (- diff))
7957 (forbidden-re (concat org-outline-regexp
7958 "\\|"
7959 (substring org-footnote-definition-re 1))))
7960 (save-excursion
7961 (while (not (eobp))
7962 (cond
7963 ((looking-at-p "[ \t]*$") (forward-line))
7964 ((and (looking-at-p org-footnote-definition-re)
7965 (let ((e (org-element-at-point)))
7966 (and (eq (org-element-type e) 'footnote-definition)
7967 (goto-char (org-element-property :end e))))))
7968 ((looking-at-p org-outline-regexp) (forward-line))
7969 ;; Give up if shifting would move before column 0 or
7970 ;; if it would introduce a headline or a footnote
7971 ;; definition.
7973 (skip-chars-forward " \t")
7974 (let ((ind (current-column)))
7975 (when (or (< ind diff)
7976 (and (= ind diff) (looking-at-p forbidden-re)))
7977 (throw 'no-shift nil)))
7978 ;; Ignore contents of example blocks and source
7979 ;; blocks if their indentation is meant to be
7980 ;; preserved. Jump to block's closing line.
7981 (beginning-of-line)
7982 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7983 (let ((e (org-element-at-point)))
7984 (and (memq (org-element-type e)
7985 '(example-block src-block))
7986 (or org-src-preserve-indentation
7987 (org-element-property :preserve-indent e))
7988 (goto-char (org-element-property :end e))
7989 (progn (skip-chars-backward " \r\t\n")
7990 (beginning-of-line)
7991 t))))
7992 (forward-line))))))))
7993 ;; Shift lines but footnote definitions, inlinetasks boundaries
7994 ;; by DIFF. Also skip contents of source or example blocks
7995 ;; when indentation is meant to be preserved.
7996 (while (not (eobp))
7997 (cond
7998 ((and (looking-at-p org-footnote-definition-re)
7999 (let ((e (org-element-at-point)))
8000 (and (eq (org-element-type e) 'footnote-definition)
8001 (goto-char (org-element-property :end e))))))
8002 ((looking-at-p org-outline-regexp) (forward-line))
8003 ((looking-at-p "[ \t]*$") (forward-line))
8005 (indent-line-to (+ (org-get-indentation) diff))
8006 (beginning-of-line)
8007 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8008 (let ((e (org-element-at-point)))
8009 (and (memq (org-element-type e)
8010 '(example-block src-block))
8011 (or org-src-preserve-indentation
8012 (org-element-property :preserve-indent e))
8013 (goto-char (org-element-property :end e))
8014 (progn (skip-chars-backward " \r\t\n")
8015 (beginning-of-line)
8016 t))))
8017 (forward-line)))))))))
8019 (defun org-convert-to-odd-levels ()
8020 "Convert an Org file with all levels allowed to one with odd levels.
8021 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8022 level 5 etc."
8023 (interactive)
8024 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8025 (let ((outline-level 'org-outline-level)
8026 (org-odd-levels-only nil) n)
8027 (save-excursion
8028 (goto-char (point-min))
8029 (while (re-search-forward "^\\*\\*+ " nil t)
8030 (setq n (- (length (match-string 0)) 2))
8031 (while (>= (setq n (1- n)) 0)
8032 (org-demote))
8033 (end-of-line 1))))))
8035 (defun org-convert-to-oddeven-levels ()
8036 "Convert an Org file with only odd levels to one with odd/even levels.
8037 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8038 file contains a section with an even level, conversion would
8039 destroy the structure of the file. An error is signaled in this
8040 case."
8041 (interactive)
8042 (goto-char (point-min))
8043 ;; First check if there are no even levels
8044 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8045 (org-show-set-visibility 'canonical)
8046 (error "Not all levels are odd in this file. Conversion not possible"))
8047 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8048 (let ((outline-regexp org-outline-regexp)
8049 (outline-level 'org-outline-level)
8050 (org-odd-levels-only nil) n)
8051 (save-excursion
8052 (goto-char (point-min))
8053 (while (re-search-forward "^\\*\\*+ " nil t)
8054 (setq n (/ (1- (length (match-string 0))) 2))
8055 (while (>= (setq n (1- n)) 0)
8056 (org-promote))
8057 (end-of-line 1))))))
8059 (defun org-tr-level (n)
8060 "Make N odd if required."
8061 (if org-odd-levels-only (1+ (/ n 2)) n))
8063 ;;; Vertical tree motion, cutting and pasting of subtrees
8065 (defun org-move-subtree-up (&optional arg)
8066 "Move the current subtree up past ARG headlines of the same level."
8067 (interactive "p")
8068 (org-move-subtree-down (- (prefix-numeric-value arg))))
8070 (defun org-move-subtree-down (&optional arg)
8071 "Move the current subtree down past ARG headlines of the same level."
8072 (interactive "p")
8073 (setq arg (prefix-numeric-value arg))
8074 (org-preserve-local-variables
8075 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8076 'org-get-last-sibling))
8077 (ins-point (make-marker))
8078 (cnt (abs arg))
8079 (col (current-column))
8080 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8081 ;; Select the tree
8082 (org-back-to-heading)
8083 (setq beg0 (point))
8084 (save-excursion
8085 (setq ne-beg (org-back-over-empty-lines))
8086 (setq beg (point)))
8087 (save-match-data
8088 (save-excursion (outline-end-of-heading)
8089 (setq folded (org-invisible-p)))
8090 (progn (org-end-of-subtree nil t)
8091 (unless (eobp) (backward-char))))
8092 (outline-next-heading)
8093 (setq ne-end (org-back-over-empty-lines))
8094 (setq end (point))
8095 (goto-char beg0)
8096 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8097 ;; include less whitespace
8098 (save-excursion
8099 (goto-char beg)
8100 (forward-line (- ne-beg ne-end))
8101 (setq beg (point))))
8102 ;; Find insertion point, with error handling
8103 (while (> cnt 0)
8104 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8105 (progn (goto-char beg0)
8106 (user-error "Cannot move past superior level or buffer limit")))
8107 (setq cnt (1- cnt)))
8108 (when (> arg 0)
8109 ;; Moving forward - still need to move over subtree
8110 (org-end-of-subtree t t)
8111 (save-excursion
8112 (org-back-over-empty-lines)
8113 (unless (bolp) (insert "\n"))))
8114 (setq ne-ins (org-back-over-empty-lines))
8115 (move-marker ins-point (point))
8116 (setq txt (buffer-substring beg end))
8117 (org-save-markers-in-region beg end)
8118 (delete-region beg end)
8119 (org-remove-empty-overlays-at beg)
8120 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8121 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8122 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8123 (let ((bbb (point)))
8124 (insert-before-markers txt)
8125 (org-reinstall-markers-in-region bbb)
8126 (move-marker ins-point bbb))
8127 (or (bolp) (insert "\n"))
8128 (setq ins-end (point))
8129 (goto-char ins-point)
8130 (org-skip-whitespace)
8131 (when (and (< arg 0)
8132 (org-first-sibling-p)
8133 (> ne-ins ne-beg))
8134 ;; Move whitespace back to beginning.
8135 (save-excursion
8136 (goto-char ins-end)
8137 (let ((kill-whole-line t))
8138 (kill-line (- ne-ins ne-beg)) (point)))
8139 (insert (make-string (- ne-ins ne-beg) ?\n)))
8140 (move-marker ins-point nil)
8141 (if folded
8142 (outline-hide-subtree)
8143 (org-show-entry)
8144 (org-show-children)
8145 (org-cycle-hide-drawers 'children))
8146 (org-clean-visibility-after-subtree-move)
8147 ;; Move back to the initial column we were at.
8148 (move-to-column col))))
8150 (defvar org-subtree-clip ""
8151 "Clipboard for cut and paste of subtrees.
8152 This is actually only a copy of the kill, because we use the normal kill
8153 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8155 (defvar org-subtree-clip-folded nil
8156 "Was the last copied subtree folded?
8157 This is used to fold the tree back after pasting.")
8159 (defun org-cut-subtree (&optional n)
8160 "Cut the current subtree into the clipboard.
8161 With prefix arg N, cut this many sequential subtrees.
8162 This is a short-hand for marking the subtree and then cutting it."
8163 (interactive "p")
8164 (org-copy-subtree n 'cut))
8166 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8167 "Copy the current subtree it in the clipboard.
8168 With prefix arg N, copy this many sequential subtrees.
8169 This is a short-hand for marking the subtree and then copying it.
8170 If CUT is non-nil, actually cut the subtree.
8171 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8172 of some markers in the region, even if CUT is non-nil. This is
8173 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8174 (interactive "p")
8175 (org-preserve-local-variables
8176 (let (beg end folded (beg0 (point)))
8177 (if (called-interactively-p 'any)
8178 (org-back-to-heading nil) ; take what looks like a subtree
8179 (org-back-to-heading t)) ; take what is really there
8180 (setq beg (point))
8181 (skip-chars-forward " \t\r\n")
8182 (save-match-data
8183 (if nosubtrees
8184 (outline-next-heading)
8185 (save-excursion (outline-end-of-heading)
8186 (setq folded (org-invisible-p)))
8187 (ignore-errors (org-forward-heading-same-level (1- n) t))
8188 (org-end-of-subtree t t)))
8189 ;; Include the end of an inlinetask
8190 (when (and (featurep 'org-inlinetask)
8191 (looking-at-p (concat (org-inlinetask-outline-regexp)
8192 "END[ \t]*$")))
8193 (end-of-line))
8194 (setq end (point))
8195 (goto-char beg0)
8196 (when (> end beg)
8197 (setq org-subtree-clip-folded folded)
8198 (when (or cut force-store-markers)
8199 (org-save-markers-in-region beg end))
8200 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8201 (setq org-subtree-clip (current-kill 0))
8202 (message "%s: Subtree(s) with %d characters"
8203 (if cut "Cut" "Copied")
8204 (length org-subtree-clip))))))
8206 (defun org-paste-subtree (&optional level tree for-yank remove)
8207 "Paste the clipboard as a subtree, with modification of headline level.
8208 The entire subtree is promoted or demoted in order to match a new headline
8209 level.
8211 If the cursor is at the beginning of a headline, the same level as
8212 that headline is used to paste the tree.
8214 If not, the new level is derived from the *visible* headings
8215 before and after the insertion point, and taken to be the inferior headline
8216 level of the two. So if the previous visible heading is level 3 and the
8217 next is level 4 (or vice versa), level 4 will be used for insertion.
8218 This makes sure that the subtree remains an independent subtree and does
8219 not swallow low level entries.
8221 You can also force a different level, either by using a numeric prefix
8222 argument, or by inserting the heading marker by hand. For example, if the
8223 cursor is after \"*****\", then the tree will be shifted to level 5.
8225 If optional TREE is given, use this text instead of the kill ring.
8227 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8228 move back over whitespace before inserting, and move point to the end of
8229 the inserted text when done.
8231 When REMOVE is non-nil, remove the subtree from the clipboard."
8232 (interactive "P")
8233 (setq tree (or tree (and kill-ring (current-kill 0))))
8234 (unless (org-kill-is-subtree-p tree)
8235 (user-error "%s"
8236 (substitute-command-keys
8237 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8238 (org-with-limited-levels
8239 (let* ((visp (not (org-invisible-p)))
8240 (txt tree)
8241 (^re_ "\\(\\*+\\)[ \t]*")
8242 (old-level (if (string-match org-outline-regexp-bol txt)
8243 (- (match-end 0) (match-beginning 0) 1)
8244 -1))
8245 (force-level (cond (level (prefix-numeric-value level))
8246 ((and (looking-at "[ \t]*$")
8247 (string-match
8248 "^\\*+$" (buffer-substring
8249 (point-at-bol) (point))))
8250 (- (match-end 0) (match-beginning 0)))
8251 ((and (bolp)
8252 (looking-at org-outline-regexp))
8253 (- (match-end 0) (point) 1))))
8254 (previous-level (save-excursion
8255 (condition-case nil
8256 (progn
8257 (outline-previous-visible-heading 1)
8258 (if (looking-at ^re_)
8259 (- (match-end 0) (match-beginning 0) 1)
8261 (error 1))))
8262 (next-level (save-excursion
8263 (condition-case nil
8264 (progn
8265 (or (looking-at org-outline-regexp)
8266 (outline-next-visible-heading 1))
8267 (if (looking-at ^re_)
8268 (- (match-end 0) (match-beginning 0) 1)
8270 (error 1))))
8271 (new-level (or force-level (max previous-level next-level)))
8272 (shift (if (or (= old-level -1)
8273 (= new-level -1)
8274 (= old-level new-level))
8276 (- new-level old-level)))
8277 (delta (if (> shift 0) -1 1))
8278 (func (if (> shift 0) 'org-demote 'org-promote))
8279 (org-odd-levels-only nil)
8280 beg end newend)
8281 ;; Remove the forced level indicator
8282 (when force-level
8283 (delete-region (point-at-bol) (point)))
8284 ;; Paste
8285 (beginning-of-line (if (bolp) 1 2))
8286 (setq beg (point))
8287 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8288 (insert-before-markers txt)
8289 (unless (string-suffix-p "\n" txt) (insert "\n"))
8290 (setq newend (point))
8291 (org-reinstall-markers-in-region beg)
8292 (setq end (point))
8293 (goto-char beg)
8294 (skip-chars-forward " \t\n\r")
8295 (setq beg (point))
8296 (when (and (org-invisible-p) visp)
8297 (save-excursion (outline-show-heading)))
8298 ;; Shift if necessary
8299 (unless (= shift 0)
8300 (save-restriction
8301 (narrow-to-region beg end)
8302 (while (not (= shift 0))
8303 (org-map-region func (point-min) (point-max))
8304 (setq shift (+ delta shift)))
8305 (goto-char (point-min))
8306 (setq newend (point-max))))
8307 (when (or (called-interactively-p 'interactive) for-yank)
8308 (message "Clipboard pasted as level %d subtree" new-level))
8309 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8310 kill-ring
8311 (eq org-subtree-clip (current-kill 0))
8312 org-subtree-clip-folded)
8313 ;; The tree was folded before it was killed/copied
8314 (outline-hide-subtree))
8315 (and for-yank (goto-char newend))
8316 (and remove (setq kill-ring (cdr kill-ring))))))
8318 (defun org-kill-is-subtree-p (&optional txt)
8319 "Check if the current kill is an outline subtree, or a set of trees.
8320 Returns nil if kill does not start with a headline, or if the first
8321 headline level is not the largest headline level in the tree.
8322 So this will actually accept several entries of equal levels as well,
8323 which is OK for `org-paste-subtree'.
8324 If optional TXT is given, check this string instead of the current kill."
8325 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8326 (re (org-get-limited-outline-regexp))
8327 (^re (concat "^" re))
8328 (start-level (and kill
8329 (string-match
8330 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8331 kill)
8332 (- (match-end 2) (match-beginning 2) 1)))
8333 (start (1+ (or (match-beginning 2) -1))))
8334 (if (not start-level)
8335 (progn
8336 nil) ;; does not even start with a heading
8337 (catch 'exit
8338 (while (setq start (string-match ^re kill (1+ start)))
8339 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8340 (throw 'exit nil)))
8341 t))))
8343 (defvar org-markers-to-move nil
8344 "Markers that should be moved with a cut-and-paste operation.
8345 Those markers are stored together with their positions relative to
8346 the start of the region.")
8348 (defun org-save-markers-in-region (beg end)
8349 "Check markers in region.
8350 If these markers are between BEG and END, record their position relative
8351 to BEG, so that after moving the block of text, we can put the markers back
8352 into place.
8353 This function gets called just before an entry or tree gets cut from the
8354 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8355 called immediately, to move the markers with the entries."
8356 (setq org-markers-to-move nil)
8357 (when (featurep 'org-clock)
8358 (org-clock-save-markers-for-cut-and-paste beg end))
8359 (when (featurep 'org-agenda)
8360 (org-agenda-save-markers-for-cut-and-paste beg end)))
8362 (defun org-check-and-save-marker (marker beg end)
8363 "Check if MARKER is between BEG and END.
8364 If yes, remember the marker and the distance to BEG."
8365 (when (and (marker-buffer marker)
8366 (equal (marker-buffer marker) (current-buffer))
8367 (>= marker beg) (< marker end))
8368 (push (cons marker (- marker beg)) org-markers-to-move)))
8370 (defun org-reinstall-markers-in-region (beg)
8371 "Move all remembered markers to their position relative to BEG."
8372 (dolist (x org-markers-to-move)
8373 (move-marker (car x) (+ beg (cdr x))))
8374 (setq org-markers-to-move nil))
8376 (defun org-narrow-to-subtree ()
8377 "Narrow buffer to the current subtree."
8378 (interactive)
8379 (save-excursion
8380 (save-match-data
8381 (org-with-limited-levels
8382 (narrow-to-region
8383 (progn (org-back-to-heading t) (point))
8384 (progn (org-end-of-subtree t t)
8385 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8386 (point)))))))
8388 (defun org-narrow-to-block ()
8389 "Narrow buffer to the current block."
8390 (interactive)
8391 (let* ((case-fold-search t)
8392 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8393 "^[ \t]*#\\+end_.*")))
8394 (if blockp
8395 (narrow-to-region (car blockp) (cdr blockp))
8396 (user-error "Not in a block"))))
8398 (defun org-clone-subtree-with-time-shift (n &optional shift)
8399 "Clone the task (subtree) at point N times.
8400 The clones will be inserted as siblings.
8402 In interactive use, the user will be prompted for the number of
8403 clones to be produced. If the entry has a timestamp, the user
8404 will also be prompted for a time shift, which may be a repeater
8405 as used in time stamps, for example `+3d'. To disable this,
8406 you can call the function with a universal prefix argument.
8408 When a valid repeater is given and the entry contains any time
8409 stamps, the clones will become a sequence in time, with time
8410 stamps in the subtree shifted for each clone produced. If SHIFT
8411 is nil or the empty string, time stamps will be left alone. The
8412 ID property of the original subtree is removed.
8414 In each clone, all the CLOCK entries will be removed. This
8415 prevents Org from considering that the clocked times overlap.
8417 If the original subtree did contain time stamps with a repeater,
8418 the following will happen:
8419 - the repeater will be removed in each clone
8420 - an additional clone will be produced, with the current, unshifted
8421 date(s) in the entry.
8422 - the original entry will be placed *after* all the clones, with
8423 repeater intact.
8424 - the start days in the repeater in the original entry will be shifted
8425 to past the last clone.
8426 In this way you can spell out a number of instances of a repeating task,
8427 and still retain the repeater to cover future instances of the task.
8429 As described above, N+1 clones are produced when the original
8430 subtree has a repeater. Setting N to 0, then, can be used to
8431 remove the repeater from a subtree and create a shifted clone
8432 with the original repeater."
8433 (interactive "nNumber of clones to produce: ")
8434 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8435 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8436 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8437 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8438 (shift
8439 (or shift
8440 (if (and (not (equal current-prefix-arg '(4)))
8441 (save-excursion
8442 (goto-char beg)
8443 (re-search-forward org-ts-regexp-both end-of-tree t)))
8444 (read-from-minibuffer
8445 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8446 ""))) ;No time shift
8447 (doshift
8448 (and (org-string-nw-p shift)
8449 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8450 shift)
8451 (user-error "Invalid shift specification %s" shift)))))
8452 (goto-char end-of-tree)
8453 (unless (bolp) (insert "\n"))
8454 (let* ((end (point))
8455 (template (buffer-substring beg end))
8456 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8457 (shift-what (pcase (and doshift (match-string 2 shift))
8458 (`nil nil)
8459 ("d" 'day)
8460 ("w" (setq shift-n (* 7 shift-n)) 'day)
8461 ("m" 'month)
8462 ("y" 'year)
8463 (_ (error "Unsupported time unit"))))
8464 (nmin 1)
8465 (nmax n)
8466 (n-no-remove -1)
8467 (idprop (org-entry-get nil "ID")))
8468 (when (and doshift
8469 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8470 template))
8471 (delete-region beg end)
8472 (setq end beg)
8473 (setq nmin 0)
8474 (setq nmax (1+ nmax))
8475 (setq n-no-remove nmax))
8476 (goto-char end)
8477 (cl-loop for n from nmin to nmax do
8478 (insert
8479 ;; Prepare clone.
8480 (with-temp-buffer
8481 (insert template)
8482 (org-mode)
8483 (goto-char (point-min))
8484 (org-show-subtree)
8485 (and idprop (if org-clone-delete-id
8486 (org-entry-delete nil "ID")
8487 (org-id-get-create t)))
8488 (unless (= n 0)
8489 (while (re-search-forward org-clock-line-re nil t)
8490 (delete-region (line-beginning-position)
8491 (line-beginning-position 2)))
8492 (goto-char (point-min))
8493 (while (re-search-forward org-drawer-regexp nil t)
8494 (org-remove-empty-drawer-at (point))))
8495 (goto-char (point-min))
8496 (when doshift
8497 (while (re-search-forward org-ts-regexp-both nil t)
8498 (org-timestamp-change (* n shift-n) shift-what))
8499 (unless (= n n-no-remove)
8500 (goto-char (point-min))
8501 (while (re-search-forward org-ts-regexp nil t)
8502 (save-excursion
8503 (goto-char (match-beginning 0))
8504 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8505 (delete-region (match-beginning 1) (match-end 1)))))))
8506 (buffer-string)))))
8507 (goto-char beg)))
8509 ;;; Outline Sorting
8511 (defun org-sort (&optional with-case)
8512 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8513 Optional argument WITH-CASE means sort case-sensitively."
8514 (interactive "P")
8515 (org-call-with-arg
8516 (cond ((org-at-table-p) #'org-table-sort-lines)
8517 ((org-at-item-p) #'org-sort-list)
8518 (t #'org-sort-entries))
8519 with-case))
8521 (defun org-sort-remove-invisible (s)
8522 "Remove invisible part of links and emphasis markers from string S."
8523 (remove-text-properties 0 (length s) org-rm-props s)
8524 (replace-regexp-in-string
8525 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8526 (replace-regexp-in-string
8527 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8528 (org-link-display-format s)
8529 t t) t t))
8531 (defvar org-priority-regexp) ; defined later in the file
8533 (defvar org-after-sorting-entries-or-items-hook nil
8534 "Hook that is run after a bunch of entries or items have been sorted.
8535 When children are sorted, the cursor is in the parent line when this
8536 hook gets called. When a region or a plain list is sorted, the cursor
8537 will be in the first entry of the sorted region/list.")
8539 (defun org-sort-entries
8540 (&optional with-case sorting-type getkey-func compare-func property
8541 interactive?)
8542 "Sort entries on a certain level of an outline tree.
8543 If there is an active region, the entries in the region are sorted.
8544 Else, if the cursor is before the first entry, sort the top-level items.
8545 Else, the children of the entry at point are sorted.
8547 Sorting can be alphabetically, numerically, by date/time as given by
8548 a time stamp, by a property, by priority order, or by a custom function.
8550 The command prompts for the sorting type unless it has been given to the
8551 function through the SORTING-TYPE argument, which needs to be a character,
8552 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8553 the precise meaning of each character:
8555 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8556 c By creation time, which is assumed to be the first inactive time stamp
8557 at the beginning of a line.
8558 d By deadline date/time.
8559 k By clocking time.
8560 n Numerically, by converting the beginning of the entry/item to a number.
8561 o By order of TODO keywords.
8562 p By priority according to the cookie.
8563 r By the value of a property.
8564 s By scheduled date/time.
8565 t By date/time, either the first active time stamp in the entry, or, if
8566 none exist, by the first inactive one.
8568 Capital letters will reverse the sort order.
8570 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8571 called with point at the beginning of the record. It must return a
8572 value that is compatible with COMPARE-FUNC, the function used to
8573 compare entries.
8575 Comparing entries ignores case by default. However, with an optional argument
8576 WITH-CASE, the sorting considers case as well.
8578 Sorting is done against the visible part of the headlines, it ignores hidden
8579 links.
8581 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8583 A non-nil value for INTERACTIVE? is used to signal that this
8584 function is being called interactively."
8585 (interactive (list current-prefix-arg nil nil nil nil t))
8586 (let ((case-func (if with-case 'identity 'downcase))
8587 start beg end stars re re2
8588 txt what tmp)
8589 ;; Find beginning and end of region to sort
8590 (cond
8591 ((org-region-active-p)
8592 ;; we will sort the region
8593 (setq end (region-end)
8594 what "region")
8595 (goto-char (region-beginning))
8596 (unless (org-at-heading-p) (outline-next-heading))
8597 (setq start (point)))
8598 ((or (org-at-heading-p)
8599 (ignore-errors (progn (org-back-to-heading) t)))
8600 ;; we will sort the children of the current headline
8601 (org-back-to-heading)
8602 (setq start (point)
8603 end (progn (org-end-of-subtree t t)
8604 (or (bolp) (insert "\n"))
8605 (when (>= (org-back-over-empty-lines) 1)
8606 (forward-line 1))
8607 (point))
8608 what "children")
8609 (goto-char start)
8610 (outline-show-subtree)
8611 (outline-next-heading))
8613 ;; we will sort the top-level entries in this file
8614 (goto-char (point-min))
8615 (or (org-at-heading-p) (outline-next-heading))
8616 (setq start (point))
8617 (goto-char (point-max))
8618 (beginning-of-line 1)
8619 (when (looking-at ".*?\\S-")
8620 ;; File ends in a non-white line
8621 (end-of-line 1)
8622 (insert "\n"))
8623 (setq end (point-max))
8624 (setq what "top-level")
8625 (goto-char start)
8626 (outline-show-all)))
8628 (setq beg (point))
8629 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8631 (looking-at "\\(\\*+\\)")
8632 (setq stars (match-string 1)
8633 re (concat "^" (regexp-quote stars) " +")
8634 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8635 txt (buffer-substring beg end))
8636 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8637 (when (and (not (equal stars "*")) (string-match re2 txt))
8638 (user-error "Region to sort contains a level above the first entry"))
8640 (unless sorting-type
8641 (message
8642 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8643 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8644 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8645 what)
8646 (setq sorting-type (read-char-exclusive)))
8648 (unless getkey-func
8649 (and (= (downcase sorting-type) ?f)
8650 (setq getkey-func
8651 (or (and interactive?
8652 (org-read-function
8653 "Function for extracting keys: "))
8654 (error "Missing key extractor")))))
8656 (and (= (downcase sorting-type) ?r)
8657 (not property)
8658 (setq property
8659 (completing-read "Property: "
8660 (mapcar #'list (org-buffer-property-keys t))
8661 nil t)))
8663 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8664 (message "Sorting entries...")
8666 (save-restriction
8667 (narrow-to-region start end)
8668 (let ((restore-clock?
8669 ;; The clock marker is lost when using `sort-subr'; mark
8670 ;; the clock with temporary `:org-clock-marker-backup'
8671 ;; text property.
8672 (when (and (eq (org-clock-is-active) (current-buffer))
8673 (<= start (marker-position org-clock-marker))
8674 (>= end (marker-position org-clock-marker)))
8675 (org-with-silent-modifications
8676 (put-text-property (1- org-clock-marker) org-clock-marker
8677 :org-clock-marker-backup t))
8679 (dcst (downcase sorting-type))
8680 (case-fold-search nil)
8681 (now (current-time)))
8682 (org-preserve-local-variables
8683 (sort-subr
8684 (/= dcst sorting-type)
8685 ;; This function moves to the beginning character of the
8686 ;; "record" to be sorted.
8687 (lambda nil
8688 (if (re-search-forward re nil t)
8689 (goto-char (match-beginning 0))
8690 (goto-char (point-max))))
8691 ;; This function moves to the last character of the "record" being
8692 ;; sorted.
8693 (lambda nil
8694 (save-match-data
8695 (condition-case nil
8696 (outline-forward-same-level 1)
8697 (error
8698 (goto-char (point-max))))))
8699 ;; This function returns the value that gets sorted against.
8700 (lambda ()
8701 (cond
8702 ((= dcst ?n)
8703 (if (looking-at org-complex-heading-regexp)
8704 (string-to-number
8705 (org-sort-remove-invisible (match-string 4)))
8706 nil))
8707 ((= dcst ?a)
8708 (if (looking-at org-complex-heading-regexp)
8709 (funcall case-func
8710 (org-sort-remove-invisible (match-string 4)))
8711 nil))
8712 ((= dcst ?k)
8713 (or (get-text-property (point) :org-clock-minutes) 0))
8714 ((= dcst ?t)
8715 (let ((end (save-excursion (outline-next-heading) (point))))
8716 (if (or (re-search-forward org-ts-regexp end t)
8717 (re-search-forward org-ts-regexp-both end t))
8718 (org-time-string-to-seconds (match-string 0))
8719 (float-time now))))
8720 ((= dcst ?c)
8721 (let ((end (save-excursion (outline-next-heading) (point))))
8722 (if (re-search-forward
8723 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8724 end t)
8725 (org-time-string-to-seconds (match-string 0))
8726 (float-time now))))
8727 ((= dcst ?s)
8728 (let ((end (save-excursion (outline-next-heading) (point))))
8729 (if (re-search-forward org-scheduled-time-regexp end t)
8730 (org-time-string-to-seconds (match-string 1))
8731 (float-time now))))
8732 ((= dcst ?d)
8733 (let ((end (save-excursion (outline-next-heading) (point))))
8734 (if (re-search-forward org-deadline-time-regexp end t)
8735 (org-time-string-to-seconds (match-string 1))
8736 (float-time now))))
8737 ((= dcst ?p)
8738 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8739 (string-to-char (match-string 2))
8740 org-default-priority))
8741 ((= dcst ?r)
8742 (or (org-entry-get nil property) ""))
8743 ((= dcst ?o)
8744 (when (looking-at org-complex-heading-regexp)
8745 (let* ((m (match-string 2))
8746 (s (if (member m org-done-keywords) '- '+)))
8747 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8748 ((= dcst ?f)
8749 (if getkey-func
8750 (progn
8751 (setq tmp (funcall getkey-func))
8752 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8753 tmp)
8754 (error "Invalid key function `%s'" getkey-func)))
8755 (t (error "Invalid sorting type `%c'" sorting-type))))
8757 (cond
8758 ((= dcst ?a) 'string<)
8759 ((= dcst ?f)
8760 (or compare-func
8761 (and interactive?
8762 (org-read-function
8763 (concat "Function for comparing keys "
8764 "(empty for default `sort-subr' predicate): ")
8765 'allow-empty))))
8766 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8767 (when restore-clock?
8768 (move-marker org-clock-marker
8769 (1+ (next-single-property-change
8770 start :org-clock-marker-backup)))
8771 (remove-text-properties (1- org-clock-marker) org-clock-marker
8772 '(:org-clock-marker-backup t)))))
8773 (run-hooks 'org-after-sorting-entries-or-items-hook)
8774 (message "Sorting entries...done")))
8776 (defun org-contextualize-keys (alist contexts)
8777 "Return valid elements in ALIST depending on CONTEXTS.
8779 `org-agenda-custom-commands' or `org-capture-templates' are the
8780 values used for ALIST, and `org-agenda-custom-commands-contexts'
8781 or `org-capture-templates-contexts' are the associated contexts
8782 definitions."
8783 (let ((contexts
8784 ;; normalize contexts
8785 (mapcar
8786 (lambda(c) (cond ((listp (cadr c))
8787 (list (car c) (car c) (nth 1 c)))
8788 ((string= "" (cadr c))
8789 (list (car c) (car c) (nth 2 c)))
8790 (t c)))
8791 contexts))
8792 (a alist) r s)
8793 ;; loop over all commands or templates
8794 (dolist (c a)
8795 (let (vrules repl)
8796 (cond
8797 ((not (assoc (car c) contexts))
8798 (push c r))
8799 ((and (assoc (car c) contexts)
8800 (setq vrules (org-contextualize-validate-key
8801 (car c) contexts)))
8802 (mapc (lambda (vr)
8803 (unless (equal (car vr) (cadr vr))
8804 (setq repl vr)))
8805 vrules)
8806 (if (not repl) (push c r)
8807 (push (cadr repl) s)
8808 (push
8809 (cons (car c)
8810 (cdr (or (assoc (cadr repl) alist)
8811 (error "Undefined key `%s' as contextual replacement for `%s'"
8812 (cadr repl) (car c)))))
8813 r))))))
8814 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8815 (delq
8817 (delete-dups
8818 (mapcar (lambda (x)
8819 (let ((tpl (car x)))
8820 (unless (delq
8822 (mapcar (lambda (y)
8823 (equal y tpl))
8825 x)))
8826 (reverse r))))))
8828 (defun org-contextualize-validate-key (key contexts)
8829 "Check CONTEXTS for agenda or capture KEY."
8830 (let (res)
8831 (dolist (r contexts)
8832 (dolist (rr (car (last r)))
8833 (when
8834 (and (equal key (car r))
8835 (if (functionp rr) (funcall rr)
8836 (or (and (eq (car rr) 'in-file)
8837 (buffer-file-name)
8838 (string-match (cdr rr) (buffer-file-name)))
8839 (and (eq (car rr) 'in-mode)
8840 (string-match (cdr rr) (symbol-name major-mode)))
8841 (and (eq (car rr) 'in-buffer)
8842 (string-match (cdr rr) (buffer-name)))
8843 (when (and (eq (car rr) 'not-in-file)
8844 (buffer-file-name))
8845 (not (string-match (cdr rr) (buffer-file-name))))
8846 (when (eq (car rr) 'not-in-mode)
8847 (not (string-match (cdr rr) (symbol-name major-mode))))
8848 (when (eq (car rr) 'not-in-buffer)
8849 (not (string-match (cdr rr) (buffer-name)))))))
8850 (push r res))))
8851 (delete-dups (delq nil res))))
8853 (defun org-context-p (&rest contexts)
8854 "Check if local context is any of CONTEXTS.
8855 Possible values in the list of contexts are `table', `headline', and `item'."
8856 (let ((pos (point)))
8857 (goto-char (point-at-bol))
8858 (prog1 (or (and (memq 'table contexts)
8859 (looking-at "[ \t]*|"))
8860 (and (memq 'headline contexts)
8861 (looking-at org-outline-regexp))
8862 (and (memq 'item contexts)
8863 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8864 (and (memq 'item-body contexts)
8865 (org-in-item-p)))
8866 (goto-char pos))))
8868 ;;;###autoload
8869 (defun org-run-like-in-org-mode (cmd)
8870 "Run a command, pretending that the current buffer is in Org mode.
8871 This will temporarily bind local variables that are typically bound in
8872 Org mode to the values they have in Org mode, and then interactively
8873 call CMD."
8874 (org-load-modules-maybe)
8875 (let (binds)
8876 (dolist (var (org-get-local-variables))
8877 (when (or (not (boundp (car var)))
8878 (eq (symbol-value (car var))
8879 (default-value (car var))))
8880 (push (list (car var) `(quote ,(cadr var))) binds)))
8881 (eval `(let ,binds
8882 (call-interactively (quote ,cmd))))))
8884 (defun org-get-category (&optional pos force-refresh)
8885 "Get the category applying to position POS."
8886 (save-match-data
8887 (when force-refresh (org-refresh-category-properties))
8888 (let ((pos (or pos (point))))
8889 (or (get-text-property pos 'org-category)
8890 (progn (org-refresh-category-properties)
8891 (get-text-property pos 'org-category))))))
8893 ;;; Refresh properties
8895 (defun org-refresh-properties (dprop tprop)
8896 "Refresh buffer text properties.
8897 DPROP is the drawer property and TPROP is either the
8898 corresponding text property to set, or an alist with each element
8899 being a text property (as a symbol) and a function to apply to
8900 the value of the drawer property."
8901 (let* ((case-fold-search t)
8902 (inhibit-read-only t)
8903 (inherit? (org-property-inherit-p dprop))
8904 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8905 (global (and inherit? (org--property-global-value dprop nil))))
8906 (org-with-silent-modifications
8907 (org-with-point-at 1
8908 ;; Set global values (e.g., values defined through
8909 ;; "#+PROPERTY:" keywords) to the whole buffer.
8910 (when global (put-text-property (point-min) (point-max) tprop global))
8911 ;; Set local values.
8912 (while (re-search-forward property-re nil t)
8913 (when (org-at-property-p)
8914 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8915 (outline-next-heading))))))
8917 (defun org-refresh-property (tprop p &optional inherit)
8918 "Refresh the buffer text property TPROP from the drawer property P.
8919 The refresh happens only for the current headline, or the whole
8920 sub-tree if optional argument INHERIT is non-nil."
8921 (unless (org-before-first-heading-p)
8922 (save-excursion
8923 (org-back-to-heading t)
8924 (let ((start (point))
8925 (end (save-excursion
8926 (if inherit (org-end-of-subtree t t)
8927 (or (outline-next-heading) (point-max))))))
8928 (if (symbolp tprop)
8929 ;; TPROP is a text property symbol.
8930 (put-text-property start end tprop p)
8931 ;; TPROP is an alist with (property . function) elements.
8932 (pcase-dolist (`(,prop . ,f) tprop)
8933 (put-text-property start end prop (funcall f p))))))))
8935 (defun org-refresh-category-properties ()
8936 "Refresh category text properties in the buffer."
8937 (let ((case-fold-search t)
8938 (inhibit-read-only t)
8939 (default-category
8940 (cond ((null org-category)
8941 (if buffer-file-name
8942 (file-name-sans-extension
8943 (file-name-nondirectory buffer-file-name))
8944 "???"))
8945 ((symbolp org-category) (symbol-name org-category))
8946 (t org-category))))
8947 (org-with-silent-modifications
8948 (org-with-wide-buffer
8949 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8950 ;; This is the default category for the buffer. If none is
8951 ;; found, fall-back to `org-category' or buffer file name.
8952 (put-text-property
8953 (point-min) (point-max)
8954 'org-category
8955 (catch 'buffer-category
8956 (goto-char (point-max))
8957 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8958 (let ((element (org-element-at-point)))
8959 (when (eq (org-element-type element) 'keyword)
8960 (throw 'buffer-category
8961 (org-element-property :value element)))))
8962 default-category))
8963 ;; Set sub-tree specific categories.
8964 (goto-char (point-min))
8965 (let ((regexp (org-re-property "CATEGORY")))
8966 (while (re-search-forward regexp nil t)
8967 (let ((value (match-string-no-properties 3)))
8968 (when (org-at-property-p)
8969 (put-text-property
8970 (save-excursion (org-back-to-heading t) (point))
8971 (save-excursion (org-end-of-subtree t t) (point))
8972 'org-category
8973 value)))))))))
8975 (defun org-refresh-stats-properties ()
8976 "Refresh stats text properties in the buffer."
8977 (org-with-silent-modifications
8978 (org-with-point-at 1
8979 (let ((regexp (concat org-outline-regexp-bol
8980 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
8981 (while (re-search-forward regexp nil t)
8982 (let* ((numerator (string-to-number (match-string 1)))
8983 (denominator (and (match-end 2)
8984 (string-to-number (match-string 2))))
8985 (stats (cond ((not denominator) numerator) ;percent
8986 ((= denominator 0) 0)
8987 (t (/ (* numerator 100) denominator)))))
8988 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
8989 'org-stats stats)))))))
8991 (defun org-refresh-effort-properties ()
8992 "Refresh effort properties"
8993 (org-refresh-properties
8994 org-effort-property
8995 '((effort . identity)
8996 (effort-minutes . org-duration-to-minutes))))
8998 ;;;; Link Stuff
9000 ;;; Link abbreviations
9002 (defun org-link-expand-abbrev (link)
9003 "Apply replacements as defined in `org-link-abbrev-alist'."
9004 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9005 (let* ((key (match-string 1 link))
9006 (as (or (assoc key org-link-abbrev-alist-local)
9007 (assoc key org-link-abbrev-alist)))
9008 (tag (and (match-end 2) (match-string 3 link)))
9009 rpl)
9010 (if (not as)
9011 link
9012 (setq rpl (cdr as))
9013 (cond
9014 ((symbolp rpl) (funcall rpl tag))
9015 ((string-match "%(\\([^)]+\\))" rpl)
9016 (replace-match
9017 (save-match-data
9018 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9019 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9020 ((string-match "%h" rpl)
9021 (replace-match (url-hexify-string (or tag "")) t t rpl))
9022 (t (concat rpl tag)))))
9023 link))
9025 ;;; Storing and inserting links
9027 (defvar org-insert-link-history nil
9028 "Minibuffer history for links inserted with `org-insert-link'.")
9030 (defvar org-stored-links nil
9031 "Contains the links stored with `org-store-link'.")
9033 (defvar org-store-link-plist nil
9034 "Plist with info about the most recently link created with `org-store-link'.")
9036 (defun org-store-link-functions ()
9037 "Return a list of functions that are called to create and store a link.
9038 The functions defined in the :store property of
9039 `org-link-parameters'.
9041 Each function will be called in turn until one returns a non-nil
9042 value. Each function should check if it is responsible for
9043 creating this link (for example by looking at the major mode).
9044 If not, it must exit and return nil. If yes, it should return
9045 a non-nil value after calling `org-store-link-props' with a list
9046 of properties and values. Special properties are:
9048 :type The link prefix, like \"http\". This must be given.
9049 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9050 This is obligatory as well.
9051 :description Optional default description for the second pair
9052 of brackets in an Org mode link. The user can still change
9053 this when inserting this link into an Org mode buffer.
9055 In addition to these, any additional properties can be specified
9056 and then used in capture templates."
9057 (cl-loop for link in org-link-parameters
9058 with store-func
9059 do (setq store-func (org-link-get-parameter (car link) :store))
9060 if store-func
9061 collect store-func))
9063 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9064 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9066 ;;;###autoload
9067 (defun org-store-link (arg)
9068 "Store an org-link to the current location.
9069 \\<org-mode-map>
9070 This link is added to `org-stored-links' and can later be inserted
9071 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9073 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9074 A single
9075 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9076 `org-gnus-prefer-web-links' for links to Usenet articles.
9078 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9079 skipping storing functions that are not
9080 part of Org core.
9082 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9083 prefix ARG forces storing a link for each line in the
9084 active region."
9085 (interactive "P")
9086 (org-load-modules-maybe)
9087 (if (and (equal arg '(64)) (org-region-active-p))
9088 (save-excursion
9089 (let ((end (region-end)))
9090 (goto-char (region-beginning))
9091 (set-mark (point))
9092 (while (< (point-at-eol) end)
9093 (move-end-of-line 1) (activate-mark)
9094 (let (current-prefix-arg)
9095 (call-interactively 'org-store-link))
9096 (move-beginning-of-line 2)
9097 (set-mark (point)))))
9098 (setq org-store-link-plist nil)
9099 (let (link cpltxt desc description search txt custom-id agenda-link)
9100 (cond
9101 ;; Store a link using an external link type, if any function is
9102 ;; available. If more than one can generate a link from current
9103 ;; location, ask which one to use.
9104 ((and (not (equal arg '(16)))
9105 (let ((results-alist nil))
9106 (dolist (f (org-store-link-functions))
9107 (when (funcall f)
9108 ;; XXX: return value is not link's plist, so we
9109 ;; store the new value before it is modified. It
9110 ;; would be cleaner to ask store link functions to
9111 ;; return the plist instead.
9112 (push (cons f (copy-sequence org-store-link-plist))
9113 results-alist)))
9114 (pcase results-alist
9115 (`nil nil)
9116 (`((,_ . ,_)) t) ;single choice: nothing to do
9117 (`((,name . ,_) . ,_)
9118 ;; Reinstate link plist associated to the chosen
9119 ;; function.
9120 (apply #'org-store-link-props
9121 (cdr (assoc-string
9122 (completing-read
9123 "Which function for creating the link? "
9124 (mapcar #'car results-alist) nil t name)
9125 results-alist)))
9126 t))))
9127 (setq link (plist-get org-store-link-plist :link))
9128 (setq desc (or (plist-get org-store-link-plist :description)
9129 link)))
9131 ;; Store a link from a source code buffer.
9132 ((org-src-edit-buffer-p)
9133 (let ((coderef-format (org-src-coderef-format)))
9134 (cond ((save-excursion
9135 (beginning-of-line)
9136 (looking-at (org-src-coderef-regexp coderef-format)))
9137 (setq link (format "(%s)" (match-string-no-properties 3))))
9138 ((called-interactively-p 'any)
9139 (let ((label (read-string "Code line label: ")))
9140 (end-of-line)
9141 (setq link (format coderef-format label))
9142 (let ((gc (- 79 (length link))))
9143 (if (< (current-column) gc)
9144 (org-move-to-column gc t)
9145 (insert " ")))
9146 (insert link)
9147 (setq link (concat "(" label ")"))
9148 (setq desc nil)))
9149 (t (setq link nil)))))
9151 ;; We are in the agenda, link to referenced location
9152 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9153 (let ((m (or (get-text-property (point) 'org-hd-marker)
9154 (get-text-property (point) 'org-marker))))
9155 (when m
9156 (org-with-point-at m
9157 (setq agenda-link
9158 (if (called-interactively-p 'any)
9159 (call-interactively 'org-store-link)
9160 (org-store-link nil)))))))
9162 ((eq major-mode 'calendar-mode)
9163 (let ((cd (calendar-cursor-to-date)))
9164 (setq link
9165 (format-time-string
9166 (car org-time-stamp-formats)
9167 (apply 'encode-time
9168 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9169 nil nil nil))))
9170 (org-store-link-props :type "calendar" :date cd)))
9172 ((eq major-mode 'help-mode)
9173 (setq link (concat "help:" (save-excursion
9174 (goto-char (point-min))
9175 (looking-at "^[^ ]+")
9176 (match-string 0))))
9177 (org-store-link-props :type "help"))
9179 ((eq major-mode 'w3-mode)
9180 (setq cpltxt (if (and (buffer-name)
9181 (not (string-match "Untitled" (buffer-name))))
9182 (buffer-name)
9183 (url-view-url t))
9184 link (url-view-url t))
9185 (org-store-link-props :type "w3" :url (url-view-url t)))
9187 ((eq major-mode 'image-mode)
9188 (setq cpltxt (concat "file:"
9189 (abbreviate-file-name buffer-file-name))
9190 link cpltxt)
9191 (org-store-link-props :type "image" :file buffer-file-name))
9193 ;; In dired, store a link to the file of the current line
9194 ((derived-mode-p 'dired-mode)
9195 (let ((file (dired-get-filename nil t)))
9196 (setq file (if file
9197 (abbreviate-file-name
9198 (expand-file-name (dired-get-filename nil t)))
9199 ;; otherwise, no file so use current directory.
9200 default-directory))
9201 (setq cpltxt (concat "file:" file)
9202 link cpltxt)))
9204 ((setq search (run-hook-with-args-until-success
9205 'org-create-file-search-functions))
9206 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9207 "::" search))
9208 (setq cpltxt (or description link)))
9210 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9211 (org-with-limited-levels
9212 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9213 (cond
9214 ;; Store a link using the target at point
9215 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9216 (setq cpltxt
9217 (concat "file:"
9218 (abbreviate-file-name
9219 (buffer-file-name (buffer-base-buffer)))
9220 "::" (match-string 1))
9221 link cpltxt))
9222 ((and (featurep 'org-id)
9223 (or (eq org-id-link-to-org-use-id t)
9224 (and (called-interactively-p 'any)
9225 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9226 (and (eq org-id-link-to-org-use-id
9227 'create-if-interactive-and-no-custom-id)
9228 (not custom-id))))
9229 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9230 ;; Store a link using the ID at point
9231 (setq link (condition-case nil
9232 (prog1 (org-id-store-link)
9233 (setq desc (or (plist-get org-store-link-plist
9234 :description)
9235 "")))
9236 (error
9237 ;; Probably before first headline, link only to file
9238 (concat "file:"
9239 (abbreviate-file-name
9240 (buffer-file-name (buffer-base-buffer))))))))
9242 ;; Just link to current headline
9243 (setq cpltxt (concat "file:"
9244 (abbreviate-file-name
9245 (buffer-file-name (buffer-base-buffer)))))
9246 ;; Add a context search string
9247 (when (org-xor org-context-in-file-links
9248 (equal arg '(4)))
9249 (let* ((element (org-element-at-point))
9250 (name (org-element-property :name element)))
9251 (setq txt (cond
9252 ((org-at-heading-p) nil)
9253 (name)
9254 ((org-region-active-p)
9255 (buffer-substring (region-beginning) (region-end)))))
9256 (when (or (null txt) (string-match "\\S-" txt))
9257 (setq cpltxt
9258 (concat cpltxt "::"
9259 (condition-case nil
9260 (org-make-org-heading-search-string txt)
9261 (error "")))
9262 desc (or name
9263 (nth 4 (ignore-errors (org-heading-components)))
9264 "NONE")))))
9265 (when (string-match "::\\'" cpltxt)
9266 (setq cpltxt (substring cpltxt 0 -2)))
9267 (setq link cpltxt)))))
9269 ((buffer-file-name (buffer-base-buffer))
9270 ;; Just link to this file here.
9271 (setq cpltxt (concat "file:"
9272 (abbreviate-file-name
9273 (buffer-file-name (buffer-base-buffer)))))
9274 ;; Add a context string.
9275 (when (org-xor org-context-in-file-links
9276 (equal arg '(4)))
9277 (setq txt (if (org-region-active-p)
9278 (buffer-substring (region-beginning) (region-end))
9279 (buffer-substring (point-at-bol) (point-at-eol))))
9280 ;; Only use search option if there is some text.
9281 (when (string-match "\\S-" txt)
9282 (setq cpltxt
9283 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9284 desc "NONE")))
9285 (setq link cpltxt))
9287 ((called-interactively-p 'interactive)
9288 (user-error "No method for storing a link from this buffer"))
9290 (t (setq link nil)))
9292 ;; We're done setting link and desc, clean up
9293 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9294 (setq link (or link cpltxt)
9295 desc (or desc cpltxt))
9296 (cond ((not desc))
9297 ((equal desc "NONE") (setq desc nil))
9298 (t (setq desc
9299 (replace-regexp-in-string
9300 org-bracket-link-analytic-regexp
9301 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9302 desc))))
9303 ;; Return the link
9304 (if (not (and (or (called-interactively-p 'any)
9305 executing-kbd-macro)
9306 link))
9307 (or agenda-link (and link (org-make-link-string link desc)))
9308 (push (list link desc) org-stored-links)
9309 (message "Stored: %s" (or desc link))
9310 (when custom-id
9311 (setq link (concat "file:" (abbreviate-file-name
9312 (buffer-file-name)) "::#" custom-id))
9313 (push (list link desc) org-stored-links))
9314 (car org-stored-links)))))
9316 (defun org-store-link-props (&rest plist)
9317 "Store link properties.
9318 The properties are pre-processed by extracting names, addresses
9319 and dates."
9320 (let ((x (plist-get plist :from)))
9321 (when x
9322 (let ((adr (mail-extract-address-components x)))
9323 (setq plist (plist-put plist :fromname (car adr)))
9324 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9325 (let ((x (plist-get plist :to)))
9326 (when x
9327 (let ((adr (mail-extract-address-components x)))
9328 (setq plist (plist-put plist :toname (car adr)))
9329 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9330 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9331 (when x
9332 (setq plist (plist-put plist :date-timestamp
9333 (format-time-string
9334 (org-time-stamp-format t) x)))
9335 (setq plist (plist-put plist :date-timestamp-inactive
9336 (format-time-string
9337 (org-time-stamp-format t t) x)))))
9338 (let ((from (plist-get plist :from))
9339 (to (plist-get plist :to)))
9340 (when (and from to org-from-is-user-regexp)
9341 (setq plist
9342 (plist-put plist :fromto
9343 (if (string-match org-from-is-user-regexp from)
9344 (concat "to %t")
9345 (concat "from %f"))))))
9346 (setq org-store-link-plist plist))
9348 (defun org-add-link-props (&rest plist)
9349 "Add these properties to the link property list."
9350 (let (key value)
9351 (while plist
9352 (setq key (pop plist) value (pop plist))
9353 (setq org-store-link-plist
9354 (plist-put org-store-link-plist key value)))))
9356 (defun org-email-link-description (&optional fmt)
9357 "Return the description part of an email link.
9358 This takes information from `org-store-link-plist' and formats it
9359 according to FMT (default from `org-email-link-description-format')."
9360 (setq fmt (or fmt org-email-link-description-format))
9361 (let* ((p org-store-link-plist)
9362 (to (plist-get p :toaddress))
9363 (from (plist-get p :fromaddress))
9364 (table
9365 (list
9366 (cons "%c" (plist-get p :fromto))
9367 (cons "%F" (plist-get p :from))
9368 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9369 (cons "%T" (plist-get p :to))
9370 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9371 (cons "%s" (plist-get p :subject))
9372 (cons "%d" (plist-get p :date))
9373 (cons "%m" (plist-get p :message-id)))))
9374 (when (string-match "%c" fmt)
9375 ;; Check if the user wrote this message
9376 (if (and org-from-is-user-regexp from to
9377 (save-match-data (string-match org-from-is-user-regexp from)))
9378 (setq fmt (replace-match "to %t" t t fmt))
9379 (setq fmt (replace-match "from %f" t t fmt))))
9380 (org-replace-escapes fmt table)))
9382 (defun org-make-org-heading-search-string (&optional string)
9383 "Make search string for the current headline or STRING."
9384 (let ((s (or string
9385 (and (derived-mode-p 'org-mode)
9386 (save-excursion
9387 (org-back-to-heading t)
9388 (org-element-property :raw-value (org-element-at-point))))))
9389 (lines org-context-in-file-links))
9390 (unless string (setq s (concat "*" s))) ;Add * for headlines
9391 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9392 (when (and string (integerp lines) (> lines 0))
9393 (let ((slines (org-split-string s "\n")))
9394 (when (< lines (length slines))
9395 (setq s (mapconcat
9396 'identity
9397 (reverse (nthcdr (- (length slines) lines)
9398 (reverse slines))) "\n")))))
9399 (mapconcat #'identity (split-string s) " ")))
9401 (defconst org-link-escape-chars
9402 ;;%20 %5B %5D %25
9403 '(?\s ?\[ ?\] ?%)
9404 "List of characters that should be escaped in a link when stored to Org.
9405 This is the list that is used for internal purposes.")
9407 (defun org-make-link-string (link &optional description)
9408 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9409 (unless (org-string-nw-p link) (error "Empty link"))
9410 (let ((uri (cond ((string-match org-link-types-re link)
9411 (concat (match-string 1 link)
9412 (org-link-escape (substring link (match-end 1)))))
9413 ((or (file-name-absolute-p link)
9414 (string-match-p "\\`\\.\\.?/" link))
9415 (org-link-escape link))
9416 ;; For readability, do not encode space characters
9417 ;; in fuzzy links.
9418 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9419 (description
9420 (and (org-string-nw-p description)
9421 ;; Remove brackets from description, as they are fatal.
9422 (replace-regexp-in-string
9423 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9424 (org-trim description)))))
9425 (format "[[%s]%s]"
9427 (if description (format "[%s]" description) ""))))
9429 (defun org-link-escape (text &optional table merge)
9430 "Return percent escaped representation of TEXT.
9431 TEXT is a string with the text to escape.
9432 Optional argument TABLE is a list with characters that should be
9433 escaped. When nil, `org-link-escape-chars' is used.
9434 If optional argument MERGE is set, merge TABLE into
9435 `org-link-escape-chars'."
9436 (let ((characters-to-encode
9437 (cond ((null table) org-link-escape-chars)
9438 (merge (append org-link-escape-chars table))
9439 (t table))))
9440 (mapconcat
9441 (lambda (c)
9442 (if (or (memq c characters-to-encode)
9443 (and org-url-hexify-p (or (< c 32) (> c 126))))
9444 (mapconcat (lambda (e) (format "%%%.2X" e))
9445 (or (encode-coding-char c 'utf-8)
9446 (error "Unable to percent escape character: %c" c))
9448 (char-to-string c)))
9449 text "")))
9451 (defun org-link-unescape (str)
9452 "Unhex hexified Unicode parts in string STR.
9453 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9454 reciprocal of `org-link-escape', which see."
9455 (if (org-string-nw-p str)
9456 (replace-regexp-in-string
9457 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9458 str))
9460 (defun org-link-unescape-compound (hex)
9461 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9462 Note: this function also decodes single byte encodings like
9463 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9464 (save-match-data
9465 (let* ((bytes (cdr (split-string hex "%")))
9466 (ret "")
9467 (eat 0)
9468 (sum 0))
9469 (while bytes
9470 (let* ((val (string-to-number (pop bytes) 16))
9471 (shift-xor
9472 (if (= 0 eat)
9473 (cond
9474 ((>= val 252) (cons 6 252))
9475 ((>= val 248) (cons 5 248))
9476 ((>= val 240) (cons 4 240))
9477 ((>= val 224) (cons 3 224))
9478 ((>= val 192) (cons 2 192))
9479 (t (cons 0 0)))
9480 (cons 6 128))))
9481 (when (>= val 192) (setq eat (car shift-xor)))
9482 (setq val (logxor val (cdr shift-xor)))
9483 (setq sum (+ (lsh sum (car shift-xor)) val))
9484 (when (> eat 0) (setq eat (- eat 1)))
9485 (cond
9486 ((= 0 eat) ;multi byte
9487 (setq ret (concat ret (char-to-string sum)))
9488 (setq sum 0))
9489 ((not bytes) ; single byte(s)
9490 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9491 ret)))
9493 (defun org-link-unescape-single-byte-sequence (hex)
9494 "Unhexify hex-encoded single byte character sequences."
9495 (mapconcat (lambda (byte)
9496 (char-to-string (string-to-number byte 16)))
9497 (cdr (split-string hex "%")) ""))
9499 (defun org-fixup-message-id-for-http (s)
9500 "Replace special characters in a message id, so it can be used in an http query."
9501 (when (string-match "%" s)
9502 (setq s (mapconcat (lambda (c)
9503 (if (eq c ?%)
9504 "%25"
9505 (char-to-string c)))
9506 s "")))
9507 (while (string-match "<" s)
9508 (setq s (replace-match "%3C" t t s)))
9509 (while (string-match ">" s)
9510 (setq s (replace-match "%3E" t t s)))
9511 (while (string-match "@" s)
9512 (setq s (replace-match "%40" t t s)))
9515 (defun org-link-prettify (link)
9516 "Return a human-readable representation of LINK.
9517 The car of LINK must be a raw link.
9518 The cdr of LINK must be either a link description or nil."
9519 (let ((desc (or (cadr link) "<no description>")))
9520 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9521 "<" (car link) ">")))
9523 ;;;###autoload
9524 (defun org-insert-link-global ()
9525 "Insert a link like Org mode does.
9526 This command can be called in any mode to insert a link in Org syntax."
9527 (interactive)
9528 (org-load-modules-maybe)
9529 (org-run-like-in-org-mode 'org-insert-link))
9531 (defun org-insert-all-links (arg &optional pre post)
9532 "Insert all links in `org-stored-links'.
9533 When a universal prefix, do not delete the links from `org-stored-links'.
9534 When `ARG' is a number, insert the last N link(s).
9535 `PRE' and `POST' are optional arguments to define a string to
9536 prepend or to append."
9537 (interactive "P")
9538 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9539 (links (copy-sequence org-stored-links))
9540 (pr (or pre "- "))
9541 (po (or post "\n"))
9542 (cnt 1) l)
9543 (if (null org-stored-links)
9544 (message "No link to insert")
9545 (while (and (or (listp arg) (>= arg cnt))
9546 (setq l (if (listp arg)
9547 (pop links)
9548 (pop org-stored-links))))
9549 (setq cnt (1+ cnt))
9550 (insert pr)
9551 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9552 (insert po)))))
9554 (defun org-insert-last-stored-link (arg)
9555 "Insert the last link stored in `org-stored-links'."
9556 (interactive "p")
9557 (org-insert-all-links arg "" "\n"))
9559 (defun org-link-fontify-links-to-this-file ()
9560 "Fontify links to the current file in `org-stored-links'."
9561 (let ((f (buffer-file-name)) a b)
9562 (setq a (mapcar (lambda(l)
9563 (let ((ll (car l)))
9564 (when (and (string-match "^file:\\(.+\\)::" ll)
9565 (equal f (expand-file-name (match-string 1 ll))))
9566 ll)))
9567 org-stored-links))
9568 (when (featurep 'org-id)
9569 (setq b (mapcar (lambda(l)
9570 (let ((ll (car l)))
9571 (when (and (string-match "^id:\\(.+\\)$" ll)
9572 (equal f (expand-file-name
9573 (or (org-id-find-id-file
9574 (match-string 1 ll)) ""))))
9575 ll)))
9576 org-stored-links)))
9577 (mapcar (lambda(l)
9578 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9579 (delq nil (append a b)))))
9581 (defvar org--links-history nil)
9582 (defun org-insert-link (&optional complete-file link-location default-description)
9583 "Insert a link. At the prompt, enter the link.
9585 Completion can be used to insert any of the link protocol prefixes in use.
9587 The history can be used to select a link previously stored with
9588 `org-store-link'. When the empty string is entered (i.e. if you just
9589 press `RET' at the prompt), the link defaults to the most recently
9590 stored link. As `SPC' triggers completion in the minibuffer, you need to
9591 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9593 You will also be prompted for a description, and if one is given, it will
9594 be displayed in the buffer instead of the link.
9596 If there is already a link at point, this command will allow you to edit
9597 link and description parts.
9599 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9600 file name can be
9601 selected using completion. The path to the file will be relative to the
9602 current directory if the file is in the current directory or a subdirectory.
9603 Otherwise, the link will be the absolute path as completed in the minibuffer
9604 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9605 option `org-link-file-path-type'.
9607 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9608 absolute path even if the file is in
9609 the current directory or below.
9611 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9612 prefix negates `org-keep-stored-link-after-insertion'.
9614 If the LINK-LOCATION parameter is non-nil, this value will be used as
9615 the link location instead of reading one interactively.
9617 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9618 be used as the default description. Otherwise, if
9619 `org-make-link-description-function' is non-nil, this function
9620 will be called with the link target, and the result will be the
9621 default link description. When called non-interactivily, don't
9622 allow to edit the default description."
9623 (interactive "P")
9624 (let* ((wcf (current-window-configuration))
9625 (origbuf (current-buffer))
9626 (region (when (org-region-active-p)
9627 (buffer-substring (region-beginning) (region-end))))
9628 (remove (and region (list (region-beginning) (region-end))))
9629 (desc region)
9630 (link link-location)
9631 (abbrevs org-link-abbrev-alist-local)
9632 entry all-prefixes auto-desc)
9633 (cond
9634 (link-location) ; specified by arg, just use it.
9635 ((org-in-regexp org-bracket-link-regexp 1)
9636 ;; We do have a link at point, and we are going to edit it.
9637 (setq remove (list (match-beginning 0) (match-end 0)))
9638 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9639 (setq link (read-string "Link: "
9640 (org-link-unescape
9641 (match-string-no-properties 1)))))
9642 ((or (org-in-regexp org-angle-link-re)
9643 (org-in-regexp org-plain-link-re))
9644 ;; Convert to bracket link
9645 (setq remove (list (match-beginning 0) (match-end 0))
9646 link (read-string "Link: "
9647 (org-unbracket-string "<" ">" (match-string 0)))))
9648 ((member complete-file '((4) (16)))
9649 ;; Completing read for file names.
9650 (setq link (org-file-complete-link complete-file)))
9652 ;; Read link, with completion for stored links.
9653 (org-link-fontify-links-to-this-file)
9654 (org-switch-to-buffer-other-window "*Org Links*")
9655 (with-current-buffer "*Org Links*"
9656 (erase-buffer)
9657 (insert "Insert a link.
9658 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9659 (when org-stored-links
9660 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9661 (insert (mapconcat 'org-link-prettify
9662 (reverse org-stored-links) "\n")))
9663 (goto-char (point-min)))
9664 (let ((cw (selected-window)))
9665 (select-window (get-buffer-window "*Org Links*" 'visible))
9666 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9667 (unless (pos-visible-in-window-p (point-max))
9668 (org-fit-window-to-buffer))
9669 (and (window-live-p cw) (select-window cw)))
9670 (setq all-prefixes (append (mapcar 'car abbrevs)
9671 (mapcar 'car org-link-abbrev-alist)
9672 (org-link-types)))
9673 (unwind-protect
9674 ;; Fake a link history, containing the stored links.
9675 (let ((org--links-history
9676 (append (mapcar #'car org-stored-links)
9677 org-insert-link-history)))
9678 (setq link
9679 (org-completing-read
9680 "Link: "
9681 (append
9682 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9683 (mapcar #'car org-stored-links))
9684 nil nil nil
9685 'org--links-history
9686 (caar org-stored-links)))
9687 (unless (org-string-nw-p link) (user-error "No link selected"))
9688 (dolist (l org-stored-links)
9689 (when (equal link (cadr l))
9690 (setq link (car l))
9691 (setq auto-desc t)))
9692 (when (or (member link all-prefixes)
9693 (and (equal ":" (substring link -1))
9694 (member (substring link 0 -1) all-prefixes)
9695 (setq link (substring link 0 -1))))
9696 (setq link (with-current-buffer origbuf
9697 (org-link-try-special-completion link)))))
9698 (set-window-configuration wcf)
9699 (kill-buffer "*Org Links*"))
9700 (setq entry (assoc link org-stored-links))
9701 (or entry (push link org-insert-link-history))
9702 (setq desc (or desc (nth 1 entry)))))
9704 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9705 (not org-keep-stored-link-after-insertion))
9706 (setq org-stored-links (delq (assoc link org-stored-links)
9707 org-stored-links)))
9709 (when (and (string-match org-plain-link-re link)
9710 (not (string-match org-ts-regexp link)))
9711 ;; URL-like link, normalize the use of angular brackets.
9712 (setq link (org-unbracket-string "<" ">" link)))
9714 ;; Check if we are linking to the current file with a search
9715 ;; option If yes, simplify the link by using only the search
9716 ;; option.
9717 (when (and buffer-file-name
9718 (let ((case-fold-search nil))
9719 (string-match "\\`file:\\(.+?\\)::" link)))
9720 (let ((path (match-string-no-properties 1 link))
9721 (search (substring-no-properties link (match-end 0))))
9722 (save-match-data
9723 (when (equal (file-truename buffer-file-name) (file-truename path))
9724 ;; We are linking to this same file, with a search option
9725 (setq link search)))))
9727 ;; Check if we can/should use a relative path. If yes, simplify
9728 ;; the link.
9729 (let ((case-fold-search nil))
9730 (when (string-match "\\`\\(file\\|docview\\):" link)
9731 (let* ((type (match-string-no-properties 0 link))
9732 (path-start (match-end 0))
9733 (search (and (string-match "::\\(.*\\)\\'" link)
9734 (match-string 1 link)))
9735 (path
9736 (if search
9737 (substring-no-properties
9738 link path-start (match-beginning 0))
9739 (substring-no-properties link (match-end 0))))
9740 (origpath path))
9741 (cond
9742 ((or (eq org-link-file-path-type 'absolute)
9743 (equal complete-file '(16)))
9744 (setq path (abbreviate-file-name (expand-file-name path))))
9745 ((eq org-link-file-path-type 'noabbrev)
9746 (setq path (expand-file-name path)))
9747 ((eq org-link-file-path-type 'relative)
9748 (setq path (file-relative-name path)))
9750 (save-match-data
9751 (if (string-match (concat "^" (regexp-quote
9752 (expand-file-name
9753 (file-name-as-directory
9754 default-directory))))
9755 (expand-file-name path))
9756 ;; We are linking a file with relative path name.
9757 (setq path (substring (expand-file-name path)
9758 (match-end 0)))
9759 (setq path (abbreviate-file-name (expand-file-name path)))))))
9760 (setq link (concat type path (and search (concat "::" search))))
9761 (when (equal desc origpath)
9762 (setq desc path)))))
9764 (unless auto-desc
9765 (let ((initial-input
9766 (cond
9767 (default-description)
9768 ((not org-make-link-description-function) desc)
9769 (t (condition-case nil
9770 (funcall org-make-link-description-function link desc)
9771 (error
9772 (message "Can't get link description from `%s'"
9773 (symbol-name org-make-link-description-function))
9774 (sit-for 2)
9775 nil))))))
9776 (setq desc (if (called-interactively-p 'any)
9777 (read-string "Description: " initial-input)
9778 initial-input))))
9780 (unless (string-match "\\S-" desc) (setq desc nil))
9781 (when remove (apply 'delete-region remove))
9782 (insert (org-make-link-string link desc))
9783 ;; Redisplay so as the new link has proper invisible characters.
9784 (sit-for 0)))
9786 (defun org-link-try-special-completion (type)
9787 "If there is completion support for link type TYPE, offer it."
9788 (let ((fun (org-link-get-parameter type :complete)))
9789 (if (functionp fun)
9790 (funcall fun)
9791 (read-string "Link (no completion support): " (concat type ":")))))
9793 (defun org-file-complete-link (&optional arg)
9794 "Create a file link using completion."
9795 (let ((file (read-file-name "File: "))
9796 (pwd (file-name-as-directory (expand-file-name ".")))
9797 (pwd1 (file-name-as-directory (abbreviate-file-name
9798 (expand-file-name ".")))))
9799 (cond ((equal arg '(16))
9800 (concat "file:"
9801 (abbreviate-file-name (expand-file-name file))))
9802 ((string-match
9803 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9804 (concat "file:" (match-string 1 file)))
9805 ((string-match
9806 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9807 (expand-file-name file))
9808 (concat "file:"
9809 (match-string 1 (expand-file-name file))))
9810 (t (concat "file:" file)))))
9813 ;;; Opening/following a link
9815 (defvar org-link-search-failed nil)
9817 (defvar org-open-link-functions nil
9818 "Hook for functions finding a plain text link.
9819 These functions must take a single argument, the link content.
9820 They will be called for links that look like [[link text][description]]
9821 when LINK TEXT does not have a protocol like \"http:\" and does not look
9822 like a filename (e.g. \"./blue.png\").
9824 These functions will be called *before* Org attempts to resolve the
9825 link by doing text searches in the current buffer - so if you want a
9826 link \"[[target]]\" to still find \"<<target>>\", your function should
9827 handle this as a special case.
9829 When the function does handle the link, it must return a non-nil value.
9830 If it decides that it is not responsible for this link, it must return
9831 nil to indicate that that Org can continue with other options like
9832 exact and fuzzy text search.")
9834 (defun org-next-link (&optional search-backward)
9835 "Move forward to the next link.
9836 If the link is in hidden text, expose it."
9837 (interactive "P")
9838 (when (and org-link-search-failed (eq this-command last-command))
9839 (goto-char (point-min))
9840 (message "Link search wrapped back to beginning of buffer"))
9841 (setq org-link-search-failed nil)
9842 (let* ((pos (point))
9843 (ct (org-context))
9844 (a (assq :link ct))
9845 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9846 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9847 ((looking-at org-any-link-re)
9848 ;; Don't stay stuck at link without an org-link face
9849 (forward-char (if search-backward -1 1))))
9850 (if (funcall srch-fun org-any-link-re nil t)
9851 (progn
9852 (goto-char (match-beginning 0))
9853 (when (org-invisible-p) (org-show-context)))
9854 (goto-char pos)
9855 (setq org-link-search-failed t)
9856 (message "No further link found"))))
9858 (defun org-previous-link ()
9859 "Move backward to the previous link.
9860 If the link is in hidden text, expose it."
9861 (interactive)
9862 (funcall 'org-next-link t))
9864 (defun org-translate-link (s)
9865 "Translate a link string if a translation function has been defined."
9866 (with-temp-buffer
9867 (insert (org-trim s))
9868 (org-trim (org-element-interpret-data (org-element-context)))))
9870 (defun org-translate-link-from-planner (type path)
9871 "Translate a link from Emacs Planner syntax so that Org can follow it.
9872 This is still an experimental function, your mileage may vary."
9873 (cond
9874 ((member type '("http" "https" "news" "ftp"))
9875 ;; standard Internet links are the same.
9876 nil)
9877 ((and (equal type "irc") (string-match "^//" path))
9878 ;; Planner has two / at the beginning of an irc link, we have 1.
9879 ;; We should have zero, actually....
9880 (setq path (substring path 1)))
9881 ((and (equal type "lisp") (string-match "^/" path))
9882 ;; Planner has a slash, we do not.
9883 (setq type "elisp" path (substring path 1)))
9884 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9885 ;; A typical message link. Planner has the id after the final slash,
9886 ;; we separate it with a hash mark
9887 (setq path (concat (match-string 1 path) "#"
9888 (org-unbracket-string "<" ">" (match-string 2 path))))))
9889 (cons type path))
9891 (defun org-find-file-at-mouse (ev)
9892 "Open file link or URL at mouse."
9893 (interactive "e")
9894 (mouse-set-point ev)
9895 (org-open-at-point 'in-emacs))
9897 (defun org-open-at-mouse (ev)
9898 "Open file link or URL at mouse.
9899 See the docstring of `org-open-file' for details."
9900 (interactive "e")
9901 (mouse-set-point ev)
9902 (when (eq major-mode 'org-agenda-mode)
9903 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9904 (org-open-at-point))
9906 (defvar org-window-config-before-follow-link nil
9907 "The window configuration before following a link.
9908 This is saved in case the need arises to restore it.")
9910 ;;;###autoload
9911 (defun org-open-at-point-global ()
9912 "Follow a link or time-stamp like Org mode does.
9913 This command can be called in any mode to follow an external link
9914 or a time-stamp that has Org mode syntax. Its behavior is
9915 undefined when called on internal links (e.g., fuzzy links).
9916 Raise an error when there is nothing to follow. "
9917 (interactive)
9918 (cond ((org-in-regexp org-any-link-re)
9919 (org-open-link-from-string (match-string-no-properties 0)))
9920 ((or (org-in-regexp org-ts-regexp-both nil t)
9921 (org-in-regexp org-tsr-regexp-both nil t))
9922 (org-follow-timestamp-link))
9923 (t (user-error "No link found"))))
9925 ;;;###autoload
9926 (defun org-open-link-from-string (s &optional arg reference-buffer)
9927 "Open a link in the string S, as if it was in Org mode."
9928 (interactive "sLink: \nP")
9929 (let ((reference-buffer (or reference-buffer (current-buffer))))
9930 (with-temp-buffer
9931 (let ((org-inhibit-startup (not reference-buffer)))
9932 (org-mode)
9933 (insert s)
9934 (goto-char (point-min))
9935 (when reference-buffer
9936 (setq org-link-abbrev-alist-local
9937 (with-current-buffer reference-buffer
9938 org-link-abbrev-alist-local)))
9939 (org-open-at-point arg reference-buffer)))))
9941 (defvar org-open-at-point-functions nil
9942 "Hook that is run when following a link at point.
9944 Functions in this hook must return t if they identify and follow
9945 a link at point. If they don't find anything interesting at point,
9946 they must return nil.")
9948 (defvar org-link-search-inhibit-query nil)
9949 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9950 (defun org--open-doi-link (path)
9951 "Open a \"doi\" type link.
9952 PATH is a the path to search for, as a string."
9953 (browse-url (url-encode-url (concat org-doi-server-url path))))
9955 (defun org--open-elisp-link (path)
9956 "Open a \"elisp\" type link.
9957 PATH is the sexp to evaluate, as a string."
9958 (let ((cmd path))
9959 (if (or (and (org-string-nw-p
9960 org-confirm-elisp-link-not-regexp)
9961 (string-match-p org-confirm-elisp-link-not-regexp cmd))
9962 (not org-confirm-elisp-link-function)
9963 (funcall org-confirm-elisp-link-function
9964 (format "Execute \"%s\" as elisp? "
9965 (org-add-props cmd nil 'face 'org-warning))))
9966 (message "%s => %s" cmd
9967 (if (eq (string-to-char cmd) ?\()
9968 (eval (read cmd))
9969 (call-interactively (read cmd))))
9970 (user-error "Abort"))))
9972 (defun org--open-help-link (path)
9973 "Open a \"help\" type link.
9974 PATH is a symbol name, as a string."
9975 (pcase (intern path)
9976 ((and (pred fboundp) variable) (describe-function variable))
9977 ((and (pred boundp) function) (describe-variable function))
9978 (name (user-error "Unknown function or variable: %s" name))))
9980 (defun org--open-shell-link (path)
9981 "Open a \"shell\" type link.
9982 PATH is the command to execute, as a string."
9983 (let ((buf (generate-new-buffer "*Org Shell Output*"))
9984 (cmd path))
9985 (if (or (and (org-string-nw-p
9986 org-confirm-shell-link-not-regexp)
9987 (string-match
9988 org-confirm-shell-link-not-regexp cmd))
9989 (not org-confirm-shell-link-function)
9990 (funcall org-confirm-shell-link-function
9991 (format "Execute \"%s\" in shell? "
9992 (org-add-props cmd nil
9993 'face 'org-warning))))
9994 (progn
9995 (message "Executing %s" cmd)
9996 (shell-command cmd buf)
9997 (when (featurep 'midnight)
9998 (setq clean-buffer-list-kill-buffer-names
9999 (cons (buffer-name buf)
10000 clean-buffer-list-kill-buffer-names))))
10001 (user-error "Abort"))))
10003 (defun org-open-at-point (&optional arg reference-buffer)
10004 "Open link, timestamp, footnote or tags at point.
10006 When point is on a link, follow it. Normally, files will be
10007 opened by an appropriate application. If the optional prefix
10008 argument ARG is non-nil, Emacs will visit the file. With
10009 a double prefix argument, try to open outside of Emacs, in the
10010 application the system uses for this file type.
10012 When point is on a timestamp, open the agenda at the day
10013 specified.
10015 When point is a footnote definition, move to the first reference
10016 found. If it is on a reference, move to the associated
10017 definition.
10019 When point is on a headline, display a list of every link in the
10020 entry, so it is possible to pick one, or all, of them. If point
10021 is on a tag, call `org-tags-view' instead.
10023 When optional argument REFERENCE-BUFFER is non-nil, it should
10024 specify a buffer from where the link search should happen. This
10025 is used internally by `org-open-link-from-string'.
10027 On top of syntactically correct links, this function will also
10028 try to open links and time-stamps in comments, example
10029 blocks... i.e., whenever point is on something looking like
10030 a timestamp or a link."
10031 (interactive "P")
10032 ;; On a code block, open block's results.
10033 (unless (call-interactively 'org-babel-open-src-block-result)
10034 (org-load-modules-maybe)
10035 (setq org-window-config-before-follow-link (current-window-configuration))
10036 (org-remove-occur-highlights nil nil t)
10037 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10038 (let* ((context
10039 ;; Only consider supported types, even if they are not
10040 ;; the closest one.
10041 (org-element-lineage
10042 (org-element-context)
10043 '(clock footnote-definition footnote-reference headline
10044 inlinetask link timestamp)
10046 (type (org-element-type context))
10047 (value (org-element-property :value context)))
10048 (cond
10049 ;; On a headline or an inlinetask, but not on a timestamp,
10050 ;; a link, a footnote reference.
10051 ((memq type '(headline inlinetask))
10052 (org-match-line org-complex-heading-regexp)
10053 (if (and (match-beginning 5)
10054 (>= (point) (match-beginning 5))
10055 (< (point) (match-end 5)))
10056 ;; On tags.
10057 (org-tags-view arg (substring (match-string 5) 0 -1))
10058 ;; Not on tags.
10059 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10060 (`(nil . ,_)
10061 (require 'org-attach)
10062 (org-attach-reveal 'if-exists))
10063 (`(,links . ,links-end)
10064 (dolist (link (if (stringp links) (list links) links))
10065 (search-forward link nil links-end)
10066 (goto-char (match-beginning 0))
10067 (org-open-at-point))))))
10068 ;; On a footnote reference or at definition's label.
10069 ((or (eq type 'footnote-reference)
10070 (and (eq type 'footnote-definition)
10071 (save-excursion
10072 ;; Do not validate action when point is on the
10073 ;; spaces right after the footnote label, in
10074 ;; order to be on par with behaviour on links.
10075 (skip-chars-forward " \t")
10076 (let ((begin
10077 (org-element-property :contents-begin context)))
10078 (if begin (< (point) begin)
10079 (= (org-element-property :post-affiliated context)
10080 (line-beginning-position)))))))
10081 (org-footnote-action))
10082 ;; No valid context. Ignore catch-all types like `headline'.
10083 ;; If point is on something looking like a link or
10084 ;; a time-stamp, try opening it. It may be useful in
10085 ;; comments, example blocks...
10086 ((memq type '(footnote-definition headline inlinetask nil))
10087 (call-interactively #'org-open-at-point-global))
10088 ;; On a clock line, make sure point is on the timestamp
10089 ;; before opening it.
10090 ((and (eq type 'clock)
10091 value
10092 (>= (point) (org-element-property :begin value))
10093 (<= (point) (org-element-property :end value)))
10094 (org-follow-timestamp-link))
10095 ;; Do nothing on white spaces after an object.
10096 ((>= (point)
10097 (save-excursion
10098 (goto-char (org-element-property :end context))
10099 (skip-chars-backward " \t")
10100 (point)))
10101 (user-error "No link found"))
10102 ((eq type 'timestamp) (org-follow-timestamp-link))
10103 ((eq type 'link)
10104 (let ((type (org-element-property :type context))
10105 (path (org-link-unescape (org-element-property :path context))))
10106 ;; Switch back to REFERENCE-BUFFER needed when called in
10107 ;; a temporary buffer through `org-open-link-from-string'.
10108 (with-current-buffer (or reference-buffer (current-buffer))
10109 (cond
10110 ((equal type "file")
10111 (if (string-match "[*?{]" (file-name-nondirectory path))
10112 (dired path)
10113 ;; Look into `org-link-parameters' in order to find
10114 ;; a DEDICATED-FUNCTION to open file. The function
10115 ;; will be applied on raw link instead of parsed
10116 ;; link due to the limitation in `org-add-link-type'
10117 ;; ("open" function called with a single argument).
10118 ;; If no such function is found, fallback to
10119 ;; `org-open-file'.
10120 (let* ((option (org-element-property :search-option context))
10121 (app (org-element-property :application context))
10122 (dedicated-function
10123 (org-link-get-parameter
10124 (if app (concat type "+" app) type)
10125 :follow)))
10126 (if dedicated-function
10127 (funcall dedicated-function
10128 (concat path
10129 (and option (concat "::" option))))
10130 (apply #'org-open-file
10131 path
10132 (cond (arg)
10133 ((equal app "emacs") 'emacs)
10134 ((equal app "sys") 'system))
10135 (cond ((not option) nil)
10136 ((string-match-p "\\`[0-9]+\\'" option)
10137 (list (string-to-number option)))
10138 (t (list nil
10139 (org-link-unescape option)))))))))
10140 ((functionp (org-link-get-parameter type :follow))
10141 (funcall (org-link-get-parameter type :follow) path))
10142 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10143 (unless (run-hook-with-args-until-success
10144 'org-open-link-functions path)
10145 (if (not arg) (org-mark-ring-push)
10146 (switch-to-buffer-other-window
10147 (org-get-buffer-for-internal-link (current-buffer))))
10148 (let ((destination
10149 (org-with-wide-buffer
10150 (if (equal type "radio")
10151 (org-search-radio-target
10152 (org-element-property :path context))
10153 (org-link-search
10154 (if (member type '("custom-id" "coderef"))
10155 (org-element-property :raw-link context)
10156 path)
10157 ;; Prevent fuzzy links from matching
10158 ;; themselves.
10159 (and (equal type "fuzzy")
10160 (+ 2 (org-element-property :begin context)))))
10161 (point))))
10162 (unless (and (<= (point-min) destination)
10163 (>= (point-max) destination))
10164 (widen))
10165 (goto-char destination))))
10166 (t (browse-url-at-point))))))
10167 (t (user-error "No link found")))))
10168 (run-hook-with-args 'org-follow-link-hook)))
10170 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10171 "Offer links in the current entry and return the selected link.
10172 If there is only one link, return it.
10173 If NTH is an integer, return the NTH link found.
10174 If ZERO is a string, check also this string for a link, and if
10175 there is one, return it."
10176 (with-current-buffer buffer
10177 (org-with-wide-buffer
10178 (goto-char marker)
10179 (let ((cnt ?0)
10180 have-zero end links link c)
10181 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10182 (push (match-string 0 zero) links)
10183 (setq cnt (1- cnt) have-zero t))
10184 (save-excursion
10185 (org-back-to-heading t)
10186 (setq end (save-excursion (outline-next-heading) (point)))
10187 (while (re-search-forward org-any-link-re end t)
10188 (push (match-string 0) links))
10189 (setq links (org-uniquify (reverse links))))
10190 (cond
10191 ((null links)
10192 (message "No links"))
10193 ((equal (length links) 1)
10194 (setq link (car links)))
10195 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10196 (setq link (nth (if have-zero nth (1- nth)) links)))
10197 (t ; we have to select a link
10198 (save-excursion
10199 (save-window-excursion
10200 (delete-other-windows)
10201 (with-output-to-temp-buffer "*Select Link*"
10202 (dolist (l links)
10203 (cond
10204 ((not (string-match org-bracket-link-regexp l))
10205 (princ (format "[%c] %s\n" (cl-incf cnt)
10206 (org-unbracket-string "<" ">" l))))
10207 ((match-end 3)
10208 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10209 (match-string 3 l) (match-string 1 l))))
10210 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10211 (match-string 1 l)))))))
10212 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10213 (message "Select link to open, RET to open all:")
10214 (setq c (read-char-exclusive))
10215 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10216 (when (equal c ?q) (user-error "Abort"))
10217 (if (equal c ?\C-m)
10218 (setq link links)
10219 (setq nth (- c ?0))
10220 (when have-zero (setq nth (1+ nth)))
10221 (unless (and (integerp nth) (>= (length links) nth))
10222 (user-error "Invalid link selection"))
10223 (setq link (nth (1- nth) links)))))
10224 (cons link end)))))
10226 ;; TODO: These functions are deprecated since `org-open-at-point'
10227 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10228 (defun org-open-file-with-system (path)
10229 "Open file at PATH using the system way of opening it."
10230 (org-open-file path 'system))
10231 (defun org-open-file-with-emacs (path)
10232 "Open file at PATH in Emacs."
10233 (org-open-file path 'emacs))
10236 ;;; File search
10238 (defvar org-create-file-search-functions nil
10239 "List of functions to construct the right search string for a file link.
10240 These functions are called in turn with point at the location to
10241 which the link should point.
10243 A function in the hook should first test if it would like to
10244 handle this file type, for example by checking the `major-mode'
10245 or the file extension. If it decides not to handle this file, it
10246 should just return nil to give other functions a chance. If it
10247 does handle the file, it must return the search string to be used
10248 when following the link. The search string will be part of the
10249 file link, given after a double colon, and `org-open-at-point'
10250 will automatically search for it. If special measures must be
10251 taken to make the search successful, another function should be
10252 added to the companion hook `org-execute-file-search-functions',
10253 which see.
10255 A function in this hook may also use `setq' to set the variable
10256 `description' to provide a suggestion for the descriptive text to
10257 be used for this link when it gets inserted into an Org buffer
10258 with \\[org-insert-link].")
10260 (defvar org-execute-file-search-functions nil
10261 "List of functions to execute a file search triggered by a link.
10263 Functions added to this hook must accept a single argument, the
10264 search string that was part of the file link, the part after the
10265 double colon. The function must first check if it would like to
10266 handle this search, for example by checking the `major-mode' or
10267 the file extension. If it decides not to handle this search, it
10268 should just return nil to give other functions a chance. If it
10269 does handle the search, it must return a non-nil value to keep
10270 other functions from trying.
10272 Each function can access the current prefix argument through the
10273 variable `current-prefix-arg'. Note that a single prefix is used
10274 to force opening a link in Emacs, so it may be good to only use a
10275 numeric or double prefix to guide the search function.
10277 In case this is needed, a function in this hook can also restore
10278 the window configuration before `org-open-at-point' was called using:
10280 (set-window-configuration org-window-config-before-follow-link)")
10282 (defun org-search-radio-target (target)
10283 "Search a radio target matching TARGET in current buffer.
10284 White spaces are not significant."
10285 (let ((re (format "<<<%s>>>"
10286 (mapconcat #'regexp-quote
10287 (split-string target)
10288 "[ \t]+\\(?:\n[ \t]*\\)?")))
10289 (origin (point)))
10290 (goto-char (point-min))
10291 (catch :radio-match
10292 (while (re-search-forward re nil t)
10293 (backward-char)
10294 (let ((object (org-element-context)))
10295 (when (eq (org-element-type object) 'radio-target)
10296 (goto-char (org-element-property :begin object))
10297 (org-show-context 'link-search)
10298 (throw :radio-match nil))))
10299 (goto-char origin)
10300 (user-error "No match for radio target: %s" target))))
10302 (defun org-link-search (s &optional avoid-pos stealth)
10303 "Search for a search string S.
10305 If S starts with \"#\", it triggers a custom ID search.
10307 If S is enclosed within parenthesis, it initiates a coderef
10308 search.
10310 If S is surrounded by forward slashes, it is interpreted as
10311 a regular expression. In Org mode files, this will create an
10312 `org-occur' sparse tree. In ordinary files, `occur' will be used
10313 to list matches. If the current buffer is in `dired-mode', grep
10314 will be used to search in all files.
10316 When AVOID-POS is given, ignore matches near that position.
10318 When optional argument STEALTH is non-nil, do not modify
10319 visibility around point, thus ignoring `org-show-context-detail'
10320 variable.
10322 Search is case-insensitive and ignores white spaces. Return type
10323 of matched result, which is either `dedicated' or `fuzzy'."
10324 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10325 (let* ((case-fold-search t)
10326 (origin (point))
10327 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10328 (starred (eq (string-to-char normalized) ?*))
10329 (words (split-string (if starred (substring s 1) s)))
10330 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10331 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10332 type)
10333 (cond
10334 ;; Check if there are any special search functions.
10335 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10336 ((eq (string-to-char s) ?#)
10337 ;; Look for a custom ID S if S starts with "#".
10338 (let* ((id (substring normalized 1))
10339 (match (org-find-property "CUSTOM_ID" id)))
10340 (if match (progn (goto-char match) (setf type 'dedicated))
10341 (error "No match for custom ID: %s" id))))
10342 ((string-match "\\`(\\(.*\\))\\'" normalized)
10343 ;; Look for coderef targets if S is enclosed within parenthesis.
10344 (let ((coderef (match-string-no-properties 1 normalized))
10345 (re (substring s-single-re 1 -1)))
10346 (goto-char (point-min))
10347 (catch :coderef-match
10348 (while (re-search-forward re nil t)
10349 (let ((element (org-element-at-point)))
10350 (when (and (memq (org-element-type element)
10351 '(example-block src-block))
10352 ;; Build proper regexp according to current
10353 ;; block's label format.
10354 (let ((label-fmt
10355 (regexp-quote
10356 (or (org-element-property :label-fmt element)
10357 org-coderef-label-format))))
10358 (save-excursion
10359 (beginning-of-line)
10360 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10361 (format label-fmt coderef))))))
10362 (setq type 'dedicated)
10363 (goto-char (match-beginning 1))
10364 (throw :coderef-match nil))))
10365 (goto-char origin)
10366 (error "No match for coderef: %s" coderef))))
10367 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10368 ;; Look for a regular expression.
10369 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10370 (match-string 1 s)))
10371 ;; From here, we handle fuzzy links.
10373 ;; Look for targets, only if not in a headline search.
10374 ((and (not starred)
10375 (let ((target (format "<<%s>>" s-multi-re)))
10376 (catch :target-match
10377 (goto-char (point-min))
10378 (while (re-search-forward target nil t)
10379 (backward-char)
10380 (let ((context (org-element-context)))
10381 (when (eq (org-element-type context) 'target)
10382 (setq type 'dedicated)
10383 (goto-char (org-element-property :begin context))
10384 (throw :target-match t))))
10385 nil))))
10386 ;; Look for elements named after S, only if not in a headline
10387 ;; search.
10388 ((and (not starred)
10389 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10390 (catch :name-match
10391 (goto-char (point-min))
10392 (while (re-search-forward name nil t)
10393 (let ((element (org-element-at-point)))
10394 (when (equal words
10395 (split-string
10396 (org-element-property :name element)))
10397 (setq type 'dedicated)
10398 (beginning-of-line)
10399 (throw :name-match t))))
10400 nil))))
10401 ;; Regular text search. Prefer headlines in Org mode buffers.
10402 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10403 ;; statistics cookies and tags.
10404 ((and (derived-mode-p 'org-mode)
10405 (let ((title-re
10406 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10407 org-outline-regexp-bol
10408 org-comment-string
10409 (mapconcat #'regexp-quote words ".+")))
10410 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10411 (comment-re (eval-when-compile
10412 (format "\\`%s[ \t]+" org-comment-string))))
10413 (goto-char (point-min))
10414 (catch :found
10415 (while (re-search-forward title-re nil t)
10416 (when (equal words
10417 (split-string
10418 (replace-regexp-in-string
10419 cookie-re ""
10420 (replace-regexp-in-string
10421 comment-re "" (org-get-heading t t t)))))
10422 (throw :found t)))
10423 nil)))
10424 (beginning-of-line)
10425 (setq type 'dedicated))
10426 ;; Offer to create non-existent headline depending on
10427 ;; `org-link-search-must-match-exact-headline'.
10428 ((and (derived-mode-p 'org-mode)
10429 (not org-link-search-inhibit-query)
10430 (eq org-link-search-must-match-exact-headline 'query-to-create)
10431 (yes-or-no-p "No match - create this as a new heading? "))
10432 (goto-char (point-max))
10433 (unless (bolp) (newline))
10434 (org-insert-heading nil t t)
10435 (insert s "\n")
10436 (beginning-of-line 0))
10437 ;; Only headlines are looked after. No need to process
10438 ;; further: throw an error.
10439 ((and (derived-mode-p 'org-mode)
10440 (or starred org-link-search-must-match-exact-headline))
10441 (goto-char origin)
10442 (error "No match for fuzzy expression: %s" normalized))
10443 ;; Regular text search.
10444 ((catch :fuzzy-match
10445 (goto-char (point-min))
10446 (while (re-search-forward s-multi-re nil t)
10447 ;; Skip match if it contains AVOID-POS or it is included in
10448 ;; a link with a description but outside the description.
10449 (unless (or (and avoid-pos
10450 (<= (match-beginning 0) avoid-pos)
10451 (> (match-end 0) avoid-pos))
10452 (and (save-match-data
10453 (org-in-regexp org-bracket-link-regexp))
10454 (match-beginning 3)
10455 (or (> (match-beginning 3) (point))
10456 (<= (match-end 3) (point)))
10457 (org-element-lineage
10458 (save-match-data (org-element-context))
10459 '(link) t)))
10460 (goto-char (match-beginning 0))
10461 (setq type 'fuzzy)
10462 (throw :fuzzy-match t)))
10463 nil))
10464 ;; All failed. Throw an error.
10465 (t (goto-char origin)
10466 (error "No match for fuzzy expression: %s" normalized)))
10467 ;; Disclose surroundings of match, if appropriate.
10468 (when (and (derived-mode-p 'org-mode) (not stealth))
10469 (org-show-context 'link-search))
10470 type))
10472 (defun org-get-buffer-for-internal-link (buffer)
10473 "Return a buffer to be used for displaying the link target of internal links."
10474 (cond
10475 ((not org-display-internal-link-with-indirect-buffer)
10476 buffer)
10477 ((string-suffix-p "(Clone)" (buffer-name buffer))
10478 (message "Buffer is already a clone, not making another one")
10479 ;; we also do not modify visibility in this case
10480 buffer)
10481 (t ; make a new indirect buffer for displaying the link
10482 (let* ((bn (buffer-name buffer))
10483 (ibn (concat bn "(Clone)"))
10484 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10485 (with-current-buffer ib (org-overview))
10486 ib))))
10488 (defun org-do-occur (regexp &optional cleanup)
10489 "Call the Emacs command `occur'.
10490 If CLEANUP is non-nil, remove the printout of the regular expression
10491 in the *Occur* buffer. This is useful if the regex is long and not useful
10492 to read."
10493 (occur regexp)
10494 (when cleanup
10495 (let ((cwin (selected-window)) win beg end)
10496 (when (setq win (get-buffer-window "*Occur*"))
10497 (select-window win))
10498 (goto-char (point-min))
10499 (when (re-search-forward "match[a-z]+" nil t)
10500 (setq beg (match-end 0))
10501 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10502 (setq end (1- (match-beginning 0)))))
10503 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10504 (goto-char (point-min))
10505 (select-window cwin))))
10507 ;;; The mark ring for links jumps
10509 (defvar org-mark-ring nil
10510 "Mark ring for positions before jumps in Org mode.")
10511 (defvar org-mark-ring-last-goto nil
10512 "Last position in the mark ring used to go back.")
10513 ;; Fill and close the ring
10514 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10515 (dotimes (_ org-mark-ring-length)
10516 (push (make-marker) org-mark-ring))
10517 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10518 org-mark-ring)
10520 (defun org-mark-ring-push (&optional pos buffer)
10521 "Put the current position or POS into the mark ring and rotate it."
10522 (interactive)
10523 (setq pos (or pos (point)))
10524 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10525 (move-marker (car org-mark-ring)
10526 (or pos (point))
10527 (or buffer (current-buffer)))
10528 (message "%s"
10529 (substitute-command-keys
10530 "Position saved to mark ring, go back with \
10531 `\\[org-mark-ring-goto]'.")))
10533 (defun org-mark-ring-goto (&optional n)
10534 "Jump to the previous position in the mark ring.
10535 With prefix arg N, jump back that many stored positions. When
10536 called several times in succession, walk through the entire ring.
10537 Org mode commands jumping to a different position in the current file,
10538 or to another Org file, automatically push the old position onto the ring."
10539 (interactive "p")
10540 (let (p m)
10541 (if (eq last-command this-command)
10542 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10543 (setq p org-mark-ring))
10544 (setq org-mark-ring-last-goto p)
10545 (setq m (car p))
10546 (pop-to-buffer-same-window (marker-buffer m))
10547 (goto-char m)
10548 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10550 (defun org-add-angle-brackets (s)
10551 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10552 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10555 ;;; Following specific links
10557 (defvar org-agenda-buffer-tmp-name)
10558 (defvar org-agenda-start-on-weekday)
10559 (defun org-follow-timestamp-link ()
10560 "Open an agenda view for the time-stamp date/range at point."
10561 (cond
10562 ((org-at-date-range-p t)
10563 (let ((org-agenda-start-on-weekday)
10564 (t1 (match-string 1))
10565 (t2 (match-string 2)) tt1 tt2)
10566 (setq tt1 (time-to-days (org-time-string-to-time t1))
10567 tt2 (time-to-days (org-time-string-to-time t2)))
10568 (let ((org-agenda-buffer-tmp-name
10569 (format "*Org Agenda(a:%s)"
10570 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10571 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10572 ((org-at-timestamp-p 'lax)
10573 (let ((org-agenda-buffer-tmp-name
10574 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10575 (org-agenda-list nil (time-to-days (org-time-string-to-time
10576 (substring (match-string 1) 0 10)))
10577 1)))
10578 (t (error "This should not happen"))))
10581 ;;; Following file links
10582 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10583 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10584 (declare-function mailcap-mime-info
10585 "mailcap" (string &optional request no-decode))
10586 (defvar org-wait nil)
10587 (defun org-open-file (path &optional in-emacs line search)
10588 "Open the file at PATH.
10589 First, this expands any special file name abbreviations. Then the
10590 configuration variable `org-file-apps' is checked if it contains an
10591 entry for this file type, and if yes, the corresponding command is launched.
10593 If no application is found, Emacs simply visits the file.
10595 With optional prefix argument IN-EMACS, Emacs will visit the file.
10596 With a double \\[universal-argument] \\[universal-argument] \
10597 prefix arg, Org tries to avoid opening in Emacs
10598 and to use an external application to visit the file.
10600 Optional LINE specifies a line to go to, optional SEARCH a string
10601 to search for. If LINE or SEARCH is given, the file will be
10602 opened in Emacs, unless an entry from org-file-apps that makes
10603 use of groups in a regexp matches.
10605 If you want to change the way frames are used when following a
10606 link, please customize `org-link-frame-setup'.
10608 If the file does not exist, an error is thrown."
10609 (let* ((file (if (equal path "")
10610 buffer-file-name
10611 (substitute-in-file-name (expand-file-name path))))
10612 (file-apps (append org-file-apps (org-default-apps)))
10613 (apps (cl-remove-if
10614 'org-file-apps-entry-match-against-dlink-p file-apps))
10615 (apps-dlink (cl-remove-if-not
10616 'org-file-apps-entry-match-against-dlink-p file-apps))
10617 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10618 (dirp (unless remp (file-directory-p file)))
10619 (file (if (and dirp org-open-directory-means-index-dot-org)
10620 (concat (file-name-as-directory file) "index.org")
10621 file))
10622 (a-m-a-p (assq 'auto-mode apps))
10623 (dfile (downcase file))
10624 ;; Reconstruct the original link from the PATH, LINE and
10625 ;; SEARCH args.
10626 (link (cond (line (concat file "::" (number-to-string line)))
10627 (search (concat file "::" search))
10628 (t file)))
10629 (dlink (downcase link))
10630 (ext
10631 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10632 (match-string 1 dfile)))
10633 (save-position-maybe
10634 (let ((old-buffer (current-buffer))
10635 (old-pos (point))
10636 (old-mode major-mode))
10637 (lambda ()
10638 (and (derived-mode-p 'org-mode)
10639 (eq old-mode 'org-mode)
10640 (or (not (eq old-buffer (current-buffer)))
10641 (not (eq old-pos (point))))
10642 (org-mark-ring-push old-pos old-buffer)))))
10643 cmd link-match-data)
10644 (cond
10645 ((member in-emacs '((16) system))
10646 (setq cmd (cdr (assq 'system apps))))
10647 (in-emacs (setq cmd 'emacs))
10649 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10650 (and dirp (cdr (assq 'directory apps)))
10651 ;; First, try matching against apps-dlink if we
10652 ;; get a match here, store the match data for
10653 ;; later.
10654 (let ((match (assoc-default dlink apps-dlink
10655 'string-match)))
10656 (if match
10657 (progn (setq link-match-data (match-data))
10658 match)
10659 (progn (setq in-emacs (or in-emacs line search))
10660 nil))) ; if we have no match in apps-dlink,
10661 ; always open the file in emacs if line or search
10662 ; is given (for backwards compatibility)
10663 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10664 'string-match)
10665 (cdr (assoc ext apps))
10666 (cdr (assq t apps))))))
10667 (when (eq cmd 'system)
10668 (setq cmd (cdr (assq 'system apps))))
10669 (when (eq cmd 'default)
10670 (setq cmd (cdr (assoc t apps))))
10671 (when (eq cmd 'mailcap)
10672 (require 'mailcap)
10673 (mailcap-parse-mailcaps)
10674 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10675 (command (mailcap-mime-info mime-type)))
10676 (if (stringp command)
10677 (setq cmd command)
10678 (setq cmd 'emacs))))
10679 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10680 (not (file-exists-p file))
10681 (not org-open-non-existing-files))
10682 (user-error "No such file: %s" file))
10683 (cond
10684 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10685 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10686 (while (string-match "['\"]%s['\"]" cmd)
10687 (setq cmd (replace-match "%s" t t cmd)))
10688 (setq cmd (replace-regexp-in-string
10689 "%s"
10690 (shell-quote-argument (convert-standard-filename file))
10692 nil t))
10694 ;; Replace "%1", "%2" etc. in command with group matches from regex
10695 (save-match-data
10696 (let ((match-index 1)
10697 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10698 (set-match-data link-match-data)
10699 (while (<= match-index number-of-groups)
10700 (let ((regex (concat "%" (number-to-string match-index)))
10701 (replace-with (match-string match-index dlink)))
10702 (while (string-match regex cmd)
10703 (setq cmd (replace-match replace-with t t cmd))))
10704 (setq match-index (+ match-index 1)))))
10706 (save-window-excursion
10707 (message "Running %s...done" cmd)
10708 (start-process-shell-command cmd nil cmd)
10709 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10710 ((or (stringp cmd)
10711 (eq cmd 'emacs))
10712 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10713 (widen)
10714 (cond (line (org-goto-line line)
10715 (when (derived-mode-p 'org-mode) (org-reveal)))
10716 (search (condition-case err
10717 (org-link-search search)
10718 ;; Save position before error-ing out so user
10719 ;; can easily move back to the original buffer.
10720 (error (funcall save-position-maybe)
10721 (error (nth 1 err)))))))
10722 ((functionp cmd)
10723 (save-match-data
10724 (set-match-data link-match-data)
10725 (condition-case nil
10726 (funcall cmd file link)
10727 ;; FIXME: Remove this check when most default installations
10728 ;; of Emacs have at least Org 9.0.
10729 ((debug wrong-number-of-arguments wrong-type-argument
10730 invalid-function)
10731 (user-error "Please see Org News for version 9.0 about \
10732 `org-file-apps'--Lisp error: %S" cmd)))))
10733 ((consp cmd)
10734 ;; FIXME: Remove this check when most default installations of
10735 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10736 ;; fall back to `org-link-frame-setup' for an old usage of
10737 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10738 (user-error "Please see Org News for version 9.0 about \
10739 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10740 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10741 (funcall save-position-maybe)))
10743 (defun org-file-apps-entry-match-against-dlink-p (entry)
10744 "This function returns non-nil if `entry' uses a regular
10745 expression which should be matched against the whole link by
10746 org-open-file.
10748 It assumes that is the case when the entry uses a regular
10749 expression which has at least one grouping construct and the
10750 action is either a lisp form or a command string containing
10751 `%1', i.e. using at least one subexpression match as a
10752 parameter."
10753 (let ((selector (car entry))
10754 (action (cdr entry)))
10755 (if (stringp selector)
10756 (and (> (regexp-opt-depth selector) 0)
10757 (or (and (stringp action)
10758 (string-match "%[0-9]" action))
10759 (consp action)))
10760 nil)))
10762 (defun org-default-apps ()
10763 "Return the default applications for this operating system."
10764 (cond
10765 ((eq system-type 'darwin)
10766 org-file-apps-defaults-macosx)
10767 ((eq system-type 'windows-nt)
10768 org-file-apps-defaults-windowsnt)
10769 (t org-file-apps-defaults-gnu)))
10771 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10772 "Convert extensions to regular expressions in the cars of LIST.
10773 Also, weed out any non-string entries, because the return value is used
10774 only for regexp matching.
10775 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10776 point to the symbol `emacs', indicating that the file should
10777 be opened in Emacs."
10778 (append
10779 (delq nil
10780 (mapcar (lambda (x)
10781 (unless (not (stringp (car x)))
10782 (if (string-match "\\W" (car x))
10784 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10785 list))
10786 (when add-auto-mode
10787 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10789 (defvar ange-ftp-name-format)
10790 (defun org-file-remote-p (file)
10791 "Test whether FILE specifies a location on a remote system.
10792 Return non-nil if the location is indeed remote.
10794 For example, the filename \"/user@host:/foo\" specifies a location
10795 on the system \"/user@host:\"."
10796 (cond ((fboundp 'file-remote-p)
10797 (file-remote-p file))
10798 ((fboundp 'tramp-handle-file-remote-p)
10799 (tramp-handle-file-remote-p file))
10800 ((and (boundp 'ange-ftp-name-format)
10801 (string-match (car ange-ftp-name-format) file))
10802 t)))
10805 ;;;; Refiling
10807 (defun org-get-org-file ()
10808 "Read a filename, with default directory `org-directory'."
10809 (let ((default (or org-default-notes-file remember-data-file)))
10810 (read-file-name (format "File name [%s]: " default)
10811 (file-name-as-directory org-directory)
10812 default)))
10814 (defun org-notes-order-reversed-p ()
10815 "Check if the current file should receive notes in reversed order."
10816 (cond
10817 ((not org-reverse-note-order) nil)
10818 ((eq t org-reverse-note-order) t)
10819 ((not (listp org-reverse-note-order)) nil)
10820 (t (catch 'exit
10821 (dolist (entry org-reverse-note-order)
10822 (when (string-match (car entry) buffer-file-name)
10823 (throw 'exit (cdr entry))))))))
10825 (defvar org-refile-target-table nil
10826 "The list of refile targets, created by `org-refile'.")
10828 (defvar org-agenda-new-buffers nil
10829 "Buffers created to visit agenda files.")
10831 (defvar org-refile-cache nil
10832 "Cache for refile targets.")
10834 (defvar org-refile-markers nil
10835 "All the markers used for caching refile locations.")
10837 (defun org-refile-marker (pos)
10838 "Get a new refile marker, but only if caching is in use."
10839 (if (not org-refile-use-cache)
10841 (let ((m (make-marker)))
10842 (move-marker m pos)
10843 (push m org-refile-markers)
10844 m)))
10846 (defun org-refile-cache-clear ()
10847 "Clear the refile cache and disable all the markers."
10848 (dolist (m org-refile-markers) (move-marker m nil))
10849 (setq org-refile-markers nil)
10850 (setq org-refile-cache nil)
10851 (message "Refile cache has been cleared"))
10853 (defun org-refile-cache-check-set (set)
10854 "Check if all the markers in the cache still have live buffers."
10855 (let (marker)
10856 (catch 'exit
10857 (while (and set (setq marker (nth 3 (pop set))))
10858 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10859 (when (and marker (null (marker-buffer marker)))
10860 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10861 (sit-for 3)
10862 (throw 'exit nil)))
10863 t)))
10865 (defun org-refile-cache-put (set &rest identifiers)
10866 "Push the refile targets SET into the cache, under IDENTIFIERS."
10867 (let* ((key (sha1 (prin1-to-string identifiers)))
10868 (entry (assoc key org-refile-cache)))
10869 (if entry
10870 (setcdr entry set)
10871 (push (cons key set) org-refile-cache))))
10873 (defun org-refile-cache-get (&rest identifiers)
10874 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10875 (cond
10876 ((not org-refile-cache) nil)
10877 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10879 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10880 org-refile-cache))))
10881 (and set (org-refile-cache-check-set set) set)))))
10883 (defvar org-outline-path-cache nil
10884 "Alist between buffer positions and outline paths.
10885 It value is an alist (POSITION . PATH) where POSITION is the
10886 buffer position at the beginning of an entry and PATH is a list
10887 of strings describing the outline path for that entry, in reverse
10888 order.")
10890 (defun org-refile-get-targets (&optional default-buffer)
10891 "Produce a table with refile targets."
10892 (let ((case-fold-search nil)
10893 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10894 (entries (or org-refile-targets '((nil . (:level . 1)))))
10895 targets tgs files desc descre)
10896 (message "Getting targets...")
10897 (with-current-buffer (or default-buffer (current-buffer))
10898 (dolist (entry entries)
10899 (setq files (car entry) desc (cdr entry))
10900 (cond
10901 ((null files) (setq files (list (current-buffer))))
10902 ((eq files 'org-agenda-files)
10903 (setq files (org-agenda-files 'unrestricted)))
10904 ((and (symbolp files) (fboundp files))
10905 (setq files (funcall files)))
10906 ((and (symbolp files) (boundp files))
10907 (setq files (symbol-value files))))
10908 (when (stringp files) (setq files (list files)))
10909 (cond
10910 ((eq (car desc) :tag)
10911 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10912 ((eq (car desc) :todo)
10913 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10914 ((eq (car desc) :regexp)
10915 (setq descre (cdr desc)))
10916 ((eq (car desc) :level)
10917 (setq descre (concat "^\\*\\{" (number-to-string
10918 (if org-odd-levels-only
10919 (1- (* 2 (cdr desc)))
10920 (cdr desc)))
10921 "\\}[ \t]")))
10922 ((eq (car desc) :maxlevel)
10923 (setq descre (concat "^\\*\\{1," (number-to-string
10924 (if org-odd-levels-only
10925 (1- (* 2 (cdr desc)))
10926 (cdr desc)))
10927 "\\}[ \t]")))
10928 (t (error "Bad refiling target description %s" desc)))
10929 (dolist (f files)
10930 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10932 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10933 (progn
10934 (when (bufferp f)
10935 (setq f (buffer-file-name (buffer-base-buffer f))))
10936 (setq f (and f (expand-file-name f)))
10937 (when (eq org-refile-use-outline-path 'file)
10938 (push (list (file-name-nondirectory f) f nil nil) tgs))
10939 (when (eq org-refile-use-outline-path 'buffer-name)
10940 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10941 (when (eq org-refile-use-outline-path 'full-file-path)
10942 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10943 (org-with-wide-buffer
10944 (goto-char (point-min))
10945 (setq org-outline-path-cache nil)
10946 (while (re-search-forward descre nil t)
10947 (beginning-of-line)
10948 (let ((case-fold-search nil))
10949 (looking-at org-complex-heading-regexp))
10950 (let ((begin (point))
10951 (heading (match-string-no-properties 4)))
10952 (unless (or (and
10953 org-refile-target-verify-function
10954 (not
10955 (funcall org-refile-target-verify-function)))
10956 (not heading))
10957 (let ((re (format org-complex-heading-regexp-format
10958 (regexp-quote heading)))
10959 (target
10960 (if (not org-refile-use-outline-path) heading
10961 (mapconcat
10962 #'identity
10963 (append
10964 (pcase org-refile-use-outline-path
10965 (`file (list (file-name-nondirectory
10966 (buffer-file-name
10967 (buffer-base-buffer)))))
10968 (`full-file-path
10969 (list (buffer-file-name
10970 (buffer-base-buffer))))
10971 (`buffer-name
10972 (list (buffer-name
10973 (buffer-base-buffer))))
10974 (_ nil))
10975 (mapcar (lambda (s) (replace-regexp-in-string
10976 "/" "\\/" s nil t))
10977 (org-get-outline-path t t)))
10978 "/"))))
10979 (push (list target f re (org-refile-marker (point)))
10980 tgs)))
10981 (when (= (point) begin)
10982 ;; Verification function has not moved point.
10983 (end-of-line)))))))
10984 (when org-refile-use-cache
10985 (org-refile-cache-put tgs (buffer-file-name) descre))
10986 (setq targets (append tgs targets))))))
10987 (message "Getting targets...done")
10988 (delete-dups (nreverse targets))))
10990 (defun org--get-outline-path-1 (&optional use-cache)
10991 "Return outline path to current headline.
10993 Outline path is a list of strings, in reverse order. When
10994 optional argument USE-CACHE is non-nil, make use of a cache. See
10995 `org-get-outline-path' for details.
10997 Assume buffer is widened and point is on a headline."
10998 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
10999 (let ((p (point))
11000 (heading (let ((case-fold-search nil))
11001 (looking-at org-complex-heading-regexp)
11002 (if (not (match-end 4)) ""
11003 ;; Remove statistics cookies.
11004 (org-trim
11005 (org-link-display-format
11006 (replace-regexp-in-string
11007 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11008 (match-string-no-properties 4))))))))
11009 (if (org-up-heading-safe)
11010 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11011 (when use-cache
11012 (push (cons p path) org-outline-path-cache))
11013 path)
11014 ;; This is a new root node. Since we assume we are moving
11015 ;; forward, we can drop previous cache so as to limit number
11016 ;; of associations there.
11017 (let ((path (list heading)))
11018 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11019 path)))))
11021 (defun org-get-outline-path (&optional with-self use-cache)
11022 "Return the outline path to the current entry.
11024 An outline path is a list of ancestors for current headline, as
11025 a list of strings. Statistics cookies are removed and links are
11026 replaced with their description, if any, or their path otherwise.
11028 When optional argument WITH-SELF is non-nil, the path also
11029 includes the current headline.
11031 When optional argument USE-CACHE is non-nil, cache outline paths
11032 between calls to this function so as to avoid backtracking. This
11033 argument is useful when planning to find more than one outline
11034 path in the same document. In that case, there are two
11035 conditions to satisfy:
11036 - `org-outline-path-cache' is set to nil before starting the
11037 process;
11038 - outline paths are computed by increasing buffer positions."
11039 (org-with-wide-buffer
11040 (and (or (and with-self (org-back-to-heading t))
11041 (org-up-heading-safe))
11042 (reverse (org--get-outline-path-1 use-cache)))))
11044 (defun org-format-outline-path (path &optional width prefix separator)
11045 "Format the outline path PATH for display.
11046 WIDTH is the maximum number of characters that is available.
11047 PREFIX is a prefix to be included in the returned string,
11048 such as the file name.
11049 SEPARATOR is inserted between the different parts of the path,
11050 the default is \"/\"."
11051 (setq width (or width 79))
11052 (setq path (delq nil path))
11053 (unless (> width 0)
11054 (user-error "Argument `width' must be positive"))
11055 (setq separator (or separator "/"))
11056 (let* ((org-odd-levels-only nil)
11057 (fpath (concat
11058 prefix (and prefix path separator)
11059 (mapconcat
11060 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11061 (cl-loop for head in path
11062 for n from 0
11063 collect (org-add-props
11064 head nil 'face
11065 (nth (% n org-n-level-faces) org-level-faces)))
11066 separator))))
11067 (when (> (length fpath) width)
11068 (if (< width 7)
11069 ;; It's unlikely that `width' will be this small, but don't
11070 ;; waste characters by adding ".." if it is.
11071 (setq fpath (substring fpath 0 width))
11072 (setf (substring fpath (- width 2)) "..")))
11073 fpath))
11075 (defun org-display-outline-path (&optional file current separator just-return-string)
11076 "Display the current outline path in the echo area.
11078 If FILE is non-nil, prepend the output with the file name.
11079 If CURRENT is non-nil, append the current heading to the output.
11080 SEPARATOR is passed through to `org-format-outline-path'. It separates
11081 the different parts of the path and defaults to \"/\".
11082 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11083 (interactive "P")
11084 (let* (case-fold-search
11085 (bfn (buffer-file-name (buffer-base-buffer)))
11086 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11087 res)
11088 (when current (setq path (append path
11089 (save-excursion
11090 (org-back-to-heading t)
11091 (when (looking-at org-complex-heading-regexp)
11092 (list (match-string 4)))))))
11093 (setq res
11094 (org-format-outline-path
11095 path
11096 (1- (frame-width))
11097 (and file bfn (concat (file-name-nondirectory bfn) separator))
11098 separator))
11099 (if just-return-string
11100 (org-no-properties res)
11101 (org-unlogged-message "%s" res))))
11103 (defvar org-refile-history nil
11104 "History for refiling operations.")
11106 (defvar org-after-refile-insert-hook nil
11107 "Hook run after `org-refile' has inserted its stuff at the new location.
11108 Note that this is still *before* the stuff will be removed from
11109 the *old* location.")
11111 (defvar org-capture-last-stored-marker)
11112 (defvar org-refile-keep nil
11113 "Non-nil means `org-refile' will copy instead of refile.")
11115 (defun org-copy ()
11116 "Like `org-refile', but copy."
11117 (interactive)
11118 (let ((org-refile-keep t))
11119 (funcall 'org-refile nil nil nil "Copy")))
11121 (defun org-refile (&optional arg default-buffer rfloc msg)
11122 "Move the entry or entries at point to another heading.
11124 The list of target headings is compiled using the information in
11125 `org-refile-targets', which see.
11127 At the target location, the entry is filed as a subitem of the
11128 target heading. Depending on `org-reverse-note-order', the new
11129 subitem will either be the first or the last subitem.
11131 If there is an active region, all entries in that region will be
11132 refiled. However, the region must fulfill the requirement that
11133 the first heading sets the top-level of the moved text.
11135 With a `\\[universal-argument]' ARG, the command will only visit the target \
11136 location
11137 and not actually move anything.
11139 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11140 location where the last
11141 refiling operation has put the subtree.
11143 With a numeric prefix argument of `2', refile to the running clock.
11145 With a numeric prefix argument of `3', emulate `org-refile-keep'
11146 being set to t and copy to the target location, don't move it.
11147 Beware that keeping refiled entries may result in duplicated ID
11148 properties.
11150 RFLOC can be a refile location obtained in a different way.
11152 MSG is a string to replace \"Refile\" in the default prompt with
11153 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11155 See also `org-refile-use-outline-path'.
11157 If you are using target caching (see `org-refile-use-cache'), you
11158 have to clear the target cache in order to find new targets.
11159 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11160 prefix argument (`C-u C-u C-u C-c C-w')."
11161 (interactive "P")
11162 (if (member arg '(0 (64)))
11163 (org-refile-cache-clear)
11164 (let* ((actionmsg (cond (msg msg)
11165 ((equal arg 3) "Refile (and keep)")
11166 (t "Refile")))
11167 (regionp (org-region-active-p))
11168 (region-start (and regionp (region-beginning)))
11169 (region-end (and regionp (region-end)))
11170 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11171 pos it nbuf file level reversed)
11172 (setq last-command nil)
11173 (when regionp
11174 (goto-char region-start)
11175 (or (bolp) (goto-char (point-at-bol)))
11176 (setq region-start (point))
11177 (unless (or (org-kill-is-subtree-p
11178 (buffer-substring region-start region-end))
11179 (prog1 org-refile-active-region-within-subtree
11180 (let ((s (point-at-eol)))
11181 (org-toggle-heading)
11182 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11183 (user-error "The region is not a (sequence of) subtree(s)")))
11184 (if (equal arg '(16))
11185 (org-refile-goto-last-stored)
11186 (when (or
11187 (and (equal arg 2)
11188 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11189 (prog1
11190 (setq it (list (or org-clock-heading "running clock")
11191 (buffer-file-name
11192 (marker-buffer org-clock-hd-marker))
11194 (marker-position org-clock-hd-marker)))
11195 (setq arg nil)))
11196 (setq it
11197 (or rfloc
11198 (let (heading-text)
11199 (save-excursion
11200 (unless (and arg (listp arg))
11201 (org-back-to-heading t)
11202 (setq heading-text
11203 (replace-regexp-in-string
11204 org-bracket-link-regexp
11205 "\\3"
11206 (or (nth 4 (org-heading-components))
11207 ""))))
11208 (org-refile-get-location
11209 (cond ((and arg (listp arg)) "Goto")
11210 (regionp (concat actionmsg " region to"))
11211 (t (concat actionmsg " subtree \""
11212 heading-text "\" to")))
11213 default-buffer
11214 (and (not (equal '(4) arg))
11215 org-refile-allow-creating-parent-nodes)))))))
11216 (setq file (nth 1 it)
11217 pos (nth 3 it))
11218 (when (and (not arg)
11220 (equal (buffer-file-name) file)
11221 (if regionp
11222 (and (>= pos region-start)
11223 (<= pos region-end))
11224 (and (>= pos (point))
11225 (< pos (save-excursion
11226 (org-end-of-subtree t t))))))
11227 (error "Cannot refile to position inside the tree or region"))
11228 (setq nbuf (or (find-buffer-visiting file)
11229 (find-file-noselect file)))
11230 (if (and arg (not (equal arg 3)))
11231 (progn
11232 (pop-to-buffer-same-window nbuf)
11233 (goto-char (cond (pos)
11234 ((org-notes-order-reversed-p) (point-min))
11235 (t (point-max))))
11236 (org-show-context 'org-goto))
11237 (if regionp
11238 (progn
11239 (org-kill-new (buffer-substring region-start region-end))
11240 (org-save-markers-in-region region-start region-end))
11241 (org-copy-subtree 1 nil t))
11242 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11243 (find-file-noselect file)))
11244 (setq reversed (org-notes-order-reversed-p))
11245 (org-with-wide-buffer
11246 (if pos
11247 (progn
11248 (goto-char pos)
11249 (setq level (org-get-valid-level (funcall outline-level) 1))
11250 (goto-char
11251 (if reversed
11252 (or (outline-next-heading) (point-max))
11253 (or (save-excursion (org-get-next-sibling))
11254 (org-end-of-subtree t t)
11255 (point-max)))))
11256 (setq level 1)
11257 (if (not reversed)
11258 (goto-char (point-max))
11259 (goto-char (point-min))
11260 (or (outline-next-heading) (goto-char (point-max)))))
11261 (unless (bolp) (newline))
11262 (org-paste-subtree level nil nil t)
11263 (when org-log-refile
11264 (org-add-log-setup 'refile nil nil org-log-refile)
11265 (unless (eq org-log-refile 'note)
11266 (save-excursion (org-add-log-note))))
11267 (and org-auto-align-tags
11268 (let ((org-loop-over-headlines-in-active-region nil))
11269 (org-set-tags nil t)))
11270 (let ((bookmark-name (plist-get org-bookmark-names-plist
11271 :last-refile)))
11272 (when bookmark-name
11273 (with-demoted-errors
11274 (bookmark-set bookmark-name))))
11275 ;; If we are refiling for capture, make sure that the
11276 ;; last-capture pointers point here
11277 (when (bound-and-true-p org-capture-is-refiling)
11278 (let ((bookmark-name (plist-get org-bookmark-names-plist
11279 :last-capture-marker)))
11280 (when bookmark-name
11281 (with-demoted-errors
11282 (bookmark-set bookmark-name))))
11283 (move-marker org-capture-last-stored-marker (point)))
11284 (when (fboundp 'deactivate-mark) (deactivate-mark))
11285 (run-hooks 'org-after-refile-insert-hook)))
11286 (unless org-refile-keep
11287 (if regionp
11288 (delete-region (point) (+ (point) (- region-end region-start)))
11289 (org-preserve-local-variables
11290 (delete-region
11291 (and (org-back-to-heading t) (point))
11292 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11293 (when (featurep 'org-inlinetask)
11294 (org-inlinetask-remove-END-maybe))
11295 (setq org-markers-to-move nil)
11296 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11298 (defun org-refile-goto-last-stored ()
11299 "Go to the location where the last refile was stored."
11300 (interactive)
11301 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11302 (message "This is the location of the last refile"))
11304 (defun org-refile--get-location (refloc tbl)
11305 "When user refile to REFLOC, find the associated target in TBL.
11306 Also check `org-refile-target-table'."
11307 (car (delq
11309 (mapcar
11310 (lambda (r) (or (assoc r tbl)
11311 (assoc r org-refile-target-table)))
11312 (list (replace-regexp-in-string "/$" "" refloc)
11313 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11315 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11316 "Prompt the user for a refile location, using PROMPT.
11317 PROMPT should not be suffixed with a colon and a space, because
11318 this function appends the default value from
11319 `org-refile-history' automatically, if that is not empty."
11320 (let ((org-refile-targets org-refile-targets)
11321 (org-refile-use-outline-path org-refile-use-outline-path))
11322 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11323 (unless org-refile-target-table
11324 (user-error "No refile targets"))
11325 (let* ((cbuf (current-buffer))
11326 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11327 (cfunc (if (and org-refile-use-outline-path
11328 org-outline-path-complete-in-steps)
11329 #'org-olpath-completing-read
11330 #'completing-read))
11331 (extra (if org-refile-use-outline-path "/" ""))
11332 (cbnex (concat (buffer-name) extra))
11333 (filename (and cfn (expand-file-name cfn)))
11334 (tbl (mapcar
11335 (lambda (x)
11336 (if (and (not (member org-refile-use-outline-path
11337 '(file full-file-path)))
11338 (not (equal filename (nth 1 x))))
11339 (cons (concat (car x) extra " ("
11340 (file-name-nondirectory (nth 1 x)) ")")
11341 (cdr x))
11342 (cons (concat (car x) extra) (cdr x))))
11343 org-refile-target-table))
11344 (completion-ignore-case t)
11345 cdef
11346 (prompt (concat prompt
11347 (or (and (car org-refile-history)
11348 (concat " (default " (car org-refile-history) ")"))
11349 (and (assoc cbnex tbl) (setq cdef cbnex)
11350 (concat " (default " cbnex ")"))) ": "))
11351 pa answ parent-target child parent old-hist)
11352 (setq old-hist org-refile-history)
11353 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11354 nil 'org-refile-history (or cdef (car org-refile-history))))
11355 (if (setq pa (org-refile--get-location answ tbl))
11356 (progn
11357 (org-refile-check-position pa)
11358 (when (or (not org-refile-history)
11359 (not (eq old-hist org-refile-history))
11360 (not (equal (car pa) (car org-refile-history))))
11361 (setq org-refile-history
11362 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11363 org-refile-history
11364 (cdr org-refile-history))))
11365 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11366 (pop org-refile-history)))
11368 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11369 (progn
11370 (setq parent (match-string 1 answ)
11371 child (match-string 2 answ))
11372 (setq parent-target (org-refile--get-location parent tbl))
11373 (when (and parent-target
11374 (or (eq new-nodes t)
11375 (and (eq new-nodes 'confirm)
11376 (y-or-n-p (format "Create new node \"%s\"? "
11377 child)))))
11378 (org-refile-new-child parent-target child)))
11379 (user-error "Invalid target location")))))
11381 (declare-function org-string-nw-p "org-macs" (s))
11382 (defun org-refile-check-position (refile-pointer)
11383 "Check if the refile pointer matches the headline to which it points."
11384 (let* ((file (nth 1 refile-pointer))
11385 (re (nth 2 refile-pointer))
11386 (pos (nth 3 refile-pointer))
11387 buffer)
11388 (if (and (not (markerp pos)) (not file))
11389 (user-error "Please indicate a target file in the refile path")
11390 (when (org-string-nw-p re)
11391 (setq buffer (if (markerp pos)
11392 (marker-buffer pos)
11393 (or (find-buffer-visiting file)
11394 (find-file-noselect file))))
11395 (with-current-buffer buffer
11396 (org-with-wide-buffer
11397 (goto-char pos)
11398 (beginning-of-line 1)
11399 (unless (looking-at-p re)
11400 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11402 (defun org-refile-new-child (parent-target child)
11403 "Use refile target PARENT-TARGET to add new CHILD below it."
11404 (unless parent-target
11405 (error "Cannot find parent for new node"))
11406 (let ((file (nth 1 parent-target))
11407 (pos (nth 3 parent-target))
11408 level)
11409 (with-current-buffer (or (find-buffer-visiting file)
11410 (find-file-noselect file))
11411 (org-with-wide-buffer
11412 (if pos
11413 (goto-char pos)
11414 (goto-char (point-max))
11415 (unless (bolp) (newline)))
11416 (when (looking-at org-outline-regexp)
11417 (setq level (funcall outline-level))
11418 (org-end-of-subtree t t))
11419 (org-back-over-empty-lines)
11420 (insert "\n" (make-string
11421 (if pos (org-get-valid-level level 1) 1) ?*)
11422 " " child "\n")
11423 (beginning-of-line 0)
11424 (list (concat (car parent-target) "/" child) file "" (point))))))
11426 (defun org-olpath-completing-read (prompt collection &rest args)
11427 "Read an outline path like a file name."
11428 (let ((thetable collection))
11429 (apply #'completing-read
11430 prompt
11431 (lambda (string predicate &optional flag)
11432 (cond
11433 ((eq flag nil) (try-completion string thetable))
11434 ((eq flag t)
11435 (let ((l (length string)))
11436 (mapcar (lambda (x)
11437 (let ((r (substring x l))
11438 (f (if (string-match " ([^)]*)$" x)
11439 (match-string 0 x)
11440 "")))
11441 (if (string-match "/" r)
11442 (concat string (substring r 0 (match-end 0)) f)
11443 x)))
11444 (all-completions string thetable predicate))))
11445 ;; Exact match?
11446 ((eq flag 'lambda) (assoc string thetable))))
11447 args)))
11449 ;;;; Dynamic blocks
11451 (defun org-find-dblock (name)
11452 "Find the first dynamic block with name NAME in the buffer.
11453 If not found, stay at current position and return nil."
11454 (let ((case-fold-search t) pos)
11455 (save-excursion
11456 (goto-char (point-min))
11457 (setq pos (and (re-search-forward
11458 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11459 (match-beginning 0))))
11460 (when pos (goto-char pos))
11461 pos))
11463 (defun org-create-dblock (plist)
11464 "Create a dynamic block section, with parameters taken from PLIST.
11465 PLIST must contain a :name entry which is used as the name of the block."
11466 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11467 (end-of-line 1)
11468 (newline))
11469 (let ((col (current-column))
11470 (name (plist-get plist :name)))
11471 (insert "#+BEGIN: " name)
11472 (while plist
11473 (if (eq (car plist) :name)
11474 (setq plist (cddr plist))
11475 (insert " " (prin1-to-string (pop plist)))))
11476 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11477 (beginning-of-line -2)))
11479 (defun org-prepare-dblock ()
11480 "Prepare dynamic block for refresh.
11481 This empties the block, puts the cursor at the insert position and returns
11482 the property list including an extra property :name with the block name."
11483 (unless (looking-at org-dblock-start-re)
11484 (user-error "Not at a dynamic block"))
11485 (let* ((begdel (1+ (match-end 0)))
11486 (name (org-no-properties (match-string 1)))
11487 (params (append (list :name name)
11488 (read (concat "(" (match-string 3) ")")))))
11489 (save-excursion
11490 (beginning-of-line 1)
11491 (skip-chars-forward " \t")
11492 (setq params (plist-put params :indentation-column (current-column))))
11493 (unless (re-search-forward org-dblock-end-re nil t)
11494 (error "Dynamic block not terminated"))
11495 (setq params
11496 (append params
11497 (list :content (buffer-substring
11498 begdel (match-beginning 0)))))
11499 (delete-region begdel (match-beginning 0))
11500 (goto-char begdel)
11501 (open-line 1)
11502 params))
11504 (defun org-map-dblocks (&optional command)
11505 "Apply COMMAND to all dynamic blocks in the current buffer.
11506 If COMMAND is not given, use `org-update-dblock'."
11507 (let ((cmd (or command 'org-update-dblock)))
11508 (save-excursion
11509 (goto-char (point-min))
11510 (while (re-search-forward org-dblock-start-re nil t)
11511 (goto-char (match-beginning 0))
11512 (save-excursion
11513 (condition-case nil
11514 (funcall cmd)
11515 (error (message "Error during update of dynamic block"))))
11516 (unless (re-search-forward org-dblock-end-re nil t)
11517 (error "Dynamic block not terminated"))))))
11519 (defun org-dblock-update (&optional arg)
11520 "User command for updating dynamic blocks.
11521 Update the dynamic block at point. With prefix ARG, update all dynamic
11522 blocks in the buffer."
11523 (interactive "P")
11524 (if arg
11525 (org-update-all-dblocks)
11526 (or (looking-at org-dblock-start-re)
11527 (org-beginning-of-dblock))
11528 (org-update-dblock)))
11530 (defun org-update-dblock ()
11531 "Update the dynamic block at point.
11532 This means to empty the block, parse for parameters and then call
11533 the correct writing function."
11534 (interactive)
11535 (save-excursion
11536 (let* ((win (selected-window))
11537 (pos (point))
11538 (line (org-current-line))
11539 (params (org-prepare-dblock))
11540 (name (plist-get params :name))
11541 (indent (plist-get params :indentation-column))
11542 (cmd (intern (concat "org-dblock-write:" name))))
11543 (message "Updating dynamic block `%s' at line %d..." name line)
11544 (funcall cmd params)
11545 (message "Updating dynamic block `%s' at line %d...done" name line)
11546 (goto-char pos)
11547 (when (and indent (> indent 0))
11548 (setq indent (make-string indent ?\ ))
11549 (save-excursion
11550 (select-window win)
11551 (org-beginning-of-dblock)
11552 (forward-line 1)
11553 (while (not (looking-at org-dblock-end-re))
11554 (insert indent)
11555 (beginning-of-line 2))
11556 (when (looking-at org-dblock-end-re)
11557 (and (looking-at "[ \t]+")
11558 (replace-match ""))
11559 (insert indent)))))))
11561 (defun org-beginning-of-dblock ()
11562 "Find the beginning of the dynamic block at point.
11563 Error if there is no such block at point."
11564 (let ((pos (point))
11565 beg)
11566 (end-of-line 1)
11567 (if (and (re-search-backward org-dblock-start-re nil t)
11568 (setq beg (match-beginning 0))
11569 (re-search-forward org-dblock-end-re nil t)
11570 (> (match-end 0) pos))
11571 (goto-char beg)
11572 (goto-char pos)
11573 (error "Not in a dynamic block"))))
11575 (defun org-update-all-dblocks ()
11576 "Update all dynamic blocks in the buffer.
11577 This function can be used in a hook."
11578 (interactive)
11579 (when (derived-mode-p 'org-mode)
11580 (org-map-dblocks 'org-update-dblock)))
11583 ;;;; Completion
11585 (declare-function org-export-backend-options "ox" (cl-x) t)
11586 (defun org-get-export-keywords ()
11587 "Return a list of all currently understood export keywords.
11588 Export keywords include options, block names, attributes and
11589 keywords relative to each registered export back-end."
11590 (let (keywords)
11591 (dolist (backend
11592 (bound-and-true-p org-export-registered-backends)
11593 (delq nil keywords))
11594 ;; Back-end name (for keywords, like #+LATEX:)
11595 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11596 (dolist (option-entry (org-export-backend-options backend))
11597 ;; Back-end options.
11598 (push (nth 1 option-entry) keywords)))))
11600 (defconst org-options-keywords
11601 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11602 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11603 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11604 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11605 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11607 (defcustom org-structure-template-alist
11608 '((?a . "export ascii")
11609 (?c . "center")
11610 (?C . "comment")
11611 (?e . "example")
11612 (?E . "export")
11613 (?h . "export html")
11614 (?l . "export latex")
11615 (?q . "quote")
11616 (?s . "src")
11617 (?v . "verse"))
11618 "Structure completion elements.
11619 This is an alist of characters and values. When
11620 `org-insert-structure-template' is called, an additional key is
11621 read. The key is first looked up in this alist, and the
11622 corresponding structure is inserted, with \"#+BEGIN_\" and
11623 \"#+END_\" added automatically."
11624 :group 'org-edit-structure
11625 :type '(repeat
11626 (cons (character :tag "Key")
11627 (string :tag "Template")))
11628 :package-version '(Org . "9.2"))
11630 (defun org-insert-structure-template (type)
11631 "Insert a block structure of the type #+begin_foo/#+end_foo.
11632 First read a character, which can be one of the keys in
11633 `org-structure-template-alist'. When it is <TAB>, prompt the
11634 user for a string to use. With an active region, wrap the region
11635 in the block. Otherwise, insert an empty block."
11636 (interactive
11637 (list
11638 (let* ((key (read-key "Key: "))
11639 (struct-string
11640 (or (cdr (assq key org-structure-template-alist))
11641 (and (= key ?\t)
11642 (read-string "Structure type: "))
11643 (user-error "`%c' has no structure definition" key))))
11644 struct-string)))
11645 (let* ((region? (use-region-p))
11646 (s (if region? (region-beginning) (point)))
11647 (e (copy-marker (if region? (region-end) (point)) t))
11648 column)
11649 (when (string-match-p
11650 (concat "\\`" (regexp-opt '("example" "export" "src")))
11651 type)
11652 (org-escape-code-in-region s e))
11653 (goto-char s)
11654 (setq column (current-indentation))
11655 (beginning-of-line)
11656 (indent-to column)
11657 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11658 (goto-char e)
11659 (if (bolp)
11660 (progn
11661 (skip-chars-backward " \n\t")
11662 (forward-line))
11663 (end-of-line)
11664 (insert "\n"))
11665 (indent-to column)
11666 (insert (format "#+end_%s\n"
11667 (car (split-string type))))
11668 (when (or (not region?)
11669 (string-match-p "src\\|\\`export\\'" type))
11670 (goto-char s)
11671 (end-of-line))
11672 (set-marker e nil)))
11674 ;;;; TODO, DEADLINE, Comments
11676 (defun org-toggle-comment ()
11677 "Change the COMMENT state of an entry."
11678 (interactive)
11679 (save-excursion
11680 (org-back-to-heading)
11681 (let ((case-fold-search nil))
11682 (looking-at org-complex-heading-regexp))
11683 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11684 (skip-chars-forward " \t")
11685 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11686 (if (org-in-commented-heading-p t)
11687 (delete-region (point)
11688 (progn (search-forward " " (line-end-position) 'move)
11689 (skip-chars-forward " \t")
11690 (point)))
11691 (insert org-comment-string)
11692 (unless (eolp) (insert " ")))))
11694 (defvar org-last-todo-state-is-todo nil
11695 "This is non-nil when the last TODO state change led to a TODO state.
11696 If the last change removed the TODO tag or switched to DONE, then
11697 this is nil.")
11699 (defvar org-setting-tags nil) ; dynamically skipped
11701 (defvar org-todo-setup-filter-hook nil
11702 "Hook for functions that pre-filter todo specs.
11703 Each function takes a todo spec and returns either nil or the spec
11704 transformed into canonical form." )
11706 (defvar org-todo-get-default-hook nil
11707 "Hook for functions that get a default item for todo.
11708 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11709 nil or a string to be used for the todo mark." )
11711 (defvar org-agenda-headline-snapshot-before-repeat)
11713 (defun org-current-effective-time ()
11714 "Return current time adjusted for `org-extend-today-until' variable."
11715 (let* ((ct (org-current-time))
11716 (dct (decode-time ct))
11717 (ct1
11718 (cond
11719 (org-use-last-clock-out-time-as-effective-time
11720 (or (org-clock-get-last-clock-out-time) ct))
11721 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11722 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11723 (t ct))))
11724 ct1))
11726 (defun org-todo-yesterday (&optional arg)
11727 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11728 (interactive "P")
11729 (if (eq major-mode 'org-agenda-mode)
11730 (apply 'org-agenda-todo-yesterday arg)
11731 (let* ((org-use-effective-time t)
11732 (hour (nth 2 (decode-time (org-current-time))))
11733 (org-extend-today-until (1+ hour)))
11734 (org-todo arg))))
11736 (defvar org-block-entry-blocking ""
11737 "First entry preventing the TODO state change.")
11739 (defun org-cancel-repeater ()
11740 "Cancel a repeater by setting its numeric value to zero."
11741 (interactive)
11742 (save-excursion
11743 (org-back-to-heading t)
11744 (let ((bound1 (point))
11745 (bound0 (save-excursion (outline-next-heading) (point))))
11746 (when (and (re-search-forward
11747 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11748 org-deadline-time-regexp "\\)\\|\\("
11749 org-ts-regexp "\\)")
11750 bound0 t)
11751 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11752 bound1 t))
11753 (replace-match "0" t nil nil 1)))))
11755 (defvar org-state)
11756 (defvar org-blocked-by-checkboxes)
11757 (defun org-todo (&optional arg)
11758 "Change the TODO state of an item.
11760 The state of an item is given by a keyword at the start of the heading,
11761 like
11762 *** TODO Write paper
11763 *** DONE Call mom
11765 The different keywords are specified in the variable `org-todo-keywords'.
11766 By default the available states are \"TODO\" and \"DONE\". So, for this
11767 example: when the item starts with TODO, it is changed to DONE.
11768 When it starts with DONE, the DONE is removed. And when neither TODO nor
11769 DONE are present, add TODO at the beginning of the heading.
11771 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11772 state.
11773 With numeric prefix ARG, switch to that state.
11774 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11775 next set of TODO \
11776 keywords (nextset).
11777 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11778 prefix, circumvent any state blocking.
11779 With a numeric prefix arg of 0, inhibit note taking for the change.
11780 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11782 When called through ELisp, arg is also interpreted in the following way:
11783 `none' -> empty state
11784 \"\" -> switch to empty state
11785 `done' -> switch to DONE
11786 `nextset' -> switch to the next set of keywords
11787 `previousset' -> switch to the previous set of keywords
11788 \"WAITING\" -> switch to the specified keyword, but only if it
11789 really is a member of `org-todo-keywords'."
11790 (interactive "P")
11791 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11792 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11793 'region-start-level 'region))
11794 org-loop-over-headlines-in-active-region)
11795 (org-map-entries
11796 `(org-todo ,arg)
11797 org-loop-over-headlines-in-active-region
11798 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11799 (when (equal arg '(16)) (setq arg 'nextset))
11800 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11801 (let ((org-blocker-hook org-blocker-hook)
11802 commentp
11803 case-fold-search)
11804 (when (equal arg '(64))
11805 (setq arg nil org-blocker-hook nil))
11806 (when (and org-blocker-hook
11807 (or org-inhibit-blocking
11808 (org-entry-get nil "NOBLOCKING")))
11809 (setq org-blocker-hook nil))
11810 (save-excursion
11811 (catch 'exit
11812 (org-back-to-heading t)
11813 (when (org-in-commented-heading-p t)
11814 (org-toggle-comment)
11815 (setq commentp t))
11816 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11817 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11818 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11819 (let* ((match-data (match-data))
11820 (startpos (copy-marker (line-beginning-position)))
11821 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11822 (org-log-done org-log-done)
11823 (org-log-repeat org-log-repeat)
11824 (org-todo-log-states org-todo-log-states)
11825 (org-inhibit-logging
11826 (if (equal arg 0)
11827 (progn (setq arg nil) 'note) org-inhibit-logging))
11828 (this (match-string 1))
11829 (hl-pos (match-beginning 0))
11830 (head (org-get-todo-sequence-head this))
11831 (ass (assoc head org-todo-kwd-alist))
11832 (interpret (nth 1 ass))
11833 (done-word (nth 3 ass))
11834 (final-done-word (nth 4 ass))
11835 (org-last-state (or this ""))
11836 (completion-ignore-case t)
11837 (member (member this org-todo-keywords-1))
11838 (tail (cdr member))
11839 (org-state (cond
11840 ((and org-todo-key-trigger
11841 (or (and (equal arg '(4))
11842 (eq org-use-fast-todo-selection 'prefix))
11843 (and (not arg) org-use-fast-todo-selection
11844 (not (eq org-use-fast-todo-selection
11845 'prefix)))))
11846 ;; Use fast selection.
11847 (org-fast-todo-selection))
11848 ((and (equal arg '(4))
11849 (or (not org-use-fast-todo-selection)
11850 (not org-todo-key-trigger)))
11851 ;; Read a state with completion.
11852 (completing-read
11853 "State: " (mapcar #'list org-todo-keywords-1)
11854 nil t))
11855 ((eq arg 'right)
11856 (if this
11857 (if tail (car tail) nil)
11858 (car org-todo-keywords-1)))
11859 ((eq arg 'left)
11860 (unless (equal member org-todo-keywords-1)
11861 (if this
11862 (nth (- (length org-todo-keywords-1)
11863 (length tail) 2)
11864 org-todo-keywords-1)
11865 (org-last org-todo-keywords-1))))
11866 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11867 (setq arg nil))) ;hack to fall back to cycling
11868 (arg
11869 ;; User or caller requests a specific state.
11870 (cond
11871 ((equal arg "") nil)
11872 ((eq arg 'none) nil)
11873 ((eq arg 'done) (or done-word (car org-done-keywords)))
11874 ((eq arg 'nextset)
11875 (or (car (cdr (member head org-todo-heads)))
11876 (car org-todo-heads)))
11877 ((eq arg 'previousset)
11878 (let ((org-todo-heads (reverse org-todo-heads)))
11879 (or (car (cdr (member head org-todo-heads)))
11880 (car org-todo-heads))))
11881 ((car (member arg org-todo-keywords-1)))
11882 ((stringp arg)
11883 (user-error "State `%s' not valid in this file" arg))
11884 ((nth (1- (prefix-numeric-value arg))
11885 org-todo-keywords-1))))
11886 ((null member) (or head (car org-todo-keywords-1)))
11887 ((equal this final-done-word) nil) ;-> make empty
11888 ((null tail) nil) ;-> first entry
11889 ((memq interpret '(type priority))
11890 (if (eq this-command last-command)
11891 (car tail)
11892 (if (> (length tail) 0)
11893 (or done-word (car org-done-keywords))
11894 nil)))
11896 (car tail))))
11897 (org-state (or
11898 (run-hook-with-args-until-success
11899 'org-todo-get-default-hook org-state org-last-state)
11900 org-state))
11901 (next (if org-state (concat " " org-state " ") " "))
11902 (change-plist (list :type 'todo-state-change :from this :to org-state
11903 :position startpos))
11904 dolog now-done-p)
11905 (when org-blocker-hook
11906 (let (org-blocked-by-checkboxes block-reason)
11907 (setq org-last-todo-state-is-todo
11908 (not (member this org-done-keywords)))
11909 (unless (save-excursion
11910 (save-match-data
11911 (org-with-wide-buffer
11912 (run-hook-with-args-until-failure
11913 'org-blocker-hook change-plist))))
11914 (setq block-reason (if org-blocked-by-checkboxes
11915 "contained checkboxes"
11916 (format "\"%s\"" org-block-entry-blocking)))
11917 (if (called-interactively-p 'interactive)
11918 (user-error "TODO state change from %s to %s blocked (by %s)"
11919 this org-state block-reason)
11920 ;; Fail silently.
11921 (message "TODO state change from %s to %s blocked (by %s)"
11922 this org-state block-reason)
11923 (throw 'exit nil)))))
11924 (store-match-data match-data)
11925 (replace-match next t t)
11926 (cond ((equal this org-state)
11927 (message "TODO state was already %s" (org-trim next)))
11928 ((not (pos-visible-in-window-p hl-pos))
11929 (message "TODO state changed to %s" (org-trim next))))
11930 (unless head
11931 (setq head (org-get-todo-sequence-head org-state)
11932 ass (assoc head org-todo-kwd-alist)
11933 interpret (nth 1 ass)
11934 done-word (nth 3 ass)
11935 final-done-word (nth 4 ass)))
11936 (when (memq arg '(nextset previousset))
11937 (message "Keyword-Set %d/%d: %s"
11938 (- (length org-todo-sets) -1
11939 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11940 (length org-todo-sets)
11941 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11942 (setq org-last-todo-state-is-todo
11943 (not (member org-state org-done-keywords)))
11944 (setq now-done-p (and (member org-state org-done-keywords)
11945 (not (member this org-done-keywords))))
11946 (and logging (org-local-logging logging))
11947 (when (and (or org-todo-log-states org-log-done)
11948 (not (eq org-inhibit-logging t))
11949 (not (memq arg '(nextset previousset))))
11950 ;; We need to look at recording a time and note.
11951 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11952 (nth 2 (assoc this org-todo-log-states))))
11953 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11954 (setq dolog 'time))
11955 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
11956 (and org-state
11957 (member org-state org-not-done-keywords)
11958 (not (member this org-not-done-keywords))))
11959 ;; This is now a todo state and was not one before
11960 ;; If there was a CLOSED time stamp, get rid of it.
11961 (org-add-planning-info nil nil 'closed))
11962 (when (and now-done-p org-log-done)
11963 ;; It is now done, and it was not done before.
11964 (org-add-planning-info 'closed (org-current-effective-time))
11965 (when (and (not dolog) (eq 'note org-log-done))
11966 (org-add-log-setup 'done org-state this 'note)))
11967 (when (and org-state dolog)
11968 ;; This is a non-nil state, and we need to log it.
11969 (org-add-log-setup 'state org-state this dolog)))
11970 ;; Fixup tag positioning.
11971 (org-todo-trigger-tag-changes org-state)
11972 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11973 (when org-provide-todo-statistics
11974 (org-update-parent-todo-statistics))
11975 (run-hooks 'org-after-todo-state-change-hook)
11976 (when (and arg (not (member org-state org-done-keywords)))
11977 (setq head (org-get-todo-sequence-head org-state)))
11978 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11979 ;; Do we need to trigger a repeat?
11980 (when now-done-p
11981 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11982 ;; This is for the agenda, take a snapshot of the headline.
11983 (save-match-data
11984 (setq org-agenda-headline-snapshot-before-repeat
11985 (org-get-heading))))
11986 (org-auto-repeat-maybe org-state))
11987 ;; Fixup cursor location if close to the keyword.
11988 (when (and (outline-on-heading-p)
11989 (not (bolp))
11990 (save-excursion (beginning-of-line 1)
11991 (looking-at org-todo-line-regexp))
11992 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11993 (goto-char (or (match-end 2) (match-end 1)))
11994 (and (looking-at " ") (just-one-space)))
11995 (when org-trigger-hook
11996 (save-excursion
11997 (run-hook-with-args 'org-trigger-hook change-plist)))
11998 (when commentp (org-toggle-comment))))))))
12000 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12001 "Block turning an entry into a TODO, using the hierarchy.
12002 This checks whether the current task should be blocked from state
12003 changes. Such blocking occurs when:
12005 1. The task has children which are not all in a completed state.
12007 2. A task has a parent with the property :ORDERED:, and there
12008 are siblings prior to the current task with incomplete
12009 status.
12011 3. The parent of the task is blocked because it has siblings that should
12012 be done first, or is child of a block grandparent TODO entry."
12014 (if (not org-enforce-todo-dependencies)
12015 t ; if locally turned off don't block
12016 (catch 'dont-block
12017 ;; If this is not a todo state change, or if this entry is already DONE,
12018 ;; do not block
12019 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12020 (member (plist-get change-plist :from)
12021 (cons 'done org-done-keywords))
12022 (member (plist-get change-plist :to)
12023 (cons 'todo org-not-done-keywords))
12024 (not (plist-get change-plist :to)))
12025 (throw 'dont-block t))
12026 ;; If this task has children, and any are undone, it's blocked
12027 (save-excursion
12028 (org-back-to-heading t)
12029 (let ((this-level (funcall outline-level)))
12030 (outline-next-heading)
12031 (let ((child-level (funcall outline-level)))
12032 (while (and (not (eobp))
12033 (> child-level this-level))
12034 ;; this todo has children, check whether they are all
12035 ;; completed
12036 (when (and (not (org-entry-is-done-p))
12037 (org-entry-is-todo-p))
12038 (setq org-block-entry-blocking (org-get-heading))
12039 (throw 'dont-block nil))
12040 (outline-next-heading)
12041 (setq child-level (funcall outline-level))))))
12042 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12043 ;; any previous siblings are undone, it's blocked
12044 (save-excursion
12045 (org-back-to-heading t)
12046 (let* ((pos (point))
12047 (parent-pos (and (org-up-heading-safe) (point)))
12048 (case-fold-search nil))
12049 (unless parent-pos (throw 'dont-block t)) ; no parent
12050 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12051 (forward-line 1)
12052 (re-search-forward org-not-done-heading-regexp pos t))
12053 (setq org-block-entry-blocking (match-string 0))
12054 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12055 ;; Search further up the hierarchy, to see if an ancestor is blocked
12056 (while t
12057 (goto-char parent-pos)
12058 (unless (looking-at org-not-done-heading-regexp)
12059 (throw 'dont-block t)) ; do not block, parent is not a TODO
12060 (setq pos (point))
12061 (setq parent-pos (and (org-up-heading-safe) (point)))
12062 (unless parent-pos (throw 'dont-block t)) ; no parent
12063 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12064 (forward-line 1)
12065 (re-search-forward org-not-done-heading-regexp pos t)
12066 (setq org-block-entry-blocking (org-get-heading)))
12067 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12069 (defcustom org-track-ordered-property-with-tag nil
12070 "Should the ORDERED property also be shown as a tag?
12071 The ORDERED property decides if an entry should require subtasks to be
12072 completed in sequence. Since a property is not very visible, setting
12073 this option means that toggling the ORDERED property with the command
12074 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12075 not relevant for the behavior, but it makes things more visible.
12077 Note that toggling the tag with tags commands will not change the property
12078 and therefore not influence behavior!
12080 This can be t, meaning the tag ORDERED should be used, It can also be a
12081 string to select a different tag for this task."
12082 :group 'org-todo
12083 :type '(choice
12084 (const :tag "No tracking" nil)
12085 (const :tag "Track with ORDERED tag" t)
12086 (string :tag "Use other tag")))
12088 (defun org-toggle-ordered-property ()
12089 "Toggle the ORDERED property of the current entry.
12090 For better visibility, you can track the value of this property with a tag.
12091 See variable `org-track-ordered-property-with-tag'."
12092 (interactive)
12093 (let* ((t1 org-track-ordered-property-with-tag)
12094 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12095 (save-excursion
12096 (org-back-to-heading)
12097 (if (org-entry-get nil "ORDERED")
12098 (progn
12099 (org-delete-property "ORDERED")
12100 (and tag (org-toggle-tag tag 'off))
12101 (message "Subtasks can be completed in arbitrary order"))
12102 (org-entry-put nil "ORDERED" "t")
12103 (and tag (org-toggle-tag tag 'on))
12104 (message "Subtasks must be completed in sequence")))))
12106 (defun org-block-todo-from-checkboxes (change-plist)
12107 "Block turning an entry into a TODO, using checkboxes.
12108 This checks whether the current task should be blocked from state
12109 changes because there are unchecked boxes in this entry."
12110 (if (not org-enforce-todo-checkbox-dependencies)
12111 t ; if locally turned off don't block
12112 (catch 'dont-block
12113 ;; If this is not a todo state change, or if this entry is already DONE,
12114 ;; do not block
12115 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12116 (member (plist-get change-plist :from)
12117 (cons 'done org-done-keywords))
12118 (member (plist-get change-plist :to)
12119 (cons 'todo org-not-done-keywords))
12120 (not (plist-get change-plist :to)))
12121 (throw 'dont-block t))
12122 ;; If this task has checkboxes that are not checked, it's blocked
12123 (save-excursion
12124 (org-back-to-heading t)
12125 (let ((beg (point)) end)
12126 (outline-next-heading)
12127 (setq end (point))
12128 (goto-char beg)
12129 (when (org-list-search-forward
12130 (concat (org-item-beginning-re)
12131 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12132 "\\[[- ]\\]")
12133 end t)
12134 (when (boundp 'org-blocked-by-checkboxes)
12135 (setq org-blocked-by-checkboxes t))
12136 (throw 'dont-block nil))))
12137 t))) ; do not block
12139 (defun org-entry-blocked-p ()
12140 "Non-nil if entry at point is blocked."
12141 (and (not (org-entry-get nil "NOBLOCKING"))
12142 (member (org-entry-get nil "TODO") org-not-done-keywords)
12143 (not (run-hook-with-args-until-failure
12144 'org-blocker-hook
12145 (list :type 'todo-state-change
12146 :position (point)
12147 :from 'todo
12148 :to 'done)))))
12150 (defun org-update-statistics-cookies (all)
12151 "Update the statistics cookie, either from TODO or from checkboxes.
12152 This should be called with the cursor in a line with a statistics
12153 cookie. When called with a \\[universal-argument] prefix, update
12154 all statistics cookies in the buffer."
12155 (interactive "P")
12156 (if all
12157 (progn
12158 (org-update-checkbox-count 'all)
12159 (org-map-entries 'org-update-parent-todo-statistics))
12160 (if (not (org-at-heading-p))
12161 (org-update-checkbox-count)
12162 (let ((pos (point-marker))
12163 end l1 l2)
12164 (ignore-errors (org-back-to-heading t))
12165 (if (not (org-at-heading-p))
12166 (org-update-checkbox-count)
12167 (setq l1 (org-outline-level))
12168 (setq end (save-excursion
12169 (outline-next-heading)
12170 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12171 (point)))
12172 (if (and (save-excursion
12173 (re-search-forward
12174 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12175 (not (save-excursion (re-search-forward
12176 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12177 (org-update-checkbox-count)
12178 (if (and l2 (> l2 l1))
12179 (progn
12180 (goto-char end)
12181 (org-update-parent-todo-statistics))
12182 (goto-char pos)
12183 (beginning-of-line 1)
12184 (while (re-search-forward
12185 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12186 (point-at-eol) t)
12187 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12188 (goto-char pos)
12189 (move-marker pos nil)))))
12191 (defvar org-entry-property-inherited-from) ;; defined below
12192 (defun org-update-parent-todo-statistics ()
12193 "Update any statistics cookie in the parent of the current headline.
12194 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12195 the entire subtree and this will travel up the hierarchy and update
12196 statistics everywhere."
12197 (let* ((prop (save-excursion (org-up-heading-safe)
12198 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12199 (recursive (or (not org-hierarchical-todo-statistics)
12200 (and prop (string-match "\\<recursive\\>" prop))))
12201 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12203 (first t)
12204 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12205 level ltoggle l1 new ndel
12206 (cnt-all 0) (cnt-done 0) is-percent kwd
12207 checkbox-beg cookie-present)
12208 (catch 'exit
12209 (save-excursion
12210 (beginning-of-line 1)
12211 (setq ltoggle (funcall outline-level))
12212 ;; Three situations are to consider:
12214 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12215 ;; to the top-level ancestor on the headline;
12217 ;; 2. If parent has "recursive" property, repeat up to the
12218 ;; headline setting that property, taking inheritance into
12219 ;; account;
12221 ;; 3. Else, move up to direct parent and proceed only once.
12222 (while (and (setq level (org-up-heading-safe))
12223 (or recursive first)
12224 (>= (point) lim))
12225 (setq first nil cookie-present nil)
12226 (unless (and level
12227 (not (string-match
12228 "\\<checkbox\\>"
12229 (downcase (or (org-entry-get nil "COOKIE_DATA")
12230 "")))))
12231 (throw 'exit nil))
12232 (while (re-search-forward box-re (point-at-eol) t)
12233 (setq cnt-all 0 cnt-done 0 cookie-present t)
12234 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12235 (save-match-data
12236 (unless (outline-next-heading) (throw 'exit nil))
12237 (while (and (looking-at org-complex-heading-regexp)
12238 (> (setq l1 (length (match-string 1))) level))
12239 (setq kwd (and (or recursive (= l1 ltoggle))
12240 (match-string 2)))
12241 (if (or (eq org-provide-todo-statistics 'all-headlines)
12242 (and (eq org-provide-todo-statistics t)
12243 (or (member kwd org-done-keywords)))
12244 (and (listp org-provide-todo-statistics)
12245 (stringp (car org-provide-todo-statistics))
12246 (or (member kwd org-provide-todo-statistics)
12247 (member kwd org-done-keywords)))
12248 (and (listp org-provide-todo-statistics)
12249 (listp (car org-provide-todo-statistics))
12250 (or (member kwd (car org-provide-todo-statistics))
12251 (and (member kwd org-done-keywords)
12252 (member kwd (cadr org-provide-todo-statistics))))))
12253 (setq cnt-all (1+ cnt-all))
12254 (and (eq org-provide-todo-statistics t)
12256 (setq cnt-all (1+ cnt-all))))
12257 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12258 (member kwd org-done-keywords))
12259 (and (listp org-provide-todo-statistics)
12260 (listp (car org-provide-todo-statistics))
12261 (member kwd org-done-keywords)
12262 (member kwd (cadr org-provide-todo-statistics)))
12263 (and (listp org-provide-todo-statistics)
12264 (stringp (car org-provide-todo-statistics))
12265 (member kwd org-done-keywords)))
12266 (setq cnt-done (1+ cnt-done)))
12267 (outline-next-heading)))
12268 (setq new
12269 (if is-percent
12270 (format "[%d%%]" (floor (* 100.0 cnt-done)
12271 (max 1 cnt-all)))
12272 (format "[%d/%d]" cnt-done cnt-all))
12273 ndel (- (match-end 0) checkbox-beg))
12274 (goto-char checkbox-beg)
12275 (insert new)
12276 (delete-region (point) (+ (point) ndel))
12277 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12278 (when cookie-present
12279 (run-hook-with-args 'org-after-todo-statistics-hook
12280 cnt-done (- cnt-all cnt-done))))))
12281 (run-hooks 'org-todo-statistics-hook)))
12283 (defvar org-after-todo-statistics-hook nil
12284 "Hook that is called after a TODO statistics cookie has been updated.
12285 Each function is called with two arguments: the number of not-done entries
12286 and the number of done entries.
12288 For example, the following function, when added to this hook, will switch
12289 an entry to DONE when all children are done, and back to TODO when new
12290 entries are set to a TODO status. Note that this hook is only called
12291 when there is a statistics cookie in the headline!
12293 (defun org-summary-todo (n-done n-not-done)
12294 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12295 (let (org-log-done org-log-states) ; turn off logging
12296 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12299 (defvar org-todo-statistics-hook nil
12300 "Hook that is run whenever Org thinks TODO statistics should be updated.
12301 This hook runs even if there is no statistics cookie present, in which case
12302 `org-after-todo-statistics-hook' would not run.")
12304 (defun org-todo-trigger-tag-changes (state)
12305 "Apply the changes defined in `org-todo-state-tags-triggers'."
12306 (let ((l org-todo-state-tags-triggers)
12307 changes)
12308 (when (or (not state) (equal state ""))
12309 (setq changes (append changes (cdr (assoc "" l)))))
12310 (when (and (stringp state) (> (length state) 0))
12311 (setq changes (append changes (cdr (assoc state l)))))
12312 (when (member state org-not-done-keywords)
12313 (setq changes (append changes (cdr (assq 'todo l)))))
12314 (when (member state org-done-keywords)
12315 (setq changes (append changes (cdr (assq 'done l)))))
12316 (dolist (c changes)
12317 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12319 (defun org-local-logging (value)
12320 "Get logging settings from a property VALUE."
12321 ;; Directly set the variables, they are already local.
12322 (setq org-log-done nil
12323 org-log-repeat nil
12324 org-todo-log-states nil)
12325 (dolist (w (split-string value))
12326 (let (a)
12327 (cond
12328 ((setq a (assoc w org-startup-options))
12329 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12330 (set (nth 1 a) (nth 2 a))))
12331 ((setq a (org-extract-log-state-settings w))
12332 (and (member (car a) org-todo-keywords-1)
12333 (push a org-todo-log-states)))))))
12335 (defun org-get-todo-sequence-head (kwd)
12336 "Return the head of the TODO sequence to which KWD belongs.
12337 If KWD is not set, check if there is a text property remembering the
12338 right sequence."
12339 (let (p)
12340 (cond
12341 ((not kwd)
12342 (or (get-text-property (point-at-bol) 'org-todo-head)
12343 (progn
12344 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12345 nil (point-at-eol)))
12346 (get-text-property p 'org-todo-head))))
12347 ((not (member kwd org-todo-keywords-1))
12348 (car org-todo-keywords-1))
12349 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12351 (defun org-fast-todo-selection ()
12352 "Fast TODO keyword selection with single keys.
12353 Returns the new TODO keyword, or nil if no state change should occur."
12354 (let* ((fulltable org-todo-key-alist)
12355 (done-keywords org-done-keywords) ;; needed for the faces.
12356 (maxlen (apply 'max (mapcar
12357 (lambda (x)
12358 (if (stringp (car x)) (string-width (car x)) 0))
12359 fulltable)))
12360 (expert nil)
12361 (fwidth (+ maxlen 3 1 3))
12362 (ncol (/ (- (window-width) 4) fwidth))
12363 tg cnt e c tbl
12364 groups ingroup)
12365 (save-excursion
12366 (save-window-excursion
12367 (if expert
12368 (set-buffer (get-buffer-create " *Org todo*"))
12369 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12370 (erase-buffer)
12371 (setq-local org-done-keywords done-keywords)
12372 (setq tbl fulltable cnt 0)
12373 (while (setq e (pop tbl))
12374 (cond
12375 ((equal e '(:startgroup))
12376 (push '() groups) (setq ingroup t)
12377 (unless (= cnt 0)
12378 (setq cnt 0)
12379 (insert "\n"))
12380 (insert "{ "))
12381 ((equal e '(:endgroup))
12382 (setq ingroup nil cnt 0)
12383 (insert "}\n"))
12384 ((equal e '(:newline))
12385 (unless (= cnt 0)
12386 (setq cnt 0)
12387 (insert "\n")
12388 (setq e (car tbl))
12389 (while (equal (car tbl) '(:newline))
12390 (insert "\n")
12391 (setq tbl (cdr tbl)))))
12393 (setq tg (car e) c (cdr e))
12394 (when ingroup (push tg (car groups)))
12395 (setq tg (org-add-props tg nil 'face
12396 (org-get-todo-face tg)))
12397 (when (and (= cnt 0) (not ingroup)) (insert " "))
12398 (insert "[" c "] " tg (make-string
12399 (- fwidth 4 (length tg)) ?\ ))
12400 (when (= (setq cnt (1+ cnt)) ncol)
12401 (insert "\n")
12402 (when ingroup (insert " "))
12403 (setq cnt 0)))))
12404 (insert "\n")
12405 (goto-char (point-min))
12406 (unless expert (org-fit-window-to-buffer))
12407 (message "[a-z..]:Set [SPC]:clear")
12408 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12409 (cond
12410 ((or (= c ?\C-g)
12411 (and (= c ?q) (not (rassoc c fulltable))))
12412 (setq quit-flag t))
12413 ((= c ?\ ) nil)
12414 ((setq e (rassoc c fulltable) tg (car e))
12416 (t (setq quit-flag t)))))))
12418 (defun org-entry-is-todo-p ()
12419 (member (org-get-todo-state) org-not-done-keywords))
12421 (defun org-entry-is-done-p ()
12422 (member (org-get-todo-state) org-done-keywords))
12424 (defun org-get-todo-state ()
12425 "Return the TODO keyword of the current subtree."
12426 (save-excursion
12427 (org-back-to-heading t)
12428 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12429 (match-end 2)
12430 (match-string 2))))
12432 (defun org-at-date-range-p (&optional inactive-ok)
12433 "Non-nil if point is inside a date range.
12435 When optional argument INACTIVE-OK is non-nil, also consider
12436 inactive time ranges.
12438 When this function returns a non-nil value, match data is set
12439 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12440 on INACTIVE-OK."
12441 (interactive)
12442 (save-excursion
12443 (catch 'exit
12444 (let ((pos (point)))
12445 (skip-chars-backward "^[<\r\n")
12446 (skip-chars-backward "<[")
12447 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12448 (>= (match-end 0) pos)
12449 (throw 'exit t))
12450 (skip-chars-backward "^<[\r\n")
12451 (skip-chars-backward "<[")
12452 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12453 (>= (match-end 0) pos)
12454 (throw 'exit t)))
12455 nil)))
12457 (defun org-get-repeat (&optional timestamp)
12458 "Check if there is a time-stamp with repeater in this entry.
12460 Return the repeater, as a string, or nil. Also return nil when
12461 this function is called before first heading.
12463 When optional argument TIMESTAMP is a string, extract the
12464 repeater from there instead."
12465 (save-match-data
12466 (cond (timestamp
12467 (and (string-match org-repeat-re timestamp)
12468 (match-string-no-properties 1 timestamp)))
12469 ((org-before-first-heading-p) nil)
12471 (save-excursion
12472 (org-back-to-heading t)
12473 (let ((end (org-entry-end-position)))
12474 (catch :repeat
12475 (while (re-search-forward org-repeat-re end t)
12476 (when (save-match-data (org-at-timestamp-p 'agenda))
12477 (throw :repeat (match-string-no-properties 1)))))))))))
12479 (defvar org-last-changed-timestamp)
12480 (defvar org-last-inserted-timestamp)
12481 (defvar org-log-post-message)
12482 (defvar org-log-note-purpose)
12483 (defvar org-log-note-how nil)
12484 (defvar org-log-note-extra)
12485 (defun org-auto-repeat-maybe (done-word)
12486 "Check if the current headline contains a repeated time-stamp.
12488 If yes, set TODO state back to what it was and change the base date
12489 of repeating deadline/scheduled time stamps to new date.
12491 This function is run automatically after each state change to a DONE state."
12492 (let* ((repeat (org-get-repeat))
12493 (aa (assoc org-last-state org-todo-kwd-alist))
12494 (interpret (nth 1 aa))
12495 (head (nth 2 aa))
12496 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12497 (msg "Entry repeats: ")
12498 (org-log-done nil)
12499 (org-todo-log-states nil)
12500 (end (copy-marker (org-entry-end-position))))
12501 (unwind-protect
12502 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12503 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12504 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12505 (and (stringp org-todo-repeat-to-state)
12506 org-todo-repeat-to-state)
12507 (and org-todo-repeat-to-state org-last-state))))
12508 (org-todo (cond
12509 ((and to-state (member to-state org-todo-keywords-1))
12510 to-state)
12511 ((eq interpret 'type) org-last-state)
12512 (head)
12513 (t 'none))))
12514 (org-back-to-heading t)
12515 (org-add-planning-info nil nil 'closed)
12516 ;; When `org-log-repeat' is non-nil or entry contains
12517 ;; a clock, set LAST_REPEAT property.
12518 (when (or org-log-repeat
12519 (catch :clock
12520 (save-excursion
12521 (while (re-search-forward org-clock-line-re end t)
12522 (when (org-at-clock-log-p) (throw :clock t))))))
12523 (org-entry-put nil "LAST_REPEAT" (format-time-string
12524 (org-time-stamp-format t t)
12525 (current-time))))
12526 (when org-log-repeat
12527 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12528 (memq 'org-add-log-note post-command-hook))
12529 ;; We are already setup for some record.
12530 (when (eq org-log-repeat 'note)
12531 ;; Make sure we take a note, not only a time stamp.
12532 (setq org-log-note-how 'note))
12533 ;; Set up for taking a record.
12534 (org-add-log-setup 'state
12535 (or done-word (car org-done-keywords))
12536 org-last-state
12537 org-log-repeat)))
12538 (let ((planning-re (regexp-opt
12539 (list org-scheduled-string org-deadline-string))))
12540 (while (re-search-forward org-ts-regexp end t)
12541 (let* ((ts (match-string 0))
12542 (planning? (org-at-planning-p))
12543 (type (if (not planning?) "Plain:"
12544 (save-excursion
12545 (re-search-backward
12546 planning-re (line-beginning-position) t)
12547 (match-string 0)))))
12548 (cond
12549 ;; Ignore fake time-stamps (e.g., within comments).
12550 ((not (org-at-timestamp-p 'agenda)))
12551 ;; Time-stamps without a repeater are usually
12552 ;; skipped. However, a SCHEDULED time-stamp without
12553 ;; one is removed, as they are no longer relevant.
12554 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12555 ts))
12556 (when (equal type org-scheduled-string)
12557 (org-remove-timestamp-with-keyword type)))
12559 (let ((n (string-to-number (match-string 2 ts)))
12560 (what (match-string 3 ts)))
12561 (when (equal what "w") (setq n (* n 7) what "d"))
12562 (when (and (equal what "h")
12563 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12564 ts)))
12565 (user-error
12566 "Cannot repeat in Repeat in %d hour(s) because no hour \
12567 has been set"
12569 ;; Preparation, see if we need to modify the start
12570 ;; date for the change.
12571 (when (match-end 1)
12572 (let ((time (save-match-data
12573 (org-time-string-to-time ts))))
12574 (cond
12575 ((equal (match-string 1 ts) ".")
12576 ;; Shift starting date to today
12577 (org-timestamp-change
12578 (- (org-today) (time-to-days time))
12579 'day))
12580 ((equal (match-string 1 ts) "+")
12581 (let ((nshiftmax 10)
12582 (nshift 0))
12583 (while (or (= nshift 0)
12584 (not (time-less-p (current-time) time)))
12585 (when (= (cl-incf nshift) nshiftmax)
12586 (or (y-or-n-p
12587 (format "%d repeater intervals were not \
12588 enough to shift date past today. Continue? "
12589 nshift))
12590 (user-error "Abort")))
12591 (org-timestamp-change n (cdr (assoc what whata)))
12592 (org-in-regexp org-ts-regexp3)
12593 (setq ts (match-string 1))
12594 (setq time
12595 (save-match-data
12596 (org-time-string-to-time ts)))))
12597 (org-timestamp-change (- n) (cdr (assoc what whata)))
12598 ;; Rematch, so that we have everything in place
12599 ;; for the real shift.
12600 (org-in-regexp org-ts-regexp3)
12601 (setq ts (match-string 1))
12602 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12603 ts)))))
12604 (save-excursion
12605 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12606 (setq msg
12607 (concat
12608 msg type " " org-last-changed-timestamp " "))))))))
12609 (setq org-log-post-message msg)
12610 (message "%s" msg))
12611 (set-marker end nil))))
12613 (defun org-show-todo-tree (arg)
12614 "Make a compact tree which shows all headlines marked with TODO.
12615 The tree will show the lines where the regexp matches, and all higher
12616 headlines above the match.
12617 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12618 With a numeric prefix N, construct a sparse tree for the Nth element
12619 of `org-todo-keywords-1'."
12620 (interactive "P")
12621 (let ((case-fold-search nil)
12622 (kwd-re
12623 (cond ((null arg) org-not-done-regexp)
12624 ((equal arg '(4))
12625 (let ((kwd
12626 (completing-read "Keyword (or KWD1|KWD2|...): "
12627 (mapcar #'list org-todo-keywords-1))))
12628 (concat "\\("
12629 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12630 "\\)\\>")))
12631 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12632 (regexp-quote (nth (1- (prefix-numeric-value arg))
12633 org-todo-keywords-1)))
12634 (t (user-error "Invalid prefix argument: %s" arg)))))
12635 (message "%d TODO entries found"
12636 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12638 (defun org--deadline-or-schedule (arg type time)
12639 "Insert DEADLINE or SCHEDULE information in current entry.
12640 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12641 `org-schedule' for information about ARG and TIME arguments."
12642 (let* ((deadline? (eq type 'deadline))
12643 (keyword (if deadline? org-deadline-string org-scheduled-string))
12644 (log (if deadline? org-log-redeadline org-log-reschedule))
12645 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12646 (old-date-time (and old-date (org-time-string-to-time old-date)))
12647 ;; Save repeater cookie from either TIME or current scheduled
12648 ;; time stamp. We are going to insert it back at the end of
12649 ;; the process.
12650 (repeater (or (and (org-string-nw-p time)
12651 ;; We use `org-repeat-re' because we need
12652 ;; to tell the difference between a real
12653 ;; repeater and a time delta, e.g. "+2d".
12654 (string-match org-repeat-re time)
12655 (match-string 1 time))
12656 (and (org-string-nw-p old-date)
12657 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12658 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12659 old-date)
12660 (match-string 1 old-date)))))
12661 (pcase arg
12662 (`(4)
12663 (when (and old-date log)
12664 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12665 nil old-date log))
12666 (org-remove-timestamp-with-keyword keyword)
12667 (message (if deadline? "Item no longer has a deadline."
12668 "Item is no longer scheduled.")))
12669 (`(16)
12670 (save-excursion
12671 (org-back-to-heading t)
12672 (let ((regexp (if deadline? org-deadline-time-regexp
12673 org-scheduled-time-regexp)))
12674 (if (not (re-search-forward regexp (line-end-position 2) t))
12675 (user-error (if deadline? "No deadline information to update"
12676 "No scheduled information to update"))
12677 (let* ((rpl0 (match-string 1))
12678 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12679 (msg (if deadline? "Warn starting from" "Delay until")))
12680 (replace-match
12681 (concat keyword
12682 " <" rpl
12683 (format " -%dd"
12684 (abs (- (time-to-days
12685 (save-match-data
12686 (org-read-date
12687 nil t nil msg old-date-time)))
12688 (time-to-days old-date-time))))
12689 ">") t t))))))
12691 (org-add-planning-info type time 'closed)
12692 (when (and old-date
12694 (not (equal old-date org-last-inserted-timestamp)))
12695 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12696 org-last-inserted-timestamp
12697 old-date
12698 log))
12699 (when repeater
12700 (save-excursion
12701 (org-back-to-heading t)
12702 (when (re-search-forward
12703 (concat keyword " " org-last-inserted-timestamp)
12704 (line-end-position 2)
12706 (goto-char (1- (match-end 0)))
12707 (insert " " repeater)
12708 (setq org-last-inserted-timestamp
12709 (concat (substring org-last-inserted-timestamp 0 -1)
12710 " " repeater
12711 (substring org-last-inserted-timestamp -1))))))
12712 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12713 org-last-inserted-timestamp)))))
12715 (defun org-deadline (arg &optional time)
12716 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12717 With one universal prefix argument, remove any deadline from the item.
12718 With two universal prefix arguments, prompt for a warning delay.
12719 With argument TIME, set the deadline at the corresponding date. TIME
12720 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12721 (interactive "P")
12722 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12723 (org-map-entries
12724 (lambda () (org--deadline-or-schedule arg 'deadline time))
12726 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12727 'region-start-level
12728 'region)
12729 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12730 (org--deadline-or-schedule arg 'deadline time)))
12732 (defun org-schedule (arg &optional time)
12733 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12734 With one universal prefix argument, remove any scheduling date from the item.
12735 With two universal prefix arguments, prompt for a delay cookie.
12736 With argument TIME, scheduled at the corresponding date. TIME can
12737 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12738 (interactive "P")
12739 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12740 (org-map-entries
12741 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12743 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12744 'region-start-level
12745 'region)
12746 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12747 (org--deadline-or-schedule arg 'scheduled time)))
12749 (defun org-get-scheduled-time (pom &optional inherit)
12750 "Get the scheduled time as a time tuple, of a format suitable
12751 for calling org-schedule with, or if there is no scheduling,
12752 returns nil."
12753 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12754 (when time
12755 (apply 'encode-time (org-parse-time-string time)))))
12757 (defun org-get-deadline-time (pom &optional inherit)
12758 "Get the deadline as a time tuple, of a format suitable for
12759 calling org-deadline with, or if there is no scheduling, returns
12760 nil."
12761 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12762 (when time
12763 (apply 'encode-time (org-parse-time-string time)))))
12765 (defun org-remove-timestamp-with-keyword (keyword)
12766 "Remove all time stamps with KEYWORD in the current entry."
12767 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12768 beg)
12769 (save-excursion
12770 (org-back-to-heading t)
12771 (setq beg (point))
12772 (outline-next-heading)
12773 (while (re-search-backward re beg t)
12774 (replace-match "")
12775 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12776 (equal (char-before) ?\ ))
12777 (backward-delete-char 1)
12778 (when (string-match "^[ \t]*$" (buffer-substring
12779 (point-at-bol) (point-at-eol)))
12780 (delete-region (point-at-bol)
12781 (min (point-max) (1+ (point-at-eol))))))))))
12783 (defvar org-time-was-given) ; dynamically scoped parameter
12784 (defvar org-end-time-was-given) ; dynamically scoped parameter
12786 (defun org-at-planning-p ()
12787 "Non-nil when point is on a planning info line."
12788 ;; This is as accurate and faster than `org-element-at-point' since
12789 ;; planning info location is fixed in the section.
12790 (org-with-wide-buffer
12791 (beginning-of-line)
12792 (and (looking-at-p org-planning-line-re)
12793 (eq (point)
12794 (ignore-errors
12795 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12796 (org-back-to-heading t)
12797 (org-with-limited-levels (org-back-to-heading t)))
12798 (line-beginning-position 2))))))
12800 (defun org-add-planning-info (what &optional time &rest remove)
12801 "Insert new timestamp with keyword in the planning line.
12802 WHAT indicates what kind of time stamp to add. It is a symbol
12803 among `closed', `deadline', `scheduled' and nil. TIME indicates
12804 the time to use. If none is given, the user is prompted for
12805 a date. REMOVE indicates what kind of entries to remove. An old
12806 WHAT entry will also be removed."
12807 (let (org-time-was-given org-end-time-was-given default-time default-input)
12808 (catch 'exit
12809 (when (and (memq what '(scheduled deadline))
12810 (or (not time)
12811 (and (stringp time)
12812 (string-match "^[-+]+[0-9]" time))))
12813 ;; Try to get a default date/time from existing timestamp
12814 (save-excursion
12815 (org-back-to-heading t)
12816 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12817 (when (re-search-forward (if (eq what 'scheduled)
12818 org-scheduled-time-regexp
12819 org-deadline-time-regexp)
12820 end t)
12821 (setq ts (match-string 1)
12822 default-time (apply 'encode-time (org-parse-time-string ts))
12823 default-input (and ts (org-get-compact-tod ts)))))))
12824 (when what
12825 (setq time
12826 (if (stringp time)
12827 ;; This is a string (relative or absolute), set
12828 ;; proper date.
12829 (apply #'encode-time
12830 (org-read-date-analyze
12831 time default-time (decode-time default-time)))
12832 ;; If necessary, get the time from the user
12833 (or time (org-read-date nil 'to-time nil nil
12834 default-time default-input)))))
12836 (org-with-wide-buffer
12837 (org-back-to-heading t)
12838 (forward-line)
12839 (unless (bolp) (insert "\n"))
12840 (cond ((looking-at-p org-planning-line-re)
12841 ;; Move to current indentation.
12842 (skip-chars-forward " \t")
12843 ;; Check if we have to remove something.
12844 (dolist (type (if what (cons what remove) remove))
12845 (save-excursion
12846 (when (re-search-forward
12847 (cl-case type
12848 (closed org-closed-time-regexp)
12849 (deadline org-deadline-time-regexp)
12850 (scheduled org-scheduled-time-regexp)
12851 (otherwise
12852 (error "Invalid planning type: %s" type)))
12853 (line-end-position) t)
12854 ;; Delete until next keyword or end of line.
12855 (delete-region
12856 (match-beginning 0)
12857 (if (re-search-forward org-keyword-time-not-clock-regexp
12858 (line-end-position)
12860 (match-beginning 0)
12861 (line-end-position))))))
12862 ;; If there is nothing more to add and no more keyword
12863 ;; is left, remove the line completely.
12864 (if (and (looking-at-p "[ \t]*$") (not what))
12865 (delete-region (line-beginning-position)
12866 (line-beginning-position 2))
12867 ;; If we removed last keyword, do not leave trailing
12868 ;; white space at the end of line.
12869 (let ((p (point)))
12870 (save-excursion
12871 (end-of-line)
12872 (unless (= (skip-chars-backward " \t" p) 0)
12873 (delete-region (point) (line-end-position)))))))
12874 ((not what) (throw 'exit nil)) ; Nothing to do.
12875 (t (insert-before-markers "\n")
12876 (backward-char 1)
12877 (when org-adapt-indentation
12878 (indent-to-column (1+ (org-outline-level))))))
12879 (when what
12880 ;; Insert planning keyword.
12881 (insert (cl-case what
12882 (closed org-closed-string)
12883 (deadline org-deadline-string)
12884 (scheduled org-scheduled-string)
12885 (otherwise (error "Invalid planning type: %s" what)))
12886 " ")
12887 ;; Insert associated timestamp.
12888 (let ((ts (org-insert-time-stamp
12889 time
12890 (or org-time-was-given
12891 (and (eq what 'closed) org-log-done-with-time))
12892 (eq what 'closed)
12893 nil nil (list org-end-time-was-given))))
12894 (unless (eolp) (insert " "))
12895 ts))))))
12897 (defvar org-log-note-marker (make-marker)
12898 "Marker pointing at the entry where the note is to be inserted.")
12899 (defvar org-log-note-purpose nil)
12900 (defvar org-log-note-state nil)
12901 (defvar org-log-note-previous-state nil)
12902 (defvar org-log-note-extra nil)
12903 (defvar org-log-note-window-configuration nil)
12904 (defvar org-log-note-return-to (make-marker))
12905 (defvar org-log-note-effective-time nil
12906 "Remembered current time so that dynamically scoped
12907 `org-extend-today-until' affects timestamps in state change log")
12909 (defvar org-log-post-message nil
12910 "Message to be displayed after a log note has been stored.
12911 The auto-repeater uses this.")
12913 (defun org-add-note ()
12914 "Add a note to the current entry.
12915 This is done in the same way as adding a state change note."
12916 (interactive)
12917 (org-add-log-setup 'note))
12919 (defun org-log-beginning (&optional create)
12920 "Return expected start of log notes in current entry.
12921 When optional argument CREATE is non-nil, the function creates
12922 a drawer to store notes, if necessary. Returned position ignores
12923 narrowing."
12924 (org-with-wide-buffer
12925 (let ((drawer (org-log-into-drawer)))
12926 (cond
12927 (drawer
12928 (org-end-of-meta-data)
12929 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
12930 (end (if (org-at-heading-p) (point)
12931 (save-excursion (outline-next-heading) (point))))
12932 (case-fold-search t))
12933 (catch 'exit
12934 ;; Try to find existing drawer.
12935 (while (re-search-forward regexp end t)
12936 (let ((element (org-element-at-point)))
12937 (when (eq (org-element-type element) 'drawer)
12938 (let ((cend (org-element-property :contents-end element)))
12939 (when (and (not org-log-states-order-reversed) cend)
12940 (goto-char cend)))
12941 (throw 'exit nil))))
12942 ;; No drawer found. Create one, if permitted.
12943 (when create
12944 (unless (bolp) (insert "\n"))
12945 (let ((beg (point)))
12946 (insert ":" drawer ":\n:END:\n")
12947 (org-indent-region beg (point)))
12948 (end-of-line -1)))))
12950 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
12951 (skip-chars-forward " \t\n")
12952 (beginning-of-line)
12953 (unless org-log-states-order-reversed
12954 (org-skip-over-state-notes)
12955 (skip-chars-backward " \t\n")
12956 (forward-line)))))
12957 (if (bolp) (point) (line-beginning-position 2))))
12959 (defun org-add-log-setup (&optional purpose state prev-state how extra)
12960 "Set up the post command hook to take a note.
12961 If this is about to TODO state change, the new state is expected in STATE.
12962 HOW is an indicator what kind of note should be created.
12963 EXTRA is additional text that will be inserted into the notes buffer."
12964 (move-marker org-log-note-marker (point))
12965 (setq org-log-note-purpose purpose
12966 org-log-note-state state
12967 org-log-note-previous-state prev-state
12968 org-log-note-how how
12969 org-log-note-extra extra
12970 org-log-note-effective-time (org-current-effective-time))
12971 (add-hook 'post-command-hook 'org-add-log-note 'append))
12973 (defun org-skip-over-state-notes ()
12974 "Skip past the list of State notes in an entry."
12975 (when (ignore-errors (goto-char (org-in-item-p)))
12976 (let* ((struct (org-list-struct))
12977 (prevs (org-list-prevs-alist struct))
12978 (regexp
12979 (concat "[ \t]*- +"
12980 (replace-regexp-in-string
12981 " +" " +"
12982 (org-replace-escapes
12983 (regexp-quote (cdr (assq 'state org-log-note-headings)))
12984 `(("%d" . ,org-ts-regexp-inactive)
12985 ("%D" . ,org-ts-regexp)
12986 ("%s" . "\"\\S-+\"")
12987 ("%S" . "\"\\S-+\"")
12988 ("%t" . ,org-ts-regexp-inactive)
12989 ("%T" . ,org-ts-regexp)
12990 ("%u" . ".*?")
12991 ("%U" . ".*?")))))))
12992 (while (looking-at-p regexp)
12993 (goto-char (or (org-list-get-next-item (point) struct prevs)
12994 (org-list-get-item-end (point) struct)))))))
12996 (defun org-add-log-note (&optional _purpose)
12997 "Pop up a window for taking a note, and add this note later."
12998 (remove-hook 'post-command-hook 'org-add-log-note)
12999 (setq org-log-note-window-configuration (current-window-configuration))
13000 (delete-other-windows)
13001 (move-marker org-log-note-return-to (point))
13002 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13003 (goto-char org-log-note-marker)
13004 (org-switch-to-buffer-other-window "*Org Note*")
13005 (erase-buffer)
13006 (if (memq org-log-note-how '(time state))
13007 (org-store-log-note)
13008 (let ((org-inhibit-startup t)) (org-mode))
13009 (insert (format "# Insert note for %s.
13010 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13011 (cond
13012 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13013 ((eq org-log-note-purpose 'done) "closed todo item")
13014 ((eq org-log-note-purpose 'state)
13015 (format "state change from \"%s\" to \"%s\""
13016 (or org-log-note-previous-state "")
13017 (or org-log-note-state "")))
13018 ((eq org-log-note-purpose 'reschedule)
13019 "rescheduling")
13020 ((eq org-log-note-purpose 'delschedule)
13021 "no longer scheduled")
13022 ((eq org-log-note-purpose 'redeadline)
13023 "changing deadline")
13024 ((eq org-log-note-purpose 'deldeadline)
13025 "removing deadline")
13026 ((eq org-log-note-purpose 'refile)
13027 "refiling")
13028 ((eq org-log-note-purpose 'note)
13029 "this entry")
13030 (t (error "This should not happen")))))
13031 (when org-log-note-extra (insert org-log-note-extra))
13032 (setq-local org-finish-function 'org-store-log-note)
13033 (run-hooks 'org-log-buffer-setup-hook)))
13035 (defvar org-note-abort nil) ; dynamically scoped
13036 (defun org-store-log-note ()
13037 "Finish taking a log note, and insert it to where it belongs."
13038 (let ((txt (prog1 (buffer-string)
13039 (kill-buffer)))
13040 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13041 lines)
13042 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13043 (setq txt (replace-match "" t t txt)))
13044 (when (string-match "\\s-+\\'" txt)
13045 (setq txt (replace-match "" t t txt)))
13046 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13047 (when (org-string-nw-p note)
13048 (setq note
13049 (org-replace-escapes
13050 note
13051 (list (cons "%u" (user-login-name))
13052 (cons "%U" user-full-name)
13053 (cons "%t" (format-time-string
13054 (org-time-stamp-format 'long 'inactive)
13055 org-log-note-effective-time))
13056 (cons "%T" (format-time-string
13057 (org-time-stamp-format 'long nil)
13058 org-log-note-effective-time))
13059 (cons "%d" (format-time-string
13060 (org-time-stamp-format nil 'inactive)
13061 org-log-note-effective-time))
13062 (cons "%D" (format-time-string
13063 (org-time-stamp-format nil nil)
13064 org-log-note-effective-time))
13065 (cons "%s" (cond
13066 ((not org-log-note-state) "")
13067 ((string-match-p org-ts-regexp
13068 org-log-note-state)
13069 (format "\"[%s]\""
13070 (substring org-log-note-state 1 -1)))
13071 (t (format "\"%s\"" org-log-note-state))))
13072 (cons "%S"
13073 (cond
13074 ((not org-log-note-previous-state) "")
13075 ((string-match-p org-ts-regexp
13076 org-log-note-previous-state)
13077 (format "\"[%s]\""
13078 (substring
13079 org-log-note-previous-state 1 -1)))
13080 (t (format "\"%s\""
13081 org-log-note-previous-state)))))))
13082 (when lines (setq note (concat note " \\\\")))
13083 (push note lines))
13084 (when (and lines (not org-note-abort))
13085 (with-current-buffer (marker-buffer org-log-note-marker)
13086 (org-with-wide-buffer
13087 ;; Find location for the new note.
13088 (goto-char org-log-note-marker)
13089 (set-marker org-log-note-marker nil)
13090 ;; Note associated to a clock is to be located right after
13091 ;; the clock. Do not move point.
13092 (unless (eq org-log-note-purpose 'clock-out)
13093 (goto-char (org-log-beginning t)))
13094 ;; Make sure point is at the beginning of an empty line.
13095 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13096 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13097 ;; In an existing list, add a new item at the top level.
13098 ;; Otherwise, indent line like a regular one.
13099 (let ((itemp (org-in-item-p)))
13100 (if itemp
13101 (indent-line-to
13102 (let ((struct (save-excursion
13103 (goto-char itemp) (org-list-struct))))
13104 (org-list-get-ind (org-list-get-top-point struct) struct)))
13105 (org-indent-line)))
13106 (insert (org-list-bullet-string "-") (pop lines))
13107 (let ((ind (org-list-item-body-column (line-beginning-position))))
13108 (dolist (line lines)
13109 (insert "\n")
13110 (indent-line-to ind)
13111 (insert line)))
13112 (message "Note stored")
13113 (org-back-to-heading t)
13114 (org-cycle-hide-drawers 'children))
13115 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13116 ;; from within `org-add-log-note' because `buffer-undo-list'
13117 ;; is then modified outside of `org-with-remote-undo'.
13118 (when (eq this-command 'org-agenda-todo)
13119 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13120 ;; Don't add undo information when called from `org-agenda-todo'.
13121 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13122 (set-window-configuration org-log-note-window-configuration)
13123 (with-current-buffer (marker-buffer org-log-note-return-to)
13124 (goto-char org-log-note-return-to))
13125 (move-marker org-log-note-return-to nil)
13126 (when org-log-post-message (message "%s" org-log-post-message))))
13128 (defun org-remove-empty-drawer-at (pos)
13129 "Remove an empty drawer at position POS.
13130 POS may also be a marker."
13131 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13132 (org-with-wide-buffer
13133 (goto-char pos)
13134 (let ((drawer (org-element-at-point)))
13135 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13136 (not (org-element-property :contents-begin drawer)))
13137 (delete-region (org-element-property :begin drawer)
13138 (progn (goto-char (org-element-property :end drawer))
13139 (skip-chars-backward " \r\t\n")
13140 (forward-line)
13141 (point))))))))
13143 (defvar org-ts-type nil)
13144 (defun org-sparse-tree (&optional arg type)
13145 "Create a sparse tree, prompt for the details.
13146 This command can create sparse trees. You first need to select the type
13147 of match used to create the tree:
13149 t Show all TODO entries.
13150 T Show entries with a specific TODO keyword.
13151 m Show entries selected by a tags/property match.
13152 p Enter a property name and its value (both with completion on existing
13153 names/values) and show entries with that property.
13154 r Show entries matching a regular expression (`/' can be used as well).
13155 b Show deadlines and scheduled items before a date.
13156 a Show deadlines and scheduled items after a date.
13157 d Show deadlines due within `org-deadline-warning-days'.
13158 D Show deadlines and scheduled items between a date range."
13159 (interactive "P")
13160 (setq type (or type org-sparse-tree-default-date-type))
13161 (setq org-ts-type type)
13162 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13163 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13164 \[c]ycle through date types: %s"
13165 (cl-case type
13166 (all "all timestamps")
13167 (scheduled "only scheduled")
13168 (deadline "only deadline")
13169 (active "only active timestamps")
13170 (inactive "only inactive timestamps")
13171 (closed "with a closed time-stamp")
13172 (otherwise "scheduled/deadline")))
13173 (let ((answer (read-char-exclusive)))
13174 (cl-case answer
13176 (org-sparse-tree
13178 (cadr
13179 (memq type '(nil all scheduled deadline active inactive closed)))))
13180 (?d (call-interactively 'org-check-deadlines))
13181 (?b (call-interactively 'org-check-before-date))
13182 (?a (call-interactively 'org-check-after-date))
13183 (?D (call-interactively 'org-check-dates-range))
13184 (?t (call-interactively 'org-show-todo-tree))
13185 (?T (org-show-todo-tree '(4)))
13186 (?m (call-interactively 'org-match-sparse-tree))
13187 ((?p ?P)
13188 (let* ((kwd (completing-read
13189 "Property: " (mapcar #'list (org-buffer-property-keys))))
13190 (value (completing-read
13191 "Value: " (mapcar #'list (org-property-values kwd)))))
13192 (unless (string-match "\\`{.*}\\'" value)
13193 (setq value (concat "\"" value "\"")))
13194 (org-match-sparse-tree arg (concat kwd "=" value))))
13195 ((?r ?R ?/) (call-interactively 'org-occur))
13196 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13198 (defvar-local org-occur-highlights nil
13199 "List of overlays used for occur matches.")
13200 (defvar-local org-occur-parameters nil
13201 "Parameters of the active org-occur calls.
13202 This is a list, each call to org-occur pushes as cons cell,
13203 containing the regular expression and the callback, onto the list.
13204 The list can contain several entries if `org-occur' has been called
13205 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13206 will only contain one set of parameters. When the highlights are
13207 removed (for example with `C-c C-c', or with the next edit (depending
13208 on `org-remove-highlights-with-change'), this variable is emptied
13209 as well.")
13211 (defun org-occur (regexp &optional keep-previous callback)
13212 "Make a compact tree which shows all matches of REGEXP.
13214 The tree will show the lines where the regexp matches, and any other context
13215 defined in `org-show-context-detail', which see.
13217 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13218 done by a previous call to `org-occur' will be kept, to allow stacking of
13219 calls to this command.
13221 Optional argument CALLBACK can be a function of no argument. In this case,
13222 it is called with point at the end of the match, match data being set
13223 accordingly. Current match is shown only if the return value is non-nil.
13224 The function must neither move point nor alter narrowing."
13225 (interactive "sRegexp: \nP")
13226 (when (equal regexp "")
13227 (user-error "Regexp cannot be empty"))
13228 (unless keep-previous
13229 (org-remove-occur-highlights nil nil t))
13230 (push (cons regexp callback) org-occur-parameters)
13231 (let ((cnt 0))
13232 (save-excursion
13233 (goto-char (point-min))
13234 (when (or (not keep-previous) ; do not want to keep
13235 (not org-occur-highlights)) ; no previous matches
13236 ;; hide everything
13237 (org-overview))
13238 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13239 (isearch-no-upper-case-p regexp t)
13240 org-occur-case-fold-search)))
13241 (while (re-search-forward regexp nil t)
13242 (when (or (not callback)
13243 (save-match-data (funcall callback)))
13244 (setq cnt (1+ cnt))
13245 (when org-highlight-sparse-tree-matches
13246 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13247 (org-show-context 'occur-tree)))))
13248 (when org-remove-highlights-with-change
13249 (add-hook 'before-change-functions 'org-remove-occur-highlights
13250 nil 'local))
13251 (unless org-sparse-tree-open-archived-trees
13252 (org-hide-archived-subtrees (point-min) (point-max)))
13253 (run-hooks 'org-occur-hook)
13254 (when (called-interactively-p 'interactive)
13255 (message "%d match(es) for regexp %s" cnt regexp))
13256 cnt))
13258 (defun org-occur-next-match (&optional n _reset)
13259 "Function for `next-error-function' to find sparse tree matches.
13260 N is the number of matches to move, when negative move backwards.
13261 This function always goes back to the starting point when no
13262 match is found."
13263 (let* ((limit (if (< n 0) (point-min) (point-max)))
13264 (search-func (if (< n 0)
13265 'previous-single-char-property-change
13266 'next-single-char-property-change))
13267 (n (abs n))
13268 (pos (point))
13270 (catch 'exit
13271 (while (setq p1 (funcall search-func (point) 'org-type))
13272 (when (equal p1 limit)
13273 (goto-char pos)
13274 (user-error "No more matches"))
13275 (when (equal (get-char-property p1 'org-type) 'org-occur)
13276 (setq n (1- n))
13277 (when (= n 0)
13278 (goto-char p1)
13279 (throw 'exit (point))))
13280 (goto-char p1))
13281 (goto-char p1)
13282 (user-error "No more matches"))))
13284 (defun org-show-context (&optional key)
13285 "Make sure point and context are visible.
13286 Optional argument KEY, when non-nil, is a symbol. See
13287 `org-show-context-detail' for allowed values and how much is to
13288 be shown."
13289 (org-show-set-visibility
13290 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13291 ((cdr (assq key org-show-context-detail)))
13292 (t (cdr (assq 'default org-show-context-detail))))))
13294 (defun org-show-set-visibility (detail)
13295 "Set visibility around point according to DETAIL.
13296 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13297 `tree', `canonical' or t. See `org-show-context-detail' for more
13298 information."
13299 ;; Show current heading and possibly its entry, following headline
13300 ;; or all children.
13301 (if (and (org-at-heading-p) (not (eq detail 'local)))
13302 (org-flag-heading nil)
13303 (org-show-entry)
13304 ;; If point is hidden within a drawer or a block, make sure to
13305 ;; expose it.
13306 (dolist (o (overlays-at (point)))
13307 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13308 (delete-overlay o)))
13309 (unless (org-before-first-heading-p)
13310 (org-with-limited-levels
13311 (cl-case detail
13312 ((tree canonical t) (org-show-children))
13313 ((nil minimal ancestors))
13314 (t (save-excursion
13315 (outline-next-heading)
13316 (org-flag-heading nil)))))))
13317 ;; Show all siblings.
13318 (when (eq detail 'lineage) (org-show-siblings))
13319 ;; Show ancestors, possibly with their children.
13320 (when (memq detail '(ancestors lineage tree canonical t))
13321 (save-excursion
13322 (while (org-up-heading-safe)
13323 (org-flag-heading nil)
13324 (when (memq detail '(canonical t)) (org-show-entry))
13325 (when (memq detail '(tree canonical t)) (org-show-children))))))
13327 (defvar org-reveal-start-hook nil
13328 "Hook run before revealing a location.")
13330 (defun org-reveal (&optional siblings)
13331 "Show current entry, hierarchy above it, and the following headline.
13333 This can be used to show a consistent set of context around
13334 locations exposed with `org-show-context'.
13336 With optional argument SIBLINGS, on each level of the hierarchy all
13337 siblings are shown. This repairs the tree structure to what it would
13338 look like when opened with hierarchical calls to `org-cycle'.
13340 With a \\[universal-argument] \\[universal-argument] prefix, \
13341 go to the parent and show the entire tree."
13342 (interactive "P")
13343 (run-hooks 'org-reveal-start-hook)
13344 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13345 ((equal siblings '(16))
13346 (save-excursion
13347 (when (org-up-heading-safe)
13348 (org-show-subtree)
13349 (run-hook-with-args 'org-cycle-hook 'subtree))))
13350 (t (org-show-set-visibility 'lineage))))
13352 (defun org-highlight-new-match (beg end)
13353 "Highlight from BEG to END and mark the highlight is an occur headline."
13354 (let ((ov (make-overlay beg end)))
13355 (overlay-put ov 'face 'secondary-selection)
13356 (overlay-put ov 'org-type 'org-occur)
13357 (push ov org-occur-highlights)))
13359 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13360 "Remove the occur highlights from the buffer.
13361 BEG and END are ignored. If NOREMOVE is nil, remove this function
13362 from the `before-change-functions' in the current buffer."
13363 (interactive)
13364 (unless org-inhibit-highlight-removal
13365 (mapc #'delete-overlay org-occur-highlights)
13366 (setq org-occur-highlights nil)
13367 (setq org-occur-parameters nil)
13368 (unless noremove
13369 (remove-hook 'before-change-functions
13370 'org-remove-occur-highlights 'local))))
13372 ;;;; Priorities
13374 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13375 "Regular expression matching the priority indicator.")
13377 (defvar org-remove-priority-next-time nil)
13379 (defun org-priority-up ()
13380 "Increase the priority of the current item."
13381 (interactive)
13382 (org-priority 'up))
13384 (defun org-priority-down ()
13385 "Decrease the priority of the current item."
13386 (interactive)
13387 (org-priority 'down))
13389 (defun org-priority (&optional action _show)
13390 "Change the priority of an item.
13391 ACTION can be `set', `up', `down', or a character."
13392 (interactive "P")
13393 (if (equal action '(4))
13394 (org-show-priority)
13395 (unless org-enable-priority-commands
13396 (user-error "Priority commands are disabled"))
13397 (setq action (or action 'set))
13398 (let (current new news have remove)
13399 (save-excursion
13400 (org-back-to-heading t)
13401 (when (looking-at org-priority-regexp)
13402 (setq current (string-to-char (match-string 2))
13403 have t))
13404 (cond
13405 ((eq action 'remove)
13406 (setq remove t new ?\ ))
13407 ((or (eq action 'set)
13408 (integerp action))
13409 (if (not (eq action 'set))
13410 (setq new action)
13411 (message "Priority %c-%c, SPC to remove: "
13412 org-highest-priority org-lowest-priority)
13413 (save-match-data
13414 (setq new (read-char-exclusive))))
13415 (when (and (= (upcase org-highest-priority) org-highest-priority)
13416 (= (upcase org-lowest-priority) org-lowest-priority))
13417 (setq new (upcase new)))
13418 (cond ((equal new ?\ ) (setq remove t))
13419 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13420 (user-error "Priority must be between `%c' and `%c'"
13421 org-highest-priority org-lowest-priority))))
13422 ((eq action 'up)
13423 (setq new (if have
13424 (1- current) ; normal cycling
13425 ;; last priority was empty
13426 (if (eq last-command this-command)
13427 org-lowest-priority ; wrap around empty to lowest
13428 ;; default
13429 (if org-priority-start-cycle-with-default
13430 org-default-priority
13431 (1- org-default-priority))))))
13432 ((eq action 'down)
13433 (setq new (if have
13434 (1+ current) ; normal cycling
13435 ;; last priority was empty
13436 (if (eq last-command this-command)
13437 org-highest-priority ; wrap around empty to highest
13438 ;; default
13439 (if org-priority-start-cycle-with-default
13440 org-default-priority
13441 (1+ org-default-priority))))))
13442 (t (user-error "Invalid action")))
13443 (when (or (< (upcase new) org-highest-priority)
13444 (> (upcase new) org-lowest-priority))
13445 (if (and (memq action '(up down))
13446 (not have) (not (eq last-command this-command)))
13447 ;; `new' is from default priority
13448 (error
13449 "The default can not be set, see `org-default-priority' why")
13450 ;; normal cycling: `new' is beyond highest/lowest priority
13451 ;; and is wrapped around to the empty priority
13452 (setq remove t)))
13453 (setq news (format "%c" new))
13454 (if have
13455 (if remove
13456 (replace-match "" t t nil 1)
13457 (replace-match news t t nil 2))
13458 (if remove
13459 (user-error "No priority cookie found in line")
13460 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13461 (if (match-end 2)
13462 (progn
13463 (goto-char (match-end 2))
13464 (insert " [#" news "]"))
13465 (goto-char (match-beginning 3))
13466 (insert "[#" news "] "))))
13467 (org-set-tags nil 'align))
13468 (if remove
13469 (message "Priority removed")
13470 (message "Priority of current item set to %s" news)))))
13472 (defun org-show-priority ()
13473 "Show the priority of the current item.
13474 This priority is composed of the main priority given with the [#A] cookies,
13475 and by additional input from the age of a schedules or deadline entry."
13476 (interactive)
13477 (let ((pri (if (eq major-mode 'org-agenda-mode)
13478 (org-get-at-bol 'priority)
13479 (save-excursion
13480 (save-match-data
13481 (beginning-of-line)
13482 (and (looking-at org-heading-regexp)
13483 (org-get-priority (match-string 0))))))))
13484 (message "Priority is %d" (if pri pri -1000))))
13486 (defun org-get-priority (s)
13487 "Find priority cookie and return priority."
13488 (save-match-data
13489 (if (functionp org-get-priority-function)
13490 (funcall org-get-priority-function)
13491 (if (not (string-match org-priority-regexp s))
13492 (* 1000 (- org-lowest-priority org-default-priority))
13493 (* 1000 (- org-lowest-priority
13494 (string-to-char (match-string 2 s))))))))
13496 ;;;; Tags
13498 (defvar org-agenda-archives-mode)
13499 (defvar org-map-continue-from nil
13500 "Position from where mapping should continue.
13501 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13503 (defvar org-scanner-tags nil
13504 "The current tag list while the tags scanner is running.")
13506 (defvar org-trust-scanner-tags nil
13507 "Should `org-get-tags-at' use the tags for the scanner.
13508 This is for internal dynamical scoping only.
13509 When this is non-nil, the function `org-get-tags-at' will return the value
13510 of `org-scanner-tags' instead of building the list by itself. This
13511 can lead to large speed-ups when the tags scanner is used in a file with
13512 many entries, and when the list of tags is retrieved, for example to
13513 obtain a list of properties. Building the tags list for each entry in such
13514 a file becomes an N^2 operation - but with this variable set, it scales
13515 as N.")
13517 (defvar org--matcher-tags-todo-only nil)
13519 (defun org-scan-tags (action matcher todo-only &optional start-level)
13520 "Scan headline tags with inheritance and produce output ACTION.
13522 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13523 or `agenda' to produce an entry list for an agenda view. It can also be
13524 a Lisp form or a function that should be called at each matched headline, in
13525 this case the return value is a list of all return values from these calls.
13527 MATCHER is a function accepting three arguments, returning
13528 a non-nil value whenever a given set of tags qualifies a headline
13529 for inclusion. See `org-make-tags-matcher' for more information.
13530 As a special case, it can also be set to t (respectively nil) in
13531 order to match all (respectively none) headline.
13533 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13534 included in the output.
13536 START-LEVEL can be a string with asterisks, reducing the scope to
13537 headlines matching this string."
13538 (require 'org-agenda)
13539 (let* ((re (concat "^"
13540 (if start-level
13541 ;; Get the correct level to match
13542 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13543 org-outline-regexp)
13544 " *\\(\\<\\("
13545 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13546 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13547 (props (list 'face 'default
13548 'done-face 'org-agenda-done
13549 'undone-face 'default
13550 'mouse-face 'highlight
13551 'org-not-done-regexp org-not-done-regexp
13552 'org-todo-regexp org-todo-regexp
13553 'org-complex-heading-regexp org-complex-heading-regexp
13554 'help-echo
13555 (format "mouse-2 or RET jump to org file %s"
13556 (abbreviate-file-name
13557 (or (buffer-file-name (buffer-base-buffer))
13558 (buffer-name (buffer-base-buffer)))))))
13559 (org-map-continue-from nil)
13560 lspos tags tags-list
13561 (tags-alist (list (cons 0 org-file-tags)))
13562 (llast 0) rtn rtn1 level category i txt
13563 todo marker entry priority
13564 ts-date ts-date-type ts-date-pair)
13565 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13566 (setq action (list 'lambda nil action)))
13567 (save-excursion
13568 (goto-char (point-min))
13569 (when (eq action 'sparse-tree)
13570 (org-overview)
13571 (org-remove-occur-highlights))
13572 (while (let (case-fold-search)
13573 (re-search-forward re nil t))
13574 (setq org-map-continue-from nil)
13575 (catch :skip
13576 (setq todo
13577 ;; TODO: is the 1-2 difference a bug?
13578 (when (match-end 1) (match-string-no-properties 2))
13579 tags (when (match-end 4) (match-string-no-properties 4)))
13580 (goto-char (setq lspos (match-beginning 0)))
13581 (setq level (org-reduced-level (org-outline-level))
13582 category (org-get-category))
13583 (when (eq action 'agenda)
13584 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13585 ts-date (car ts-date-pair)
13586 ts-date-type (cdr ts-date-pair)))
13587 (setq i llast llast level)
13588 ;; remove tag lists from same and sublevels
13589 (while (>= i level)
13590 (when (setq entry (assoc i tags-alist))
13591 (setq tags-alist (delete entry tags-alist)))
13592 (setq i (1- i)))
13593 ;; add the next tags
13594 (when tags
13595 (setq tags (org-split-string tags ":")
13596 tags-alist
13597 (cons (cons level tags) tags-alist)))
13598 ;; compile tags for current headline
13599 (setq tags-list
13600 (if org-use-tag-inheritance
13601 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13602 tags)
13603 org-scanner-tags tags-list)
13604 (when org-use-tag-inheritance
13605 (setcdr (car tags-alist)
13606 (mapcar (lambda (x)
13607 (setq x (copy-sequence x))
13608 (org-add-prop-inherited x))
13609 (cdar tags-alist))))
13610 (when (and tags org-use-tag-inheritance
13611 (or (not (eq t org-use-tag-inheritance))
13612 org-tags-exclude-from-inheritance))
13613 ;; Selective inheritance, remove uninherited ones.
13614 (setcdr (car tags-alist)
13615 (org-remove-uninherited-tags (cdar tags-alist))))
13616 (when (and
13618 ;; eval matcher only when the todo condition is OK
13619 (and (or (not todo-only) (member todo org-todo-keywords-1))
13620 (if (functionp matcher)
13621 (let ((case-fold-search t) (org-trust-scanner-tags t))
13622 (funcall matcher todo tags-list level))
13623 matcher))
13625 ;; Call the skipper, but return t if it does not
13626 ;; skip, so that the `and' form continues evaluating.
13627 (progn
13628 (unless (eq action 'sparse-tree) (org-agenda-skip))
13631 ;; Check if timestamps are deselecting this entry
13632 (or (not todo-only)
13633 (and (member todo org-todo-keywords-1)
13634 (or (not org-agenda-tags-todo-honor-ignore-options)
13635 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13637 ;; select this headline
13638 (cond
13639 ((eq action 'sparse-tree)
13640 (and org-highlight-sparse-tree-matches
13641 (org-get-heading) (match-end 0)
13642 (org-highlight-new-match
13643 (match-beginning 1) (match-end 1)))
13644 (org-show-context 'tags-tree))
13645 ((eq action 'agenda)
13646 (setq txt (org-agenda-format-item
13648 (concat
13649 (if (eq org-tags-match-list-sublevels 'indented)
13650 (make-string (1- level) ?.) "")
13651 (org-get-heading))
13652 (make-string level ?\s)
13653 category
13654 tags-list)
13655 priority (org-get-priority txt))
13656 (goto-char lspos)
13657 (setq marker (org-agenda-new-marker))
13658 (org-add-props txt props
13659 'org-marker marker 'org-hd-marker marker 'org-category category
13660 'todo-state todo
13661 'ts-date ts-date
13662 'priority priority
13663 'type (concat "tagsmatch" ts-date-type))
13664 (push txt rtn))
13665 ((functionp action)
13666 (setq org-map-continue-from nil)
13667 (save-excursion
13668 (setq rtn1 (funcall action))
13669 (push rtn1 rtn)))
13670 (t (user-error "Invalid action")))
13672 ;; if we are to skip sublevels, jump to end of subtree
13673 (unless org-tags-match-list-sublevels
13674 (org-end-of-subtree t)
13675 (backward-char 1))))
13676 ;; Get the correct position from where to continue
13677 (if org-map-continue-from
13678 (goto-char org-map-continue-from)
13679 (and (= (point) lspos) (end-of-line 1)))))
13680 (when (and (eq action 'sparse-tree)
13681 (not org-sparse-tree-open-archived-trees))
13682 (org-hide-archived-subtrees (point-min) (point-max)))
13683 (nreverse rtn)))
13685 (defun org-remove-uninherited-tags (tags)
13686 "Remove all tags that are not inherited from the list TAGS."
13687 (cond
13688 ((eq org-use-tag-inheritance t)
13689 (if org-tags-exclude-from-inheritance
13690 (org-delete-all org-tags-exclude-from-inheritance tags)
13691 tags))
13692 ((not org-use-tag-inheritance) nil)
13693 ((stringp org-use-tag-inheritance)
13694 (delq nil (mapcar
13695 (lambda (x)
13696 (if (and (string-match org-use-tag-inheritance x)
13697 (not (member x org-tags-exclude-from-inheritance)))
13698 x nil))
13699 tags)))
13700 ((listp org-use-tag-inheritance)
13701 (delq nil (mapcar
13702 (lambda (x)
13703 (if (member x org-use-tag-inheritance) x nil))
13704 tags)))))
13706 (defun org-match-sparse-tree (&optional todo-only match)
13707 "Create a sparse tree according to tags string MATCH.
13709 MATCH is a string with match syntax. It can contain a selection
13710 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13711 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13712 those. See the manual for details.
13714 If optional argument TODO-ONLY is non-nil, only select lines that
13715 are also TODO tasks."
13716 (interactive "P")
13717 (org-agenda-prepare-buffers (list (current-buffer)))
13718 (let ((org--matcher-tags-todo-only todo-only))
13719 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13720 org--matcher-tags-todo-only)))
13722 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13724 (defvar org-cached-props nil)
13725 (defun org-cached-entry-get (pom property)
13726 (if (or (eq t org-use-property-inheritance)
13727 (and (stringp org-use-property-inheritance)
13728 (let ((case-fold-search t))
13729 (string-match-p org-use-property-inheritance property)))
13730 (and (listp org-use-property-inheritance)
13731 (member-ignore-case property org-use-property-inheritance)))
13732 ;; Caching is not possible, check it directly.
13733 (org-entry-get pom property 'inherit)
13734 ;; Get all properties, so we can do complicated checks easily.
13735 (cdr (assoc-string property
13736 (or org-cached-props
13737 (setq org-cached-props (org-entry-properties pom)))
13738 t))))
13740 (defun org-global-tags-completion-table (&optional files)
13741 "Return the list of all tags in all agenda buffer/files.
13742 Optional FILES argument is a list of files which can be used
13743 instead of the agenda files."
13744 (save-excursion
13745 (org-uniquify
13746 (delq nil
13747 (apply #'append
13748 (mapcar
13749 (lambda (file)
13750 (set-buffer (find-file-noselect file))
13751 (mapcar (lambda (x)
13752 (and (stringp (car-safe x))
13753 (list (car-safe x))))
13754 (or org-current-tag-alist (org-get-buffer-tags))))
13755 (if (car-safe files) files
13756 (org-agenda-files))))))))
13758 (defun org-make-tags-matcher (match)
13759 "Create the TAGS/TODO matcher form for the selection string MATCH.
13761 Returns a cons of the selection string MATCH and a function
13762 implementing the matcher.
13764 The matcher is to be called at an Org entry, with point on the
13765 headline, and returns non-nil if the entry matches the selection
13766 string MATCH. It must be called with three arguments: the TODO
13767 keyword at the entry (or nil if none), the list of all tags at
13768 the entry including inherited ones and the reduced level of the
13769 headline. Additionally, the category of the entry, if any, must
13770 be specified as the text property `org-category' on the headline.
13772 This function sets the variable `org--matcher-tags-todo-only' to
13773 a non-nil value if the matcher restricts matching to TODO
13774 entries, otherwise it is not touched.
13776 See also `org-scan-tags'."
13777 (unless match
13778 ;; Get a new match request, with completion against the global
13779 ;; tags table and the local tags in current buffer.
13780 (let ((org-last-tags-completion-table
13781 (org-uniquify
13782 (delq nil (append (org-get-buffer-tags)
13783 (org-global-tags-completion-table))))))
13784 (setq match
13785 (completing-read
13786 "Match: "
13787 'org-tags-completion-function nil nil nil 'org-tags-history))))
13789 (let ((match0 match)
13790 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13791 (start 0)
13792 tagsmatch todomatch tagsmatcher todomatcher)
13794 ;; Expand group tags.
13795 (setq match (org-tags-expand match))
13797 ;; Check if there is a TODO part of this match, which would be the
13798 ;; part after a "/". To make sure that this slash is not part of
13799 ;; a property value to be matched against, we also check that
13800 ;; there is no / after that slash. First, find the last slash.
13801 (let ((s 0))
13802 (while (string-match "/+" match s)
13803 (setq start (match-beginning 0))
13804 (setq s (match-end 0))))
13805 (if (and (string-match "/+" match start)
13806 (not (string-match-p "\"" match start)))
13807 ;; Match contains also a TODO-matching request.
13808 (progn
13809 (setq tagsmatch (substring match 0 (match-beginning 0)))
13810 (setq todomatch (substring match (match-end 0)))
13811 (when (string-prefix-p "!" todomatch)
13812 (setq org--matcher-tags-todo-only t)
13813 (setq todomatch (substring todomatch 1)))
13814 (when (string-match "\\`\\s-*\\'" todomatch)
13815 (setq todomatch nil)))
13816 ;; Only matching tags.
13817 (setq tagsmatch match)
13818 (setq todomatch nil))
13820 ;; Make the tags matcher.
13821 (when (org-string-nw-p tagsmatch)
13822 (let ((orlist nil)
13823 (orterms (org-split-string tagsmatch "|"))
13824 term)
13825 (while (setq term (pop orterms))
13826 (while (and (equal (substring term -1) "\\") orterms)
13827 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13828 (while (string-match re term)
13829 (let* ((rest (substring term (match-end 0)))
13830 (minus (and (match-end 1)
13831 (equal (match-string 1 term) "-")))
13832 (tag (save-match-data
13833 (replace-regexp-in-string
13834 "\\\\-" "-" (match-string 2 term))))
13835 (regexp (eq (string-to-char tag) ?{))
13836 (levelp (match-end 4))
13837 (propp (match-end 5))
13839 (cond
13840 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13841 (levelp
13842 `(,(org-op-to-function (match-string 3 term))
13843 level
13844 ,(string-to-number (match-string 4 term))))
13845 (propp
13846 (let* ((gv (pcase (upcase (match-string 5 term))
13847 ("CATEGORY"
13848 '(get-text-property (point) 'org-category))
13849 ("TODO" 'todo)
13850 (p `(org-cached-entry-get nil ,p))))
13851 (pv (match-string 7 term))
13852 (regexp (eq (string-to-char pv) ?{))
13853 (strp (eq (string-to-char pv) ?\"))
13854 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13855 (po (org-op-to-function (match-string 6 term)
13856 (if timep 'time strp))))
13857 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13858 (when timep (setq pv (org-matcher-time pv)))
13859 (cond ((and regexp (eq po 'org<>))
13860 `(not (string-match ,pv (or ,gv ""))))
13861 (regexp `(string-match ,pv (or ,gv "")))
13862 (strp `(,po (or ,gv "") ,pv))
13864 `(,po
13865 (string-to-number (or ,gv ""))
13866 ,(string-to-number pv))))))
13867 (t `(member ,tag tags-list)))))
13868 (push (if minus `(not ,mm) mm) tagsmatcher)
13869 (setq term rest)))
13870 (push `(and ,@tagsmatcher) orlist)
13871 (setq tagsmatcher nil))
13872 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13874 ;; Make the TODO matcher.
13875 (when (org-string-nw-p todomatch)
13876 (let ((orlist nil))
13877 (dolist (term (org-split-string todomatch "|"))
13878 (while (string-match re term)
13879 (let* ((minus (and (match-end 1)
13880 (equal (match-string 1 term) "-")))
13881 (kwd (match-string 2 term))
13882 (regexp (eq (string-to-char kwd) ?{))
13883 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13884 `(equal todo ,kwd))))
13885 (push (if minus `(not ,mm) mm) todomatcher))
13886 (setq term (substring term (match-end 0))))
13887 (push (if (> (length todomatcher) 1)
13888 (cons 'and todomatcher)
13889 (car todomatcher))
13890 orlist)
13891 (setq todomatcher nil))
13892 (setq todomatcher (cons 'or orlist))))
13894 ;; Return the string and function of the matcher. If no
13895 ;; tags-specific or todo-specific matcher exists, match
13896 ;; everything.
13897 (let ((matcher (if (and tagsmatcher todomatcher)
13898 `(and ,tagsmatcher ,todomatcher)
13899 (or tagsmatcher todomatcher t))))
13900 (when org--matcher-tags-todo-only
13901 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13902 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13904 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13905 "Expand group tags in MATCH.
13907 This replaces every group tag in MATCH with a regexp tag search.
13908 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13909 will be replaced like this:
13911 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13912 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13913 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13915 Replacing by a regexp preserves the structure of the match.
13916 E.g., this expansion
13918 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
13920 will match anything tagged with \"Lab\" and \"Home\", or tagged
13921 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
13923 A group tag in MATCH can contain regular expressions of its own.
13924 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
13925 will be replaced like this:
13927 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
13929 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
13930 assumed to be a single group tag, and the function will return
13931 the list of tags in this group.
13933 When DOWNCASE is non-nil, expand downcased TAGS."
13934 (if org-group-tags
13935 (let* ((case-fold-search t)
13936 (stable org-mode-syntax-table)
13937 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
13938 (taggroups (if downcased
13939 (mapcar (lambda (tg) (mapcar #'downcase tg))
13940 taggroups)
13941 taggroups))
13942 (taggroups-keys (mapcar #'car taggroups))
13943 (return-match (if downcased (downcase match) match))
13944 (count 0)
13945 (work-already-expanded tags-already-expanded)
13946 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
13947 ;; @ and _ are allowed as word-components in tags.
13948 (modify-syntax-entry ?@ "w" stable)
13949 (modify-syntax-entry ?_ "w" stable)
13950 ;; Temporarily replace regexp-expressions in the match-expression.
13951 (while (string-match "{.+?}" return-match)
13952 (cl-incf count)
13953 (push (match-string 0 return-match) regexps-in-match)
13954 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
13955 (while (and taggroups-keys
13956 (with-syntax-table stable
13957 (string-match
13958 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
13959 (regexp-opt taggroups-keys) "\\>\\)")
13960 return-match)))
13961 (let* ((dir (match-string 1 return-match))
13962 (tag (match-string 2 return-match))
13963 (tag (if downcased (downcase tag) tag)))
13964 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
13965 (member tag work-already-expanded))
13966 (setq tags-in-group (assoc tag taggroups))
13967 (push tag work-already-expanded)
13968 ;; Recursively expand each tag in the group, if the tag hasn't
13969 ;; already been expanded. Restore the match-data after all recursive calls.
13970 (save-match-data
13971 (let (tags-expanded)
13972 (dolist (x (cdr tags-in-group))
13973 (if (and (member x taggroups-keys)
13974 (not (member x work-already-expanded)))
13975 (setq tags-expanded
13976 (delete-dups
13977 (append
13978 (org-tags-expand x t downcased
13979 work-already-expanded)
13980 tags-expanded)))
13981 (setq tags-expanded
13982 (append (list x) tags-expanded)))
13983 (setq work-already-expanded
13984 (delete-dups
13985 (append tags-expanded
13986 work-already-expanded))))
13987 (setq tags-in-group
13988 (delete-dups (cons (car tags-in-group)
13989 tags-expanded)))))
13990 ;; Filter tag-regexps from tags.
13991 (setq regexp-in-group-escaped
13992 (delq nil (mapcar (lambda (x)
13993 (if (stringp x)
13994 (and (equal "{" (substring x 0 1))
13995 (equal "}" (substring x -1))
13998 tags-in-group))
13999 regexp-in-group
14000 (mapcar (lambda (x)
14001 (substring x 1 -1))
14002 regexp-in-group-escaped)
14003 tags-in-group
14004 (delq nil (mapcar (lambda (x)
14005 (if (stringp x)
14006 (and (not (equal "{" (substring x 0 1)))
14007 (not (equal "}" (substring x -1)))
14010 tags-in-group)))
14011 ;; If single-as-list, do no more in the while-loop.
14012 (if (not single-as-list)
14013 (progn
14014 (when regexp-in-group
14015 (setq regexp-in-group
14016 (concat "\\|"
14017 (mapconcat 'identity regexp-in-group
14018 "\\|"))))
14019 (setq tags-in-group
14020 (concat dir
14021 "{\\<"
14022 (regexp-opt tags-in-group)
14023 "\\>"
14024 regexp-in-group
14025 "}"))
14026 (when (stringp tags-in-group)
14027 (org-add-props tags-in-group '(grouptag t)))
14028 (setq return-match
14029 (replace-match tags-in-group t t return-match)))
14030 (setq tags-in-group
14031 (append regexp-in-group-escaped tags-in-group))))
14032 (setq taggroups-keys (delete tag taggroups-keys))))
14033 ;; Add the regular expressions back into the match-expression again.
14034 (while regexps-in-match
14035 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14036 (pop regexps-in-match)
14037 return-match t t))
14038 (cl-decf count))
14039 (if single-as-list
14040 (if tags-in-group tags-in-group (list return-match))
14041 return-match))
14042 (if single-as-list
14043 (list (if downcased (downcase match) match))
14044 match)))
14046 (defun org-op-to-function (op &optional stringp)
14047 "Turn an operator into the appropriate function."
14048 (setq op
14049 (cond
14050 ((equal op "<" ) '(< string< org-time<))
14051 ((equal op ">" ) '(> org-string> org-time>))
14052 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14053 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14054 ((member op '("=" "==")) '(= string= org-time=))
14055 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14056 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14058 (defun org<> (a b) (not (= a b)))
14059 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14060 (defun org-string>= (a b) (not (string< a b)))
14061 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14062 (defun org-string<> (a b) (not (string= 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) (> a b)))
14067 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14068 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14069 (defun org-2ft (s)
14070 "Convert S to a floating point time.
14071 If S is already a number, just return it. If it is a string, parse
14072 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14073 (cond
14074 ((numberp s) s)
14075 ((stringp s)
14076 (condition-case nil
14077 (float-time (apply #'encode-time (org-parse-time-string s)))
14078 (error 0.)))
14079 (t 0.)))
14081 (defun org-time-today ()
14082 "Time in seconds today at 0:00.
14083 Returns the float number of seconds since the beginning of the
14084 epoch to the beginning of today (00:00)."
14085 (float-time (apply 'encode-time
14086 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14088 (defun org-matcher-time (s)
14089 "Interpret a time comparison value."
14090 (save-match-data
14091 (cond
14092 ((string= s "<now>") (float-time))
14093 ((string= s "<today>") (org-time-today))
14094 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14095 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14096 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14097 (+ (org-time-today)
14098 (* (string-to-number (match-string 1 s))
14099 (cdr (assoc (match-string 2 s)
14100 '(("d" . 86400.0) ("w" . 604800.0)
14101 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14102 (t (org-2ft s)))))
14104 (defun org-match-any-p (re list)
14105 "Does re match any element of list?"
14106 (setq list (mapcar (lambda (x) (string-match re x)) list))
14107 (delq nil list))
14109 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14110 (defvar org-tags-overlay (make-overlay 1 1))
14111 (delete-overlay org-tags-overlay)
14113 (defun org-get-local-tags-at (&optional pos)
14114 "Get a list of tags defined in the current headline."
14115 (org-get-tags-at pos 'local))
14117 (defun org-get-local-tags ()
14118 "Get a list of tags defined in the current headline."
14119 (org-get-tags-at nil 'local))
14121 (defun org-get-tags-at (&optional pos local)
14122 "Get a list of all headline tags applicable at POS.
14123 POS defaults to point. If tags are inherited, the list contains
14124 the targets in the same sequence as the headlines appear, i.e.
14125 the tags of the current headline come last.
14126 When LOCAL is non-nil, only return tags from the current headline,
14127 ignore inherited ones."
14128 (interactive)
14129 (if (and org-trust-scanner-tags
14130 (or (not pos) (equal pos (point)))
14131 (not local))
14132 org-scanner-tags
14133 (let (tags ltags lastpos parent)
14134 (save-excursion
14135 (save-restriction
14136 (widen)
14137 (goto-char (or pos (point)))
14138 (save-match-data
14139 (catch 'done
14140 (condition-case nil
14141 (progn
14142 (org-back-to-heading t)
14143 (while (not (equal lastpos (point)))
14144 (setq lastpos (point))
14145 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14146 (setq ltags (org-split-string
14147 (match-string-no-properties 1) ":"))
14148 (when parent
14149 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14150 (setq tags (append
14151 (if parent
14152 (org-remove-uninherited-tags ltags)
14153 ltags)
14154 tags)))
14155 (or org-use-tag-inheritance (throw 'done t))
14156 (when local (throw 'done t))
14157 (or (org-up-heading-safe) (error nil))
14158 (setq parent t)))
14159 (error nil)))))
14160 (if local
14161 tags
14162 (reverse (delete-dups
14163 (reverse (append
14164 (org-remove-uninherited-tags
14165 org-file-tags)
14166 tags)))))))))
14168 (defun org-add-prop-inherited (s)
14169 (add-text-properties 0 (length s) '(inherited t) s)
14172 (defun org-toggle-tag (tag &optional onoff)
14173 "Toggle the tag TAG for the current line.
14174 If ONOFF is `on' or `off', don't toggle but set to this state."
14175 (save-excursion
14176 (org-back-to-heading t)
14177 (let ((current
14178 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14179 (line-end-position) t)
14180 (let ((tags (match-string 1)))
14181 ;; Clear current tags.
14182 (replace-match "")
14183 ;; Reverse the tags list so any new tag is appended to
14184 ;; the current list of tags.
14185 (nreverse (org-split-string tags ":")))))
14186 res)
14187 (pcase onoff
14188 (`off (setq current (delete tag current)))
14189 ((or `on (guard (not (member tag current))))
14190 (setq res t)
14191 (cl-pushnew tag current :test #'equal))
14192 (_ (setq current (delete tag current))))
14193 (end-of-line)
14194 (if current
14195 (progn
14196 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14197 (org-set-tags nil t))
14198 (delete-horizontal-space))
14199 (run-hooks 'org-after-tags-change-hook)
14200 res)))
14202 (defun org--align-tags-here (to-col)
14203 "Align tags on the current headline to TO-COL.
14204 Assume point is on a headline."
14205 (let ((pos (point)))
14206 (beginning-of-line)
14207 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14208 (>= pos (match-beginning 2)))
14209 ;; No tags or point within tags: do not align.
14210 (goto-char pos)
14211 (goto-char (match-beginning 1))
14212 (let ((shift (max (- (if (>= to-col 0) to-col
14213 (- (abs to-col) (string-width (match-string 2))))
14214 (current-column))
14215 1)))
14216 (replace-match (make-string shift ?\s) nil nil nil 1)
14217 ;; Preserve initial position, if possible. In any case, stop
14218 ;; before tags.
14219 (when (< pos (point)) (goto-char pos))))))
14221 (defun org-set-tags-command (&optional arg just-align)
14222 "Call the set-tags command for the current entry."
14223 (interactive "P")
14224 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14225 (org-set-tags arg just-align)
14226 (save-excursion
14227 (unless (and (org-region-active-p)
14228 org-loop-over-headlines-in-active-region)
14229 (org-back-to-heading t))
14230 (org-set-tags arg just-align))))
14232 (defun org-set-tags-to (data)
14233 "Set the tags of the current entry to DATA, replacing the current tags.
14234 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14235 If DATA is nil or the empty string, any tags will be removed."
14236 (interactive "sTags: ")
14237 (setq data
14238 (cond
14239 ((eq data nil) "")
14240 ((equal data "") "")
14241 ((stringp data)
14242 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14243 ":"))
14244 ((listp data)
14245 (concat ":" (mapconcat 'identity data ":") ":"))))
14246 (when data
14247 (save-excursion
14248 (org-back-to-heading t)
14249 (when (let ((case-fold-search nil))
14250 (looking-at org-complex-heading-regexp))
14251 (if (match-end 5)
14252 (progn
14253 (goto-char (match-beginning 5))
14254 (insert data)
14255 (delete-region (point) (point-at-eol))
14256 (org-set-tags nil 'align))
14257 (goto-char (point-at-eol))
14258 (insert " " data)
14259 (org-set-tags nil 'align)))
14260 (beginning-of-line 1)
14261 (when (looking-at ".*?\\([ \t]+\\)$")
14262 (delete-region (match-beginning 1) (match-end 1))))))
14264 (defun org-align-all-tags ()
14265 "Align the tags in all headings."
14266 (interactive)
14267 (save-excursion
14268 (or (ignore-errors (org-back-to-heading t))
14269 (outline-next-heading))
14270 (if (org-at-heading-p)
14271 (org-set-tags t)
14272 (message "No headings"))))
14274 (defvar org-indent-indentation-per-level)
14275 (defun org-set-tags (&optional arg just-align)
14276 "Set the tags for the current headline.
14277 With prefix ARG, realign all tags in headings in the current buffer.
14278 When JUST-ALIGN is non-nil, only align tags."
14279 (interactive "P")
14280 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14281 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14282 'region-start-level
14283 'region))
14284 org-loop-over-headlines-in-active-region)
14285 (org-map-entries
14286 ;; We don't use ARG and JUST-ALIGN here because these args
14287 ;; are not useful when looping over headlines.
14288 #'org-set-tags
14289 org-loop-over-headlines-in-active-region
14291 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14292 (let ((org-setting-tags t))
14293 (if arg
14294 (save-excursion
14295 (goto-char (point-min))
14296 (while (re-search-forward org-outline-regexp-bol nil t)
14297 (org-set-tags nil t)
14298 (end-of-line))
14299 (message "All tags realigned to column %d" org-tags-column))
14300 (let* ((current (org-get-tags-string))
14301 (tags
14302 (if just-align current
14303 ;; Get a new set of tags from the user.
14304 (save-excursion
14305 (let* ((seen)
14306 (table
14307 (setq
14308 org-last-tags-completion-table
14309 ;; Uniquify tags in alists, yet preserve
14310 ;; structure (i.e., keywords).
14311 (delq nil
14312 (mapcar
14313 (lambda (pair)
14314 (let ((head (car pair)))
14315 (cond ((symbolp head) pair)
14316 ((member head seen) nil)
14317 (t (push head seen)
14318 pair))))
14319 (append
14320 (or org-current-tag-alist
14321 (org-get-buffer-tags))
14322 (and
14323 org-complete-tags-always-offer-all-agenda-tags
14324 (org-global-tags-completion-table
14325 (org-agenda-files))))))))
14326 (current-tags (org-split-string current ":"))
14327 (inherited-tags
14328 (nreverse (nthcdr (length current-tags)
14329 (nreverse (org-get-tags-at))))))
14330 (replace-regexp-in-string
14331 "\\([-+&]+\\|,\\)"
14333 (if (or (eq t org-use-fast-tag-selection)
14334 (and org-use-fast-tag-selection
14335 (delq nil (mapcar #'cdr table))))
14336 (org-fast-tag-selection
14337 current-tags inherited-tags table
14338 (and org-fast-tag-selection-include-todo
14339 org-todo-key-alist))
14340 (let ((org-add-colon-after-tag-completion
14341 (< 1 (length table))))
14342 (org-trim
14343 (completing-read
14344 "Tags: "
14345 #'org-tags-completion-function
14346 nil nil current 'org-tags-history))))))))))
14348 (when org-tags-sort-function
14349 (setq tags
14350 (mapconcat
14351 #'identity
14352 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14353 org-tags-sort-function)
14354 ":")))
14356 (if (or (string= ":" tags)
14357 (string= "::" tags))
14358 (setq tags ""))
14359 (if (not (org-string-nw-p tags)) (setq tags "")
14360 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14361 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14363 ;; Insert new tags at the correct column.
14364 (unless (equal current tags)
14365 (save-excursion
14366 (beginning-of-line)
14367 (let ((case-fold-search nil))
14368 (looking-at org-complex-heading-regexp))
14369 ;; Remove current tags, if any.
14370 (when (match-end 5) (replace-match "" nil nil nil 5))
14371 ;; Insert new tags, if any. Otherwise, remove trailing
14372 ;; white spaces.
14373 (end-of-line)
14374 (if (not (equal tags ""))
14375 ;; When text is being inserted on an invisible
14376 ;; region boundary, it can be inadvertently sucked
14377 ;; into invisibility.
14378 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14379 (skip-chars-backward " \t")
14380 (delete-region (point) (line-end-position)))))
14381 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14382 ;; is on.
14383 (unless (equal tags "")
14384 (let* ((level (save-excursion
14385 (beginning-of-line)
14386 (skip-chars-forward "\\*")))
14387 (offset (if (bound-and-true-p org-indent-mode)
14388 (* (1- org-indent-indentation-per-level)
14389 (1- level))
14391 (tags-column
14392 (+ org-tags-column
14393 (if (> org-tags-column 0) (- offset) offset))))
14394 (org--align-tags-here tags-column))))
14395 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14397 (defun org-change-tag-in-region (beg end tag off)
14398 "Add or remove TAG for each entry in the region.
14399 This works in the agenda, and also in an Org buffer."
14400 (interactive
14401 (list (region-beginning) (region-end)
14402 (let ((org-last-tags-completion-table
14403 (if (derived-mode-p 'org-mode)
14404 (org-uniquify
14405 (delq nil (append (org-get-buffer-tags)
14406 (org-global-tags-completion-table))))
14407 (org-global-tags-completion-table))))
14408 (completing-read
14409 "Tag: " 'org-tags-completion-function nil nil nil
14410 'org-tags-history))
14411 (progn
14412 (message "[s]et or [r]emove? ")
14413 (equal (read-char-exclusive) ?r))))
14414 (when (fboundp 'deactivate-mark) (deactivate-mark))
14415 (let ((agendap (equal major-mode 'org-agenda-mode))
14416 l1 l2 m buf pos newhead (cnt 0))
14417 (goto-char end)
14418 (setq l2 (1- (org-current-line)))
14419 (goto-char beg)
14420 (setq l1 (org-current-line))
14421 (cl-loop for l from l1 to l2 do
14422 (org-goto-line l)
14423 (setq m (get-text-property (point) 'org-hd-marker))
14424 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14425 (and agendap m))
14426 (setq buf (if agendap (marker-buffer m) (current-buffer))
14427 pos (if agendap m (point)))
14428 (with-current-buffer buf
14429 (save-excursion
14430 (save-restriction
14431 (goto-char pos)
14432 (setq cnt (1+ cnt))
14433 (org-toggle-tag tag (if off 'off 'on))
14434 (setq newhead (org-get-heading)))))
14435 (and agendap (org-agenda-change-all-lines newhead m))))
14436 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14438 (defun org-tags-completion-function (string _predicate &optional flag)
14439 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14440 (confirm (lambda (x) (stringp (car x)))))
14441 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14442 (setq s1 (match-string 1 string)
14443 s2 (match-string 2 string))
14444 (setq s1 "" s2 string))
14445 (cond
14446 ((eq flag nil)
14447 ;; try completion
14448 (setq rtn (try-completion s2 ctable confirm))
14449 (when (stringp rtn)
14450 (setq rtn
14451 (concat s1 s2 (substring rtn (length s2))
14452 (if (and org-add-colon-after-tag-completion
14453 (assoc rtn ctable))
14454 ":" ""))))
14455 rtn)
14456 ((eq flag t)
14457 ;; all-completions
14458 (all-completions s2 ctable confirm))
14459 ((eq flag 'lambda)
14460 ;; exact match?
14461 (assoc s2 ctable)))))
14463 (defun org-fast-tag-insert (kwd tags face &optional end)
14464 "Insert KDW, and the TAGS, the latter with face FACE.
14465 Also insert END."
14466 (insert (format "%-12s" (concat kwd ":"))
14467 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14468 (or end "")))
14470 (defun org-fast-tag-show-exit (flag)
14471 (save-excursion
14472 (org-goto-line 3)
14473 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14474 (replace-match ""))
14475 (when flag
14476 (end-of-line 1)
14477 (org-move-to-column (- (window-width) 19) t)
14478 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14480 (defun org-set-current-tags-overlay (current prefix)
14481 "Add an overlay to CURRENT tag with PREFIX."
14482 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14483 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14484 (org-overlay-display org-tags-overlay (concat prefix s))))
14486 (defvar org-last-tag-selection-key nil)
14487 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14488 "Fast tag selection with single keys.
14489 CURRENT is the current list of tags in the headline, INHERITED is the
14490 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14491 possibly with grouping information. TODO-TABLE is a similar table with
14492 TODO keywords, should these have keys assigned to them.
14493 If the keys are nil, a-z are automatically assigned.
14494 Returns the new tags string, or nil to not change the current settings."
14495 (let* ((fulltable (append table todo-table))
14496 (maxlen (apply 'max (mapcar
14497 (lambda (x)
14498 (if (stringp (car x)) (string-width (car x)) 0))
14499 fulltable)))
14500 (buf (current-buffer))
14501 (expert (eq org-fast-tag-selection-single-key 'expert))
14502 (buffer-tags nil)
14503 (fwidth (+ maxlen 3 1 3))
14504 (ncol (/ (- (window-width) 4) fwidth))
14505 (i-face 'org-done)
14506 (c-face 'org-todo)
14507 tg cnt e c char c1 c2 ntable tbl rtn
14508 ov-start ov-end ov-prefix
14509 (exit-after-next org-fast-tag-selection-single-key)
14510 (done-keywords org-done-keywords)
14511 groups ingroup intaggroup)
14512 (save-excursion
14513 (beginning-of-line 1)
14514 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14515 (setq ov-start (match-beginning 1)
14516 ov-end (match-end 1)
14517 ov-prefix "")
14518 (setq ov-start (1- (point-at-eol))
14519 ov-end (1+ ov-start))
14520 (skip-chars-forward "^\n\r")
14521 (setq ov-prefix
14522 (concat
14523 (buffer-substring (1- (point)) (point))
14524 (if (> (current-column) org-tags-column)
14526 (make-string (- org-tags-column (current-column)) ?\ ))))))
14527 (move-overlay org-tags-overlay ov-start ov-end)
14528 (save-window-excursion
14529 (if expert
14530 (set-buffer (get-buffer-create " *Org tags*"))
14531 (delete-other-windows)
14532 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14533 (org-switch-to-buffer-other-window " *Org tags*"))
14534 (erase-buffer)
14535 (setq-local org-done-keywords done-keywords)
14536 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14537 (org-fast-tag-insert "Current" current c-face "\n\n")
14538 (org-fast-tag-show-exit exit-after-next)
14539 (org-set-current-tags-overlay current ov-prefix)
14540 (setq tbl fulltable char ?a cnt 0)
14541 (while (setq e (pop tbl))
14542 (cond
14543 ((eq (car e) :startgroup)
14544 (push '() groups) (setq ingroup t)
14545 (unless (zerop cnt)
14546 (setq cnt 0)
14547 (insert "\n"))
14548 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14549 ((eq (car e) :endgroup)
14550 (setq ingroup nil cnt 0)
14551 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14552 ((eq (car e) :startgrouptag)
14553 (setq intaggroup t)
14554 (unless (zerop cnt)
14555 (setq cnt 0)
14556 (insert "\n"))
14557 (insert "[ "))
14558 ((eq (car e) :endgrouptag)
14559 (setq intaggroup nil cnt 0)
14560 (insert "]\n"))
14561 ((equal e '(:newline))
14562 (unless (zerop cnt)
14563 (setq cnt 0)
14564 (insert "\n")
14565 (setq e (car tbl))
14566 (while (equal (car tbl) '(:newline))
14567 (insert "\n")
14568 (setq tbl (cdr tbl)))))
14569 ((equal e '(:grouptags)) (insert " : "))
14571 (setq tg (copy-sequence (car e)) c2 nil)
14572 (if (cdr e)
14573 (setq c (cdr e))
14574 ;; automatically assign a character.
14575 (setq c1 (string-to-char
14576 (downcase (substring
14577 tg (if (= (string-to-char tg) ?@) 1 0)))))
14578 (if (or (rassoc c1 ntable) (rassoc c1 table))
14579 (while (or (rassoc char ntable) (rassoc char table))
14580 (setq char (1+ char)))
14581 (setq c2 c1))
14582 (setq c (or c2 char)))
14583 (when ingroup (push tg (car groups)))
14584 (setq tg (org-add-props tg nil 'face
14585 (cond
14586 ((not (assoc tg table))
14587 (org-get-todo-face tg))
14588 ((member tg current) c-face)
14589 ((member tg inherited) i-face))))
14590 (when (equal (caar tbl) :grouptags)
14591 (org-add-props tg nil 'face 'org-tag-group))
14592 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14593 (insert "[" c "] " tg (make-string
14594 (- fwidth 4 (length tg)) ?\ ))
14595 (push (cons tg c) ntable)
14596 (when (= (cl-incf cnt) ncol)
14597 (insert "\n")
14598 (when (or ingroup intaggroup) (insert " "))
14599 (setq cnt 0)))))
14600 (setq ntable (nreverse ntable))
14601 (insert "\n")
14602 (goto-char (point-min))
14603 (unless expert (org-fit-window-to-buffer))
14604 (setq rtn
14605 (catch 'exit
14606 (while t
14607 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14608 (if (not groups) "no " "")
14609 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14610 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14611 (setq org-last-tag-selection-key c)
14612 (cond
14613 ((= c ?\r) (throw 'exit t))
14614 ((= c ?!)
14615 (setq groups (not groups))
14616 (goto-char (point-min))
14617 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14618 ((= c ?\C-c)
14619 (if (not expert)
14620 (org-fast-tag-show-exit
14621 (setq exit-after-next (not exit-after-next)))
14622 (setq expert nil)
14623 (delete-other-windows)
14624 (set-window-buffer (split-window-vertically) " *Org tags*")
14625 (org-switch-to-buffer-other-window " *Org tags*")
14626 (org-fit-window-to-buffer)))
14627 ((or (= c ?\C-g)
14628 (and (= c ?q) (not (rassoc c ntable))))
14629 (delete-overlay org-tags-overlay)
14630 (setq quit-flag t))
14631 ((= c ?\ )
14632 (setq current nil)
14633 (when exit-after-next (setq exit-after-next 'now)))
14634 ((= c ?\t)
14635 (condition-case nil
14636 (setq tg (completing-read
14637 "Tag: "
14638 (or buffer-tags
14639 (with-current-buffer buf
14640 (setq buffer-tags
14641 (org-get-buffer-tags))))))
14642 (quit (setq tg "")))
14643 (when (string-match "\\S-" tg)
14644 (cl-pushnew (list tg) buffer-tags :test #'equal)
14645 (if (member tg current)
14646 (setq current (delete tg current))
14647 (push tg current)))
14648 (when exit-after-next (setq exit-after-next 'now)))
14649 ((setq e (rassoc c todo-table) tg (car e))
14650 (with-current-buffer buf
14651 (save-excursion (org-todo tg)))
14652 (when exit-after-next (setq exit-after-next 'now)))
14653 ((setq e (rassoc c ntable) tg (car e))
14654 (if (member tg current)
14655 (setq current (delete tg current))
14656 (cl-loop for g in groups do
14657 (when (member tg g)
14658 (dolist (x g) (setq current (delete x current)))))
14659 (push tg current))
14660 (when exit-after-next (setq exit-after-next 'now))))
14662 ;; Create a sorted list
14663 (setq current
14664 (sort current
14665 (lambda (a b)
14666 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14667 (when (eq exit-after-next 'now) (throw 'exit t))
14668 (goto-char (point-min))
14669 (beginning-of-line 2)
14670 (delete-region (point) (point-at-eol))
14671 (org-fast-tag-insert "Current" current c-face)
14672 (org-set-current-tags-overlay current ov-prefix)
14673 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14674 (setq tg (match-string 1))
14675 (add-text-properties
14676 (match-beginning 1) (match-end 1)
14677 (list 'face
14678 (cond
14679 ((member tg current) c-face)
14680 ((member tg inherited) i-face)
14681 (t (get-text-property (match-beginning 1) 'face))))))
14682 (goto-char (point-min)))))
14683 (delete-overlay org-tags-overlay)
14684 (if rtn
14685 (mapconcat 'identity current ":")
14686 nil))))
14688 (defun org-get-tags-string ()
14689 "Get the TAGS string in the current headline."
14690 (unless (org-at-heading-p t)
14691 (user-error "Not on a heading"))
14692 (save-excursion
14693 (beginning-of-line 1)
14694 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14695 (match-string-no-properties 1)
14696 "")))
14698 (defun org-get-tags ()
14699 "Get the list of tags specified in the current headline."
14700 (org-split-string (org-get-tags-string) ":"))
14702 (defun org-get-buffer-tags ()
14703 "Get a table of all tags used in the buffer, for completion."
14704 (org-with-wide-buffer
14705 (goto-char (point-min))
14706 (let ((tag-re (concat org-outline-regexp-bol
14707 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14708 tags)
14709 (while (re-search-forward tag-re nil t)
14710 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14711 (push tag tags)))
14712 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14714 ;;;; The mapping API
14716 (defvar org-agenda-skip-comment-trees)
14717 (defvar org-agenda-skip-function)
14718 (defun org-map-entries (func &optional match scope &rest skip)
14719 "Call FUNC at each headline selected by MATCH in SCOPE.
14721 FUNC is a function or a lisp form. The function will be called without
14722 arguments, with the cursor positioned at the beginning of the headline.
14723 The return values of all calls to the function will be collected and
14724 returned as a list.
14726 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14727 does not need to preserve point. After evaluation, the cursor will be
14728 moved to the end of the line (presumably of the headline of the
14729 processed entry) and search continues from there. Under some
14730 circumstances, this may not produce the wanted results. For example,
14731 if you have removed (e.g. archived) the current (sub)tree it could
14732 mean that the next entry will be skipped entirely. In such cases, you
14733 can specify the position from where search should continue by making
14734 FUNC set the variable `org-map-continue-from' to the desired buffer
14735 position.
14737 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14738 Only headlines that are matched by this query will be considered during
14739 the iteration. When MATCH is nil or t, all headlines will be
14740 visited by the iteration.
14742 SCOPE determines the scope of this command. It can be any of:
14744 nil The current buffer, respecting the restriction if any
14745 tree The subtree started with the entry at point
14746 region The entries within the active region, if any
14747 region-start-level
14748 The entries within the active region, but only those at
14749 the same level than the first one.
14750 file The current buffer, without restriction
14751 file-with-archives
14752 The current buffer, and any archives associated with it
14753 agenda All agenda files
14754 agenda-with-archives
14755 All agenda files with any archive files associated with them
14756 \(file1 file2 ...)
14757 If this is a list, all files in the list will be scanned
14759 The remaining args are treated as settings for the skipping facilities of
14760 the scanner. The following items can be given here:
14762 archive skip trees with the archive tag
14763 comment skip trees with the COMMENT keyword
14764 function or Emacs Lisp form:
14765 will be used as value for `org-agenda-skip-function', so
14766 whenever the function returns a position, FUNC will not be
14767 called for that entry and search will continue from the
14768 position returned
14770 If your function needs to retrieve the tags including inherited tags
14771 at the *current* entry, you can use the value of the variable
14772 `org-scanner-tags' which will be much faster than getting the value
14773 with `org-get-tags-at'. If your function gets properties with
14774 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14775 to t around the call to `org-entry-properties' to get the same speedup.
14776 Note that if your function moves around to retrieve tags and properties at
14777 a *different* entry, you cannot use these techniques."
14778 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14779 (not (org-region-active-p)))
14780 (let* ((org-agenda-archives-mode nil) ; just to make sure
14781 (org-agenda-skip-archived-trees (memq 'archive skip))
14782 (org-agenda-skip-comment-trees (memq 'comment skip))
14783 (org-agenda-skip-function
14784 (car (org-delete-all '(comment archive) skip)))
14785 (org-tags-match-list-sublevels t)
14786 (start-level (eq scope 'region-start-level))
14787 matcher res
14788 org-todo-keywords-for-agenda
14789 org-done-keywords-for-agenda
14790 org-todo-keyword-alist-for-agenda
14791 org-tag-alist-for-agenda
14792 org--matcher-tags-todo-only)
14794 (cond
14795 ((eq match t) (setq matcher t))
14796 ((eq match nil) (setq matcher t))
14797 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14799 (save-excursion
14800 (save-restriction
14801 (cond ((eq scope 'tree)
14802 (org-back-to-heading t)
14803 (org-narrow-to-subtree)
14804 (setq scope nil))
14805 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14806 (org-region-active-p))
14807 ;; If needed, set start-level to a string like "2"
14808 (when start-level
14809 (save-excursion
14810 (goto-char (region-beginning))
14811 (unless (org-at-heading-p) (outline-next-heading))
14812 (setq start-level (org-current-level))))
14813 (narrow-to-region (region-beginning)
14814 (save-excursion
14815 (goto-char (region-end))
14816 (unless (and (bolp) (org-at-heading-p))
14817 (outline-next-heading))
14818 (point)))
14819 (setq scope nil)))
14821 (if (not scope)
14822 (progn
14823 (org-agenda-prepare-buffers
14824 (and buffer-file-name (list buffer-file-name)))
14825 (setq res
14826 (org-scan-tags
14827 func matcher org--matcher-tags-todo-only start-level)))
14828 ;; Get the right scope
14829 (cond
14830 ((and scope (listp scope) (symbolp (car scope)))
14831 (setq scope (eval scope)))
14832 ((eq scope 'agenda)
14833 (setq scope (org-agenda-files t)))
14834 ((eq scope 'agenda-with-archives)
14835 (setq scope (org-agenda-files t))
14836 (setq scope (org-add-archive-files scope)))
14837 ((eq scope 'file)
14838 (setq scope (and buffer-file-name (list buffer-file-name))))
14839 ((eq scope 'file-with-archives)
14840 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14841 (org-agenda-prepare-buffers scope)
14842 (dolist (file scope)
14843 (with-current-buffer (org-find-base-buffer-visiting file)
14844 (org-with-wide-buffer
14845 (goto-char (point-min))
14846 (setq res
14847 (append
14849 (org-scan-tags
14850 func matcher org--matcher-tags-todo-only)))))))))
14851 res)))
14853 ;;; Properties API
14855 (defconst org-special-properties
14856 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14857 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14858 "The special properties valid in Org mode.
14859 These are properties that are not defined in the property drawer,
14860 but in some other way.")
14862 (defconst org-default-properties
14863 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14864 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14865 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14866 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14867 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14868 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14869 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14870 "Some properties that are used by Org mode for various purposes.
14871 Being in this list makes sure that they are offered for completion.")
14873 (defun org--valid-property-p (property)
14874 "Non nil when string PROPERTY is a valid property name."
14875 (not
14876 (or (equal property "")
14877 (string-match-p "\\s-" property))))
14879 (defun org--update-property-plist (key val props)
14880 "Associate KEY to VAL in alist PROPS.
14881 Modifications are made by side-effect. Return new alist."
14882 (let* ((appending (string= (substring key -1) "+"))
14883 (key (if appending (substring key 0 -1) key))
14884 (old (assoc-string key props t)))
14885 (if (not old) (cons (cons key val) props)
14886 (setcdr old (if appending (concat (cdr old) " " val) val))
14887 props)))
14889 (defun org-get-property-block (&optional beg force)
14890 "Return the (beg . end) range of the body of the property drawer.
14891 BEG is the beginning of the current subtree, or of the part
14892 before the first headline. If it is not given, it will be found.
14893 If the drawer does not exist, create it if FORCE is non-nil, or
14894 return nil."
14895 (org-with-wide-buffer
14896 (when beg (goto-char beg))
14897 (unless (org-before-first-heading-p)
14898 (let ((beg (cond (beg)
14899 ((or (not (featurep 'org-inlinetask))
14900 (org-inlinetask-in-task-p))
14901 (org-back-to-heading t))
14902 (t (org-with-limited-levels (org-back-to-heading t))))))
14903 (forward-line)
14904 (when (looking-at-p org-planning-line-re) (forward-line))
14905 (cond ((looking-at org-property-drawer-re)
14906 (forward-line)
14907 (cons (point) (progn (goto-char (match-end 0))
14908 (line-beginning-position))))
14909 (force
14910 (goto-char beg)
14911 (org-insert-property-drawer)
14912 (let ((pos (save-excursion (search-forward ":END:")
14913 (line-beginning-position))))
14914 (cons pos pos))))))))
14916 (defun org-at-property-p ()
14917 "Non-nil when point is inside a property drawer.
14918 See `org-property-re' for match data, if applicable."
14919 (save-excursion
14920 (beginning-of-line)
14921 (and (looking-at org-property-re)
14922 (let ((property-drawer (save-match-data (org-get-property-block))))
14923 (and property-drawer
14924 (>= (point) (car property-drawer))
14925 (< (point) (cdr property-drawer)))))))
14927 (defun org-property-action ()
14928 "Do an action on properties."
14929 (interactive)
14930 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14931 (let ((c (read-char-exclusive)))
14932 (cl-case c
14933 (?s (call-interactively #'org-set-property))
14934 (?d (call-interactively #'org-delete-property))
14935 (?D (call-interactively #'org-delete-property-globally))
14936 (?c (call-interactively #'org-compute-property-at-point))
14937 (otherwise (user-error "No such property action %c" c)))))
14939 (defun org-inc-effort ()
14940 "Increment the value of the effort property in the current entry."
14941 (interactive)
14942 (org-set-effort t))
14944 (defvar org-clock-effort) ; Defined in org-clock.el.
14945 (defvar org-clock-current-task) ; Defined in org-clock.el.
14946 (defun org-set-effort (&optional increment value)
14947 "Set the effort property of the current entry.
14948 If INCREMENT is non-nil, set the property to the next allowed
14949 value. Otherwise, if optional argument VALUE is provided, use
14950 it. Eventually, prompt for the new value if none of the previous
14951 variables is set."
14952 (interactive "P")
14953 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14954 (current (org-entry-get nil org-effort-property))
14955 (value
14956 (cond
14957 (increment
14958 (unless allowed (user-error "Allowed effort values are not set"))
14959 (or (cl-caadr (member (list current) allowed))
14960 (user-error "Unknown value %S among allowed values" current)))
14961 (value
14962 (if (stringp value) value
14963 (error "Invalid effort value: %S" value)))
14965 (let ((must-match
14966 (and allowed
14967 (not (get-text-property 0 'org-unrestricted
14968 (caar allowed))))))
14969 (completing-read "Effort: " allowed nil must-match))))))
14970 (unless (equal current value)
14971 (org-entry-put nil org-effort-property value))
14972 (org-refresh-property '((effort . identity)
14973 (effort-minutes . org-duration-to-minutes))
14974 value)
14975 (when (equal (org-get-heading t t t t)
14976 (bound-and-true-p org-clock-current-task))
14977 (setq org-clock-effort (org-get-at-bol 'effort))
14978 (org-clock-update-mode-line))
14979 (message "%s is now %s" org-effort-property value)))
14981 (defun org-entry-properties (&optional pom which)
14982 "Get all properties of the current entry.
14984 When POM is a buffer position, get all properties from the entry
14985 there instead.
14987 This includes the TODO keyword, the tags, time strings for
14988 deadline, scheduled, and clocking, and any additional properties
14989 defined in the entry.
14991 If WHICH is nil or `all', get all properties. If WHICH is
14992 `special' or `standard', only get that subclass. If WHICH is
14993 a string, only get that property.
14995 Return value is an alist. Keys are properties, as upcased
14996 strings."
14997 (org-with-point-at pom
14998 (when (and (derived-mode-p 'org-mode)
14999 (ignore-errors (org-back-to-heading t)))
15000 (catch 'exit
15001 (let* ((beg (point))
15002 (specific (and (stringp which) (upcase which)))
15003 (which (cond ((not specific) which)
15004 ((member specific org-special-properties) 'special)
15005 (t 'standard)))
15006 props)
15007 ;; Get the special properties, like TODO and TAGS.
15008 (when (memq which '(nil all special))
15009 (when (or (not specific) (string= specific "CLOCKSUM"))
15010 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15011 (when clocksum
15012 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15013 props)))
15014 (when specific (throw 'exit props)))
15015 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15016 (let ((clocksumt (get-text-property (point)
15017 :org-clock-minutes-today)))
15018 (when clocksumt
15019 (push (cons "CLOCKSUM_T"
15020 (org-duration-from-minutes clocksumt))
15021 props)))
15022 (when specific (throw 'exit props)))
15023 (when (or (not specific) (string= specific "ITEM"))
15024 (let ((case-fold-search nil))
15025 (when (looking-at org-complex-heading-regexp)
15026 (push (cons "ITEM"
15027 (let ((title (match-string-no-properties 4)))
15028 (if (org-string-nw-p title)
15029 (org-remove-tabs title)
15030 "")))
15031 props)))
15032 (when specific (throw 'exit props)))
15033 (when (or (not specific) (string= specific "TODO"))
15034 (let ((case-fold-search nil))
15035 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15036 (push (cons "TODO" (match-string-no-properties 2)) props)))
15037 (when specific (throw 'exit props)))
15038 (when (or (not specific) (string= specific "PRIORITY"))
15039 (push (cons "PRIORITY"
15040 (if (looking-at org-priority-regexp)
15041 (match-string-no-properties 2)
15042 (char-to-string org-default-priority)))
15043 props)
15044 (when specific (throw 'exit props)))
15045 (when (or (not specific) (string= specific "FILE"))
15046 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15047 props)
15048 (when specific (throw 'exit props)))
15049 (when (or (not specific) (string= specific "TAGS"))
15050 (let ((value (org-string-nw-p (org-get-tags-string))))
15051 (when value (push (cons "TAGS" value) props)))
15052 (when specific (throw 'exit props)))
15053 (when (or (not specific) (string= specific "ALLTAGS"))
15054 (let ((value (org-get-tags-at)))
15055 (when value
15056 (push (cons "ALLTAGS"
15057 (format ":%s:" (mapconcat #'identity value ":")))
15058 props)))
15059 (when specific (throw 'exit props)))
15060 (when (or (not specific) (string= specific "BLOCKED"))
15061 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15062 (when specific (throw 'exit props)))
15063 (when (or (not specific)
15064 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15065 (forward-line)
15066 (when (looking-at-p org-planning-line-re)
15067 (end-of-line)
15068 (let ((bol (line-beginning-position))
15069 ;; Backward compatibility: time keywords used to
15070 ;; be configurable (before 8.3). Make sure we
15071 ;; get the correct keyword.
15072 (key-assoc `(("CLOSED" . ,org-closed-string)
15073 ("DEADLINE" . ,org-deadline-string)
15074 ("SCHEDULED" . ,org-scheduled-string))))
15075 (dolist (pair (if specific (list (assoc specific key-assoc))
15076 key-assoc))
15077 (save-excursion
15078 (when (search-backward (cdr pair) bol t)
15079 (goto-char (match-end 0))
15080 (skip-chars-forward " \t")
15081 (and (looking-at org-ts-regexp-both)
15082 (push (cons (car pair)
15083 (match-string-no-properties 0))
15084 props)))))))
15085 (when specific (throw 'exit props)))
15086 (when (or (not specific)
15087 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15088 (let ((find-ts
15089 (lambda (end ts)
15090 ;; Fix next time-stamp before END. TS is the
15091 ;; list of time-stamps found so far.
15092 (let ((ts ts)
15093 (regexp (cond
15094 ((string= specific "TIMESTAMP")
15095 org-ts-regexp)
15096 ((string= specific "TIMESTAMP_IA")
15097 org-ts-regexp-inactive)
15098 ((assoc "TIMESTAMP_IA" ts)
15099 org-ts-regexp)
15100 ((assoc "TIMESTAMP" ts)
15101 org-ts-regexp-inactive)
15102 (t org-ts-regexp-both))))
15103 (catch 'next
15104 (while (re-search-forward regexp end t)
15105 (backward-char)
15106 (let ((object (org-element-context)))
15107 ;; Accept to match timestamps in node
15108 ;; properties, too.
15109 (when (memq (org-element-type object)
15110 '(node-property timestamp))
15111 (let ((type
15112 (org-element-property :type object)))
15113 (cond
15114 ((and (memq type '(active active-range))
15115 (not (equal specific "TIMESTAMP_IA")))
15116 (unless (assoc "TIMESTAMP" ts)
15117 (push (cons "TIMESTAMP"
15118 (org-element-property
15119 :raw-value object))
15121 (when specific (throw 'exit ts))))
15122 ((and (memq type '(inactive inactive-range))
15123 (not (string= specific "TIMESTAMP")))
15124 (unless (assoc "TIMESTAMP_IA" ts)
15125 (push (cons "TIMESTAMP_IA"
15126 (org-element-property
15127 :raw-value object))
15129 (when specific (throw 'exit ts))))))
15130 ;; Both timestamp types are found,
15131 ;; move to next part.
15132 (when (= (length ts) 2) (throw 'next ts)))))
15133 ts)))))
15134 (goto-char beg)
15135 ;; First look for timestamps within headline.
15136 (let ((ts (funcall find-ts (line-end-position) nil)))
15137 (if (= (length ts) 2) (setq props (nconc ts props))
15138 ;; Then find timestamps in the section, skipping
15139 ;; planning line.
15140 (let ((end (save-excursion (outline-next-heading))))
15141 (forward-line)
15142 (when (looking-at-p org-planning-line-re) (forward-line))
15143 (setq props (nconc (funcall find-ts end ts) props))))))))
15144 ;; Get the standard properties, like :PROP:.
15145 (when (memq which '(nil all standard))
15146 ;; If we are looking after a specific property, delegate
15147 ;; to `org-entry-get', which is faster. However, make an
15148 ;; exception for "CATEGORY", since it can be also set
15149 ;; through keywords (i.e. #+CATEGORY).
15150 (if (and specific (not (equal specific "CATEGORY")))
15151 (let ((value (org-entry-get beg specific nil t)))
15152 (throw 'exit (and value (list (cons specific value)))))
15153 (let ((range (org-get-property-block beg)))
15154 (when range
15155 (let ((end (cdr range)) seen-base)
15156 (goto-char (car range))
15157 ;; Unlike to `org--update-property-plist', we
15158 ;; handle the case where base values is found
15159 ;; after its extension. We also forbid standard
15160 ;; properties to be named as special properties.
15161 (while (re-search-forward org-property-re end t)
15162 (let* ((key (upcase (match-string-no-properties 2)))
15163 (extendp (string-match-p "\\+\\'" key))
15164 (key-base (if extendp (substring key 0 -1) key))
15165 (value (match-string-no-properties 3)))
15166 (cond
15167 ((member-ignore-case key-base org-special-properties))
15168 (extendp
15169 (setq props
15170 (org--update-property-plist key value props)))
15171 ((member key seen-base))
15172 (t (push key seen-base)
15173 (let ((p (assoc-string key props t)))
15174 (if p (setcdr p (concat value " " (cdr p)))
15175 (push (cons key value) props))))))))))))
15176 (unless (assoc "CATEGORY" props)
15177 (push (cons "CATEGORY" (org-get-category beg)) props)
15178 (when (string= specific "CATEGORY") (throw 'exit props)))
15179 ;; Return value.
15180 props)))))
15182 (defun org--property-local-values (property literal-nil)
15183 "Return value for PROPERTY in current entry.
15184 Value is a list whose car is the base value for PROPERTY and cdr
15185 a list of accumulated values. Return nil if neither is found in
15186 the entry. Also return nil when PROPERTY is set to \"nil\",
15187 unless LITERAL-NIL is non-nil."
15188 (let ((range (org-get-property-block)))
15189 (when range
15190 (goto-char (car range))
15191 (let* ((case-fold-search t)
15192 (end (cdr range))
15193 (value
15194 ;; Base value.
15195 (save-excursion
15196 (let ((v (and (re-search-forward
15197 (org-re-property property nil t) end t)
15198 (match-string-no-properties 3))))
15199 (list (if literal-nil v (org-not-nil v)))))))
15200 ;; Find additional values.
15201 (let* ((property+ (org-re-property (concat property "+") nil t)))
15202 (while (re-search-forward property+ end t)
15203 (push (match-string-no-properties 3) value)))
15204 ;; Return final values.
15205 (and (not (equal value '(nil))) (nreverse value))))))
15207 (defun org--property-global-value (property literal-nil)
15208 "Return value for PROPERTY in current buffer.
15209 Return value is a string. Return nil if property is not set
15210 globally. Also return nil when PROPERTY is set to \"nil\",
15211 unless LITERAL-NIL is non-nil."
15212 (let ((global
15213 (cdr (or (assoc-string property org-file-properties t)
15214 (assoc-string property org-global-properties t)
15215 (assoc-string property org-global-properties-fixed t)))))
15216 (if literal-nil global (org-not-nil global))))
15218 (defun org-entry-get (pom property &optional inherit literal-nil)
15219 "Get value of PROPERTY for entry or content at point-or-marker POM.
15221 If INHERIT is non-nil and the entry does not have the property,
15222 then also check higher levels of the hierarchy. If INHERIT is
15223 the symbol `selective', use inheritance only if the setting in
15224 `org-use-property-inheritance' selects PROPERTY for inheritance.
15226 If the property is present but empty, the return value is the
15227 empty string. If the property is not present at all, nil is
15228 returned. In any other case, return the value as a string.
15229 Search is case-insensitive.
15231 If LITERAL-NIL is set, return the string value \"nil\" as
15232 a string, do not interpret it as the list atom nil. This is used
15233 for inheritance when a \"nil\" value can supersede a non-nil
15234 value higher up the hierarchy."
15235 (org-with-point-at pom
15236 (cond
15237 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15238 ;; We need a special property. Use `org-entry-properties' to
15239 ;; retrieve it, but specify the wanted property.
15240 (cdr (assoc-string property (org-entry-properties nil property))))
15241 ((and inherit
15242 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15243 (org-entry-get-with-inheritance property literal-nil))
15245 (let* ((local (org--property-local-values property literal-nil))
15246 (value (and local (mapconcat #'identity (delq nil local) " "))))
15247 (if literal-nil value (org-not-nil value)))))))
15249 (defun org-property-or-variable-value (var &optional inherit)
15250 "Check if there is a property fixing the value of VAR.
15251 If yes, return this value. If not, return the current value of the variable."
15252 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15253 (if (and prop (stringp prop) (string-match "\\S-" prop))
15254 (read prop)
15255 (symbol-value var))))
15257 (defun org-entry-delete (pom property)
15258 "Delete PROPERTY from entry at point-or-marker POM.
15259 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15260 non-nil when a property was removed."
15261 (org-with-point-at pom
15262 (pcase (org-get-property-block)
15263 (`(,begin . ,origin)
15264 (let* ((end (copy-marker origin))
15265 (re (org-re-property
15266 (concat (regexp-quote property) "\\+?") t t)))
15267 (goto-char begin)
15268 (while (re-search-forward re end t)
15269 (delete-region (match-beginning 0) (line-beginning-position 2)))
15270 ;; If drawer is empty, remove it altogether.
15271 (when (= begin end)
15272 (delete-region (line-beginning-position 0)
15273 (line-beginning-position 2)))
15274 ;; Return non-nil if some property was removed.
15275 (prog1 (/= end origin) (set-marker end nil))))
15276 (_ nil))))
15278 ;; Multi-values properties are properties that contain multiple values
15279 ;; These values are assumed to be single words, separated by whitespace.
15280 (defun org-entry-add-to-multivalued-property (pom property value)
15281 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15282 (let* ((old (org-entry-get pom property))
15283 (values (and old (split-string old))))
15284 (setq value (org-entry-protect-space value))
15285 (unless (member value values)
15286 (setq values (append values (list value)))
15287 (org-entry-put pom property (mapconcat #'identity values " ")))))
15289 (defun org-entry-remove-from-multivalued-property (pom property value)
15290 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15291 (let* ((old (org-entry-get pom property))
15292 (values (and old (split-string old))))
15293 (setq value (org-entry-protect-space value))
15294 (when (member value values)
15295 (setq values (delete value values))
15296 (org-entry-put pom property (mapconcat #'identity values " ")))))
15298 (defun org-entry-member-in-multivalued-property (pom property value)
15299 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15300 (let* ((old (org-entry-get pom property))
15301 (values (and old (split-string old))))
15302 (setq value (org-entry-protect-space value))
15303 (member value values)))
15305 (defun org-entry-get-multivalued-property (pom property)
15306 "Return a list of values in a multivalued property."
15307 (let* ((value (org-entry-get pom property))
15308 (values (and value (split-string value))))
15309 (mapcar #'org-entry-restore-space values)))
15311 (defun org-entry-put-multivalued-property (pom property &rest values)
15312 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15313 VALUES should be a list of strings. Spaces will be protected."
15314 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15315 (let* ((value (org-entry-get pom property))
15316 (values (and value (split-string value))))
15317 (mapcar #'org-entry-restore-space values)))
15319 (defun org-entry-protect-space (s)
15320 "Protect spaces and newline in string S."
15321 (while (string-match " " s)
15322 (setq s (replace-match "%20" t t s)))
15323 (while (string-match "\n" s)
15324 (setq s (replace-match "%0A" t t s)))
15327 (defun org-entry-restore-space (s)
15328 "Restore spaces and newline in string S."
15329 (while (string-match "%20" s)
15330 (setq s (replace-match " " t t s)))
15331 (while (string-match "%0A" s)
15332 (setq s (replace-match "\n" t t s)))
15335 (defvar org-entry-property-inherited-from (make-marker)
15336 "Marker pointing to the entry from where a property was inherited.
15337 Each call to `org-entry-get-with-inheritance' will set this marker to the
15338 location of the entry where the inheritance search matched. If there was
15339 no match, the marker will point nowhere.
15340 Note that also `org-entry-get' calls this function, if the INHERIT flag
15341 is set.")
15343 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15344 "Get PROPERTY of entry or content at point, search higher levels if needed.
15345 The search will stop at the first ancestor which has the property defined.
15346 If the value found is \"nil\", return nil to show that the property
15347 should be considered as undefined (this is the meaning of nil here).
15348 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15349 (move-marker org-entry-property-inherited-from nil)
15350 (org-with-wide-buffer
15351 (let (value)
15352 (catch 'exit
15353 (while t
15354 (let ((v (org--property-local-values property literal-nil)))
15355 (when v
15356 (setq value
15357 (concat (mapconcat #'identity (delq nil v) " ")
15358 (and value " ")
15359 value)))
15360 (cond
15361 ((car v)
15362 (org-back-to-heading t)
15363 (move-marker org-entry-property-inherited-from (point))
15364 (throw 'exit nil))
15365 ((org-up-heading-safe))
15367 (let ((global (org--property-global-value property literal-nil)))
15368 (cond ((not global))
15369 (value (setq value (concat global " " value)))
15370 (t (setq value global))))
15371 (throw 'exit nil))))))
15372 (if literal-nil value (org-not-nil value)))))
15374 (defvar org-property-changed-functions nil
15375 "Hook called when the value of a property has changed.
15376 Each hook function should accept two arguments, the name of the property
15377 and the new value.")
15379 (defun org-entry-put (pom property value)
15380 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15382 If the value is nil, it is converted to the empty string. If it
15383 is not a string, an error is raised. Also raise an error on
15384 invalid property names.
15386 PROPERTY can be any regular property (see
15387 `org-special-properties'). It can also be \"TODO\",
15388 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15390 For the last two properties, VALUE may have any of the special
15391 values \"earlier\" and \"later\". The function then increases or
15392 decreases scheduled or deadline date by one day."
15393 (cond ((null value) (setq value ""))
15394 ((not (stringp value)) (error "Properties values should be strings"))
15395 ((not (org--valid-property-p property))
15396 (user-error "Invalid property name: \"%s\"" property)))
15397 (org-with-point-at pom
15398 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15399 (org-back-to-heading t)
15400 (org-with-limited-levels (org-back-to-heading t)))
15401 (let ((beg (point)))
15402 (cond
15403 ((equal property "TODO")
15404 (cond ((not (org-string-nw-p value)) (setq value 'none))
15405 ((not (member value org-todo-keywords-1))
15406 (user-error "\"%s\" is not a valid TODO state" value)))
15407 (org-todo value)
15408 (org-set-tags nil 'align))
15409 ((equal property "PRIORITY")
15410 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15411 (org-set-tags nil 'align))
15412 ((equal property "SCHEDULED")
15413 (forward-line)
15414 (if (and (looking-at-p org-planning-line-re)
15415 (re-search-forward
15416 org-scheduled-time-regexp (line-end-position) t))
15417 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15418 ((string= value "later") (org-timestamp-change 1 'day))
15419 ((string= value "") (org-schedule '(4)))
15420 (t (org-schedule nil value)))
15421 (if (member value '("earlier" "later" ""))
15422 (call-interactively #'org-schedule)
15423 (org-schedule nil value))))
15424 ((equal property "DEADLINE")
15425 (forward-line)
15426 (if (and (looking-at-p org-planning-line-re)
15427 (re-search-forward
15428 org-deadline-time-regexp (line-end-position) t))
15429 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15430 ((string= value "later") (org-timestamp-change 1 'day))
15431 ((string= value "") (org-deadline '(4)))
15432 (t (org-deadline nil value)))
15433 (if (member value '("earlier" "later" ""))
15434 (call-interactively #'org-deadline)
15435 (org-deadline nil value))))
15436 ((member property org-special-properties)
15437 (error "The %s property cannot be set with `org-entry-put'" property))
15439 (let* ((range (org-get-property-block beg 'force))
15440 (end (cdr range))
15441 (case-fold-search t))
15442 (goto-char (car range))
15443 (if (re-search-forward (org-re-property property nil t) end t)
15444 (progn (delete-region (match-beginning 0) (match-end 0))
15445 (goto-char (match-beginning 0)))
15446 (goto-char end)
15447 (insert "\n")
15448 (backward-char))
15449 (insert ":" property ":")
15450 (when value (insert " " value))
15451 (org-indent-line)))))
15452 (run-hook-with-args 'org-property-changed-functions property value)))
15454 (defun org-buffer-property-keys (&optional specials defaults columns)
15455 "Get all property keys in the current buffer.
15457 When SPECIALS is non-nil, also list the special properties that
15458 reflect things like tags and TODO state.
15460 When DEFAULTS is non-nil, also include properties that has
15461 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15462 DESCRIPTION, LOCATION, and LOGGING and others.
15464 When COLUMNS in non-nil, also include property names given in
15465 COLUMN formats in the current buffer."
15466 (let ((case-fold-search t)
15467 (props (append
15468 (and specials org-special-properties)
15469 (and defaults (cons org-effort-property org-default-properties))
15470 nil)))
15471 (org-with-wide-buffer
15472 (goto-char (point-min))
15473 (while (re-search-forward org-property-start-re nil t)
15474 (catch :skip
15475 (let ((range (org-get-property-block)))
15476 (unless range (throw :skip nil))
15477 (goto-char (car range))
15478 (let ((begin (car range))
15479 (end (cdr range)))
15480 ;; Make sure that found property block is not located
15481 ;; before current point, as it would generate an infloop.
15482 ;; It can happen, for example, in the following
15483 ;; situation:
15485 ;; * Headline
15486 ;; :PROPERTIES:
15487 ;; ...
15488 ;; :END:
15489 ;; *************** Inlinetask
15490 ;; #+BEGIN_EXAMPLE
15491 ;; :PROPERTIES:
15492 ;; #+END_EXAMPLE
15494 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15495 (while (< (point) end)
15496 (let ((p (progn (looking-at org-property-re)
15497 (match-string-no-properties 2))))
15498 ;; Only add true property name, not extension symbol.
15499 (push (if (not (string-match-p "\\+\\'" p)) p
15500 (substring p 0 -1))
15501 props))
15502 (forward-line))))
15503 (outline-next-heading)))
15504 (when columns
15505 (goto-char (point-min))
15506 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15507 (let ((element (org-element-at-point)))
15508 (when (memq (org-element-type element) '(keyword node-property))
15509 (let ((value (org-element-property :value element))
15510 (start 0))
15511 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15512 \\(?:{[^}]+}\\)?"
15513 value start)
15514 (setq start (match-end 0))
15515 (let ((p (match-string-no-properties 1 value)))
15516 (unless (member-ignore-case p org-special-properties)
15517 (push p props))))))))))
15518 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15520 (defun org-property-values (key)
15521 "List all non-nil values of property KEY in current buffer."
15522 (org-with-wide-buffer
15523 (goto-char (point-min))
15524 (let ((case-fold-search t)
15525 (re (org-re-property key))
15526 values)
15527 (while (re-search-forward re nil t)
15528 (push (org-entry-get (point) key) values))
15529 (delete-dups values))))
15531 (defun org-insert-property-drawer ()
15532 "Insert a property drawer into the current entry."
15533 (org-with-wide-buffer
15534 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15535 (org-back-to-heading t)
15536 (org-with-limited-levels (org-back-to-heading t)))
15537 (forward-line)
15538 (when (looking-at-p org-planning-line-re) (forward-line))
15539 (unless (looking-at-p org-property-drawer-re)
15540 ;; Make sure we start editing a line from current entry, not from
15541 ;; next one. It prevents extending text properties or overlays
15542 ;; belonging to the latter.
15543 (when (bolp) (backward-char))
15544 (let ((begin (1+ (point)))
15545 (inhibit-read-only t))
15546 (insert "\n:PROPERTIES:\n:END:")
15547 (when (eobp) (insert "\n"))
15548 (org-indent-region begin (point))))))
15550 (defun org-insert-drawer (&optional arg drawer)
15551 "Insert a drawer at point.
15553 When optional argument ARG is non-nil, insert a property drawer.
15555 Optional argument DRAWER, when non-nil, is a string representing
15556 drawer's name. Otherwise, the user is prompted for a name.
15558 If a region is active, insert the drawer around that region
15559 instead.
15561 Point is left between drawer's boundaries."
15562 (interactive "P")
15563 (let* ((drawer (if arg "PROPERTIES"
15564 (or drawer (read-from-minibuffer "Drawer: ")))))
15565 (cond
15566 ;; With C-u, fall back on `org-insert-property-drawer'
15567 (arg (org-insert-property-drawer))
15568 ;; Check validity of suggested drawer's name.
15569 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15570 (user-error "Invalid drawer name"))
15571 ;; With an active region, insert a drawer at point.
15572 ((not (org-region-active-p))
15573 (progn
15574 (unless (bolp) (insert "\n"))
15575 (insert (format ":%s:\n\n:END:\n" drawer))
15576 (forward-line -2)))
15577 ;; Otherwise, insert the drawer at point
15579 (let ((rbeg (region-beginning))
15580 (rend (copy-marker (region-end))))
15581 (unwind-protect
15582 (progn
15583 (goto-char rbeg)
15584 (beginning-of-line)
15585 (when (save-excursion
15586 (re-search-forward org-outline-regexp-bol rend t))
15587 (user-error "Drawers cannot contain headlines"))
15588 ;; Position point at the beginning of the first
15589 ;; non-blank line in region. Insert drawer's opening
15590 ;; there, then indent it.
15591 (org-skip-whitespace)
15592 (beginning-of-line)
15593 (insert ":" drawer ":\n")
15594 (forward-line -1)
15595 (indent-for-tab-command)
15596 ;; Move point to the beginning of the first blank line
15597 ;; after the last non-blank line in region. Insert
15598 ;; drawer's closing, then indent it.
15599 (goto-char rend)
15600 (skip-chars-backward " \r\t\n")
15601 (insert "\n:END:")
15602 (deactivate-mark t)
15603 (indent-for-tab-command)
15604 (unless (eolp) (insert "\n")))
15605 ;; Clear marker, whatever the outcome of insertion is.
15606 (set-marker rend nil)))))))
15608 (defvar org-property-set-functions-alist nil
15609 "Property set function alist.
15610 Each entry should have the following format:
15612 (PROPERTY . READ-FUNCTION)
15614 The read function will be called with the same argument as
15615 `org-completing-read'.")
15617 (defun org-set-property-function (property)
15618 "Get the function that should be used to set PROPERTY.
15619 This is computed according to `org-property-set-functions-alist'."
15620 (or (cdr (assoc property org-property-set-functions-alist))
15621 'org-completing-read))
15623 (defun org-read-property-value (property)
15624 "Read PROPERTY value from user."
15625 (let* ((completion-ignore-case t)
15626 (allowed (org-property-get-allowed-values nil property 'table))
15627 (cur (org-entry-get nil property))
15628 (prompt (concat property " value"
15629 (if (and cur (string-match "\\S-" cur))
15630 (concat " [" cur "]") "") ": "))
15631 (set-function (org-set-property-function property))
15632 (val (if allowed
15633 (funcall set-function prompt allowed nil
15634 (not (get-text-property 0 'org-unrestricted
15635 (caar allowed))))
15636 (funcall set-function prompt
15637 (mapcar 'list (org-property-values property))
15638 nil nil "" nil cur))))
15639 (org-trim val)))
15641 (defvar org-last-set-property nil)
15642 (defvar org-last-set-property-value nil)
15643 (defun org-read-property-name ()
15644 "Read a property name."
15645 (let ((completion-ignore-case t)
15646 (default-prop (or (and (org-at-property-p)
15647 (match-string-no-properties 2))
15648 org-last-set-property)))
15649 (org-completing-read
15650 (concat "Property"
15651 (if default-prop (concat " [" default-prop "]") "")
15652 ": ")
15653 (mapcar #'list (org-buffer-property-keys nil t t))
15654 nil nil nil nil default-prop)))
15656 (defun org-set-property-and-value (use-last)
15657 "Allow to set [PROPERTY]: [value] direction from prompt.
15658 When use-default, don't even ask, just use the last
15659 \"[PROPERTY]: [value]\" string from the history."
15660 (interactive "P")
15661 (let* ((completion-ignore-case t)
15662 (pv (or (and use-last org-last-set-property-value)
15663 (org-completing-read
15664 "Enter a \"[Property]: [value]\" pair: "
15665 nil nil nil nil nil
15666 org-last-set-property-value)))
15667 prop val)
15668 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15669 (setq prop (match-string 1 pv)
15670 val (match-string 2 pv))
15671 (org-set-property prop val))))
15673 (defun org-set-property (property value)
15674 "In the current entry, set PROPERTY to VALUE.
15676 When called interactively, this will prompt for a property name, offering
15677 completion on existing and default properties. And then it will prompt
15678 for a value, offering completion either on allowed values (via an inherited
15679 xxx_ALL property) or on existing values in other instances of this property
15680 in the current file.
15682 Throw an error when trying to set a property with an invalid name."
15683 (interactive (list nil nil))
15684 (let ((property (or property (org-read-property-name))))
15685 ;; `org-entry-put' also makes the following check, but this one
15686 ;; avoids polluting `org-last-set-property' and
15687 ;; `org-last-set-property-value' needlessly.
15688 (unless (org--valid-property-p property)
15689 (user-error "Invalid property name: \"%s\"" property))
15690 (let ((value (or value (org-read-property-value property)))
15691 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15692 (setq org-last-set-property property)
15693 (setq org-last-set-property-value (concat property ": " value))
15694 ;; Possibly postprocess the inserted value:
15695 (when fn (setq value (funcall fn value)))
15696 (unless (equal (org-entry-get nil property) value)
15697 (org-entry-put nil property value)))))
15699 (defun org-find-property (property &optional value)
15700 "Find first entry in buffer that sets PROPERTY.
15702 When optional argument VALUE is non-nil, only consider an entry
15703 if it contains PROPERTY set to this value. If PROPERTY should be
15704 explicitly set to nil, use string \"nil\" for VALUE.
15706 Return position where the entry begins, or nil if there is no
15707 such entry. If narrowing is in effect, only search the visible
15708 part of the buffer."
15709 (save-excursion
15710 (goto-char (point-min))
15711 (let ((case-fold-search t)
15712 (re (org-re-property property nil (not value) value)))
15713 (catch 'exit
15714 (while (re-search-forward re nil t)
15715 (when (if value (org-at-property-p)
15716 (org-entry-get (point) property nil t))
15717 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15719 (defun org-delete-property (property)
15720 "In the current entry, delete PROPERTY."
15721 (interactive
15722 (let* ((completion-ignore-case t)
15723 (cat (org-entry-get (point) "CATEGORY"))
15724 (props0 (org-entry-properties nil 'standard))
15725 (props (if cat props0
15726 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15727 (prop (if (< 1 (length props))
15728 (completing-read "Property: " props nil t)
15729 (caar props))))
15730 (list prop)))
15731 (if (not property)
15732 (message "No property to delete in this entry")
15733 (org-entry-delete nil property)
15734 (message "Property \"%s\" deleted" property)))
15736 (defun org-delete-property-globally (property)
15737 "Remove PROPERTY globally, from all entries.
15738 This function ignores narrowing, if any."
15739 (interactive
15740 (let* ((completion-ignore-case t)
15741 (prop (completing-read
15742 "Globally remove property: "
15743 (mapcar #'list (org-buffer-property-keys)))))
15744 (list prop)))
15745 (org-with-wide-buffer
15746 (goto-char (point-min))
15747 (let ((count 0)
15748 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15749 (while (re-search-forward re nil t)
15750 (when (org-entry-delete (point) property) (cl-incf count)))
15751 (message "Property \"%s\" removed from %d entries" property count))))
15753 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15755 (defun org-compute-property-at-point ()
15756 "Compute the property at point.
15757 This looks for an enclosing column format, extracts the operator and
15758 then applies it to the property in the column format's scope."
15759 (interactive)
15760 (unless (org-at-property-p)
15761 (user-error "Not at a property"))
15762 (let ((prop (match-string-no-properties 2)))
15763 (org-columns-get-format-and-top-level)
15764 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15765 (user-error "No operator defined for property %s" prop))
15766 (org-columns-compute prop)))
15768 (defvar org-property-allowed-value-functions nil
15769 "Hook for functions supplying allowed values for a specific property.
15770 The functions must take a single argument, the name of the property, and
15771 return a flat list of allowed values. If \":ETC\" is one of
15772 the values, this means that these values are intended as defaults for
15773 completion, but that other values should be allowed too.
15774 The functions must return nil if they are not responsible for this
15775 property.")
15777 (defun org-property-get-allowed-values (pom property &optional table)
15778 "Get allowed values for the property PROPERTY.
15779 When TABLE is non-nil, return an alist that can directly be used for
15780 completion."
15781 (let (vals)
15782 (cond
15783 ((equal property "TODO")
15784 (setq vals (org-with-point-at pom
15785 (append org-todo-keywords-1 '("")))))
15786 ((equal property "PRIORITY")
15787 (let ((n org-lowest-priority))
15788 (while (>= n org-highest-priority)
15789 (push (char-to-string n) vals)
15790 (setq n (1- n)))))
15791 ((equal property "CATEGORY"))
15792 ((member property org-special-properties))
15793 ((setq vals (run-hook-with-args-until-success
15794 'org-property-allowed-value-functions property)))
15796 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15797 (when (and vals (string-match "\\S-" vals))
15798 (setq vals (car (read-from-string (concat "(" vals ")"))))
15799 (setq vals (mapcar (lambda (x)
15800 (cond ((stringp x) x)
15801 ((numberp x) (number-to-string x))
15802 ((symbolp x) (symbol-name x))
15803 (t "???")))
15804 vals)))))
15805 (when (member ":ETC" vals)
15806 (setq vals (remove ":ETC" vals))
15807 (org-add-props (car vals) '(org-unrestricted t)))
15808 (if table (mapcar 'list vals) vals)))
15810 (defun org-property-previous-allowed-value (&optional _previous)
15811 "Switch to the next allowed value for this property."
15812 (interactive)
15813 (org-property-next-allowed-value t))
15815 (defun org-property-next-allowed-value (&optional previous)
15816 "Switch to the next allowed value for this property."
15817 (interactive)
15818 (unless (org-at-property-p)
15819 (user-error "Not at a property"))
15820 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15821 (key (match-string 2))
15822 (value (match-string 3))
15823 (allowed (or (org-property-get-allowed-values (point) key)
15824 (and (member value '("[ ]" "[-]" "[X]"))
15825 '("[ ]" "[X]"))))
15826 (heading (save-match-data (nth 4 (org-heading-components))))
15827 nval)
15828 (unless allowed
15829 (user-error "Allowed values for this property have not been defined"))
15830 (when previous (setq allowed (reverse allowed)))
15831 (when (member value allowed)
15832 (setq nval (car (cdr (member value allowed)))))
15833 (setq nval (or nval (car allowed)))
15834 (when (equal nval value)
15835 (user-error "Only one allowed value for this property"))
15836 (org-at-property-p)
15837 (replace-match (concat " :" key ": " nval) t t)
15838 (org-indent-line)
15839 (beginning-of-line 1)
15840 (skip-chars-forward " \t")
15841 (when (equal prop org-effort-property)
15842 (org-refresh-property
15843 '((effort . identity)
15844 (effort-minutes . org-duration-to-minutes))
15845 nval)
15846 (when (string= org-clock-current-task heading)
15847 (setq org-clock-effort nval)
15848 (org-clock-update-mode-line)))
15849 (run-hook-with-args 'org-property-changed-functions key nval)))
15851 (defun org-find-olp (path &optional this-buffer)
15852 "Return a marker pointing to the entry at outline path OLP.
15853 If anything goes wrong, throw an error.
15854 You can wrap this call to catch the error like this:
15856 (condition-case msg
15857 (org-mobile-locate-entry (match-string 4))
15858 (error (nth 1 msg)))
15860 The return value will then be either a string with the error message,
15861 or a marker if everything is OK.
15863 If THIS-BUFFER is set, the outline path does not contain a file,
15864 only headings."
15865 (let* ((file (if this-buffer buffer-file-name (pop path)))
15866 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15867 (level 1)
15868 (lmin 1)
15869 (lmax 1)
15870 end found flevel)
15871 (unless buffer (error "File not found :%s" file))
15872 (with-current-buffer buffer
15873 (unless (derived-mode-p 'org-mode)
15874 (error "Buffer %s needs to be in Org mode" buffer))
15875 (org-with-wide-buffer
15876 (goto-char (point-min))
15877 (dolist (heading path)
15878 (let ((re (format org-complex-heading-regexp-format
15879 (regexp-quote heading)))
15880 (cnt 0))
15881 (while (re-search-forward re end t)
15882 (setq level (- (match-end 1) (match-beginning 1)))
15883 (when (and (>= level lmin) (<= level lmax))
15884 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15885 (when (= cnt 0)
15886 (error "Heading not found on level %d: %s" lmax heading))
15887 (when (> cnt 1)
15888 (error "Heading not unique on level %d: %s" lmax heading))
15889 (goto-char found)
15890 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15891 (setq end (save-excursion (org-end-of-subtree t t)))))
15892 (when (org-at-heading-p)
15893 (point-marker))))))
15895 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15896 "Find node HEADING in BUFFER.
15897 Return a marker to the heading if it was found, or nil if not.
15898 If POS-ONLY is set, return just the position instead of a marker.
15900 The heading text must match exact, but it may have a TODO keyword,
15901 a priority cookie and tags in the standard locations."
15902 (with-current-buffer (or buffer (current-buffer))
15903 (org-with-wide-buffer
15904 (goto-char (point-min))
15905 (let (case-fold-search)
15906 (when (re-search-forward
15907 (format org-complex-heading-regexp-format
15908 (regexp-quote heading)) nil t)
15909 (if pos-only
15910 (match-beginning 0)
15911 (move-marker (make-marker) (match-beginning 0))))))))
15913 (defun org-find-exact-heading-in-directory (heading &optional dir)
15914 "Find Org node headline HEADING in all .org files in directory DIR.
15915 When the target headline is found, return a marker to this location."
15916 (let ((files (directory-files (or dir default-directory)
15917 t "\\`[^.#].*\\.org\\'"))
15918 visiting m buffer)
15919 (catch 'found
15920 (dolist (file files)
15921 (message "trying %s" file)
15922 (setq visiting (org-find-base-buffer-visiting file))
15923 (setq buffer (or visiting (find-file-noselect file)))
15924 (setq m (org-find-exact-headline-in-buffer
15925 heading buffer))
15926 (when (and (not m) (not visiting)) (kill-buffer buffer))
15927 (and m (throw 'found m))))))
15929 (defun org-find-entry-with-id (ident)
15930 "Locate the entry that contains the ID property with exact value IDENT.
15931 IDENT can be a string, a symbol or a number, this function will search for
15932 the string representation of it.
15933 Return the position where this entry starts, or nil if there is no such entry."
15934 (interactive "sID: ")
15935 (let ((id (cond
15936 ((stringp ident) ident)
15937 ((symbolp ident) (symbol-name ident))
15938 ((numberp ident) (number-to-string ident))
15939 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15940 (org-with-wide-buffer (org-find-property "ID" id))))
15942 ;;;; Timestamps
15944 (defvar org-last-changed-timestamp nil)
15945 (defvar org-last-inserted-timestamp nil
15946 "The last time stamp inserted with `org-insert-time-stamp'.")
15948 (defun org-time-stamp (arg &optional inactive)
15949 "Prompt for a date/time and insert a time stamp.
15951 If the user specifies a time like HH:MM or if this command is
15952 called with at least one prefix argument, the time stamp contains
15953 the date and the time. Otherwise, only the date is included.
15955 All parts of a date not specified by the user are filled in from
15956 the timestamp at point, if any, or the current date/time
15957 otherwise.
15959 If there is already a timestamp at the cursor, it is replaced.
15961 With two universal prefix arguments, insert an active timestamp
15962 with the current time without prompting the user.
15964 When called from lisp, the timestamp is inactive if INACTIVE is
15965 non-nil."
15966 (interactive "P")
15967 (let* ((ts (cond
15968 ((org-at-date-range-p t)
15969 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15970 ((org-at-timestamp-p 'lax) (match-string 0))))
15971 ;; Default time is either the timestamp at point or today.
15972 ;; When entering a range, only the range start is considered.
15973 (default-time (if (not ts) (current-time)
15974 (apply #'encode-time (org-parse-time-string ts))))
15975 (default-input (and ts (org-get-compact-tod ts)))
15976 (repeater (and ts
15977 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15978 (match-string 0 ts)))
15979 org-time-was-given
15980 org-end-time-was-given
15981 (time
15982 (and (if (equal arg '(16)) (current-time)
15983 ;; Preserve `this-command' and `last-command'.
15984 (let ((this-command this-command)
15985 (last-command last-command))
15986 (org-read-date
15987 arg 'totime nil nil default-time default-input
15988 inactive))))))
15989 (cond
15990 ((and ts
15991 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15992 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15993 (insert "--")
15994 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15996 ;; Make sure we're on a timestamp. When in the middle of a date
15997 ;; range, move arbitrarily to range end.
15998 (unless (org-at-timestamp-p 'lax)
15999 (skip-chars-forward "-")
16000 (org-at-timestamp-p 'lax))
16001 (replace-match "")
16002 (setq org-last-changed-timestamp
16003 (org-insert-time-stamp
16004 time (or org-time-was-given arg)
16005 inactive nil nil (list org-end-time-was-given)))
16006 (when repeater
16007 (backward-char)
16008 (insert " " repeater)
16009 (setq org-last-changed-timestamp
16010 (concat (substring org-last-inserted-timestamp 0 -1)
16011 " " repeater ">")))
16012 (message "Timestamp updated"))
16013 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16014 (t (org-insert-time-stamp
16015 time (or org-time-was-given arg) inactive nil nil
16016 (list org-end-time-was-given))))))
16018 ;; FIXME: can we use this for something else, like computing time differences?
16019 (defun org-get-compact-tod (s)
16020 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16021 (let* ((t1 (match-string 1 s))
16022 (h1 (string-to-number (match-string 2 s)))
16023 (m1 (string-to-number (match-string 3 s)))
16024 (t2 (and (match-end 4) (match-string 5 s)))
16025 (h2 (and t2 (string-to-number (match-string 6 s))))
16026 (m2 (and t2 (string-to-number (match-string 7 s))))
16027 dh dm)
16028 (if (not t2)
16030 (setq dh (- h2 h1) dm (- m2 m1))
16031 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16032 (concat t1 "+" (number-to-string dh)
16033 (and (/= 0 dm) (format ":%02d" dm)))))))
16035 (defun org-time-stamp-inactive (&optional arg)
16036 "Insert an inactive time stamp.
16037 An inactive time stamp is enclosed in square brackets instead of angle
16038 brackets. It is inactive in the sense that it does not trigger agenda entries,
16039 does not link to the calendar and cannot be changed with the S-cursor keys.
16040 So these are more for recording a certain time/date."
16041 (interactive "P")
16042 (org-time-stamp arg 'inactive))
16044 (defvar org-date-ovl (make-overlay 1 1))
16045 (overlay-put org-date-ovl 'face 'org-date-selected)
16046 (delete-overlay org-date-ovl)
16048 (defvar org-ans1) ; dynamically scoped parameter
16049 (defvar org-ans2) ; dynamically scoped parameter
16051 (defvar org-plain-time-of-day-regexp) ; defined below
16053 (defvar org-overriding-default-time nil) ; dynamically scoped
16054 (defvar org-read-date-overlay nil)
16055 (defvar org-dcst nil) ; dynamically scoped
16056 (defvar org-read-date-history nil)
16057 (defvar org-read-date-final-answer nil)
16058 (defvar org-read-date-analyze-futurep nil)
16059 (defvar org-read-date-analyze-forced-year nil)
16060 (defvar org-read-date-inactive)
16062 (defvar org-read-date-minibuffer-local-map
16063 (let* ((map (make-sparse-keymap)))
16064 (set-keymap-parent map minibuffer-local-map)
16065 (org-defkey map (kbd ".")
16066 (lambda () (interactive)
16067 ;; Are we at the beginning of the prompt?
16068 (if (looking-back "^[^:]+: "
16069 (let ((inhibit-field-text-motion t))
16070 (line-beginning-position)))
16071 (org-eval-in-calendar '(calendar-goto-today))
16072 (insert "."))))
16073 (org-defkey map (kbd "C-.")
16074 (lambda () (interactive)
16075 (org-eval-in-calendar '(calendar-goto-today))))
16076 (org-defkey map [(meta shift left)]
16077 (lambda () (interactive)
16078 (org-eval-in-calendar '(calendar-backward-month 1))))
16079 (org-defkey map [(meta shift right)]
16080 (lambda () (interactive)
16081 (org-eval-in-calendar '(calendar-forward-month 1))))
16082 (org-defkey map [(meta shift up)]
16083 (lambda () (interactive)
16084 (org-eval-in-calendar '(calendar-backward-year 1))))
16085 (org-defkey map [(meta shift down)]
16086 (lambda () (interactive)
16087 (org-eval-in-calendar '(calendar-forward-year 1))))
16088 (org-defkey map [?\e (shift left)]
16089 (lambda () (interactive)
16090 (org-eval-in-calendar '(calendar-backward-month 1))))
16091 (org-defkey map [?\e (shift right)]
16092 (lambda () (interactive)
16093 (org-eval-in-calendar '(calendar-forward-month 1))))
16094 (org-defkey map [?\e (shift up)]
16095 (lambda () (interactive)
16096 (org-eval-in-calendar '(calendar-backward-year 1))))
16097 (org-defkey map [?\e (shift down)]
16098 (lambda () (interactive)
16099 (org-eval-in-calendar '(calendar-forward-year 1))))
16100 (org-defkey map [(shift up)]
16101 (lambda () (interactive)
16102 (org-eval-in-calendar '(calendar-backward-week 1))))
16103 (org-defkey map [(shift down)]
16104 (lambda () (interactive)
16105 (org-eval-in-calendar '(calendar-forward-week 1))))
16106 (org-defkey map [(shift left)]
16107 (lambda () (interactive)
16108 (org-eval-in-calendar '(calendar-backward-day 1))))
16109 (org-defkey map [(shift right)]
16110 (lambda () (interactive)
16111 (org-eval-in-calendar '(calendar-forward-day 1))))
16112 (org-defkey map "!"
16113 (lambda () (interactive)
16114 (org-eval-in-calendar '(diary-view-entries))
16115 (message "")))
16116 (org-defkey map ">"
16117 (lambda () (interactive)
16118 (org-eval-in-calendar '(calendar-scroll-left 1))))
16119 (org-defkey map "<"
16120 (lambda () (interactive)
16121 (org-eval-in-calendar '(calendar-scroll-right 1))))
16122 (org-defkey map "\C-v"
16123 (lambda () (interactive)
16124 (org-eval-in-calendar
16125 '(calendar-scroll-left-three-months 1))))
16126 (org-defkey map "\M-v"
16127 (lambda () (interactive)
16128 (org-eval-in-calendar
16129 '(calendar-scroll-right-three-months 1))))
16130 map)
16131 "Keymap for minibuffer commands when using `org-read-date'.")
16133 (defvar org-def)
16134 (defvar org-defdecode)
16135 (defvar org-with-time)
16137 (defvar calendar-setup) ; Dynamically scoped.
16138 (defun org-read-date (&optional with-time to-time from-string prompt
16139 default-time default-input inactive)
16140 "Read a date, possibly a time, and make things smooth for the user.
16141 The prompt will suggest to enter an ISO date, but you can also enter anything
16142 which will at least partially be understood by `parse-time-string'.
16143 Unrecognized parts of the date will default to the current day, month, year,
16144 hour and minute. If this command is called to replace a timestamp at point,
16145 or to enter the second timestamp of a range, the default time is taken
16146 from the existing stamp. Furthermore, the command prefers the future,
16147 so if you are giving a date where the year is not given, and the day-month
16148 combination is already past in the current year, it will assume you
16149 mean next year. For details, see the manual. A few examples:
16151 3-2-5 --> 2003-02-05
16152 feb 15 --> currentyear-02-15
16153 2/15 --> currentyear-02-15
16154 sep 12 9 --> 2009-09-12
16155 12:45 --> today 12:45
16156 22 sept 0:34 --> currentyear-09-22 0:34
16157 12 --> currentyear-currentmonth-12
16158 Fri --> nearest Friday after today
16159 -Tue --> last Tuesday
16160 etc.
16162 Furthermore you can specify a relative date by giving, as the *first* thing
16163 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16164 change in days weeks, months, years.
16165 With a single plus or minus, the date is relative to today. With a double
16166 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16167 +4d --> four days from today
16168 +4 --> same as above
16169 +2w --> two weeks from today
16170 ++5 --> five days from default date
16172 The function understands only English month and weekday abbreviations.
16174 While prompting, a calendar is popped up - you can also select the
16175 date with the mouse (button 1). The calendar shows a period of three
16176 months. To scroll it to other months, use the keys `>' and `<'.
16177 If you don't like the calendar, turn it off with
16178 (setq org-read-date-popup-calendar nil)
16180 With optional argument TO-TIME, the date will immediately be converted
16181 to an internal time.
16182 With an optional argument WITH-TIME, the prompt will suggest to
16183 also insert a time. Note that when WITH-TIME is not set, you can
16184 still enter a time, and this function will inform the calling routine
16185 about this change. The calling routine may then choose to change the
16186 format used to insert the time stamp into the buffer to include the time.
16187 With optional argument FROM-STRING, read from this string instead from
16188 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16189 the time/date that is used for everything that is not specified by the
16190 user."
16191 (require 'parse-time)
16192 (let* ((org-with-time with-time)
16193 (org-time-stamp-rounding-minutes
16194 (if (equal org-with-time '(16))
16195 '(0 0)
16196 org-time-stamp-rounding-minutes))
16197 (org-dcst org-display-custom-times)
16198 (ct (org-current-time))
16199 (org-def (or org-overriding-default-time default-time ct))
16200 (org-defdecode (decode-time org-def))
16201 (cur-frame (selected-frame))
16202 (mouse-autoselect-window nil) ; Don't let the mouse jump
16203 (calendar-setup
16204 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16205 (calendar-move-hook nil)
16206 (calendar-view-diary-initially-flag nil)
16207 (calendar-view-holidays-initially-flag nil)
16208 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16209 ;; Rationalize `org-def' and `org-defdecode', if required.
16210 (when (< (nth 2 org-defdecode) org-extend-today-until)
16211 (setf (nth 2 org-defdecode) -1)
16212 (setf (nth 1 org-defdecode) 59)
16213 (setq org-def (apply #'encode-time org-defdecode))
16214 (setq org-defdecode (decode-time org-def)))
16215 (let* ((timestr (format-time-string
16216 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16217 org-def))
16218 (prompt (concat (if prompt (concat prompt " ") "")
16219 (format "Date+time [%s]: " timestr))))
16220 (cond
16221 (from-string (setq ans from-string))
16222 (org-read-date-popup-calendar
16223 (save-excursion
16224 (save-window-excursion
16225 (calendar)
16226 (when (eq calendar-setup 'calendar-only)
16227 (setq cal-frame
16228 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16229 (select-frame cal-frame))
16230 (org-eval-in-calendar '(setq cursor-type nil) t)
16231 (unwind-protect
16232 (progn
16233 (calendar-forward-day (- (time-to-days org-def)
16234 (calendar-absolute-from-gregorian
16235 (calendar-current-date))))
16236 (org-eval-in-calendar nil t)
16237 (let* ((old-map (current-local-map))
16238 (map (copy-keymap calendar-mode-map))
16239 (minibuffer-local-map
16240 (copy-keymap org-read-date-minibuffer-local-map)))
16241 (org-defkey map (kbd "RET") 'org-calendar-select)
16242 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16243 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16244 (unwind-protect
16245 (progn
16246 (use-local-map map)
16247 (setq org-read-date-inactive inactive)
16248 (add-hook 'post-command-hook 'org-read-date-display)
16249 (setq org-ans0
16250 (read-string prompt
16251 default-input
16252 'org-read-date-history
16253 nil))
16254 ;; org-ans0: from prompt
16255 ;; org-ans1: from mouse click
16256 ;; org-ans2: from calendar motion
16257 (setq ans
16258 (concat org-ans0 " " (or org-ans1 org-ans2))))
16259 (remove-hook 'post-command-hook 'org-read-date-display)
16260 (use-local-map old-map)
16261 (when org-read-date-overlay
16262 (delete-overlay org-read-date-overlay)
16263 (setq org-read-date-overlay nil)))))
16264 (bury-buffer "*Calendar*")
16265 (when cal-frame
16266 (delete-frame cal-frame)
16267 (select-frame-set-input-focus cur-frame))))))
16269 (t ; Naked prompt only
16270 (unwind-protect
16271 (setq ans (read-string prompt default-input
16272 'org-read-date-history timestr))
16273 (when org-read-date-overlay
16274 (delete-overlay org-read-date-overlay)
16275 (setq org-read-date-overlay nil))))))
16277 (setq final (org-read-date-analyze ans org-def org-defdecode))
16279 (when org-read-date-analyze-forced-year
16280 (message "Year was forced into %s"
16281 (if org-read-date-force-compatible-dates
16282 "compatible range (1970-2037)"
16283 "range representable on this machine"))
16284 (ding))
16286 ;; One round trip to get rid of 34th of August and stuff like that....
16287 (setq final (decode-time (apply 'encode-time final)))
16289 (setq org-read-date-final-answer ans)
16291 (if to-time
16292 (apply 'encode-time final)
16293 (if (and (boundp 'org-time-was-given) org-time-was-given)
16294 (format "%04d-%02d-%02d %02d:%02d"
16295 (nth 5 final) (nth 4 final) (nth 3 final)
16296 (nth 2 final) (nth 1 final))
16297 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16299 (defun org-read-date-display ()
16300 "Display the current date prompt interpretation in the minibuffer."
16301 (when org-read-date-display-live
16302 (when org-read-date-overlay
16303 (delete-overlay org-read-date-overlay))
16304 (when (minibufferp (current-buffer))
16305 (save-excursion
16306 (end-of-line 1)
16307 (while (not (equal (buffer-substring
16308 (max (point-min) (- (point) 4)) (point))
16309 " "))
16310 (insert " ")))
16311 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16312 " " (or org-ans1 org-ans2)))
16313 (org-end-time-was-given nil)
16314 (f (org-read-date-analyze ans org-def org-defdecode))
16315 (fmts (if org-dcst
16316 org-time-stamp-custom-formats
16317 org-time-stamp-formats))
16318 (fmt (if (or org-with-time
16319 (and (boundp 'org-time-was-given) org-time-was-given))
16320 (cdr fmts)
16321 (car fmts)))
16322 (txt (format-time-string fmt (apply 'encode-time f)))
16323 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16324 (txt (concat "=> " txt)))
16325 (when (and org-end-time-was-given
16326 (string-match org-plain-time-of-day-regexp txt))
16327 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16328 org-end-time-was-given
16329 (substring txt (match-end 0)))))
16330 (when org-read-date-analyze-futurep
16331 (setq txt (concat txt " (=>F)")))
16332 (setq org-read-date-overlay
16333 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16334 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16336 (defun org-read-date-analyze (ans def defdecode)
16337 "Analyze the combined answer of the date prompt."
16338 ;; FIXME: cleanup and comment
16339 ;; Pass `current-time' result to `decode-time' (instead of calling
16340 ;; without arguments) so that only `current-time' has to be
16341 ;; overridden in tests.
16342 (let ((org-def def)
16343 (org-defdecode defdecode)
16344 (nowdecode (decode-time (current-time)))
16345 delta deltan deltaw deltadef year month day
16346 hour minute second wday pm h2 m2 tl wday1
16347 iso-year iso-weekday iso-week iso-date futurep kill-year)
16348 (setq org-read-date-analyze-futurep nil
16349 org-read-date-analyze-forced-year nil)
16350 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16351 (setq ans "+0"))
16353 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16354 (setq ans (replace-match "" t t ans)
16355 deltan (car delta)
16356 deltaw (nth 1 delta)
16357 deltadef (nth 2 delta)))
16359 ;; Check if there is an iso week date in there. If yes, store the
16360 ;; info and postpone interpreting it until the rest of the parsing
16361 ;; is done.
16362 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16363 (setq iso-year (when (match-end 1)
16364 (org-small-year-to-year
16365 (string-to-number (match-string 1 ans))))
16366 iso-weekday (when (match-end 3)
16367 (string-to-number (match-string 3 ans)))
16368 iso-week (string-to-number (match-string 2 ans)))
16369 (setq ans (replace-match "" t t ans)))
16371 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16372 (when (string-match
16373 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16374 (setq year (if (match-end 2)
16375 (string-to-number (match-string 2 ans))
16376 (progn (setq kill-year t)
16377 (string-to-number (format-time-string "%Y"))))
16378 month (string-to-number (match-string 3 ans))
16379 day (string-to-number (match-string 4 ans)))
16380 (setq year (org-small-year-to-year year))
16381 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16382 t nil ans)))
16384 ;; Help matching dotted european dates
16385 (when (string-match
16386 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16387 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16388 (setq kill-year t)
16389 (string-to-number (format-time-string "%Y")))
16390 day (string-to-number (match-string 1 ans))
16391 month (string-to-number (match-string 2 ans))
16392 ans (replace-match (format "%04d-%02d-%02d" year month day)
16393 t nil ans)))
16395 ;; Help matching american dates, like 5/30 or 5/30/7
16396 (when (string-match
16397 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16398 (setq year (if (match-end 4)
16399 (string-to-number (match-string 4 ans))
16400 (progn (setq kill-year t)
16401 (string-to-number (format-time-string "%Y"))))
16402 month (string-to-number (match-string 1 ans))
16403 day (string-to-number (match-string 2 ans)))
16404 (setq year (org-small-year-to-year year))
16405 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16406 t nil ans)))
16407 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16408 ;; If there is a time with am/pm, and *no* time without it, we convert
16409 ;; so that matching will be successful.
16410 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16411 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16412 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16413 (setq hour (string-to-number (match-string 1 ans))
16414 minute (if (match-end 3)
16415 (string-to-number (match-string 3 ans))
16417 pm (equal ?p
16418 (string-to-char (downcase (match-string 4 ans)))))
16419 (if (and (= hour 12) (not pm))
16420 (setq hour 0)
16421 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16422 (setq ans (replace-match (format "%02d:%02d" hour minute)
16423 t t ans))))
16425 ;; Check if a time range is given as a duration
16426 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16427 (setq hour (string-to-number (match-string 1 ans))
16428 h2 (+ hour (string-to-number (match-string 3 ans)))
16429 minute (string-to-number (match-string 2 ans))
16430 m2 (+ minute (if (match-end 5) (string-to-number
16431 (match-string 5 ans))0)))
16432 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16433 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16434 t t ans)))
16436 ;; Check if there is a time range
16437 (when (boundp 'org-end-time-was-given)
16438 (setq org-time-was-given nil)
16439 (when (and (string-match org-plain-time-of-day-regexp ans)
16440 (match-end 8))
16441 (setq org-end-time-was-given (match-string 8 ans))
16442 (setq ans (concat (substring ans 0 (match-beginning 7))
16443 (substring ans (match-end 7))))))
16445 (setq tl (parse-time-string ans)
16446 day (or (nth 3 tl) (nth 3 org-defdecode))
16447 month
16448 (cond ((nth 4 tl))
16449 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16450 ;; Day was specified. Make sure DAY+MONTH
16451 ;; combination happens in the future.
16452 ((nth 3 tl)
16453 (setq futurep t)
16454 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16455 (nth 4 nowdecode)))
16456 (t (nth 4 org-defdecode)))
16457 year
16458 (cond ((and (not kill-year) (nth 5 tl)))
16459 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16460 ;; Month was guessed in the future and is at least
16461 ;; equal to NOWDECODE's. Fix year accordingly.
16462 (futurep
16463 (if (or (> month (nth 4 nowdecode))
16464 (>= day (nth 3 nowdecode)))
16465 (nth 5 nowdecode)
16466 (1+ (nth 5 nowdecode))))
16467 ;; Month was specified. Make sure MONTH+YEAR
16468 ;; combination happens in the future.
16469 ((nth 4 tl)
16470 (setq futurep t)
16471 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16472 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16473 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16474 (t (nth 5 nowdecode))))
16475 (t (nth 5 org-defdecode)))
16476 hour (or (nth 2 tl) (nth 2 org-defdecode))
16477 minute (or (nth 1 tl) (nth 1 org-defdecode))
16478 second (or (nth 0 tl) 0)
16479 wday (nth 6 tl))
16481 (when (and (eq org-read-date-prefer-future 'time)
16482 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16483 (equal day (nth 3 nowdecode))
16484 (equal month (nth 4 nowdecode))
16485 (equal year (nth 5 nowdecode))
16486 (nth 2 tl)
16487 (or (< (nth 2 tl) (nth 2 nowdecode))
16488 (and (= (nth 2 tl) (nth 2 nowdecode))
16489 (nth 1 tl)
16490 (< (nth 1 tl) (nth 1 nowdecode)))))
16491 (setq day (1+ day)
16492 futurep t))
16494 ;; Special date definitions below
16495 (cond
16496 (iso-week
16497 ;; There was an iso week
16498 (require 'cal-iso)
16499 (setq futurep nil)
16500 (setq year (or iso-year year)
16501 day (or iso-weekday wday 1)
16502 wday nil ; to make sure that the trigger below does not match
16503 iso-date (calendar-gregorian-from-absolute
16504 (calendar-iso-to-absolute
16505 (list iso-week day year))))
16506 ; FIXME: Should we also push ISO weeks into the future?
16507 ; (when (and org-read-date-prefer-future
16508 ; (not iso-year)
16509 ; (< (calendar-absolute-from-gregorian iso-date)
16510 ; (time-to-days (current-time))))
16511 ; (setq year (1+ year)
16512 ; iso-date (calendar-gregorian-from-absolute
16513 ; (calendar-iso-to-absolute
16514 ; (list iso-week day year)))))
16515 (setq month (car iso-date)
16516 year (nth 2 iso-date)
16517 day (nth 1 iso-date)))
16518 (deltan
16519 (setq futurep nil)
16520 (unless deltadef
16521 ;; Pass `current-time' result to `decode-time' (instead of
16522 ;; calling without arguments) so that only `current-time' has
16523 ;; to be overridden in tests.
16524 (let ((now (decode-time (current-time))))
16525 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16526 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16527 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16528 ((equal deltaw "m") (setq month (+ month deltan)))
16529 ((equal deltaw "y") (setq year (+ year deltan)))))
16530 ((and wday (not (nth 3 tl)))
16531 ;; Weekday was given, but no day, so pick that day in the week
16532 ;; on or after the derived date.
16533 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16534 (unless (equal wday wday1)
16535 (setq day (+ day (% (- wday wday1 -7) 7))))))
16536 (when (and (boundp 'org-time-was-given)
16537 (nth 2 tl))
16538 (setq org-time-was-given t))
16539 (when (< year 100) (setq year (+ 2000 year)))
16540 ;; Check of the date is representable
16541 (if org-read-date-force-compatible-dates
16542 (progn
16543 (when (< year 1970)
16544 (setq year 1970 org-read-date-analyze-forced-year t))
16545 (when (> year 2037)
16546 (setq year 2037 org-read-date-analyze-forced-year t)))
16547 (condition-case nil
16548 (ignore (encode-time second minute hour day month year))
16549 (error
16550 (setq year (nth 5 org-defdecode))
16551 (setq org-read-date-analyze-forced-year t))))
16552 (setq org-read-date-analyze-futurep futurep)
16553 (list second minute hour day month year)))
16555 (defvar parse-time-weekdays)
16556 (defun org-read-date-get-relative (s today default)
16557 "Check string S for special relative date string.
16558 TODAY and DEFAULT are internal times, for today and for a default.
16559 Return shift list (N what def-flag)
16560 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16561 N is the number of WHATs to shift.
16562 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16563 the DEFAULT date rather than TODAY."
16564 (require 'parse-time)
16565 (when (and
16566 (string-match
16567 (concat
16568 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16569 "\\([0-9]+\\)?"
16570 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16571 "\\([ \t]\\|$\\)") s)
16572 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16573 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16574 (string-to-char (substring (match-string 1 s) -1))
16575 ?+))
16576 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16577 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16578 (what (if (match-end 3) (match-string 3 s) "d"))
16579 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16580 (date (if rel default today))
16581 (wday (nth 6 (decode-time date)))
16582 delta)
16583 (if wday1
16584 (progn
16585 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16586 (when (= delta 0) (setq delta 7))
16587 (when (= dir ?-)
16588 (setq delta (- delta 7))
16589 (when (= delta 0) (setq delta -7)))
16590 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16591 (list delta "d" rel))
16592 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16594 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16595 "Turn a user-specified date into the internal representation.
16596 The internal representation needed by the calendar is (month day year).
16597 This is a wrapper to handle the brain-dead convention in calendar that
16598 user function argument order change dependent on argument order."
16599 (pcase calendar-date-style
16600 (`american (list arg1 arg2 arg3))
16601 (`european (list arg2 arg1 arg3))
16602 (`iso (list arg2 arg3 arg1))))
16604 (defun org-eval-in-calendar (form &optional keepdate)
16605 "Eval FORM in the calendar window and return to current window.
16606 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16607 (let ((sf (selected-frame))
16608 (sw (selected-window)))
16609 (select-window (get-buffer-window "*Calendar*" t))
16610 (eval form)
16611 (when (and (not keepdate) (calendar-cursor-to-date))
16612 (let* ((date (calendar-cursor-to-date))
16613 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16614 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16615 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16616 (select-window sw)
16617 (select-frame-set-input-focus sf)))
16619 (defun org-calendar-select ()
16620 "Return to `org-read-date' with the date currently selected.
16621 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16622 (interactive)
16623 (when (calendar-cursor-to-date)
16624 (let* ((date (calendar-cursor-to-date))
16625 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16626 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16627 (when (active-minibuffer-window) (exit-minibuffer))))
16629 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16630 "Insert a date stamp for the date given by the internal TIME.
16631 See `format-time-string' for the format of TIME.
16632 WITH-HM means use the stamp format that includes the time of the day.
16633 INACTIVE means use square brackets instead of angular ones, so that the
16634 stamp will not contribute to the agenda.
16635 PRE and POST are optional strings to be inserted before and after the
16636 stamp.
16637 The command returns the inserted time stamp."
16638 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16639 stamp)
16640 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16641 (insert-before-markers (or pre ""))
16642 (when (listp extra)
16643 (setq extra (car extra))
16644 (if (and (stringp extra)
16645 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16646 (setq extra (format "-%02d:%02d"
16647 (string-to-number (match-string 1 extra))
16648 (string-to-number (match-string 2 extra))))
16649 (setq extra nil)))
16650 (when extra
16651 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16652 (insert-before-markers (setq stamp (format-time-string fmt time)))
16653 (insert-before-markers (or post ""))
16654 (setq org-last-inserted-timestamp stamp)))
16656 (defun org-toggle-time-stamp-overlays ()
16657 "Toggle the use of custom time stamp formats."
16658 (interactive)
16659 (setq org-display-custom-times (not org-display-custom-times))
16660 (unless org-display-custom-times
16661 (let ((p (point-min)) (bmp (buffer-modified-p)))
16662 (while (setq p (next-single-property-change p 'display))
16663 (when (and (get-text-property p 'display)
16664 (eq (get-text-property p 'face) 'org-date))
16665 (remove-text-properties
16666 p (setq p (next-single-property-change p 'display))
16667 '(display t))))
16668 (set-buffer-modified-p bmp)))
16669 (org-restart-font-lock)
16670 (setq org-table-may-need-update t)
16671 (if org-display-custom-times
16672 (message "Time stamps are overlaid with custom format")
16673 (message "Time stamp overlays removed")))
16675 (defun org-display-custom-time (beg end)
16676 "Overlay modified time stamp format over timestamp between BEG and END."
16677 (let* ((ts (buffer-substring beg end))
16678 t1 with-hm tf time str (off 0))
16679 (save-match-data
16680 (setq t1 (org-parse-time-string ts t))
16681 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16682 (setq off (- (match-end 0) (match-beginning 0)))))
16683 (setq end (- end off))
16684 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16685 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16686 time (org-fix-decoded-time t1)
16687 str (org-add-props
16688 (format-time-string
16689 (substring tf 1 -1) (apply 'encode-time time))
16690 nil 'mouse-face 'highlight))
16691 (put-text-property beg end 'display str)))
16693 (defun org-fix-decoded-time (time)
16694 "Set 0 instead of nil for the first 6 elements of time.
16695 Don't touch the rest."
16696 (let ((n 0))
16697 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16699 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16700 "Difference between TIMESTAMP-STRING and now in days.
16701 If SECONDS is non-nil, return the difference in seconds."
16702 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16703 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16704 (funcall fdiff (current-time)))))
16706 (defun org-deadline-close-p (timestamp-string &optional ndays)
16707 "Is the time in TIMESTAMP-STRING close to the current date?"
16708 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16709 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16710 (not (org-entry-is-done-p))))
16712 (defun org-get-wdays (ts &optional delay zero-delay)
16713 "Get the deadline lead time appropriate for timestring TS.
16714 When DELAY is non-nil, get the delay time for scheduled items
16715 instead of the deadline lead time. When ZERO-DELAY is non-nil
16716 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16717 don't try to find the delay cookie in the scheduled timestamp."
16718 (let ((tv (if delay org-scheduled-delay-days
16719 org-deadline-warning-days)))
16720 (cond
16721 ((or (and delay (< tv 0))
16722 (and delay zero-delay (<= tv 0))
16723 (and (not delay) (<= tv 0)))
16724 ;; Enforce this value no matter what
16725 (- tv))
16726 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16727 ;; lead time is specified.
16728 (floor (* (string-to-number (match-string 1 ts))
16729 (cdr (assoc (match-string 2 ts)
16730 '(("d" . 1) ("w" . 7)
16731 ("m" . 30.4) ("y" . 365.25)
16732 ("h" . 0.041667)))))))
16733 ;; go for the default.
16734 (t tv))))
16736 (defun org-calendar-select-mouse (ev)
16737 "Return to `org-read-date' with the date currently selected.
16738 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16739 (interactive "e")
16740 (mouse-set-point ev)
16741 (when (calendar-cursor-to-date)
16742 (let* ((date (calendar-cursor-to-date))
16743 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16744 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16745 (when (active-minibuffer-window) (exit-minibuffer))))
16747 (defun org-check-deadlines (ndays)
16748 "Check if there are any deadlines due or past due.
16749 A deadline is considered due if it happens within `org-deadline-warning-days'
16750 days from today's date. If the deadline appears in an entry marked DONE,
16751 it is not shown. A numeric prefix argument NDAYS can be used to test that
16752 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16753 are shown."
16754 (interactive "P")
16755 (let* ((org-warn-days
16756 (cond
16757 ((equal ndays '(4)) 100000)
16758 (ndays (prefix-numeric-value ndays))
16759 (t (abs org-deadline-warning-days))))
16760 (case-fold-search nil)
16761 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16762 (callback
16763 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16764 (message "%d deadlines past-due or due within %d days"
16765 (org-occur regexp nil callback)
16766 org-warn-days)))
16768 (defsubst org-re-timestamp (type)
16769 "Return a regexp for timestamp TYPE.
16770 Allowed values for TYPE are:
16772 all: all timestamps
16773 active: only active timestamps (<...>)
16774 inactive: only inactive timestamps ([...])
16775 scheduled: only scheduled timestamps
16776 deadline: only deadline timestamps
16777 closed: only closed time-stamps
16779 When TYPE is nil, fall back on returning a regexp that matches
16780 both scheduled and deadline timestamps."
16781 (cl-case type
16782 (all org-ts-regexp-both)
16783 (active org-ts-regexp)
16784 (inactive org-ts-regexp-inactive)
16785 (scheduled org-scheduled-time-regexp)
16786 (deadline org-deadline-time-regexp)
16787 (closed org-closed-time-regexp)
16788 (otherwise
16789 (concat "\\<"
16790 (regexp-opt (list org-deadline-string org-scheduled-string))
16791 " *<\\([^>]+\\)>"))))
16793 (defun org-check-before-date (d)
16794 "Check if there are deadlines or scheduled entries before date D."
16795 (interactive (list (org-read-date)))
16796 (let* ((case-fold-search nil)
16797 (regexp (org-re-timestamp org-ts-type))
16798 (ts-type org-ts-type)
16799 (callback
16800 (lambda ()
16801 (let ((match (match-string 1)))
16802 (and (if (memq ts-type '(active inactive all))
16803 (eq (org-element-type (save-excursion
16804 (backward-char)
16805 (org-element-context)))
16806 'timestamp)
16807 (org-at-planning-p))
16808 (time-less-p
16809 (org-time-string-to-time match)
16810 (org-time-string-to-time d)))))))
16811 (message "%d entries before %s"
16812 (org-occur regexp nil callback)
16813 d)))
16815 (defun org-check-after-date (d)
16816 "Check if there are deadlines or scheduled entries after date D."
16817 (interactive (list (org-read-date)))
16818 (let* ((case-fold-search nil)
16819 (regexp (org-re-timestamp org-ts-type))
16820 (ts-type org-ts-type)
16821 (callback
16822 (lambda ()
16823 (let ((match (match-string 1)))
16824 (and (if (memq ts-type '(active inactive all))
16825 (eq (org-element-type (save-excursion
16826 (backward-char)
16827 (org-element-context)))
16828 'timestamp)
16829 (org-at-planning-p))
16830 (not (time-less-p
16831 (org-time-string-to-time match)
16832 (org-time-string-to-time d))))))))
16833 (message "%d entries after %s"
16834 (org-occur regexp nil callback)
16835 d)))
16837 (defun org-check-dates-range (start-date end-date)
16838 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16839 (interactive (list (org-read-date nil nil nil "Range starts")
16840 (org-read-date nil nil nil "Range end")))
16841 (let ((case-fold-search nil)
16842 (regexp (org-re-timestamp org-ts-type))
16843 (callback
16844 (let ((type org-ts-type))
16845 (lambda ()
16846 (let ((match (match-string 1)))
16847 (and
16848 (if (memq type '(active inactive all))
16849 (eq (org-element-type (save-excursion
16850 (backward-char)
16851 (org-element-context)))
16852 'timestamp)
16853 (org-at-planning-p))
16854 (not (time-less-p
16855 (org-time-string-to-time match)
16856 (org-time-string-to-time start-date)))
16857 (time-less-p
16858 (org-time-string-to-time match)
16859 (org-time-string-to-time end-date))))))))
16860 (message "%d entries between %s and %s"
16861 (org-occur regexp nil callback) start-date end-date)))
16863 (defun org-evaluate-time-range (&optional to-buffer)
16864 "Evaluate a time range by computing the difference between start and end.
16865 Normally the result is just printed in the echo area, but with prefix arg
16866 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16867 If the time range is actually in a table, the result is inserted into the
16868 next column.
16869 For time difference computation, a year is assumed to be exactly 365
16870 days in order to avoid rounding problems."
16871 (interactive "P")
16873 (org-clock-update-time-maybe)
16874 (save-excursion
16875 (unless (org-at-date-range-p t)
16876 (goto-char (point-at-bol))
16877 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16878 (unless (org-at-date-range-p t)
16879 (user-error "Not at a time-stamp range, and none found in current line")))
16880 (let* ((ts1 (match-string 1))
16881 (ts2 (match-string 2))
16882 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16883 (match-end (match-end 0))
16884 (time1 (org-time-string-to-time ts1))
16885 (time2 (org-time-string-to-time ts2))
16886 (t1 (float-time time1))
16887 (t2 (float-time time2))
16888 (diff (abs (- t2 t1)))
16889 (negative (< (- t2 t1) 0))
16890 ;; (ys (floor (* 365 24 60 60)))
16891 (ds (* 24 60 60))
16892 (hs (* 60 60))
16893 (fy "%dy %dd %02d:%02d")
16894 (fy1 "%dy %dd")
16895 (fd "%dd %02d:%02d")
16896 (fd1 "%dd")
16897 (fh "%02d:%02d")
16898 y d h m align)
16899 (if havetime
16900 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16902 d (floor (/ diff ds)) diff (mod diff ds)
16903 h (floor (/ diff hs)) diff (mod diff hs)
16904 m (floor (/ diff 60)))
16905 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16907 d (floor (+ (/ diff ds) 0.5))
16908 h 0 m 0))
16909 (if (not to-buffer)
16910 (message "%s" (org-make-tdiff-string y d h m))
16911 (if (org-at-table-p)
16912 (progn
16913 (goto-char match-end)
16914 (setq align t)
16915 (and (looking-at " *|") (goto-char (match-end 0))))
16916 (goto-char match-end))
16917 (when (looking-at
16918 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16919 (replace-match ""))
16920 (when negative (insert " -"))
16921 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16922 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16923 (insert " " (format fh h m))))
16924 (when align (org-table-align))
16925 (message "Time difference inserted")))))
16927 (defun org-make-tdiff-string (y d h m)
16928 (let ((fmt "")
16929 (l nil))
16930 (when (> y 0)
16931 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16932 (push y l))
16933 (when (> d 0)
16934 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16935 (push d l))
16936 (when (> h 0)
16937 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16938 (push h l))
16939 (when (> m 0)
16940 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16941 (push m l))
16942 (apply 'format fmt (nreverse l))))
16944 (defun org-time-string-to-time (s)
16945 "Convert timestamp string S into internal time."
16946 (apply #'encode-time (org-parse-time-string s)))
16948 (defun org-time-string-to-seconds (s)
16949 "Convert a timestamp string S into a number of seconds."
16950 (float-time (org-time-string-to-time s)))
16952 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16954 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16955 "Convert time stamp S to an absolute day number.
16957 If DAYNR in non-nil, and there is a specifier for a cyclic time
16958 stamp, get the closest date to DAYNR. If PREFER is
16959 `past' (respectively `future') return a date past (respectively
16960 after) or equal to DAYNR.
16962 POS is the location of time stamp S, as a buffer position in
16963 BUFFER.
16965 Diary sexp timestamps are matched against DAYNR, when non-nil.
16966 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16967 signaled."
16968 (cond
16969 ((string-match "\\`%%\\((.*)\\)" s)
16970 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16971 ;; only able to match individual dates. If it fails, raise an
16972 ;; error.
16973 (if (and daynr
16974 (org-diary-sexp-entry
16975 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16976 daynr
16977 (signal 'org-diary-sexp-no-match (list s))))
16978 (daynr (org-closest-date s daynr prefer))
16979 (t (time-to-days
16980 (condition-case errdata
16981 (apply #'encode-time (org-parse-time-string s))
16982 (error (error "Bad timestamp `%s'%s\nError was: %s"
16984 (if (not (and buffer pos)) ""
16985 (format-message " at %d in buffer `%s'" pos buffer))
16986 (cdr errdata))))))))
16988 (defun org-days-to-iso-week (days)
16989 "Return the iso week number."
16990 (require 'cal-iso)
16991 (car (calendar-iso-from-absolute days)))
16993 (defun org-small-year-to-year (year)
16994 "Convert 2-digit years into 4-digit years.
16995 YEAR is expanded into one of the 30 next years, if possible, or
16996 into a past one. Any year larger than 99 is returned unchanged."
16997 (if (>= year 100) year
16998 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
16999 (century (/ current 100))
17000 (offset (- year (% current 100))))
17001 (cond ((> offset 30) (+ (* (1- century) 100) year))
17002 ((> offset -70) (+ (* century 100) year))
17003 (t (+ (* (1+ century) 100) year))))))
17005 (defun org-time-from-absolute (d)
17006 "Return the time corresponding to date D.
17007 D may be an absolute day number, or a calendar-type list (month day year)."
17008 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17009 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17011 (defvar org-agenda-current-date)
17012 (defun org-calendar-holiday ()
17013 "List of holidays, for Diary display in Org mode."
17014 (require 'holidays)
17015 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17016 (and hl (mapconcat #'identity hl "; "))))
17018 (defun org-diary-sexp-entry (sexp entry d)
17019 "Process a SEXP diary ENTRY for date D."
17020 (require 'diary-lib)
17021 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17022 ;; dynamically.
17023 (let* ((sexp `(let ((entry ,entry)
17024 (date ',d))
17025 ,(car (read-from-string sexp))))
17026 (result (if calendar-debug-sexp (eval sexp)
17027 (condition-case nil
17028 (eval sexp)
17029 (error
17030 (beep)
17031 (message "Bad sexp at line %d in %s: %s"
17032 (org-current-line)
17033 (buffer-file-name) sexp)
17034 (sleep-for 2))))))
17035 (cond ((stringp result) (split-string result "; "))
17036 ((and (consp result)
17037 (not (consp (cdr result)))
17038 (stringp (cdr result))) (cdr result))
17039 ((and (consp result)
17040 (stringp (car result))) result)
17041 (result entry))))
17043 (defun org-diary-to-ical-string (frombuf)
17044 "Get iCalendar entries from diary entries in buffer FROMBUF.
17045 This uses the icalendar.el library."
17046 (let* ((tmpdir temporary-file-directory)
17047 (tmpfile (make-temp-name
17048 (expand-file-name "orgics" tmpdir)))
17049 buf rtn b e)
17050 (with-current-buffer frombuf
17051 (icalendar-export-region (point-min) (point-max) tmpfile)
17052 (setq buf (find-buffer-visiting tmpfile))
17053 (set-buffer buf)
17054 (goto-char (point-min))
17055 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17056 (setq b (match-beginning 0)))
17057 (goto-char (point-max))
17058 (when (re-search-backward "^END:VEVENT" nil t)
17059 (setq e (match-end 0)))
17060 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17061 (kill-buffer buf)
17062 (delete-file tmpfile)
17063 rtn))
17065 (defun org-closest-date (start current prefer)
17066 "Return closest date to CURRENT starting from START.
17068 CURRENT and START are both time stamps.
17070 When PREFER is `past', return a date that is either CURRENT or
17071 past. When PREFER is `future', return a date that is either
17072 CURRENT or future.
17074 Only time stamps with a repeater are modified. Any other time
17075 stamp stay unchanged. In any case, return value is an absolute
17076 day number."
17077 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17078 ;; No repeater. Do not shift time stamp.
17079 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17080 (let ((value (string-to-number (match-string 1 start)))
17081 (type (match-string 2 start)))
17082 (if (= 0 value)
17083 ;; Repeater with a 0-value is considered as void.
17084 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17085 (let* ((base (org-date-to-gregorian start))
17086 (target (org-date-to-gregorian current))
17087 (sday (calendar-absolute-from-gregorian base))
17088 (cday (calendar-absolute-from-gregorian target))
17089 n1 n2)
17090 ;; If START is already past CURRENT, just return START.
17091 (if (<= cday sday) sday
17092 ;; Compute closest date before (N1) and closest date past
17093 ;; (N2) CURRENT.
17094 (pcase type
17095 ("h"
17096 (let ((missing-hours
17097 (mod (+ (- (* 24 (- cday sday))
17098 (nth 2 (org-parse-time-string start)))
17099 org-extend-today-until)
17100 value)))
17101 (setf n1 (if (= missing-hours 0) cday
17102 (- cday (1+ (/ missing-hours 24)))))
17103 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17104 ((or "d" "w")
17105 (let ((value (if (equal type "w") (* 7 value) value)))
17106 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17107 (setf n2 (+ n1 value))))
17108 ("m"
17109 (let* ((add-months
17110 (lambda (d n)
17111 ;; Add N months to gregorian date D, i.e.,
17112 ;; a list (MONTH DAY YEAR). Return a valid
17113 ;; gregorian date.
17114 (let ((m (+ (nth 0 d) n)))
17115 (list (mod m 12)
17116 (nth 1 d)
17117 (+ (/ m 12) (nth 2 d))))))
17118 (months ; Complete months to TARGET.
17119 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17120 (- (nth 0 target) (nth 0 base))
17121 ;; If START's day is greater than
17122 ;; TARGET's, remove incomplete month.
17123 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17124 value)
17125 value))
17126 (before (funcall add-months base months)))
17127 (setf n1 (calendar-absolute-from-gregorian before))
17128 (setf n2
17129 (calendar-absolute-from-gregorian
17130 (funcall add-months before value)))))
17132 (let* ((d (nth 1 base))
17133 (m (nth 0 base))
17134 (y (nth 2 base))
17135 (years ; Complete years to TARGET.
17136 (* (/ (- (nth 2 target)
17138 ;; If START's month and day are
17139 ;; greater than TARGET's, remove
17140 ;; incomplete year.
17141 (if (or (> (nth 0 target) m)
17142 (and (= (nth 0 target) m)
17143 (> (nth 1 target) d)))
17146 value)
17147 value))
17148 (before (list m d (+ y years))))
17149 (setf n1 (calendar-absolute-from-gregorian before))
17150 (setf n2 (calendar-absolute-from-gregorian
17151 (list m d (+ (nth 2 before) value)))))))
17152 ;; Handle PREFER parameter, if any.
17153 (cond
17154 ((eq prefer 'past) (if (= cday n2) n2 n1))
17155 ((eq prefer 'future) (if (= cday n1) n1 n2))
17156 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17158 (defun org-date-to-gregorian (d)
17159 "Turn any specification of date D into a Gregorian date for the calendar."
17160 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17161 ((and (listp d) (= (length d) 3)) d)
17162 ((stringp d)
17163 (let ((d (org-parse-time-string d)))
17164 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17165 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17167 (defun org-parse-time-string (s &optional nodefault)
17168 "Parse the standard Org time string.
17170 This should be a lot faster than the normal `parse-time-string'.
17172 If time is not given, defaults to 0:00. However, with optional
17173 NODEFAULT, hour and minute fields will be nil if not given."
17174 (cond ((string-match org-ts-regexp0 s)
17175 (list 0
17176 (when (or (match-beginning 8) (not nodefault))
17177 (string-to-number (or (match-string 8 s) "0")))
17178 (when (or (match-beginning 7) (not nodefault))
17179 (string-to-number (or (match-string 7 s) "0")))
17180 (string-to-number (match-string 4 s))
17181 (string-to-number (match-string 3 s))
17182 (string-to-number (match-string 2 s))
17183 nil nil nil))
17184 ((string-match "^<[^>]+>$" s)
17185 ;; FIXME: `decode-time' needs to be called with ZONE as its
17186 ;; second argument. However, this requires at least Emacs
17187 ;; 25.1. We can do it when we switch to this version as our
17188 ;; minimal requirement.
17189 (decode-time (seconds-to-time (org-matcher-time s))))
17190 (t (error "Not a standard Org time string: %s" s))))
17192 (defun org-timestamp-up (&optional arg)
17193 "Increase the date item at the cursor by one.
17194 If the cursor is on the year, change the year. If it is on the month,
17195 the day or the time, change that.
17196 With prefix ARG, change by that many units."
17197 (interactive "p")
17198 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17200 (defun org-timestamp-down (&optional arg)
17201 "Decrease the date item at the cursor by one.
17202 If the cursor is on the year, change the year. If it is on the month,
17203 the day or the time, change that.
17204 With prefix ARG, change by that many units."
17205 (interactive "p")
17206 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17208 (defun org-timestamp-up-day (&optional arg)
17209 "Increase the date in the time stamp by one day.
17210 With prefix ARG, change that many days."
17211 (interactive "p")
17212 (if (and (not (org-at-timestamp-p 'lax))
17213 (org-at-heading-p))
17214 (org-todo 'up)
17215 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17217 (defun org-timestamp-down-day (&optional arg)
17218 "Decrease the date in the time stamp by one day.
17219 With prefix ARG, change that many days."
17220 (interactive "p")
17221 (if (and (not (org-at-timestamp-p 'lax))
17222 (org-at-heading-p))
17223 (org-todo 'down)
17224 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17226 (defun org-at-timestamp-p (&optional extended)
17227 "Non-nil if point is inside a timestamp.
17229 By default, the function only consider syntactically valid active
17230 timestamps. However, the caller may have a broader definition
17231 for timestamps. As a consequence, optional argument EXTENDED can
17232 be set to the following values
17234 `inactive'
17236 Include also syntactically valid inactive timestamps.
17238 `agenda'
17240 Include timestamps allowed in Agenda, i.e., those in
17241 properties drawers, planning lines and clock lines.
17243 `lax'
17245 Ignore context. The function matches any part of the
17246 document looking like a timestamp. This includes comments,
17247 example blocks...
17249 For backward-compatibility with Org 9.0, every other non-nil
17250 value is equivalent to `inactive'.
17252 When at a timestamp, return the position of the point as a symbol
17253 among `bracket', `after', `year', `month', `hour', `minute',
17254 `day' or a number of character from the last know part of the
17255 time stamp.
17257 When matching, the match groups are the following:
17258 group 1: year
17259 group 2: month
17260 group 3: day number
17261 group 4: day name
17262 group 5: hours, if any
17263 group 6: minutes, if any"
17264 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17265 (pos (point))
17266 (match?
17267 (let ((boundaries (org-in-regexp regexp)))
17268 (save-match-data
17269 (cond ((null boundaries) nil)
17270 ((eq extended 'lax) t)
17272 (or (and (eq extended 'agenda)
17273 (or (org-at-planning-p)
17274 (org-at-property-p)
17275 (and (bound-and-true-p
17276 org-agenda-include-inactive-timestamps)
17277 (org-at-clock-log-p))))
17278 (eq 'timestamp
17279 (save-excursion
17280 (when (= pos (cdr boundaries)) (forward-char -1))
17281 (org-element-type (org-element-context)))))))))))
17282 (cond
17283 ((not match?) nil)
17284 ((= pos (match-beginning 0)) 'bracket)
17285 ;; Distinguish location right before the closing bracket from
17286 ;; right after it.
17287 ((= pos (1- (match-end 0))) 'bracket)
17288 ((= pos (match-end 0)) 'after)
17289 ((org-pos-in-match-range pos 2) 'year)
17290 ((org-pos-in-match-range pos 3) 'month)
17291 ((org-pos-in-match-range pos 7) 'hour)
17292 ((org-pos-in-match-range pos 8) 'minute)
17293 ((or (org-pos-in-match-range pos 4)
17294 (org-pos-in-match-range pos 5)) 'day)
17295 ((and (> pos (or (match-end 8) (match-end 5)))
17296 (< pos (match-end 0)))
17297 (- pos (or (match-end 8) (match-end 5))))
17298 (t 'day))))
17300 (defun org-toggle-timestamp-type ()
17301 "Toggle the type (<active> or [inactive]) of a time stamp."
17302 (interactive)
17303 (when (org-at-timestamp-p 'lax)
17304 (let ((beg (match-beginning 0)) (end (match-end 0))
17305 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17306 (save-excursion
17307 (goto-char beg)
17308 (while (re-search-forward "[][<>]" end t)
17309 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17310 t t)))
17311 (message "Timestamp is now %sactive"
17312 (if (equal (char-after beg) ?<) "" "in")))))
17314 (defun org-at-clock-log-p ()
17315 "Non-nil if point is on a clock log line."
17316 (and (org-match-line org-clock-line-re)
17317 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17319 (defvar org-clock-history) ; defined in org-clock.el
17320 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17321 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17322 "Change the date in the time stamp at point.
17323 The date will be changed by N times WHAT. WHAT can be `day', `month',
17324 `year', `minute', `second'. If WHAT is not given, the cursor position
17325 in the timestamp determines what will be changed.
17326 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17327 (let ((origin (point))
17328 (timestamp? (org-at-timestamp-p 'lax))
17329 origin-cat
17330 with-hm inactive
17331 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17332 extra rem
17333 ts time time0 fixnext clrgx)
17334 (unless timestamp? (user-error "Not at a timestamp"))
17335 (if (and (not what) (eq timestamp? 'bracket))
17336 (org-toggle-timestamp-type)
17337 ;; Point isn't on brackets. Remember the part of the time-stamp
17338 ;; the point was in. Indeed, size of time-stamps may change,
17339 ;; but point must be kept in the same category nonetheless.
17340 (setq origin-cat timestamp?)
17341 (when (and (not what) (not (eq timestamp? 'day))
17342 org-display-custom-times
17343 (get-text-property (point) 'display)
17344 (not (get-text-property (1- (point)) 'display)))
17345 (setq timestamp? 'day))
17346 (setq timestamp? (or what timestamp?)
17347 inactive (= (char-after (match-beginning 0)) ?\[)
17348 ts (match-string 0))
17349 (replace-match "")
17350 (when (string-match
17351 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17353 (setq extra (match-string 1 ts))
17354 (when suppress-tmp-delay
17355 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17356 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17357 (setq with-hm t))
17358 (setq time0 (org-parse-time-string ts))
17359 (when (and updown
17360 (eq timestamp? 'minute)
17361 (not current-prefix-arg))
17362 ;; This looks like s-up and s-down. Change by one rounding step.
17363 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17364 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17365 (setcar (cdr time0) (+ (nth 1 time0)
17366 (if (> n 0) (- rem) (- dm rem))))))
17367 (setq time
17368 (apply #'encode-time
17369 (or (car time0) 0)
17370 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17371 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17372 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17373 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17374 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17375 (nthcdr 6 time0)))
17376 (when (and (memq timestamp? '(hour minute))
17377 extra
17378 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17379 (setq extra (org-modify-ts-extra
17380 extra
17381 (if (eq timestamp? 'hour) 2 5)
17382 n dm)))
17383 (when (integerp timestamp?)
17384 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17385 (when (eq what 'calendar)
17386 (let ((cal-date (org-get-date-from-calendar)))
17387 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17388 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17389 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17390 (setcar time0 (or (car time0) 0))
17391 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17392 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17393 (setq time (apply 'encode-time time0))))
17394 ;; Insert the new time-stamp, and ensure point stays in the same
17395 ;; category as before (i.e. not after the last position in that
17396 ;; category).
17397 (let ((pos (point)))
17398 ;; Stay before inserted string. `save-excursion' is of no use.
17399 (setq org-last-changed-timestamp
17400 (org-insert-time-stamp time with-hm inactive nil nil extra))
17401 (goto-char pos))
17402 (save-match-data
17403 (looking-at org-ts-regexp3)
17404 (goto-char
17405 (pcase origin-cat
17406 ;; `day' category ends before `hour' if any, or at the end
17407 ;; of the day name.
17408 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17409 (`hour (min (match-end 7) origin))
17410 (`minute (min (1- (match-end 8)) origin))
17411 ((pred integerp) (min (1- (match-end 0)) origin))
17412 ;; Point was right after the time-stamp. However, the
17413 ;; time-stamp length might have changed, so refer to
17414 ;; (match-end 0) instead.
17415 (`after (match-end 0))
17416 ;; `year' and `month' have both fixed size: point couldn't
17417 ;; have moved into another part.
17418 (_ origin))))
17419 ;; Update clock if on a CLOCK line.
17420 (org-clock-update-time-maybe)
17421 ;; Maybe adjust the closest clock in `org-clock-history'
17422 (when org-clock-adjust-closest
17423 (if (not (and (org-at-clock-log-p)
17424 (< 1 (length (delq nil (mapcar 'marker-position
17425 org-clock-history))))))
17426 (message "No clock to adjust")
17427 (cond ((save-excursion ; fix previous clock?
17428 (re-search-backward org-ts-regexp0 nil t)
17429 (looking-back (concat org-clock-string " \\[")
17430 (line-beginning-position)))
17431 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17432 ((save-excursion ; fix next clock?
17433 (re-search-backward org-ts-regexp0 nil t)
17434 (looking-at (concat org-ts-regexp0 "\\] =>")))
17435 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17436 (save-window-excursion
17437 ;; Find closest clock to point, adjust the previous/next one in history
17438 (let* ((p (save-excursion (org-back-to-heading t)))
17439 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17440 (clfixnth
17441 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17442 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17443 (if (not clfixpos)
17444 (message "No clock to adjust")
17445 (save-excursion
17446 (org-goto-marker-or-bmk clfixpos)
17447 (org-show-subtree)
17448 (when (re-search-forward clrgx nil t)
17449 (goto-char (match-beginning 1))
17450 (let (org-clock-adjust-closest)
17451 (org-timestamp-change n timestamp? updown))
17452 (message "Clock adjusted in %s for heading: %s"
17453 (file-name-nondirectory (buffer-file-name))
17454 (org-get-heading t t)))))))))
17455 ;; Try to recenter the calendar window, if any.
17456 (when (and org-calendar-follow-timestamp-change
17457 (get-buffer-window "*Calendar*" t)
17458 (memq timestamp? '(day month year)))
17459 (org-recenter-calendar (time-to-days time))))))
17461 (defun org-modify-ts-extra (s pos n dm)
17462 "Change the different parts of the lead-time and repeat fields in timestamp."
17463 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17464 ng h m new rem)
17465 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17466 (cond
17467 ((or (org-pos-in-match-range pos 2)
17468 (org-pos-in-match-range pos 3))
17469 (setq m (string-to-number (match-string 3 s))
17470 h (string-to-number (match-string 2 s)))
17471 (if (org-pos-in-match-range pos 2)
17472 (setq h (+ h n))
17473 (setq n (* dm (with-no-warnings (signum n))))
17474 (unless (= 0 (setq rem (% m dm)))
17475 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17476 (setq m (+ m n)))
17477 (when (< m 0) (setq m (+ m 60) h (1- h)))
17478 (when (> m 59) (setq m (- m 60) h (1+ h)))
17479 (setq h (mod h 24))
17480 (setq ng 1 new (format "-%02d:%02d" h m)))
17481 ((org-pos-in-match-range pos 6)
17482 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17483 ((org-pos-in-match-range pos 5)
17484 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17486 ((org-pos-in-match-range pos 9)
17487 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17488 ((org-pos-in-match-range pos 8)
17489 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17491 (when ng
17492 (setq s (concat
17493 (substring s 0 (match-beginning ng))
17495 (substring s (match-end ng))))))
17498 (defun org-recenter-calendar (d)
17499 "If the calendar is visible, recenter it to date D."
17500 (let ((cwin (get-buffer-window "*Calendar*" t)))
17501 (when cwin
17502 (let ((calendar-move-hook nil))
17503 (with-selected-window cwin
17504 (calendar-goto-date
17505 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17507 (defun org-goto-calendar (&optional arg)
17508 "Go to the Emacs calendar at the current date.
17509 If there is a time stamp in the current line, go to that date.
17510 A prefix ARG can be used to force the current date."
17511 (interactive "P")
17512 (let ((calendar-move-hook nil)
17513 (calendar-view-holidays-initially-flag nil)
17514 (calendar-view-diary-initially-flag nil)
17515 diff)
17516 (when (or (org-at-timestamp-p 'lax)
17517 (org-match-line (concat ".*" org-ts-regexp)))
17518 (let ((d1 (time-to-days (current-time)))
17519 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17520 (setq diff (- d2 d1))))
17521 (calendar)
17522 (calendar-goto-today)
17523 (when (and diff (not arg)) (calendar-forward-day diff))))
17525 (defun org-get-date-from-calendar ()
17526 "Return a list (month day year) of date at point in calendar."
17527 (with-current-buffer "*Calendar*"
17528 (save-match-data
17529 (calendar-cursor-to-date))))
17531 (defun org-date-from-calendar ()
17532 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17533 If there is already a time stamp at the cursor position, update it."
17534 (interactive)
17535 (if (org-at-timestamp-p 'lax)
17536 (org-timestamp-change 0 'calendar)
17537 (let ((cal-date (org-get-date-from-calendar)))
17538 (org-insert-time-stamp
17539 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17541 (defcustom org-effort-durations
17542 `(("min" . 1)
17543 ("h" . 60)
17544 ("d" . ,(* 60 8))
17545 ("w" . ,(* 60 8 5))
17546 ("m" . ,(* 60 8 5 4))
17547 ("y" . ,(* 60 8 5 40)))
17548 "Conversion factor to minutes for an effort modifier.
17550 Each entry has the form (MODIFIER . MINUTES).
17552 In an effort string, a number followed by MODIFIER is multiplied
17553 by the specified number of MINUTES to obtain an effort in
17554 minutes.
17556 For example, if the value of this variable is ((\"hours\" . 60)), then an
17557 effort string \"2hours\" is equivalent to 120 minutes."
17558 :group 'org-agenda
17559 :version "26.1"
17560 :package-version '(Org . "8.3")
17561 :type '(alist :key-type (string :tag "Modifier")
17562 :value-type (number :tag "Minutes")))
17564 (defcustom org-image-actual-width t
17565 "Should we use the actual width of images when inlining them?
17567 When set to t, always use the image width.
17569 When set to a number, use imagemagick (when available) to set
17570 the image's width to this value.
17572 When set to a number in a list, try to get the width from any
17573 #+ATTR.* keyword if it matches a width specification like
17575 #+ATTR_HTML: :width 300px
17577 and fall back on that number if none is found.
17579 When set to nil, try to get the width from an #+ATTR.* keyword
17580 and fall back on the original width if none is found.
17582 This requires Emacs >= 24.1, build with imagemagick support."
17583 :group 'org-appearance
17584 :version "24.4"
17585 :package-version '(Org . "8.0")
17586 :type '(choice
17587 (const :tag "Use the image width" t)
17588 (integer :tag "Use a number of pixels")
17589 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17590 (const :tag "Use #+ATTR* or don't resize" nil)))
17592 (defcustom org-agenda-inhibit-startup nil
17593 "Inhibit startup when preparing agenda buffers.
17594 When this variable is t, the initialization of the Org agenda
17595 buffers is inhibited: e.g. the visibility state is not set, the
17596 tables are not re-aligned, etc."
17597 :type 'boolean
17598 :version "24.3"
17599 :group 'org-agenda)
17601 (defcustom org-agenda-ignore-properties nil
17602 "Avoid updating text properties when building the agenda.
17603 Properties are used to prepare buffers for effort estimates,
17604 appointments, statistics and subtree-local categories.
17605 If you don't use these in the agenda, you can add them to this
17606 list and agenda building will be a bit faster.
17607 The value is a list, with zero or more of the symbols `effort', `appt',
17608 `stats' or `category'."
17609 :type '(set :greedy t
17610 (const effort)
17611 (const appt)
17612 (const stats)
17613 (const category))
17614 :version "26.1"
17615 :package-version '(Org . "8.3")
17616 :group 'org-agenda)
17618 ;;;; Files
17620 (defun org-save-all-org-buffers ()
17621 "Save all Org buffers without user confirmation."
17622 (interactive)
17623 (message "Saving all Org buffers...")
17624 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17625 (when (featurep 'org-id) (org-id-locations-save))
17626 (message "Saving all Org buffers... done"))
17628 (defun org-revert-all-org-buffers ()
17629 "Revert all Org buffers.
17630 Prompt for confirmation when there are unsaved changes.
17631 Be sure you know what you are doing before letting this function
17632 overwrite your changes.
17634 This function is useful in a setup where one tracks org files
17635 with a version control system, to revert on one machine after pulling
17636 changes from another. I believe the procedure must be like this:
17638 1. M-x org-save-all-org-buffers
17639 2. Pull changes from the other machine, resolve conflicts
17640 3. M-x org-revert-all-org-buffers"
17641 (interactive)
17642 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17643 (user-error "Abort"))
17644 (save-excursion
17645 (save-window-excursion
17646 (dolist (b (buffer-list))
17647 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17648 (with-current-buffer b buffer-file-name))
17649 (pop-to-buffer-same-window b)
17650 (revert-buffer t 'no-confirm)))
17651 (when (and (featurep 'org-id) org-id-track-globally)
17652 (org-id-locations-load)))))
17654 ;;;; Agenda files
17656 ;;;###autoload
17657 (defun org-switchb (&optional arg)
17658 "Switch between Org buffers.
17660 With `\\[universal-argument]' prefix, restrict available buffers to files.
17662 With `\\[universal-argument] \\[universal-argument]' \
17663 prefix, restrict available buffers to agenda files."
17664 (interactive "P")
17665 (let ((blist (org-buffer-list
17666 (cond ((equal arg '(4)) 'files)
17667 ((equal arg '(16)) 'agenda)))))
17668 (pop-to-buffer-same-window
17669 (completing-read "Org buffer: "
17670 (mapcar #'list (mapcar #'buffer-name blist))
17671 nil t))))
17673 (defun org-buffer-list (&optional predicate exclude-tmp)
17674 "Return a list of Org buffers.
17675 PREDICATE can be `export', `files' or `agenda'.
17677 export restrict the list to Export buffers.
17678 files restrict the list to buffers visiting Org files.
17679 agenda restrict the list to buffers visiting agenda files.
17681 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17682 (let* ((bfn nil)
17683 (agenda-files (and (eq predicate 'agenda)
17684 (mapcar 'file-truename (org-agenda-files t))))
17685 (filter
17686 (cond
17687 ((eq predicate 'files)
17688 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17689 ((eq predicate 'export)
17690 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17691 ((eq predicate 'agenda)
17692 (lambda (b)
17693 (with-current-buffer b
17694 (and (derived-mode-p 'org-mode)
17695 (setq bfn (buffer-file-name b))
17696 (member (file-truename bfn) agenda-files)))))
17697 (t (lambda (b) (with-current-buffer b
17698 (or (derived-mode-p 'org-mode)
17699 (string-match "\\*Org .*Export"
17700 (buffer-name b)))))))))
17701 (delq nil
17702 (mapcar
17703 (lambda(b)
17704 (if (and (funcall filter b)
17705 (or (not exclude-tmp)
17706 (not (string-match "tmp" (buffer-name b)))))
17708 nil))
17709 (buffer-list)))))
17711 (defun org-agenda-files (&optional unrestricted archives)
17712 "Get the list of agenda files.
17713 Optional UNRESTRICTED means return the full list even if a restriction
17714 is currently in place.
17715 When ARCHIVES is t, include all archive files that are really being
17716 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17717 `org-agenda-archives-mode' is t."
17718 (let ((files
17719 (cond
17720 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17721 ((stringp org-agenda-files) (org-read-agenda-file-list))
17722 ((listp org-agenda-files) org-agenda-files)
17723 (t (error "Invalid value of `org-agenda-files'")))))
17724 (setq files (apply 'append
17725 (mapcar (lambda (f)
17726 (if (file-directory-p f)
17727 (directory-files
17728 f t org-agenda-file-regexp)
17729 (list f)))
17730 files)))
17731 (when org-agenda-skip-unavailable-files
17732 (setq files (delq nil
17733 (mapcar (function
17734 (lambda (file)
17735 (and (file-readable-p file) file)))
17736 files))))
17737 (when (or (eq archives t)
17738 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17739 (setq files (org-add-archive-files files)))
17740 files))
17742 (defun org-agenda-file-p (&optional file)
17743 "Return non-nil, if FILE is an agenda file.
17744 If FILE is omitted, use the file associated with the current
17745 buffer."
17746 (let ((fname (or file (buffer-file-name))))
17747 (and fname
17748 (member (file-truename fname)
17749 (mapcar #'file-truename (org-agenda-files t))))))
17751 (defun org-edit-agenda-file-list ()
17752 "Edit the list of agenda files.
17753 Depending on setup, this either uses customize to edit the variable
17754 `org-agenda-files', or it visits the file that is holding the list. In the
17755 latter case, the buffer is set up in a way that saving it automatically kills
17756 the buffer and restores the previous window configuration."
17757 (interactive)
17758 (if (stringp org-agenda-files)
17759 (let ((cw (current-window-configuration)))
17760 (find-file org-agenda-files)
17761 (setq-local org-window-configuration cw)
17762 (add-hook 'after-save-hook
17763 (lambda ()
17764 (set-window-configuration
17765 (prog1 org-window-configuration
17766 (kill-buffer (current-buffer))))
17767 (org-install-agenda-files-menu)
17768 (message "New agenda file list installed"))
17769 nil 'local)
17770 (message "%s" (substitute-command-keys
17771 "Edit list and finish with \\[save-buffer]")))
17772 (customize-variable 'org-agenda-files)))
17774 (defun org-store-new-agenda-file-list (list)
17775 "Set new value for the agenda file list and save it correctly."
17776 (if (stringp org-agenda-files)
17777 (let ((fe (org-read-agenda-file-list t)) b u)
17778 (while (setq b (find-buffer-visiting org-agenda-files))
17779 (kill-buffer b))
17780 (with-temp-file org-agenda-files
17781 (insert
17782 (mapconcat
17783 (lambda (f) ;; Keep un-expanded entries.
17784 (if (setq u (assoc f fe))
17785 (cdr u)
17787 list "\n")
17788 "\n")))
17789 (let ((org-mode-hook nil) (org-inhibit-startup t)
17790 (org-insert-mode-line-in-empty-file nil))
17791 (setq org-agenda-files list)
17792 (customize-save-variable 'org-agenda-files org-agenda-files))))
17794 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17795 "Read the list of agenda files from a file.
17796 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17797 filenames, used by `org-store-new-agenda-file-list' to write back
17798 un-expanded file names."
17799 (when (file-directory-p org-agenda-files)
17800 (error "`org-agenda-files' cannot be a single directory"))
17801 (when (stringp org-agenda-files)
17802 (with-temp-buffer
17803 (insert-file-contents org-agenda-files)
17804 (mapcar
17805 (lambda (f)
17806 (let ((e (expand-file-name (substitute-in-file-name f)
17807 org-directory)))
17808 (if pair-with-expansion
17809 (cons e f)
17810 e)))
17811 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17813 ;;;###autoload
17814 (defun org-cycle-agenda-files ()
17815 "Cycle through the files in `org-agenda-files'.
17816 If the current buffer visits an agenda file, find the next one in the list.
17817 If the current buffer does not, find the first agenda file."
17818 (interactive)
17819 (let* ((fs (or (org-agenda-files t)
17820 (user-error "No agenda files")))
17821 (files (copy-sequence fs))
17822 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17823 file)
17824 (when tcf
17825 (while (and (setq file (pop files))
17826 (not (equal (file-truename file) tcf)))))
17827 (find-file (car (or files fs)))
17828 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17830 (defun org-agenda-file-to-front (&optional to-end)
17831 "Move/add the current file to the top of the agenda file list.
17832 If the file is not present in the list, it is added to the front. If it is
17833 present, it is moved there. With optional argument TO-END, add/move to the
17834 end of the list."
17835 (interactive "P")
17836 (let ((org-agenda-skip-unavailable-files nil)
17837 (file-alist (mapcar (lambda (x)
17838 (cons (file-truename x) x))
17839 (org-agenda-files t)))
17840 (ctf (file-truename
17841 (or buffer-file-name
17842 (user-error "Please save the current buffer to a file"))))
17843 x had)
17844 (setq x (assoc ctf file-alist) had x)
17846 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17847 (if to-end
17848 (setq file-alist (append (delq x file-alist) (list x)))
17849 (setq file-alist (cons x (delq x file-alist))))
17850 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17851 (org-install-agenda-files-menu)
17852 (message "File %s to %s of agenda file list"
17853 (if had "moved" "added") (if to-end "end" "front"))))
17855 (defun org-remove-file (&optional file)
17856 "Remove current file from the list of files in variable `org-agenda-files'.
17857 These are the files which are being checked for agenda entries.
17858 Optional argument FILE means use this file instead of the current."
17859 (interactive)
17860 (let* ((org-agenda-skip-unavailable-files nil)
17861 (file (or file buffer-file-name
17862 (user-error "Current buffer does not visit a file")))
17863 (true-file (file-truename file))
17864 (afile (abbreviate-file-name file))
17865 (files (delq nil (mapcar
17866 (lambda (x)
17867 (unless (equal true-file
17868 (file-truename x))
17870 (org-agenda-files t)))))
17871 (if (not (= (length files) (length (org-agenda-files t))))
17872 (progn
17873 (org-store-new-agenda-file-list files)
17874 (org-install-agenda-files-menu)
17875 (message "Removed from Org Agenda list: %s" afile))
17876 (message "File was not in list: %s (not removed)" afile))))
17878 (defun org-file-menu-entry (file)
17879 (vector file (list 'find-file file) t))
17881 (defun org-check-agenda-file (file)
17882 "Make sure FILE exists. If not, ask user what to do."
17883 (unless (file-exists-p file)
17884 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17885 (abbreviate-file-name file))
17886 (let ((r (downcase (read-char-exclusive))))
17887 (cond
17888 ((equal r ?r)
17889 (org-remove-file file)
17890 (throw 'nextfile t))
17891 (t (user-error "Abort"))))))
17893 (defun org-get-agenda-file-buffer (file)
17894 "Get an agenda buffer visiting FILE.
17895 If the buffer needs to be created, add it to the list of buffers
17896 which might be released later."
17897 (let ((buf (org-find-base-buffer-visiting file)))
17898 (if buf
17899 buf ; just return it
17900 ;; Make a new buffer and remember it
17901 (setq buf (find-file-noselect file))
17902 (when buf (push buf org-agenda-new-buffers))
17903 buf)))
17905 (defun org-release-buffers (blist)
17906 "Release all buffers in list, asking the user for confirmation when needed.
17907 When a buffer is unmodified, it is just killed. When modified, it is saved
17908 \(if the user agrees) and then killed."
17909 (let (file)
17910 (dolist (buf blist)
17911 (setq file (buffer-file-name buf))
17912 (when (and (buffer-modified-p buf)
17913 file
17914 (y-or-n-p (format "Save file %s? " file)))
17915 (with-current-buffer buf (save-buffer)))
17916 (kill-buffer buf))))
17918 (defun org-agenda-prepare-buffers (files)
17919 "Create buffers for all agenda files, protect archived trees and comments."
17920 (interactive)
17921 (let ((pa '(:org-archived t))
17922 (pc '(:org-comment t))
17923 (pall '(:org-archived t :org-comment t))
17924 (inhibit-read-only t)
17925 (org-inhibit-startup org-agenda-inhibit-startup)
17926 (rea (concat ":" org-archive-tag ":"))
17927 re pos)
17928 (setq org-tag-alist-for-agenda nil
17929 org-tag-groups-alist-for-agenda nil)
17930 (save-excursion
17931 (save-restriction
17932 (dolist (file files)
17933 (catch 'nextfile
17934 (if (bufferp file)
17935 (set-buffer file)
17936 (org-check-agenda-file file)
17937 (set-buffer (org-get-agenda-file-buffer file)))
17938 (widen)
17939 (org-set-regexps-and-options 'tags-only)
17940 (setq pos (point))
17941 (or (memq 'category org-agenda-ignore-properties)
17942 (org-refresh-category-properties))
17943 (or (memq 'stats org-agenda-ignore-properties)
17944 (org-refresh-stats-properties))
17945 (or (memq 'effort org-agenda-ignore-properties)
17946 (org-refresh-effort-properties))
17947 (or (memq 'appt org-agenda-ignore-properties)
17948 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17949 (setq org-todo-keywords-for-agenda
17950 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17951 (setq org-done-keywords-for-agenda
17952 (append org-done-keywords-for-agenda org-done-keywords))
17953 (setq org-todo-keyword-alist-for-agenda
17954 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17955 (setq org-tag-alist-for-agenda
17956 (org-uniquify
17957 (append org-tag-alist-for-agenda
17958 org-current-tag-alist)))
17959 ;; Merge current file's tag groups into global
17960 ;; `org-tag-groups-alist-for-agenda'.
17961 (when org-group-tags
17962 (dolist (alist org-tag-groups-alist)
17963 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17964 (if old
17965 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17966 (push alist org-tag-groups-alist-for-agenda)))))
17967 (org-with-silent-modifications
17968 (save-excursion
17969 (remove-text-properties (point-min) (point-max) pall)
17970 (when org-agenda-skip-archived-trees
17971 (goto-char (point-min))
17972 (while (re-search-forward rea nil t)
17973 (when (org-at-heading-p t)
17974 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17975 (goto-char (point-min))
17976 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17977 (while (re-search-forward re nil t)
17978 (when (save-match-data (org-in-commented-heading-p t))
17979 (add-text-properties
17980 (match-beginning 0) (org-end-of-subtree t) pc)))))
17981 (goto-char pos)))))
17982 (setq org-todo-keywords-for-agenda
17983 (org-uniquify org-todo-keywords-for-agenda))
17984 (setq org-todo-keyword-alist-for-agenda
17985 (org-uniquify org-todo-keyword-alist-for-agenda))))
17988 ;;;; CDLaTeX minor mode
17990 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17991 "Keymap for the minor `org-cdlatex-mode'.")
17993 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17994 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17995 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17996 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17997 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
17999 (defvar org-cdlatex-texmathp-advice-is-done nil
18000 "Flag remembering if we have applied the advice to texmathp already.")
18002 (define-minor-mode org-cdlatex-mode
18003 "Toggle the minor `org-cdlatex-mode'.
18004 This mode supports entering LaTeX environment and math in LaTeX fragments
18005 in Org mode.
18006 \\{org-cdlatex-mode-map}"
18007 nil " OCDL" nil
18008 (when org-cdlatex-mode
18009 (require 'cdlatex)
18010 (run-hooks 'cdlatex-mode-hook)
18011 (cdlatex-compute-tables))
18012 (unless org-cdlatex-texmathp-advice-is-done
18013 (setq org-cdlatex-texmathp-advice-is-done t)
18014 (defadvice texmathp (around org-math-always-on activate)
18015 "Always return t in Org buffers.
18016 This is because we want to insert math symbols without dollars even outside
18017 the LaTeX math segments. If Org mode thinks that point is actually inside
18018 an embedded LaTeX fragment, let `texmathp' do its job.
18019 `\\[org-cdlatex-mode-map]'"
18020 (interactive)
18021 (let (p)
18022 (cond
18023 ((not (derived-mode-p 'org-mode)) ad-do-it)
18024 ((eq this-command 'cdlatex-math-symbol)
18025 (setq ad-return-value t
18026 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18028 (let ((p (org-inside-LaTeX-fragment-p)))
18029 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18030 (setq ad-return-value t
18031 texmathp-why '("Org mode embedded math" . 0))
18032 (when p ad-do-it)))))))))
18034 (defun turn-on-org-cdlatex ()
18035 "Unconditionally turn on `org-cdlatex-mode'."
18036 (org-cdlatex-mode 1))
18038 (defun org-try-cdlatex-tab ()
18039 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18040 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18041 - inside a LaTeX fragment, or
18042 - after the first word in a line, where an abbreviation expansion could
18043 insert a LaTeX environment."
18044 (when org-cdlatex-mode
18045 (cond
18046 ;; Before any word on the line: No expansion possible.
18047 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18048 ;; Just after first word on the line: Expand it. Make sure it
18049 ;; cannot happen on headlines, though.
18050 ((save-excursion
18051 (skip-chars-backward "a-zA-Z0-9*")
18052 (skip-chars-backward " \t")
18053 (and (bolp) (not (org-at-heading-p))))
18054 (cdlatex-tab) t)
18055 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18057 (defun org-cdlatex-underscore-caret (&optional _arg)
18058 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18059 Revert to the normal definition outside of these fragments."
18060 (interactive "P")
18061 (if (org-inside-LaTeX-fragment-p)
18062 (call-interactively 'cdlatex-sub-superscript)
18063 (let (org-cdlatex-mode)
18064 (call-interactively (key-binding (vector last-input-event))))))
18066 (defun org-cdlatex-math-modify (&optional _arg)
18067 "Execute `cdlatex-math-modify' in LaTeX fragments.
18068 Revert to the normal definition outside of these fragments."
18069 (interactive "P")
18070 (if (org-inside-LaTeX-fragment-p)
18071 (call-interactively 'cdlatex-math-modify)
18072 (let (org-cdlatex-mode)
18073 (call-interactively (key-binding (vector last-input-event))))))
18075 (defun org-cdlatex-environment-indent (&optional environment item)
18076 "Execute `cdlatex-environment' and indent the inserted environment.
18078 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18080 The inserted environment is indented to current indentation
18081 unless point is at the beginning of the line, in which the
18082 environment remains unintended."
18083 (interactive)
18084 ;; cdlatex-environment always return nil. Therefore, capture output
18085 ;; first and determine if an environment was selected.
18086 (let* ((beg (point-marker))
18087 (end (copy-marker (point) t))
18088 (inserted (progn
18089 (ignore-errors (cdlatex-environment environment item))
18090 (< beg end)))
18091 ;; Figure out how many lines to move forward after the
18092 ;; environment has been inserted.
18093 (lines (when inserted
18094 (save-excursion
18095 (- (cl-loop while (< beg (point))
18096 with x = 0
18097 do (forward-line -1)
18098 (cl-incf x)
18099 finally return x)
18100 (if (progn (goto-char beg)
18101 (and (progn (skip-chars-forward " \t") (eolp))
18102 (progn (skip-chars-backward " \t") (bolp))))
18103 1 0)))))
18104 (env (org-trim (delete-and-extract-region beg end))))
18105 (when inserted
18106 ;; Get indentation of next line unless at column 0.
18107 (let ((ind (if (bolp) 0
18108 (save-excursion
18109 (org-return-indent)
18110 (prog1 (org-get-indentation)
18111 (when (progn (skip-chars-forward " \t") (eolp))
18112 (delete-region beg (point)))))))
18113 (bol (progn (skip-chars-backward " \t") (bolp))))
18114 ;; Insert a newline before environment unless at column zero
18115 ;; to "escape" the current line. Insert a newline if
18116 ;; something is one the same line as \end{ENVIRONMENT}.
18117 (insert
18118 (concat (unless bol "\n") env
18119 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18120 (unless (zerop ind)
18121 (save-excursion
18122 (goto-char beg)
18123 (while (< (point) end)
18124 (unless (eolp) (indent-line-to ind))
18125 (forward-line))))
18126 (goto-char beg)
18127 (forward-line lines)
18128 (indent-line-to ind)))
18129 (set-marker beg nil)
18130 (set-marker end nil)))
18133 ;;;; LaTeX fragments
18135 (defun org-inside-LaTeX-fragment-p ()
18136 "Test if point is inside a LaTeX fragment.
18137 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18138 sequence appearing also before point.
18139 Even though the matchers for math are configurable, this function assumes
18140 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18141 delimiters are skipped when they have been removed by customization.
18142 The return value is nil, or a cons cell with the delimiter and the
18143 position of this delimiter.
18145 This function does a reasonably good job, but can locally be fooled by
18146 for example currency specifications. For example it will assume being in
18147 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18148 fragments that are properly closed, but during editing, we have to live
18149 with the uncertainty caused by missing closing delimiters. This function
18150 looks only before point, not after."
18151 (catch 'exit
18152 (let ((pos (point))
18153 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18154 (lim (save-excursion (org-backward-paragraph) (point)))
18155 dd-on str (start 0) m re)
18156 (goto-char pos)
18157 (when dodollar
18158 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18159 re (nth 1 (assoc "$" org-latex-regexps)))
18160 (while (string-match re str start)
18161 (cond
18162 ((= (match-end 0) (length str))
18163 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18164 ((= (match-end 0) (- (length str) 5))
18165 (throw 'exit nil))
18166 (t (setq start (match-end 0))))))
18167 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18168 (goto-char pos)
18169 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18170 (and (match-beginning 2) (throw 'exit nil))
18171 ;; count $$
18172 (while (re-search-backward "\\$\\$" lim t)
18173 (setq dd-on (not dd-on)))
18174 (goto-char pos)
18175 (when dd-on (cons "$$" m))))))
18177 (defun org-inside-latex-macro-p ()
18178 "Is point inside a LaTeX macro or its arguments?"
18179 (save-match-data
18180 (org-in-regexp
18181 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18183 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18184 "Build an overlay between BEG and END using IMAGE file.
18185 Argument IMAGETYPE is the extension of the displayed image,
18186 as a string. It defaults to \"png\"."
18187 (let ((ov (make-overlay beg end))
18188 (imagetype (or (intern imagetype) 'png)))
18189 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18190 (overlay-put ov 'evaporate t)
18191 (overlay-put ov
18192 'modification-hooks
18193 (list (lambda (o _flag _beg _end &optional _l)
18194 (delete-overlay o))))
18195 (overlay-put ov
18196 'display
18197 (list 'image :type imagetype :file image :ascent 'center))))
18199 (defun org--list-latex-overlays (&optional beg end)
18200 "List all Org LaTeX overlays in current buffer.
18201 Limit to overlays between BEG and END when those are provided."
18202 (cl-remove-if-not
18203 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18204 (overlays-in (or beg (point-min)) (or end (point-max)))))
18206 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18207 "Remove all overlays with LaTeX fragment images in current buffer.
18208 When optional arguments BEG and END are non-nil, remove all
18209 overlays between them instead. Return a non-nil value when some
18210 overlays were removed, nil otherwise."
18211 (let ((overlays (org--list-latex-overlays beg end)))
18212 (mapc #'delete-overlay overlays)
18213 overlays))
18215 (defun org-toggle-latex-fragment (&optional arg)
18216 "Preview the LaTeX fragment at point, or all locally or globally.
18218 If the cursor is on a LaTeX fragment, create the image and overlay
18219 it over the source code, if there is none. Remove it otherwise.
18220 If there is no fragment at point, display all fragments in the
18221 current section.
18223 With prefix ARG, preview or clear image for all fragments in the
18224 current subtree or in the whole buffer when used before the first
18225 headline. With a prefix ARG `\\[universal-argument] \
18226 \\[universal-argument]' preview or clear images
18227 for all fragments in the buffer."
18228 (interactive "P")
18229 (when (display-graphic-p)
18230 (catch 'exit
18231 (save-excursion
18232 (let (beg end msg)
18233 (cond
18234 ((or (equal arg '(16))
18235 (and (equal arg '(4))
18236 (org-with-limited-levels (org-before-first-heading-p))))
18237 (if (org-remove-latex-fragment-image-overlays)
18238 (progn (message "LaTeX fragments images removed from buffer")
18239 (throw 'exit nil))
18240 (setq msg "Creating images for buffer...")))
18241 ((equal arg '(4))
18242 (org-with-limited-levels (org-back-to-heading t))
18243 (setq beg (point))
18244 (setq end (progn (org-end-of-subtree t) (point)))
18245 (if (org-remove-latex-fragment-image-overlays beg end)
18246 (progn
18247 (message "LaTeX fragment images removed from subtree")
18248 (throw 'exit nil))
18249 (setq msg "Creating images for subtree...")))
18250 ((let ((datum (org-element-context)))
18251 (when (memq (org-element-type datum)
18252 '(latex-environment latex-fragment))
18253 (setq beg (org-element-property :begin datum))
18254 (setq end (org-element-property :end datum))
18255 (if (org-remove-latex-fragment-image-overlays beg end)
18256 (progn (message "LaTeX fragment image removed")
18257 (throw 'exit nil))
18258 (setq msg "Creating image...")))))
18260 (org-with-limited-levels
18261 (setq beg (if (org-at-heading-p) (line-beginning-position)
18262 (outline-previous-heading)
18263 (point)))
18264 (setq end (progn (outline-next-heading) (point)))
18265 (if (org-remove-latex-fragment-image-overlays beg end)
18266 (progn
18267 (message "LaTeX fragment images removed from section")
18268 (throw 'exit nil))
18269 (setq msg "Creating images for section...")))))
18270 (let ((file (buffer-file-name (buffer-base-buffer))))
18271 (org-format-latex
18272 (concat org-preview-latex-image-directory "org-ltximg")
18273 beg end
18274 ;; Emacs cannot overlay images from remote hosts. Create
18275 ;; it in `temporary-file-directory' instead.
18276 (if (or (not file) (file-remote-p file))
18277 temporary-file-directory
18278 default-directory)
18279 'overlays msg 'forbuffer org-preview-latex-default-process))
18280 (message (concat msg "done")))))))
18282 (defun org-format-latex
18283 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18284 "Replace LaTeX fragments with links to an image.
18286 The function takes care of creating the replacement image.
18288 Only consider fragments between BEG and END when those are
18289 provided.
18291 When optional argument OVERLAYS is non-nil, display the image on
18292 top of the fragment instead of replacing it.
18294 PROCESSING-TYPE is the conversion method to use, as a symbol.
18296 Some of the options can be changed using the variable
18297 `org-format-latex-options', which see."
18298 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18299 (unless (eq processing-type 'verbatim)
18300 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18301 (cnt 0)
18302 checkdir-flag)
18303 (goto-char (or beg (point-min)))
18304 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18305 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18306 (overlay-recenter (or end (point-max))))
18307 (while (re-search-forward math-regexp end t)
18308 (unless (and overlays
18309 (eq (get-char-property (point) 'org-overlay-type)
18310 'org-latex-overlay))
18311 (let* ((context (org-element-context))
18312 (type (org-element-type context)))
18313 (when (memq type '(latex-environment latex-fragment))
18314 (let ((block-type (eq type 'latex-environment))
18315 (value (org-element-property :value context))
18316 (beg (org-element-property :begin context))
18317 (end (save-excursion
18318 (goto-char (org-element-property :end context))
18319 (skip-chars-backward " \r\t\n")
18320 (point))))
18321 (cond
18322 ((eq processing-type 'mathjax)
18323 ;; Prepare for MathJax processing.
18324 (if (not (string-match "\\`\\$\\$?" value))
18325 (goto-char end)
18326 (delete-region beg end)
18327 (if (string= (match-string 0 value) "$$")
18328 (insert "\\[" (substring value 2 -2) "\\]")
18329 (insert "\\(" (substring value 1 -1) "\\)"))))
18330 ((assq processing-type org-preview-latex-process-alist)
18331 ;; Process to an image.
18332 (cl-incf cnt)
18333 (goto-char beg)
18334 (let* ((processing-info
18335 (cdr (assq processing-type org-preview-latex-process-alist)))
18336 (face (face-at-point))
18337 ;; Get the colors from the face at point.
18339 (let ((color (plist-get org-format-latex-options
18340 :foreground)))
18341 (if (and forbuffer (eq color 'auto))
18342 (face-attribute face :foreground nil 'default)
18343 color)))
18345 (let ((color (plist-get org-format-latex-options
18346 :background)))
18347 (if (and forbuffer (eq color 'auto))
18348 (face-attribute face :background nil 'default)
18349 color)))
18350 (hash (sha1 (prin1-to-string
18351 (list org-format-latex-header
18352 org-latex-default-packages-alist
18353 org-latex-packages-alist
18354 org-format-latex-options
18355 forbuffer value fg bg))))
18356 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18357 (absprefix (expand-file-name prefix dir))
18358 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18359 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18360 (sep (and block-type "\n\n"))
18361 (link (concat sep "[[file:" linkfile "]]" sep))
18362 (options
18363 (org-combine-plists
18364 org-format-latex-options
18365 `(:foreground ,fg :background ,bg))))
18366 (when msg (message msg cnt))
18367 (unless checkdir-flag ; Ensure the directory exists.
18368 (setq checkdir-flag t)
18369 (let ((todir (file-name-directory absprefix)))
18370 (unless (file-directory-p todir)
18371 (make-directory todir t))))
18372 (unless (file-exists-p movefile)
18373 (org-create-formula-image
18374 value movefile options forbuffer processing-type))
18375 (if overlays
18376 (progn
18377 (dolist (o (overlays-in beg end))
18378 (when (eq (overlay-get o 'org-overlay-type)
18379 'org-latex-overlay)
18380 (delete-overlay o)))
18381 (org--format-latex-make-overlay beg end movefile imagetype)
18382 (goto-char end))
18383 (delete-region beg end)
18384 (insert
18385 (org-add-props link
18386 (list 'org-latex-src
18387 (replace-regexp-in-string "\"" "" value)
18388 'org-latex-src-embed-type
18389 (if block-type 'paragraph 'character)))))))
18390 ((eq processing-type 'mathml)
18391 ;; Process to MathML.
18392 (unless (org-format-latex-mathml-available-p)
18393 (user-error "LaTeX to MathML converter not configured"))
18394 (cl-incf cnt)
18395 (when msg (message msg cnt))
18396 (goto-char beg)
18397 (delete-region beg end)
18398 (insert (org-format-latex-as-mathml
18399 value block-type prefix dir)))
18401 (error "Unknown conversion process %s for LaTeX fragments"
18402 processing-type)))))))))))
18404 (defun org-create-math-formula (latex-frag &optional mathml-file)
18405 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18406 Use `org-latex-to-mathml-convert-command'. If the conversion is
18407 sucessful, return the portion between \"<math...> </math>\"
18408 elements otherwise return nil. When MATHML-FILE is specified,
18409 write the results in to that file. When invoked as an
18410 interactive command, prompt for LATEX-FRAG, with initial value
18411 set to the current active region and echo the results for user
18412 inspection."
18413 (interactive (list (let ((frag (when (org-region-active-p)
18414 (buffer-substring-no-properties
18415 (region-beginning) (region-end)))))
18416 (read-string "LaTeX Fragment: " frag nil frag))))
18417 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18418 (let* ((tmp-in-file
18419 (let ((file (file-relative-name
18420 (make-temp-name (expand-file-name "ltxmathml-in")))))
18421 (write-region latex-frag nil file)
18422 file))
18423 (tmp-out-file (file-relative-name
18424 (make-temp-name (expand-file-name "ltxmathml-out"))))
18425 (cmd (format-spec
18426 org-latex-to-mathml-convert-command
18427 `((?j . ,(and org-latex-to-mathml-jar-file
18428 (shell-quote-argument
18429 (expand-file-name
18430 org-latex-to-mathml-jar-file))))
18431 (?I . ,(shell-quote-argument tmp-in-file))
18432 (?i . ,latex-frag)
18433 (?o . ,(shell-quote-argument tmp-out-file)))))
18434 mathml shell-command-output)
18435 (when (called-interactively-p 'any)
18436 (unless (org-format-latex-mathml-available-p)
18437 (user-error "LaTeX to MathML converter not configured")))
18438 (message "Running %s" cmd)
18439 (setq shell-command-output (shell-command-to-string cmd))
18440 (setq mathml
18441 (when (file-readable-p tmp-out-file)
18442 (with-current-buffer (find-file-noselect tmp-out-file t)
18443 (goto-char (point-min))
18444 (when (re-search-forward
18445 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18446 (regexp-quote
18447 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18448 nil t)
18449 (prog1 (match-string 0) (kill-buffer))))))
18450 (cond
18451 (mathml
18452 (setq mathml
18453 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18454 (when mathml-file
18455 (write-region mathml nil mathml-file))
18456 (when (called-interactively-p 'any)
18457 (message mathml)))
18458 ((message "LaTeX to MathML conversion failed")
18459 (message shell-command-output)))
18460 (delete-file tmp-in-file)
18461 (when (file-exists-p tmp-out-file)
18462 (delete-file tmp-out-file))
18463 mathml))
18465 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18466 prefix &optional dir)
18467 "Use `org-create-math-formula' but check local cache first."
18468 (let* ((absprefix (expand-file-name prefix dir))
18469 (print-length nil) (print-level nil)
18470 (formula-id (concat
18471 "formula-"
18472 (sha1
18473 (prin1-to-string
18474 (list latex-frag
18475 org-latex-to-mathml-convert-command)))))
18476 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18477 (formula-cache-dir (file-name-directory formula-cache)))
18479 (unless (file-directory-p formula-cache-dir)
18480 (make-directory formula-cache-dir t))
18482 (unless (file-exists-p formula-cache)
18483 (org-create-math-formula latex-frag formula-cache))
18485 (if (file-exists-p formula-cache)
18486 ;; Successful conversion. Return the link to MathML file.
18487 (org-add-props
18488 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18489 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18490 'org-latex-src-embed-type (if latex-frag-type
18491 'paragraph 'character)))
18492 ;; Failed conversion. Return the LaTeX fragment verbatim
18493 latex-frag)))
18495 (defun org--get-display-dpi ()
18496 "Get the DPI of the display.
18497 The function assumes that the display has the same pixel width in
18498 the horizontal and vertical directions."
18499 (if (display-graphic-p)
18500 (round (/ (display-pixel-height)
18501 (/ (display-mm-height) 25.4)))
18502 (error "Attempt to calculate the dpi of a non-graphic display")))
18504 (defun org-create-formula-image
18505 (string tofile options buffer &optional processing-type)
18506 "Create an image from LaTeX source using external processes.
18508 The LaTeX STRING is saved to a temporary LaTeX file, then
18509 converted to an image file by process PROCESSING-TYPE defined in
18510 `org-preview-latex-process-alist'. A nil value defaults to
18511 `org-preview-latex-default-process'.
18513 The generated image file is eventually moved to TOFILE.
18515 The OPTIONS argument controls the size, foreground color and
18516 background color of the generated image.
18518 When BUFFER non-nil, this function is used for LaTeX previewing.
18519 Otherwise, it is used to deal with LaTeX snippets showed in
18520 a HTML file."
18521 (let* ((processing-type (or processing-type
18522 org-preview-latex-default-process))
18523 (processing-info
18524 (cdr (assq processing-type org-preview-latex-process-alist)))
18525 (programs (plist-get processing-info :programs))
18526 (error-message (or (plist-get processing-info :message) ""))
18527 (use-xcolor (plist-get processing-info :use-xcolor))
18528 (image-input-type (plist-get processing-info :image-input-type))
18529 (image-output-type (plist-get processing-info :image-output-type))
18530 (post-clean (or (plist-get processing-info :post-clean)
18531 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18532 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18533 (latex-header
18534 (or (plist-get processing-info :latex-header)
18535 (org-latex-make-preamble
18536 (org-export-get-environment (org-export-get-backend 'latex))
18537 org-format-latex-header
18538 'snippet)))
18539 (latex-compiler (plist-get processing-info :latex-compiler))
18540 (image-converter (plist-get processing-info :image-converter))
18541 (tmpdir temporary-file-directory)
18542 (texfilebase (make-temp-name
18543 (expand-file-name "orgtex" tmpdir)))
18544 (texfile (concat texfilebase ".tex"))
18545 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18546 '(1.0 . 1.0)))
18547 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18548 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18549 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18550 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18551 "Black"))
18552 (bg (or (plist-get options (if buffer :background :html-background))
18553 "Transparent"))
18554 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18555 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18556 (dolist (program programs)
18557 (org-check-external-command program error-message))
18558 (if use-xcolor
18559 (progn (if (eq fg 'default)
18560 (setq fg (org-latex-color :foreground))
18561 (setq fg (org-latex-color-format fg)))
18562 (if (eq bg 'default)
18563 (setq bg (org-latex-color :background))
18564 (setq bg (org-latex-color-format
18565 (if (string= bg "Transparent") "white" bg))))
18566 (with-temp-file texfile
18567 (insert latex-header)
18568 (insert "\n\\begin{document}\n"
18569 "\\definecolor{fg}{rgb}{" fg "}\n"
18570 "\\definecolor{bg}{rgb}{" bg "}\n"
18571 "\n\\pagecolor{bg}\n"
18572 "\n{\\color{fg}\n"
18573 string
18574 "\n}\n"
18575 "\n\\end{document}\n")))
18576 (if (eq fg 'default)
18577 (setq fg (org-dvipng-color :foreground))
18578 (unless (string= fg "Transparent")
18579 (setq fg (org-dvipng-color-format fg))))
18580 (if (eq bg 'default)
18581 (setq bg (org-dvipng-color :background))
18582 (unless (string= bg "Transparent")
18583 (setq bg (org-dvipng-color-format bg))))
18584 (with-temp-file texfile
18585 (insert latex-header)
18586 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18588 (let* ((err-msg (format "Please adjust `%s' part of \
18589 `org-preview-latex-process-alist'."
18590 processing-type))
18591 (image-input-file
18592 (org-compile-file
18593 texfile latex-compiler image-input-type err-msg log-buf))
18594 (image-output-file
18595 (org-compile-file
18596 image-input-file image-converter image-output-type err-msg log-buf
18597 `((?F . ,(shell-quote-argument fg))
18598 (?B . ,(shell-quote-argument bg))
18599 (?D . ,(shell-quote-argument (format "%s" dpi)))
18600 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18601 (copy-file image-output-file tofile 'replace)
18602 (dolist (e post-clean)
18603 (when (file-exists-p (concat texfilebase e))
18604 (delete-file (concat texfilebase e))))
18605 image-output-file)))
18607 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18608 "Fill a LaTeX header template TPL.
18609 In the template, the following place holders will be recognized:
18611 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18612 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18613 [PACKAGES] \\usepackage statements for PKG
18614 [NO-PACKAGES] do not include PKG
18615 [EXTRA] the string EXTRA
18616 [NO-EXTRA] do not include EXTRA
18618 For backward compatibility, if both the positive and the negative place
18619 holder is missing, the positive one (without the \"NO-\") will be
18620 assumed to be present at the end of the template.
18621 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18622 EXTRA is a string.
18623 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18624 (let (rpl (end ""))
18625 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18626 (setq rpl (if (or (match-end 1) (not def-pkg))
18627 "" (org-latex-packages-to-string def-pkg snippets-p t))
18628 tpl (replace-match rpl t t tpl))
18629 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18631 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18632 (setq rpl (if (or (match-end 1) (not pkg))
18633 "" (org-latex-packages-to-string pkg snippets-p t))
18634 tpl (replace-match rpl t t tpl))
18635 (when pkg (setq end
18636 (concat end "\n"
18637 (org-latex-packages-to-string pkg snippets-p)))))
18639 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18640 (setq rpl (if (or (match-end 1) (not extra))
18641 "" (concat extra "\n"))
18642 tpl (replace-match rpl t t tpl))
18643 (when (and extra (string-match "\\S-" extra))
18644 (setq end (concat end "\n" extra))))
18646 (if (string-match "\\S-" end)
18647 (concat tpl "\n" end)
18648 tpl)))
18650 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18651 "Turn an alist of packages into a string with the \\usepackage macros."
18652 (setq pkg (mapconcat (lambda(p)
18653 (cond
18654 ((stringp p) p)
18655 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18656 (format "%% Package %s omitted" (cadr p)))
18657 ((equal "" (car p))
18658 (format "\\usepackage{%s}" (cadr p)))
18660 (format "\\usepackage[%s]{%s}"
18661 (car p) (cadr p)))))
18663 "\n"))
18664 (if newline (concat pkg "\n") pkg))
18666 (defun org-dvipng-color (attr)
18667 "Return a RGB color specification for dvipng."
18668 (org-dvipng-color-format (face-attribute 'default attr nil)))
18670 (defun org-dvipng-color-format (color-name)
18671 "Convert COLOR-NAME to a RGB color value for dvipng."
18672 (apply #'format "rgb %s %s %s"
18673 (mapcar 'org-normalize-color
18674 (color-values color-name))))
18676 (defun org-latex-color (attr)
18677 "Return a RGB color for the LaTeX color package."
18678 (org-latex-color-format (face-attribute 'default attr nil)))
18680 (defun org-latex-color-format (color-name)
18681 "Convert COLOR-NAME to a RGB color value."
18682 (apply #'format "%s,%s,%s"
18683 (mapcar 'org-normalize-color
18684 (color-values color-name))))
18686 (defun org-normalize-color (value)
18687 "Return string to be used as color value for an RGB component."
18688 (format "%g" (/ value 65535.0)))
18692 ;; Image display
18694 (defvar-local org-inline-image-overlays nil)
18696 (defun org-toggle-inline-images (&optional include-linked)
18697 "Toggle the display of inline images.
18698 INCLUDE-LINKED is passed to `org-display-inline-images'."
18699 (interactive "P")
18700 (if org-inline-image-overlays
18701 (progn
18702 (org-remove-inline-images)
18703 (when (called-interactively-p 'interactive)
18704 (message "Inline image display turned off")))
18705 (org-display-inline-images include-linked)
18706 (when (called-interactively-p 'interactive)
18707 (message (if org-inline-image-overlays
18708 (format "%d images displayed inline"
18709 (length org-inline-image-overlays))
18710 "No images to display inline")))))
18712 (defun org-redisplay-inline-images ()
18713 "Refresh the display of inline images."
18714 (interactive)
18715 (if (not org-inline-image-overlays)
18716 (org-toggle-inline-images)
18717 (org-toggle-inline-images)
18718 (org-toggle-inline-images)))
18720 (defun org-display-inline-images (&optional include-linked refresh beg end)
18721 "Display inline images.
18723 An inline image is a link which follows either of these
18724 conventions:
18726 1. Its path is a file with an extension matching return value
18727 from `image-file-name-regexp' and it has no contents.
18729 2. Its description consists in a single link of the previous
18730 type.
18732 When optional argument INCLUDE-LINKED is non-nil, also links with
18733 a text description part will be inlined. This can be nice for
18734 a quick look at those images, but it does not reflect what
18735 exported files will look like.
18737 When optional argument REFRESH is non-nil, refresh existing
18738 images between BEG and END. This will create new image displays
18739 only if necessary. BEG and END default to the buffer
18740 boundaries."
18741 (interactive "P")
18742 (when (display-graphic-p)
18743 (unless refresh
18744 (org-remove-inline-images)
18745 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18746 (org-with-wide-buffer
18747 (goto-char (or beg (point-min)))
18748 (let* ((case-fold-search t)
18749 (file-extension-re (image-file-name-regexp))
18750 (link-abbrevs (mapcar #'car
18751 (append org-link-abbrev-alist-local
18752 org-link-abbrev-alist)))
18753 ;; Check absolute, relative file names and explicit
18754 ;; "file:" links. Also check link abbreviations since
18755 ;; some might expand to "file" links.
18756 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18757 (if (not link-abbrevs) ""
18758 (format "\\|\\(?:%s:\\)"
18759 (regexp-opt link-abbrevs))))))
18760 (while (re-search-forward file-types-re end t)
18761 (let ((link (save-match-data (org-element-context))))
18762 ;; Check if we're at an inline image, i.e., an image file
18763 ;; link without a description (unless INCLUDE-LINKED is
18764 ;; non-nil).
18765 (when (and (equal "file" (org-element-property :type link))
18766 (or include-linked
18767 (null (org-element-contents link)))
18768 (string-match-p file-extension-re
18769 (org-element-property :path link)))
18770 (let ((file (expand-file-name
18771 (org-link-unescape
18772 (org-element-property :path link)))))
18773 (when (file-exists-p file)
18774 (let ((width
18775 ;; Apply `org-image-actual-width' specifications.
18776 (cond
18777 ((not (image-type-available-p 'imagemagick)) nil)
18778 ((eq org-image-actual-width t) nil)
18779 ((listp org-image-actual-width)
18781 ;; First try to find a width among
18782 ;; attributes associated to the paragraph
18783 ;; containing link.
18784 (let ((paragraph
18785 (let ((e link))
18786 (while (and (setq e (org-element-property
18787 :parent e))
18788 (not (eq (org-element-type e)
18789 'paragraph))))
18790 e)))
18791 (when paragraph
18792 (save-excursion
18793 (goto-char (org-element-property :begin paragraph))
18794 (when
18795 (re-search-forward
18796 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18797 (org-element-property
18798 :post-affiliated paragraph)
18800 (string-to-number (match-string 1))))))
18801 ;; Otherwise, fall-back to provided number.
18802 (car org-image-actual-width)))
18803 ((numberp org-image-actual-width)
18804 org-image-actual-width)))
18805 (old (get-char-property-and-overlay
18806 (org-element-property :begin link)
18807 'org-image-overlay)))
18808 (if (and (car-safe old) refresh)
18809 (image-refresh (overlay-get (cdr old) 'display))
18810 (let ((image (create-image file
18811 (and width 'imagemagick)
18813 :width width)))
18814 (when image
18815 (let ((ov (make-overlay
18816 (org-element-property :begin link)
18817 (progn
18818 (goto-char
18819 (org-element-property :end link))
18820 (skip-chars-backward " \t")
18821 (point)))))
18822 (overlay-put ov 'display image)
18823 (overlay-put ov 'face 'default)
18824 (overlay-put ov 'org-image-overlay t)
18825 (overlay-put
18826 ov 'modification-hooks
18827 (list 'org-display-inline-remove-overlay))
18828 (push ov org-inline-image-overlays)))))))))))))))
18830 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18831 "Remove inline-display overlay if a corresponding region is modified."
18832 (let ((inhibit-modification-hooks t))
18833 (when (and ov after)
18834 (delete ov org-inline-image-overlays)
18835 (delete-overlay ov))))
18837 (defun org-remove-inline-images ()
18838 "Remove inline display of images."
18839 (interactive)
18840 (mapc #'delete-overlay org-inline-image-overlays)
18841 (setq org-inline-image-overlays nil))
18843 ;;;; Key bindings
18845 (defun org-remap (map &rest commands)
18846 "In MAP, remap the functions given in COMMANDS.
18847 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18848 (let (new old)
18849 (while commands
18850 (setq old (pop commands) new (pop commands))
18851 (org-defkey map (vector 'remap old) new))))
18853 ;; Outline functions from `outline-mode-prefix-map'
18854 ;; that can be remapped in Org:
18855 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18856 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
18857 (define-key org-mode-map [remap outline-forward-same-level]
18858 'org-forward-heading-same-level)
18859 (define-key org-mode-map [remap outline-backward-same-level]
18860 'org-backward-heading-same-level)
18861 (define-key org-mode-map [remap outline-show-branches]
18862 'org-kill-note-or-show-branches)
18863 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18864 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18865 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18866 (define-key org-mode-map [remap outline-next-visible-heading]
18867 'org-next-visible-heading)
18868 (define-key org-mode-map [remap outline-previous-visible-heading]
18869 'org-previous-visible-heading)
18870 (define-key org-mode-map [remap show-children] 'org-show-children)
18872 ;; Outline functions from `outline-mode-prefix-map' that can not
18873 ;; be remapped in Org:
18875 ;; - the column "key binding" shows whether the Outline function is still
18876 ;; available in Org mode on the same key that it has been bound to in
18877 ;; Outline mode:
18878 ;; - "overridden": key used for a different functionality in Org mode
18879 ;; - else: key still bound to the same Outline function in Org mode
18881 ;; | Outline function | key binding | Org replacement |
18882 ;; |------------------------------------+-------------+--------------------------|
18883 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18884 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18885 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18886 ;; | `show-entry' | overridden | no replacement |
18887 ;; | `show-branches' | `C-c C-k' | still same function |
18888 ;; | `show-subtree' | overridden | visibility cycling |
18889 ;; | `show-all' | overridden | no replacement |
18890 ;; | `hide-subtree' | overridden | visibility cycling |
18891 ;; | `hide-body' | overridden | no replacement |
18892 ;; | `hide-entry' | overridden | visibility cycling |
18893 ;; | `hide-leaves' | overridden | no replacement |
18894 ;; | `hide-sublevels' | overridden | no replacement |
18895 ;; | `hide-other' | overridden | no replacement |
18897 ;; Make `C-c C-x' a prefix key
18898 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18900 ;; TAB key with modifiers
18901 (org-defkey org-mode-map "\C-i" 'org-cycle)
18902 (org-defkey org-mode-map [(tab)] 'org-cycle)
18903 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18904 (org-defkey org-mode-map "\M-\t" #'pcomplete)
18906 ;; The following line is necessary under Suse GNU/Linux
18907 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
18908 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18909 (define-key org-mode-map [backtab] 'org-shifttab)
18911 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18912 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18913 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18915 ;; Cursor keys with modifiers
18916 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18917 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18918 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18919 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18921 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
18922 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
18923 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18924 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18925 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18926 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18928 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18929 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18930 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18931 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18933 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18934 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18935 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18936 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18938 ;; Babel keys
18939 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18940 (dolist (pair org-babel-key-bindings)
18941 (define-key org-babel-map (car pair) (cdr pair)))
18943 ;;; Extra keys for tty access.
18944 ;; We only set them when really needed because otherwise the
18945 ;; menus don't show the simple keys
18947 (when (or org-use-extra-keys (not window-system))
18948 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18949 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18950 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18951 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18952 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18953 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18954 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18955 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18956 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18957 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18958 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18959 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18960 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18961 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18962 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18963 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18964 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18965 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18966 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18967 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18968 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18969 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18970 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
18971 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18972 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18973 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18974 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18975 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18977 ;; All the other keys
18978 (org-remap org-mode-map
18979 'self-insert-command 'org-self-insert-command
18980 'delete-char 'org-delete-char
18981 'delete-backward-char 'org-delete-backward-char)
18982 (org-defkey org-mode-map "|" 'org-force-self-insert)
18984 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
18985 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18986 (if (boundp 'narrow-map)
18987 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18988 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18989 (if (boundp 'narrow-map)
18990 (org-defkey narrow-map "b" 'org-narrow-to-block)
18991 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18992 (if (boundp 'narrow-map)
18993 (org-defkey narrow-map "e" 'org-narrow-to-element)
18994 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18995 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18996 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18997 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18998 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18999 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19000 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19001 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19002 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19003 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19004 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19005 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19006 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19007 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19008 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19009 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19010 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19011 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19012 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19013 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19014 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19015 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19016 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19017 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19018 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19019 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19020 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19021 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19022 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19023 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19024 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19025 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19026 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19027 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19028 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19029 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19030 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19031 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19032 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19033 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19034 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19035 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19036 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19037 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19038 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19039 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19040 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19041 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19042 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19043 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19044 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19045 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19046 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19047 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19048 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19049 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19050 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19051 (org-defkey org-mode-map "\C-c^" 'org-sort)
19052 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19053 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19054 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19055 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19056 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19057 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19058 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19059 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19060 (org-defkey org-mode-map "\C-m" 'org-return)
19061 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19062 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19063 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19064 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19065 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19066 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19067 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19068 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19069 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19070 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19071 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19072 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19073 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19074 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19075 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19076 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19077 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19078 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19079 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19080 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19081 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19082 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19083 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19084 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19085 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19087 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19088 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19089 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19091 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19092 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19093 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19094 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19095 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19096 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19097 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19098 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19099 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19100 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19101 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19102 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19103 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19104 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19105 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19106 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19107 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19108 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19109 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19110 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19111 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19112 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19113 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19115 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19116 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19117 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19118 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19119 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19121 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19123 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19125 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19126 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19128 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19131 (defconst org-speed-commands-default
19133 ("Outline Navigation")
19134 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19135 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19136 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19137 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19138 ("F" . org-next-block)
19139 ("B" . org-previous-block)
19140 ("u" . (org-speed-move-safe 'outline-up-heading))
19141 ("j" . org-goto)
19142 ("g" . (org-refile t))
19143 ("Outline Visibility")
19144 ("c" . org-cycle)
19145 ("C" . org-shifttab)
19146 (" " . org-display-outline-path)
19147 ("s" . org-narrow-to-subtree)
19148 ("=" . org-columns)
19149 ("Outline Structure Editing")
19150 ("U" . org-metaup)
19151 ("D" . org-metadown)
19152 ("r" . org-metaright)
19153 ("l" . org-metaleft)
19154 ("R" . org-shiftmetaright)
19155 ("L" . org-shiftmetaleft)
19156 ("i" . (progn (forward-char 1) (call-interactively
19157 'org-insert-heading-respect-content)))
19158 ("^" . org-sort)
19159 ("w" . org-refile)
19160 ("a" . org-archive-subtree-default-with-confirmation)
19161 ("@" . org-mark-subtree)
19162 ("#" . org-toggle-comment)
19163 ("Clock Commands")
19164 ("I" . org-clock-in)
19165 ("O" . org-clock-out)
19166 ("Meta Data Editing")
19167 ("t" . org-todo)
19168 ("," . (org-priority))
19169 ("0" . (org-priority ?\ ))
19170 ("1" . (org-priority ?A))
19171 ("2" . (org-priority ?B))
19172 ("3" . (org-priority ?C))
19173 (":" . org-set-tags-command)
19174 ("e" . org-set-effort)
19175 ("E" . org-inc-effort)
19176 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19177 (org-entry-put (point) "APPT_WARNTIME" m)))
19178 ("Agenda Views etc")
19179 ("v" . org-agenda)
19180 ("/" . org-sparse-tree)
19181 ("Misc")
19182 ("o" . org-open-at-point)
19183 ("?" . org-speed-command-help)
19184 ("<" . (org-agenda-set-restriction-lock 'subtree))
19185 (">" . (org-agenda-remove-restriction-lock))
19187 "The default speed commands.")
19189 (defun org-print-speed-command (e)
19190 (if (> (length (car e)) 1)
19191 (progn
19192 (princ "\n")
19193 (princ (car e))
19194 (princ "\n")
19195 (princ (make-string (length (car e)) ?-))
19196 (princ "\n"))
19197 (princ (car e))
19198 (princ " ")
19199 (if (symbolp (cdr e))
19200 (princ (symbol-name (cdr e)))
19201 (prin1 (cdr e)))
19202 (princ "\n")))
19204 (defun org-speed-command-help ()
19205 "Show the available speed commands."
19206 (interactive)
19207 (if (not org-use-speed-commands)
19208 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19209 (with-output-to-temp-buffer "*Help*"
19210 (princ "User-defined Speed commands\n===========================\n")
19211 (mapc #'org-print-speed-command org-speed-commands-user)
19212 (princ "\n")
19213 (princ "Built-in Speed commands\n=======================\n")
19214 (mapc #'org-print-speed-command org-speed-commands-default))
19215 (with-current-buffer "*Help*"
19216 (setq truncate-lines t))))
19218 (defun org-speed-move-safe (cmd)
19219 "Execute CMD, but make sure that the cursor always ends up in a headline.
19220 If not, return to the original position and throw an error."
19221 (interactive)
19222 (let ((pos (point)))
19223 (call-interactively cmd)
19224 (unless (and (bolp) (org-at-heading-p))
19225 (goto-char pos)
19226 (error "Boundary reached while executing %s" cmd))))
19228 (defvar org-self-insert-command-undo-counter 0)
19230 (defvar org-table-auto-blank-field) ; defined in org-table.el
19231 (defvar org-speed-command nil)
19233 (defun org-speed-command-activate (keys)
19234 "Hook for activating single-letter speed commands.
19235 `org-speed-commands-default' specifies a minimal command set.
19236 Use `org-speed-commands-user' for further customization."
19237 (when (or (and (bolp) (looking-at org-outline-regexp))
19238 (and (functionp org-use-speed-commands)
19239 (funcall org-use-speed-commands)))
19240 (cdr (assoc keys (append org-speed-commands-user
19241 org-speed-commands-default)))))
19243 (defun org-babel-speed-command-activate (keys)
19244 "Hook for activating single-letter code block commands."
19245 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19246 (cdr (assoc keys org-babel-key-bindings))))
19248 (defcustom org-speed-command-hook
19249 '(org-speed-command-activate org-babel-speed-command-activate)
19250 "Hook for activating speed commands at strategic locations.
19251 Hook functions are called in sequence until a valid handler is
19252 found.
19254 Each hook takes a single argument, a user-pressed command key
19255 which is also a `self-insert-command' from the global map.
19257 Within the hook, examine the cursor position and the command key
19258 and return nil or a valid handler as appropriate. Handler could
19259 be one of an interactive command, a function, or a form.
19261 Set `org-use-speed-commands' to non-nil value to enable this
19262 hook. The default setting is `org-speed-command-activate'."
19263 :group 'org-structure
19264 :version "24.1"
19265 :type 'hook)
19267 (defun org-self-insert-command (N)
19268 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19269 If the cursor is in a table looking at whitespace, the whitespace is
19270 overwritten, and the table is not marked as requiring realignment."
19271 (interactive "p")
19272 (org-check-before-invisible-edit 'insert)
19273 (cond
19274 ((and org-use-speed-commands
19275 (let ((kv (this-command-keys-vector)))
19276 (setq org-speed-command
19277 (run-hook-with-args-until-success
19278 'org-speed-command-hook
19279 (make-string 1 (aref kv (1- (length kv))))))))
19280 (cond
19281 ((commandp org-speed-command)
19282 (setq this-command org-speed-command)
19283 (call-interactively org-speed-command))
19284 ((functionp org-speed-command)
19285 (funcall org-speed-command))
19286 ((and org-speed-command (listp org-speed-command))
19287 (eval org-speed-command))
19288 (t (let (org-use-speed-commands)
19289 (call-interactively 'org-self-insert-command)))))
19290 ((and
19291 (org-at-table-p)
19292 (eq N 1)
19293 (not (org-region-active-p))
19294 (progn
19295 ;; Check if we blank the field, and if that triggers align.
19296 (and (featurep 'org-table) org-table-auto-blank-field
19297 (memq last-command
19298 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19299 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19300 ;; Got extra space, this field does not determine
19301 ;; column width.
19302 (let (org-table-may-need-update) (org-table-blank-field))
19303 ;; No extra space, this field may determine column
19304 ;; width.
19305 (org-table-blank-field)))
19307 (looking-at "[^|\n]* \\( \\)|"))
19308 ;; There is room for insertion without re-aligning the table.
19309 (delete-region (match-beginning 1) (match-end 1))
19310 (self-insert-command N))
19312 (setq org-table-may-need-update t)
19313 (self-insert-command N)
19314 (org-fix-tags-on-the-fly)
19315 (when org-self-insert-cluster-for-undo
19316 (if (not (eq last-command 'org-self-insert-command))
19317 (setq org-self-insert-command-undo-counter 1)
19318 (if (>= org-self-insert-command-undo-counter 20)
19319 (setq org-self-insert-command-undo-counter 1)
19320 (and (> org-self-insert-command-undo-counter 0)
19321 buffer-undo-list (listp buffer-undo-list)
19322 (not (cadr buffer-undo-list)) ; remove nil entry
19323 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19324 (setq org-self-insert-command-undo-counter
19325 (1+ org-self-insert-command-undo-counter))))))))
19327 (defun org-check-before-invisible-edit (kind)
19328 "Check is editing if kind KIND would be dangerous with invisible text around.
19329 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19330 ;; First, try to get out of here as quickly as possible, to reduce overhead
19331 (when (and org-catch-invisible-edits
19332 (or (not (boundp 'visible-mode)) (not visible-mode))
19333 (or (get-char-property (point) 'invisible)
19334 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19335 ;; OK, we need to take a closer look. Do not consider
19336 ;; invisibility obtained through text properties (e.g., link
19337 ;; fontification), as it cannot be toggled.
19338 (let* ((invisible-at-point
19339 (pcase (get-char-property-and-overlay (point) 'invisible)
19340 (`(,_ . ,(and (pred overlayp) o)) o)))
19341 ;; Assume that point cannot land in the middle of an
19342 ;; overlay, or between two overlays.
19343 (invisible-before-point
19344 (and (not invisible-at-point)
19345 (not (bobp))
19346 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19347 (`(,_ . ,(and (pred overlayp) o)) o))))
19348 (border-and-ok-direction
19350 ;; Check if we are acting predictably before invisible
19351 ;; text.
19352 (and invisible-at-point
19353 (memq kind '(insert delete-backward)))
19354 ;; Check if we are acting predictably after invisible text
19355 ;; This works not well, and I have turned it off. It seems
19356 ;; better to always show and stop after invisible text.
19357 ;; (and (not invisible-at-point) invisible-before-point
19358 ;; (memq kind '(insert delete)))
19360 (when (or invisible-at-point invisible-before-point)
19361 (when (eq org-catch-invisible-edits 'error)
19362 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19363 (if (and org-custom-properties-overlays
19364 (y-or-n-p "Display invisible properties in this buffer? "))
19365 (org-toggle-custom-properties-visibility)
19366 ;; Make the area visible
19367 (save-excursion
19368 (when invisible-before-point
19369 (goto-char
19370 (previous-single-char-property-change (point) 'invisible)))
19371 ;; Remove whatever overlay is currently making yet-to-be
19372 ;; edited text invisible. Also remove nested invisibility
19373 ;; related overlays.
19374 (delete-overlay (or invisible-at-point invisible-before-point))
19375 (let ((origin (if invisible-at-point (point) (1- (point)))))
19376 (while (pcase (get-char-property-and-overlay origin 'invisible)
19377 (`(,_ . ,(and (pred overlayp) o))
19378 (delete-overlay o)
19379 t)))))
19380 (cond
19381 ((eq org-catch-invisible-edits 'show)
19382 ;; That's it, we do the edit after showing
19383 (message
19384 "Unfolding invisible region around point before editing")
19385 (sit-for 1))
19386 ((and (eq org-catch-invisible-edits 'smart)
19387 border-and-ok-direction)
19388 (message "Unfolding invisible region around point before editing"))
19390 ;; Don't do the edit, make the user repeat it in full visibility
19391 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19393 (defun org-fix-tags-on-the-fly ()
19394 "Align tags in headline at point.
19395 Unlike to `org-set-tags', it ignores region and sorting."
19396 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19397 (org-at-heading-p))
19398 (let ((org-ignore-region t)
19399 (org-tags-sort-function nil))
19400 (org-set-tags nil t))))
19402 (defun org-delete-backward-char (N)
19403 "Like `delete-backward-char', insert whitespace at field end in tables.
19404 When deleting backwards, in tables this function will insert whitespace in
19405 front of the next \"|\" separator, to keep the table aligned. The table will
19406 still be marked for re-alignment if the field did fill the entire column,
19407 because, in this case the deletion might narrow the column."
19408 (interactive "p")
19409 (save-match-data
19410 (org-check-before-invisible-edit 'delete-backward)
19411 (if (and (org-at-table-p)
19412 (eq N 1)
19413 (not (org-region-active-p))
19414 (string-match "|" (buffer-substring (point-at-bol) (point)))
19415 (looking-at ".*?|"))
19416 (let ((pos (point))
19417 (noalign (looking-at "[^|\n\r]* |"))
19418 (c org-table-may-need-update))
19419 (backward-delete-char N)
19420 (unless overwrite-mode
19421 (skip-chars-forward "^|")
19422 (insert " ")
19423 (goto-char (1- pos)))
19424 ;; noalign: if there were two spaces at the end, this field
19425 ;; does not determine the width of the column.
19426 (when noalign (setq org-table-may-need-update c)))
19427 (backward-delete-char N)
19428 (org-fix-tags-on-the-fly))))
19430 (defun org-delete-char (N)
19431 "Like `delete-char', but insert whitespace at field end in tables.
19432 When deleting characters, in tables this function will insert whitespace in
19433 front of the next \"|\" separator, to keep the table aligned. The table will
19434 still be marked for re-alignment if the field did fill the entire column,
19435 because, in this case the deletion might narrow the column."
19436 (interactive "p")
19437 (save-match-data
19438 (org-check-before-invisible-edit 'delete)
19439 (if (and (org-at-table-p)
19440 (not (bolp))
19441 (not (= (char-after) ?|))
19442 (eq N 1))
19443 (if (looking-at ".*?|")
19444 (let ((pos (point))
19445 (noalign (looking-at "[^|\n\r]* |"))
19446 (c org-table-may-need-update))
19447 (replace-match
19448 (concat (substring (match-string 0) 1 -1) " |") nil t)
19449 (goto-char pos)
19450 ;; noalign: if there were two spaces at the end, this field
19451 ;; does not determine the width of the column.
19452 (when noalign (setq org-table-may-need-update c)))
19453 (delete-char N))
19454 (delete-char N)
19455 (org-fix-tags-on-the-fly))))
19457 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19458 (put 'org-self-insert-command 'delete-selection
19459 (lambda ()
19460 (not (run-hook-with-args-until-success
19461 'self-insert-uses-region-functions))))
19462 (put 'orgtbl-self-insert-command 'delete-selection
19463 (lambda ()
19464 (not (run-hook-with-args-until-success
19465 'self-insert-uses-region-functions))))
19466 (put 'org-delete-char 'delete-selection 'supersede)
19467 (put 'org-delete-backward-char 'delete-selection 'supersede)
19468 (put 'org-yank 'delete-selection 'yank)
19470 ;; Make `flyspell-mode' delay after some commands
19471 (put 'org-self-insert-command 'flyspell-delayed t)
19472 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19473 (put 'org-delete-char 'flyspell-delayed t)
19474 (put 'org-delete-backward-char 'flyspell-delayed t)
19476 ;; Make pabbrev-mode expand after Org mode commands
19477 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19478 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19480 (defun org-transpose-words ()
19481 "Transpose words for Org.
19482 This uses the `org-mode-transpose-word-syntax-table' syntax
19483 table, which interprets characters in `org-emphasis-alist' as
19484 word constituents."
19485 (interactive)
19486 (with-syntax-table org-mode-transpose-word-syntax-table
19487 (call-interactively 'transpose-words)))
19488 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19490 (defvar org-ctrl-c-ctrl-c-hook nil
19491 "Hook for functions attaching themselves to `C-c C-c'.
19493 This can be used to add additional functionality to the C-c C-c
19494 key which executes context-dependent commands. This hook is run
19495 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19496 run after the last test.
19498 Each function will be called with no arguments. The function
19499 must check if the context is appropriate for it to act. If yes,
19500 it should do its thing and then return a non-nil value. If the
19501 context is wrong, just do nothing and return nil.")
19503 (defvar org-ctrl-c-ctrl-c-final-hook nil
19504 "Hook for functions attaching themselves to `C-c C-c'.
19506 This can be used to add additional functionality to the C-c C-c
19507 key which executes context-dependent commands. This hook is run
19508 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19509 before the first test.
19511 Each function will be called with no arguments. The function
19512 must check if the context is appropriate for it to act. If yes,
19513 it should do its thing and then return a non-nil value. If the
19514 context is wrong, just do nothing and return nil.")
19516 (defvar org-tab-first-hook nil
19517 "Hook for functions to attach themselves to TAB.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.
19519 This hook runs as the first action when TAB is pressed, even before
19520 `org-cycle' messes around with the `outline-regexp' to cater for
19521 inline tasks and plain list item folding.
19522 If any function in this hook returns t, any other actions that
19523 would have been caused by TAB (such as table field motion or visibility
19524 cycling) will not occur.")
19526 (defvar org-tab-after-check-for-table-hook nil
19527 "Hook for functions to attach themselves to TAB.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.
19529 This hook runs after it has been established that the cursor is not in a
19530 table, but before checking if the cursor is in a headline or if global cycling
19531 should be done.
19532 If any function in this hook returns t, not other actions like visibility
19533 cycling will be done.")
19535 (defvar org-tab-after-check-for-cycling-hook nil
19536 "Hook for functions to attach themselves to TAB.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.
19538 This hook runs after it has been established that not table field motion and
19539 not visibility should be done because of current context. This is probably
19540 the place where a package like yasnippets can hook in.")
19542 (defvar org-tab-before-tab-emulation-hook nil
19543 "Hook for functions to attach themselves to TAB.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.
19545 This hook runs after every other options for TAB have been exhausted, but
19546 before indentation and \t insertion takes place.")
19548 (defvar org-metaleft-hook nil
19549 "Hook for functions attaching themselves to `M-left'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-metaright-hook nil
19552 "Hook for functions attaching themselves to `M-right'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-metaup-hook nil
19555 "Hook for functions attaching themselves to `M-up'.
19556 See `org-ctrl-c-ctrl-c-hook' for more information.")
19557 (defvar org-metadown-hook nil
19558 "Hook for functions attaching themselves to `M-down'.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19560 (defvar org-shiftmetaleft-hook nil
19561 "Hook for functions attaching themselves to `M-S-left'.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-shiftmetaright-hook nil
19564 "Hook for functions attaching themselves to `M-S-right'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftmetaup-hook nil
19567 "Hook for functions attaching themselves to `M-S-up'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftmetadown-hook nil
19570 "Hook for functions attaching themselves to `M-S-down'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-metareturn-hook nil
19573 "Hook for functions attaching themselves to `M-RET'.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftup-hook nil
19576 "Hook for functions attaching themselves to `S-up'.
19577 See `org-ctrl-c-ctrl-c-hook' for more information.")
19578 (defvar org-shiftup-final-hook nil
19579 "Hook for functions attaching themselves to `S-up'.
19580 This one runs after all other options except shift-select have been excluded.
19581 See `org-ctrl-c-ctrl-c-hook' for more information.")
19582 (defvar org-shiftdown-hook nil
19583 "Hook for functions attaching themselves to `S-down'.
19584 See `org-ctrl-c-ctrl-c-hook' for more information.")
19585 (defvar org-shiftdown-final-hook nil
19586 "Hook for functions attaching themselves to `S-down'.
19587 This one runs after all other options except shift-select have been excluded.
19588 See `org-ctrl-c-ctrl-c-hook' for more information.")
19589 (defvar org-shiftleft-hook nil
19590 "Hook for functions attaching themselves to `S-left'.
19591 See `org-ctrl-c-ctrl-c-hook' for more information.")
19592 (defvar org-shiftleft-final-hook nil
19593 "Hook for functions attaching themselves to `S-left'.
19594 This one runs after all other options except shift-select have been excluded.
19595 See `org-ctrl-c-ctrl-c-hook' for more information.")
19596 (defvar org-shiftright-hook nil
19597 "Hook for functions attaching themselves to `S-right'.
19598 See `org-ctrl-c-ctrl-c-hook' for more information.")
19599 (defvar org-shiftright-final-hook nil
19600 "Hook for functions attaching themselves to `S-right'.
19601 This one runs after all other options except shift-select have been excluded.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.")
19604 (defun org-modifier-cursor-error ()
19605 "Throw an error, a modified cursor command was applied in wrong context."
19606 (user-error "This command is active in special context like tables, headlines or items"))
19608 (defun org-shiftselect-error ()
19609 "Throw an error because Shift-Cursor command was applied in wrong context."
19610 (if (and (boundp 'shift-select-mode) shift-select-mode)
19611 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19612 (user-error "This command works only in special context like headlines or timestamps")))
19614 (defun org-call-for-shift-select (cmd)
19615 (let ((this-command-keys-shift-translated t))
19616 (call-interactively cmd)))
19618 (defun org-shifttab (&optional arg)
19619 "Global visibility cycling or move to previous table field.
19620 Call `org-table-previous-field' within a table.
19621 When ARG is nil, cycle globally through visibility states.
19622 When ARG is a numeric prefix, show contents of this level."
19623 (interactive "P")
19624 (cond
19625 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19626 ((integerp arg)
19627 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19628 (message "Content view to level: %d" arg)
19629 (org-content (prefix-numeric-value arg2))
19630 (org-cycle-show-empty-lines t)
19631 (setq org-cycle-global-status 'overview)))
19632 (t (call-interactively 'org-global-cycle))))
19634 (defun org-shiftmetaleft ()
19635 "Promote subtree or delete table column.
19636 Calls `org-promote-subtree', `org-outdent-item-tree', or
19637 `org-table-delete-column', depending on context. See the
19638 individual commands for more information."
19639 (interactive)
19640 (cond
19641 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19642 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19643 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19644 ((if (not (org-region-active-p)) (org-at-item-p)
19645 (save-excursion (goto-char (region-beginning))
19646 (org-at-item-p)))
19647 (call-interactively 'org-outdent-item-tree))
19648 (t (org-modifier-cursor-error))))
19650 (defun org-shiftmetaright ()
19651 "Demote subtree or insert table column.
19652 Calls `org-demote-subtree', `org-indent-item-tree', or
19653 `org-table-insert-column', depending on context. See the
19654 individual commands for more information."
19655 (interactive)
19656 (cond
19657 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19658 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19659 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19660 ((if (not (org-region-active-p)) (org-at-item-p)
19661 (save-excursion (goto-char (region-beginning))
19662 (org-at-item-p)))
19663 (call-interactively 'org-indent-item-tree))
19664 (t (org-modifier-cursor-error))))
19666 (defun org-shiftmetaup (&optional _arg)
19667 "Drag the line at point up.
19668 In a table, kill the current row.
19669 On a clock timestamp, update the value of the timestamp like `S-<up>'
19670 but also adjust the previous clocked item in the clock history.
19671 Everywhere else, drag the line at point up."
19672 (interactive "P")
19673 (cond
19674 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19675 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19676 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19677 (call-interactively 'org-timestamp-up)))
19678 (t (call-interactively 'org-drag-line-backward))))
19680 (defun org-shiftmetadown (&optional _arg)
19681 "Drag the line at point down.
19682 In a table, insert an empty row at the current line.
19683 On a clock timestamp, update the value of the timestamp like `S-<down>'
19684 but also adjust the previous clocked item in the clock history.
19685 Everywhere else, drag the line at point down."
19686 (interactive "P")
19687 (cond
19688 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19689 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19690 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19691 (call-interactively 'org-timestamp-down)))
19692 (t (call-interactively 'org-drag-line-forward))))
19694 (defsubst org-hidden-tree-error ()
19695 (user-error
19696 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19698 (defun org-metaleft (&optional _arg)
19699 "Promote heading, list item at point or move table column left.
19701 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19702 depending on context. With no specific context, calls the Emacs
19703 default `backward-word'. See the individual commands for more
19704 information.
19706 This function runs the hook `org-metaleft-hook' as a first step,
19707 and returns at first non-nil value."
19708 (interactive "P")
19709 (cond
19710 ((run-hook-with-args-until-success 'org-metaleft-hook))
19711 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19712 ((org-with-limited-levels
19713 (or (org-at-heading-p)
19714 (and (org-region-active-p)
19715 (save-excursion
19716 (goto-char (region-beginning))
19717 (org-at-heading-p)))))
19718 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19719 (call-interactively 'org-do-promote))
19720 ;; At an inline task.
19721 ((org-at-heading-p)
19722 (call-interactively 'org-inlinetask-promote))
19723 ((or (org-at-item-p)
19724 (and (org-region-active-p)
19725 (save-excursion
19726 (goto-char (region-beginning))
19727 (org-at-item-p))))
19728 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19729 (call-interactively 'org-outdent-item))
19730 (t (call-interactively 'backward-word))))
19732 (defun org-metaright (&optional _arg)
19733 "Demote heading, list item at point or move table column right.
19735 In front of a drawer or a block keyword, indent it correctly.
19737 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19738 `org-indent-drawer' or `org-indent-block' depending on context.
19739 With no specific context, calls the Emacs default `forward-word'.
19740 See the individual commands for more information.
19742 This function runs the hook `org-metaright-hook' as a first step,
19743 and returns at first non-nil value."
19744 (interactive "P")
19745 (cond
19746 ((run-hook-with-args-until-success 'org-metaright-hook))
19747 ((org-at-table-p) (call-interactively 'org-table-move-column))
19748 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19749 ((org-at-block-p) (call-interactively 'org-indent-block))
19750 ((org-with-limited-levels
19751 (or (org-at-heading-p)
19752 (and (org-region-active-p)
19753 (save-excursion
19754 (goto-char (region-beginning))
19755 (org-at-heading-p)))))
19756 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19757 (call-interactively 'org-do-demote))
19758 ;; At an inline task.
19759 ((org-at-heading-p)
19760 (call-interactively 'org-inlinetask-demote))
19761 ((or (org-at-item-p)
19762 (and (org-region-active-p)
19763 (save-excursion
19764 (goto-char (region-beginning))
19765 (org-at-item-p))))
19766 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19767 (call-interactively 'org-indent-item))
19768 (t (call-interactively 'forward-word))))
19770 (defun org-check-for-hidden (what)
19771 "Check if there are hidden headlines/items in the current visual line.
19772 WHAT can be either `headlines' or `items'. If the current line is
19773 an outline or item heading and it has a folded subtree below it,
19774 this function returns t, nil otherwise."
19775 (let ((re (cond
19776 ((eq what 'headlines) org-outline-regexp-bol)
19777 ((eq what 'items) (org-item-beginning-re))
19778 (t (error "This should not happen"))))
19779 beg end)
19780 (save-excursion
19781 (catch 'exit
19782 (unless (org-region-active-p)
19783 (setq beg (point-at-bol))
19784 (beginning-of-line 2)
19785 (while (and (not (eobp)) ;; this is like `next-line'
19786 (get-char-property (1- (point)) 'invisible))
19787 (beginning-of-line 2))
19788 (setq end (point))
19789 (goto-char beg)
19790 (goto-char (point-at-eol))
19791 (setq end (max end (point)))
19792 (while (re-search-forward re end t)
19793 (when (get-char-property (match-beginning 0) 'invisible)
19794 (throw 'exit t))))
19795 nil))))
19797 (defun org-metaup (&optional _arg)
19798 "Move subtree up or move table row up.
19799 Calls `org-move-subtree-up' or `org-table-move-row' or
19800 `org-move-item-up', depending on context. See the individual commands
19801 for more information."
19802 (interactive "P")
19803 (cond
19804 ((run-hook-with-args-until-success 'org-metaup-hook))
19805 ((org-region-active-p)
19806 (let* ((a (min (region-beginning) (region-end)))
19807 (b (1- (max (region-beginning) (region-end))))
19808 (c (save-excursion (goto-char a)
19809 (move-beginning-of-line 0)))
19810 (d (save-excursion (goto-char a)
19811 (move-end-of-line 0) (point))))
19812 (transpose-regions a b c d)
19813 (goto-char c)))
19814 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19815 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19816 ((org-at-item-p) (call-interactively 'org-move-item-up))
19817 (t (org-drag-element-backward))))
19819 (defun org-metadown (&optional _arg)
19820 "Move subtree down or move table row down.
19821 Calls `org-move-subtree-down' or `org-table-move-row' or
19822 `org-move-item-down', depending on context. See the individual
19823 commands for more information."
19824 (interactive "P")
19825 (cond
19826 ((run-hook-with-args-until-success 'org-metadown-hook))
19827 ((org-region-active-p)
19828 (let* ((a (min (region-beginning) (region-end)))
19829 (b (max (region-beginning) (region-end)))
19830 (c (save-excursion (goto-char b)
19831 (move-beginning-of-line 1)))
19832 (d (save-excursion (goto-char b)
19833 (move-end-of-line 1) (1+ (point)))))
19834 (transpose-regions a b c d)
19835 (goto-char d)))
19836 ((org-at-table-p) (call-interactively 'org-table-move-row))
19837 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19838 ((org-at-item-p) (call-interactively 'org-move-item-down))
19839 (t (org-drag-element-forward))))
19841 (defun org-shiftup (&optional arg)
19842 "Increase item in timestamp or increase priority of current headline.
19843 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19844 depending on context. See the individual commands for more information."
19845 (interactive "P")
19846 (cond
19847 ((run-hook-with-args-until-success 'org-shiftup-hook))
19848 ((and org-support-shift-select (org-region-active-p))
19849 (org-call-for-shift-select 'previous-line))
19850 ((org-at-timestamp-p 'lax)
19851 (call-interactively (if org-edit-timestamp-down-means-later
19852 'org-timestamp-down 'org-timestamp-up)))
19853 ((and (not (eq org-support-shift-select 'always))
19854 org-enable-priority-commands
19855 (org-at-heading-p))
19856 (call-interactively 'org-priority-up))
19857 ((and (not org-support-shift-select) (org-at-item-p))
19858 (call-interactively 'org-previous-item))
19859 ((org-clocktable-try-shift 'up arg))
19860 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19861 (org-support-shift-select
19862 (org-call-for-shift-select 'previous-line))
19863 (t (org-shiftselect-error))))
19865 (defun org-shiftdown (&optional arg)
19866 "Decrease item in timestamp or decrease priority of current headline.
19867 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19868 depending on context. See the individual commands for more information."
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19872 ((and org-support-shift-select (org-region-active-p))
19873 (org-call-for-shift-select 'next-line))
19874 ((org-at-timestamp-p 'lax)
19875 (call-interactively (if org-edit-timestamp-down-means-later
19876 'org-timestamp-up 'org-timestamp-down)))
19877 ((and (not (eq org-support-shift-select 'always))
19878 org-enable-priority-commands
19879 (org-at-heading-p))
19880 (call-interactively 'org-priority-down))
19881 ((and (not org-support-shift-select) (org-at-item-p))
19882 (call-interactively 'org-next-item))
19883 ((org-clocktable-try-shift 'down arg))
19884 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19885 (org-support-shift-select
19886 (org-call-for-shift-select 'next-line))
19887 (t (org-shiftselect-error))))
19889 (defun org-shiftright (&optional arg)
19890 "Cycle the thing at point or in the current line, depending on context.
19891 Depending on context, this does one of the following:
19893 - switch a timestamp at point one day into the future
19894 - on a headline, switch to the next TODO keyword.
19895 - on an item, switch entire list to the next bullet type
19896 - on a property line, switch to the next allowed value
19897 - on a clocktable definition line, move time block into the future"
19898 (interactive "P")
19899 (cond
19900 ((run-hook-with-args-until-success 'org-shiftright-hook))
19901 ((and org-support-shift-select (org-region-active-p))
19902 (org-call-for-shift-select 'forward-char))
19903 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19904 ((and (not (eq org-support-shift-select 'always))
19905 (org-at-heading-p))
19906 (let ((org-inhibit-logging
19907 (not org-treat-S-cursor-todo-selection-as-state-change))
19908 (org-inhibit-blocking
19909 (not org-treat-S-cursor-todo-selection-as-state-change)))
19910 (org-call-with-arg 'org-todo 'right)))
19911 ((or (and org-support-shift-select
19912 (not (eq org-support-shift-select 'always))
19913 (org-at-item-bullet-p))
19914 (and (not org-support-shift-select) (org-at-item-p)))
19915 (org-call-with-arg 'org-cycle-list-bullet nil))
19916 ((and (not (eq org-support-shift-select 'always))
19917 (org-at-property-p))
19918 (call-interactively 'org-property-next-allowed-value))
19919 ((org-clocktable-try-shift 'right arg))
19920 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19921 (org-support-shift-select
19922 (org-call-for-shift-select 'forward-char))
19923 (t (org-shiftselect-error))))
19925 (defun org-shiftleft (&optional arg)
19926 "Cycle the thing at point or in the current line, depending on context.
19927 Depending on context, this does one of the following:
19929 - switch a timestamp at point one day into the past
19930 - on a headline, switch to the previous TODO keyword.
19931 - on an item, switch entire list to the previous bullet type
19932 - on a property line, switch to the previous allowed value
19933 - on a clocktable definition line, move time block into the past"
19934 (interactive "P")
19935 (cond
19936 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19937 ((and org-support-shift-select (org-region-active-p))
19938 (org-call-for-shift-select 'backward-char))
19939 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19940 ((and (not (eq org-support-shift-select 'always))
19941 (org-at-heading-p))
19942 (let ((org-inhibit-logging
19943 (not org-treat-S-cursor-todo-selection-as-state-change))
19944 (org-inhibit-blocking
19945 (not org-treat-S-cursor-todo-selection-as-state-change)))
19946 (org-call-with-arg 'org-todo 'left)))
19947 ((or (and org-support-shift-select
19948 (not (eq org-support-shift-select 'always))
19949 (org-at-item-bullet-p))
19950 (and (not org-support-shift-select) (org-at-item-p)))
19951 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19952 ((and (not (eq org-support-shift-select 'always))
19953 (org-at-property-p))
19954 (call-interactively 'org-property-previous-allowed-value))
19955 ((org-clocktable-try-shift 'left arg))
19956 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19957 (org-support-shift-select
19958 (org-call-for-shift-select 'backward-char))
19959 (t (org-shiftselect-error))))
19961 (defun org-shiftcontrolright ()
19962 "Switch to next TODO set."
19963 (interactive)
19964 (cond
19965 ((and org-support-shift-select (org-region-active-p))
19966 (org-call-for-shift-select 'forward-word))
19967 ((and (not (eq org-support-shift-select 'always))
19968 (org-at-heading-p))
19969 (org-call-with-arg 'org-todo 'nextset))
19970 (org-support-shift-select
19971 (org-call-for-shift-select 'forward-word))
19972 (t (org-shiftselect-error))))
19974 (defun org-shiftcontrolleft ()
19975 "Switch to previous TODO set."
19976 (interactive)
19977 (cond
19978 ((and org-support-shift-select (org-region-active-p))
19979 (org-call-for-shift-select 'backward-word))
19980 ((and (not (eq org-support-shift-select 'always))
19981 (org-at-heading-p))
19982 (org-call-with-arg 'org-todo 'previousset))
19983 (org-support-shift-select
19984 (org-call-for-shift-select 'backward-word))
19985 (t (org-shiftselect-error))))
19987 (defun org-shiftcontrolup (&optional n)
19988 "Change timestamps synchronously up in CLOCK log lines.
19989 Optional argument N tells to change by that many units."
19990 (interactive "P")
19991 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19992 (let (org-support-shift-select)
19993 (org-clock-timestamps-up n))
19994 (user-error "Not at a clock log")))
19996 (defun org-shiftcontroldown (&optional n)
19997 "Change timestamps synchronously down in CLOCK log lines.
19998 Optional argument N tells to change by that many units."
19999 (interactive "P")
20000 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20001 (let (org-support-shift-select)
20002 (org-clock-timestamps-down n))
20003 (user-error "Not at a clock log")))
20005 (defun org-increase-number-at-point (&optional inc)
20006 "Increment the number at point.
20007 With an optional prefix numeric argument INC, increment using
20008 this numeric value."
20009 (interactive "p")
20010 (if (not (number-at-point))
20011 (user-error "Not on a number")
20012 (unless inc (setq inc 1))
20013 (let ((pos (point))
20014 (beg (skip-chars-backward "-+^/*0-9eE."))
20015 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20016 (setq nap (buffer-substring-no-properties
20017 (+ pos beg) (+ pos beg end)))
20018 (delete-region (+ pos beg) (+ pos beg end))
20019 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20020 (when (org-at-table-p)
20021 (org-table-align)
20022 (org-table-end-of-field 1))))
20024 (defun org-decrease-number-at-point (&optional inc)
20025 "Decrement the number at point.
20026 With an optional prefix numeric argument INC, decrement using
20027 this numeric value."
20028 (interactive "p")
20029 (org-increase-number-at-point (- (or inc 1))))
20031 (defun org-ctrl-c-ret ()
20032 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20033 (interactive)
20034 (cond
20035 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20036 (t (call-interactively 'org-insert-heading))))
20038 (defun org-find-visible ()
20039 (let ((s (point)))
20040 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20041 (get-char-property s 'invisible)))
20043 (defun org-find-invisible ()
20044 (let ((s (point)))
20045 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20046 (not (get-char-property s 'invisible))))
20049 (defun org-copy-visible (beg end)
20050 "Copy the visible parts of the region."
20051 (interactive "r")
20052 (let ((result ""))
20053 (while (/= beg end)
20054 (when (get-char-property beg 'invisible)
20055 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20056 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20057 (setq result (concat result (buffer-substring beg next)))
20058 (setq beg next)))
20059 (kill-new result)))
20061 (defun org-copy-special ()
20062 "Copy region in table or copy current subtree.
20063 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20064 context. See the individual commands for more information."
20065 (interactive)
20066 (call-interactively
20067 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20069 (defun org-cut-special ()
20070 "Cut region in table or cut current subtree.
20071 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20072 context. See the individual commands for more information."
20073 (interactive)
20074 (call-interactively
20075 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20077 (defun org-paste-special (arg)
20078 "Paste rectangular region into table, or past subtree relative to level.
20079 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20080 See the individual commands for more information."
20081 (interactive "P")
20082 (if (org-at-table-p)
20083 (org-table-paste-rectangle)
20084 (org-paste-subtree arg)))
20086 (defun org-edit-special (&optional arg)
20087 "Call a special editor for the element at point.
20088 When at a table, call the formula editor with `org-table-edit-formulas'.
20089 When in a source code block, call `org-edit-src-code'.
20090 When in a fixed-width region, call `org-edit-fixed-width-region'.
20091 When in an export block, call `org-edit-export-block'.
20092 When in a LaTeX environment, call `org-edit-latex-environment'.
20093 When at an #+INCLUDE keyword, visit the included file.
20094 When at a footnote reference, call `org-edit-footnote-reference'
20095 On a link, call `ffap' to visit the link at point.
20096 Otherwise, return a user error."
20097 (interactive "P")
20098 (let ((element (org-element-at-point)))
20099 (barf-if-buffer-read-only)
20100 (pcase (org-element-type element)
20101 (`src-block
20102 (if (not arg) (org-edit-src-code)
20103 (let* ((info (org-babel-get-src-block-info))
20104 (lang (nth 0 info))
20105 (params (nth 2 info))
20106 (session (cdr (assq :session params))))
20107 (if (not session) (org-edit-src-code)
20108 ;; At a src-block with a session and function called with
20109 ;; an ARG: switch to the buffer related to the inferior
20110 ;; process.
20111 (switch-to-buffer
20112 (funcall (intern (concat "org-babel-prep-session:" lang))
20113 session params))))))
20114 (`keyword
20115 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20116 (org-open-link-from-string
20117 (format "[[%s]]"
20118 (expand-file-name
20119 (let ((value (org-element-property :value element)))
20120 (cond ((org-file-url-p value)
20121 (user-error "The file is specified as a URL, cannot be edited"))
20122 ((not (org-string-nw-p value))
20123 (user-error "No file to edit"))
20124 ((string-match "\\`\"\\(.*?\\)\"" value)
20125 (match-string 1 value))
20126 ((string-match "\\`[^ \t\"]\\S-*" value)
20127 (match-string 0 value))
20128 (t (user-error "No valid file specified")))))))
20129 (user-error "No special environment to edit here")))
20130 (`table
20131 (if (eq (org-element-property :type element) 'table.el)
20132 (org-edit-table.el)
20133 (call-interactively 'org-table-edit-formulas)))
20134 ;; Only Org tables contain `table-row' type elements.
20135 (`table-row (call-interactively 'org-table-edit-formulas))
20136 (`example-block (org-edit-src-code))
20137 (`export-block (org-edit-export-block))
20138 (`fixed-width (org-edit-fixed-width-region))
20139 (`latex-environment (org-edit-latex-environment))
20141 ;; No notable element at point. Though, we may be at a link or
20142 ;; a footnote reference, which are objects. Thus, scan deeper.
20143 (let ((context (org-element-context element)))
20144 (pcase (org-element-type context)
20145 (`footnote-reference (org-edit-footnote-reference))
20146 (`inline-src-block (org-edit-inline-src-code))
20147 (`link (call-interactively #'ffap))
20148 (_ (user-error "No special environment to edit here"))))))))
20150 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20151 (defun org-ctrl-c-ctrl-c (&optional arg)
20152 "Set tags in headline, or update according to changed information at point.
20154 This command does many different things, depending on context:
20156 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20157 this is what we do.
20159 - If the cursor is on a statistics cookie, update it.
20161 - If the cursor is in a headline, prompt for tags and insert them
20162 into the current line, aligned to `org-tags-column'. When called
20163 with prefix arg, realign all tags in the current buffer.
20165 - If the cursor is in one of the special #+KEYWORD lines, this
20166 triggers scanning the buffer for these lines and updating the
20167 information.
20169 - If the cursor is inside a table, realign the table. This command
20170 works even if the automatic table editor has been turned off.
20172 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20173 the entire table.
20175 - If the cursor is at a footnote reference or definition, jump to
20176 the corresponding definition or references, respectively.
20178 - If the cursor is a the beginning of a dynamic block, update it.
20180 - If the current buffer is a capture buffer, close note and file it.
20182 - If the cursor is on a <<<target>>>, update radio targets and
20183 corresponding links in this buffer.
20185 - If the cursor is on a numbered item in a plain list, renumber the
20186 ordered list.
20188 - If the cursor is on a checkbox, toggle it.
20190 - If the cursor is on a code block, evaluate it. The variable
20191 `org-confirm-babel-evaluate' can be used to control prompting
20192 before code block evaluation, by default every code block
20193 evaluation requires confirmation. Code block evaluation can be
20194 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20195 (interactive "P")
20196 (cond
20197 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20198 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20199 (org-remove-occur-highlights)
20200 (message "Temporary highlights/overlays removed from current buffer"))
20201 ((and (local-variable-p 'org-finish-function)
20202 (fboundp org-finish-function))
20203 (funcall org-finish-function))
20204 ((org-babel-hash-at-point))
20205 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20207 (let* ((context
20208 (org-element-lineage
20209 (org-element-context)
20210 ;; Limit to supported contexts.
20211 '(babel-call clock dynamic-block footnote-definition
20212 footnote-reference inline-babel-call inline-src-block
20213 inlinetask item keyword node-property paragraph
20214 plain-list planning property-drawer radio-target
20215 src-block statistics-cookie table table-cell table-row
20216 timestamp)
20218 (type (org-element-type context)))
20219 ;; For convenience: at the first line of a paragraph on the same
20220 ;; line as an item, apply function on that item instead.
20221 (when (eq type 'paragraph)
20222 (let ((parent (org-element-property :parent context)))
20223 (when (and (eq (org-element-type parent) 'item)
20224 (= (line-beginning-position)
20225 (org-element-property :begin parent)))
20226 (setq context parent)
20227 (setq type 'item))))
20228 ;; Act according to type of element or object at point.
20230 ;; Do nothing on a blank line, except if it is contained in
20231 ;; a src block. Hence, we first check if point is in such
20232 ;; a block and then if it is at a blank line.
20233 (pcase type
20234 ((or `inline-src-block `src-block)
20235 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20236 (org-babel-eval-wipe-error-buffer)
20237 (org-babel-execute-src-block
20238 current-prefix-arg (org-babel-get-src-block-info nil context))))
20239 ((guard (org-match-line "[ \t]*$"))
20240 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20241 (user-error
20242 (substitute-command-keys
20243 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20244 ((or `babel-call `inline-babel-call)
20245 (let ((info (org-babel-lob-get-info context)))
20246 (when info (org-babel-execute-src-block nil info))))
20247 (`clock (org-clock-update-time-maybe))
20248 (`dynamic-block
20249 (save-excursion
20250 (goto-char (org-element-property :post-affiliated context))
20251 (org-update-dblock)))
20252 (`footnote-definition
20253 (goto-char (org-element-property :post-affiliated context))
20254 (call-interactively 'org-footnote-action))
20255 (`footnote-reference (call-interactively #'org-footnote-action))
20256 ((or `headline `inlinetask)
20257 (save-excursion (goto-char (org-element-property :begin context))
20258 (call-interactively #'org-set-tags)))
20259 (`item
20260 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20261 ;; unconditionally, whereas `C-u' will toggle its presence.
20262 ;; Without a universal argument, if the item has a checkbox,
20263 ;; toggle it. Otherwise repair the list.
20264 (let* ((box (org-element-property :checkbox context))
20265 (struct (org-element-property :structure context))
20266 (old-struct (copy-tree struct))
20267 (parents (org-list-parents-alist struct))
20268 (prevs (org-list-prevs-alist struct))
20269 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20270 (org-list-set-checkbox
20271 (org-element-property :begin context) struct
20272 (cond ((equal arg '(16)) "[-]")
20273 ((and (not box) (equal arg '(4))) "[ ]")
20274 ((or (not box) (equal arg '(4))) nil)
20275 ((eq box 'on) "[ ]")
20276 (t "[X]")))
20277 ;; Mimic `org-list-write-struct' but with grabbing a return
20278 ;; value from `org-list-struct-fix-box'.
20279 (org-list-struct-fix-ind struct parents 2)
20280 (org-list-struct-fix-item-end struct)
20281 (org-list-struct-fix-bul struct prevs)
20282 (org-list-struct-fix-ind struct parents)
20283 (let ((block-item
20284 (org-list-struct-fix-box struct parents prevs orderedp)))
20285 (if (and box (equal struct old-struct))
20286 (if (equal arg '(16))
20287 (message "Checkboxes already reset")
20288 (user-error "Cannot toggle this checkbox: %s"
20289 (if (eq box 'on)
20290 "all subitems checked"
20291 "unchecked subitems")))
20292 (org-list-struct-apply-struct struct old-struct)
20293 (org-update-checkbox-count-maybe))
20294 (when block-item
20295 (message "Checkboxes were removed due to empty box at line %d"
20296 (org-current-line block-item))))))
20297 (`keyword
20298 (let ((org-inhibit-startup-visibility-stuff t)
20299 (org-startup-align-all-tables nil))
20300 (when (boundp 'org-table-coordinate-overlays)
20301 (mapc #'delete-overlay org-table-coordinate-overlays)
20302 (setq org-table-coordinate-overlays nil))
20303 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20304 (message "Local setup has been refreshed"))
20305 (`plain-list
20306 ;; At a plain list, with a double C-u argument, set
20307 ;; checkboxes of each item to "[-]", whereas a single one
20308 ;; will toggle their presence according to the state of the
20309 ;; first item in the list. Without an argument, repair the
20310 ;; list.
20311 (let* ((begin (org-element-property :contents-begin context))
20312 (struct (org-element-property :structure context))
20313 (old-struct (copy-tree struct))
20314 (first-box (save-excursion
20315 (goto-char begin)
20316 (looking-at org-list-full-item-re)
20317 (match-string-no-properties 3)))
20318 (new-box (cond ((equal arg '(16)) "[-]")
20319 ((equal arg '(4)) (unless first-box "[ ]"))
20320 ((equal first-box "[X]") "[ ]")
20321 (t "[X]"))))
20322 (cond
20323 (arg
20324 (dolist (pos
20325 (org-list-get-all-items
20326 begin struct (org-list-prevs-alist struct)))
20327 (org-list-set-checkbox pos struct new-box)))
20328 ((and first-box (eq (point) begin))
20329 ;; For convenience, when point is at bol on the first
20330 ;; item of the list and no argument is provided, simply
20331 ;; toggle checkbox of that item, if any.
20332 (org-list-set-checkbox begin struct new-box)))
20333 (org-list-write-struct
20334 struct (org-list-parents-alist struct) old-struct)
20335 (org-update-checkbox-count-maybe)))
20336 ((or `property-drawer `node-property)
20337 (call-interactively #'org-property-action))
20338 (`radio-target
20339 (call-interactively #'org-update-radio-target-regexp))
20340 (`statistics-cookie
20341 (call-interactively #'org-update-statistics-cookies))
20342 ((or `table `table-cell `table-row)
20343 ;; At a table, recalculate every field and align it. Also
20344 ;; send the table if necessary. If the table has
20345 ;; a `table.el' type, just give up. At a table row or cell,
20346 ;; maybe recalculate line but always align table.
20347 (if (eq (org-element-property :type context) 'table.el)
20348 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20349 Use `\\[org-edit-special]' to edit table.el tables"))
20350 (if (or (eq type 'table)
20351 ;; Check if point is at a TBLFM line.
20352 (and (eq type 'table-row)
20353 (= (point) (org-element-property :end context))))
20354 (save-excursion
20355 (if (org-at-TBLFM-p)
20356 (progn (require 'org-table)
20357 (org-table-calc-current-TBLFM))
20358 (goto-char (org-element-property :contents-begin context))
20359 (org-call-with-arg 'org-table-recalculate (or arg t))
20360 (orgtbl-send-table 'maybe)))
20361 (org-table-maybe-eval-formula)
20362 (cond (arg (call-interactively #'org-table-recalculate))
20363 ((org-table-maybe-recalculate-line))
20364 (t (org-table-align))))))
20365 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20366 (org-timestamp-change 0 'day))
20367 ((and `nil (guard (org-at-heading-p)))
20368 ;; When point is on an unsupported object type, we can miss
20369 ;; the fact that it also is at a heading. Handle it here.
20370 (call-interactively #'org-set-tags))
20371 ((guard
20372 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20374 (user-error
20375 (substitute-command-keys
20376 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20378 (defun org-mode-restart ()
20379 (interactive)
20380 (let ((indent-status (bound-and-true-p org-indent-mode)))
20381 (funcall major-mode)
20382 (hack-local-variables)
20383 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20384 (org-indent-mode -1))
20385 (org-reset-file-cache))
20386 (message "%s restarted" major-mode))
20388 (defun org-kill-note-or-show-branches ()
20389 "Abort storing current note, or call `outline-show-branches'."
20390 (interactive)
20391 (if (not org-finish-function)
20392 (progn
20393 (outline-hide-subtree)
20394 (call-interactively 'outline-show-branches))
20395 (let ((org-note-abort t))
20396 (funcall org-finish-function))))
20398 (defun org-delete-indentation (&optional arg)
20399 "Join current line to previous and fix whitespace at join.
20401 If previous line is a headline add to headline title. Otherwise
20402 the function calls `delete-indentation'.
20404 With a non-nil optional argument, join it to the following one."
20405 (interactive "*P")
20406 (if (save-excursion
20407 (beginning-of-line (if arg 1 0))
20408 (let ((case-fold-search nil))
20409 (looking-at org-complex-heading-regexp)))
20410 ;; At headline.
20411 (let ((tags-column (when (match-beginning 5)
20412 (save-excursion (goto-char (match-beginning 5))
20413 (current-column))))
20414 (string (concat " " (progn (when arg (forward-line 1))
20415 (org-trim (delete-and-extract-region
20416 (line-beginning-position)
20417 (line-end-position)))))))
20418 (unless (bobp) (delete-region (point) (1- (point))))
20419 (goto-char (or (match-end 4)
20420 (match-beginning 5)
20421 (match-end 0)))
20422 (skip-chars-backward " \t")
20423 (save-excursion (insert string))
20424 ;; Adjust alignment of tags.
20425 (cond
20426 ((not tags-column)) ;no tags
20427 (org-auto-align-tags (org-set-tags nil t))
20428 (t (org--align-tags-here tags-column)))) ;preserve tags column
20429 (delete-indentation arg)))
20431 (defun org-open-line (n)
20432 "Insert a new row in tables, call `open-line' elsewhere.
20433 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20434 As a special case, when a document starts with a table, allow to
20435 call `open-line' on the very first character."
20436 (interactive "*p")
20437 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20438 (org-table-insert-row)
20439 (open-line n)))
20441 (defun org-return (&optional indent)
20442 "Goto next table row or insert a newline.
20444 Calls `org-table-next-row' or `newline', depending on context.
20446 When optional INDENT argument is non-nil, call
20447 `newline-and-indent' instead of `newline'.
20449 When `org-return-follows-link' is non-nil and point is on
20450 a timestamp or a link, call `org-open-at-point'. However, it
20451 will not happen if point is in a table or on a \"dead\"
20452 object (e.g., within a comment). In these case, you need to use
20453 `org-open-at-point' directly."
20454 (interactive)
20455 (let ((context (if org-return-follows-link (org-element-context)
20456 (org-element-at-point))))
20457 (cond
20458 ;; In a table, call `org-table-next-row'. However, before first
20459 ;; column or after last one, split the table.
20460 ((or (and (eq (org-element-type context) 'table)
20461 (>= (point) (org-element-property :contents-begin context))
20462 (< (point) (org-element-property :contents-end context)))
20463 (org-element-lineage context '(table-row table-cell) t))
20464 (if (or (looking-at-p "[ \t]*$")
20465 (save-excursion (skip-chars-backward " \t") (bolp)))
20466 (insert "\n")
20467 (org-table-justify-field-maybe)
20468 (call-interactively #'org-table-next-row)))
20469 ;; On a link or a timestamp, call `org-open-at-point' if
20470 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20471 ;; locations, e.g., in a comment, as `org-open-at-point'.
20472 ((and org-return-follows-link
20473 (or (org-in-regexp org-ts-regexp-both nil t)
20474 (org-in-regexp org-tsr-regexp-both nil t)
20475 (org-in-regexp org-any-link-re nil t)))
20476 (call-interactively #'org-open-at-point))
20477 ;; Insert newline in heading, but preserve tags.
20478 ((and (not (bolp))
20479 (save-excursion (beginning-of-line)
20480 (let ((case-fold-search nil))
20481 (looking-at org-complex-heading-regexp))))
20482 ;; At headline. Split line. However, if point is on keyword,
20483 ;; priority cookie or tags, do not break any of them: add
20484 ;; a newline after the headline instead.
20485 (let ((tags-column (and (match-beginning 5)
20486 (save-excursion (goto-char (match-beginning 5))
20487 (current-column))))
20488 (string
20489 (when (and (match-end 4) (org-point-in-group (point) 4))
20490 (delete-and-extract-region (point) (match-end 4)))))
20491 ;; Adjust tag alignment.
20492 (cond
20493 ((not (and tags-column string)))
20494 (org-auto-align-tags (org-set-tags nil t))
20495 (t (org--align-tags-here tags-column))) ;preserve tags column
20496 (end-of-line)
20497 (org-show-entry)
20498 (if indent (newline-and-indent) (newline))
20499 (when string (save-excursion (insert (org-trim string))))))
20500 ;; In a list, make sure indenting keeps trailing text within.
20501 ((and indent
20502 (not (eolp))
20503 (org-element-lineage context '(item)))
20504 (let ((trailing-data
20505 (delete-and-extract-region (point) (line-end-position))))
20506 (newline-and-indent)
20507 (save-excursion (insert trailing-data))))
20508 (t (if indent (newline-and-indent) (newline))))))
20510 (defun org-return-indent ()
20511 "Goto next table row or insert a newline and indent.
20512 Calls `org-table-next-row' or `newline-and-indent', depending on
20513 context. See the individual commands for more information."
20514 (interactive)
20515 (org-return t))
20517 (defun org-ctrl-c-tab (&optional _arg)
20518 "Toggle columns width in a table, or show children.
20519 Call `org-table-toggle-column-width' if point is in a table.
20520 Otherwise, call `org-show-children'."
20521 (interactive "p")
20522 (call-interactively
20523 (if (org-at-table-p) #'org-table-toggle-column-width
20524 #'org-show-children)))
20526 (defun org-ctrl-c-star ()
20527 "Compute table, or change heading status of lines.
20528 Calls `org-table-recalculate' or `org-toggle-heading',
20529 depending on context."
20530 (interactive)
20531 (cond
20532 ((org-at-table-p)
20533 (call-interactively 'org-table-recalculate))
20535 ;; Convert all lines in region to list items
20536 (call-interactively 'org-toggle-heading))))
20538 (defun org-ctrl-c-minus ()
20539 "Insert separator line in table or modify bullet status of line.
20540 Also turns a plain line or a region of lines into list items.
20541 Calls `org-table-insert-hline', `org-toggle-item', or
20542 `org-cycle-list-bullet', depending on context."
20543 (interactive)
20544 (cond
20545 ((org-at-table-p)
20546 (call-interactively 'org-table-insert-hline))
20547 ((org-region-active-p)
20548 (call-interactively 'org-toggle-item))
20549 ((org-in-item-p)
20550 (call-interactively 'org-cycle-list-bullet))
20552 (call-interactively 'org-toggle-item))))
20554 (defun org-toggle-heading (&optional nstars)
20555 "Convert headings to normal text, or items or text to headings.
20556 If there is no active region, only convert the current line.
20558 With a `\\[universal-argument]' prefix, convert the whole list at
20559 point into heading.
20561 In a region:
20563 - If the first non blank line is a headline, remove the stars
20564 from all headlines in the region.
20566 - If it is a normal line, turn each and every normal line (i.e.,
20567 not an heading or an item) in the region into headings. If you
20568 want to convert only the first line of this region, use one
20569 universal prefix argument.
20571 - If it is a plain list item, turn all plain list items into headings.
20573 When converting a line into a heading, the number of stars is chosen
20574 such that the lines become children of the current entry. However,
20575 when a numeric prefix argument is given, its value determines the
20576 number of stars to add."
20577 (interactive "P")
20578 (let ((skip-blanks
20579 (function
20580 ;; Return beginning of first non-blank line, starting from
20581 ;; line at POS.
20582 (lambda (pos)
20583 (save-excursion
20584 (goto-char pos)
20585 (while (org-at-comment-p) (forward-line))
20586 (skip-chars-forward " \r\t\n")
20587 (point-at-bol)))))
20588 beg end toggled)
20589 ;; Determine boundaries of changes. If a universal prefix has
20590 ;; been given, put the list in a region. If region ends at a bol,
20591 ;; do not consider the last line to be in the region.
20593 (when (and current-prefix-arg (org-at-item-p))
20594 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20595 (org-mark-element))
20597 (if (org-region-active-p)
20598 (setq beg (funcall skip-blanks (region-beginning))
20599 end (copy-marker (save-excursion
20600 (goto-char (region-end))
20601 (if (bolp) (point) (point-at-eol)))))
20602 (setq beg (funcall skip-blanks (point-at-bol))
20603 end (copy-marker (point-at-eol))))
20604 ;; Ensure inline tasks don't count as headings.
20605 (org-with-limited-levels
20606 (save-excursion
20607 (goto-char beg)
20608 (cond
20609 ;; Case 1. Started at an heading: de-star headings.
20610 ((org-at-heading-p)
20611 (while (< (point) end)
20612 (when (org-at-heading-p t)
20613 (looking-at org-outline-regexp) (replace-match "")
20614 (setq toggled t))
20615 (forward-line)))
20616 ;; Case 2. Started at an item: change items into headlines.
20617 ;; One star will be added by `org-list-to-subtree'.
20618 ((org-at-item-p)
20619 (while (< (point) end)
20620 (when (org-at-item-p)
20621 ;; Pay attention to cases when region ends before list.
20622 (let* ((struct (org-list-struct))
20623 (list-end
20624 (min (org-list-get-bottom-point struct) (1+ end))))
20625 (save-restriction
20626 (narrow-to-region (point) list-end)
20627 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20628 (setq toggled t))
20629 (forward-line)))
20630 ;; Case 3. Started at normal text: make every line an heading,
20631 ;; skipping headlines and items.
20632 (t (let* ((stars
20633 (make-string
20634 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20635 (add-stars
20636 (cond (nstars "") ; stars from prefix only
20637 ((equal stars "") "*") ; before first heading
20638 (org-odd-levels-only "**") ; inside heading, odd
20639 (t "*"))) ; inside heading, oddeven
20640 (rpl (concat stars add-stars " "))
20641 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20642 (while (< (point) (if (equal nstars '(4)) lend end))
20643 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20644 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20645 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20646 (forward-line)))))))
20647 (unless toggled (message "Cannot toggle heading from here"))))
20649 (defun org-meta-return (&optional arg)
20650 "Insert a new heading or wrap a region in a table.
20651 Calls `org-insert-heading', `org-insert-item' or
20652 `org-table-wrap-region', depending on context. When called with
20653 an argument, unconditionally call `org-insert-heading'."
20654 (interactive "P")
20655 (org-check-before-invisible-edit 'insert)
20656 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20657 (call-interactively (cond (arg #'org-insert-heading)
20658 ((org-at-table-p) #'org-table-wrap-region)
20659 ((org-in-item-p) #'org-insert-item)
20660 (t #'org-insert-heading)))))
20662 ;;; Menu entries
20664 (defsubst org-in-subtree-not-table-p ()
20665 "Are we in a subtree and not in a table?"
20666 (and (not (org-before-first-heading-p))
20667 (not (org-at-table-p))))
20669 ;; Define the Org mode menus
20670 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20671 '("Tbl"
20672 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20673 ["Next Field" org-cycle (org-at-table-p)]
20674 ["Previous Field" org-shifttab (org-at-table-p)]
20675 ["Next Row" org-return (org-at-table-p)]
20676 "--"
20677 ["Blank Field" org-table-blank-field (org-at-table-p)]
20678 ["Edit Field" org-table-edit-field (org-at-table-p)]
20679 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20680 "--"
20681 ("Column"
20682 ["Move Column Left" org-metaleft (org-at-table-p)]
20683 ["Move Column Right" org-metaright (org-at-table-p)]
20684 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20685 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20686 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20687 ("Row"
20688 ["Move Row Up" org-metaup (org-at-table-p)]
20689 ["Move Row Down" org-metadown (org-at-table-p)]
20690 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20691 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20692 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20693 "--"
20694 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20695 ("Rectangle"
20696 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20697 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20698 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20699 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20700 "--"
20701 ("Calculate"
20702 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20703 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20704 ["Edit Formulas" org-edit-special (org-at-table-p)]
20705 "--"
20706 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20707 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20708 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20709 "--"
20710 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20711 "--"
20712 ["Sum Column/Rectangle" org-table-sum
20713 (or (org-at-table-p) (org-region-active-p))]
20714 ["Which Column?" org-table-current-column (org-at-table-p)])
20715 ["Debug Formulas"
20716 org-table-toggle-formula-debugger
20717 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20718 ["Show Col/Row Numbers"
20719 org-table-toggle-coordinate-overlays
20720 :style toggle
20721 :selected (bound-and-true-p org-table-overlay-coordinates)]
20722 "--"
20723 ["Create" org-table-create (not (org-at-table-p))]
20724 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20725 ["Import from File" org-table-import (not (org-at-table-p))]
20726 ["Export to File" org-table-export (org-at-table-p)]
20727 "--"
20728 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20729 "--"
20730 ("Plot"
20731 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20732 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20734 (easy-menu-define org-org-menu org-mode-map "Org menu"
20735 '("Org"
20736 ("Show/Hide"
20737 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20738 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20739 ["Sparse Tree..." org-sparse-tree t]
20740 ["Reveal Context" org-reveal t]
20741 ["Show All" outline-show-all t]
20742 "--"
20743 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20744 "--"
20745 ["New Heading" org-insert-heading t]
20746 ("Navigate Headings"
20747 ["Up" outline-up-heading t]
20748 ["Next" outline-next-visible-heading t]
20749 ["Previous" outline-previous-visible-heading t]
20750 ["Next Same Level" outline-forward-same-level t]
20751 ["Previous Same Level" outline-backward-same-level t]
20752 "--"
20753 ["Jump" org-goto t])
20754 ("Edit Structure"
20755 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20756 "--"
20757 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20758 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20759 "--"
20760 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20761 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20762 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20763 "--"
20764 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20765 "--"
20766 ["Copy visible text" org-copy-visible t]
20767 "--"
20768 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20769 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20770 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20771 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20772 "--"
20773 ["Sort Region/Children" org-sort t]
20774 "--"
20775 ["Convert to odd levels" org-convert-to-odd-levels t]
20776 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20777 ("Editing"
20778 ["Emphasis..." org-emphasize t]
20779 ["Edit Source Example" org-edit-special t]
20780 "--"
20781 ["Footnote new/jump" org-footnote-action t]
20782 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20783 ("Archive"
20784 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20785 "--"
20786 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20787 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20788 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20790 "--"
20791 ("Hyperlinks"
20792 ["Store Link (Global)" org-store-link t]
20793 ["Find existing link to here" org-occur-link-in-agenda-files t]
20794 ["Insert Link" org-insert-link t]
20795 ["Follow Link" org-open-at-point t]
20796 "--"
20797 ["Next link" org-next-link t]
20798 ["Previous link" org-previous-link t]
20799 "--"
20800 ["Descriptive Links"
20801 org-toggle-link-display
20802 :style radio
20803 :selected org-descriptive-links
20805 ["Literal Links"
20806 org-toggle-link-display
20807 :style radio
20808 :selected (not org-descriptive-links)])
20809 "--"
20810 ("TODO Lists"
20811 ["TODO/DONE/-" org-todo t]
20812 ("Select keyword"
20813 ["Next keyword" org-shiftright (org-at-heading-p)]
20814 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20815 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20816 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20817 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20818 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20819 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20820 "--"
20821 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20822 :selected org-enforce-todo-dependencies :style toggle :active t]
20823 "Settings for tree at point"
20824 ["Do Children sequentially" org-toggle-ordered-property :style radio
20825 :selected (org-entry-get nil "ORDERED")
20826 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20827 ["Do Children parallel" org-toggle-ordered-property :style radio
20828 :selected (not (org-entry-get nil "ORDERED"))
20829 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20830 "--"
20831 ["Set Priority" org-priority t]
20832 ["Priority Up" org-shiftup t]
20833 ["Priority Down" org-shiftdown t]
20834 "--"
20835 ["Get news from all feeds" org-feed-update-all t]
20836 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20837 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20838 ("TAGS and Properties"
20839 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20840 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20841 "--"
20842 ["Set property" org-set-property (not (org-before-first-heading-p))]
20843 ["Column view of properties" org-columns t]
20844 ["Insert Column View DBlock" org-columns-insert-dblock t])
20845 ("Dates and Scheduling"
20846 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20847 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20848 ("Change Date"
20849 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20850 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20851 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20852 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20853 ["Compute Time Range" org-evaluate-time-range t]
20854 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20855 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20856 "--"
20857 ["Custom time format" org-toggle-time-stamp-overlays
20858 :style radio :selected org-display-custom-times]
20859 "--"
20860 ["Goto Calendar" org-goto-calendar t]
20861 ["Date from Calendar" org-date-from-calendar t]
20862 "--"
20863 ["Start/Restart Timer" org-timer-start t]
20864 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20865 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20866 ["Insert Timer String" org-timer t]
20867 ["Insert Timer Item" org-timer-item t])
20868 ("Logging work"
20869 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20870 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20871 ["Clock out" org-clock-out t]
20872 ["Clock cancel" org-clock-cancel t]
20873 "--"
20874 ["Mark as default task" org-clock-mark-default-task t]
20875 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20876 ["Goto running clock" org-clock-goto t]
20877 "--"
20878 ["Display times" org-clock-display t]
20879 ["Create clock table" org-clock-report t]
20880 "--"
20881 ["Record DONE time"
20882 (progn (setq org-log-done (not org-log-done))
20883 (message "Switching to %s will %s record a timestamp"
20884 (car org-done-keywords)
20885 (if org-log-done "automatically" "not")))
20886 :style toggle :selected org-log-done])
20887 "--"
20888 ["Agenda Command..." org-agenda t]
20889 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20890 ("File List for Agenda")
20891 ("Special views current file"
20892 ["TODO Tree" org-show-todo-tree t]
20893 ["Check Deadlines" org-check-deadlines t]
20894 ["Tags/Property tree" org-match-sparse-tree t])
20895 "--"
20896 ["Export/Publish..." org-export-dispatch t]
20897 ("LaTeX"
20898 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20899 :style toggle :selected org-cdlatex-mode]
20900 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20901 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20902 ["Modify math symbol" org-cdlatex-math-modify
20903 (org-inside-LaTeX-fragment-p)]
20904 ["Insert citation" org-reftex-citation t])
20905 "--"
20906 ("MobileOrg"
20907 ["Push Files and Views" org-mobile-push t]
20908 ["Get Captured and Flagged" org-mobile-pull t]
20909 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20910 "--"
20911 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20912 "--"
20913 ("Documentation"
20914 ["Show Version" org-version t]
20915 ["Info Documentation" org-info t])
20916 ("Customize"
20917 ["Browse Org Group" org-customize t]
20918 "--"
20919 ["Expand This Menu" org-create-customize-menu
20920 (fboundp 'customize-menu-create)])
20921 ["Send bug report" org-submit-bug-report t]
20922 "--"
20923 ("Refresh/Reload"
20924 ["Refresh setup current buffer" org-mode-restart t]
20925 ["Reload Org (after update)" org-reload t]
20926 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20929 (defun org-info (&optional node)
20930 "Read documentation for Org in the info system.
20931 With optional NODE, go directly to that node."
20932 (interactive)
20933 (info (format "(org)%s" (or node ""))))
20935 ;;;###autoload
20936 (defun org-submit-bug-report ()
20937 "Submit a bug report on Org via mail.
20939 Don't hesitate to report any problems or inaccurate documentation.
20941 If you don't have setup sending mail from (X)Emacs, please copy the
20942 output buffer into your mail program, as it gives us important
20943 information about your Org version and configuration."
20944 (interactive)
20945 (require 'reporter)
20946 (defvar reporter-prompt-for-summary-p)
20947 (org-load-modules-maybe)
20948 (org-require-autoloaded-modules)
20949 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20950 (reporter-submit-bug-report
20951 "emacs-orgmode@gnu.org"
20952 (org-version nil 'full)
20953 (let (list)
20954 (save-window-excursion
20955 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20956 (delete-other-windows)
20957 (erase-buffer)
20958 (insert "You are about to submit a bug report to the Org mailing list.
20960 We would like to add your full Org and Outline configuration to the
20961 bug report. This greatly simplifies the work of the maintainer and
20962 other experts on the mailing list.
20964 HOWEVER, some variables you have customized may contain private
20965 information. The names of customers, colleagues, or friends, might
20966 appear in the form of file names, tags, todo states, or search strings.
20967 If you answer yes to the prompt, you might want to check and remove
20968 such private information before sending the email.")
20969 (add-text-properties (point-min) (point-max) '(face org-warning))
20970 (when (yes-or-no-p "Include your Org configuration ")
20971 (mapatoms
20972 (lambda (v)
20973 (and (boundp v)
20974 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20975 (or (and (symbol-value v)
20976 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20977 (and
20978 (get v 'custom-type) (get v 'standard-value)
20979 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20980 (push v list)))))
20981 (kill-buffer (get-buffer "*Warn about privacy*"))
20982 list))
20983 nil nil
20984 "Remember to cover the basics, that is, what you expected to happen and
20985 what in fact did happen. You don't know how to make a good report? See
20987 http://orgmode.org/manual/Feedback.html#Feedback
20989 Your bug report will be posted to the Org mailing list.
20990 ------------------------------------------------------------------------")
20991 (save-excursion
20992 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20993 (replace-match "\\1Bug: \\3 [\\2]")))))
20996 (defun org-install-agenda-files-menu ()
20997 (let ((bl (buffer-list)))
20998 (save-excursion
20999 (while bl
21000 (set-buffer (pop bl))
21001 (when (derived-mode-p 'org-mode) (setq bl nil)))
21002 (when (derived-mode-p 'org-mode)
21003 (easy-menu-change
21004 '("Org") "File List for Agenda"
21005 (append
21006 (list
21007 ["Edit File List" (org-edit-agenda-file-list) t]
21008 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21009 ["Remove Current File from List" org-remove-file t]
21010 ["Cycle through agenda files" org-cycle-agenda-files t]
21011 ["Occur in all agenda files" org-occur-in-agenda-files t]
21012 "--")
21013 (mapcar 'org-file-menu-entry
21014 ;; Prevent initialization from failing.
21015 (ignore-errors (org-agenda-files t)))))))))
21017 ;;;; Documentation
21019 (defun org-require-autoloaded-modules ()
21020 (interactive)
21021 (mapc #'require
21022 '(org-agenda org-archive org-attach org-clock org-colview org-id
21023 org-table org-timer)))
21025 ;;;###autoload
21026 (defun org-reload (&optional uncompiled)
21027 "Reload all org lisp files.
21028 With prefix arg UNCOMPILED, load the uncompiled versions."
21029 (interactive "P")
21030 (require 'loadhist)
21031 (let* ((org-dir (org-find-library-dir "org"))
21032 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21033 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21034 (remove-re (format "\\`%s\\'"
21035 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21036 (feats (delete-dups
21037 (mapcar 'file-name-sans-extension
21038 (mapcar 'file-name-nondirectory
21039 (delq nil
21040 (mapcar 'feature-file
21041 features))))))
21042 (lfeat (append
21043 (sort
21044 (setq feats
21045 (delq nil (mapcar
21046 (lambda (f)
21047 (if (and (string-match feature-re f)
21048 (not (string-match remove-re f)))
21049 f nil))
21050 feats)))
21051 'string-lessp)
21052 (list "org-version" "org")))
21053 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21054 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21055 load-uncore load-misses)
21056 (setq load-misses
21057 (delq 't
21058 (mapcar (lambda (f)
21059 (or (org-load-noerror-mustsuffix (concat org-dir f))
21060 (and (string= org-dir contrib-dir)
21061 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21062 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21063 (add-to-list 'load-uncore f 'append)
21066 lfeat)))
21067 (when load-uncore
21068 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21069 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21070 (if load-misses
21071 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21072 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21073 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21075 ;;;###autoload
21076 (defun org-customize ()
21077 "Call the customize function with org as argument."
21078 (interactive)
21079 (org-load-modules-maybe)
21080 (org-require-autoloaded-modules)
21081 (customize-browse 'org))
21083 (defun org-create-customize-menu ()
21084 "Create a full customization menu for Org mode, insert it into the menu."
21085 (interactive)
21086 (org-load-modules-maybe)
21087 (org-require-autoloaded-modules)
21088 (if (fboundp 'customize-menu-create)
21089 (progn
21090 (easy-menu-change
21091 '("Org") "Customize"
21092 `(["Browse Org group" org-customize t]
21093 "--"
21094 ,(customize-menu-create 'org)
21095 ["Set" Custom-set t]
21096 ["Save" Custom-save t]
21097 ["Reset to Current" Custom-reset-current t]
21098 ["Reset to Saved" Custom-reset-saved t]
21099 ["Reset to Standard Settings" Custom-reset-standard t]))
21100 (message "\"Org\"-menu now contains full customization menu"))
21101 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21103 ;;;; Miscellaneous stuff
21105 ;;; Generally useful functions
21107 (defun org-link-display-format (s)
21108 "Replace links in string S with their description.
21109 If there is no description, use the link target."
21110 (save-match-data
21111 (replace-regexp-in-string
21112 org-bracket-link-analytic-regexp
21113 (lambda (m)
21114 (if (match-end 5) (match-string 5 m)
21115 (concat (match-string 1 m) (match-string 3 m))))
21116 s nil t)))
21118 (defun org-toggle-link-display ()
21119 "Toggle the literal or descriptive display of links."
21120 (interactive)
21121 (if org-descriptive-links
21122 (progn (org-remove-from-invisibility-spec '(org-link))
21123 (org-restart-font-lock)
21124 (setq org-descriptive-links nil))
21125 (progn (add-to-invisibility-spec '(org-link))
21126 (org-restart-font-lock)
21127 (setq org-descriptive-links t))))
21129 (defun org-in-clocktable-p ()
21130 "Check if the cursor is in a clocktable."
21131 (let ((pos (point)) start)
21132 (save-excursion
21133 (end-of-line 1)
21134 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21135 (setq start (match-beginning 0))
21136 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21137 (>= (match-end 0) pos)
21138 start))))
21140 (defun org-in-verbatim-emphasis ()
21141 (save-match-data
21142 (and (org-in-regexp org-verbatim-re 2)
21143 (>= (point) (match-beginning 3))
21144 (<= (point) (match-end 4)))))
21146 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21147 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21148 (if (and marker (marker-buffer marker)
21149 (buffer-live-p (marker-buffer marker)))
21150 (progn
21151 (pop-to-buffer-same-window (marker-buffer marker))
21152 (when (or (> marker (point-max)) (< marker (point-min)))
21153 (widen))
21154 (goto-char marker)
21155 (org-show-context 'org-goto))
21156 (if bookmark
21157 (bookmark-jump bookmark)
21158 (error "Cannot find location"))))
21160 (defun org-quote-csv-field (s)
21161 "Quote field for inclusion in CSV material."
21162 (if (string-match "[\",]" s)
21163 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21166 (defun org-force-self-insert (N)
21167 "Needed to enforce self-insert under remapping."
21168 (interactive "p")
21169 (self-insert-command N))
21171 (defun org-get-indentation (&optional line)
21172 "Get the indentation of the current line, interpreting tabs.
21173 When LINE is given, assume it represents a line and compute its indentation."
21174 (if line
21175 (when (string-match "^ *" (org-remove-tabs line))
21176 (match-end 0))
21177 (save-excursion
21178 (beginning-of-line 1)
21179 (skip-chars-forward " \t")
21180 (current-column))))
21182 (defun org-get-string-indentation (s)
21183 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21184 (let ((n -1) (i 0) (w tab-width) c)
21185 (catch 'exit
21186 (while (< (setq n (1+ n)) (length s))
21187 (setq c (aref s n))
21188 (cond ((= c ?\ ) (setq i (1+ i)))
21189 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21190 (t (throw 'exit t)))))
21193 (defun org-fix-indentation (line ind)
21194 "Fix indentation in LINE.
21195 IND is a cons cell with target and minimum indentation.
21196 If the current indentation in LINE is smaller than the minimum,
21197 leave it alone. If it is larger than ind, set it to the target."
21198 (let* ((l (org-remove-tabs line))
21199 (i (org-get-indentation l))
21200 (i1 (car ind)) (i2 (cdr ind)))
21201 (when (>= i i2) (setq l (substring line i2)))
21202 (if (> i1 0)
21203 (concat (make-string i1 ?\ ) l)
21204 l)))
21206 (defun org-fill-template (template alist)
21207 "Find each %key of ALIST in TEMPLATE and replace it."
21208 (let ((case-fold-search nil))
21209 (dolist (entry (sort (copy-sequence alist)
21210 (lambda (a b) (< (length (car a)) (length (car b))))))
21211 (setq template
21212 (replace-regexp-in-string
21213 (concat "%" (regexp-quote (car entry)))
21214 (or (cdr entry) "") template t t)))
21215 template))
21217 (defun org-quote-vert (s)
21218 "Replace \"|\" with \"\\vert\"."
21219 (while (string-match "|" s)
21220 (setq s (replace-match "\\vert" t t s)))
21223 (defun org-uuidgen-p (s)
21224 "Is S an ID created by UUIDGEN?"
21225 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21227 (defun org-in-src-block-p (&optional inside)
21228 "Whether point is in a code source block.
21229 When INSIDE is non-nil, don't consider we are within a src block
21230 when point is at #+BEGIN_SRC or #+END_SRC."
21231 (let ((case-fold-search t))
21232 (or (and (eq (get-char-property (point) 'src-block) t))
21233 (and (not inside)
21234 (save-match-data
21235 (save-excursion
21236 (beginning-of-line)
21237 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21239 (defun org-context ()
21240 "Return a list of contexts of the current cursor position.
21241 If several contexts apply, all are returned.
21242 Each context entry is a list with a symbol naming the context, and
21243 two positions indicating start and end of the context. Possible
21244 contexts are:
21246 :headline anywhere in a headline
21247 :headline-stars on the leading stars in a headline
21248 :todo-keyword on a TODO keyword (including DONE) in a headline
21249 :tags on the TAGS in a headline
21250 :priority on the priority cookie in a headline
21251 :item on the first line of a plain list item
21252 :item-bullet on the bullet/number of a plain list item
21253 :checkbox on the checkbox in a plain list item
21254 :table in an Org table
21255 :table-special on a special filed in a table
21256 :table-table in a table.el table
21257 :clocktable in a clocktable
21258 :src-block in a source block
21259 :link on a hyperlink
21260 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21261 :target on a <<target>>
21262 :radio-target on a <<<radio-target>>>
21263 :latex-fragment on a LaTeX fragment
21264 :latex-preview on a LaTeX fragment with overlaid preview image
21266 This function expects the position to be visible because it uses font-lock
21267 faces as a help to recognize the following contexts: :table-special, :link,
21268 and :keyword."
21269 (let* ((f (get-text-property (point) 'face))
21270 (faces (if (listp f) f (list f)))
21271 (case-fold-search t)
21272 (p (point)) clist o)
21273 ;; First the large context
21274 (cond
21275 ((org-at-heading-p t)
21276 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21277 (when (progn
21278 (beginning-of-line 1)
21279 (looking-at org-todo-line-tags-regexp))
21280 (push (org-point-in-group p 1 :headline-stars) clist)
21281 (push (org-point-in-group p 2 :todo-keyword) clist)
21282 (push (org-point-in-group p 4 :tags) clist))
21283 (goto-char p)
21284 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21285 (when (looking-at "\\[#[A-Z0-9]\\]")
21286 (push (org-point-in-group p 0 :priority) clist)))
21288 ((org-at-item-p)
21289 (push (org-point-in-group p 2 :item-bullet) clist)
21290 (push (list :item (point-at-bol)
21291 (save-excursion (org-end-of-item) (point)))
21292 clist)
21293 (and (org-at-item-checkbox-p)
21294 (push (org-point-in-group p 0 :checkbox) clist)))
21296 ((org-at-table-p)
21297 (push (list :table (org-table-begin) (org-table-end)) clist)
21298 (when (memq 'org-formula faces)
21299 (push (list :table-special
21300 (previous-single-property-change p 'face)
21301 (next-single-property-change p 'face)) clist)))
21302 ((org-at-table-p 'any)
21303 (push (list :table-table) clist)))
21304 (goto-char p)
21306 (let ((case-fold-search t))
21307 ;; New the "medium" contexts: clocktables, source blocks
21308 (cond ((org-in-clocktable-p)
21309 (push (list :clocktable
21310 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21311 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21312 (match-beginning 1))
21313 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21314 (match-end 0))) clist))
21315 ((org-in-src-block-p)
21316 (push (list :src-block
21317 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21318 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21319 (match-beginning 1))
21320 (and (search-forward "#+END_SRC" nil t)
21321 (match-beginning 0))) clist))))
21322 (goto-char p)
21324 ;; Now the small context
21325 (cond
21326 ((org-at-timestamp-p)
21327 (push (org-point-in-group p 0 :timestamp) clist))
21328 ((memq 'org-link faces)
21329 (push (list :link
21330 (previous-single-property-change p 'face)
21331 (next-single-property-change p 'face)) clist))
21332 ((memq 'org-special-keyword faces)
21333 (push (list :keyword
21334 (previous-single-property-change p 'face)
21335 (next-single-property-change p 'face)) clist))
21336 ((org-at-target-p)
21337 (push (org-point-in-group p 0 :target) clist)
21338 (goto-char (1- (match-beginning 0)))
21339 (when (looking-at org-radio-target-regexp)
21340 (push (org-point-in-group p 0 :radio-target) clist))
21341 (goto-char p))
21342 ((setq o (cl-some
21343 (lambda (o)
21344 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21346 (overlays-at (point))))
21347 (push (list :latex-fragment
21348 (overlay-start o) (overlay-end o)) clist)
21349 (push (list :latex-preview
21350 (overlay-start o) (overlay-end o)) clist))
21351 ((org-inside-LaTeX-fragment-p)
21352 ;; FIXME: positions wrong.
21353 (push (list :latex-fragment (point) (point)) clist)))
21355 (setq clist (nreverse (delq nil clist)))
21356 clist))
21358 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21359 "Non-nil when point is between matches of START-RE and END-RE.
21361 Also return a non-nil value when point is on one of the matches.
21363 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21364 buffer positions. Default values are the positions of headlines
21365 surrounding the point.
21367 The functions returns a cons cell whose car (resp. cdr) is the
21368 position before START-RE (resp. after END-RE)."
21369 (save-match-data
21370 (let ((pos (point))
21371 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21372 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21373 beg end)
21374 (save-excursion
21375 ;; Point is on a block when on START-RE or if START-RE can be
21376 ;; found before it...
21377 (and (or (org-in-regexp start-re)
21378 (re-search-backward start-re limit-up t))
21379 (setq beg (match-beginning 0))
21380 ;; ... and END-RE after it...
21381 (goto-char (match-end 0))
21382 (re-search-forward end-re limit-down t)
21383 (> (setq end (match-end 0)) pos)
21384 ;; ... without another START-RE in-between.
21385 (goto-char (match-beginning 0))
21386 (not (re-search-backward start-re (1+ beg) t))
21387 ;; Return value.
21388 (cons beg end))))))
21390 (defun org-in-block-p (names)
21391 "Non-nil when point belongs to a block whose name belongs to NAMES.
21393 NAMES is a list of strings containing names of blocks.
21395 Return first block name matched, or nil. Beware that in case of
21396 nested blocks, the returned name may not belong to the closest
21397 block from point."
21398 (save-match-data
21399 (catch 'exit
21400 (let ((case-fold-search t)
21401 (lim-up (save-excursion (outline-previous-heading)))
21402 (lim-down (save-excursion (outline-next-heading))))
21403 (dolist (name names)
21404 (let ((n (regexp-quote name)))
21405 (when (org-between-regexps-p
21406 (concat "^[ \t]*#\\+begin_" n)
21407 (concat "^[ \t]*#\\+end_" n)
21408 lim-up lim-down)
21409 (throw 'exit n)))))
21410 nil)))
21412 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21413 "Call `multi-occur' with buffers for all agenda files."
21414 (interactive "sOrg-files matching: ")
21415 (let* ((files (org-agenda-files))
21416 (tnames (mapcar #'file-truename files))
21417 (extra org-agenda-text-search-extra-files))
21418 (when (eq (car extra) 'agenda-archives)
21419 (setq extra (cdr extra))
21420 (setq files (org-add-archive-files files)))
21421 (dolist (f extra)
21422 (unless (member (file-truename f) tnames)
21423 (unless (member f files) (setq files (append files (list f))))
21424 (setq tnames (append tnames (list (file-truename f))))))
21425 (multi-occur
21426 (mapcar (lambda (x)
21427 (with-current-buffer
21428 ;; FIXME: Why not just (find-file-noselect x)?
21429 ;; Is it to avoid the "revert buffer" prompt?
21430 (or (get-file-buffer x) (find-file-noselect x))
21431 (widen)
21432 (current-buffer)))
21433 files)
21434 regexp)))
21436 (add-hook 'occur-mode-find-occurrence-hook
21437 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21439 (defun org-occur-link-in-agenda-files ()
21440 "Create a link and search for it in the agendas.
21441 The link is not stored in `org-stored-links', it is just created
21442 for the search purpose."
21443 (interactive)
21444 (let ((link (condition-case nil
21445 (org-store-link nil)
21446 (error "Unable to create a link to here"))))
21447 (org-occur-in-agenda-files (regexp-quote link))))
21449 (defun org-back-over-empty-lines ()
21450 "Move backwards over whitespace, to the beginning of the first empty line.
21451 Returns the number of empty lines passed."
21452 (let ((pos (point)))
21453 (if (cdr (assq 'heading org-blank-before-new-entry))
21454 (skip-chars-backward " \t\n\r")
21455 (unless (eobp)
21456 (forward-line -1)))
21457 (beginning-of-line 2)
21458 (goto-char (min (point) pos))
21459 (count-lines (point) pos)))
21461 (defun org-switch-to-buffer-other-window (&rest args)
21462 "Switch to buffer in a second window on the current frame.
21463 In particular, do not allow pop-up frames.
21464 Returns the newly created buffer."
21465 (org-no-popups
21466 (apply 'switch-to-buffer-other-window args)))
21468 (defun org-replace-escapes (string table)
21469 "Replace %-escapes in STRING with values in TABLE.
21470 TABLE is an association list with keys like \"%a\" and string values.
21471 The sequences in STRING may contain normal field width and padding information,
21472 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21473 so values can contain further %-escapes if they are define later in TABLE."
21474 (let ((tbl (copy-alist table))
21475 (case-fold-search nil)
21476 (pchg 0)
21477 re rpl)
21478 (dolist (e tbl)
21479 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21480 (when (and (cdr e) (string-match re (cdr e)))
21481 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21482 (safe "SREF"))
21483 (add-text-properties 0 3 (list 'sref sref) safe)
21484 (setcdr e (replace-match safe t t (cdr e)))))
21485 (while (string-match re string)
21486 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21487 (cdr e)))
21488 (setq string (replace-match rpl t t string))))
21489 (while (setq pchg (next-property-change pchg string))
21490 (let ((sref (get-text-property pchg 'sref string)))
21491 (when (and sref (string-match "SREF" string pchg))
21492 (setq string (replace-match sref t t string)))))
21493 string))
21495 ;;; TODO: Only called once, from ox-odt which should probably use
21496 ;;; org-export-inline-image-p or something.
21497 (defun org-file-image-p (file)
21498 "Return non-nil if FILE is an image."
21499 (save-match-data
21500 (string-match (image-file-name-regexp) file)))
21502 (defun org-get-cursor-date (&optional with-time)
21503 "Return the date at cursor in as a time.
21504 This works in the calendar and in the agenda, anywhere else it just
21505 returns the current time.
21506 If WITH-TIME is non-nil, returns the time of the event at point (in
21507 the agenda) or the current time of the day."
21508 (let (date day defd tp hod mod)
21509 (when with-time
21510 (setq tp (get-text-property (point) 'time))
21511 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21512 (setq hod (string-to-number (match-string 1 tp))
21513 mod (string-to-number (match-string 2 tp))))
21514 (or tp (let ((now (decode-time)))
21515 (setq hod (nth 2 now)
21516 mod (nth 1 now)))))
21517 (cond
21518 ((eq major-mode 'calendar-mode)
21519 (setq date (calendar-cursor-to-date)
21520 defd (encode-time 0 (or mod 0) (or hod 0)
21521 (nth 1 date) (nth 0 date) (nth 2 date))))
21522 ((eq major-mode 'org-agenda-mode)
21523 (setq day (get-text-property (point) 'day))
21524 (when day
21525 (setq date (calendar-gregorian-from-absolute day)
21526 defd (encode-time 0 (or mod 0) (or hod 0)
21527 (nth 1 date) (nth 0 date) (nth 2 date))))))
21528 (or defd (current-time))))
21530 (defun org-mark-subtree (&optional up)
21531 "Mark the current subtree.
21532 This puts point at the start of the current subtree, and mark at
21533 the end. If a numeric prefix UP is given, move up into the
21534 hierarchy of headlines by UP levels before marking the subtree."
21535 (interactive "P")
21536 (org-with-limited-levels
21537 (cond ((org-at-heading-p) (beginning-of-line))
21538 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21539 (t (outline-previous-visible-heading 1))))
21540 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21541 (if (called-interactively-p 'any)
21542 (call-interactively 'org-mark-element)
21543 (org-mark-element)))
21545 (defun org-file-newer-than-p (file time)
21546 "Non-nil if FILE is newer than TIME.
21547 FILE is a filename, as a string, TIME is a list of integers, as
21548 returned by, e.g., `current-time'."
21549 (and (file-exists-p file)
21550 ;; Only compare times up to whole seconds as some file-systems
21551 ;; (e.g. HFS+) do not retain any finer granularity. As
21552 ;; a consequence, make sure we return non-nil when the two
21553 ;; times are equal.
21554 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21555 (cl-subseq time 0 2)))))
21557 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21558 "Compile a SOURCE file using PROCESS.
21560 PROCESS is either a function or a list of shell commands, as
21561 strings. EXT is a file extension, without the leading dot, as
21562 a string. It is used to check if the process actually succeeded.
21564 PROCESS must create a file with the same base name and directory
21565 as SOURCE, but ending with EXT. The function then returns its
21566 filename. Otherwise, it raises an error. The error message can
21567 then be refined by providing string ERR-MSG, which is appended to
21568 the standard message.
21570 If PROCESS is a function, it is called with a single argument:
21571 the SOURCE file.
21573 If it is a list of commands, each of them is called using
21574 `shell-command'. By default, in each command, %b, %f, %F, %o and
21575 %O are replaced with, respectively, SOURCE base name, name, full
21576 name, directory and absolute output file name. It is possible,
21577 however, to use more place-holders by specifying them in optional
21578 argument SPEC, as an alist following the pattern
21580 (CHARACTER . REPLACEMENT-STRING).
21582 When PROCESS is a list of commands, optional argument LOG-BUF can
21583 be set to a buffer or a buffer name. `shell-command' then uses
21584 it for output."
21585 (let* ((base-name (file-name-base source))
21586 (full-name (file-truename source))
21587 (out-dir (or (file-name-directory source) "./"))
21588 (output (expand-file-name (concat base-name "." ext) out-dir))
21589 (time (current-time))
21590 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21591 (save-window-excursion
21592 (pcase process
21593 ((pred functionp) (funcall process (shell-quote-argument source)))
21594 ((pred consp)
21595 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21596 (spec (append spec
21597 `((?b . ,(shell-quote-argument base-name))
21598 (?f . ,(shell-quote-argument source))
21599 (?F . ,(shell-quote-argument full-name))
21600 (?o . ,(shell-quote-argument out-dir))
21601 (?O . ,(shell-quote-argument output))))))
21602 (dolist (command process)
21603 (shell-command (format-spec command spec) log-buf))
21604 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21605 (_ (error "No valid command to process %S%s" source err-msg))))
21606 ;; Check for process failure. Output file is expected to be
21607 ;; located in the same directory as SOURCE.
21608 (unless (org-file-newer-than-p output time)
21609 (error (format "File %S wasn't produced%s" output err-msg)))
21610 output))
21612 ;;; Indentation
21614 (defvar org-element-greater-elements)
21615 (defun org--get-expected-indentation (element contentsp)
21616 "Expected indentation column for current line, according to ELEMENT.
21617 ELEMENT is an element containing point. CONTENTSP is non-nil
21618 when indentation is to be computed according to contents of
21619 ELEMENT."
21620 (let ((type (org-element-type element))
21621 (start (org-element-property :begin element))
21622 (post-affiliated (org-element-property :post-affiliated element)))
21623 (org-with-wide-buffer
21624 (cond
21625 (contentsp
21626 (cl-case type
21627 ((diary-sexp footnote-definition) 0)
21628 ((headline inlinetask nil)
21629 (if (not org-adapt-indentation) 0
21630 (let ((level (org-current-level)))
21631 (if level (1+ level) 0))))
21632 ((item plain-list) (org-list-item-body-column post-affiliated))
21634 (goto-char start)
21635 (org-get-indentation))))
21636 ((memq type '(headline inlinetask nil))
21637 (if (org-match-line "[ \t]*$")
21638 (org--get-expected-indentation element t)
21640 ((memq type '(diary-sexp footnote-definition)) 0)
21641 ;; First paragraph of a footnote definition or an item.
21642 ;; Indent like parent.
21643 ((< (line-beginning-position) start)
21644 (org--get-expected-indentation
21645 (org-element-property :parent element) t))
21646 ;; At first line: indent according to previous sibling, if any,
21647 ;; ignoring footnote definitions and inline tasks, or parent's
21648 ;; contents.
21649 ((= (line-beginning-position) start)
21650 (catch 'exit
21651 (while t
21652 (if (= (point-min) start) (throw 'exit 0)
21653 (goto-char (1- start))
21654 (let* ((previous (org-element-at-point))
21655 (parent previous))
21656 (while (and parent (<= (org-element-property :end parent) start))
21657 (setq previous parent
21658 parent (org-element-property :parent parent)))
21659 (cond
21660 ((not previous) (throw 'exit 0))
21661 ((> (org-element-property :end previous) start)
21662 (throw 'exit (org--get-expected-indentation previous t)))
21663 ((memq (org-element-type previous)
21664 '(footnote-definition inlinetask))
21665 (setq start (org-element-property :begin previous)))
21666 (t (goto-char (org-element-property :begin previous))
21667 (throw 'exit
21668 (if (bolp) (org-get-indentation)
21669 ;; At first paragraph in an item or
21670 ;; a footnote definition.
21671 (org--get-expected-indentation
21672 (org-element-property :parent previous) t))))))))))
21673 ;; Otherwise, move to the first non-blank line above.
21675 (beginning-of-line)
21676 (let ((pos (point)))
21677 (skip-chars-backward " \r\t\n")
21678 (cond
21679 ;; Two blank lines end a footnote definition or a plain
21680 ;; list. When we indent an empty line after them, the
21681 ;; containing list or footnote definition is over, so it
21682 ;; qualifies as a previous sibling. Therefore, we indent
21683 ;; like its first line.
21684 ((and (memq type '(footnote-definition plain-list))
21685 (> (count-lines (point) pos) 2))
21686 (goto-char start)
21687 (org-get-indentation))
21688 ;; Line above is the first one of a paragraph at the
21689 ;; beginning of an item or a footnote definition. Indent
21690 ;; like parent.
21691 ((< (line-beginning-position) start)
21692 (org--get-expected-indentation
21693 (org-element-property :parent element) t))
21694 ;; Line above is the beginning of an element, i.e., point
21695 ;; was originally on the blank lines between element's start
21696 ;; and contents.
21697 ((= (line-beginning-position) post-affiliated)
21698 (org--get-expected-indentation element t))
21699 ;; POS is after contents in a greater element. Indent like
21700 ;; the beginning of the element.
21701 ((and (memq type org-element-greater-elements)
21702 (let ((cend (org-element-property :contents-end element)))
21703 (and cend (<= cend pos))))
21704 ;; As a special case, if point is at the end of a footnote
21705 ;; definition or an item, indent like the very last element
21706 ;; within. If that last element is an item, indent like
21707 ;; its contents.
21708 (if (memq type '(footnote-definition item plain-list))
21709 (let ((last (org-element-at-point)))
21710 (goto-char pos)
21711 (org--get-expected-indentation
21712 last (eq (org-element-type last) 'item)))
21713 (goto-char start)
21714 (org-get-indentation)))
21715 ;; In any other case, indent like the current line.
21716 (t (org-get-indentation)))))))))
21718 (defun org--align-node-property ()
21719 "Align node property at point.
21720 Alignment is done according to `org-property-format', which see."
21721 (when (save-excursion
21722 (beginning-of-line)
21723 (looking-at org-property-re))
21724 (replace-match
21725 (concat (match-string 4)
21726 (org-trim
21727 (format org-property-format (match-string 1) (match-string 3))))
21728 t t)))
21730 (defun org-indent-line ()
21731 "Indent line depending on context.
21733 Indentation is done according to the following rules:
21735 - Footnote definitions, diary sexps, headlines and inline tasks
21736 have to start at column 0.
21738 - On the very first line of an element, consider, in order, the
21739 next rules until one matches:
21741 1. If there's a sibling element before, ignoring footnote
21742 definitions and inline tasks, indent like its first line.
21744 2. If element has a parent, indent like its contents. More
21745 precisely, if parent is an item, indent after the
21746 description part, if any, or the bullet (see
21747 `org-list-description-max-indent'). Else, indent like
21748 parent's first line.
21750 3. Otherwise, indent relatively to current level, if
21751 `org-adapt-indentation' is non-nil, or to left margin.
21753 - On a blank line at the end of an element, indent according to
21754 the type of the element. More precisely
21756 1. If element is a plain list, an item, or a footnote
21757 definition, indent like the very last element within.
21759 2. If element is a paragraph, indent like its last non blank
21760 line.
21762 3. Otherwise, indent like its very first line.
21764 - In the code part of a source block, use language major mode
21765 to indent current line if `org-src-tab-acts-natively' is
21766 non-nil. If it is nil, do nothing.
21768 - Otherwise, indent like the first non-blank line above.
21770 The function doesn't indent an item as it could break the whole
21771 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21772 `\\[org-shiftmetaright]'.
21774 Also align node properties according to `org-property-format'."
21775 (interactive)
21776 (cond
21777 ((org-at-heading-p) 'noindent)
21779 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21780 (type (org-element-type element)))
21781 (cond ((and (memq type '(plain-list item))
21782 (= (line-beginning-position)
21783 (org-element-property :post-affiliated element)))
21784 'noindent)
21785 ((and (eq type 'latex-environment)
21786 (>= (point) (org-element-property :post-affiliated element))
21787 (< (point) (org-with-wide-buffer
21788 (goto-char (org-element-property :end element))
21789 (skip-chars-backward " \r\t\n")
21790 (line-beginning-position 2))))
21791 'noindent)
21792 ((and (eq type 'src-block)
21793 org-src-tab-acts-natively
21794 (> (line-beginning-position)
21795 (org-element-property :post-affiliated element))
21796 (< (line-beginning-position)
21797 (org-with-wide-buffer
21798 (goto-char (org-element-property :end element))
21799 (skip-chars-backward " \r\t\n")
21800 (line-beginning-position))))
21801 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21803 (let ((column (org--get-expected-indentation element nil)))
21804 ;; Preserve current column.
21805 (if (<= (current-column) (current-indentation))
21806 (indent-line-to column)
21807 (save-excursion (indent-line-to column))))
21808 ;; Align node property. Also preserve current column.
21809 (when (eq type 'node-property)
21810 (let ((column (current-column)))
21811 (org--align-node-property)
21812 (org-move-to-column column)))))))))
21814 (defun org-indent-region (start end)
21815 "Indent each non-blank line in the region.
21816 Called from a program, START and END specify the region to
21817 indent. The function will not indent contents of example blocks,
21818 verse blocks and export blocks as leading white spaces are
21819 assumed to be significant there."
21820 (interactive "r")
21821 (save-excursion
21822 (goto-char start)
21823 (skip-chars-forward " \r\t\n")
21824 (unless (eobp) (beginning-of-line))
21825 (let ((indent-to
21826 (lambda (ind pos)
21827 ;; Set IND as indentation for all lines between point and
21828 ;; POS. Blank lines are ignored. Leave point after POS
21829 ;; once done.
21830 (let ((limit (copy-marker pos)))
21831 (while (< (point) limit)
21832 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21833 (forward-line))
21834 (set-marker limit nil))))
21835 (end (copy-marker end)))
21836 (while (< (point) end)
21837 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21838 (let* ((element (org-element-at-point))
21839 (type (org-element-type element))
21840 (element-end (copy-marker (org-element-property :end element)))
21841 (ind (org--get-expected-indentation element nil)))
21842 (cond
21843 ;; Element indented as a single block. Example blocks
21844 ;; preserving indentation are a special case since the
21845 ;; "contents" must not be indented whereas the block
21846 ;; boundaries can.
21847 ((or (memq type '(export-block latex-environment))
21848 (and (eq type 'example-block)
21849 (not
21850 (or org-src-preserve-indentation
21851 (org-element-property :preserve-indent element)))))
21852 (let ((offset (- ind (org-get-indentation))))
21853 (unless (zerop offset)
21854 (indent-rigidly (org-element-property :begin element)
21855 (org-element-property :end element)
21856 offset)))
21857 (goto-char element-end))
21858 ;; Elements indented line wise. Be sure to exclude
21859 ;; example blocks (preserving indentation) and source
21860 ;; blocks from this category as they are treated
21861 ;; specially later.
21862 ((or (memq type '(paragraph table table-row))
21863 (not (or (org-element-property :contents-begin element)
21864 (memq type '(example-block src-block)))))
21865 (when (eq type 'node-property)
21866 (org--align-node-property)
21867 (beginning-of-line))
21868 (funcall indent-to ind (min element-end end)))
21869 ;; Elements consisting of three parts: before the
21870 ;; contents, the contents, and after the contents. The
21871 ;; contents are treated specially, according to the
21872 ;; element type, or not indented at all. Other parts are
21873 ;; indented as a single block.
21875 (let* ((post (copy-marker
21876 (org-element-property :post-affiliated element)))
21877 (cbeg
21878 (copy-marker
21879 (cond
21880 ((not (org-element-property :contents-begin element))
21881 ;; Fake contents for source blocks.
21882 (org-with-wide-buffer
21883 (goto-char post)
21884 (line-beginning-position 2)))
21885 ((memq type '(footnote-definition item plain-list))
21886 ;; Contents in these elements could start on
21887 ;; the same line as the beginning of the
21888 ;; element. Make sure we start indenting
21889 ;; from the second line.
21890 (org-with-wide-buffer
21891 (goto-char post)
21892 (end-of-line)
21893 (skip-chars-forward " \r\t\n")
21894 (if (eobp) (point) (line-beginning-position))))
21895 (t (org-element-property :contents-begin element)))))
21896 (cend (copy-marker
21897 (or (org-element-property :contents-end element)
21898 ;; Fake contents for source blocks.
21899 (org-with-wide-buffer
21900 (goto-char element-end)
21901 (skip-chars-backward " \r\t\n")
21902 (line-beginning-position)))
21903 t)))
21904 ;; Do not change items indentation individually as it
21905 ;; might break the list as a whole. On the other
21906 ;; hand, when at a plain list, indent it as a whole.
21907 (cond ((eq type 'plain-list)
21908 (let ((offset (- ind (org-get-indentation))))
21909 (unless (zerop offset)
21910 (indent-rigidly (org-element-property :begin element)
21911 (org-element-property :end element)
21912 offset))
21913 (goto-char cbeg)))
21914 ((eq type 'item) (goto-char cbeg))
21915 (t (funcall indent-to ind (min cbeg end))))
21916 (when (< (point) end)
21917 (cl-case type
21918 ((example-block verse-block))
21919 (src-block
21920 ;; In a source block, indent source code
21921 ;; according to language major mode, but only if
21922 ;; `org-src-tab-acts-natively' is non-nil.
21923 (when (and (< (point) end) org-src-tab-acts-natively)
21924 (ignore-errors
21925 (org-babel-do-in-edit-buffer
21926 (indent-region (point-min) (point-max))))))
21927 (t (org-indent-region (point) (min cend end))))
21928 (goto-char (min cend end))
21929 (when (< (point) end)
21930 (funcall indent-to ind (min element-end end))))
21931 (set-marker post nil)
21932 (set-marker cbeg nil)
21933 (set-marker cend nil))))
21934 (set-marker element-end nil))))
21935 (set-marker end nil))))
21937 (defun org-indent-drawer ()
21938 "Indent the drawer at point."
21939 (interactive)
21940 (unless (save-excursion
21941 (beginning-of-line)
21942 (looking-at-p org-drawer-regexp))
21943 (user-error "Not at a drawer"))
21944 (let ((element (org-element-at-point)))
21945 (unless (memq (org-element-type element) '(drawer property-drawer))
21946 (user-error "Not at a drawer"))
21947 (org-with-wide-buffer
21948 (org-indent-region (org-element-property :begin element)
21949 (org-element-property :end element))))
21950 (message "Drawer at point indented"))
21952 (defun org-indent-block ()
21953 "Indent the block at point."
21954 (interactive)
21955 (unless (save-excursion
21956 (beginning-of-line)
21957 (let ((case-fold-search t))
21958 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21959 (user-error "Not at a block"))
21960 (let ((element (org-element-at-point)))
21961 (unless (memq (org-element-type element)
21962 '(comment-block center-block dynamic-block example-block
21963 export-block quote-block special-block
21964 src-block verse-block))
21965 (user-error "Not at a block"))
21966 (org-with-wide-buffer
21967 (org-indent-region (org-element-property :begin element)
21968 (org-element-property :end element))))
21969 (message "Block at point indented"))
21972 ;;; Filling
21974 ;; We use our own fill-paragraph and auto-fill functions.
21976 ;; `org-fill-paragraph' relies on adaptive filling and context
21977 ;; checking. Appropriate `fill-prefix' is computed with
21978 ;; `org-adaptive-fill-function'.
21980 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21981 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21982 ;; `org-adaptive-fill-function' value. Internally,
21983 ;; `org-comment-line-break-function' breaks the line.
21985 ;; `org-setup-filling' installs filling and auto-filling related
21986 ;; variables during `org-mode' initialization.
21988 (defun org-setup-filling ()
21989 (require 'org-element)
21990 ;; Prevent auto-fill from inserting unwanted new items.
21991 (when (boundp 'fill-nobreak-predicate)
21992 (setq-local
21993 fill-nobreak-predicate
21994 (org-uniquify
21995 (append fill-nobreak-predicate
21996 '(org-fill-line-break-nobreak-p
21997 org-fill-n-macro-as-item-nobreak-p
21998 org-fill-paragraph-with-timestamp-nobreak-p)))))
21999 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22000 (setq-local paragraph-start paragraph-ending)
22001 (setq-local paragraph-separate paragraph-ending))
22002 (setq-local fill-paragraph-function 'org-fill-paragraph)
22003 (setq-local auto-fill-inhibit-regexp nil)
22004 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22005 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22006 (setq-local comment-line-break-function 'org-comment-line-break-function))
22008 (defun org-fill-line-break-nobreak-p ()
22009 "Non-nil when a new line at point would create an Org line break."
22010 (save-excursion
22011 (skip-chars-backward "[ \t]")
22012 (skip-chars-backward "\\\\")
22013 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22015 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22016 "Non-nil when a new line at point would split a timestamp."
22017 (and (org-at-timestamp-p 'lax)
22018 (not (looking-at org-ts-regexp-both))))
22020 (defun org-fill-n-macro-as-item-nobreak-p ()
22021 "Non-nil when a new line at point would create a new list."
22022 ;; During export, a "n" macro followed by a dot or a closing
22023 ;; parenthesis can end up being parsed as a new list item.
22024 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22026 (declare-function message-in-body-p "message" ())
22027 (defvar orgtbl-line-start-regexp) ; From org-table.el
22028 (defun org-adaptive-fill-function ()
22029 "Compute a fill prefix for the current line.
22030 Return fill prefix, as a string, or nil if current line isn't
22031 meant to be filled. For convenience, if `adaptive-fill-regexp'
22032 matches in paragraphs or comments, use it."
22033 (org-with-wide-buffer
22034 (unless (org-at-heading-p)
22035 (let* ((p (line-beginning-position))
22036 (element (save-excursion
22037 (beginning-of-line)
22038 (org-element-at-point)))
22039 (type (org-element-type element))
22040 (post-affiliated (org-element-property :post-affiliated element)))
22041 (unless (< p post-affiliated)
22042 (cl-case type
22043 (comment
22044 (save-excursion
22045 (beginning-of-line)
22046 (looking-at "[ \t]*")
22047 (concat (match-string 0) "# ")))
22048 (footnote-definition "")
22049 ((item plain-list)
22050 (make-string (org-list-item-body-column post-affiliated) ?\s))
22051 (paragraph
22052 ;; Fill prefix is usually the same as the current line,
22053 ;; unless the paragraph is at the beginning of an item.
22054 (let ((parent (org-element-property :parent element)))
22055 (save-excursion
22056 (beginning-of-line)
22057 (cond ((eq (org-element-type parent) 'item)
22058 (make-string (org-list-item-body-column
22059 (org-element-property :begin parent))
22060 ?\s))
22061 ((and adaptive-fill-regexp
22062 ;; Locally disable
22063 ;; `adaptive-fill-function' to let
22064 ;; `fill-context-prefix' handle
22065 ;; `adaptive-fill-regexp' variable.
22066 (let (adaptive-fill-function)
22067 (fill-context-prefix
22068 post-affiliated
22069 (org-element-property :end element)))))
22070 ((looking-at "[ \t]+") (match-string 0))
22071 (t "")))))
22072 (comment-block
22073 ;; Only fill contents if P is within block boundaries.
22074 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22075 (forward-line)
22076 (point)))
22077 (cend (save-excursion
22078 (goto-char (org-element-property :end element))
22079 (skip-chars-backward " \r\t\n")
22080 (line-beginning-position))))
22081 (when (and (>= p cbeg) (< p cend))
22082 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22083 (match-string 0)
22084 ""))))))))))
22086 (declare-function message-goto-body "message" ())
22087 (defvar message-cite-prefix-regexp) ; From message.el
22089 (defun org-fill-element (&optional justify)
22090 "Fill element at point, when applicable.
22092 This function only applies to comment blocks, comments, example
22093 blocks and paragraphs. Also, as a special case, re-align table
22094 when point is at one.
22096 If JUSTIFY is non-nil (interactively, with prefix argument),
22097 justify as well. If `sentence-end-double-space' is non-nil, then
22098 period followed by one space does not end a sentence, so don't
22099 break a line there. The variable `fill-column' controls the
22100 width for filling.
22102 For convenience, when point is at a plain list, an item or
22103 a footnote definition, try to fill the first paragraph within."
22104 (with-syntax-table org-mode-transpose-word-syntax-table
22105 ;; Move to end of line in order to get the first paragraph within
22106 ;; a plain list or a footnote definition.
22107 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22108 ;; First check if point is in a blank line at the beginning of
22109 ;; the buffer. In that case, ignore filling.
22110 (cl-case (org-element-type element)
22111 ;; Use major mode filling function is src blocks.
22112 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22113 ;; Align Org tables, leave table.el tables as-is.
22114 (table-row (org-table-align) t)
22115 (table
22116 (when (eq (org-element-property :type element) 'org)
22117 (save-excursion
22118 (goto-char (org-element-property :post-affiliated element))
22119 (org-table-align)))
22121 (paragraph
22122 ;; Paragraphs may contain `line-break' type objects.
22123 (let ((beg (max (point-min)
22124 (org-element-property :contents-begin element)))
22125 (end (min (point-max)
22126 (org-element-property :contents-end element))))
22127 ;; Do nothing if point is at an affiliated keyword.
22128 (if (< (line-end-position) beg) t
22129 ;; Fill paragraph, taking line breaks into account.
22130 (save-excursion
22131 (goto-char beg)
22132 (let ((cuts (list beg)))
22133 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22134 (when (eq 'line-break
22135 (org-element-type
22136 (save-excursion (backward-char)
22137 (org-element-context))))
22138 (push (point) cuts)))
22139 (dolist (c (delq end cuts))
22140 (fill-region-as-paragraph c end justify)
22141 (setq end c))))
22142 t)))
22143 ;; Contents of `comment-block' type elements should be
22144 ;; filled as plain text, but only if point is within block
22145 ;; markers.
22146 (comment-block
22147 (let* ((case-fold-search t)
22148 (beg (save-excursion
22149 (goto-char (org-element-property :begin element))
22150 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22151 (forward-line)
22152 (point)))
22153 (end (save-excursion
22154 (goto-char (org-element-property :end element))
22155 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22156 (line-beginning-position))))
22157 (if (or (< (point) beg) (> (point) end)) t
22158 (fill-region-as-paragraph
22159 (save-excursion (end-of-line)
22160 (re-search-backward "^[ \t]*$" beg 'move)
22161 (line-beginning-position))
22162 (save-excursion (beginning-of-line)
22163 (re-search-forward "^[ \t]*$" end 'move)
22164 (line-beginning-position))
22165 justify))))
22166 ;; Fill comments.
22167 (comment
22168 (let ((begin (org-element-property :post-affiliated element))
22169 (end (org-element-property :end element)))
22170 (when (and (>= (point) begin) (<= (point) end))
22171 (let ((begin (save-excursion
22172 (end-of-line)
22173 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22174 (progn (forward-line) (point))
22175 begin)))
22176 (end (save-excursion
22177 (end-of-line)
22178 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22179 (1- (line-beginning-position))
22180 (skip-chars-backward " \r\t\n")
22181 (line-end-position)))))
22182 ;; Do not fill comments when at a blank line.
22183 (when (> end begin)
22184 (let ((fill-prefix
22185 (save-excursion
22186 (beginning-of-line)
22187 (looking-at "[ \t]*#")
22188 (let ((comment-prefix (match-string 0)))
22189 (goto-char (match-end 0))
22190 (if (looking-at adaptive-fill-regexp)
22191 (concat comment-prefix (match-string 0))
22192 (concat comment-prefix " "))))))
22193 (save-excursion
22194 (fill-region-as-paragraph begin end justify))))))
22196 ;; Ignore every other element.
22197 (otherwise t)))))
22199 (defun org-fill-paragraph (&optional justify region)
22200 "Fill element at point, when applicable.
22202 This function only applies to comment blocks, comments, example
22203 blocks and paragraphs. Also, as a special case, re-align table
22204 when point is at one.
22206 For convenience, when point is at a plain list, an item or
22207 a footnote definition, try to fill the first paragraph within.
22209 If JUSTIFY is non-nil (interactively, with prefix argument),
22210 justify as well. If `sentence-end-double-space' is non-nil, then
22211 period followed by one space does not end a sentence, so don't
22212 break a line there. The variable `fill-column' controls the
22213 width for filling.
22215 The REGION argument is non-nil if called interactively; in that
22216 case, if Transient Mark mode is enabled and the mark is active,
22217 fill each of the elements in the active region, instead of just
22218 filling the current element."
22219 (interactive (progn
22220 (barf-if-buffer-read-only)
22221 (list (if current-prefix-arg 'full) t)))
22222 (cond
22223 ((and region transient-mark-mode mark-active
22224 (not (eq (region-beginning) (region-end))))
22225 (let ((origin (point-marker))
22226 (start (region-beginning)))
22227 (unwind-protect
22228 (progn
22229 (goto-char (region-end))
22230 (while (> (point) start)
22231 (org-backward-paragraph)
22232 (org-fill-element justify)))
22233 (goto-char origin)
22234 (set-marker origin nil))))
22235 (t (org-fill-element justify))))
22236 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22238 (defun org-auto-fill-function ()
22239 "Auto-fill function."
22240 ;; Check if auto-filling is meaningful.
22241 (let ((fc (current-fill-column)))
22242 (when (and fc (> (current-column) fc))
22243 (let* ((fill-prefix (org-adaptive-fill-function))
22244 ;; Enforce empty fill prefix, if required. Otherwise, it
22245 ;; will be computed again.
22246 (adaptive-fill-mode (not (equal fill-prefix ""))))
22247 (when fill-prefix (do-auto-fill))))))
22249 (defun org-comment-line-break-function (&optional soft)
22250 "Break line at point and indent, continuing comment if within one.
22251 The inserted newline is marked hard if variable
22252 `use-hard-newlines' is true, unless optional argument SOFT is
22253 non-nil."
22254 (if soft (insert-and-inherit ?\n) (newline 1))
22255 (save-excursion (forward-char -1) (delete-horizontal-space))
22256 (delete-horizontal-space)
22257 (indent-to-left-margin)
22258 (insert-before-markers-and-inherit fill-prefix))
22261 ;;; Fixed Width Areas
22263 (defun org-toggle-fixed-width ()
22264 "Toggle fixed-width markup.
22266 Add or remove fixed-width markup on current line, whenever it
22267 makes sense. Return an error otherwise.
22269 If a region is active and if it contains only fixed-width areas
22270 or blank lines, remove all fixed-width markup in it. If the
22271 region contains anything else, convert all non-fixed-width lines
22272 to fixed-width ones.
22274 Blank lines at the end of the region are ignored unless the
22275 region only contains such lines."
22276 (interactive)
22277 (if (not (org-region-active-p))
22278 ;; No region:
22280 ;; Remove fixed width marker only in a fixed-with element.
22282 ;; Add fixed width maker in paragraphs, in blank lines after
22283 ;; elements or at the beginning of a headline or an inlinetask,
22284 ;; and before any one-line elements (e.g., a clock).
22285 (progn
22286 (beginning-of-line)
22287 (let* ((element (org-element-at-point))
22288 (type (org-element-type element)))
22289 (cond
22290 ((and (eq type 'fixed-width)
22291 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22292 (replace-match
22293 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22294 ((and (memq type '(babel-call clock comment diary-sexp headline
22295 horizontal-rule keyword paragraph
22296 planning))
22297 (<= (org-element-property :post-affiliated element) (point)))
22298 (skip-chars-forward " \t")
22299 (insert ": "))
22300 ((and (looking-at-p "[ \t]*$")
22301 (or (eq type 'inlinetask)
22302 (save-excursion
22303 (skip-chars-forward " \r\t\n")
22304 (<= (org-element-property :end element) (point)))))
22305 (delete-region (point) (line-end-position))
22306 (org-indent-line)
22307 (insert ": "))
22308 (t (user-error "Cannot insert a fixed-width line here")))))
22309 ;; Region active.
22310 (let* ((begin (save-excursion
22311 (goto-char (region-beginning))
22312 (line-beginning-position)))
22313 (end (copy-marker
22314 (save-excursion
22315 (goto-char (region-end))
22316 (unless (eolp) (beginning-of-line))
22317 (if (save-excursion (re-search-backward "\\S-" begin t))
22318 (progn (skip-chars-backward " \r\t\n") (point))
22319 (point)))))
22320 (all-fixed-width-p
22321 (catch 'not-all-p
22322 (save-excursion
22323 (goto-char begin)
22324 (skip-chars-forward " \r\t\n")
22325 (when (eobp) (throw 'not-all-p nil))
22326 (while (< (point) end)
22327 (let ((element (org-element-at-point)))
22328 (if (eq (org-element-type element) 'fixed-width)
22329 (goto-char (org-element-property :end element))
22330 (throw 'not-all-p nil))))
22331 t))))
22332 (if all-fixed-width-p
22333 (save-excursion
22334 (goto-char begin)
22335 (while (< (point) end)
22336 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22337 (replace-match
22338 "" nil nil nil
22339 (if (= (line-end-position) (match-end 0)) 0 1)))
22340 (forward-line)))
22341 (let ((min-ind (point-max)))
22342 ;; Find minimum indentation across all lines.
22343 (save-excursion
22344 (goto-char begin)
22345 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22346 (setq min-ind 0)
22347 (catch 'zerop
22348 (while (< (point) end)
22349 (unless (looking-at-p "[ \t]*$")
22350 (let ((ind (org-get-indentation)))
22351 (setq min-ind (min min-ind ind))
22352 (when (zerop ind) (throw 'zerop t))))
22353 (forward-line)))))
22354 ;; Loop over all lines and add fixed-width markup everywhere
22355 ;; but in fixed-width lines.
22356 (save-excursion
22357 (goto-char begin)
22358 (while (< (point) end)
22359 (cond
22360 ((org-at-heading-p)
22361 (insert ": ")
22362 (forward-line)
22363 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22364 (insert ":")
22365 (forward-line)))
22366 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22367 (let* ((element (org-element-at-point))
22368 (element-end (org-element-property :end element)))
22369 (if (eq (org-element-type element) 'fixed-width)
22370 (progn (goto-char element-end)
22371 (skip-chars-backward " \r\t\n")
22372 (forward-line))
22373 (let ((limit (min end element-end)))
22374 (while (< (point) limit)
22375 (org-move-to-column min-ind t)
22376 (insert ": ")
22377 (forward-line))))))
22379 (org-move-to-column min-ind t)
22380 (insert ": ")
22381 (forward-line)))))))
22382 (set-marker end nil))))
22385 ;;; Comments
22387 ;; Org comments syntax is quite complex. It requires the entire line
22388 ;; to be just a comment. Also, even with the right syntax at the
22389 ;; beginning of line, some elements (e.g., verse-block or
22390 ;; example-block) don't accept comments. Usual Emacs comment commands
22391 ;; cannot cope with those requirements. Therefore, Org replaces them.
22393 ;; Org still relies on `comment-dwim', but cannot trust
22394 ;; `comment-only-p'. So, `comment-region-function' and
22395 ;; `uncomment-region-function' both point
22396 ;; to`org-comment-or-uncomment-region'. Eventually,
22397 ;; `org-insert-comment' takes care of insertion of comments at the
22398 ;; beginning of line.
22400 ;; `org-setup-comments-handling' install comments related variables
22401 ;; during `org-mode' initialization.
22403 (defun org-setup-comments-handling ()
22404 (interactive)
22405 (setq-local comment-use-syntax nil)
22406 (setq-local comment-start "# ")
22407 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22408 (setq-local comment-insert-comment-function 'org-insert-comment)
22409 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22410 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22412 (defun org-insert-comment ()
22413 "Insert an empty comment above current line.
22414 If the line is empty, insert comment at its beginning. When
22415 point is within a source block, comment according to the related
22416 major mode."
22417 (if (let ((element (org-element-at-point)))
22418 (and (eq (org-element-type element) 'src-block)
22419 (< (save-excursion
22420 (goto-char (org-element-property :post-affiliated element))
22421 (line-end-position))
22422 (point))
22423 (> (save-excursion
22424 (goto-char (org-element-property :end element))
22425 (skip-chars-backward " \r\t\n")
22426 (line-beginning-position))
22427 (point))))
22428 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22429 (beginning-of-line)
22430 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22431 (open-line 1))
22432 (org-indent-line)
22433 (insert "# ")))
22435 (defvar comment-empty-lines) ; From newcomment.el.
22436 (defun org-comment-or-uncomment-region (beg end &rest _)
22437 "Comment or uncomment each non-blank line in the region.
22438 Uncomment each non-blank line between BEG and END if it only
22439 contains commented lines. Otherwise, comment them. If region is
22440 strictly within a source block, use appropriate comment syntax."
22441 (if (let ((element (org-element-at-point)))
22442 (and (eq (org-element-type element) 'src-block)
22443 (< (save-excursion
22444 (goto-char (org-element-property :post-affiliated element))
22445 (line-end-position))
22446 beg)
22447 (>= (save-excursion
22448 (goto-char (org-element-property :end element))
22449 (skip-chars-backward " \r\t\n")
22450 (line-beginning-position))
22451 end)))
22452 ;; Translate region boundaries for the Org buffer to the source
22453 ;; buffer.
22454 (let ((offset (- end beg)))
22455 (save-excursion
22456 (goto-char beg)
22457 (org-babel-do-in-edit-buffer
22458 (comment-or-uncomment-region (point) (+ offset (point))))))
22459 (save-restriction
22460 ;; Restrict region
22461 (narrow-to-region (save-excursion (goto-char beg)
22462 (skip-chars-forward " \r\t\n" end)
22463 (line-beginning-position))
22464 (save-excursion (goto-char end)
22465 (skip-chars-backward " \r\t\n" beg)
22466 (line-end-position)))
22467 (let ((uncommentp
22468 ;; UNCOMMENTP is non-nil when every non blank line between
22469 ;; BEG and END is a comment.
22470 (save-excursion
22471 (goto-char (point-min))
22472 (while (and (not (eobp))
22473 (let ((element (org-element-at-point)))
22474 (and (eq (org-element-type element) 'comment)
22475 (goto-char (min (point-max)
22476 (org-element-property
22477 :end element)))))))
22478 (eobp))))
22479 (if uncommentp
22480 ;; Only blank lines and comments in region: uncomment it.
22481 (save-excursion
22482 (goto-char (point-min))
22483 (while (not (eobp))
22484 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22485 (replace-match "" nil nil nil 1))
22486 (forward-line)))
22487 ;; Comment each line in region.
22488 (let ((min-indent (point-max)))
22489 ;; First find the minimum indentation across all lines.
22490 (save-excursion
22491 (goto-char (point-min))
22492 (while (and (not (eobp)) (not (zerop min-indent)))
22493 (unless (looking-at "[ \t]*$")
22494 (setq min-indent (min min-indent (current-indentation))))
22495 (forward-line)))
22496 ;; Then loop over all lines.
22497 (save-excursion
22498 (goto-char (point-min))
22499 (while (not (eobp))
22500 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22501 ;; Don't get fooled by invisible text (e.g. link path)
22502 ;; when moving to column MIN-INDENT.
22503 (let ((buffer-invisibility-spec nil))
22504 (org-move-to-column min-indent t))
22505 (insert comment-start))
22506 (forward-line)))))))))
22508 (defun org-comment-dwim (_arg)
22509 "Call the comment command you mean.
22510 Call `org-toggle-comment' if on a heading, otherwise call
22511 `comment-dwim', within a source edit buffer if needed."
22512 (interactive "*P")
22513 (cond ((org-at-heading-p)
22514 (call-interactively #'org-toggle-comment))
22515 ((org-in-src-block-p)
22516 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22517 (t (call-interactively #'comment-dwim))))
22520 ;;; Timestamps API
22522 ;; This section contains tools to operate on timestamp objects, as
22523 ;; returned by, e.g. `org-element-context'.
22525 (defun org-timestamp--to-internal-time (timestamp &optional end)
22526 "Encode TIMESTAMP object into Emacs internal time.
22527 Use end of date range or time range when END is non-nil."
22528 (apply #'encode-time
22529 (cons 0
22530 (mapcar
22531 (lambda (prop) (or (org-element-property prop timestamp) 0))
22532 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22533 '(:minute-start :hour-start :day-start :month-start
22534 :year-start))))))
22536 (defun org-timestamp-has-time-p (timestamp)
22537 "Non-nil when TIMESTAMP has a time specified."
22538 (org-element-property :hour-start timestamp))
22540 (defun org-timestamp-format (timestamp format &optional end utc)
22541 "Format a TIMESTAMP object into a string.
22543 FORMAT is a format specifier to be passed to
22544 `format-time-string'.
22546 When optional argument END is non-nil, use end of date-range or
22547 time-range, if possible.
22549 When optional argument UTC is non-nil, time will be expressed as
22550 Universal Time."
22551 (format-time-string
22552 format (org-timestamp--to-internal-time timestamp end)
22553 (and utc t)))
22555 (defun org-timestamp-split-range (timestamp &optional end)
22556 "Extract a TIMESTAMP object from a date or time range.
22558 END, when non-nil, means extract the end of the range.
22559 Otherwise, extract its start.
22561 Return a new timestamp object."
22562 (let ((type (org-element-property :type timestamp)))
22563 (if (memq type '(active inactive diary)) timestamp
22564 (let ((split-ts (org-element-copy timestamp)))
22565 ;; Set new type.
22566 (org-element-put-property
22567 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22568 ;; Copy start properties over end properties if END is
22569 ;; non-nil. Otherwise, copy end properties over `start' ones.
22570 (let ((p-alist '((:minute-start . :minute-end)
22571 (:hour-start . :hour-end)
22572 (:day-start . :day-end)
22573 (:month-start . :month-end)
22574 (:year-start . :year-end))))
22575 (dolist (p-cell p-alist)
22576 (org-element-put-property
22577 split-ts
22578 (funcall (if end #'car #'cdr) p-cell)
22579 (org-element-property
22580 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22581 ;; Eventually refresh `:raw-value'.
22582 (org-element-put-property split-ts :raw-value nil)
22583 (org-element-put-property
22584 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22586 (defun org-timestamp-translate (timestamp &optional boundary)
22587 "Translate TIMESTAMP object to custom format.
22589 Format string is defined in `org-time-stamp-custom-formats',
22590 which see.
22592 When optional argument BOUNDARY is non-nil, it is either the
22593 symbol `start' or `end'. In this case, only translate the
22594 starting or ending part of TIMESTAMP if it is a date or time
22595 range. Otherwise, translate both parts.
22597 Return timestamp as-is if `org-display-custom-times' is nil or if
22598 it has a `diary' type."
22599 (let ((type (org-element-property :type timestamp)))
22600 (if (or (not org-display-custom-times) (eq type 'diary))
22601 (org-element-interpret-data timestamp)
22602 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22603 org-time-stamp-custom-formats)))
22604 (if (and (not boundary) (memq type '(active-range inactive-range)))
22605 (concat (org-timestamp-format timestamp fmt)
22606 "--"
22607 (org-timestamp-format timestamp fmt t))
22608 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22612 ;;; Other stuff.
22614 (defvar reftex-docstruct-symbol)
22615 (defvar org--rds)
22617 (defun org-reftex-citation ()
22618 "Use reftex-citation to insert a citation into the buffer.
22619 This looks for a line like
22621 #+BIBLIOGRAPHY: foo plain option:-d
22623 and derives from it that foo.bib is the bibliography file relevant
22624 for this document. It then installs the necessary environment for RefTeX
22625 to work in this buffer and calls `reftex-citation' to insert a citation
22626 into the buffer.
22628 Export of such citations to both LaTeX and HTML is handled by the contributed
22629 package ox-bibtex by Taru Karttunen."
22630 (interactive)
22631 (let ((reftex-docstruct-symbol 'org--rds)
22632 org--rds bib)
22633 (org-with-wide-buffer
22634 (let ((case-fold-search t)
22635 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22636 (if (not (save-excursion
22637 (or (re-search-forward re nil t)
22638 (re-search-backward re nil t))))
22639 (user-error "No bibliography defined in file")
22640 (setq bib (concat (match-string 1) ".bib")
22641 org--rds (list (list 'bib bib))))))
22642 (call-interactively 'reftex-citation)))
22644 ;;;; Functions extending outline functionality
22646 (defun org-beginning-of-line (&optional n)
22647 "Go to the beginning of the current visible line.
22649 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22650 tags on the first attempt, and only move to after the tags when
22651 the cursor is already beyond the end of the headline.
22653 With argument N not nil or 1, move forward N - 1 lines first."
22654 (interactive "^p")
22655 (let ((origin (point))
22656 (special (pcase org-special-ctrl-a/e
22657 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22658 deactivate-mark)
22659 ;; First move to a visible line.
22660 (if (bound-and-true-p visual-line-mode)
22661 (beginning-of-visual-line n)
22662 (move-beginning-of-line n)
22663 ;; `move-beginning-of-line' may leave point after invisible
22664 ;; characters if line starts with such of these (e.g., with
22665 ;; a link at column 0). Really move to the beginning of the
22666 ;; current visible line.
22667 (beginning-of-line))
22668 (cond
22669 ;; No special behavior. Point is already at the beginning of
22670 ;; a line, logical or visual.
22671 ((not special))
22672 ;; `beginning-of-visual-line' left point before logical beginning
22673 ;; of line: point is at the beginning of a visual line. Bail
22674 ;; out.
22675 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22676 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22677 ;; At a headline, special position is before the title, but
22678 ;; after any TODO keyword or priority cookie.
22679 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22680 (line-end-position)))
22681 (bol (point)))
22682 (if (eq special 'reversed)
22683 (when (and (= origin bol) (eq last-command this-command))
22684 (goto-char refpos))
22685 (when (or (> origin refpos) (= origin bol))
22686 (goto-char refpos)))))
22687 ((and (looking-at org-list-full-item-re)
22688 (memq (org-element-type (save-match-data (org-element-at-point)))
22689 '(item plain-list)))
22690 ;; Set special position at first white space character after
22691 ;; bullet, and check-box, if any.
22692 (let ((after-bullet
22693 (let ((box (match-end 3)))
22694 (cond ((not box) (match-end 1))
22695 ((eq (char-after box) ?\s) (1+ box))
22696 (t box)))))
22697 (if (eq special 'reversed)
22698 (when (and (= (point) origin) (eq last-command this-command))
22699 (goto-char after-bullet))
22700 (when (or (> origin after-bullet) (= (point) origin))
22701 (goto-char after-bullet)))))
22702 ;; No special context. Point is already at beginning of line.
22703 (t nil))))
22705 (defun org-end-of-line (&optional n)
22706 "Go to the end of the line, but before ellipsis, if any.
22708 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22709 tags on the first attempt, and only move to after the tags when
22710 the cursor is already beyond the end of the headline.
22712 With argument N not nil or 1, move forward N - 1 lines first."
22713 (interactive "^p")
22714 (let ((origin (point))
22715 (special (pcase org-special-ctrl-a/e
22716 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22717 deactivate-mark)
22718 ;; First move to a visible line.
22719 (if (bound-and-true-p visual-line-mode)
22720 (beginning-of-visual-line n)
22721 (move-beginning-of-line n))
22722 (cond
22723 ;; At a headline, with tags.
22724 ((and special
22725 (save-excursion
22726 (beginning-of-line)
22727 (let ((case-fold-search nil))
22728 (looking-at org-complex-heading-regexp)))
22729 (match-end 5))
22730 (let ((tags (save-excursion
22731 (goto-char (match-beginning 5))
22732 (skip-chars-backward " \t")
22733 (point)))
22734 (visual-end (and (bound-and-true-p visual-line-mode)
22735 (save-excursion
22736 (end-of-visual-line)
22737 (point)))))
22738 ;; If `end-of-visual-line' brings us before end of line or
22739 ;; even tags, i.e., the headline spans over multiple visual
22740 ;; lines, move there.
22741 (cond ((and visual-end
22742 (< visual-end tags)
22743 (<= origin visual-end))
22744 (goto-char visual-end))
22745 ((eq special 'reversed)
22746 (if (and (= origin (line-end-position))
22747 (eq this-command last-command))
22748 (goto-char tags)
22749 (end-of-line)))
22751 (if (or (< origin tags) (= origin (line-end-position)))
22752 (goto-char tags)
22753 (end-of-line))))))
22754 ((bound-and-true-p visual-line-mode)
22755 (let ((bol (line-beginning-position)))
22756 (end-of-visual-line)
22757 ;; If `end-of-visual-line' gets us past the ellipsis at the
22758 ;; end of a line, backtrack and use `end-of-line' instead.
22759 (when (/= bol (line-beginning-position))
22760 (goto-char bol)
22761 (end-of-line))))
22762 (t (end-of-line)))))
22764 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22765 (define-key org-mode-map "\C-e" 'org-end-of-line)
22767 (defun org-backward-sentence (&optional _arg)
22768 "Go to beginning of sentence, or beginning of table field.
22769 This will call `backward-sentence' or `org-table-beginning-of-field',
22770 depending on context."
22771 (interactive)
22772 (let* ((element (org-element-at-point))
22773 (contents-begin (org-element-property :contents-begin element))
22774 (table (org-element-lineage element '(table) t)))
22775 (if (and table
22776 (> (point) contents-begin)
22777 (<= (point) (org-element-property :contents-end table)))
22778 (call-interactively #'org-table-beginning-of-field)
22779 (save-restriction
22780 (when (and contents-begin
22781 (< (point-min) contents-begin)
22782 (> (point) contents-begin))
22783 (narrow-to-region contents-begin
22784 (org-element-property :contents-end element)))
22785 (call-interactively #'backward-sentence)))))
22787 (defun org-forward-sentence (&optional _arg)
22788 "Go to end of sentence, or end of table field.
22789 This will call `forward-sentence' or `org-table-end-of-field',
22790 depending on context."
22791 (interactive)
22792 (if (and (org-at-heading-p)
22793 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22794 (save-restriction
22795 (narrow-to-region (line-beginning-position) (line-end-position))
22796 (call-interactively #'forward-sentence))
22797 (let* ((element (org-element-at-point))
22798 (contents-end (org-element-property :contents-end element))
22799 (table (org-element-lineage element '(table) t)))
22800 (if (and table
22801 (>= (point) (org-element-property :contents-begin table))
22802 (< (point) contents-end))
22803 (call-interactively #'org-table-end-of-field)
22804 (save-restriction
22805 (when (and contents-end
22806 (> (point-max) contents-end)
22807 ;; Skip blank lines between elements.
22808 (< (org-element-property :end element)
22809 (save-excursion (goto-char contents-end)
22810 (skip-chars-forward " \r\t\n"))))
22811 (narrow-to-region (org-element-property :contents-begin element)
22812 contents-end))
22813 ;; End of heading is considered as the end of a sentence.
22814 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22815 (call-interactively #'forward-sentence)))))))
22817 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22818 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22820 (defun org-kill-line (&optional _arg)
22821 "Kill line, to tags or end of line."
22822 (interactive)
22823 (cond
22824 ((or (not org-special-ctrl-k)
22825 (bolp)
22826 (not (org-at-heading-p)))
22827 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22828 org-ctrl-k-protect-subtree
22829 (or (eq org-ctrl-k-protect-subtree 'error)
22830 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22831 (user-error "C-k aborted as it would kill a hidden subtree"))
22832 (call-interactively
22833 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22834 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22835 (kill-region (point) (match-beginning 1))
22836 (org-set-tags nil t))
22837 (t (kill-region (point) (point-at-eol)))))
22839 (define-key org-mode-map "\C-k" 'org-kill-line)
22841 (defun org-yank (&optional arg)
22842 "Yank. If the kill is a subtree, treat it specially.
22843 This command will look at the current kill and check if is a single
22844 subtree, or a series of subtrees[1]. If it passes the test, and if the
22845 cursor is at the beginning of a line or after the stars of a currently
22846 empty headline, then the yank is handled specially. How exactly depends
22847 on the value of the following variables.
22849 `org-yank-folded-subtrees'
22850 By default, this variable is non-nil, which results in
22851 subtree(s) being folded after insertion, except if doing so
22852 would swallow text after the yanked text.
22854 `org-yank-adjusted-subtrees'
22855 When non-nil (the default value is nil), the subtree will be
22856 promoted or demoted in order to fit into the local outline tree
22857 structure, which means that the level will be adjusted so that it
22858 becomes the smaller one of the two *visible* surrounding headings.
22860 Any prefix to this command will cause `yank' to be called directly with
22861 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22862 will just
22863 plainly yank the text as it is.
22865 \[1] The test checks if the first non-white line is a heading
22866 and if there are no other headings with fewer stars."
22867 (interactive "P")
22868 (org-yank-generic 'yank arg))
22870 (defun org-yank-generic (command arg)
22871 "Perform some yank-like command.
22873 This function implements the behavior described in the `org-yank'
22874 documentation. However, it has been generalized to work for any
22875 interactive command with similar behavior."
22877 ;; pretend to be command COMMAND
22878 (setq this-command command)
22880 (if arg
22881 (call-interactively command)
22883 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22884 (and (org-kill-is-subtree-p)
22885 (or (bolp)
22886 (and (looking-at "[ \t]*$")
22887 (string-match
22888 "\\`\\*+\\'"
22889 (buffer-substring (point-at-bol) (point)))))))
22890 swallowp)
22891 (cond
22892 ((and subtreep org-yank-folded-subtrees)
22893 (let ((beg (point))
22894 end)
22895 (if (and subtreep org-yank-adjusted-subtrees)
22896 (org-paste-subtree nil nil 'for-yank)
22897 (call-interactively command))
22899 (setq end (point))
22900 (goto-char beg)
22901 (when (and (bolp) subtreep
22902 (not (setq swallowp
22903 (org-yank-folding-would-swallow-text beg end))))
22904 (org-with-limited-levels
22905 (or (looking-at org-outline-regexp)
22906 (re-search-forward org-outline-regexp-bol end t))
22907 (while (and (< (point) end) (looking-at org-outline-regexp))
22908 (outline-hide-subtree)
22909 (org-cycle-show-empty-lines 'folded)
22910 (condition-case nil
22911 (outline-forward-same-level 1)
22912 (error (goto-char end))))))
22913 (when swallowp
22914 (message
22915 "Inserted text not folded because that would swallow text"))
22917 (goto-char end)
22918 (skip-chars-forward " \t\n\r")
22919 (beginning-of-line 1)
22920 (push-mark beg 'nomsg)))
22921 ((and subtreep org-yank-adjusted-subtrees)
22922 (let ((beg (point-at-bol)))
22923 (org-paste-subtree nil nil 'for-yank)
22924 (push-mark beg 'nomsg)))
22926 (call-interactively command))))))
22928 (defun org-yank-folding-would-swallow-text (beg end)
22929 "Would hide-subtree at BEG swallow any text after END?"
22930 (let (level)
22931 (org-with-limited-levels
22932 (save-excursion
22933 (goto-char beg)
22934 (when (or (looking-at org-outline-regexp)
22935 (re-search-forward org-outline-regexp-bol end t))
22936 (setq level (org-outline-level)))
22937 (goto-char end)
22938 (skip-chars-forward " \t\r\n\v\f")
22939 (not (or (eobp)
22940 (and (bolp) (looking-at-p org-outline-regexp)
22941 (<= (org-outline-level) level))))))))
22943 (define-key org-mode-map "\C-y" 'org-yank)
22945 (defun org-back-to-heading (&optional invisible-ok)
22946 "Call `outline-back-to-heading', but provide a better error message."
22947 (condition-case nil
22948 (outline-back-to-heading invisible-ok)
22949 (error (error "Before first headline at position %d in buffer %s"
22950 (point) (current-buffer)))))
22952 (defun org-before-first-heading-p ()
22953 "Before first heading?"
22954 (save-excursion
22955 (end-of-line)
22956 (null (re-search-backward org-outline-regexp-bol nil t))))
22958 (defun org-at-heading-p (&optional ignored)
22959 (outline-on-heading-p t))
22961 (defun org-in-commented-heading-p (&optional no-inheritance)
22962 "Non-nil if point is under a commented heading.
22963 This function also checks ancestors of the current headline,
22964 unless optional argument NO-INHERITANCE is non-nil."
22965 (cond
22966 ((org-before-first-heading-p) nil)
22967 ((let ((headline (nth 4 (org-heading-components))))
22968 (and headline
22969 (let ((case-fold-search nil))
22970 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22971 headline)))))
22972 (no-inheritance nil)
22974 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22976 (defun org-at-comment-p nil
22977 "Is cursor in a commented line?"
22978 (save-excursion
22979 (save-match-data
22980 (beginning-of-line)
22981 (looking-at "^[ \t]*# "))))
22983 (defun org-at-drawer-p nil
22984 "Is cursor at a drawer keyword?"
22985 (save-excursion
22986 (move-beginning-of-line 1)
22987 (looking-at org-drawer-regexp)))
22989 (defun org-at-block-p nil
22990 "Is cursor at a block keyword?"
22991 (save-excursion
22992 (move-beginning-of-line 1)
22993 (looking-at org-block-regexp)))
22995 (defun org-point-at-end-of-empty-headline ()
22996 "If point is at the end of an empty headline, return t, else nil.
22997 If the heading only contains a TODO keyword, it is still still considered
22998 empty."
22999 (let ((case-fold-search nil))
23000 (and (looking-at "[ \t]*$")
23001 org-todo-line-regexp
23002 (save-excursion
23003 (beginning-of-line)
23004 (looking-at org-todo-line-regexp)
23005 (string= (match-string 3) "")))))
23007 (defun org-at-heading-or-item-p ()
23008 (or (org-at-heading-p) (org-at-item-p)))
23010 (defun org-at-target-p ()
23011 (or (org-in-regexp org-radio-target-regexp)
23012 (org-in-regexp org-target-regexp)))
23013 ;; Compatibility alias with Org versions < 7.8.03
23014 (defalias 'org-on-target-p 'org-at-target-p)
23016 (defun org-up-heading-all (arg)
23017 "Move to the heading line of which the present line is a subheading.
23018 This function considers both visible and invisible heading lines.
23019 With argument, move up ARG levels."
23020 (outline-up-heading arg t))
23022 (defun org-up-heading-safe ()
23023 "Move to the heading line of which the present line is a subheading.
23024 This version will not throw an error. It will return the level of the
23025 headline found, or nil if no higher level is found.
23027 Also, this function will be a lot faster than `outline-up-heading',
23028 because it relies on stars being the outline starters. This can really
23029 make a significant difference in outlines with very many siblings."
23030 (when (ignore-errors (org-back-to-heading t))
23031 (let ((level-up (1- (funcall outline-level))))
23032 (and (> level-up 0)
23033 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23034 (funcall outline-level)))))
23036 (defun org-first-sibling-p ()
23037 "Is this heading the first child of its parents?"
23038 (interactive)
23039 (let ((re org-outline-regexp-bol)
23040 level l)
23041 (unless (org-at-heading-p t)
23042 (user-error "Not at a heading"))
23043 (setq level (funcall outline-level))
23044 (save-excursion
23045 (if (not (re-search-backward re nil t))
23047 (setq l (funcall outline-level))
23048 (< l level)))))
23050 (defun org-goto-sibling (&optional previous)
23051 "Goto the next sibling, even if it is invisible.
23052 When PREVIOUS is set, go to the previous sibling instead. Returns t
23053 when a sibling was found. When none is found, return nil and don't
23054 move point."
23055 (let ((fun (if previous 're-search-backward 're-search-forward))
23056 (pos (point))
23057 (re org-outline-regexp-bol)
23058 level l)
23059 (when (ignore-errors (org-back-to-heading t))
23060 (setq level (funcall outline-level))
23061 (catch 'exit
23062 (or previous (forward-char 1))
23063 (while (funcall fun re nil t)
23064 (setq l (funcall outline-level))
23065 (when (< l level) (goto-char pos) (throw 'exit nil))
23066 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23067 (goto-char pos)
23068 nil))))
23070 (defun org-show-siblings ()
23071 "Show all siblings of the current headline."
23072 (save-excursion
23073 (while (org-goto-sibling) (org-flag-heading nil)))
23074 (save-excursion
23075 (while (org-goto-sibling 'previous)
23076 (org-flag-heading nil))))
23078 (defun org-goto-first-child ()
23079 "Goto the first child, even if it is invisible.
23080 Return t when a child was found. Otherwise don't move point and
23081 return nil."
23082 (let (level (pos (point)) (re org-outline-regexp-bol))
23083 (when (ignore-errors (org-back-to-heading t))
23084 (setq level (outline-level))
23085 (forward-char 1)
23086 (if (and (re-search-forward re nil t) (> (outline-level) level))
23087 (progn (goto-char (match-beginning 0)) t)
23088 (goto-char pos) nil))))
23090 (defun org-show-hidden-entry ()
23091 "Show an entry where even the heading is hidden."
23092 (save-excursion
23093 (org-show-entry)))
23095 (defun org-flag-heading (flag &optional entry)
23096 "Flag the current heading. FLAG non-nil means make invisible.
23097 When ENTRY is non-nil, show the entire entry."
23098 (save-excursion
23099 (org-back-to-heading t)
23100 ;; Check if we should show the entire entry
23101 (if entry
23102 (progn
23103 (org-show-entry)
23104 (save-excursion
23105 (and (outline-next-heading)
23106 (org-flag-heading nil))))
23107 (outline-flag-region (max (point-min) (1- (point)))
23108 (save-excursion (outline-end-of-heading) (point))
23109 flag))))
23111 (defun org-get-next-sibling ()
23112 "Move to next heading of the same level, and return point.
23113 If there is no such heading, return nil.
23114 This is like outline-next-sibling, but invisible headings are ok."
23115 (let ((level (funcall outline-level)))
23116 (outline-next-heading)
23117 (while (and (not (eobp)) (> (funcall outline-level) level))
23118 (outline-next-heading))
23119 (unless (or (eobp) (< (funcall outline-level) level))
23120 (point))))
23122 (defun org-get-last-sibling ()
23123 "Move to previous heading of the same level, and return point.
23124 If there is no such heading, return nil."
23125 (let ((opoint (point))
23126 (level (funcall outline-level)))
23127 (outline-previous-heading)
23128 (when (and (/= (point) opoint) (outline-on-heading-p t))
23129 (while (and (> (funcall outline-level) level)
23130 (not (bobp)))
23131 (outline-previous-heading))
23132 (unless (< (funcall outline-level) level)
23133 (point)))))
23135 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23136 "Goto to the end of a subtree."
23137 ;; This contains an exact copy of the original function, but it uses
23138 ;; `org-back-to-heading', to make it work also in invisible
23139 ;; trees. And is uses an invisible-ok argument.
23140 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23141 ;; Furthermore, when used inside Org, finding the end of a large subtree
23142 ;; with many children and grandchildren etc, this can be much faster
23143 ;; than the outline version.
23144 (org-back-to-heading invisible-ok)
23145 (let ((first t)
23146 (level (funcall outline-level)))
23147 (if (and (derived-mode-p 'org-mode) (< level 1000))
23148 ;; A true heading (not a plain list item), in Org
23149 ;; This means we can easily find the end by looking
23150 ;; only for the right number of stars. Using a regexp to do
23151 ;; this is so much faster than using a Lisp loop.
23152 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23153 (forward-char 1)
23154 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23155 ;; something else, do it the slow way
23156 (while (and (not (eobp))
23157 (or first (> (funcall outline-level) level)))
23158 (setq first nil)
23159 (outline-next-heading)))
23160 (unless to-heading
23161 (when (memq (preceding-char) '(?\n ?\^M))
23162 ;; Go to end of line before heading
23163 (forward-char -1)
23164 (when (memq (preceding-char) '(?\n ?\^M))
23165 ;; leave blank line before heading
23166 (forward-char -1)))))
23167 (point))
23169 (defun org-end-of-meta-data (&optional full)
23170 "Skip planning line and properties drawer in current entry.
23171 When optional argument FULL is non-nil, also skip empty lines,
23172 clocking lines and regular drawers at the beginning of the
23173 entry."
23174 (org-back-to-heading t)
23175 (forward-line)
23176 (when (looking-at-p org-planning-line-re) (forward-line))
23177 (when (looking-at org-property-drawer-re)
23178 (goto-char (match-end 0))
23179 (forward-line))
23180 (when (and full (not (org-at-heading-p)))
23181 (catch 'exit
23182 (let ((end (save-excursion (outline-next-heading) (point)))
23183 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23184 (while (not (eobp))
23185 (cond ((looking-at-p org-drawer-regexp)
23186 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23187 (forward-line)
23188 (throw 'exit t)))
23189 ((looking-at-p re) (forward-line))
23190 (t (throw 'exit t))))))))
23192 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23193 "Move forward to the ARG'th subheading at same level as this one.
23194 Stop at the first and last subheadings of a superior heading.
23195 Normally this only looks at visible headings, but when INVISIBLE-OK is
23196 non-nil it will also look at invisible ones."
23197 (interactive "p")
23198 (let ((backward? (and arg (< arg 0))))
23199 (if (org-before-first-heading-p)
23200 (if backward? (goto-char (point-min)) (outline-next-heading))
23201 (org-back-to-heading invisible-ok)
23202 (unless backward? (end-of-line)) ;do not match current headline
23203 (let ((level (- (match-end 0) (match-beginning 0) 1))
23204 (f (if backward? #'re-search-backward #'re-search-forward))
23205 (count (if arg (abs arg) 1))
23206 (result (point)))
23207 (while (and (> count 0)
23208 (funcall f org-outline-regexp-bol nil 'move))
23209 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23210 (cond ((< l level) (setq count 0))
23211 ((and (= l level)
23212 (or invisible-ok
23213 (not (org-invisible-p
23214 (line-beginning-position)))))
23215 (cl-decf count)
23216 (when (= l level) (setq result (point)))))))
23217 (goto-char result))
23218 (beginning-of-line))))
23220 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23221 "Move backward to the ARG'th subheading at same level as this one.
23222 Stop at the first and last subheadings of a superior heading."
23223 (interactive "p")
23224 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23226 (defun org-next-visible-heading (arg)
23227 "Move to the next visible heading.
23229 This function wraps `outline-next-visible-heading' with
23230 `org-with-limited-levels' in order to skip over inline tasks and
23231 respect customization of `org-odd-levels-only'."
23232 (interactive "p")
23233 (org-with-limited-levels
23234 (outline-next-visible-heading arg)))
23236 (defun org-previous-visible-heading (arg)
23237 "Move to the previous visible heading.
23239 This function wraps `outline-previous-visible-heading' with
23240 `org-with-limited-levels' in order to skip over inline tasks and
23241 respect customization of `org-odd-levels-only'."
23242 (interactive "p")
23243 (org-with-limited-levels
23244 (outline-previous-visible-heading arg)))
23246 (defun org-next-block (arg &optional backward block-regexp)
23247 "Jump to the next block.
23249 With a prefix argument ARG, jump forward ARG many blocks.
23251 When BACKWARD is non-nil, jump to the previous block.
23253 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23254 Match data is set according to this regexp when the function
23255 returns.
23257 Return point at beginning of the opening line of found block.
23258 Throw an error if no block is found."
23259 (interactive "p")
23260 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23261 (case-fold-search t)
23262 (search-fn (if backward #'re-search-backward #'re-search-forward))
23263 (count (or arg 1))
23264 (origin (point))
23265 last-element)
23266 (if backward (beginning-of-line) (end-of-line))
23267 (while (and (> count 0) (funcall search-fn re nil t))
23268 (let ((element (save-excursion
23269 (goto-char (match-beginning 0))
23270 (save-match-data (org-element-at-point)))))
23271 (when (and (memq (org-element-type element)
23272 '(center-block comment-block dynamic-block
23273 example-block export-block quote-block
23274 special-block src-block verse-block))
23275 (<= (match-beginning 0)
23276 (org-element-property :post-affiliated element)))
23277 (setq last-element element)
23278 (cl-decf count))))
23279 (if (= count 0)
23280 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23281 (save-match-data (org-show-context)))
23282 (goto-char origin)
23283 (user-error "No %s code blocks" (if backward "previous" "further")))))
23285 (defun org-previous-block (arg &optional block-regexp)
23286 "Jump to the previous block.
23287 With a prefix argument ARG, jump backward ARG many source blocks.
23288 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23289 (interactive "p")
23290 (org-next-block arg t block-regexp))
23292 (defun org-forward-paragraph ()
23293 "Move forward to beginning of next paragraph or equivalent.
23295 The function moves point to the beginning of the next visible
23296 structural element, which can be a paragraph, a table, a list
23297 item, etc. It also provides some special moves for convenience:
23299 - On an affiliated keyword, jump to the beginning of the
23300 relative element.
23301 - On an item or a footnote definition, move to the second
23302 element inside, if any.
23303 - On a table or a property drawer, jump after it.
23304 - On a verse or source block, stop after blank lines."
23305 (interactive)
23306 (unless (eobp)
23307 (let* ((deactivate-mark nil)
23308 (element (org-element-at-point))
23309 (type (org-element-type element))
23310 (post-affiliated (org-element-property :post-affiliated element))
23311 (contents-begin (org-element-property :contents-begin element))
23312 (contents-end (org-element-property :contents-end element))
23313 (end (let ((end (org-element-property :end element)) (parent element))
23314 (while (and (setq parent (org-element-property :parent parent))
23315 (= (org-element-property :contents-end parent) end))
23316 (setq end (org-element-property :end parent)))
23317 end)))
23318 (cond ((not element)
23319 (skip-chars-forward " \r\t\n")
23320 (or (eobp) (beginning-of-line)))
23321 ;; On affiliated keywords, move to element's beginning.
23322 ((< (point) post-affiliated)
23323 (goto-char post-affiliated))
23324 ;; At a table row, move to the end of the table. Similarly,
23325 ;; at a node property, move to the end of the property
23326 ;; drawer.
23327 ((memq type '(node-property table-row))
23328 (goto-char (org-element-property
23329 :end (org-element-property :parent element))))
23330 ((memq type '(property-drawer table)) (goto-char end))
23331 ;; Consider blank lines as separators in verse and source
23332 ;; blocks to ease editing.
23333 ((memq type '(src-block verse-block))
23334 (when (eq type 'src-block)
23335 (setq contents-end
23336 (save-excursion (goto-char end)
23337 (skip-chars-backward " \r\t\n")
23338 (line-beginning-position))))
23339 (beginning-of-line)
23340 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23341 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23342 (goto-char end)
23343 (skip-chars-forward " \r\t\n")
23344 (if (= (point) contents-end) (goto-char end)
23345 (beginning-of-line))))
23346 ;; With no contents, just skip element.
23347 ((not contents-begin) (goto-char end))
23348 ;; If contents are invisible, skip the element altogether.
23349 ((org-invisible-p (line-end-position))
23350 (cl-case type
23351 (headline
23352 (org-with-limited-levels (outline-next-visible-heading 1)))
23353 ;; At a plain list, make sure we move to the next item
23354 ;; instead of skipping the whole list.
23355 (plain-list (forward-char)
23356 (org-forward-paragraph))
23357 (otherwise (goto-char end))))
23358 ((>= (point) contents-end) (goto-char end))
23359 ((>= (point) contents-begin)
23360 ;; This can only happen on paragraphs and plain lists.
23361 (cl-case type
23362 (paragraph (goto-char end))
23363 ;; At a plain list, try to move to second element in
23364 ;; first item, if possible.
23365 (plain-list (end-of-line)
23366 (org-forward-paragraph))))
23367 ;; When contents start on the middle of a line (e.g. in
23368 ;; items and footnote definitions), try to reach first
23369 ;; element starting after current line.
23370 ((> (line-end-position) contents-begin)
23371 (end-of-line)
23372 (org-forward-paragraph))
23373 (t (goto-char contents-begin))))))
23375 (defun org-backward-paragraph ()
23376 "Move backward to start of previous paragraph or equivalent.
23378 The function moves point to the beginning of the current
23379 structural element, which can be a paragraph, a table, a list
23380 item, etc., or to the beginning of the previous visible one if
23381 point is already there. It also provides some special moves for
23382 convenience:
23384 - On an affiliated keyword, jump to the first one.
23385 - On a table or a property drawer, move to its beginning.
23386 - On comment, example, export, src and verse blocks, stop
23387 before blank lines."
23388 (interactive)
23389 (unless (bobp)
23390 (let* ((deactivate-mark nil)
23391 (element (org-element-at-point))
23392 (type (org-element-type element))
23393 (contents-end (org-element-property :contents-end element))
23394 (post-affiliated (org-element-property :post-affiliated element))
23395 (begin (org-element-property :begin element))
23396 (special? ;blocks handled specially
23397 (memq type '(comment-block example-block export-block src-block
23398 verse-block)))
23399 (contents-begin
23400 (if special?
23401 ;; These types have no proper contents. Fake line
23402 ;; below the block opening line as contents beginning.
23403 (save-excursion (goto-char begin) (line-beginning-position 2))
23404 (org-element-property :contents-begin element))))
23405 (cond
23406 ((not element) (goto-char (point-min)))
23407 ((= (point) begin)
23408 (backward-char)
23409 (org-backward-paragraph))
23410 ((<= (point) post-affiliated) (goto-char begin))
23411 ;; Special behavior: on a table or a property drawer, move to
23412 ;; its beginning.
23413 ((memq type '(node-property table-row))
23414 (goto-char (org-element-property
23415 :post-affiliated (org-element-property :parent element))))
23416 (special?
23417 (if (<= (point) contents-begin) (goto-char post-affiliated)
23418 ;; Inside a verse block, see blank lines as paragraph
23419 ;; separators.
23420 (let ((origin (point)))
23421 (skip-chars-backward " \r\t\n" contents-begin)
23422 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23423 (skip-chars-forward " \r\t\n" origin)
23424 (if (= (point) origin) (goto-char contents-begin)
23425 (beginning-of-line))))))
23426 ((eq type 'paragraph) (goto-char contents-begin)
23427 ;; When at first paragraph in an item or a footnote definition,
23428 ;; move directly to beginning of line.
23429 (let ((parent-contents
23430 (org-element-property
23431 :contents-begin (org-element-property :parent element))))
23432 (when (and parent-contents (= parent-contents contents-begin))
23433 (beginning-of-line))))
23434 ;; At the end of a greater element, move to the beginning of
23435 ;; the last element within.
23436 ((and contents-end (>= (point) contents-end))
23437 (goto-char (1- contents-end))
23438 (org-backward-paragraph))
23439 (t (goto-char (or post-affiliated begin))))
23440 ;; Ensure we never leave point invisible.
23441 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23443 (defun org-forward-element ()
23444 "Move forward by one element.
23445 Move to the next element at the same level, when possible."
23446 (interactive)
23447 (cond ((eobp) (user-error "Cannot move further down"))
23448 ((org-with-limited-levels (org-at-heading-p))
23449 (let ((origin (point)))
23450 (goto-char (org-end-of-subtree nil t))
23451 (unless (org-with-limited-levels (org-at-heading-p))
23452 (goto-char origin)
23453 (user-error "Cannot move further down"))))
23455 (let* ((elem (org-element-at-point))
23456 (end (org-element-property :end elem))
23457 (parent (org-element-property :parent elem)))
23458 (cond ((and parent (= (org-element-property :contents-end parent) end))
23459 (goto-char (org-element-property :end parent)))
23460 ((integer-or-marker-p end) (goto-char end))
23461 (t (message "No element at point")))))))
23463 (defun org-backward-element ()
23464 "Move backward by one element.
23465 Move to the previous element at the same level, when possible."
23466 (interactive)
23467 (cond ((bobp) (user-error "Cannot move further up"))
23468 ((org-with-limited-levels (org-at-heading-p))
23469 ;; At a headline, move to the previous one, if any, or stay
23470 ;; here.
23471 (let ((origin (point)))
23472 (org-with-limited-levels (org-backward-heading-same-level 1))
23473 ;; When current headline has no sibling above, move to its
23474 ;; parent.
23475 (when (= (point) origin)
23476 (or (org-with-limited-levels (org-up-heading-safe))
23477 (progn (goto-char origin)
23478 (user-error "Cannot move further up"))))))
23480 (let* ((elem (org-element-at-point))
23481 (beg (org-element-property :begin elem)))
23482 (cond
23483 ;; Move to beginning of current element if point isn't
23484 ;; there already.
23485 ((null beg) (message "No element at point"))
23486 ((/= (point) beg) (goto-char beg))
23487 (t (goto-char beg)
23488 (skip-chars-backward " \r\t\n")
23489 (unless (bobp)
23490 (let ((prev (org-element-at-point)))
23491 (goto-char (org-element-property :begin prev))
23492 (while (and (setq prev (org-element-property :parent prev))
23493 (<= (org-element-property :end prev) beg))
23494 (goto-char (org-element-property :begin prev)))))))))))
23496 (defun org-up-element ()
23497 "Move to upper element."
23498 (interactive)
23499 (if (org-with-limited-levels (org-at-heading-p))
23500 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23501 (let* ((elem (org-element-at-point))
23502 (parent (org-element-property :parent elem)))
23503 (if parent (goto-char (org-element-property :begin parent))
23504 (if (org-with-limited-levels (org-before-first-heading-p))
23505 (user-error "No surrounding element")
23506 (org-with-limited-levels (org-back-to-heading)))))))
23508 (defun org-down-element ()
23509 "Move to inner element."
23510 (interactive)
23511 (let ((element (org-element-at-point)))
23512 (cond
23513 ((memq (org-element-type element) '(plain-list table))
23514 (goto-char (org-element-property :contents-begin element))
23515 (forward-char))
23516 ((memq (org-element-type element) org-element-greater-elements)
23517 ;; If contents are hidden, first disclose them.
23518 (when (org-invisible-p (line-end-position)) (org-cycle))
23519 (goto-char (or (org-element-property :contents-begin element)
23520 (user-error "No content for this element"))))
23521 (t (user-error "No inner element")))))
23523 (defun org-drag-element-backward ()
23524 "Move backward element at point."
23525 (interactive)
23526 (let ((elem (or (org-element-at-point)
23527 (user-error "No element at point"))))
23528 (if (eq (org-element-type elem) 'headline)
23529 ;; Preserve point when moving a whole tree, even if point was
23530 ;; on blank lines below the headline.
23531 (let ((offset (skip-chars-backward " \t\n")))
23532 (unwind-protect (org-move-subtree-up)
23533 (forward-char (- offset))))
23534 (let ((prev-elem
23535 (save-excursion
23536 (goto-char (org-element-property :begin elem))
23537 (skip-chars-backward " \r\t\n")
23538 (unless (bobp)
23539 (let* ((beg (org-element-property :begin elem))
23540 (prev (org-element-at-point))
23541 (up prev))
23542 (while (and (setq up (org-element-property :parent up))
23543 (<= (org-element-property :end up) beg))
23544 (setq prev up))
23545 prev)))))
23546 ;; Error out if no previous element or previous element is
23547 ;; a parent of the current one.
23548 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23549 (user-error "Cannot drag element backward")
23550 (let ((pos (point)))
23551 (org-element-swap-A-B prev-elem elem)
23552 (goto-char (+ (org-element-property :begin prev-elem)
23553 (- pos (org-element-property :begin elem))))))))))
23555 (defun org-drag-element-forward ()
23556 "Move forward element at point."
23557 (interactive)
23558 (let* ((pos (point))
23559 (elem (or (org-element-at-point)
23560 (user-error "No element at point"))))
23561 (when (= (point-max) (org-element-property :end elem))
23562 (user-error "Cannot drag element forward"))
23563 (goto-char (org-element-property :end elem))
23564 (let ((next-elem (org-element-at-point)))
23565 (when (or (org-element-nested-p elem next-elem)
23566 (and (eq (org-element-type next-elem) 'headline)
23567 (not (eq (org-element-type elem) 'headline))))
23568 (goto-char pos)
23569 (user-error "Cannot drag element forward"))
23570 ;; Compute new position of point: it's shifted by NEXT-ELEM
23571 ;; body's length (without final blanks) and by the length of
23572 ;; blanks between ELEM and NEXT-ELEM.
23573 (let ((size-next (- (save-excursion
23574 (goto-char (org-element-property :end next-elem))
23575 (skip-chars-backward " \r\t\n")
23576 (forward-line)
23577 ;; Small correction if buffer doesn't end
23578 ;; with a newline character.
23579 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23580 (org-element-property :begin next-elem)))
23581 (size-blank (- (org-element-property :end elem)
23582 (save-excursion
23583 (goto-char (org-element-property :end elem))
23584 (skip-chars-backward " \r\t\n")
23585 (forward-line)
23586 (point)))))
23587 (org-element-swap-A-B elem next-elem)
23588 (goto-char (+ pos size-next size-blank))))))
23590 (defun org-drag-line-forward (arg)
23591 "Drag the line at point ARG lines forward."
23592 (interactive "p")
23593 (dotimes (_ (abs arg))
23594 (let ((c (current-column)))
23595 (if (< 0 arg)
23596 (progn
23597 (beginning-of-line 2)
23598 (transpose-lines 1)
23599 (beginning-of-line 0))
23600 (transpose-lines 1)
23601 (beginning-of-line -1))
23602 (org-move-to-column c))))
23604 (defun org-drag-line-backward (arg)
23605 "Drag the line at point ARG lines backward."
23606 (interactive "p")
23607 (org-drag-line-forward (- arg)))
23609 (defun org-mark-element ()
23610 "Put point at beginning of this element, mark at end.
23612 Interactively, if this command is repeated or (in Transient Mark
23613 mode) if the mark is active, it marks the next element after the
23614 ones already marked."
23615 (interactive)
23616 (let (deactivate-mark)
23617 (if (and (called-interactively-p 'any)
23618 (or (and (eq last-command this-command) (mark t))
23619 (and transient-mark-mode mark-active)))
23620 (set-mark
23621 (save-excursion
23622 (goto-char (mark))
23623 (goto-char (org-element-property :end (org-element-at-point)))))
23624 (let ((element (org-element-at-point)))
23625 (end-of-line)
23626 (push-mark (org-element-property :end element) t t)
23627 (goto-char (org-element-property :begin element))))))
23629 (defun org-narrow-to-element ()
23630 "Narrow buffer to current element."
23631 (interactive)
23632 (let ((elem (org-element-at-point)))
23633 (cond
23634 ((eq (car elem) 'headline)
23635 (narrow-to-region
23636 (org-element-property :begin elem)
23637 (org-element-property :end elem)))
23638 ((memq (car elem) org-element-greater-elements)
23639 (narrow-to-region
23640 (org-element-property :contents-begin elem)
23641 (org-element-property :contents-end elem)))
23643 (narrow-to-region
23644 (org-element-property :begin elem)
23645 (org-element-property :end elem))))))
23647 (defun org-transpose-element ()
23648 "Transpose current and previous elements, keeping blank lines between.
23649 Point is moved after both elements."
23650 (interactive)
23651 (org-skip-whitespace)
23652 (let ((end (org-element-property :end (org-element-at-point))))
23653 (org-drag-element-backward)
23654 (goto-char end)))
23656 (defun org-unindent-buffer ()
23657 "Un-indent the visible part of the buffer.
23658 Relative indentation (between items, inside blocks, etc.) isn't
23659 modified."
23660 (interactive)
23661 (unless (eq major-mode 'org-mode)
23662 (user-error "Cannot un-indent a buffer not in Org mode"))
23663 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23664 (unindent-tree
23665 (lambda (contents)
23666 (dolist (element (reverse contents))
23667 (if (memq (org-element-type element) '(headline section))
23668 (funcall unindent-tree (org-element-contents element))
23669 (save-excursion
23670 (save-restriction
23671 (narrow-to-region
23672 (org-element-property :begin element)
23673 (org-element-property :end element))
23674 (org-do-remove-indentation))))))))
23675 (funcall unindent-tree (org-element-contents parse-tree))))
23677 (defun org-show-children (&optional level)
23678 "Show all direct subheadings of this heading.
23679 Prefix arg LEVEL is how many levels below the current level
23680 should be shown. Default is enough to cause the following
23681 heading to appear."
23682 (interactive "p")
23683 (save-excursion
23684 (org-back-to-heading t)
23685 (let* ((current-level (funcall outline-level))
23686 (max-level (org-get-valid-level
23687 current-level
23688 (if level (prefix-numeric-value level) 1)))
23689 (end (save-excursion (org-end-of-subtree t t)))
23690 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
23691 (past-first-child nil)
23692 ;; Make sure to skip inlinetasks.
23693 (re (format regexp-fmt
23694 current-level
23695 (cond
23696 ((not (featurep 'org-inlinetask)) "")
23697 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
23699 (t (1- org-inlinetask-min-level))))))
23700 ;; Display parent heading.
23701 (outline-flag-region (line-end-position 0) (line-end-position) nil)
23702 (forward-line)
23703 ;; Display children. First child may be deeper than expected
23704 ;; MAX-LEVEL. Since we want to display it anyway, adjust
23705 ;; MAX-LEVEL accordingly.
23706 (while (re-search-forward re end t)
23707 (unless past-first-child
23708 (setq re (format regexp-fmt
23709 current-level
23710 (max (funcall outline-level) max-level)))
23711 (setq past-first-child t))
23712 (outline-flag-region (line-end-position 0) (line-end-position) nil)))))
23714 (defun org-show-subtree ()
23715 "Show everything after this heading at deeper levels."
23716 (interactive)
23717 (outline-flag-region
23718 (point)
23719 (save-excursion
23720 (org-end-of-subtree t t))
23721 nil))
23723 (defun org-show-entry ()
23724 "Show the body directly following this heading.
23725 Show the heading too, if it is currently invisible."
23726 (interactive)
23727 (save-excursion
23728 (ignore-errors
23729 (org-back-to-heading t)
23730 (outline-flag-region
23731 (max (point-min) (1- (point)))
23732 (save-excursion
23733 (if (re-search-forward
23734 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23735 (match-beginning 1)
23736 (point-max)))
23737 nil)
23738 (org-cycle-hide-drawers 'children))))
23740 (defun org-make-options-regexp (kwds &optional extra)
23741 "Make a regular expression for keyword lines.
23742 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23743 when non-nil, is a regexp matching keywords names."
23744 (concat "^[ \t]*#\\+\\("
23745 (regexp-opt kwds)
23746 (and extra (concat (and kwds "\\|") extra))
23747 "\\):[ \t]*\\(.*\\)"))
23749 ;;;; Finish up
23751 (provide 'org)
23753 (run-hooks 'org-load-hook)
23755 ;;; org.el ends here