Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob2810b8ced1e39a93c92216dc57461ea624491505
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
10 ;; Version: 9.1.10
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (require 'org-macs)
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocking-buffer "org-clock" ())
130 (declare-function org-clocktable-shift "org-clock" (dir n))
131 (declare-function
132 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-link-parser "org-element" ())
142 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
143 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-put-property "org-element" (element property value))
146 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
147 (declare-function org-element-type "org-element" (element))
148 (declare-function org-element-update-syntax "org-element" ())
149 (declare-function org-id-find-id-file "org-id" (id))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
152 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
153 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
154 (declare-function org-plot/gnuplot "org-plot" (&optional params))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-beginning-of-field "org-table" (&optional n))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
160 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
161 (declare-function org-table-cut-region "org-table" (beg end))
162 (declare-function org-table-edit-field "org-table" (arg))
163 (declare-function org-table-end "org-table" (&optional table-type))
164 (declare-function org-table-end-of-field "org-table" (&optional n))
165 (declare-function org-table-insert-row "org-table" (&optional arg))
166 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
167 (declare-function org-table-maybe-eval-formula "org-table" ())
168 (declare-function org-table-maybe-recalculate-line "org-table" ())
169 (declare-function org-table-next-row "org-table" ())
170 (declare-function org-table-paste-rectangle "org-table" ())
171 (declare-function org-table-recalculate "org-table" (&optional all noalign))
172 (declare-function
173 org-table-sort-lines "org-table"
174 (&optional with-case sorting-type getkey-func compare-func interactive?))
175 (declare-function org-table-shrink "org-table" (&optional begin end))
176 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp)
186 (defvar org-element-paragraph-separate)
188 ;; load languages based on value of `org-babel-load-languages'
189 (defvar org-babel-load-languages)
191 ;;;###autoload
192 (defun org-babel-do-load-languages (sym value)
193 "Load the languages defined in `org-babel-load-languages'."
194 (set-default sym value)
195 (dolist (pair org-babel-load-languages)
196 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
197 (if active
198 (require (intern (concat "ob-" lang)))
199 (funcall 'fmakunbound
200 (intern (concat "org-babel-execute:" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-expand-body:" lang)))))))
204 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
205 ;;;###autoload
206 (defun org-babel-load-file (file &optional compile)
207 "Load Emacs Lisp source code blocks in the Org FILE.
208 This function exports the source code using `org-babel-tangle'
209 and then loads the resulting file using `load-file'. With prefix
210 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
211 file to byte-code before it is loaded."
212 (interactive "fFile to load: \nP")
213 (let* ((age (lambda (file)
214 (float-time
215 (time-subtract (current-time)
216 (nth 5 (or (file-attributes (file-truename file))
217 (file-attributes file)))))))
218 (base-name (file-name-sans-extension file))
219 (exported-file (concat base-name ".el")))
220 ;; tangle if the Org file is newer than the elisp file
221 (unless (and (file-exists-p exported-file)
222 (> (funcall age file) (funcall age exported-file)))
223 ;; Tangle-file traversal returns reversed list of tangled files
224 ;; and we want to evaluate the first target.
225 (setq exported-file
226 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
227 (message "%s %s"
228 (if compile
229 (progn (byte-compile-file exported-file 'load)
230 "Compiled and loaded")
231 (progn (load-file exported-file) "Loaded"))
232 exported-file)))
234 (defcustom org-babel-load-languages '((emacs-lisp . t))
235 "Languages which can be evaluated in Org buffers.
236 This list can be used to load support for any of the languages
237 below, note that each language will depend on a different set of
238 system executables and/or Emacs modes. When a language is
239 \"loaded\", then code blocks in that language can be evaluated
240 with `org-babel-execute-src-block' bound by default to C-c
241 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
242 be set to remove code block evaluation from the C-c C-c
243 keybinding. By default only Emacs Lisp (which has no
244 requirements) is loaded."
245 :group 'org-babel
246 :set 'org-babel-do-load-languages
247 :version "24.1"
248 :type '(alist :tag "Babel Languages"
249 :key-type
250 (choice
251 (const :tag "Awk" awk)
252 (const :tag "C" C)
253 (const :tag "R" R)
254 (const :tag "Asymptote" asymptote)
255 (const :tag "Calc" calc)
256 (const :tag "Clojure" clojure)
257 (const :tag "CSS" css)
258 (const :tag "Ditaa" ditaa)
259 (const :tag "Dot" dot)
260 (const :tag "Ebnf2ps" ebnf2ps)
261 (const :tag "Emacs Lisp" emacs-lisp)
262 (const :tag "Forth" forth)
263 (const :tag "Fortran" fortran)
264 (const :tag "Gnuplot" gnuplot)
265 (const :tag "Haskell" haskell)
266 (const :tag "hledger" hledger)
267 (const :tag "IO" io)
268 (const :tag "J" J)
269 (const :tag "Java" java)
270 (const :tag "Javascript" js)
271 (const :tag "LaTeX" latex)
272 (const :tag "Ledger" ledger)
273 (const :tag "Lilypond" lilypond)
274 (const :tag "Lisp" lisp)
275 (const :tag "Makefile" makefile)
276 (const :tag "Maxima" maxima)
277 (const :tag "Matlab" matlab)
278 (const :tag "Mscgen" mscgen)
279 (const :tag "Ocaml" ocaml)
280 (const :tag "Octave" octave)
281 (const :tag "Org" org)
282 (const :tag "Perl" perl)
283 (const :tag "Pico Lisp" picolisp)
284 (const :tag "PlantUML" plantuml)
285 (const :tag "Python" python)
286 (const :tag "Ruby" ruby)
287 (const :tag "Sass" sass)
288 (const :tag "Scala" scala)
289 (const :tag "Scheme" scheme)
290 (const :tag "Screen" screen)
291 (const :tag "Shell Script" shell)
292 (const :tag "Shen" shen)
293 (const :tag "Sql" sql)
294 (const :tag "Sqlite" sqlite)
295 (const :tag "Stan" stan)
296 (const :tag "Vala" vala))
297 :value-type (boolean :tag "Activate" :value t)))
299 ;;;; Customization variables
300 (defcustom org-clone-delete-id nil
301 "Remove ID property of clones of a subtree.
302 When non-nil, clones of a subtree don't inherit the ID property.
303 Otherwise they inherit the ID property with a new unique
304 identifier."
305 :type 'boolean
306 :version "24.1"
307 :group 'org-id)
309 ;;; Version
310 (org-check-version)
312 ;;;###autoload
313 (defun org-version (&optional here full message)
314 "Show the Org version.
315 Interactively, or when MESSAGE is non-nil, show it in echo area.
316 With prefix argument, or when HERE is non-nil, insert it at point.
317 In non-interactive uses, a reduced version string is output unless
318 FULL is given."
319 (interactive (list current-prefix-arg t (not current-prefix-arg)))
320 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
321 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
322 (load-suffixes (list ".el"))
323 (org-install-dir
324 (ignore-errors (org-find-library-dir "org-loaddefs"))))
325 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
326 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
327 (let* ((load-suffixes save-load-suffixes)
328 (release (org-release))
329 (git-version (org-git-version))
330 (version (format "Org mode version %s (%s @ %s)"
331 release
332 git-version
333 (if org-install-dir
334 (if (string= org-dir org-install-dir)
335 org-install-dir
336 (concat "mixed installation! "
337 org-install-dir
338 " and "
339 org-dir))
340 "org-loaddefs.el can not be found!")))
341 (version1 (if full version release)))
342 (when here (insert version1))
343 (when message (message "%s" version1))
344 version1)))
346 (defconst org-version (org-version))
349 ;;; Syntax Constants
351 ;;;; Block
353 (defconst org-block-regexp
354 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
355 "Regular expression for hiding blocks.")
357 (defconst org-dblock-start-re
358 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
359 "Matches the start line of a dynamic block, with parameters.")
361 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
362 "Matches the end of a dynamic block.")
364 ;;;; Clock and Planning
366 (defconst org-clock-string "CLOCK:"
367 "String used as prefix for timestamps clocking work hours on an item.")
369 (defvar org-closed-string "CLOSED:"
370 "String used as the prefix for timestamps logging closing a TODO entry.")
372 (defvar org-deadline-string "DEADLINE:"
373 "String to mark deadline entries.
374 \\<org-mode-map>
375 A deadline is this string, followed by a time stamp. It must be
376 a word, terminated by a colon. You can insert a schedule keyword
377 and a timestamp with `\\[org-deadline]'.")
379 (defvar org-scheduled-string "SCHEDULED:"
380 "String to mark scheduled TODO entries.
381 \\<org-mode-map>
382 A schedule is this string, followed by a time stamp. It must be
383 a word, terminated by a colon. You can insert a schedule keyword
384 and a timestamp with `\\[org-schedule]'.")
386 (defconst org-ds-keyword-length
387 (+ 2
388 (apply #'max
389 (mapcar #'length
390 (list org-deadline-string org-scheduled-string
391 org-clock-string org-closed-string))))
392 "Maximum length of the DEADLINE and SCHEDULED keywords.")
394 (defconst org-planning-line-re
395 (concat "^[ \t]*"
396 (regexp-opt
397 (list org-closed-string org-deadline-string org-scheduled-string)
399 "Matches a line with planning info.
400 Matched keyword is in group 1.")
402 (defconst org-clock-line-re
403 (concat "^[ \t]*" org-clock-string)
404 "Matches a line with clock info.")
406 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
407 "Matches the DEADLINE keyword.")
409 (defconst org-deadline-time-regexp
410 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
411 "Matches the DEADLINE keyword together with a time stamp.")
413 (defconst org-deadline-time-hour-regexp
414 (concat "\\<" org-deadline-string
415 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
416 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
418 (defconst org-deadline-line-regexp
419 (concat "\\<\\(" org-deadline-string "\\).*")
420 "Matches the DEADLINE keyword and the rest of the line.")
422 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
423 "Matches the SCHEDULED keyword.")
425 (defconst org-scheduled-time-regexp
426 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
427 "Matches the SCHEDULED keyword together with a time stamp.")
429 (defconst org-scheduled-time-hour-regexp
430 (concat "\\<" org-scheduled-string
431 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
432 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
434 (defconst org-closed-time-regexp
435 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
436 "Matches the CLOSED keyword together with a time stamp.")
438 (defconst org-keyword-time-regexp
439 (concat "\\<"
440 (regexp-opt
441 (list org-scheduled-string org-deadline-string org-closed-string
442 org-clock-string)
444 " *[[<]\\([^]>]+\\)[]>]")
445 "Matches any of the 4 keywords, together with the time stamp.")
447 (defconst org-keyword-time-not-clock-regexp
448 (concat
449 "\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string) t)
452 " *[[<]\\([^]>]+\\)[]>]")
453 "Matches any of the 3 keywords, together with the time stamp.")
455 (defconst org-maybe-keyword-time-regexp
456 (concat "\\(\\<"
457 (regexp-opt
458 (list org-scheduled-string org-deadline-string org-closed-string
459 org-clock-string)
461 "\\)?"
462 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
463 "\\|"
464 "<%%([^\r\n>]*>\\)")
465 "Matches a timestamp, possibly preceded by a keyword.")
467 (defconst org-all-time-keywords
468 (mapcar (lambda (w) (substring w 0 -1))
469 (list org-scheduled-string org-deadline-string
470 org-clock-string org-closed-string))
471 "List of time keywords.")
473 ;;;; Drawer
475 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
476 "Matches first or last line of a hidden block.
477 Group 1 contains drawer's name or \"END\".")
479 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
480 "Regular expression matching the first line of a property drawer.")
482 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
483 "Regular expression matching the last line of a property drawer.")
485 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
486 "Regular expression matching the first line of a clock drawer.")
488 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a clock drawer.")
491 (defconst org-property-drawer-re
492 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
493 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
494 "[ \t]*:END:[ \t]*$")
495 "Matches an entire property drawer.")
497 (defconst org-clock-drawer-re
498 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
499 org-clock-drawer-end-re "\\)\n?")
500 "Matches an entire clock drawer.")
502 ;;;; Headline
504 (defconst org-heading-keyword-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline with some keyword.
507 This regexp will match the headline of any node which has the
508 exact keyword that is put into the format. The keyword isn't in
509 any group by default, but the stars and the body are.")
511 (defconst org-heading-keyword-maybe-regexp-format
512 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
513 "Printf format for a regexp matching a headline, possibly with some keyword.
514 This regexp can match any headline with the specified keyword, or
515 without a keyword. The keyword isn't in any group by default,
516 but the stars and the body are.")
518 (defconst org-archive-tag "ARCHIVE"
519 "The tag that marks a subtree as archived.
520 An archived subtree does not open during visibility cycling, and does
521 not contribute to the agenda listings.")
523 (eval-and-compile
524 (defconst org-comment-string "COMMENT"
525 "Entries starting with this keyword will never be exported.
526 \\<org-mode-map>
527 An entry can be toggled between COMMENT and normal with
528 `\\[org-toggle-comment]'."))
531 ;;;; LaTeX Environments and Fragments
533 (defconst org-latex-regexps
534 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
535 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
536 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
537 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
538 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
539 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
540 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
541 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
542 "Regular expressions for matching embedded LaTeX.")
544 ;;;; Node Property
546 (defconst org-effort-property "Effort"
547 "The property that is being used to keep track of effort estimates.
548 Effort estimates given in this property need to have the format H:MM.")
550 ;;;; Table
552 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
553 "Detect an org-type or table-type table.")
555 (defconst org-table-line-regexp "^[ \t]*|"
556 "Detect an org-type table line.")
558 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
559 "Detect an org-type table line.")
561 (defconst org-table-hline-regexp "^[ \t]*|-"
562 "Detect an org-type table hline.")
564 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
565 "Detect a table-type table hline.")
567 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
568 "Detect the first line outside a table when searching from within it.
569 This works for both table types.")
571 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
572 "Detect a #+TBLFM line.")
574 ;;;; Timestamp
576 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp-inactive
580 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
581 "Regular expression for fast inactive time stamp matching.")
583 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
584 "Regular expression for fast time stamp matching.")
586 (defconst org-ts-regexp0
587 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
588 "Regular expression matching time strings for analysis.
589 This one does not require the space after the date, so it can be used
590 on a string that terminates immediately after the date.")
592 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.")
595 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
596 "Regular expression matching time stamps, with groups.")
598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
599 "Regular expression matching time stamps (also [..]), with groups.")
601 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
602 "Regular expression matching a time stamp range.")
604 (defconst org-tr-regexp-both
605 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
609 org-ts-regexp "\\)?")
610 "Regular expression matching a time stamp or time stamp range.")
612 (defconst org-tsr-regexp-both
613 (concat org-ts-regexp-both "\\(--?-?"
614 org-ts-regexp-both "\\)?")
615 "Regular expression matching a time stamp or time stamp range.
616 The time stamps may be either active or inactive.")
618 (defconst org-repeat-re
619 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
620 "Regular expression for specifying repeated events.
621 After a match, group 1 contains the repeat expression.")
623 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
624 "Formats for `format-time-string' which are used for time stamps.")
627 ;;; The custom variables
629 (defgroup org nil
630 "Outline-based notes management and organizer."
631 :tag "Org"
632 :group 'outlines
633 :group 'calendar)
635 (defcustom org-mode-hook nil
636 "Mode hook for Org mode, run after the mode was turned on."
637 :group 'org
638 :type 'hook)
640 (defcustom org-load-hook nil
641 "Hook that is run after org.el has been loaded."
642 :group 'org
643 :type 'hook)
645 (defcustom org-log-buffer-setup-hook nil
646 "Hook that is run after an Org log buffer is created."
647 :group 'org
648 :version "24.1"
649 :type 'hook)
651 (defvar org-modules) ; defined below
652 (defvar org-modules-loaded nil
653 "Have the modules been loaded already?")
655 (defun org-load-modules-maybe (&optional force)
656 "Load all extensions listed in `org-modules'."
657 (when (or force (not org-modules-loaded))
658 (dolist (ext org-modules)
659 (condition-case nil (require ext)
660 (error (message "Problems while trying to load feature `%s'" ext))))
661 (setq org-modules-loaded t)))
663 (defun org-set-modules (var value)
664 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
665 (set var value)
666 (when (featurep 'org)
667 (org-load-modules-maybe 'force)
668 (org-element-cache-reset 'all)))
670 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
671 "Modules that should always be loaded together with org.el.
673 If a description starts with <C>, the file is not part of Emacs
674 and loading it will require that you have downloaded and properly
675 installed the Org mode distribution.
677 You can also use this system to load external packages (i.e. neither Org
678 core modules, nor modules from the CONTRIB directory). Just add symbols
679 to the end of the list. If the package is called org-xyz.el, then you need
680 to add the symbol `xyz', and the package must have a call to:
682 (provide \\='org-xyz)
684 For export specific modules, see also `org-export-backends'."
685 :group 'org
686 :set 'org-set-modules
687 :version "24.4"
688 :package-version '(Org . "8.0")
689 :type
690 '(set :greedy t
691 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
692 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
693 (const :tag " crypt: Encryption of subtrees" org-crypt)
694 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
695 (const :tag " docview: Links to doc-view buffers" org-docview)
696 (const :tag " eww: Store link to url of eww" org-eww)
697 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
698 (const :tag " habit: Track your consistency with habits" org-habit)
699 (const :tag " id: Global IDs for identifying entries" org-id)
700 (const :tag " info: Links to Info nodes" org-info)
701 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
702 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
703 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
704 (const :tag " mouse: Additional mouse support" org-mouse)
705 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
706 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
707 (const :tag " tempo: Fast completion for structures" org-tempo)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
717 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
722 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
723 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
724 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
725 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
726 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
727 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
728 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
729 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
730 (const :tag "C man: Support for links to manpages in Org mode" org-man)
731 (const :tag "C mew: Links to Mew folders/messages" org-mew)
732 (const :tag "C mtags: Support for muse-like tags" org-mtags)
733 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
734 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
735 (const :tag "C registry: A registry for Org links" org-registry)
736 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
737 (const :tag "C secretary: Team management with Org" org-secretary)
738 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
739 (const :tag "C toc: Table of contents for Org buffer" org-toc)
740 (const :tag "C track: Keep up with Org mode development" org-track)
741 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
742 (const :tag "C vm: Links to VM folders/messages" org-vm)
743 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
744 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
745 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
747 (defvar org-export-registered-backends) ; From ox.el.
748 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
749 (declare-function org-export-backend-name "ox" (backend) t)
750 (defcustom org-export-backends '(ascii html icalendar latex odt)
751 "List of export back-ends that should be always available.
753 If a description starts with <C>, the file is not part of Emacs
754 and loading it will require that you have downloaded and properly
755 installed the Org mode distribution.
757 Unlike to `org-modules', libraries in this list will not be
758 loaded along with Org, but only once the export framework is
759 needed.
761 This variable needs to be set before org.el is loaded. If you
762 need to make a change while Emacs is running, use the customize
763 interface or run the following code, where VAL stands for the new
764 value of the variable, after updating it:
766 (progn
767 (setq org-export-registered-backends
768 (cl-remove-if-not
769 (lambda (backend)
770 (let ((name (org-export-backend-name backend)))
771 (or (memq name val)
772 (catch \\='parentp
773 (dolist (b val)
774 (and (org-export-derived-backend-p b name)
775 (throw \\='parentp t)))))))
776 org-export-registered-backends))
777 (let ((new-list (mapcar #\\='org-export-backend-name
778 org-export-registered-backends)))
779 (dolist (backend val)
780 (cond
781 ((not (load (format \"ox-%s\" backend) t t))
782 (message \"Problems while trying to load export back-end \\=`%s\\='\"
783 backend))
784 ((not (memq backend new-list)) (push backend new-list))))
785 (set-default \\='org-export-backends new-list)))
787 Adding a back-end to this list will also pull the back-end it
788 depends on, if any."
789 :group 'org
790 :group 'org-export
791 :version "26.1"
792 :package-version '(Org . "9.0")
793 :initialize 'custom-initialize-set
794 :set (lambda (var val)
795 (if (not (featurep 'ox)) (set-default var val)
796 ;; Any back-end not required anymore (not present in VAL and not
797 ;; a parent of any back-end in the new value) is removed from the
798 ;; list of registered back-ends.
799 (setq org-export-registered-backends
800 (cl-remove-if-not
801 (lambda (backend)
802 (let ((name (org-export-backend-name backend)))
803 (or (memq name val)
804 (catch 'parentp
805 (dolist (b val)
806 (and (org-export-derived-backend-p b name)
807 (throw 'parentp t)))))))
808 org-export-registered-backends))
809 ;; Now build NEW-LIST of both new back-ends and required
810 ;; parents.
811 (let ((new-list (mapcar #'org-export-backend-name
812 org-export-registered-backends)))
813 (dolist (backend val)
814 (cond
815 ((not (load (format "ox-%s" backend) t t))
816 (message "Problems while trying to load export back-end `%s'"
817 backend))
818 ((not (memq backend new-list)) (push backend new-list))))
819 ;; Set VAR to that list with fixed dependencies.
820 (set-default var new-list))))
821 :type '(set :greedy t
822 (const :tag " ascii Export buffer to ASCII format" ascii)
823 (const :tag " beamer Export buffer to Beamer presentation" beamer)
824 (const :tag " html Export buffer to HTML format" html)
825 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
826 (const :tag " latex Export buffer to LaTeX format" latex)
827 (const :tag " man Export buffer to MAN format" man)
828 (const :tag " md Export buffer to Markdown format" md)
829 (const :tag " odt Export buffer to ODT format" odt)
830 (const :tag " org Export buffer to Org format" org)
831 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
832 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
833 (const :tag "C deck Export buffer to deck.js presentations" deck)
834 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
835 (const :tag "C groff Export buffer to Groff format" groff)
836 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
837 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
838 (const :tag "C s5 Export buffer to s5 presentations" s5)
839 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
841 (eval-after-load 'ox
842 '(dolist (backend org-export-backends)
843 (condition-case nil (require (intern (format "ox-%s" backend)))
844 (error (message "Problems while trying to load export back-end `%s'"
845 backend)))))
847 (defcustom org-support-shift-select nil
848 "Non-nil means make shift-cursor commands select text when possible.
849 \\<org-mode-map>\
851 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
852 start selecting a region, or enlarge regions started in this way.
853 In Org mode, in special contexts, these same keys are used for
854 other purposes, important enough to compete with shift selection.
855 Org tries to balance these needs by supporting `shift-select-mode'
856 outside these special contexts, under control of this variable.
858 The default of this variable is nil, to avoid confusing behavior. Shifted
859 cursor keys will then execute Org commands in the following contexts:
860 - on a headline, changing TODO state (left/right) and priority (up/down)
861 - on a time stamp, changing the time
862 - in a plain list item, changing the bullet type
863 - in a property definition line, switching between allowed values
864 - in the BEGIN line of a clock table (changing the time block).
865 Outside these contexts, the commands will throw an error.
867 When this variable is t and the cursor is not in a special
868 context, Org mode will support shift-selection for making and
869 enlarging regions. To make this more effective, the bullet
870 cycling will no longer happen anywhere in an item line, but only
871 if the cursor is exactly on the bullet.
873 If you set this variable to the symbol `always', then the keys
874 will not be special in headlines, property lines, and item lines,
875 to make shift selection work there as well. If this is what you
876 want, you can use the following alternative commands:
877 `\\[org-todo]' and `\\[org-priority]' \
878 to change TODO state and priority,
879 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
880 can be used to switch TODO sets,
881 `\\[org-ctrl-c-minus]' to cycle item bullet types,
882 and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up."
886 :group 'org
887 :type '(choice
888 (const :tag "Never" nil)
889 (const :tag "When outside special context" t)
890 (const :tag "Everywhere except timestamps" always)))
892 (defcustom org-loop-over-headlines-in-active-region nil
893 "Shall some commands act upon headlines in the active region?
895 When set to t, some commands will be performed in all headlines
896 within the active region.
898 When set to `start-level', some commands will be performed in all
899 headlines within the active region, provided that these headlines
900 are of the same level than the first one.
902 When set to a string, those commands will be performed on the
903 matching headlines within the active region. Such string must be
904 a tags/property/todo match as it is used in the agenda tags view.
906 The list of commands is: `org-schedule', `org-deadline',
907 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
908 `org-archive-to-archive-sibling'. The archiving commands skip
909 already archived entries."
910 :type '(choice (const :tag "Don't loop" nil)
911 (const :tag "All headlines in active region" t)
912 (const :tag "In active region, headlines at the same level than the first one" start-level)
913 (string :tag "Tags/Property/Todo matcher"))
914 :version "24.1"
915 :group 'org-todo
916 :group 'org-archive)
918 (defcustom org-startup-folded t
919 "Non-nil means entering Org mode will switch to OVERVIEW.
921 This can also be configured on a per-file basis by adding one of
922 the following lines anywhere in the buffer:
924 #+STARTUP: fold (or `overview', this is equivalent)
925 #+STARTUP: nofold (or `showall', this is equivalent)
926 #+STARTUP: content
927 #+STARTUP: showeverything
929 Set `org-agenda-inhibit-startup' to a non-nil value if you want
930 to ignore this option when Org opens agenda files for the first
931 time."
932 :group 'org-startup
933 :type '(choice
934 (const :tag "nofold: show all" nil)
935 (const :tag "fold: overview" t)
936 (const :tag "content: all headlines" content)
937 (const :tag "show everything, even drawers" showeverything)))
939 (defcustom org-startup-truncated t
940 "Non-nil means entering Org mode will set `truncate-lines'.
941 This is useful since some lines containing links can be very long and
942 uninteresting. Also tables look terrible when wrapped.
944 The variable `org-startup-truncated' allows to configure
945 truncation for Org mode different to the other modes that use the
946 variable `truncate-lines' and as a shortcut instead of putting
947 the variable `truncate-lines' into the `org-mode-hook'. If one
948 wants to configure truncation for Org mode not statically but
949 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
950 the variable `truncate-lines' has to be used because in such a
951 case it is too late to set the variable `org-startup-truncated'."
952 :group 'org-startup
953 :type 'boolean)
955 (defcustom org-startup-indented nil
956 "Non-nil means turn on `org-indent-mode' on startup.
957 This can also be configured on a per-file basis by adding one of
958 the following lines anywhere in the buffer:
960 #+STARTUP: indent
961 #+STARTUP: noindent"
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Not" nil)
965 (const :tag "Globally (slow on startup in large files)" t)))
967 (defcustom org-use-sub-superscripts t
968 "Non-nil means interpret \"_\" and \"^\" for display.
970 If you want to control how Org exports those characters, see
971 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
972 used to be an alias for `org-export-with-sub-superscripts' in
973 Org <8.0, it is not anymore.
975 When this option is turned on, you can use TeX-like syntax for
976 sub- and superscripts within the buffer. Several characters after
977 \"_\" or \"^\" will be considered as a single item - so grouping
978 with {} is normally not needed. For example, the following things
979 will be parsed as single sub- or superscripts:
981 10^24 or 10^tau several digits will be considered 1 item.
982 10^-12 or 10^-tau a leading sign with digits or a word
983 x^2-y^3 will be read as x^2 - y^3, because items are
984 terminated by almost any nonword/nondigit char.
985 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
987 Still, ambiguity is possible. So when in doubt, use {} to enclose
988 the sub/superscript. If you set this variable to the symbol `{}',
989 the braces are *required* in order to trigger interpretations as
990 sub/superscript. This can be helpful in documents that need \"_\"
991 frequently in plain text."
992 :group 'org-startup
993 :version "24.4"
994 :package-version '(Org . "8.0")
995 :type '(choice
996 (const :tag "Always interpret" t)
997 (const :tag "Only with braces" {})
998 (const :tag "Never interpret" nil)))
1000 (defcustom org-startup-with-beamer-mode nil
1001 "Non-nil means turn on `org-beamer-mode' on startup.
1002 This can also be configured on a per-file basis by adding one of
1003 the following lines anywhere in the buffer:
1005 #+STARTUP: beamer"
1006 :group 'org-startup
1007 :version "24.1"
1008 :type 'boolean)
1010 (defcustom org-startup-align-all-tables nil
1011 "Non-nil means align all tables when visiting a file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-shrink-all-tables nil
1020 "Non-nil means shrink all table columns with a width cookie.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: shrink"
1024 :group 'org-startup
1025 :type 'boolean
1026 :version "27.1"
1027 :package-version '(Org . "9.2")
1028 :safe #'booleanp)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1065 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1066 These keys are also used by other packages like Shift Select mode,
1067 CUA mode or Windmove. If you want to use Org mode together with
1068 one of these other modes, or more generally if you would like to
1069 move some Org mode commands to other keys, set this variable and
1070 configure the keys with the variable `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots. When a non-empty string,
1123 use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1133 (defvar org-display-table nil
1134 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car of each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-show-empty-lines
1421 org-optimize-window-after-visibility-change)
1422 "Hook that is run after `org-cycle' has changed the buffer visibility.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that was set by the most recent `org-cycle' command. The
1425 argument is a symbol. After a global state change, it can have the values
1426 `overview', `contents', or `all'. After a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook
1430 :version "26.1"
1431 :package-version '(Org . "8.3"))
1433 (defgroup org-edit-structure nil
1434 "Options concerning structure editing in Org mode."
1435 :tag "Org Edit Structure"
1436 :group 'org-structure)
1438 (defcustom org-odd-levels-only nil
1439 "Non-nil means skip even levels and only use odd levels for the outline.
1440 This has the effect that two stars are being added/taken away in
1441 promotion/demotion commands. It also influences how levels are
1442 handled by the exporters.
1443 Changing it requires restart of `font-lock-mode' to become effective
1444 for fontification also in regions already fontified.
1445 You may also set this on a per-file basis by adding one of the following
1446 lines to the buffer:
1448 #+STARTUP: odd
1449 #+STARTUP: oddeven"
1450 :group 'org-edit-structure
1451 :group 'org-appearance
1452 :type 'boolean)
1454 (defcustom org-adapt-indentation t
1455 "Non-nil means adapt indentation to outline node level.
1457 When this variable is set, Org assumes that you write outlines by
1458 indenting text in each node to align with the headline (after the
1459 stars). The following issues are influenced by this variable:
1461 - The indentation is increased by one space in a demotion
1462 command, and decreased by one in a promotion command. However,
1463 in the latter case, if shifting some line in the entry body
1464 would alter document structure (e.g., insert a new headline),
1465 indentation is not changed at all.
1467 - Property drawers and planning information is inserted indented
1468 when this variable is set. When nil, they will not be indented.
1470 - TAB indents a line relative to current level. The lines below
1471 a headline will be indented when this variable is set.
1473 Note that this is all about true indentation, by adding and
1474 removing space characters. See also \"org-indent.el\" which does
1475 level-dependent indentation in a virtual way, i.e. at display
1476 time in Emacs."
1477 :group 'org-edit-structure
1478 :type 'boolean
1479 :safe #'booleanp)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defgroup org-sparse-trees nil
1657 "Options concerning sparse trees in Org mode."
1658 :tag "Org Sparse Trees"
1659 :group 'org-structure)
1661 (defcustom org-highlight-sparse-tree-matches t
1662 "Non-nil means highlight all matches that define a sparse tree.
1663 The highlights will automatically disappear the next time the buffer is
1664 changed by an edit command."
1665 :group 'org-sparse-trees
1666 :type 'boolean)
1668 (defcustom org-remove-highlights-with-change t
1669 "Non-nil means any change to the buffer will remove temporary highlights.
1670 \\<org-mode-map>\
1671 Such highlights are created by `org-occur' and `org-clock-display'.
1672 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1673 to get rid of the highlights.
1674 The highlights created by `org-toggle-latex-fragment' always need
1675 `\\[org-toggle-latex-fragment]' to be removed."
1676 :group 'org-sparse-trees
1677 :group 'org-time
1678 :type 'boolean)
1680 (defcustom org-occur-case-fold-search t
1681 "Non-nil means `org-occur' should be case-insensitive.
1682 If set to `smart' the search will be case-insensitive only if it
1683 doesn't specify any upper case character."
1684 :group 'org-sparse-trees
1685 :version "26.1"
1686 :type '(choice
1687 (const :tag "Case-sensitive" nil)
1688 (const :tag "Case-insensitive" t)
1689 (const :tag "Case-insensitive for lower case searches only" smart)))
1691 (defcustom org-occur-hook '(org-first-headline-recenter)
1692 "Hook that is run after `org-occur' has constructed a sparse tree.
1693 This can be used to recenter the window to show as much of the structure
1694 as possible."
1695 :group 'org-sparse-trees
1696 :type 'hook)
1698 (defgroup org-table nil
1699 "Options concerning tables in Org mode."
1700 :tag "Org Table"
1701 :group 'org)
1703 (defcustom org-self-insert-cluster-for-undo nil
1704 "Non-nil means cluster self-insert commands for undo when possible.
1705 If this is set, then, like in the Emacs command loop, 20 consecutive
1706 characters will be undone together.
1707 This is configurable, because there is some impact on typing performance."
1708 :group 'org-table
1709 :type 'boolean)
1711 (defcustom org-table-tab-recognizes-table.el t
1712 "Non-nil means TAB will automatically notice a table.el table.
1713 When it sees such a table, it moves point into it and - if necessary -
1714 calls `table-recognize-table'."
1715 :group 'org-table-editing
1716 :type 'boolean)
1718 (defgroup org-link nil
1719 "Options concerning links in Org mode."
1720 :tag "Org Link"
1721 :group 'org)
1723 (defvar-local org-link-abbrev-alist-local nil
1724 "Buffer-local version of `org-link-abbrev-alist', which see.
1725 The value of this is taken from the #+LINK lines.")
1727 (defcustom org-link-parameters
1728 '(("doi" :follow org--open-doi-link)
1729 ("elisp" :follow org--open-elisp-link)
1730 ("file" :complete org-file-complete-link)
1731 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1732 ("help" :follow org--open-help-link)
1733 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1734 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1735 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1736 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1737 ("shell" :follow org--open-shell-link))
1738 "An alist of properties that defines all the links in Org mode.
1739 The key in each association is a string of the link type.
1740 Subsequent optional elements make up a p-list of link properties.
1742 :follow - A function that takes the link path as an argument.
1744 :export - A function that takes the link path, description and
1745 export-backend as arguments.
1747 :store - A function responsible for storing the link. See the
1748 function `org-store-link-functions'.
1750 :complete - A function that inserts a link with completion. The
1751 function takes one optional prefix arg.
1753 :face - A face for the link, or a function that returns a face.
1754 The function takes one argument which is the link path. The
1755 default face is `org-link'.
1757 :mouse-face - The mouse-face. The default is `highlight'.
1759 :display - `full' will not fold the link in descriptive
1760 display. Default is `org-link'.
1762 :help-echo - A string or function that takes (window object position)
1763 as arguments and returns a string.
1765 :keymap - A keymap that is active on the link. The default is
1766 `org-mouse-map'.
1768 :htmlize-link - A function for the htmlize-link. Defaults
1769 to (list :uri \"type:path\")
1771 :activate-func - A function to run at the end of font-lock
1772 activation. The function must accept (link-start link-end path bracketp)
1773 as arguments."
1774 :group 'org-link
1775 :type '(alist :tag "Link display parameters"
1776 :value-type plist)
1777 :version "26.1"
1778 :package-version '(Org . "9.1"))
1780 (defun org-link-get-parameter (type key)
1781 "Get TYPE link property for KEY.
1782 TYPE is a string and KEY is a plist keyword."
1783 (plist-get
1784 (cdr (assoc type org-link-parameters))
1785 key))
1787 (defun org-link-set-parameters (type &rest parameters)
1788 "Set link TYPE properties to PARAMETERS.
1789 PARAMETERS should be :key val pairs."
1790 (let ((data (assoc type org-link-parameters)))
1791 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1792 (push (cons type parameters) org-link-parameters)
1793 (org-make-link-regexps)
1794 (org-element-update-syntax))))
1796 (defun org-link-types ()
1797 "Return a list of known link types."
1798 (mapcar #'car org-link-parameters))
1800 (defcustom org-link-abbrev-alist nil
1801 "Alist of link abbreviations.
1802 The car of each element is a string, to be replaced at the start of a link.
1803 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1804 links in Org buffers can have an optional tag after a double colon, e.g.,
1806 [[linkkey:tag][description]]
1808 The `linkkey' must be a single word, starting with a letter, followed
1809 by letters, numbers, `-' or `_'.
1811 If REPLACE is a string, the tag will simply be appended to create the link.
1812 If the string contains \"%s\", the tag will be inserted there. If the string
1813 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1814 at that point (see the function `url-hexify-string'). If the string contains
1815 the specifier \"%(my-function)\", then the custom function `my-function' will
1816 be invoked: this function takes the tag as its only argument and must return
1817 a string.
1819 REPLACE may also be a function that will be called with the tag as the
1820 only argument to create the link, which should be returned as a string.
1822 See the manual for examples."
1823 :group 'org-link
1824 :type '(repeat
1825 (cons
1826 (string :tag "Protocol")
1827 (choice
1828 (string :tag "Format")
1829 (function)))))
1831 (defcustom org-descriptive-links t
1832 "Non-nil means Org will display descriptive links.
1833 E.g. [[https://orgmode.org][Org website]] will be displayed as
1834 \"Org Website\", hiding the link itself and just displaying its
1835 description. When set to nil, Org will display the full links
1836 literally.
1838 You can interactively set the value of this variable by calling
1839 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1840 :group 'org-link
1841 :type 'boolean)
1843 (defcustom org-link-file-path-type 'adaptive
1844 "How the path name in file links should be stored.
1845 Valid values are:
1847 relative Relative to the current directory, i.e. the directory of the file
1848 into which the link is being inserted.
1849 absolute Absolute path, if possible with ~ for home directory.
1850 noabbrev Absolute path, no abbreviation of home directory.
1851 adaptive Use relative path for files in the current directory and sub-
1852 directories of it. For other files, use an absolute path."
1853 :group 'org-link
1854 :type '(choice
1855 (const relative)
1856 (const absolute)
1857 (const noabbrev)
1858 (const adaptive)))
1860 (defvaralias 'org-activate-links 'org-highlight-links)
1861 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1862 "Types of links that should be highlighted in Org files.
1864 This is a list of symbols, each one of them leading to the
1865 highlighting of a certain link type.
1867 You can still open links that are not highlighted.
1869 In principle, it does not hurt to turn on highlighting for all
1870 link types. There may be a small gain when turning off unused
1871 link types. The types are:
1873 bracket The recommended [[link][description]] or [[link]] links with hiding.
1874 angle Links in angular brackets that may contain whitespace like
1875 <bbdb:Carsten Dominik>.
1876 plain Plain links in normal text, no whitespace, like http://google.com.
1877 radio Text that is matched by a radio target, see manual for details.
1878 tag Tag settings in a headline (link to tag search).
1879 date Time stamps (link to calendar).
1880 footnote Footnote labels.
1882 If you set this variable during an Emacs session, use `org-mode-restart'
1883 in the Org buffer so that the change takes effect."
1884 :group 'org-link
1885 :group 'org-appearance
1886 :type '(set :greedy t
1887 (const :tag "Double bracket links" bracket)
1888 (const :tag "Angular bracket links" angle)
1889 (const :tag "Plain text links" plain)
1890 (const :tag "Radio target matches" radio)
1891 (const :tag "Tags" tag)
1892 (const :tag "Timestamps" date)
1893 (const :tag "Footnotes" footnote)))
1895 (defcustom org-make-link-description-function nil
1896 "Function to use for generating link descriptions from links.
1897 This function must take two parameters: the first one is the
1898 link, the second one is the description generated by
1899 `org-insert-link'. The function should return the description to
1900 use."
1901 :group 'org-link
1902 :type '(choice (const nil) (function)))
1904 (defgroup org-link-store nil
1905 "Options concerning storing links in Org mode."
1906 :tag "Org Store Link"
1907 :group 'org-link)
1909 (defcustom org-url-hexify-p t
1910 "When non-nil, hexify URL when creating a link."
1911 :type 'boolean
1912 :version "24.3"
1913 :group 'org-link-store)
1915 (defcustom org-email-link-description-format "Email %c: %.30s"
1916 "Format of the description part of a link to an email or usenet message.
1917 The following %-escapes will be replaced by corresponding information:
1919 %F full \"From\" field
1920 %f name, taken from \"From\" field, address if no name
1921 %T full \"To\" field
1922 %t first name in \"To\" field, address if no name
1923 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1924 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1925 %s subject
1926 %d date
1927 %m message-id.
1929 You may use normal field width specification between the % and the letter.
1930 This is for example useful to limit the length of the subject.
1932 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1933 :group 'org-link-store
1934 :type 'string)
1936 (defcustom org-from-is-user-regexp
1937 (let (r1 r2)
1938 (when (and user-mail-address (not (string= user-mail-address "")))
1939 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1940 (when (and user-full-name (not (string= user-full-name "")))
1941 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1942 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1943 "Regexp matched against the \"From:\" header of an email or usenet message.
1944 It should match if the message is from the user him/herself."
1945 :group 'org-link-store
1946 :type 'regexp)
1948 (defcustom org-context-in-file-links t
1949 "Non-nil means file links from `org-store-link' contain context.
1950 \\<org-mode-map>
1951 A search string will be added to the file name with :: as separator
1952 and used to find the context when the link is activated by the command
1953 `org-open-at-point'. When this option is t, the entire active region
1954 will be placed in the search string of the file link. If set to a
1955 positive integer, only the first n lines of context will be stored.
1957 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1958 \\[org-store-link]')
1959 negates this setting for the duration of the command."
1960 :group 'org-link-store
1961 :type '(choice boolean integer))
1963 (defcustom org-keep-stored-link-after-insertion nil
1964 "Non-nil means keep link in list for entire session.
1965 \\<org-mode-map>
1966 The command `org-store-link' adds a link pointing to the current
1967 location to an internal list. These links accumulate during a session.
1968 The command `org-insert-link' can be used to insert links into any
1969 Org file (offering completion for all stored links).
1971 When this option is nil, every link which has been inserted once using
1972 `\\[org-insert-link]' will be removed from the list, to make completing the \
1973 unused
1974 links more efficient."
1975 :group 'org-link-store
1976 :type 'boolean)
1978 (defgroup org-link-follow nil
1979 "Options concerning following links in Org mode."
1980 :tag "Org Follow Link"
1981 :group 'org-link)
1983 (defcustom org-link-translation-function nil
1984 "Function to translate links with different syntax to Org syntax.
1985 This can be used to translate links created for example by the Planner
1986 or emacs-wiki packages to Org syntax.
1987 The function must accept two parameters, a TYPE containing the link
1988 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1989 which is everything after the link protocol. It should return a cons
1990 with possibly modified values of type and path.
1991 Org contains a function for this, so if you set this variable to
1992 `org-translate-link-from-planner', you should be able follow many
1993 links created by planner."
1994 :group 'org-link-follow
1995 :type '(choice (const nil) (function)))
1997 (defcustom org-follow-link-hook nil
1998 "Hook that is run after a link has been followed."
1999 :group 'org-link-follow
2000 :type 'hook)
2002 (defcustom org-tab-follows-link nil
2003 "Non-nil means on links TAB will follow the link.
2004 Needs to be set before org.el is loaded.
2005 This really should not be used, it does not make sense, and the
2006 implementation is bad."
2007 :group 'org-link-follow
2008 :type 'boolean)
2010 (defcustom org-return-follows-link nil
2011 "Non-nil means on links RET will follow the link.
2012 In tables, the special behavior of RET has precedence."
2013 :group 'org-link-follow
2014 :type 'boolean)
2016 (defcustom org-mouse-1-follows-link
2017 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2018 "Non-nil means mouse-1 on a link will follow the link.
2019 A longer mouse click will still set point. Needs to be set
2020 before org.el is loaded."
2021 :group 'org-link-follow
2022 :version "26.1"
2023 :package-version '(Org . "8.3")
2024 :type '(choice
2025 (const :tag "A double click follows the link" double)
2026 (const :tag "Unconditionally follow the link with mouse-1" t)
2027 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2029 (defcustom org-mark-ring-length 4
2030 "Number of different positions to be recorded in the ring.
2031 Changing this requires a restart of Emacs to work correctly."
2032 :group 'org-link-follow
2033 :type 'integer)
2035 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2036 "Non-nil means internal fuzzy links can only match headlines.
2038 When nil, the a fuzzy link may point to a target or a named
2039 construct in the document. When set to the special value
2040 `query-to-create', offer to create a new headline when none
2041 matched.
2043 Spaces and statistics cookies are ignored during heading searches."
2044 :group 'org-link-follow
2045 :version "24.1"
2046 :type '(choice
2047 (const :tag "Use fuzzy text search" nil)
2048 (const :tag "Match only exact headline" t)
2049 (const :tag "Match exact headline or query to create it"
2050 query-to-create))
2051 :safe #'symbolp)
2053 (defcustom org-link-frame-setup
2054 '((vm . vm-visit-folder-other-frame)
2055 (vm-imap . vm-visit-imap-folder-other-frame)
2056 (gnus . org-gnus-no-new-news)
2057 (file . find-file-other-window)
2058 (wl . wl-other-frame))
2059 "Setup the frame configuration for following links.
2060 When following a link with Emacs, it may often be useful to display
2061 this link in another window or frame. This variable can be used to
2062 set this up for the different types of links.
2063 For VM, use any of
2064 `vm-visit-folder'
2065 `vm-visit-folder-other-window'
2066 `vm-visit-folder-other-frame'
2067 For Gnus, use any of
2068 `gnus'
2069 `gnus-other-frame'
2070 `org-gnus-no-new-news'
2071 For FILE, use any of
2072 `find-file'
2073 `find-file-other-window'
2074 `find-file-other-frame'
2075 For Wanderlust use any of
2076 `wl'
2077 `wl-other-frame'
2078 For the calendar, use the variable `calendar-setup'.
2079 For BBDB, it is currently only possible to display the matches in
2080 another window."
2081 :group 'org-link-follow
2082 :type '(list
2083 (cons (const vm)
2084 (choice
2085 (const vm-visit-folder)
2086 (const vm-visit-folder-other-window)
2087 (const vm-visit-folder-other-frame)))
2088 (cons (const vm-imap)
2089 (choice
2090 (const vm-visit-imap-folder)
2091 (const vm-visit-imap-folder-other-window)
2092 (const vm-visit-imap-folder-other-frame)))
2093 (cons (const gnus)
2094 (choice
2095 (const gnus)
2096 (const gnus-other-frame)
2097 (const org-gnus-no-new-news)))
2098 (cons (const file)
2099 (choice
2100 (const find-file)
2101 (const find-file-other-window)
2102 (const find-file-other-frame)))
2103 (cons (const wl)
2104 (choice
2105 (const wl)
2106 (const wl-other-frame)))))
2108 (defcustom org-display-internal-link-with-indirect-buffer nil
2109 "Non-nil means use indirect buffer to display infile links.
2110 Activating internal links (from one location in a file to another location
2111 in the same file) normally just jumps to the location. When the link is
2112 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2113 is displayed in
2114 another window. When this option is set, the other window actually displays
2115 an indirect buffer clone of the current buffer, to avoid any visibility
2116 changes to the current buffer."
2117 :group 'org-link-follow
2118 :type 'boolean)
2120 (defcustom org-open-non-existing-files nil
2121 "Non-nil means `org-open-file' will open non-existing files.
2122 When nil, an error will be generated.
2123 This variable applies only to external applications because they
2124 might choke on non-existing files. If the link is to a file that
2125 will be opened in Emacs, the variable is ignored."
2126 :group 'org-link-follow
2127 :type 'boolean)
2129 (defcustom org-open-directory-means-index-dot-org nil
2130 "Non-nil means a link to a directory really means to index.org.
2131 When nil, following a directory link will run dired or open a finder/explorer
2132 window on that directory."
2133 :group 'org-link-follow
2134 :type 'boolean)
2136 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2137 "Non-nil means ask for confirmation before executing shell links.
2138 Shell links can be dangerous: just think about a link
2140 [[shell:rm -rf ~/*][Google Search]]
2142 This link would show up in your Org document as \"Google Search\",
2143 but really it would remove your entire home directory.
2144 Therefore we advise against setting this variable to nil.
2145 Just change it to `y-or-n-p' if you want to confirm with a
2146 single keystroke rather than having to type \"yes\"."
2147 :group 'org-link-follow
2148 :type '(choice
2149 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2150 (const :tag "with y-or-n (faster)" y-or-n-p)
2151 (const :tag "no confirmation (dangerous)" nil)))
2152 (put 'org-confirm-shell-link-function
2153 'safe-local-variable
2154 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2156 (defcustom org-confirm-shell-link-not-regexp ""
2157 "A regexp to skip confirmation for shell links."
2158 :group 'org-link-follow
2159 :version "24.1"
2160 :type 'regexp)
2162 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2164 Elisp links can be dangerous: just think about a link
2166 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-elisp-link-not-regexp ""
2183 "A regexp to skip confirmation for Elisp links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defconst org-file-apps-defaults-gnu
2189 '((remote . emacs)
2190 (system . mailcap)
2191 (t . mailcap))
2192 "Default file applications on a UNIX or GNU/Linux system.
2193 See `org-file-apps'.")
2195 (defconst org-file-apps-defaults-macosx
2196 '((remote . emacs)
2197 (system . "open %s")
2198 ("ps.gz" . "gv %s")
2199 ("eps.gz" . "gv %s")
2200 ("dvi" . "xdvi %s")
2201 ("fig" . "xfig %s")
2202 (t . "open %s"))
2203 "Default file applications on a macOS system.
2204 The system \"open\" is known as a default, but we use X11 applications
2205 for some files for which the OS does not have a good default.
2206 See `org-file-apps'.")
2208 (defconst org-file-apps-defaults-windowsnt
2209 (list '(remote . emacs)
2210 (cons 'system (lambda (file _path)
2211 (with-no-warnings (w32-shell-execute "open" file))))
2212 (cons t (lambda (file _path)
2213 (with-no-warnings (w32-shell-execute "open" file)))))
2214 "Default file applications on a Windows NT system.
2215 The system \"open\" is used for most files.
2216 See `org-file-apps'.")
2218 (defcustom org-file-apps
2219 '((auto-mode . emacs)
2220 ("\\.mm\\'" . default)
2221 ("\\.x?html?\\'" . default)
2222 ("\\.pdf\\'" . default))
2223 "External applications for opening `file:path' items in a document.
2224 \\<org-mode-map>\
2226 Org mode uses system defaults for different file types, but
2227 you can use this variable to set the application for a given file
2228 extension. The entries in this list are cons cells where the car identifies
2229 files and the cdr the corresponding command.
2231 Possible values for the file identifier are:
2233 \"string\" A string as a file identifier can be interpreted in different
2234 ways, depending on its contents:
2236 - Alphanumeric characters only:
2237 Match links with this file extension.
2238 Example: (\"pdf\" . \"evince %s\")
2239 to open PDFs with evince.
2241 - Regular expression: Match links where the
2242 filename matches the regexp. If you want to
2243 use groups here, use shy groups.
2245 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2246 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2247 to open *.html and *.xhtml with firefox.
2249 - Regular expression which contains (non-shy) groups:
2250 Match links where the whole link, including \"::\", and
2251 anything after that, matches the regexp.
2252 In a custom command string, %1, %2, etc. are replaced with
2253 the parts of the link that were matched by the groups.
2254 For backwards compatibility, if a command string is given
2255 that does not use any of the group matches, this case is
2256 handled identically to the second one (i.e. match against
2257 file name only).
2258 In a custom function, you can access the group matches with
2259 (match-string n link).
2261 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2262 \"evince -p %1 %s\")
2263 to open [[file:document.pdf::5]] with evince at page 5.
2265 `directory' Matches a directory
2266 `remote' Matches a remote file, accessible through tramp or efs.
2267 Remote files most likely should be visited through Emacs
2268 because external applications cannot handle such paths.
2269 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2270 so all files Emacs knows how to handle. Using this with
2271 command `emacs' will open most files in Emacs. Beware that this
2272 will also open html files inside Emacs, unless you add
2273 (\"html\" . default) to the list as well.
2274 `system' The system command to open files, like `open' on Windows
2275 and macOS, and mailcap under GNU/Linux. This is the command
2276 that will be selected if you call `org-open-at-point' with a
2277 double prefix argument (`\\[universal-argument] \
2278 \\[universal-argument] \\[org-open-at-point]').
2279 t Default for files not matched by any of the other options.
2281 Possible values for the command are:
2283 `emacs' The file will be visited by the current Emacs process.
2284 `default' Use the default application for this file type, which is the
2285 association for t in the list, most likely in the system-specific
2286 part. This can be used to overrule an unwanted setting in the
2287 system-specific variable.
2288 `system' Use the system command for opening files, like \"open\".
2289 This command is specified by the entry whose car is `system'.
2290 Most likely, the system-specific version of this variable
2291 does define this command, but you can overrule/replace it
2292 here.
2293 `mailcap' Use command specified in the mailcaps.
2294 string A command to be executed by a shell; %s will be replaced
2295 by the path to the file.
2296 function A Lisp function, which will be called with two arguments:
2297 the file path and the original link string, without the
2298 \"file:\" prefix.
2300 For more examples, see the system specific constants
2301 `org-file-apps-defaults-macosx'
2302 `org-file-apps-defaults-windowsnt'
2303 `org-file-apps-defaults-gnu'."
2304 :group 'org-link-follow
2305 :type '(repeat
2306 (cons (choice :value ""
2307 (string :tag "Extension")
2308 (const :tag "System command to open files" system)
2309 (const :tag "Default for unrecognized files" t)
2310 (const :tag "Remote file" remote)
2311 (const :tag "Links to a directory" directory)
2312 (const :tag "Any files that have Emacs modes"
2313 auto-mode))
2314 (choice :value ""
2315 (const :tag "Visit with Emacs" emacs)
2316 (const :tag "Use default" default)
2317 (const :tag "Use the system command" system)
2318 (string :tag "Command")
2319 (function :tag "Function")))))
2321 (defcustom org-doi-server-url "http://dx.doi.org/"
2322 "The URL of the DOI server."
2323 :type 'string
2324 :version "24.3"
2325 :group 'org-link-follow)
2327 (defgroup org-refile nil
2328 "Options concerning refiling entries in Org mode."
2329 :tag "Org Refile"
2330 :group 'org)
2332 (defcustom org-directory "~/org"
2333 "Directory with Org files.
2334 This is just a default location to look for Org files. There is no need
2335 at all to put your files into this directory. It is used in the
2336 following situations:
2338 1. When a capture template specifies a target file that is not an
2339 absolute path. The path will then be interpreted relative to
2340 `org-directory'
2341 2. When the value of variable `org-agenda-files' is a single file, any
2342 relative paths in this file will be taken as relative to
2343 `org-directory'."
2344 :group 'org-refile
2345 :group 'org-capture
2346 :type 'directory)
2348 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2349 "Default target for storing notes.
2350 Used as a fall back file for org-capture.el, for templates that
2351 do not specify a target file."
2352 :group 'org-refile
2353 :group 'org-capture
2354 :type 'file)
2356 (defcustom org-reverse-note-order nil
2357 "Non-nil means store new notes at the beginning of a file or entry.
2358 When nil, new notes will be filed to the end of a file or entry.
2359 This can also be a list with cons cells of regular expressions that
2360 are matched against file names, and values."
2361 :group 'org-capture
2362 :group 'org-refile
2363 :type '(choice
2364 (const :tag "Reverse always" t)
2365 (const :tag "Reverse never" nil)
2366 (repeat :tag "By file name regexp"
2367 (cons regexp boolean))))
2369 (defcustom org-log-refile nil
2370 "Information to record when a task is refiled.
2372 Possible values are:
2374 nil Don't add anything
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologrefile
2381 #+STARTUP: logrefile
2382 #+STARTUP: lognoterefile
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords.
2387 When bulk-refiling from the agenda, the value `note' is forbidden and
2388 will temporarily be changed to `time'."
2389 :group 'org-refile
2390 :group 'org-progress
2391 :version "24.1"
2392 :type '(choice
2393 (const :tag "No logging" nil)
2394 (const :tag "Record timestamp" time)
2395 (const :tag "Record timestamp with note." note)))
2397 (defcustom org-refile-targets nil
2398 "Targets for refiling entries with `\\[org-refile]'.
2399 This is a list of cons cells. Each cell contains:
2400 - a specification of the files to be considered, either a list of files,
2401 or a symbol whose function or variable value will be used to retrieve
2402 a file name or a list of file names. If you use `org-agenda-files' for
2403 that, all agenda files will be scanned for targets. Nil means consider
2404 headings in the current buffer.
2405 - A specification of how to find candidate refile targets. This may be
2406 any of:
2407 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2408 This tag has to be present in all target headlines, inheritance will
2409 not be considered.
2410 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2411 todo keyword.
2412 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2413 headlines that are refiling targets.
2414 - a cons cell (:level . N). Any headline of level N is considered a target.
2415 Note that, when `org-odd-levels-only' is set, level corresponds to
2416 order in hierarchy, not to the number of stars.
2417 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2418 Note that, when `org-odd-levels-only' is set, level corresponds to
2419 order in hierarchy, not to the number of stars.
2421 Each element of this list generates a set of possible targets.
2422 The union of these sets is presented (with completion) to
2423 the user by `org-refile'.
2425 You can set the variable `org-refile-target-verify-function' to a function
2426 to verify each headline found by the simple criteria above.
2428 When this variable is nil, all top-level headlines in the current buffer
2429 are used, equivalent to the value `((nil . (:level . 1))'."
2430 :group 'org-refile
2431 :type '(repeat
2432 (cons
2433 (choice :value org-agenda-files
2434 (const :tag "All agenda files" org-agenda-files)
2435 (const :tag "Current buffer" nil)
2436 (function) (variable) (file))
2437 (choice :tag "Identify target headline by"
2438 (cons :tag "Specific tag" (const :value :tag) (string))
2439 (cons :tag "TODO keyword" (const :value :todo) (string))
2440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2441 (cons :tag "Level number" (const :value :level) (integer))
2442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2444 (defcustom org-refile-target-verify-function nil
2445 "Function to verify if the headline at point should be a refile target.
2446 The function will be called without arguments, with point at the
2447 beginning of the headline. It should return t and leave point
2448 where it is if the headline is a valid target for refiling.
2450 If the target should not be selected, the function must return nil.
2451 In addition to this, it may move point to a place from where the search
2452 should be continued. For example, the function may decide that the entire
2453 subtree of the current entry should be excluded and move point to the end
2454 of the subtree."
2455 :group 'org-refile
2456 :type '(choice
2457 (const nil)
2458 (function)))
2460 (defcustom org-refile-use-cache nil
2461 "Non-nil means cache refile targets to speed up the process.
2462 \\<org-mode-map>\
2463 The cache for a particular file will be updated automatically when
2464 the buffer has been killed, or when any of the marker used for flagging
2465 refile targets no longer points at a live buffer.
2466 If you have added new entries to a buffer that might themselves be targets,
2467 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2468 if you find that easier, \
2469 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2470 \\[org-refile]'."
2471 :group 'org-refile
2472 :version "24.1"
2473 :type 'boolean)
2475 (defcustom org-refile-use-outline-path nil
2476 "Non-nil means provide refile targets as paths.
2477 So a level 3 headline will be available as level1/level2/level3.
2479 When the value is `file', also include the file name (without directory)
2480 into the path. In this case, you can also stop the completion after
2481 the file name, to get entries inserted as top level in the file.
2483 When `full-file-path', include the full file path.
2485 When `buffer-name', use the buffer name."
2486 :group 'org-refile
2487 :type '(choice
2488 (const :tag "Not" nil)
2489 (const :tag "Yes" t)
2490 (const :tag "Start with file name" file)
2491 (const :tag "Start with full file path" full-file-path)
2492 (const :tag "Start with buffer name" buffer-name)))
2494 (defcustom org-outline-path-complete-in-steps t
2495 "Non-nil means complete the outline path in hierarchical steps.
2496 When Org uses the refile interface to select an outline path (see
2497 `org-refile-use-outline-path'), the completion of the path can be
2498 done in a single go, or it can be done in steps down the headline
2499 hierarchy. Going in steps is probably the best if you do not use
2500 a special completion package like `ido' or `icicles'. However,
2501 when using these packages, going in one step can be very fast,
2502 while still showing the whole path to the entry."
2503 :group 'org-refile
2504 :type 'boolean)
2506 (defcustom org-refile-allow-creating-parent-nodes nil
2507 "Non-nil means allow the creation of new nodes as refile targets.
2508 New nodes are then created by adding \"/new node name\" to the completion
2509 of an existing node. When the value of this variable is `confirm',
2510 new node creation must be confirmed by the user (recommended).
2511 When nil, the completion must match an existing entry.
2513 Note that, if the new heading is not seen by the criteria
2514 listed in `org-refile-targets', multiple instances of the same
2515 heading would be created by trying again to file under the new
2516 heading."
2517 :group 'org-refile
2518 :type '(choice
2519 (const :tag "Never" nil)
2520 (const :tag "Always" t)
2521 (const :tag "Prompt for confirmation" confirm)))
2523 (defcustom org-refile-active-region-within-subtree nil
2524 "Non-nil means also refile active region within a subtree.
2526 By default `org-refile' doesn't allow refiling regions if they
2527 don't contain a set of subtrees, but it might be convenient to
2528 do so sometimes: in that case, the first line of the region is
2529 converted to a headline before refiling."
2530 :group 'org-refile
2531 :version "24.1"
2532 :type 'boolean)
2534 (defgroup org-todo nil
2535 "Options concerning TODO items in Org mode."
2536 :tag "Org TODO"
2537 :group 'org)
2539 (defgroup org-progress nil
2540 "Options concerning Progress logging in Org mode."
2541 :tag "Org Progress"
2542 :group 'org-time)
2544 (defvar org-todo-interpretation-widgets
2545 '((:tag "Sequence (cycling hits every state)" sequence)
2546 (:tag "Type (cycling directly to DONE)" type))
2547 "The available interpretation symbols for customizing `org-todo-keywords'.
2548 Interested libraries should add to this list.")
2550 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2551 "List of TODO entry keyword sequences and their interpretation.
2552 \\<org-mode-map>This is a list of sequences.
2554 Each sequence starts with a symbol, either `sequence' or `type',
2555 indicating if the keywords should be interpreted as a sequence of
2556 action steps, or as different types of TODO items. The first
2557 keywords are states requiring action - these states will select a headline
2558 for inclusion into the global TODO list Org produces. If one of the
2559 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2560 signify that no further action is necessary. If \"|\" is not found,
2561 the last keyword is treated as the only DONE state of the sequence.
2563 The command `\\[org-todo]' cycles an entry through these states, and one
2564 additional state where no keyword is present. For details about this
2565 cycling, see the manual.
2567 TODO keywords and interpretation can also be set on a per-file basis with
2568 the special #+SEQ_TODO and #+TYP_TODO lines.
2570 Each keyword can optionally specify a character for fast state selection
2571 \(in combination with the variable `org-use-fast-todo-selection')
2572 and specifiers for state change logging, using the same syntax that
2573 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2574 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2575 indicates to record a time stamp each time this state is selected.
2577 Each keyword may also specify if a timestamp or a note should be
2578 recorded when entering or leaving the state, by adding additional
2579 characters in the parenthesis after the keyword. This looks like this:
2580 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2581 record only the time of the state change. With X and Y being either
2582 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2583 Y when leaving the state if and only if the *target* state does not
2584 define X. You may omit any of the fast-selection key or X or /Y,
2585 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2587 For backward compatibility, this variable may also be just a list
2588 of keywords. In this case the interpretation (sequence or type) will be
2589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2590 :group 'org-todo
2591 :group 'org-keywords
2592 :type '(choice
2593 (repeat :tag "Old syntax, just keywords"
2594 (string :tag "Keyword"))
2595 (repeat :tag "New syntax"
2596 (cons
2597 (choice
2598 :tag "Interpretation"
2599 ;;Quick and dirty way to see
2600 ;;`org-todo-interpretations'. This takes the
2601 ;;place of item arguments
2602 :convert-widget
2603 (lambda (widget)
2604 (widget-put widget
2605 :args (mapcar
2606 (lambda (x)
2607 (widget-convert
2608 (cons 'const x)))
2609 org-todo-interpretation-widgets))
2610 widget))
2611 (repeat
2612 (string :tag "Keyword"))))))
2614 (defvar-local org-todo-keywords-1 nil
2615 "All TODO and DONE keywords active in a buffer.")
2616 (defvar org-todo-keywords-for-agenda nil)
2617 (defvar org-done-keywords-for-agenda nil)
2618 (defvar org-todo-keyword-alist-for-agenda nil)
2619 (defvar org-tag-alist-for-agenda nil
2620 "Alist of all tags from all agenda files.")
2621 (defvar org-tag-groups-alist-for-agenda nil
2622 "Alist of all groups tags from all current agenda files.")
2623 (defvar-local org-tag-groups-alist nil)
2624 (defvar org-agenda-contributing-files nil)
2625 (defvar-local org-current-tag-alist nil
2626 "Alist of all tag groups in current buffer.
2627 This variable takes into consideration `org-tag-alist',
2628 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2629 (defvar-local org-not-done-keywords nil)
2630 (defvar-local org-done-keywords nil)
2631 (defvar-local org-todo-heads nil)
2632 (defvar-local org-todo-sets nil)
2633 (defvar-local org-todo-log-states nil)
2634 (defvar-local org-todo-kwd-alist nil)
2635 (defvar-local org-todo-key-alist nil)
2636 (defvar-local org-todo-key-trigger nil)
2638 (defcustom org-todo-interpretation 'sequence
2639 "Controls how TODO keywords are interpreted.
2640 This variable is in principle obsolete and is only used for
2641 backward compatibility, if the interpretation of todo keywords is
2642 not given already in `org-todo-keywords'. See that variable for
2643 more information."
2644 :group 'org-todo
2645 :group 'org-keywords
2646 :type '(choice (const sequence)
2647 (const type)))
2649 (defcustom org-use-fast-todo-selection t
2650 "\\<org-mode-map>\
2651 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2652 This variable describes if and under what circumstances the cycling
2653 mechanism for TODO keywords will be replaced by a single-key, direct
2654 selection scheme.
2656 When nil, fast selection is never used.
2658 When the symbol `prefix', it will be used when `org-todo' is called
2659 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2660 in an Org buffer, and
2661 `\\[universal-argument] t' in an agenda buffer.
2663 When t, fast selection is used by default. In this case, the prefix
2664 argument forces cycling instead.
2666 In all cases, the special interface is only used if access keys have
2667 actually been assigned by the user, i.e. if keywords in the configuration
2668 are followed by a letter in parenthesis, like TODO(t)."
2669 :group 'org-todo
2670 :type '(choice
2671 (const :tag "Never" nil)
2672 (const :tag "By default" t)
2673 (const :tag "Only with C-u C-c C-t" prefix)))
2675 (defcustom org-provide-todo-statistics t
2676 "Non-nil means update todo statistics after insert and toggle.
2677 ALL-HEADLINES means update todo statistics by including headlines
2678 with no TODO keyword as well, counting them as not done.
2679 A list of TODO keywords means the same, but skip keywords that are
2680 not in this list.
2681 When set to a list of two lists, the first list contains keywords
2682 to consider as TODO keywords, the second list contains keywords
2683 to consider as DONE keywords.
2685 When this is set, todo statistics is updated in the parent of the
2686 current entry each time a todo state is changed."
2687 :group 'org-todo
2688 :type '(choice
2689 (const :tag "Yes, only for TODO entries" t)
2690 (const :tag "Yes, including all entries" all-headlines)
2691 (repeat :tag "Yes, for TODOs in this list"
2692 (string :tag "TODO keyword"))
2693 (list :tag "Yes, for TODOs and DONEs in these lists"
2694 (repeat (string :tag "TODO keyword"))
2695 (repeat (string :tag "DONE keyword")))
2696 (other :tag "No TODO statistics" nil)))
2698 (defcustom org-hierarchical-todo-statistics t
2699 "Non-nil means TODO statistics covers just direct children.
2700 When nil, all entries in the subtree are considered.
2701 This has only an effect if `org-provide-todo-statistics' is set.
2702 To set this to nil for only a single subtree, use a COOKIE_DATA
2703 property and include the word \"recursive\" into the value."
2704 :group 'org-todo
2705 :type 'boolean)
2707 (defcustom org-after-todo-state-change-hook nil
2708 "Hook which is run after the state of a TODO item was changed.
2709 The new state (a string with a TODO keyword, or nil) is available in the
2710 Lisp variable `org-state'."
2711 :group 'org-todo
2712 :type 'hook)
2714 (defvar org-blocker-hook nil
2715 "Hook for functions that are allowed to block a state change.
2717 Functions in this hook should not modify the buffer.
2718 Each function gets as its single argument a property list,
2719 see `org-trigger-hook' for more information about this list.
2721 If any of the functions in this hook returns nil, the state change
2722 is blocked.")
2724 (defvar org-trigger-hook nil
2725 "Hook for functions that are triggered by a state change.
2727 Each function gets as its single argument a property list with at
2728 least the following elements:
2730 (:type type-of-change :position pos-at-entry-start
2731 :from old-state :to new-state)
2733 Depending on the type, more properties may be present.
2735 This mechanism is currently implemented for:
2737 TODO state changes
2738 ------------------
2739 :type todo-state-change
2740 :from previous state (keyword as a string), or nil, or a symbol
2741 `todo' or `done', to indicate the general type of state.
2742 :to new state, like in :from")
2744 (defcustom org-enforce-todo-dependencies nil
2745 "Non-nil means undone TODO entries will block switching the parent to DONE.
2746 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2747 be blocked if any prior sibling is not yet done.
2748 Finally, if the parent is blocked because of ordered siblings of its own,
2749 the child will also be blocked."
2750 :set (lambda (var val)
2751 (set var val)
2752 (if val
2753 (add-hook 'org-blocker-hook
2754 'org-block-todo-from-children-or-siblings-or-parent)
2755 (remove-hook 'org-blocker-hook
2756 'org-block-todo-from-children-or-siblings-or-parent)))
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-enforce-todo-checkbox-dependencies nil
2761 "Non-nil means unchecked boxes will block switching the parent to DONE.
2762 When this is nil, checkboxes have no influence on switching TODO states.
2763 When non-nil, you first need to check off all check boxes before the TODO
2764 entry can be switched to DONE.
2765 This variable needs to be set before org.el is loaded, and you need to
2766 restart Emacs after a change to make the change effective. The only way
2767 to change is while Emacs is running is through the customize interface."
2768 :set (lambda (var val)
2769 (set var val)
2770 (if val
2771 (add-hook 'org-blocker-hook
2772 'org-block-todo-from-checkboxes)
2773 (remove-hook 'org-blocker-hook
2774 'org-block-todo-from-checkboxes)))
2775 :group 'org-todo
2776 :type 'boolean)
2778 (defcustom org-treat-insert-todo-heading-as-state-change nil
2779 "Non-nil means inserting a TODO heading is treated as state change.
2780 So when the command `\\[org-insert-todo-heading]' is used, state change
2781 logging will apply if appropriate. When nil, the new TODO item will
2782 be inserted directly, and no logging will take place."
2783 :group 'org-todo
2784 :type 'boolean)
2786 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2787 "Non-nil means switching TODO states with S-cursor counts as state change.
2788 This is the default behavior. However, setting this to nil allows a
2789 convenient way to select a TODO state and bypass any logging associated
2790 with that."
2791 :group 'org-todo
2792 :type 'boolean)
2794 (defcustom org-todo-state-tags-triggers nil
2795 "Tag changes that should be triggered by TODO state changes.
2796 This is a list. Each entry is
2798 (state-change (tag . flag) .......)
2800 State-change can be a string with a state, and empty string to indicate the
2801 state that has no TODO keyword, or it can be one of the symbols `todo'
2802 or `done', meaning any not-done or done state, respectively."
2803 :group 'org-todo
2804 :group 'org-tags
2805 :type '(repeat
2806 (cons (choice :tag "When changing to"
2807 (const :tag "Not-done state" todo)
2808 (const :tag "Done state" done)
2809 (string :tag "State"))
2810 (repeat
2811 (cons :tag "Tag action"
2812 (string :tag "Tag")
2813 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2815 (defcustom org-log-done nil
2816 "Information to record when a task moves to the DONE state.
2818 Possible values are:
2820 nil Don't add anything, just change the keyword
2821 time Add a time stamp to the task
2822 note Prompt for a note and add it with template `org-log-note-headings'
2824 This option can also be set with on a per-file-basis with
2826 #+STARTUP: nologdone
2827 #+STARTUP: logdone
2828 #+STARTUP: lognotedone
2830 You can have local logging settings for a subtree by setting the LOGGING
2831 property to one or more of these keywords."
2832 :group 'org-todo
2833 :group 'org-progress
2834 :type '(choice
2835 (const :tag "No logging" nil)
2836 (const :tag "Record CLOSED timestamp" time)
2837 (const :tag "Record CLOSED timestamp with note." note)))
2839 ;; Normalize old uses of org-log-done.
2840 (cond
2841 ((eq org-log-done t) (setq org-log-done 'time))
2842 ((and (listp org-log-done) (memq 'done org-log-done))
2843 (setq org-log-done 'note)))
2845 (defcustom org-log-reschedule nil
2846 "Information to record when the scheduling date of a tasks is modified.
2848 Possible values are:
2850 nil Don't add anything, just change the date
2851 time Add a time stamp to the task
2852 note Prompt for a note and add it with template `org-log-note-headings'
2854 This option can also be set with on a per-file-basis with
2856 #+STARTUP: nologreschedule
2857 #+STARTUP: logreschedule
2858 #+STARTUP: lognotereschedule"
2859 :group 'org-todo
2860 :group 'org-progress
2861 :type '(choice
2862 (const :tag "No logging" nil)
2863 (const :tag "Record timestamp" time)
2864 (const :tag "Record timestamp with note." note)))
2866 (defcustom org-log-redeadline nil
2867 "Information to record when the deadline date of a tasks is modified.
2869 Possible values are:
2871 nil Don't add anything, just change the date
2872 time Add a time stamp to the task
2873 note Prompt for a note and add it with template `org-log-note-headings'
2875 This option can also be set with on a per-file-basis with
2877 #+STARTUP: nologredeadline
2878 #+STARTUP: logredeadline
2879 #+STARTUP: lognoteredeadline
2881 You can have local logging settings for a subtree by setting the LOGGING
2882 property to one or more of these keywords."
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type '(choice
2886 (const :tag "No logging" nil)
2887 (const :tag "Record timestamp" time)
2888 (const :tag "Record timestamp with note." note)))
2890 (defcustom org-log-note-clock-out nil
2891 "Non-nil means record a note when clocking out of an item.
2892 This can also be configured on a per-file basis by adding one of
2893 the following lines anywhere in the buffer:
2895 #+STARTUP: lognoteclock-out
2896 #+STARTUP: nolognoteclock-out"
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type 'boolean)
2901 (defcustom org-log-done-with-time t
2902 "Non-nil means the CLOSED time stamp will contain date and time.
2903 When nil, only the date will be recorded."
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-note-headings
2908 '((done . "CLOSING NOTE %t")
2909 (state . "State %-12s from %-12S %t")
2910 (note . "Note taken on %t")
2911 (reschedule . "Rescheduled from %S on %t")
2912 (delschedule . "Not scheduled, was %S on %t")
2913 (redeadline . "New deadline from %S on %t")
2914 (deldeadline . "Removed deadline, was %S on %t")
2915 (refile . "Refiled on %t")
2916 (clock-out . ""))
2917 "Headings for notes added to entries.
2919 The value is an alist, with the car being a symbol indicating the
2920 note context, and the cdr is the heading to be used. The heading
2921 may also be the empty string. The following placeholders can be
2922 used:
2924 %t a time stamp.
2925 %T an active time stamp instead the default inactive one
2926 %d a short-format time stamp.
2927 %D an active short-format time stamp.
2928 %s the new TODO state or time stamp (inactive), in double quotes.
2929 %S the old TODO state or time stamp (inactive), in double quotes.
2930 %u the user name.
2931 %U full user name.
2933 In fact, it is not a good idea to change the `state' entry,
2934 because Agenda Log mode depends on the format of these entries."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(list :greedy t
2938 (cons (const :tag "Heading when closing an item" done) string)
2939 (cons (const :tag
2940 "Heading when changing todo state (todo sequence only)"
2941 state) string)
2942 (cons (const :tag "Heading when just taking a note" note) string)
2943 (cons (const :tag "Heading when rescheduling" reschedule) string)
2944 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2945 (cons (const :tag "Heading when changing deadline" redeadline) string)
2946 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2947 (cons (const :tag "Heading when refiling" refile) string)
2948 (cons (const :tag "Heading when clocking out" clock-out) string)))
2950 (unless (assq 'note org-log-note-headings)
2951 (push '(note . "%t") org-log-note-headings))
2953 (defcustom org-log-into-drawer nil
2954 "Non-nil means insert state change notes and time stamps into a drawer.
2955 When nil, state changes notes will be inserted after the headline and
2956 any scheduling and clock lines, but not inside a drawer.
2958 The value of this variable should be the name of the drawer to use.
2959 LOGBOOK is proposed as the default drawer for this purpose, you can
2960 also set this to a string to define the drawer of your choice.
2962 A value of t is also allowed, representing \"LOGBOOK\".
2964 A value of t or nil can also be set with on a per-file-basis with
2966 #+STARTUP: logdrawer
2967 #+STARTUP: nologdrawer
2969 If this variable is set, `org-log-state-notes-insert-after-drawers'
2970 will be ignored.
2972 You can set the property LOG_INTO_DRAWER to overrule this setting for
2973 a subtree.
2975 Do not check directly this variable in a Lisp program. Call
2976 function `org-log-into-drawer' instead."
2977 :group 'org-todo
2978 :group 'org-progress
2979 :type '(choice
2980 (const :tag "Not into a drawer" nil)
2981 (const :tag "LOGBOOK" t)
2982 (string :tag "Other")))
2984 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2986 (defun org-log-into-drawer ()
2987 "Name of the log drawer, as a string, or nil.
2988 This is the value of `org-log-into-drawer'. However, if the
2989 current entry has or inherits a LOG_INTO_DRAWER property, it will
2990 be used instead of the default value."
2991 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2992 (cond ((equal p "nil") nil)
2993 ((equal p "t") "LOGBOOK")
2994 ((stringp p) p)
2995 (p "LOGBOOK")
2996 ((stringp org-log-into-drawer) org-log-into-drawer)
2997 (org-log-into-drawer "LOGBOOK"))))
2999 (defcustom org-log-state-notes-insert-after-drawers nil
3000 "Non-nil means insert state change notes after any drawers in entry.
3001 Only the drawers that *immediately* follow the headline and the
3002 deadline/scheduled line are skipped.
3003 When nil, insert notes right after the heading and perhaps the line
3004 with deadline/scheduling if present.
3006 This variable will have no effect if `org-log-into-drawer' is
3007 set."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type 'boolean)
3012 (defcustom org-log-states-order-reversed t
3013 "Non-nil means the latest state note will be directly after heading.
3014 When nil, the state change notes will be ordered according to time.
3016 This option can also be set with on a per-file-basis with
3018 #+STARTUP: logstatesreversed
3019 #+STARTUP: nologstatesreversed"
3020 :group 'org-todo
3021 :group 'org-progress
3022 :type 'boolean)
3024 (defcustom org-todo-repeat-to-state nil
3025 "The TODO state to which a repeater should return the repeating task.
3026 By default this is the first task of a TODO sequence or the
3027 previous state of a TYPE_TODO set. But you can specify to use
3028 the previous state in a TODO sequence or a string.
3030 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3031 entry, which has precedence over this option."
3032 :group 'org-todo
3033 :version "24.1"
3034 :type '(choice (const :tag "Use the previous TODO state" t)
3035 (const :tag "Use the head of the TODO sequence" nil)
3036 (string :tag "Use a specific TODO state")))
3038 (defcustom org-log-repeat 'time
3039 "Non-nil means record moving through the DONE state when triggering repeat.
3040 An auto-repeating task is immediately switched back to TODO when
3041 marked DONE. If you are not logging state changes (by adding \"@\"
3042 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3043 record a closing note, there will be no record of the task moving
3044 through DONE. This variable forces taking a note anyway.
3046 nil Don't force a record
3047 time Record a time stamp
3048 note Prompt for a note and add it with template `org-log-note-headings'
3050 This option can also be set with on a per-file-basis with
3052 #+STARTUP: nologrepeat
3053 #+STARTUP: logrepeat
3054 #+STARTUP: lognoterepeat
3056 You can have local logging settings for a subtree by setting the LOGGING
3057 property to one or more of these keywords."
3058 :group 'org-todo
3059 :group 'org-progress
3060 :type '(choice
3061 (const :tag "Don't force a record" nil)
3062 (const :tag "Force recording the DONE state" time)
3063 (const :tag "Force recording a note with the DONE state" note)))
3066 (defgroup org-priorities nil
3067 "Priorities in Org mode."
3068 :tag "Org Priorities"
3069 :group 'org-todo)
3071 (defcustom org-enable-priority-commands t
3072 "Non-nil means priority commands are active.
3073 When nil, these commands will be disabled, so that you never accidentally
3074 set a priority."
3075 :group 'org-priorities
3076 :type 'boolean)
3078 (defcustom org-highest-priority ?A
3079 "The highest priority of TODO items. A character like ?A, ?B etc.
3080 Must have a smaller ASCII number than `org-lowest-priority'."
3081 :group 'org-priorities
3082 :type 'character)
3084 (defcustom org-lowest-priority ?C
3085 "The lowest priority of TODO items. A character like ?A, ?B etc.
3086 Must have a larger ASCII number than `org-highest-priority'."
3087 :group 'org-priorities
3088 :type 'character)
3090 (defcustom org-default-priority ?B
3091 "The default priority of TODO items.
3092 This is the priority an item gets if no explicit priority is given.
3093 When starting to cycle on an empty priority the first step in the cycle
3094 depends on `org-priority-start-cycle-with-default'. The resulting first
3095 step priority must not exceed the range from `org-highest-priority' to
3096 `org-lowest-priority' which means that `org-default-priority' has to be
3097 in this range exclusive or inclusive the range boundaries. Else the
3098 first step refuses to set the default and the second will fall back
3099 to (depending on the command used) the highest or lowest priority."
3100 :group 'org-priorities
3101 :type 'character)
3103 (defcustom org-priority-start-cycle-with-default t
3104 "Non-nil means start with default priority when starting to cycle.
3105 When this is nil, the first step in the cycle will be (depending on the
3106 command used) one higher or lower than the default priority.
3107 See also `org-default-priority'."
3108 :group 'org-priorities
3109 :type 'boolean)
3111 (defcustom org-get-priority-function nil
3112 "Function to extract the priority from a string.
3113 The string is normally the headline. If this is nil Org computes the
3114 priority from the priority cookie like [#A] in the headline. It returns
3115 an integer, increasing by 1000 for each priority level.
3116 The user can set a different function here, which should take a string
3117 as an argument and return the numeric priority."
3118 :group 'org-priorities
3119 :version "24.1"
3120 :type '(choice
3121 (const nil)
3122 (function)))
3124 (defgroup org-time nil
3125 "Options concerning time stamps and deadlines in Org mode."
3126 :tag "Org Time"
3127 :group 'org)
3129 (defcustom org-time-stamp-rounding-minutes '(0 5)
3130 "Number of minutes to round time stamps to.
3131 \\<org-mode-map>\
3132 These are two values, the first applies when first creating a time stamp.
3133 The second applies when changing it with the commands `S-up' and `S-down'.
3134 When changing the time stamp, this means that it will change in steps
3135 of N minutes, as given by the second value.
3137 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3138 numbers should be factors of 60, so for example 5, 10, 15.
3140 When this is larger than 1, you can still force an exact time stamp by using
3141 a double prefix argument to a time stamp command like \
3142 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3143 and by using a prefix arg to `S-up/down' to specify the exact number
3144 of minutes to shift."
3145 :group 'org-time
3146 :get (lambda (var) ; Make sure both elements are there
3147 (if (integerp (default-value var))
3148 (list (default-value var) 5)
3149 (default-value var)))
3150 :type '(list
3151 (integer :tag "when inserting times")
3152 (integer :tag "when modifying times")))
3154 ;; Normalize old customizations of this variable.
3155 (when (integerp org-time-stamp-rounding-minutes)
3156 (setq org-time-stamp-rounding-minutes
3157 (list org-time-stamp-rounding-minutes
3158 org-time-stamp-rounding-minutes)))
3160 (defcustom org-display-custom-times nil
3161 "Non-nil means overlay custom formats over all time stamps.
3162 The formats are defined through the variable `org-time-stamp-custom-formats'.
3163 To turn this on on a per-file basis, insert anywhere in the file:
3164 #+STARTUP: customtime"
3165 :group 'org-time
3166 :set 'set-default
3167 :type 'sexp)
3168 (make-variable-buffer-local 'org-display-custom-times)
3170 (defcustom org-time-stamp-custom-formats
3171 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3172 "Custom formats for time stamps. See `format-time-string' for the syntax.
3173 These are overlaid over the default ISO format if the variable
3174 `org-display-custom-times' is set. Time like %H:%M should be at the
3175 end of the second format. The custom formats are also honored by export
3176 commands, if custom time display is turned on at the time of export."
3177 :group 'org-time
3178 :type 'sexp)
3180 (defun org-time-stamp-format (&optional long inactive)
3181 "Get the right format for a time string."
3182 (let ((f (if long (cdr org-time-stamp-formats)
3183 (car org-time-stamp-formats))))
3184 (if inactive
3185 (concat "[" (substring f 1 -1) "]")
3186 f)))
3188 (defcustom org-deadline-warning-days 14
3189 "Number of days before expiration during which a deadline becomes active.
3190 This variable governs the display in sparse trees and in the agenda.
3191 When 0 or negative, it means use this number (the absolute value of it)
3192 even if a deadline has a different individual lead time specified.
3194 Custom commands can set this variable in the options section."
3195 :group 'org-time
3196 :group 'org-agenda-daily/weekly
3197 :type 'integer)
3199 (defcustom org-scheduled-delay-days 0
3200 "Number of days before a scheduled item becomes active.
3201 This variable governs the display in sparse trees and in the agenda.
3202 The default value (i.e. 0) means: don't delay scheduled item.
3203 When negative, it means use this number (the absolute value of it)
3204 even if a scheduled item has a different individual delay time
3205 specified.
3207 Custom commands can set this variable in the options section."
3208 :group 'org-time
3209 :group 'org-agenda-daily/weekly
3210 :version "24.4"
3211 :package-version '(Org . "8.0")
3212 :type 'integer)
3214 (defcustom org-read-date-prefer-future t
3215 "Non-nil means assume future for incomplete date input from user.
3216 This affects the following situations:
3217 1. The user gives a month but not a year.
3218 For example, if it is April and you enter \"feb 2\", this will be read
3219 as Feb 2, *next* year. \"May 5\", however, will be this year.
3220 2. The user gives a day, but no month.
3221 For example, if today is the 15th, and you enter \"3\", Org will read
3222 this as the third of *next* month. However, if you enter \"17\",
3223 it will be considered as *this* month.
3225 If you set this variable to the symbol `time', then also the following
3226 will work:
3228 3. If the user gives a time.
3229 If the time is before now, it will be interpreted as tomorrow.
3231 Currently none of this works for ISO week specifications.
3233 When this option is nil, the current day, month and year will always be
3234 used as defaults.
3236 See also `org-agenda-jump-prefer-future'."
3237 :group 'org-time
3238 :type '(choice
3239 (const :tag "Never" nil)
3240 (const :tag "Check month and day" t)
3241 (const :tag "Check month, day, and time" time)))
3243 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3244 "Should the agenda jump command prefer the future for incomplete dates?
3245 The default is to do the same as configured in `org-read-date-prefer-future'.
3246 But you can also set a deviating value here.
3247 This may t or nil, or the symbol `org-read-date-prefer-future'."
3248 :group 'org-agenda
3249 :group 'org-time
3250 :version "24.1"
3251 :type '(choice
3252 (const :tag "Use org-read-date-prefer-future"
3253 org-read-date-prefer-future)
3254 (const :tag "Never" nil)
3255 (const :tag "Always" t)))
3257 (defcustom org-read-date-force-compatible-dates t
3258 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3260 Depending on the system Emacs is running on, certain dates cannot
3261 be represented with the type used internally to represent time.
3262 Dates between 1970-1-1 and 2038-1-1 can always be represented
3263 correctly. Some systems allow for earlier dates, some for later,
3264 some for both. One way to find out it to insert any date into an
3265 Org buffer, putting the cursor on the year and hitting S-up and
3266 S-down to test the range.
3268 When this variable is set to t, the date/time prompt will not let
3269 you specify dates outside the 1970-2037 range, so it is certain that
3270 these dates will work in whatever version of Emacs you are
3271 running, and also that you can move a file from one Emacs implementation
3272 to another. WHenever Org is forcing the year for you, it will display
3273 a message and beep.
3275 When this variable is nil, Org will check if the date is
3276 representable in the specific Emacs implementation you are using.
3277 If not, it will force a year, usually the current year, and beep
3278 to remind you. Currently this setting is not recommended because
3279 the likelihood that you will open your Org files in an Emacs that
3280 has limited date range is not negligible.
3282 A workaround for this problem is to use diary sexp dates for time
3283 stamps outside of this range."
3284 :group 'org-time
3285 :version "24.1"
3286 :type 'boolean)
3288 (defcustom org-read-date-display-live t
3289 "Non-nil means display current interpretation of date prompt live.
3290 This display will be in an overlay, in the minibuffer."
3291 :group 'org-time
3292 :type 'boolean)
3294 (defcustom org-read-date-popup-calendar t
3295 "Non-nil means pop up a calendar when prompting for a date.
3296 In the calendar, the date can be selected with mouse-1. However, the
3297 minibuffer will also be active, and you can simply enter the date as well.
3298 When nil, only the minibuffer will be available."
3299 :group 'org-time
3300 :type 'boolean)
3301 (defvaralias 'org-popup-calendar-for-date-prompt
3302 'org-read-date-popup-calendar)
3304 (defcustom org-extend-today-until 0
3305 "The hour when your day really ends. Must be an integer.
3306 This has influence for the following applications:
3307 - When switching the agenda to \"today\". It it is still earlier than
3308 the time given here, the day recognized as TODAY is actually yesterday.
3309 - When a date is read from the user and it is still before the time given
3310 here, the current date and time will be assumed to be yesterday, 23:59.
3311 Also, timestamps inserted in capture templates follow this rule.
3313 IMPORTANT: This is a feature whose implementation is and likely will
3314 remain incomplete. Really, it is only here because past midnight seems to
3315 be the favorite working time of John Wiegley :-)"
3316 :group 'org-time
3317 :type 'integer)
3319 (defcustom org-use-effective-time nil
3320 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3321 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3322 \"effective time\" of any timestamps between midnight and 8am will be
3323 23:59 of the previous day."
3324 :group 'org-time
3325 :version "24.1"
3326 :type 'boolean)
3328 (defcustom org-use-last-clock-out-time-as-effective-time nil
3329 "When non-nil, use the last clock out time for `org-todo'.
3330 Note that this option has precedence over the combined use of
3331 `org-use-effective-time' and `org-extend-today-until'."
3332 :group 'org-time
3333 :version "24.4"
3334 :package-version '(Org . "8.0")
3335 :type 'boolean)
3337 (defcustom org-edit-timestamp-down-means-later nil
3338 "Non-nil means S-down will increase the time in a time stamp.
3339 When nil, S-up will increase."
3340 :group 'org-time
3341 :type 'boolean)
3343 (defcustom org-calendar-follow-timestamp-change t
3344 "Non-nil means make the calendar window follow timestamp changes.
3345 When a timestamp is modified and the calendar window is visible, it will be
3346 moved to the new date."
3347 :group 'org-time
3348 :type 'boolean)
3350 (defgroup org-tags nil
3351 "Options concerning tags in Org mode."
3352 :tag "Org Tags"
3353 :group 'org)
3355 (defcustom org-tag-alist nil
3356 "Default tags available in Org files.
3358 The value of this variable is an alist. Associations either:
3360 (TAG)
3361 (TAG . SELECT)
3362 (SPECIAL)
3364 where TAG is a tag as a string, SELECT is character, used to
3365 select that tag through the fast tag selection interface, and
3366 SPECIAL is one of the following keywords: `:startgroup',
3367 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3368 `:newline'. These keywords are used to define a hierarchy of
3369 tags. See manual for details.
3371 When this variable is nil, Org mode bases tag input on what is
3372 already in the buffer. The value can be overridden locally by
3373 using a TAGS keyword, e.g.,
3375 #+TAGS: tag1 tag2
3377 See also `org-tag-persistent-alist' to sidestep this behavior."
3378 :group 'org-tags
3379 :type '(repeat
3380 (choice
3381 (cons :tag "Tag with key"
3382 (string :tag "Tag name")
3383 (character :tag "Access char"))
3384 (list :tag "Tag" (string :tag "Tag name"))
3385 (const :tag "Start radio group" (:startgroup))
3386 (const :tag "Start tag group, non distinct" (:startgrouptag))
3387 (const :tag "Group tags delimiter" (:grouptags))
3388 (const :tag "End radio group" (:endgroup))
3389 (const :tag "End tag group, non distinct" (:endgrouptag))
3390 (const :tag "New line" (:newline)))))
3392 (defcustom org-tag-persistent-alist nil
3393 "Tags always available in Org files.
3395 The value of this variable is an alist. Associations either:
3397 (TAG)
3398 (TAG . SELECT)
3399 (SPECIAL)
3401 where TAG is a tag as a string, SELECT is a character, used to
3402 select that tag through the fast tag selection interface, and
3403 SPECIAL is one of the following keywords: `:startgroup',
3404 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3405 `:newline'. These keywords are used to define a hierarchy of
3406 tags. See manual for details.
3408 Unlike to `org-tag-alist', tags defined in this variable do not
3409 depend on a local TAGS keyword. Instead, to disable these tags
3410 on a per-file basis, insert anywhere in the file:
3412 #+STARTUP: noptag"
3413 :group 'org-tags
3414 :type '(repeat
3415 (choice
3416 (cons :tag "Tag with key"
3417 (string :tag "Tag name")
3418 (character :tag "Access char"))
3419 (list :tag "Tag" (string :tag "Tag name"))
3420 (const :tag "Start radio group" (:startgroup))
3421 (const :tag "Start tag group, non distinct" (:startgrouptag))
3422 (const :tag "Group tags delimiter" (:grouptags))
3423 (const :tag "End radio group" (:endgroup))
3424 (const :tag "End tag group, non distinct" (:endgrouptag))
3425 (const :tag "New line" (:newline)))))
3427 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3428 "If non-nil, always offer completion for all tags of all agenda files.
3429 Instead of customizing this variable directly, you might want to
3430 set it locally for capture buffers, because there no list of
3431 tags in that file can be created dynamically (there are none).
3433 (add-hook \\='org-capture-mode-hook
3434 (lambda ()
3435 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3436 :group 'org-tags
3437 :version "24.1"
3438 :type 'boolean)
3440 (defvar org-file-tags nil
3441 "List of tags that can be inherited by all entries in the file.
3442 The tags will be inherited if the variable `org-use-tag-inheritance'
3443 says they should be.
3444 This variable is populated from #+FILETAGS lines.")
3446 (defcustom org-use-fast-tag-selection 'auto
3447 "Non-nil means use fast tag selection scheme.
3448 This is a special interface to select and deselect tags with single keys.
3449 When nil, fast selection is never used.
3450 When the symbol `auto', fast selection is used if and only if selection
3451 characters for tags have been configured, either through the variable
3452 `org-tag-alist' or through a #+TAGS line in the buffer.
3453 When t, fast selection is always used and selection keys are assigned
3454 automatically if necessary."
3455 :group 'org-tags
3456 :type '(choice
3457 (const :tag "Always" t)
3458 (const :tag "Never" nil)
3459 (const :tag "When selection characters are configured" auto)))
3461 (defcustom org-fast-tag-selection-single-key nil
3462 "Non-nil means fast tag selection exits after first change.
3463 When nil, you have to press RET to exit it.
3464 During fast tag selection, you can toggle this flag with `C-c'.
3465 This variable can also have the value `expert'. In this case, the window
3466 displaying the tags menu is not even shown, until you press C-c again."
3467 :group 'org-tags
3468 :type '(choice
3469 (const :tag "No" nil)
3470 (const :tag "Yes" t)
3471 (const :tag "Expert" expert)))
3473 (defvar org-fast-tag-selection-include-todo nil
3474 "Non-nil means fast tags selection interface will also offer TODO states.
3475 This is an undocumented feature, you should not rely on it.")
3477 (defcustom org-tags-column -77
3478 "The column to which tags should be indented in a headline.
3479 If this number is positive, it specifies the column. If it is negative,
3480 it means that the tags should be flushright to that column. For example,
3481 -80 works well for a normal 80 character screen.
3482 When 0, place tags directly after headline text, with only one space in
3483 between."
3484 :group 'org-tags
3485 :type 'integer)
3487 (defcustom org-auto-align-tags t
3488 "Non-nil keeps tags aligned when modifying headlines.
3489 Some operations (i.e. demoting) change the length of a headline and
3490 therefore shift the tags around. With this option turned on, after
3491 each such operation the tags are again aligned to `org-tags-column'."
3492 :group 'org-tags
3493 :type 'boolean)
3495 (defcustom org-use-tag-inheritance t
3496 "Non-nil means tags in levels apply also for sublevels.
3497 When nil, only the tags directly given in a specific line apply there.
3498 This may also be a list of tags that should be inherited, or a regexp that
3499 matches tags that should be inherited. Additional control is possible
3500 with the variable `org-tags-exclude-from-inheritance' which gives an
3501 explicit list of tags to be excluded from inheritance, even if the value of
3502 `org-use-tag-inheritance' would select it for inheritance.
3504 If this option is t, a match early-on in a tree can lead to a large
3505 number of matches in the subtree when constructing the agenda or creating
3506 a sparse tree. If you only want to see the first match in a tree during
3507 a search, check out the variable `org-tags-match-list-sublevels'."
3508 :group 'org-tags
3509 :type '(choice
3510 (const :tag "Not" nil)
3511 (const :tag "Always" t)
3512 (repeat :tag "Specific tags" (string :tag "Tag"))
3513 (regexp :tag "Tags matched by regexp")))
3515 (defcustom org-tags-exclude-from-inheritance nil
3516 "List of tags that should never be inherited.
3517 This is a way to exclude a few tags from inheritance. For way to do
3518 the opposite, to actively allow inheritance for selected tags,
3519 see the variable `org-use-tag-inheritance'."
3520 :group 'org-tags
3521 :type '(repeat (string :tag "Tag")))
3523 (defun org-tag-inherit-p (tag)
3524 "Check if TAG is one that should be inherited."
3525 (cond
3526 ((member tag org-tags-exclude-from-inheritance) nil)
3527 ((eq org-use-tag-inheritance t) t)
3528 ((not org-use-tag-inheritance) nil)
3529 ((stringp org-use-tag-inheritance)
3530 (string-match org-use-tag-inheritance tag))
3531 ((listp org-use-tag-inheritance)
3532 (member tag org-use-tag-inheritance))
3533 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3535 (defcustom org-tags-match-list-sublevels t
3536 "Non-nil means list also sublevels of headlines matching a search.
3537 This variable applies to tags/property searches, and also to stuck
3538 projects because this search is based on a tags match as well.
3540 When set to the symbol `indented', sublevels are indented with
3541 leading dots.
3543 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3544 the sublevels of a headline matching a tag search often also match
3545 the same search. Listing all of them can create very long lists.
3546 Setting this variable to nil causes subtrees of a match to be skipped.
3548 This variable is semi-obsolete and probably should always be true. It
3549 is better to limit inheritance to certain tags using the variables
3550 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3551 :group 'org-tags
3552 :type '(choice
3553 (const :tag "No, don't list them" nil)
3554 (const :tag "Yes, do list them" t)
3555 (const :tag "List them, indented with leading dots" indented)))
3557 (defcustom org-tags-sort-function nil
3558 "When set, tags are sorted using this function as a comparator."
3559 :group 'org-tags
3560 :type '(choice
3561 (const :tag "No sorting" nil)
3562 (const :tag "Alphabetical" org-string-collate-lessp)
3563 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3564 (function :tag "Custom function" nil)))
3566 (defvar org-tags-history nil
3567 "History of minibuffer reads for tags.")
3568 (defvar org-last-tags-completion-table nil
3569 "The last used completion table for tags.")
3570 (defvar org-after-tags-change-hook nil
3571 "Hook that is run after the tags in a line have changed.")
3573 (defgroup org-properties nil
3574 "Options concerning properties in Org mode."
3575 :tag "Org Properties"
3576 :group 'org)
3578 (defcustom org-property-format "%-10s %s"
3579 "How property key/value pairs should be formatted by `indent-line'.
3580 When `indent-line' hits a property definition, it will format the line
3581 according to this format, mainly to make sure that the values are
3582 lined-up with respect to each other."
3583 :group 'org-properties
3584 :type 'string)
3586 (defcustom org-properties-postprocess-alist nil
3587 "Alist of properties and functions to adjust inserted values.
3588 Elements of this alist must be of the form
3590 ([string] [function])
3592 where [string] must be a property name and [function] must be a
3593 lambda expression: this lambda expression must take one argument,
3594 the value to adjust, and return the new value as a string.
3596 For example, this element will allow the property \"Remaining\"
3597 to be updated wrt the relation between the \"Effort\" property
3598 and the clock summary:
3600 ((\"Remaining\" (lambda(value)
3601 (let ((clocksum (org-clock-sum-current-item))
3602 (effort (org-duration-to-minutes
3603 (org-entry-get (point) \"Effort\"))))
3604 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3605 :group 'org-properties
3606 :version "24.1"
3607 :type '(alist :key-type (string :tag "Property")
3608 :value-type (function :tag "Function")))
3610 (defcustom org-use-property-inheritance nil
3611 "Non-nil means properties apply also for sublevels.
3613 This setting is chiefly used during property searches. Turning it on can
3614 cause significant overhead when doing a search, which is why it is not
3615 on by default.
3617 When nil, only the properties directly given in the current entry count.
3618 When t, every property is inherited. The value may also be a list of
3619 properties that should have inheritance, or a regular expression matching
3620 properties that should be inherited.
3622 However, note that some special properties use inheritance under special
3623 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3624 and the properties ending in \"_ALL\" when they are used as descriptor
3625 for valid values of a property.
3627 Note for programmers:
3628 When querying an entry with `org-entry-get', you can control if inheritance
3629 should be used. By default, `org-entry-get' looks only at the local
3630 properties. You can request inheritance by setting the inherit argument
3631 to t (to force inheritance) or to `selective' (to respect the setting
3632 in this variable)."
3633 :group 'org-properties
3634 :type '(choice
3635 (const :tag "Not" nil)
3636 (const :tag "Always" t)
3637 (repeat :tag "Specific properties" (string :tag "Property"))
3638 (regexp :tag "Properties matched by regexp")))
3640 (defun org-property-inherit-p (property)
3641 "Return a non-nil value if PROPERTY should be inherited."
3642 (cond
3643 ((eq org-use-property-inheritance t) t)
3644 ((not org-use-property-inheritance) nil)
3645 ((stringp org-use-property-inheritance)
3646 (string-match org-use-property-inheritance property))
3647 ((listp org-use-property-inheritance)
3648 (member-ignore-case property org-use-property-inheritance))
3649 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3651 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3652 "The default column format, if no other format has been defined.
3653 This variable can be set on the per-file basis by inserting a line
3655 #+COLUMNS: %25ITEM ....."
3656 :group 'org-properties
3657 :type 'string)
3659 (defcustom org-columns-ellipses ".."
3660 "The ellipses to be used when a field in column view is truncated.
3661 When this is the empty string, as many characters as possible are shown,
3662 but then there will be no visual indication that the field has been truncated.
3663 When this is a string of length N, the last N characters of a truncated
3664 field are replaced by this string. If the column is narrower than the
3665 ellipses string, only part of the ellipses string will be shown."
3666 :group 'org-properties
3667 :type 'string)
3669 (defconst org-global-properties-fixed
3670 '(("VISIBILITY_ALL" . "folded children content all")
3671 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3672 "List of property/value pairs that can be inherited by any entry.
3674 These are fixed values, for the preset properties. The user variable
3675 that can be used to add to this list is `org-global-properties'.
3677 The entries in this list are cons cells where the car is a property
3678 name and cdr is a string with the value. If the value represents
3679 multiple items like an \"_ALL\" property, separate the items by
3680 spaces.")
3682 (defcustom org-global-properties nil
3683 "List of property/value pairs that can be inherited by any entry.
3685 This list will be combined with the constant `org-global-properties-fixed'.
3687 The entries in this list are cons cells where the car is a property
3688 name and cdr is a string with the value.
3690 You can set buffer-local values for the same purpose in the variable
3691 `org-file-properties' this by adding lines like
3693 #+PROPERTY: NAME VALUE"
3694 :group 'org-properties
3695 :type '(repeat
3696 (cons (string :tag "Property")
3697 (string :tag "Value"))))
3699 (defvar-local org-file-properties nil
3700 "List of property/value pairs that can be inherited by any entry.
3701 Valid for the current buffer.
3702 This variable is populated from #+PROPERTY lines.")
3704 (defgroup org-agenda nil
3705 "Options concerning agenda views in Org mode."
3706 :tag "Org Agenda"
3707 :group 'org)
3709 (defvar-local org-category nil
3710 "Variable used by Org files to set a category for agenda display.
3711 Such files should use a file variable to set it, for example
3713 # -*- mode: org; org-category: \"ELisp\"
3715 or contain a special line
3717 #+CATEGORY: ELisp
3719 If the file does not specify a category, then file's base name
3720 is used instead.")
3721 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3723 (defcustom org-agenda-files nil
3724 "The files to be used for agenda display.
3726 If an entry is a directory, all files in that directory that are matched
3727 by `org-agenda-file-regexp' will be part of the file list.
3729 If the value of the variable is not a list but a single file name, then
3730 the list of agenda files is actually stored and maintained in that file,
3731 one agenda file per line. In this file paths can be given relative to
3732 `org-directory'. Tilde expansion and environment variable substitution
3733 are also made.
3735 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3736 and removed with `\\[org-remove-file]'."
3737 :group 'org-agenda
3738 :type '(choice
3739 (repeat :tag "List of files and directories" file)
3740 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3742 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3743 "Regular expression to match files for `org-agenda-files'.
3744 If any element in the list in that variable contains a directory instead
3745 of a normal file, all files in that directory that are matched by this
3746 regular expression will be included."
3747 :group 'org-agenda
3748 :type 'regexp)
3750 (defcustom org-agenda-text-search-extra-files nil
3751 "List of extra files to be searched by text search commands.
3752 These files will be searched in addition to the agenda files by the
3753 commands `org-search-view' (`\\[org-agenda] s') \
3754 and `org-occur-in-agenda-files'.
3755 Note that these files will only be searched for text search commands,
3756 not for the other agenda views like todo lists, tag searches or the weekly
3757 agenda. This variable is intended to list notes and possibly archive files
3758 that should also be searched by these two commands.
3759 In fact, if the first element in the list is the symbol `agenda-archives',
3760 then all archive files of all agenda files will be added to the search
3761 scope."
3762 :group 'org-agenda
3763 :type '(set :greedy t
3764 (const :tag "Agenda Archives" agenda-archives)
3765 (repeat :inline t (file))))
3767 (defvaralias 'org-agenda-multi-occur-extra-files
3768 'org-agenda-text-search-extra-files)
3770 (defcustom org-agenda-skip-unavailable-files nil
3771 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3772 A nil value means to remove them, after a query, from the list."
3773 :group 'org-agenda
3774 :type 'boolean)
3776 (defcustom org-agenda-diary-file 'diary-file
3777 "File to which to add new entries with the `i' key in agenda and calendar.
3778 When this is the symbol `diary-file', the functionality in the Emacs
3779 calendar will be used to add entries to the `diary-file'. But when this
3780 points to a file, `org-agenda-diary-entry' will be used instead."
3781 :group 'org-agenda
3782 :type '(choice
3783 (const :tag "The standard Emacs diary file" diary-file)
3784 (file :tag "Special Org file diary entries")))
3786 (defgroup org-latex nil
3787 "Options for embedding LaTeX code into Org mode."
3788 :tag "Org LaTeX"
3789 :group 'org)
3791 (defcustom org-format-latex-options
3792 '(:foreground default :background default :scale 1.0
3793 :html-foreground "Black" :html-background "Transparent"
3794 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3795 "Options for creating images from LaTeX fragments.
3796 This is a property list with the following properties:
3797 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3798 `default' means use the foreground of the default face.
3799 `auto' means use the foreground from the text face.
3800 :background the background color, or \"Transparent\".
3801 `default' means use the background of the default face.
3802 `auto' means use the background from the text face.
3803 :scale a scaling factor for the size of the images, to get more pixels
3804 :html-foreground, :html-background, :html-scale
3805 the same numbers for HTML export.
3806 :matchers a list indicating which matchers should be used to
3807 find LaTeX fragments. Valid members of this list are:
3808 \"begin\" find environments
3809 \"$1\" find single characters surrounded by $.$
3810 \"$\" find math expressions surrounded by $...$
3811 \"$$\" find math expressions surrounded by $$....$$
3812 \"\\(\" find math expressions surrounded by \\(...\\)
3813 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3814 :group 'org-latex
3815 :type 'plist)
3817 (defcustom org-format-latex-signal-error t
3818 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3819 When nil, just push out a message."
3820 :group 'org-latex
3821 :version "24.1"
3822 :type 'boolean)
3824 (defcustom org-latex-to-mathml-jar-file nil
3825 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3826 Use this to specify additional executable file say a jar file.
3828 When using MathToWeb as the converter, specify the full-path to
3829 your mathtoweb.jar file."
3830 :group 'org-latex
3831 :version "24.1"
3832 :type '(choice
3833 (const :tag "None" nil)
3834 (file :tag "JAR file" :must-match t)))
3836 (defcustom org-latex-to-mathml-convert-command nil
3837 "Command to convert LaTeX fragments to MathML.
3838 Replace format-specifiers in the command as noted below and use
3839 `shell-command' to convert LaTeX to MathML.
3840 %j: Executable file in fully expanded form as specified by
3841 `org-latex-to-mathml-jar-file'.
3842 %I: Input LaTeX file in fully expanded form.
3843 %i: The latex fragment to be converted.
3844 %o: Output MathML file.
3846 This command is used by `org-create-math-formula'.
3848 When using MathToWeb as the converter, set this option to
3849 \"java -jar %j -unicode -force -df %o %I\".
3851 When using LaTeXML set this option to
3852 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type '(choice
3856 (const :tag "None" nil)
3857 (string :tag "\nShell command")))
3859 (defcustom org-preview-latex-default-process 'dvipng
3860 "The default process to convert LaTeX fragments to image files.
3861 All available processes and theirs documents can be found in
3862 `org-preview-latex-process-alist', which see."
3863 :group 'org-latex
3864 :version "26.1"
3865 :package-version '(Org . "9.0")
3866 :type 'symbol)
3868 (defcustom org-preview-latex-process-alist
3869 '((dvipng
3870 :programs ("latex" "dvipng")
3871 :description "dvi > png"
3872 :message "you need to install the programs: latex and dvipng."
3873 :image-input-type "dvi"
3874 :image-output-type "png"
3875 :image-size-adjust (1.0 . 1.0)
3876 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3877 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3878 (dvisvgm
3879 :programs ("latex" "dvisvgm")
3880 :description "dvi > svg"
3881 :message "you need to install the programs: latex and dvisvgm."
3882 :use-xcolor t
3883 :image-input-type "dvi"
3884 :image-output-type "svg"
3885 :image-size-adjust (1.7 . 1.5)
3886 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3887 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3888 (imagemagick
3889 :programs ("latex" "convert")
3890 :description "pdf > png"
3891 :message "you need to install the programs: latex and imagemagick."
3892 :use-xcolor t
3893 :image-input-type "pdf"
3894 :image-output-type "png"
3895 :image-size-adjust (1.0 . 1.0)
3896 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3897 :image-converter
3898 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3899 "Definitions of external processes for LaTeX previewing.
3900 Org mode can use some external commands to generate TeX snippet's images for
3901 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3902 `org-create-formula-image' how to call them.
3904 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3905 PROPERTIES accepts the following attributes:
3907 :programs list of strings, required programs.
3908 :description string, describe the process.
3909 :message string, message it when required programs cannot be found.
3910 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3911 :image-output-type string, output file type of image converter (e.g., \"png\").
3912 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3913 deal with background and foreground color of image.
3914 Otherwise, dvipng style background and foreground color
3915 format are generated. You may then refer to them in
3916 command options with \"%F\" and \"%B\".
3917 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3918 image size showed in buffer and the cdr element is for
3919 HTML file. This option is only useful for process
3920 developers, users should use variable
3921 `org-format-latex-options' instead.
3922 :post-clean list of strings, files matched are to be cleaned up once
3923 the image is generated. When nil, the files with \".dvi\",
3924 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3925 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3926 be cleaned up.
3927 :latex-header list of strings, the LaTeX header of the snippet file.
3928 When nil, the fallback value is used instead, which is
3929 controlled by `org-format-latex-header',
3930 `org-latex-default-packages-alist' and
3931 `org-latex-packages-alist', which see.
3932 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3933 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3934 replaced with values defined below.
3935 :image-converter list of image converter commands strings. Each of them is
3936 given to the shell and supports any of the following
3937 place-holders defined below.
3939 Place-holders used by `:image-converter' and `:latex-compiler':
3941 %f input file name
3942 %b base name of input file
3943 %o base directory of input file
3944 %O absolute output file name
3946 Place-holders only used by `:image-converter':
3948 %F foreground of image
3949 %B background of image
3950 %D dpi, which is used to adjust image size by some processing commands.
3951 %S the image size scale ratio, which is used to adjust image size by some
3952 processing commands."
3953 :group 'org-latex
3954 :version "26.1"
3955 :package-version '(Org . "9.0")
3956 :type '(alist :tag "LaTeX to image backends"
3957 :value-type (plist)))
3959 (defcustom org-preview-latex-image-directory "ltximg/"
3960 "Path to store latex preview images.
3961 A relative path here creates many directories relative to the
3962 processed Org files paths. An absolute path puts all preview
3963 images at the same place."
3964 :group 'org-latex
3965 :version "26.1"
3966 :package-version '(Org . "9.0")
3967 :type 'string)
3969 (defun org-format-latex-mathml-available-p ()
3970 "Return t if `org-latex-to-mathml-convert-command' is usable."
3971 (save-match-data
3972 (when (and (boundp 'org-latex-to-mathml-convert-command)
3973 org-latex-to-mathml-convert-command)
3974 (let ((executable (car (split-string
3975 org-latex-to-mathml-convert-command))))
3976 (when (executable-find executable)
3977 (if (string-match
3978 "%j" org-latex-to-mathml-convert-command)
3979 (file-readable-p org-latex-to-mathml-jar-file)
3980 t))))))
3982 (defcustom org-format-latex-header "\\documentclass{article}
3983 \\usepackage[usenames]{color}
3984 \[PACKAGES]
3985 \[DEFAULT-PACKAGES]
3986 \\pagestyle{empty} % do not remove
3987 % The settings below are copied from fullpage.sty
3988 \\setlength{\\textwidth}{\\paperwidth}
3989 \\addtolength{\\textwidth}{-3cm}
3990 \\setlength{\\oddsidemargin}{1.5cm}
3991 \\addtolength{\\oddsidemargin}{-2.54cm}
3992 \\setlength{\\evensidemargin}{\\oddsidemargin}
3993 \\setlength{\\textheight}{\\paperheight}
3994 \\addtolength{\\textheight}{-\\headheight}
3995 \\addtolength{\\textheight}{-\\headsep}
3996 \\addtolength{\\textheight}{-\\footskip}
3997 \\addtolength{\\textheight}{-3cm}
3998 \\setlength{\\topmargin}{1.5cm}
3999 \\addtolength{\\topmargin}{-2.54cm}"
4000 "The document header used for processing LaTeX fragments.
4001 It is imperative that this header make sure that no page number
4002 appears on the page. The package defined in the variables
4003 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4004 will either replace the placeholder \"[PACKAGES]\" in this
4005 header, or they will be appended."
4006 :group 'org-latex
4007 :type 'string)
4009 (defun org-set-packages-alist (var val)
4010 "Set the packages alist and make sure it has 3 elements per entry."
4011 (set var (mapcar (lambda (x)
4012 (if (and (consp x) (= (length x) 2))
4013 (list (car x) (nth 1 x) t)
4015 val)))
4017 (defun org-get-packages-alist (var)
4018 "Get the packages alist and make sure it has 3 elements per entry."
4019 (mapcar (lambda (x)
4020 (if (and (consp x) (= (length x) 2))
4021 (list (car x) (nth 1 x) t)
4023 (default-value var)))
4025 (defcustom org-latex-default-packages-alist
4026 '(("AUTO" "inputenc" t ("pdflatex"))
4027 ("T1" "fontenc" t ("pdflatex"))
4028 ("" "graphicx" t)
4029 ("" "grffile" t)
4030 ("" "longtable" nil)
4031 ("" "wrapfig" nil)
4032 ("" "rotating" nil)
4033 ("normalem" "ulem" t)
4034 ("" "amsmath" t)
4035 ("" "textcomp" t)
4036 ("" "amssymb" t)
4037 ("" "capt-of" nil)
4038 ("" "hyperref" nil))
4039 "Alist of default packages to be inserted in the header.
4041 Change this only if one of the packages here causes an
4042 incompatibility with another package you are using.
4044 The packages in this list are needed by one part or another of
4045 Org mode to function properly:
4047 - inputenc, fontenc: for basic font and character selection
4048 - graphicx: for including images
4049 - grffile: allow periods and spaces in graphics file names
4050 - longtable: For multipage tables
4051 - wrapfig: for figure placement
4052 - rotating: for sideways figures and tables
4053 - ulem: for underline and strike-through
4054 - amsmath: for subscript and superscript and math environments
4055 - textcomp, amssymb: for various symbols used
4056 for interpreting the entities in `org-entities'. You can skip
4057 some of these packages if you don't use any of their symbols.
4058 - capt-of: for captions outside of floats
4059 - hyperref: for cross references
4061 Therefore you should not modify this variable unless you know
4062 what you are doing. The one reason to change it anyway is that
4063 you might be loading some other package that conflicts with one
4064 of the default packages. Each element is either a cell or
4065 a string.
4067 A cell is of the format
4069 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4071 If SNIPPET-FLAG is non-nil, the package also needs to be included
4072 when compiling LaTeX snippets into images for inclusion into
4073 non-LaTeX output. COMPILERS is a list of compilers that should
4074 include the package, see `org-latex-compiler'. If the document
4075 compiler is not in the list, and the list is non-nil, the package
4076 will not be inserted in the final document.
4078 A string will be inserted as-is in the header of the document."
4079 :group 'org-latex
4080 :group 'org-export-latex
4081 :set 'org-set-packages-alist
4082 :get 'org-get-packages-alist
4083 :version "26.1"
4084 :package-version '(Org . "8.3")
4085 :type '(repeat
4086 (choice
4087 (list :tag "options/package pair"
4088 (string :tag "options")
4089 (string :tag "package")
4090 (boolean :tag "Snippet")
4091 (choice
4092 (const :tag "For all compilers" nil)
4093 (repeat :tag "Allowed compiler" string)))
4094 (string :tag "A line of LaTeX"))))
4096 (defcustom org-latex-packages-alist nil
4097 "Alist of packages to be inserted in every LaTeX header.
4099 These will be inserted after `org-latex-default-packages-alist'.
4100 Each element is either a cell or a string.
4102 A cell is of the format:
4104 (\"options\" \"package\" SNIPPET-FLAG)
4106 SNIPPET-FLAG, when non-nil, indicates that this package is also
4107 needed when turning LaTeX snippets into images for inclusion into
4108 non-LaTeX output.
4110 A string will be inserted as-is in the header of the document.
4112 Make sure that you only list packages here which:
4114 - you want in every file;
4115 - do not conflict with the setup in `org-format-latex-header';
4116 - do not conflict with the default packages in
4117 `org-latex-default-packages-alist'."
4118 :group 'org-latex
4119 :group 'org-export-latex
4120 :set 'org-set-packages-alist
4121 :get 'org-get-packages-alist
4122 :type '(repeat
4123 (choice
4124 (list :tag "options/package pair"
4125 (string :tag "options")
4126 (string :tag "package")
4127 (boolean :tag "Snippet"))
4128 (string :tag "A line of LaTeX"))))
4130 (defgroup org-appearance nil
4131 "Settings for Org mode appearance."
4132 :tag "Org Appearance"
4133 :group 'org)
4135 (defcustom org-level-color-stars-only nil
4136 "Non-nil means fontify only the stars in each headline.
4137 When nil, the entire headline is fontified.
4138 Changing it requires restart of `font-lock-mode' to become effective
4139 also in regions already fontified."
4140 :group 'org-appearance
4141 :type 'boolean)
4143 (defcustom org-hide-leading-stars nil
4144 "Non-nil means hide the first N-1 stars in a headline.
4145 This works by using the face `org-hide' for these stars. This
4146 face is white for a light background, and black for a dark
4147 background. You may have to customize the face `org-hide' to
4148 make this work.
4149 Changing it requires restart of `font-lock-mode' to become effective
4150 also in regions already fontified.
4151 You may also set this on a per-file basis by adding one of the following
4152 lines to the buffer:
4154 #+STARTUP: hidestars
4155 #+STARTUP: showstars"
4156 :group 'org-appearance
4157 :type 'boolean)
4159 (defcustom org-hidden-keywords nil
4160 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4161 For example, a value \\='(title) for this list makes the document's title
4162 appear in the buffer without the initial \"#+TITLE:\" part."
4163 :group 'org-appearance
4164 :version "24.1"
4165 :type '(set (const :tag "#+AUTHOR" author)
4166 (const :tag "#+DATE" date)
4167 (const :tag "#+EMAIL" email)
4168 (const :tag "#+TITLE" title)))
4170 (defcustom org-custom-properties nil
4171 "List of properties (as strings) with a special meaning.
4172 The default use of these custom properties is to let the user
4173 hide them with `org-toggle-custom-properties-visibility'."
4174 :group 'org-properties
4175 :group 'org-appearance
4176 :version "24.3"
4177 :type '(repeat (string :tag "Property Name")))
4179 (defcustom org-fontify-done-headline nil
4180 "Non-nil means change the face of a headline if it is marked DONE.
4181 Normally, only the TODO/DONE keyword indicates the state of a headline.
4182 When this is non-nil, the headline after the keyword is set to the
4183 `org-headline-done' as an additional indication."
4184 :group 'org-appearance
4185 :type 'boolean)
4187 (defcustom org-fontify-emphasized-text t
4188 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4189 Changing this variable requires a restart of Emacs to take effect."
4190 :group 'org-appearance
4191 :type 'boolean)
4193 (defcustom org-fontify-whole-heading-line nil
4194 "Non-nil means fontify the whole line for headings.
4195 This is useful when setting a background color for the
4196 org-level-* faces."
4197 :group 'org-appearance
4198 :type 'boolean)
4200 (defcustom org-highlight-latex-and-related nil
4201 "Non-nil means highlight LaTeX related syntax in the buffer.
4202 When non nil, the value should be a list containing any of the
4203 following symbols:
4204 `latex' Highlight LaTeX snippets and environments.
4205 `script' Highlight subscript and superscript.
4206 `entities' Highlight entities."
4207 :group 'org-appearance
4208 :version "24.4"
4209 :package-version '(Org . "8.0")
4210 :type '(choice
4211 (const :tag "No highlighting" nil)
4212 (set :greedy t :tag "Highlight"
4213 (const :tag "LaTeX snippets and environments" latex)
4214 (const :tag "Subscript and superscript" script)
4215 (const :tag "Entities" entities))))
4217 (defcustom org-hide-emphasis-markers nil
4218 "Non-nil mean font-lock should hide the emphasis marker characters."
4219 :group 'org-appearance
4220 :type 'boolean)
4222 (defcustom org-hide-macro-markers nil
4223 "Non-nil mean font-lock should hide the brackets marking macro calls."
4224 :group 'org-appearance
4225 :type 'boolean)
4227 (defcustom org-pretty-entities nil
4228 "Non-nil means show entities as UTF8 characters.
4229 When nil, the \\name form remains in the buffer."
4230 :group 'org-appearance
4231 :version "24.1"
4232 :type 'boolean)
4234 (defcustom org-pretty-entities-include-sub-superscripts t
4235 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4236 :group 'org-appearance
4237 :version "24.1"
4238 :type 'boolean)
4240 (defvar org-emph-re nil
4241 "Regular expression for matching emphasis.
4242 After a match, the match groups contain these elements:
4243 0 The match of the full regular expression, including the characters
4244 before and after the proper match
4245 1 The character before the proper match, or empty at beginning of line
4246 2 The proper match, including the leading and trailing markers
4247 3 The leading marker like * or /, indicating the type of highlighting
4248 4 The text between the emphasis markers, not including the markers
4249 5 The character after the match, empty at the end of a line")
4251 (defvar org-verbatim-re nil
4252 "Regular expression for matching verbatim text.")
4254 (defvar org-emphasis-regexp-components) ; defined just below
4255 (defvar org-emphasis-alist) ; defined just below
4256 (defun org-set-emph-re (var val)
4257 "Set variable and compute the emphasis regular expression."
4258 (set var val)
4259 (when (and (boundp 'org-emphasis-alist)
4260 (boundp 'org-emphasis-regexp-components)
4261 org-emphasis-alist org-emphasis-regexp-components)
4262 (pcase-let*
4263 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4264 (body (if (<= nl 0) body
4265 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4266 (template
4267 (format (concat "\\([%s]\\|^\\)" ;before markers
4268 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4269 "\\([%s]\\|$\\)") ;after markers
4270 pre border border body border post)))
4271 (setq org-emph-re (format template "*/_+"))
4272 (setq org-verbatim-re (format template "=~")))))
4274 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4275 ;; set this option proved cumbersome. See this message/thread:
4276 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4277 (defvar org-emphasis-regexp-components
4278 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4279 "Components used to build the regular expression for emphasis.
4280 This is a list with five entries. Terminology: In an emphasis string
4281 like \" *strong word* \", we call the initial space PREMATCH, the final
4282 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4283 and \"trong wor\" is the body. The different components in this variable
4284 specify what is allowed/forbidden in each part:
4286 pre Chars allowed as prematch. Beginning of line will be allowed too.
4287 post Chars allowed as postmatch. End of line will be allowed too.
4288 border The chars *forbidden* as border characters.
4289 body-regexp A regexp like \".\" to match a body character. Don't use
4290 non-shy groups here, and don't allow newline here.
4291 newline The maximum number of newlines allowed in an emphasis exp.
4293 You need to reload Org or to restart Emacs after setting this.")
4295 (defcustom org-emphasis-alist
4296 '(("*" bold)
4297 ("/" italic)
4298 ("_" underline)
4299 ("=" org-verbatim verbatim)
4300 ("~" org-code verbatim)
4301 ("+" (:strike-through t)))
4302 "Alist of characters and faces to emphasize text.
4303 Text starting and ending with a special character will be emphasized,
4304 for example *bold*, _underlined_ and /italic/. This variable sets the
4305 marker characters and the face to be used by font-lock for highlighting
4306 in Org buffers.
4308 You need to reload Org or to restart Emacs after customizing this."
4309 :group 'org-appearance
4310 :set 'org-set-emph-re
4311 :version "24.4"
4312 :package-version '(Org . "8.0")
4313 :type '(repeat
4314 (list
4315 (string :tag "Marker character")
4316 (choice
4317 (face :tag "Font-lock-face")
4318 (plist :tag "Face property list"))
4319 (option (const verbatim)))))
4321 (defvar org-protecting-blocks '("src" "example" "export")
4322 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4323 This is needed for font-lock setup.")
4325 ;;; Functions and variables from their packages
4326 ;; Declared here to avoid compiler warnings
4327 (defvar mark-active)
4329 ;; Various packages
4330 (declare-function calc-eval "calc" (str &optional separator &rest args))
4331 (declare-function calendar-forward-day "cal-move" (arg))
4332 (declare-function calendar-goto-date "cal-move" (date))
4333 (declare-function calendar-goto-today "cal-move" ())
4334 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4335 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4336 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4337 (declare-function cdlatex-tab "ext:cdlatex" ())
4338 (declare-function dired-get-filename
4339 "dired"
4340 (&optional localp no-error-if-not-filep))
4341 (declare-function iswitchb-read-buffer
4342 "iswitchb"
4343 (prompt &optional
4344 default require-match _predicate start matches-set))
4345 (declare-function org-agenda-change-all-lines
4346 "org-agenda"
4347 (newhead hdmarker &optional fixface just-this))
4348 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4349 "org-agenda"
4350 (&optional end))
4351 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4352 (declare-function org-agenda-format-item
4353 "org-agenda"
4354 (extra txt &optional level category tags dotime
4355 remove-re habitp))
4356 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4357 (declare-function org-agenda-save-markers-for-cut-and-paste
4358 "org-agenda"
4359 (beg end))
4360 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4361 (declare-function org-agenda-skip "org-agenda" ())
4362 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4363 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4364 (declare-function org-indent-mode "org-indent" (&optional arg))
4365 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4366 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4367 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4368 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4369 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4370 (declare-function parse-time-string "parse-time" (string))
4372 (defvar align-mode-rules-list)
4373 (defvar calc-embedded-close-formula)
4374 (defvar calc-embedded-open-formula)
4375 (defvar calc-embedded-open-mode)
4376 (defvar font-lock-unfontify-region-function)
4377 (defvar iswitchb-temp-buflist)
4378 (defvar org-agenda-tags-todo-honor-ignore-options)
4379 (defvar remember-data-file)
4380 (defvar texmathp-why)
4382 ;;;###autoload
4383 (defun turn-on-orgtbl ()
4384 "Unconditionally turn on `orgtbl-mode'."
4385 (require 'org-table)
4386 (orgtbl-mode 1))
4388 (defun org-at-table-p (&optional table-type)
4389 "Non-nil if the cursor is inside an Org table.
4390 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4391 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4392 (or (not (derived-mode-p 'org-mode))
4393 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4394 (and e (or table-type
4395 (eq 'org (org-element-property :type e))))))))
4397 (defun org-at-table.el-p ()
4398 "Non-nil when point is at a table.el table."
4399 (and (org-match-line "[ \t]*[|+]")
4400 (let ((element (org-element-at-point)))
4401 (and (eq (org-element-type element) 'table)
4402 (eq (org-element-property :type element) 'table.el)))))
4404 (defun org-at-table-hline-p ()
4405 "Non-nil when point is inside a hline in a table.
4406 Assume point is already in a table."
4407 (org-match-line org-table-hline-regexp))
4409 (defun org-table-map-tables (function &optional quietly)
4410 "Apply FUNCTION to the start of all tables in the buffer."
4411 (org-with-wide-buffer
4412 (goto-char (point-min))
4413 (while (re-search-forward org-table-any-line-regexp nil t)
4414 (unless quietly
4415 (message "Mapping tables: %d%%"
4416 (floor (* 100.0 (point)) (buffer-size))))
4417 (beginning-of-line 1)
4418 (when (and (looking-at org-table-line-regexp)
4419 ;; Exclude tables in src/example/verbatim/clocktable blocks
4420 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4421 (save-excursion (funcall function))
4422 (or (looking-at org-table-line-regexp)
4423 (forward-char 1)))
4424 (re-search-forward org-table-any-border-regexp nil 1)))
4425 (unless quietly (message "Mapping tables: done")))
4427 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4428 (declare-function org-clock-update-mode-line "org-clock" ())
4429 (declare-function org-resolve-clocks "org-clock"
4430 (&optional also-non-dangling-p prompt last-valid))
4432 (defun org-at-TBLFM-p (&optional pos)
4433 "Non-nil when point (or POS) is in #+TBLFM line."
4434 (save-excursion
4435 (goto-char (or pos (point)))
4436 (beginning-of-line)
4437 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4438 (eq (org-element-type (org-element-at-point)) 'table))))
4440 (defvar org-clock-start-time)
4441 (defvar org-clock-marker (make-marker)
4442 "Marker recording the last clock-in.")
4443 (defvar org-clock-hd-marker (make-marker)
4444 "Marker recording the last clock-in, but the headline position.")
4445 (defvar org-clock-heading ""
4446 "The heading of the current clock entry.")
4447 (defun org-clock-is-active ()
4448 "Return the buffer where the clock is currently running.
4449 Return nil if no clock is running."
4450 (marker-buffer org-clock-marker))
4452 (defun org-check-running-clock ()
4453 "Check if the current buffer contains the running clock.
4454 If yes, offer to stop it and to save the buffer with the changes."
4455 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4456 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4457 (buffer-name))))
4458 (org-clock-out)
4459 (when (y-or-n-p "Save changed buffer?")
4460 (save-buffer))))
4462 (defun org-clocktable-try-shift (dir n)
4463 "Check if this line starts a clock table, if yes, shift the time block."
4464 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4465 (org-clocktable-shift dir n)))
4467 ;;;###autoload
4468 (defun org-clock-persistence-insinuate ()
4469 "Set up hooks for clock persistence."
4470 (require 'org-clock)
4471 (add-hook 'org-mode-hook 'org-clock-load)
4472 (add-hook 'kill-emacs-hook 'org-clock-save))
4474 (defgroup org-archive nil
4475 "Options concerning archiving in Org mode."
4476 :tag "Org Archive"
4477 :group 'org-structure)
4479 (defcustom org-archive-location "%s_archive::"
4480 "The location where subtrees should be archived.
4482 The value of this variable is a string, consisting of two parts,
4483 separated by a double-colon. The first part is a filename and
4484 the second part is a headline.
4486 When the filename is omitted, archiving happens in the same file.
4487 %s in the filename will be replaced by the current file
4488 name (without the directory part). Archiving to a different file
4489 is useful to keep archived entries from contributing to the
4490 Org Agenda.
4492 The archived entries will be filed as subtrees of the specified
4493 headline. When the headline is omitted, the subtrees are simply
4494 filed away at the end of the file, as top-level entries. Also in
4495 the heading you can use %s to represent the file name, this can be
4496 useful when using the same archive for a number of different files.
4498 Here are a few examples:
4499 \"%s_archive::\"
4500 If the current file is Projects.org, archive in file
4501 Projects.org_archive, as top-level trees. This is the default.
4503 \"::* Archived Tasks\"
4504 Archive in the current file, under the top-level headline
4505 \"* Archived Tasks\".
4507 \"~/org/archive.org::\"
4508 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4510 \"~/org/archive.org::* From %s\"
4511 Archive in file ~/org/archive.org (absolute path), under headlines
4512 \"From FILENAME\" where file name is the current file name.
4514 \"~/org/datetree.org::datetree/* Finished Tasks\"
4515 The \"datetree/\" string is special, signifying to archive
4516 items to the datetree. Items are placed in either the CLOSED
4517 date of the item, or the current date if there is no CLOSED date.
4518 The heading will be a subentry to the current date. There doesn't
4519 need to be a heading, but there always needs to be a slash after
4520 datetree. For example, to store archived items directly in the
4521 datetree, use \"~/org/datetree.org::datetree/\".
4523 \"basement::** Finished Tasks\"
4524 Archive in file ./basement (relative path), as level 3 trees
4525 below the level 2 heading \"** Finished Tasks\".
4527 You may set this option on a per-file basis by adding to the buffer a
4528 line like
4530 #+ARCHIVE: basement::** Finished Tasks
4532 You may also define it locally for a subtree by setting an ARCHIVE property
4533 in the entry. If such a property is found in an entry, or anywhere up
4534 the hierarchy, it will be used."
4535 :group 'org-archive
4536 :type 'string)
4538 (defcustom org-agenda-skip-archived-trees t
4539 "Non-nil means the agenda will skip any items located in archived trees.
4540 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4541 variable is no longer recommended, you should leave it at the value t.
4542 Instead, use the key `v' to cycle the archives-mode in the agenda."
4543 :group 'org-archive
4544 :group 'org-agenda-skip
4545 :type 'boolean)
4547 (defcustom org-columns-skip-archived-trees t
4548 "Non-nil means ignore archived trees when creating column view."
4549 :group 'org-archive
4550 :group 'org-properties
4551 :type 'boolean)
4553 (defcustom org-cycle-open-archived-trees nil
4554 "Non-nil means `org-cycle' will open archived trees.
4555 An archived tree is a tree marked with the tag ARCHIVE.
4556 When nil, archived trees will stay folded. You can still open them with
4557 normal outline commands like `show-all', but not with the cycling commands."
4558 :group 'org-archive
4559 :group 'org-cycle
4560 :type 'boolean)
4562 (defcustom org-sparse-tree-open-archived-trees nil
4563 "Non-nil means sparse tree construction shows matches in archived trees.
4564 When nil, matches in these trees are highlighted, but the trees are kept in
4565 collapsed state."
4566 :group 'org-archive
4567 :group 'org-sparse-trees
4568 :type 'boolean)
4570 (defcustom org-sparse-tree-default-date-type nil
4571 "The default date type when building a sparse tree.
4572 When this is nil, a date is a scheduled or a deadline timestamp.
4573 Otherwise, these types are allowed:
4575 all: all timestamps
4576 active: only active timestamps (<...>)
4577 inactive: only inactive timestamps ([...])
4578 scheduled: only scheduled timestamps
4579 deadline: only deadline timestamps"
4580 :type '(choice (const :tag "Scheduled or deadline" nil)
4581 (const :tag "All timestamps" all)
4582 (const :tag "Only active timestamps" active)
4583 (const :tag "Only inactive timestamps" inactive)
4584 (const :tag "Only scheduled timestamps" scheduled)
4585 (const :tag "Only deadline timestamps" deadline)
4586 (const :tag "Only closed timestamps" closed))
4587 :version "26.1"
4588 :package-version '(Org . "8.3")
4589 :group 'org-sparse-trees)
4591 (defun org-cycle-hide-archived-subtrees (state)
4592 "Re-hide all archived subtrees after a visibility state change.
4593 STATE should be one of the symbols listed in the docstring of
4594 `org-cycle-hook'."
4595 (when (and (not org-cycle-open-archived-trees)
4596 (not (memq state '(overview folded))))
4597 (save-excursion
4598 (let* ((globalp (memq state '(contents all)))
4599 (beg (if globalp (point-min) (point)))
4600 (end (if globalp (point-max) (org-end-of-subtree t))))
4601 (org-hide-archived-subtrees beg end)
4602 (goto-char beg)
4603 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4604 (message "%s" (substitute-command-keys
4605 "Subtree is archived and stays closed. Use \
4606 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4608 (defun org-force-cycle-archived ()
4609 "Cycle subtree even if it is archived."
4610 (interactive)
4611 (setq this-command 'org-cycle)
4612 (let ((org-cycle-open-archived-trees t))
4613 (call-interactively 'org-cycle)))
4615 (defun org-hide-archived-subtrees (beg end)
4616 "Re-hide all archived subtrees after a visibility state change."
4617 (org-with-wide-buffer
4618 (let ((case-fold-search nil)
4619 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4620 (goto-char beg)
4621 ;; Include headline point is currently on.
4622 (beginning-of-line)
4623 (while (and (< (point) end) (re-search-forward re end t))
4624 (when (member org-archive-tag (org-get-tags))
4625 (org-flag-subtree t)
4626 (org-end-of-subtree t))))))
4628 (defun org-flag-subtree (flag)
4629 (save-excursion
4630 (org-back-to-heading t)
4631 (org-flag-region (line-end-position)
4632 (progn (org-end-of-subtree t) (point))
4633 flag
4634 'outline)))
4636 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4638 ;; Declare Column View Code
4640 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4641 (declare-function org-columns-compute "org-colview" (property))
4643 ;; Declare ID code
4645 (declare-function org-id-store-link "org-id")
4646 (declare-function org-id-locations-load "org-id")
4647 (declare-function org-id-locations-save "org-id")
4648 (defvar org-id-track-globally)
4650 ;;; Variables for pre-computed regular expressions, all buffer local
4652 (defvar-local org-todo-regexp nil
4653 "Matches any of the TODO state keywords.
4654 Since TODO keywords are case-sensitive, `case-fold-search' is
4655 expected to be bound to nil when matching against this regexp.")
4657 (defvar-local org-not-done-regexp nil
4658 "Matches any of the TODO state keywords except the last one.
4659 Since TODO keywords are case-sensitive, `case-fold-search' is
4660 expected to be bound to nil when matching against this regexp.")
4662 (defvar-local org-not-done-heading-regexp nil
4663 "Matches a TODO headline that is not done.
4664 Since TODO keywords are case-sensitive, `case-fold-search' is
4665 expected to be bound to nil when matching against this regexp.")
4667 (defvar-local org-todo-line-regexp nil
4668 "Matches a headline and puts TODO state into group 2 if present.
4669 Since TODO keywords are case-sensitive, `case-fold-search' is
4670 expected to be bound to nil when matching against this regexp.")
4672 (defvar-local org-complex-heading-regexp nil
4673 "Matches a headline and puts everything into groups:
4675 group 1: Stars
4676 group 2: The TODO keyword, maybe
4677 group 3: Priority cookie
4678 group 4: True headline
4679 group 5: Tags
4681 Since TODO keywords are case-sensitive, `case-fold-search' is
4682 expected to be bound to nil when matching against this regexp.")
4684 (defvar-local org-complex-heading-regexp-format nil
4685 "Printf format to make regexp to match an exact headline.
4686 This regexp will match the headline of any node which has the
4687 exact headline text that is put into the format, but may have any
4688 TODO state, priority and tags.")
4690 (defvar-local org-todo-line-tags-regexp nil
4691 "Matches a headline and puts TODO state into group 2 if present.
4692 Also put tags into group 4 if tags are present.")
4694 (defconst org-plain-time-of-day-regexp
4695 (concat
4696 "\\(\\<[012]?[0-9]"
4697 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4698 "\\(--?"
4699 "\\(\\<[012]?[0-9]"
4700 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4701 "\\)?")
4702 "Regular expression to match a plain time or time range.
4703 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4704 groups carry important information:
4705 0 the full match
4706 1 the first time, range or not
4707 8 the second time, if it is a range.")
4709 (defconst org-plain-time-extension-regexp
4710 (concat
4711 "\\(\\<[012]?[0-9]"
4712 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4713 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4714 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4715 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4716 groups carry important information:
4717 0 the full match
4718 7 hours of duration
4719 9 minutes of duration")
4721 (defconst org-stamp-time-of-day-regexp
4722 (concat
4723 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4724 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4725 "\\(--?"
4726 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4727 "Regular expression to match a timestamp time or time range.
4728 After a match, the following groups carry important information:
4729 0 the full match
4730 1 date plus weekday, for back referencing to make sure both times are on the same day
4731 2 the first time, range or not
4732 4 the second time, if it is a range.")
4734 (defconst org-startup-options
4735 '(("fold" org-startup-folded t)
4736 ("overview" org-startup-folded t)
4737 ("nofold" org-startup-folded nil)
4738 ("showall" org-startup-folded nil)
4739 ("showeverything" org-startup-folded showeverything)
4740 ("content" org-startup-folded content)
4741 ("indent" org-startup-indented t)
4742 ("noindent" org-startup-indented nil)
4743 ("hidestars" org-hide-leading-stars t)
4744 ("showstars" org-hide-leading-stars nil)
4745 ("odd" org-odd-levels-only t)
4746 ("oddeven" org-odd-levels-only nil)
4747 ("align" org-startup-align-all-tables t)
4748 ("noalign" org-startup-align-all-tables nil)
4749 ("shrink" org-startup-shrink-all-tables t)
4750 ("inlineimages" org-startup-with-inline-images t)
4751 ("noinlineimages" org-startup-with-inline-images nil)
4752 ("latexpreview" org-startup-with-latex-preview t)
4753 ("nolatexpreview" org-startup-with-latex-preview nil)
4754 ("customtime" org-display-custom-times t)
4755 ("logdone" org-log-done time)
4756 ("lognotedone" org-log-done note)
4757 ("nologdone" org-log-done nil)
4758 ("lognoteclock-out" org-log-note-clock-out t)
4759 ("nolognoteclock-out" org-log-note-clock-out nil)
4760 ("logrepeat" org-log-repeat state)
4761 ("lognoterepeat" org-log-repeat note)
4762 ("logdrawer" org-log-into-drawer t)
4763 ("nologdrawer" org-log-into-drawer nil)
4764 ("logstatesreversed" org-log-states-order-reversed t)
4765 ("nologstatesreversed" org-log-states-order-reversed nil)
4766 ("nologrepeat" org-log-repeat nil)
4767 ("logreschedule" org-log-reschedule time)
4768 ("lognotereschedule" org-log-reschedule note)
4769 ("nologreschedule" org-log-reschedule nil)
4770 ("logredeadline" org-log-redeadline time)
4771 ("lognoteredeadline" org-log-redeadline note)
4772 ("nologredeadline" org-log-redeadline nil)
4773 ("logrefile" org-log-refile time)
4774 ("lognoterefile" org-log-refile note)
4775 ("nologrefile" org-log-refile nil)
4776 ("fninline" org-footnote-define-inline t)
4777 ("nofninline" org-footnote-define-inline nil)
4778 ("fnlocal" org-footnote-section nil)
4779 ("fnauto" org-footnote-auto-label t)
4780 ("fnprompt" org-footnote-auto-label nil)
4781 ("fnconfirm" org-footnote-auto-label confirm)
4782 ("fnplain" org-footnote-auto-label plain)
4783 ("fnadjust" org-footnote-auto-adjust t)
4784 ("nofnadjust" org-footnote-auto-adjust nil)
4785 ("constcgs" constants-unit-system cgs)
4786 ("constSI" constants-unit-system SI)
4787 ("noptag" org-tag-persistent-alist nil)
4788 ("hideblocks" org-hide-block-startup t)
4789 ("nohideblocks" org-hide-block-startup nil)
4790 ("beamer" org-startup-with-beamer-mode t)
4791 ("entitiespretty" org-pretty-entities t)
4792 ("entitiesplain" org-pretty-entities nil))
4793 "Variable associated with STARTUP options for Org.
4794 Each element is a list of three items: the startup options (as written
4795 in the #+STARTUP line), the corresponding variable, and the value to set
4796 this variable to if the option is found. An optional forth element PUSH
4797 means to push this value onto the list in the variable.")
4799 (defcustom org-group-tags t
4800 "When non-nil (the default), use group tags.
4801 This can be turned on/off through `org-toggle-tags-groups'."
4802 :group 'org-tags
4803 :group 'org-startup
4804 :type 'boolean)
4806 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4808 (defun org-toggle-tags-groups ()
4809 "Toggle support for group tags.
4810 Support for group tags is controlled by the option
4811 `org-group-tags', which is non-nil by default."
4812 (interactive)
4813 (setq org-group-tags (not org-group-tags))
4814 (cond ((and (derived-mode-p 'org-agenda-mode)
4815 org-group-tags)
4816 (org-agenda-redo))
4817 ((derived-mode-p 'org-mode)
4818 (let ((org-inhibit-startup t)) (org-mode))))
4819 (message "Groups tags support has been turned %s"
4820 (if org-group-tags "on" "off")))
4822 (defun org-tag-add-to-alist (alist1 alist2)
4823 "Append ALIST1 elements to ALIST2 if they are not there yet."
4824 (cond
4825 ((null alist2) alist1)
4826 ((null alist1) alist2)
4827 (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
4828 to-add)
4829 (dolist (i alist1)
4830 (unless (member (car-safe i) alist2-cars)
4831 (push i to-add)))
4832 (append to-add alist2)))))
4834 (defun org-set-regexps-and-options (&optional tags-only)
4835 "Precompute regular expressions used in the current buffer.
4836 When optional argument TAGS-ONLY is non-nil, only compute tags
4837 related expressions."
4838 (when (derived-mode-p 'org-mode)
4839 (let ((alist (org--setup-collect-keywords
4840 (org-make-options-regexp
4841 (append '("FILETAGS" "TAGS" "SETUPFILE")
4842 (and (not tags-only)
4843 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4844 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4845 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4846 ;; Startup options. Get this early since it does change
4847 ;; behavior for other options (e.g., tags).
4848 (let ((startup (cdr (assq 'startup alist))))
4849 (dolist (option startup)
4850 (let ((entry (assoc-string option org-startup-options t)))
4851 (when entry
4852 (let ((var (nth 1 entry))
4853 (val (nth 2 entry)))
4854 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4855 (unless (listp (symbol-value var))
4856 (set (make-local-variable var) nil))
4857 (add-to-list var val)))))))
4858 (setq-local org-file-tags
4859 (mapcar #'org-add-prop-inherited
4860 (cdr (assq 'filetags alist))))
4861 (setq org-current-tag-alist
4862 (org-tag-add-to-alist
4863 org-tag-persistent-alist
4864 (let ((tags (cdr (assq 'tags alist))))
4865 (if tags (org-tag-string-to-alist tags)
4866 org-tag-alist))))
4867 (setq org-tag-groups-alist
4868 (org-tag-alist-to-groups org-current-tag-alist))
4869 (unless tags-only
4870 ;; File properties.
4871 (setq-local org-file-properties (cdr (assq 'property alist)))
4872 ;; Archive location.
4873 (let ((archive (cdr (assq 'archive alist))))
4874 (when archive (setq-local org-archive-location archive)))
4875 ;; Category.
4876 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4877 (when cat
4878 (setq-local org-category (intern cat))
4879 (setq-local org-file-properties
4880 (org--update-property-plist
4881 "CATEGORY" cat org-file-properties))))
4882 ;; Columns.
4883 (let ((column (cdr (assq 'columns alist))))
4884 (when column (setq-local org-columns-default-format column)))
4885 ;; Constants.
4886 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4887 ;; Link abbreviations.
4888 (let ((links (cdr (assq 'link alist))))
4889 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4890 ;; Priorities.
4891 (let ((priorities (cdr (assq 'priorities alist))))
4892 (when priorities
4893 (setq-local org-highest-priority (nth 0 priorities))
4894 (setq-local org-lowest-priority (nth 1 priorities))
4895 (setq-local org-default-priority (nth 2 priorities))))
4896 ;; Scripts.
4897 (let ((scripts (assq 'scripts alist)))
4898 (when scripts
4899 (setq-local org-use-sub-superscripts (cdr scripts))))
4900 ;; TODO keywords.
4901 (setq-local org-todo-kwd-alist nil)
4902 (setq-local org-todo-key-alist nil)
4903 (setq-local org-todo-key-trigger nil)
4904 (setq-local org-todo-keywords-1 nil)
4905 (setq-local org-done-keywords nil)
4906 (setq-local org-todo-heads nil)
4907 (setq-local org-todo-sets nil)
4908 (setq-local org-todo-log-states nil)
4909 (let ((todo-sequences
4910 (or (nreverse (cdr (assq 'todo alist)))
4911 (let ((d (default-value 'org-todo-keywords)))
4912 (if (not (stringp (car d))) d
4913 ;; XXX: Backward compatibility code.
4914 (list (cons org-todo-interpretation d)))))))
4915 (dolist (sequence todo-sequences)
4916 (let* ((sequence (or (run-hook-with-args-until-success
4917 'org-todo-setup-filter-hook sequence)
4918 sequence))
4919 (sequence-type (car sequence))
4920 (keywords (cdr sequence))
4921 (sep (member "|" keywords))
4922 names alist)
4923 (dolist (k (remove "|" keywords))
4924 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4926 (error "Invalid TODO keyword %s" k))
4927 (let ((name (match-string 1 k))
4928 (key (match-string 2 k))
4929 (log (org-extract-log-state-settings k)))
4930 (push name names)
4931 (push (cons name (and key (string-to-char key))) alist)
4932 (when log (push log org-todo-log-states))))
4933 (let* ((names (nreverse names))
4934 (done (if sep (org-remove-keyword-keys (cdr sep))
4935 (last names)))
4936 (head (car names))
4937 (tail (list sequence-type head (car done) (org-last done))))
4938 (add-to-list 'org-todo-heads head 'append)
4939 (push names org-todo-sets)
4940 (setq org-done-keywords (append org-done-keywords done nil))
4941 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4942 (setq org-todo-key-alist
4943 (append org-todo-key-alist
4944 (and alist
4945 (append '((:startgroup))
4946 (nreverse alist)
4947 '((:endgroup))))))
4948 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4949 (setq org-todo-sets (nreverse org-todo-sets)
4950 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4951 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4952 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4953 ;; Compute the regular expressions and other local variables.
4954 ;; Using `org-outline-regexp-bol' would complicate them much,
4955 ;; because of the fixed white space at the end of that string.
4956 (unless org-done-keywords
4957 (setq org-done-keywords
4958 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4959 (setq org-not-done-keywords
4960 (org-delete-all org-done-keywords
4961 (copy-sequence org-todo-keywords-1))
4962 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4963 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4964 org-not-done-heading-regexp
4965 (format org-heading-keyword-regexp-format org-not-done-regexp)
4966 org-todo-line-regexp
4967 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4968 org-complex-heading-regexp
4969 (concat "^\\(\\*+\\)"
4970 "\\(?: +" org-todo-regexp "\\)?"
4971 "\\(?: +\\(\\[#.\\]\\)\\)?"
4972 "\\(?: +\\(.*?\\)\\)??"
4973 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4974 "[ \t]*$")
4975 org-complex-heading-regexp-format
4976 (concat "^\\(\\*+\\)"
4977 "\\(?: +" org-todo-regexp "\\)?"
4978 "\\(?: +\\(\\[#.\\]\\)\\)?"
4979 "\\(?: +"
4980 ;; Stats cookies can be stuck to body.
4981 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4982 "\\(%s\\)"
4983 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4984 "\\)"
4985 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4986 "[ \t]*$")
4987 org-todo-line-tags-regexp
4988 (concat "^\\(\\*+\\)"
4989 "\\(?: +" org-todo-regexp "\\)?"
4990 "\\(?: +\\(.*?\\)\\)??"
4991 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
4992 "[ \t]*$"))
4993 (org-compute-latex-and-related-regexp)))))
4995 (defun org--setup-collect-keywords (regexp &optional files alist)
4996 "Return setup keywords values as an alist.
4998 REGEXP matches a subset of setup keywords. FILES is a list of
4999 file names already visited. It is used to avoid circular setup
5000 files. ALIST, when non-nil, is the alist computed so far.
5002 Return value contains the following keys: `archive', `category',
5003 `columns', `constants', `filetags', `link', `priorities',
5004 `property', `scripts', `startup', `tags' and `todo'."
5005 (org-with-wide-buffer
5006 (goto-char (point-min))
5007 (let ((case-fold-search t))
5008 (while (re-search-forward regexp nil t)
5009 (let ((element (org-element-at-point)))
5010 (when (eq (org-element-type element) 'keyword)
5011 (let ((key (org-element-property :key element))
5012 (value (org-element-property :value element)))
5013 (cond
5014 ((equal key "ARCHIVE")
5015 (when (org-string-nw-p value)
5016 (push (cons 'archive value) alist)))
5017 ((equal key "CATEGORY") (push (cons 'category value) alist))
5018 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5019 ((equal key "CONSTANTS")
5020 (let* ((constants (assq 'constants alist))
5021 (store (cdr constants)))
5022 (dolist (pair (split-string value))
5023 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5024 pair)
5025 (let* ((name (match-string 1 pair))
5026 (value (match-string 2 pair))
5027 (old (assoc name store)))
5028 (if old (setcdr old value)
5029 (push (cons name value) store)))))
5030 (if constants (setcdr constants store)
5031 (push (cons 'constants store) alist))))
5032 ((equal key "FILETAGS")
5033 (when (org-string-nw-p value)
5034 (let ((old (assq 'filetags alist))
5035 (new (apply #'nconc
5036 (mapcar (lambda (x) (org-split-string x ":"))
5037 (split-string value)))))
5038 (if old (setcdr old (append new (cdr old)))
5039 (push (cons 'filetags new) alist)))))
5040 ((equal key "LINK")
5041 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5042 (let ((links (assq 'link alist))
5043 (pair (cons (match-string-no-properties 1 value)
5044 (match-string-no-properties 2 value))))
5045 (if links (push pair (cdr links))
5046 (push (list 'link pair) alist)))))
5047 ((equal key "OPTIONS")
5048 (when (and (org-string-nw-p value)
5049 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5050 (push (cons 'scripts (read (match-string 1 value))) alist)))
5051 ((equal key "PRIORITIES")
5052 (push (cons 'priorities
5053 (let ((prio (split-string value)))
5054 (if (< (length prio) 3) '(?A ?C ?B)
5055 (mapcar #'string-to-char prio))))
5056 alist))
5057 ((equal key "PROPERTY")
5058 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5059 (let* ((property (assq 'property alist))
5060 (value (org--update-property-plist
5061 (match-string-no-properties 1 value)
5062 (match-string-no-properties 2 value)
5063 (cdr property))))
5064 (if property (setcdr property value)
5065 (push (cons 'property value) alist)))))
5066 ((equal key "STARTUP")
5067 (let ((startup (assq 'startup alist)))
5068 (if startup
5069 (setcdr startup
5070 (append (cdr startup) (split-string value)))
5071 (push (cons 'startup (split-string value)) alist))))
5072 ((equal key "TAGS")
5073 (let ((tag-cell (assq 'tags alist)))
5074 (if tag-cell
5075 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5076 (push (cons 'tags value) alist))))
5077 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5078 (let ((todo (assq 'todo alist))
5079 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5080 (split-string value))))
5081 (if todo (push value (cdr todo))
5082 (push (list 'todo value) alist))))
5083 ((equal key "SETUPFILE")
5084 (unless buffer-read-only ; Do not check in Gnus messages.
5085 (let ((f (and (org-string-nw-p value)
5086 (expand-file-name
5087 (org-unbracket-string "\"" "\"" value)))))
5088 (when (and f (file-readable-p f) (not (member f files)))
5089 (with-temp-buffer
5090 (setq default-directory (file-name-directory f))
5091 (insert-file-contents f)
5092 (setq alist
5093 ;; Fake Org mode to benefit from cache
5094 ;; without recurring needlessly.
5095 (let ((major-mode 'org-mode))
5096 (org--setup-collect-keywords
5097 regexp (cons f files) alist)))))))))))))))
5098 alist)
5100 (defun org-tag-string-to-alist (s)
5101 "Return tag alist associated to string S.
5102 S is a value for TAGS keyword or produced with
5103 `org-tag-alist-to-string'. Return value is an alist suitable for
5104 `org-tag-alist' or `org-tag-persistent-alist'."
5105 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5106 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5107 "\\|{.+?}\\)" ; regular expression
5108 "\\(?:(\\(.\\))\\)?\\'"))
5109 alist group-flag)
5110 (dolist (tokens lines (cdr (nreverse alist)))
5111 (push '(:newline) alist)
5112 (while tokens
5113 (let ((token (pop tokens)))
5114 (pcase token
5115 ("{"
5116 (push '(:startgroup) alist)
5117 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5118 ("}"
5119 (push '(:endgroup) alist)
5120 (setq group-flag nil))
5121 ("["
5122 (push '(:startgrouptag) alist)
5123 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5124 ("]"
5125 (push '(:endgrouptag) alist)
5126 (setq group-flag nil))
5127 (":"
5128 (push '(:grouptags) alist))
5129 ((guard (string-match tag-re token))
5130 (let ((tag (match-string 1 token))
5131 (key (and (match-beginning 2)
5132 (string-to-char (match-string 2 token)))))
5133 ;; Push all tags in groups, no matter if they already
5134 ;; appear somewhere else in the list.
5135 (when (or group-flag (not (assoc tag alist)))
5136 (push (cons tag key) alist))))))))))
5138 (defun org-tag-alist-to-string (alist &optional skip-key)
5139 "Return tag string associated to ALIST.
5141 ALIST is an alist, as defined in `org-tag-alist' or
5142 `org-tag-persistent-alist', or produced with
5143 `org-tag-string-to-alist'.
5145 Return value is a string suitable as a value for \"TAGS\"
5146 keyword.
5148 When optional argument SKIP-KEY is non-nil, skip selection keys
5149 next to tags."
5150 (mapconcat (lambda (token)
5151 (pcase token
5152 (`(:startgroup) "{")
5153 (`(:endgroup) "}")
5154 (`(:startgrouptag) "[")
5155 (`(:endgrouptag) "]")
5156 (`(:grouptags) ":")
5157 (`(:newline) "\\n")
5158 ((and
5159 (guard (not skip-key))
5160 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5161 (format "%s(%c)" tag key))
5162 (`(,(and tag (pred stringp)) . ,_) tag)
5163 (_ (user-error "Invalid tag token: %S" token))))
5164 alist
5165 " "))
5167 (defun org-tag-alist-to-groups (alist)
5168 "Return group alist from tag ALIST.
5169 ALIST is an alist, as defined in `org-tag-alist' or
5170 `org-tag-persistent-alist', or produced with
5171 `org-tag-string-to-alist'. Return value is an alist following
5172 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5173 a string, summarizing TAGS, as a list of strings."
5174 (let (groups group-status current-group)
5175 (dolist (token alist (nreverse groups))
5176 (pcase token
5177 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5178 (`(,(or :endgroup :endgrouptag))
5179 (when (eq group-status 'append)
5180 (push (nreverse current-group) groups))
5181 (setq group-status nil current-group nil))
5182 (`(:grouptags) (setq group-status 'append))
5183 ((and `(,tag . ,_) (guard group-status))
5184 (if (eq group-status 'append) (push tag current-group)
5185 (setq current-group (list tag))))
5186 (_ nil)))))
5188 (defvar org--file-cache (make-hash-table :test #'equal)
5189 "Hash table to store contents of files referenced via a URL.
5190 This is the cache of file URLs read using `org-file-contents'.")
5192 (defun org-reset-file-cache ()
5193 "Reset the cache of files downloaded by `org-file-contents'."
5194 (clrhash org--file-cache))
5196 (defun org-file-url-p (file)
5197 "Non-nil if FILE is a URL."
5198 (require 'ffap)
5199 (string-match-p ffap-url-regexp file))
5201 (defun org-file-contents (file &optional noerror nocache)
5202 "Return the contents of FILE, as a string.
5204 FILE can be a file name or URL.
5206 If FILE is a URL, download the contents. If the URL contents are
5207 already cached in the `org--file-cache' hash table, the download step
5208 is skipped.
5210 If NOERROR is non-nil, ignore the error when unable to read the FILE
5211 from file or URL.
5213 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5214 is available. This option applies only if FILE is a URL."
5215 (let* ((is-url (org-file-url-p file))
5216 (cache (and is-url
5217 (not nocache)
5218 (gethash file org--file-cache))))
5219 (cond
5220 (cache)
5221 (is-url
5222 (with-current-buffer (url-retrieve-synchronously file)
5223 (goto-char (point-min))
5224 ;; Move point to after the url-retrieve header.
5225 (search-forward "\n\n" nil :move)
5226 ;; Search for the success code only in the url-retrieve header.
5227 (if (save-excursion
5228 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5229 ;; Update the cache `org--file-cache' and return contents.
5230 (puthash file
5231 (buffer-substring-no-properties (point) (point-max))
5232 org--file-cache)
5233 (funcall (if noerror #'message #'user-error)
5234 "Unable to fetch file from %S"
5235 file))))
5237 (with-temp-buffer
5238 (condition-case nil
5239 (progn
5240 (insert-file-contents file)
5241 (buffer-string))
5242 (file-error
5243 (funcall (if noerror #'message #'user-error)
5244 "Unable to read file %S"
5245 file))))))))
5247 (defun org-extract-log-state-settings (x)
5248 "Extract the log state setting from a TODO keyword string.
5249 This will extract info from a string like \"WAIT(w@/!)\"."
5250 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5251 (let ((kw (match-string 1 x))
5252 (log1 (and (match-end 3) (match-string 3 x)))
5253 (log2 (and (match-end 4) (match-string 4 x))))
5254 (and (or log1 log2)
5255 (list kw
5256 (and log1 (if (equal log1 "!") 'time 'note))
5257 (and log2 (if (equal log2 "!") 'time 'note)))))))
5259 (defun org-remove-keyword-keys (list)
5260 "Remove a pair of parenthesis at the end of each string in LIST."
5261 (mapcar (lambda (x)
5262 (if (string-match "(.*)$" x)
5263 (substring x 0 (match-beginning 0))
5265 list))
5267 (defun org-assign-fast-keys (alist)
5268 "Assign fast keys to a keyword-key alist.
5269 Respect keys that are already there."
5270 (let (new e (alt ?0))
5271 (while (setq e (pop alist))
5272 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5273 (cdr e)) ;; Key already assigned.
5274 (push e new)
5275 (let ((clist (string-to-list (downcase (car e))))
5276 (used (append new alist)))
5277 (when (= (car clist) ?@)
5278 (pop clist))
5279 (while (and clist (rassoc (car clist) used))
5280 (pop clist))
5281 (unless clist
5282 (while (rassoc alt used)
5283 (cl-incf alt)))
5284 (push (cons (car e) (or (car clist) alt)) new))))
5285 (nreverse new)))
5287 ;;; Some variables used in various places
5289 (defvar org-window-configuration nil
5290 "Used in various places to store a window configuration.")
5291 (defvar org-selected-window nil
5292 "Used in various places to store a window configuration.")
5293 (defvar org-finish-function nil
5294 "Function to be called when `C-c C-c' is used.
5295 This is for getting out of special buffers like capture.")
5296 (defvar org-last-state)
5298 ;; Defined somewhere in this file, but used before definition.
5299 (defvar org-entities) ;; defined in org-entities.el
5300 (defvar org-struct-menu)
5301 (defvar org-org-menu)
5302 (defvar org-tbl-menu)
5304 ;;;; Define the Org mode
5306 ;; We use a before-change function to check if a table might need
5307 ;; an update.
5308 (defvar org-table-may-need-update t
5309 "Indicates that a table might need an update.
5310 This variable is set by `org-before-change-function'.
5311 `org-table-align' sets it back to nil.")
5312 (defun org-before-change-function (_beg _end)
5313 "Every change indicates that a table might need an update."
5314 (setq org-table-may-need-update t))
5315 (defvar org-mode-map)
5316 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5317 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5318 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5319 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5320 (defvar org-table-buffer-is-an nil)
5322 (defvar bidi-paragraph-direction)
5323 (defvar buffer-face-mode-face)
5325 (require 'outline)
5327 ;; Other stuff we need.
5328 (require 'time-date)
5329 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5330 (require 'easymenu)
5331 (autoload 'easy-menu-add "easymenu")
5332 (require 'overlay)
5334 ;; (require 'org-macs) moved higher up in the file before it is first used
5335 (require 'org-entities)
5336 ;; (require 'org-compat) moved higher up in the file before it is first used
5337 (require 'org-faces)
5338 (require 'org-list)
5339 (require 'org-pcomplete)
5340 (require 'org-src)
5341 (require 'org-footnote)
5342 (require 'org-macro)
5344 ;; babel
5345 (require 'ob)
5347 ;;;###autoload
5348 (define-derived-mode org-mode outline-mode "Org"
5349 "Outline-based notes management and organizer, alias
5350 \"Carsten's outline-mode for keeping track of everything.\"
5352 Org mode develops organizational tasks around a NOTES file which
5353 contains information about projects as plain text. Org mode is
5354 implemented on top of Outline mode, which is ideal to keep the content
5355 of large files well structured. It supports ToDo items, deadlines and
5356 time stamps, which magically appear in the diary listing of the Emacs
5357 calendar. Tables are easily created with a built-in table editor.
5358 Plain text URL-like links connect to websites, emails (VM), Usenet
5359 messages (Gnus), BBDB entries, and any files related to the project.
5360 For printing and sharing of notes, an Org file (or a part of it)
5361 can be exported as a structured ASCII or HTML file.
5363 The following commands are available:
5365 \\{org-mode-map}"
5367 ;; Get rid of Outline menus, they are not needed
5368 ;; Need to do this here because define-derived-mode sets up
5369 ;; the keymap so late. Still, it is a waste to call this each time
5370 ;; we switch another buffer into Org mode.
5371 (define-key org-mode-map [menu-bar headings] 'undefined)
5372 (define-key org-mode-map [menu-bar hide] 'undefined)
5373 (define-key org-mode-map [menu-bar show] 'undefined)
5375 (org-load-modules-maybe)
5376 (org-install-agenda-files-menu)
5377 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5378 (add-to-invisibility-spec '(org-hide-block . t))
5379 (add-to-invisibility-spec '(org-hide-drawer . t))
5380 (setq-local outline-regexp org-outline-regexp)
5381 (setq-local outline-level 'org-outline-level)
5382 (setq bidi-paragraph-direction 'left-to-right)
5383 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5384 (unless org-display-table
5385 (setq org-display-table (make-display-table)))
5386 (set-display-table-slot
5387 org-display-table 4
5388 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5389 org-ellipsis)))
5390 (setq buffer-display-table org-display-table))
5391 (org-set-regexps-and-options)
5392 (org-set-font-lock-defaults)
5393 (when (and org-tag-faces (not org-tags-special-faces-re))
5394 ;; tag faces set outside customize.... force initialization.
5395 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5396 ;; Calc embedded
5397 (setq-local calc-embedded-open-mode "# ")
5398 ;; Modify a few syntax entries
5399 (modify-syntax-entry ?@ "w")
5400 (modify-syntax-entry ?\" "\"")
5401 (modify-syntax-entry ?\\ "_")
5402 (modify-syntax-entry ?~ "_")
5403 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5404 ;; Activate before-change-function
5405 (setq-local org-table-may-need-update t)
5406 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5407 ;; Check for running clock before killing a buffer
5408 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5409 ;; Initialize macros templates.
5410 (org-macro-initialize-templates)
5411 ;; Initialize radio targets.
5412 (org-update-radio-target-regexp)
5413 ;; Indentation.
5414 (setq-local indent-line-function 'org-indent-line)
5415 (setq-local indent-region-function 'org-indent-region)
5416 ;; Filling and auto-filling.
5417 (org-setup-filling)
5418 ;; Comments.
5419 (org-setup-comments-handling)
5420 ;; Initialize cache.
5421 (org-element-cache-reset)
5422 ;; Beginning/end of defun
5423 (setq-local beginning-of-defun-function 'org-backward-element)
5424 (setq-local end-of-defun-function
5425 (lambda ()
5426 (if (not (org-at-heading-p))
5427 (org-forward-element)
5428 (org-forward-element)
5429 (forward-char -1))))
5430 ;; Next error for sparse trees
5431 (setq-local next-error-function 'org-occur-next-match)
5432 ;; Make sure dependence stuff works reliably, even for users who set it
5433 ;; too late :-(
5434 (if org-enforce-todo-dependencies
5435 (add-hook 'org-blocker-hook
5436 'org-block-todo-from-children-or-siblings-or-parent)
5437 (remove-hook 'org-blocker-hook
5438 'org-block-todo-from-children-or-siblings-or-parent))
5439 (if org-enforce-todo-checkbox-dependencies
5440 (add-hook 'org-blocker-hook
5441 'org-block-todo-from-checkboxes)
5442 (remove-hook 'org-blocker-hook
5443 'org-block-todo-from-checkboxes))
5445 ;; Align options lines
5446 (setq-local
5447 align-mode-rules-list
5448 '((org-in-buffer-settings
5449 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5450 (modes . '(org-mode)))))
5452 ;; Imenu
5453 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5455 ;; Make isearch reveal context
5456 (setq-local outline-isearch-open-invisible-function
5457 (lambda (&rest _) (org-show-context 'isearch)))
5459 ;; Setup the pcomplete hooks
5460 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5461 (setq-local pcomplete-command-name-function 'org-command-at-point)
5462 (setq-local pcomplete-default-completion-function 'ignore)
5463 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5464 (setq-local pcomplete-termination-string "")
5465 (setq-local buffer-face-mode-face 'org-default)
5467 ;; If empty file that did not turn on Org mode automatically, make
5468 ;; it to.
5469 (when (and org-insert-mode-line-in-empty-file
5470 (called-interactively-p 'any)
5471 (= (point-min) (point-max)))
5472 (insert "# -*- mode: org -*-\n\n"))
5473 (unless org-inhibit-startup
5474 (org-unmodified
5475 (when org-startup-with-beamer-mode (org-beamer-mode))
5476 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5477 (org-table-map-tables
5478 (cond ((and org-startup-align-all-tables
5479 org-startup-shrink-all-tables)
5480 (lambda () (org-table-align) (org-table-shrink)))
5481 (org-startup-align-all-tables #'org-table-align)
5482 (t #'org-table-shrink))
5484 (when org-startup-with-inline-images (org-display-inline-images))
5485 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5486 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5487 (when org-startup-truncated (setq truncate-lines t))
5488 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5489 (org-refresh-effort-properties)))
5490 ;; Try to set `org-hide' face correctly.
5491 (let ((foreground (org-find-invisible-foreground)))
5492 (when foreground
5493 (set-face-foreground 'org-hide foreground))))
5495 ;; Update `customize-package-emacs-version-alist'
5496 (add-to-list 'customize-package-emacs-version-alist
5497 '(Org ("8.0" . "24.4")
5498 ("8.1" . "24.4")
5499 ("8.2" . "24.4")
5500 ("8.2.7" . "24.4")
5501 ("8.3" . "26.1")
5502 ("9.0" . "26.1")
5503 ("9.1" . "26.1")
5504 ("9.2" . "27.1")))
5506 (defvar org-mode-transpose-word-syntax-table
5507 (let ((st (make-syntax-table text-mode-syntax-table)))
5508 (dolist (c org-emphasis-alist st)
5509 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5511 (when (fboundp 'abbrev-table-put)
5512 (abbrev-table-put org-mode-abbrev-table
5513 :parents (list text-mode-abbrev-table)))
5515 (defun org-find-invisible-foreground ()
5516 (let ((candidates (remove
5517 "unspecified-bg"
5518 (nconc
5519 (list (face-background 'default)
5520 (face-background 'org-default))
5521 (mapcar
5522 (lambda (alist)
5523 (when (boundp alist)
5524 (cdr (assq 'background-color (symbol-value alist)))))
5525 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5526 (list (face-foreground 'org-hide))))))
5527 (car (remove nil candidates))))
5529 (defun org-current-time (&optional rounding-minutes past)
5530 "Current time, possibly rounded to ROUNDING-MINUTES.
5531 When ROUNDING-MINUTES is not an integer, fall back on the car of
5532 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5533 the rounding returns a past time."
5534 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5535 (car org-time-stamp-rounding-minutes)))
5536 (time (decode-time)) res)
5537 (if (< r 1)
5538 (current-time)
5539 (setq res
5540 (apply 'encode-time
5541 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5542 (nthcdr 2 time))))
5543 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5544 (seconds-to-time (- (float-time res) (* r 60)))
5545 res))))
5547 (defun org-today ()
5548 "Return today date, considering `org-extend-today-until'."
5549 (time-to-days
5550 (time-subtract (current-time)
5551 (list 0 (* 3600 org-extend-today-until) 0))))
5553 ;;;; Font-Lock stuff, including the activators
5555 (defvar org-mouse-map (make-sparse-keymap))
5556 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5557 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5558 (when org-mouse-1-follows-link
5559 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5560 (when org-tab-follows-link
5561 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5562 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5564 (require 'font-lock)
5566 (defconst org-non-link-chars "]\t\n\r<>")
5567 (defvar org-link-types-re nil
5568 "Matches a link that has a url-like prefix like \"http:\"")
5569 (defvar org-link-re-with-space nil
5570 "Matches a link with spaces, optional angular brackets around it.")
5571 (defvar org-link-re-with-space2 nil
5572 "Matches a link with spaces, optional angular brackets around it.")
5573 (defvar org-link-re-with-space3 nil
5574 "Matches a link with spaces, only for internal part in bracket links.")
5575 (defvar org-angle-link-re nil
5576 "Matches link with angular brackets, spaces are allowed.")
5577 (defvar org-plain-link-re nil
5578 "Matches plain link, without spaces.")
5579 (defvar org-bracket-link-regexp nil
5580 "Matches a link in double brackets.")
5581 (defvar org-bracket-link-analytic-regexp nil
5582 "Regular expression used to analyze links.
5583 Here is what the match groups contain after a match:
5584 1: http:
5585 2: http
5586 3: path
5587 4: [desc]
5588 5: desc")
5589 (defvar org-bracket-link-analytic-regexp++ nil
5590 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5591 (defvar org-any-link-re nil
5592 "Regular expression matching any link.")
5594 (defconst org-match-sexp-depth 3
5595 "Number of stacked braces for sub/superscript matching.")
5597 (defun org-create-multibrace-regexp (left right n)
5598 "Create a regular expression which will match a balanced sexp.
5599 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5600 as single character strings.
5601 The regexp returned will match the entire expression including the
5602 delimiters. It will also define a single group which contains the
5603 match except for the outermost delimiters. The maximum depth of
5604 stacked delimiters is N. Escaping delimiters is not possible."
5605 (let* ((nothing (concat "[^" left right "]*?"))
5606 (or "\\|")
5607 (re nothing)
5608 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5609 (while (> n 1)
5610 (setq n (1- n)
5611 re (concat re or next)
5612 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5613 (concat left "\\(" re "\\)" right)))
5615 (defconst org-match-substring-regexp
5616 (concat
5617 "\\(\\S-\\)\\([_^]\\)\\("
5618 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5619 "\\|"
5620 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5621 "\\|"
5622 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5623 "The regular expression matching a sub- or superscript.")
5625 (defconst org-match-substring-with-braces-regexp
5626 (concat
5627 "\\(\\S-\\)\\([_^]\\)"
5628 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5629 "The regular expression matching a sub- or superscript, forcing braces.")
5631 (defun org-make-link-regexps ()
5632 "Update the link regular expressions.
5633 This should be called after the variable `org-link-parameters' has changed."
5634 (let ((types-re (regexp-opt (org-link-types) t)))
5635 (setq org-link-types-re
5636 (concat "\\`" types-re ":")
5637 org-link-re-with-space
5638 (concat "<?" types-re ":"
5639 "\\([^" org-non-link-chars " ]"
5640 "[^" org-non-link-chars "]*"
5641 "[^" org-non-link-chars " ]\\)>?")
5642 org-link-re-with-space2
5643 (concat "<?" types-re ":"
5644 "\\([^" org-non-link-chars " ]"
5645 "[^\t\n\r]*"
5646 "[^" org-non-link-chars " ]\\)>?")
5647 org-link-re-with-space3
5648 (concat "<?" types-re ":"
5649 "\\([^" org-non-link-chars " ]"
5650 "[^\t\n\r]*\\)")
5651 org-angle-link-re
5652 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5653 types-re)
5654 org-plain-link-re
5655 (concat
5656 "\\<" types-re ":"
5657 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5658 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5659 org-bracket-link-regexp
5660 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5661 org-bracket-link-analytic-regexp
5662 (concat
5663 "\\[\\["
5664 "\\(" types-re ":\\)?"
5665 "\\([^]]+\\)"
5666 "\\]"
5667 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5668 "\\]")
5669 org-bracket-link-analytic-regexp++
5670 (concat
5671 "\\[\\["
5672 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5673 "\\([^]]+\\)"
5674 "\\]"
5675 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5676 "\\]")
5677 org-any-link-re
5678 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5679 org-angle-link-re "\\)\\|\\("
5680 org-plain-link-re "\\)"))))
5682 (org-make-link-regexps)
5684 (defvar org-emph-face nil)
5686 (defun org-do-emphasis-faces (limit)
5687 "Run through the buffer and emphasize strings."
5688 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5689 (car org-emphasis-regexp-components))))
5690 (catch :exit
5691 (while (re-search-forward quick-re limit t)
5692 (let* ((marker (match-string 2))
5693 (verbatim? (member marker '("~" "="))))
5694 (when (save-excursion
5695 (goto-char (match-beginning 0))
5696 (and
5697 ;; Do not match table hlines.
5698 (not (and (equal marker "+")
5699 (org-match-line
5700 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5701 ;; Do not match headline stars. Do not consider
5702 ;; stars of a headline as closing marker for bold
5703 ;; markup either.
5704 (not (and (equal marker "*")
5705 (save-excursion
5706 (forward-char)
5707 (skip-chars-backward "*")
5708 (looking-at-p org-outline-regexp-bol))))
5709 ;; Match full emphasis markup regexp.
5710 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5711 ;; Do not span over paragraph boundaries.
5712 (not (string-match-p org-element-paragraph-separate
5713 (match-string 2)))
5714 ;; Do not span over cells in table rows.
5715 (not (and (save-match-data (org-match-line "[ \t]*|"))
5716 (string-match-p "|" (match-string 4))))))
5717 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5718 (font-lock-prepend-text-property
5719 (match-beginning 2) (match-end 2) 'face face)
5720 (when verbatim?
5721 (org-remove-flyspell-overlays-in
5722 (match-beginning 0) (match-end 0)))
5723 (add-text-properties (match-beginning 2) (match-end 2)
5724 '(font-lock-multiline t org-emphasis t))
5725 (when org-hide-emphasis-markers
5726 (add-text-properties (match-end 4) (match-beginning 5)
5727 '(invisible org-link))
5728 (add-text-properties (match-beginning 3) (match-end 3)
5729 '(invisible org-link)))
5730 (throw :exit t))))))))
5732 (defun org-emphasize (&optional char)
5733 "Insert or change an emphasis, i.e. a font like bold or italic.
5734 If there is an active region, change that region to a new emphasis.
5735 If there is no region, just insert the marker characters and position
5736 the cursor between them.
5737 CHAR should be the marker character. If it is a space, it means to
5738 remove the emphasis of the selected region.
5739 If CHAR is not given (for example in an interactive call) it will be
5740 prompted for."
5741 (interactive)
5742 (let ((erc org-emphasis-regexp-components)
5743 (string "") beg end move s)
5744 (if (org-region-active-p)
5745 (setq beg (region-beginning)
5746 end (region-end)
5747 string (buffer-substring beg end))
5748 (setq move t))
5750 (unless char
5751 (message "Emphasis marker or tag: [%s]"
5752 (mapconcat #'car org-emphasis-alist ""))
5753 (setq char (read-char-exclusive)))
5754 (if (equal char ?\s)
5755 (setq s ""
5756 move nil)
5757 (unless (assoc (char-to-string char) org-emphasis-alist)
5758 (user-error "No such emphasis marker: \"%c\"" char))
5759 (setq s (char-to-string char)))
5760 (while (and (> (length string) 1)
5761 (equal (substring string 0 1) (substring string -1))
5762 (assoc (substring string 0 1) org-emphasis-alist))
5763 (setq string (substring string 1 -1)))
5764 (setq string (concat s string s))
5765 (when beg (delete-region beg end))
5766 (unless (or (bolp)
5767 (string-match (concat "[" (nth 0 erc) "\n]")
5768 (char-to-string (char-before (point)))))
5769 (insert " "))
5770 (unless (or (eobp)
5771 (string-match (concat "[" (nth 1 erc) "\n]")
5772 (char-to-string (char-after (point)))))
5773 (insert " ") (backward-char 1))
5774 (insert string)
5775 (and move (backward-char 1))))
5777 (defconst org-nonsticky-props
5778 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5780 (defsubst org-rear-nonsticky-at (pos)
5781 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5783 (defun org-activate-links (limit)
5784 "Add link properties to links.
5785 This includes angle, plain, and bracket links."
5786 (catch :exit
5787 (while (re-search-forward org-any-link-re limit t)
5788 (let* ((start (match-beginning 0))
5789 (end (match-end 0))
5790 (style (cond ((eq ?< (char-after start)) 'angle)
5791 ((eq ?\[ (char-after (1+ start))) 'bracket)
5792 (t 'plain))))
5793 (when (and (memq style org-highlight-links)
5794 ;; Do not confuse plain links with tags.
5795 (not (and (eq style 'plain)
5796 (let ((face (get-text-property
5797 (max (1- start) (point-min)) 'face)))
5798 (if (consp face) (memq 'org-tag face)
5799 (eq 'org-tag face))))))
5800 (let* ((link-object (save-excursion
5801 (goto-char start)
5802 (save-match-data (org-element-link-parser))))
5803 (link (org-element-property :raw-link link-object))
5804 (type (org-element-property :type link-object))
5805 (path (org-element-property :path link-object))
5806 (properties ;for link's visible part
5807 (list
5808 'face (pcase (org-link-get-parameter type :face)
5809 ((and (pred functionp) face) (funcall face path))
5810 ((and (pred facep) face) face)
5811 ((and (pred consp) face) face) ;anonymous
5812 (_ 'org-link))
5813 'mouse-face (or (org-link-get-parameter type :mouse-face)
5814 'highlight)
5815 'keymap (or (org-link-get-parameter type :keymap)
5816 org-mouse-map)
5817 'help-echo (pcase (org-link-get-parameter type :help-echo)
5818 ((and (pred stringp) echo) echo)
5819 ((and (pred functionp) echo) echo)
5820 (_ (concat "LINK: " link)))
5821 'htmlize-link (pcase (org-link-get-parameter type
5822 :htmlize-link)
5823 ((and (pred functionp) f) (funcall f))
5824 (_ `(:uri ,link)))
5825 'font-lock-multiline t)))
5826 (org-remove-flyspell-overlays-in start end)
5827 (org-rear-nonsticky-at end)
5828 (if (not (eq 'bracket style))
5829 (add-text-properties start end properties)
5830 ;; Handle invisible parts in bracket links.
5831 (remove-text-properties start end '(invisible nil))
5832 (let ((hidden
5833 (append `(invisible
5834 ,(or (org-link-get-parameter type :display)
5835 'org-link))
5836 properties))
5837 (visible-start (or (match-beginning 4) (match-beginning 2)))
5838 (visible-end (or (match-end 4) (match-end 2))))
5839 (add-text-properties start visible-start hidden)
5840 (add-text-properties visible-start visible-end properties)
5841 (add-text-properties visible-end end hidden)
5842 (org-rear-nonsticky-at visible-start)
5843 (org-rear-nonsticky-at visible-end)))
5844 (let ((f (org-link-get-parameter type :activate-func)))
5845 (when (functionp f)
5846 (funcall f start end path (eq style 'bracket))))
5847 (throw :exit t))))) ;signal success
5848 nil))
5850 (defun org-activate-code (limit)
5851 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5852 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5853 (remove-text-properties (match-beginning 0) (match-end 0)
5854 '(display t invisible t intangible t))
5857 (defcustom org-src-fontify-natively t
5858 "When non-nil, fontify code in code blocks.
5859 See also the `org-block' face."
5860 :type 'boolean
5861 :version "26.1"
5862 :package-version '(Org . "8.3")
5863 :group 'org-appearance
5864 :group 'org-babel)
5866 (defcustom org-allow-promoting-top-level-subtree nil
5867 "When non-nil, allow promoting a top level subtree.
5868 The leading star of the top level headline will be replaced
5869 by a #."
5870 :type 'boolean
5871 :version "24.1"
5872 :group 'org-appearance)
5874 (defun org-fontify-meta-lines-and-blocks (limit)
5875 (condition-case nil
5876 (org-fontify-meta-lines-and-blocks-1 limit)
5877 (error (message "Org mode fontification error in %S at %d"
5878 (current-buffer)
5879 (line-number-at-pos)))))
5881 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5882 "Fontify #+ lines and blocks."
5883 (let ((case-fold-search t))
5884 (when (re-search-forward
5885 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5886 limit t)
5887 (let ((beg (match-beginning 0))
5888 (block-start (match-end 0))
5889 (block-end nil)
5890 (lang (match-string 7))
5891 (beg1 (line-beginning-position 2))
5892 (dc1 (downcase (match-string 2)))
5893 (dc3 (downcase (match-string 3)))
5894 end end1 quoting block-type)
5895 (cond
5896 ((and (match-end 4) (equal dc3 "+begin"))
5897 ;; Truly a block
5898 (setq block-type (downcase (match-string 5))
5899 quoting (member block-type org-protecting-blocks))
5900 (when (re-search-forward
5901 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5902 nil t) ;; on purpose, we look further than LIMIT
5903 (setq end (min (point-max) (match-end 0))
5904 end1 (min (point-max) (1- (match-beginning 0))))
5905 (setq block-end (match-beginning 0))
5906 (when quoting
5907 (org-remove-flyspell-overlays-in beg1 end1)
5908 (remove-text-properties beg end
5909 '(display t invisible t intangible t)))
5910 (add-text-properties
5911 beg end '(font-lock-fontified t font-lock-multiline t))
5912 (add-text-properties beg beg1 '(face org-meta-line))
5913 (org-remove-flyspell-overlays-in beg beg1)
5914 (add-text-properties ; For end_src
5915 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5916 (org-remove-flyspell-overlays-in end1 end)
5917 (cond
5918 ((and lang (not (string= lang "")) org-src-fontify-natively)
5919 (org-src-font-lock-fontify-block lang block-start block-end)
5920 (add-text-properties beg1 block-end '(src-block t)))
5921 (quoting
5922 (add-text-properties beg1 (min (point-max) (1+ end1))
5923 (list 'face
5924 (list :inherit
5925 (let ((face-name
5926 (intern (format "org-block-%s" lang))))
5927 (append (and (facep face-name) (list face-name))
5928 '(org-block))))))) ; end of source block
5929 ((not org-fontify-quote-and-verse-blocks))
5930 ((string= block-type "quote")
5931 (add-face-text-property
5932 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5933 ((string= block-type "verse")
5934 (add-face-text-property
5935 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5936 (add-text-properties beg beg1 '(face org-block-begin-line))
5937 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5938 '(face org-block-end-line))
5940 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5941 (org-remove-flyspell-overlays-in
5942 (match-beginning 0)
5943 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5944 (add-text-properties
5945 beg (match-end 3)
5946 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5947 '(font-lock-fontified t invisible t)
5948 '(font-lock-fontified t face org-document-info-keyword)))
5949 (add-text-properties
5950 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5951 (if (string-equal dc1 "+title:")
5952 '(font-lock-fontified t face org-document-title)
5953 '(font-lock-fontified t face org-document-info))))
5954 ((string-prefix-p "+caption" dc1)
5955 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5956 (remove-text-properties (match-beginning 0) (match-end 0)
5957 '(display t invisible t intangible t))
5958 ;; Handle short captions.
5959 (save-excursion
5960 (beginning-of-line)
5961 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5962 (add-text-properties (line-beginning-position) (match-end 1)
5963 '(font-lock-fontified t face org-meta-line))
5964 (add-text-properties (match-end 0) (line-end-position)
5965 '(font-lock-fontified t face org-block))
5967 ((member dc3 '(" " ""))
5968 (org-remove-flyspell-overlays-in beg (match-end 0))
5969 (add-text-properties
5970 beg (match-end 0)
5971 '(font-lock-fontified t face font-lock-comment-face)))
5972 (t ;; just any other in-buffer setting, but not indented
5973 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5974 (remove-text-properties (match-beginning 0) (match-end 0)
5975 '(display t invisible t intangible t))
5976 (add-text-properties beg (match-end 0)
5977 '(font-lock-fontified t face org-meta-line))
5978 t))))))
5980 (defun org-fontify-drawers (limit)
5981 "Fontify drawers."
5982 (when (re-search-forward org-drawer-regexp limit t)
5983 (add-text-properties
5984 (match-beginning 0) (match-end 0)
5985 '(font-lock-fontified t face org-special-keyword))
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5989 (defun org-fontify-macros (limit)
5990 "Fontify macros."
5991 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
5992 (let ((begin (match-beginning 0))
5993 (opening-end (match-beginning 1)))
5994 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
5995 (match-string 1))
5996 (let ((end (match-end 1))
5997 (closing-start (match-beginning 1)))
5998 (add-text-properties
5999 begin end
6000 '(font-lock-multiline t font-lock-fontified t face org-macro))
6001 (org-remove-flyspell-overlays-in begin end)
6002 (when org-hide-macro-markers
6003 (add-text-properties begin opening-end '(invisible t))
6004 (add-text-properties closing-start end '(invisible t)))
6005 t)))))
6007 (defun org-activate-footnote-links (limit)
6008 "Add text properties for footnotes."
6009 (let ((fn (org-footnote-next-reference-or-definition limit)))
6010 (when fn
6011 (let* ((beg (nth 1 fn))
6012 (end (nth 2 fn))
6013 (label (car fn))
6014 (referencep (/= (line-beginning-position) beg)))
6015 (when (and referencep (nth 3 fn))
6016 (save-excursion
6017 (goto-char beg)
6018 (search-forward (or label "fn:"))
6019 (org-remove-flyspell-overlays-in beg (match-end 0))))
6020 (add-text-properties beg end
6021 (list 'mouse-face 'highlight
6022 'keymap org-mouse-map
6023 'help-echo
6024 (if referencep "Footnote reference"
6025 "Footnote definition")
6026 'font-lock-fontified t
6027 'font-lock-multiline t
6028 'face 'org-footnote))))))
6030 (defun org-activate-dates (limit)
6031 "Add text properties for dates."
6032 (when (and (re-search-forward org-tsr-regexp-both limit t)
6033 (not (equal (char-before (match-beginning 0)) 91)))
6034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6035 (add-text-properties (match-beginning 0) (match-end 0)
6036 (list 'mouse-face 'highlight
6037 'keymap org-mouse-map))
6038 (org-rear-nonsticky-at (match-end 0))
6039 (when org-display-custom-times
6040 ;; If it's a date range, activate custom time for second date.
6041 (when (match-end 3)
6042 (org-display-custom-time (match-beginning 3) (match-end 3)))
6043 (org-display-custom-time (match-beginning 1) (match-end 1)))
6046 (defvar-local org-target-link-regexp nil
6047 "Regular expression matching radio targets in plain text.")
6049 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6050 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6051 border border border))
6052 "Regular expression matching a link target.")
6054 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6055 "Regular expression matching a radio target.")
6057 (defconst org-any-target-regexp
6058 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6059 "Regular expression matching any target.")
6061 (defun org-activate-target-links (limit)
6062 "Add text properties for target matches."
6063 (when org-target-link-regexp
6064 (let ((case-fold-search t))
6065 (when (re-search-forward org-target-link-regexp limit t)
6066 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6067 (add-text-properties (match-beginning 1) (match-end 1)
6068 (list 'mouse-face 'highlight
6069 'keymap org-mouse-map
6070 'help-echo "Radio target link"
6071 'org-linked-text t))
6072 (org-rear-nonsticky-at (match-end 1))
6073 t))))
6075 (defun org-update-radio-target-regexp ()
6076 "Find all radio targets in this file and update the regular expression.
6077 Also refresh fontification if needed."
6078 (interactive)
6079 (let ((old-regexp org-target-link-regexp)
6080 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6081 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6082 (targets
6083 (org-with-wide-buffer
6084 (goto-char (point-min))
6085 (let (rtn)
6086 (while (re-search-forward org-radio-target-regexp nil t)
6087 ;; Make sure point is really within the object.
6088 (backward-char)
6089 (let ((obj (org-element-context)))
6090 (when (eq (org-element-type obj) 'radio-target)
6091 (cl-pushnew (org-element-property :value obj) rtn
6092 :test #'equal))))
6093 rtn))))
6094 (setq org-target-link-regexp
6095 (and targets
6096 (concat before-re
6097 (mapconcat
6098 (lambda (x)
6099 (replace-regexp-in-string
6100 " +" "\\s-+" (regexp-quote x) t t))
6101 targets
6102 "\\|")
6103 after-re)))
6104 (unless (equal old-regexp org-target-link-regexp)
6105 ;; Clean-up cache.
6106 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6107 ((not org-target-link-regexp) old-regexp)
6109 (concat before-re
6110 (mapconcat
6111 (lambda (re)
6112 (substring re (length before-re)
6113 (- (length after-re))))
6114 (list old-regexp org-target-link-regexp)
6115 "\\|")
6116 after-re)))))
6117 (org-with-wide-buffer
6118 (goto-char (point-min))
6119 (while (re-search-forward regexp nil t)
6120 (org-element-cache-refresh (match-beginning 1)))))
6121 ;; Re fontify buffer.
6122 (when (memq 'radio org-highlight-links)
6123 (org-restart-font-lock)))))
6125 (defvar org-latex-and-related-regexp nil
6126 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6128 (defun org-compute-latex-and-related-regexp ()
6129 "Compute regular expression for LaTeX, entities and sub/superscript.
6130 Result depends on variable `org-highlight-latex-and-related'."
6131 (setq-local
6132 org-latex-and-related-regexp
6133 (let* ((re-sub
6134 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6135 ((eq org-use-sub-superscripts '{})
6136 (list org-match-substring-with-braces-regexp))
6137 (org-use-sub-superscripts (list org-match-substring-regexp))))
6138 (re-latex
6139 (when (memq 'latex org-highlight-latex-and-related)
6140 (let ((matchers (plist-get org-format-latex-options :matchers)))
6141 (delq nil
6142 (mapcar (lambda (x)
6143 (and (member (car x) matchers) (nth 1 x)))
6144 org-latex-regexps)))))
6145 (re-entities
6146 (when (memq 'entities org-highlight-latex-and-related)
6147 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6148 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6150 (defun org-do-latex-and-related (limit)
6151 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6152 LIMIT bounds the search for syntax to highlight. Stop at first
6153 highlighted object, if any. Return t if some highlighting was
6154 done, nil otherwise."
6155 (when (org-string-nw-p org-latex-and-related-regexp)
6156 (catch 'found
6157 (while (re-search-forward org-latex-and-related-regexp limit t)
6158 (unless
6159 (cl-some
6160 (lambda (f)
6161 (memq f '(org-code org-verbatim underline org-special-keyword)))
6162 (save-excursion
6163 (goto-char (1+ (match-beginning 0)))
6164 (face-at-point nil t)))
6165 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6166 '(?_ ?^))
6168 0)))
6169 (font-lock-prepend-text-property
6170 (+ offset (match-beginning 0)) (match-end 0)
6171 'face 'org-latex-and-related)
6172 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6173 '(font-lock-multiline t)))
6174 (throw 'found t)))
6175 nil)))
6177 (defun org-restart-font-lock ()
6178 "Restart `font-lock-mode', to force refontification."
6179 (when (and (boundp 'font-lock-mode) font-lock-mode)
6180 (font-lock-mode -1)
6181 (font-lock-mode 1)))
6183 (defun org-activate-tags (limit)
6184 (when (re-search-forward
6185 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6186 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6187 (add-text-properties (match-beginning 1) (match-end 1)
6188 (list 'mouse-face 'highlight
6189 'keymap org-mouse-map))
6190 (org-rear-nonsticky-at (match-end 1))
6193 (defun org-outline-level ()
6194 "Compute the outline level of the heading at point.
6196 If this is called at a normal headline, the level is the number
6197 of stars. Use `org-reduced-level' to remove the effect of
6198 `org-odd-levels'. Unlike to `org-current-level', this function
6199 takes into consideration inlinetasks."
6200 (org-with-wide-buffer
6201 (end-of-line)
6202 (if (re-search-backward org-outline-regexp-bol nil t)
6203 (1- (- (match-end 0) (match-beginning 0)))
6204 0)))
6206 (defvar org-font-lock-keywords nil)
6208 (defsubst org-re-property (property &optional literal allow-null value)
6209 "Return a regexp matching a PROPERTY line.
6211 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6212 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6213 non-nil, match properties even without a value.
6215 Match group 3 is set to the value when it exists. If there is no
6216 value and ALLOW-NULL is non-nil, it is set to the empty string.
6218 With optional argument VALUE, match only property lines with
6219 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6220 unless LITERAL is non-nil."
6221 (concat
6222 "^\\(?4:[ \t]*\\)"
6223 (format "\\(?1::\\(?2:%s\\):\\)"
6224 (if literal property (regexp-quote property)))
6225 (cond (value
6226 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6227 (if literal value (regexp-quote value))))
6228 (allow-null
6229 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6231 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6233 (defconst org-property-re
6234 (org-re-property "\\S-+" 'literal t)
6235 "Regular expression matching a property line.
6236 There are four matching groups:
6237 1: :PROPKEY: including the leading and trailing colon,
6238 2: PROPKEY without the leading and trailing colon,
6239 3: PROPVAL without leading or trailing spaces,
6240 4: the indentation of the current line,
6241 5: trailing whitespace.")
6243 (defvar org-font-lock-hook nil
6244 "Functions to be called for special font lock stuff.")
6246 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6248 (defvar org-font-lock-set-keywords-hook nil
6249 "Functions that can manipulate `org-font-lock-extra-keywords'.
6250 This is called after `org-font-lock-extra-keywords' is defined, but before
6251 it is installed to be used by font lock. This can be useful if something
6252 needs to be inserted at a specific position in the font-lock sequence.")
6254 (defun org-font-lock-hook (limit)
6255 "Run `org-font-lock-hook' within LIMIT."
6256 (run-hook-with-args 'org-font-lock-hook limit))
6258 (defun org-set-font-lock-defaults ()
6259 "Set font lock defaults for the current buffer."
6260 (let* ((em org-fontify-emphasized-text)
6261 (lk org-highlight-links)
6262 (org-font-lock-extra-keywords
6263 (list
6264 ;; Call the hook
6265 '(org-font-lock-hook)
6266 ;; Headlines
6267 `(,(if org-fontify-whole-heading-line
6268 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6269 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6270 (1 (org-get-level-face 1))
6271 (2 (org-get-level-face 2))
6272 (3 (org-get-level-face 3)))
6273 ;; Table lines
6274 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6275 (1 'org-table t))
6276 ;; Table internals
6277 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6278 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6279 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6280 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6281 ;; Drawers
6282 '(org-fontify-drawers)
6283 ;; Properties
6284 (list org-property-re
6285 '(1 'org-special-keyword t)
6286 '(3 'org-property-value t))
6287 ;; Link related fontification.
6288 '(org-activate-links)
6289 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6290 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6291 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6292 (when (memq 'footnote lk) '(org-activate-footnote-links))
6293 ;; Targets.
6294 (list org-any-target-regexp '(0 'org-target t))
6295 ;; Diary sexps.
6296 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6297 ;; Macro
6298 '(org-fontify-macros)
6299 ;; TODO keyword
6300 (list (format org-heading-keyword-regexp-format
6301 org-todo-regexp)
6302 '(2 (org-get-todo-face 2) t))
6303 ;; DONE
6304 (if org-fontify-done-headline
6305 (list (format org-heading-keyword-regexp-format
6306 (concat
6307 "\\(?:"
6308 (mapconcat 'regexp-quote org-done-keywords "\\|")
6309 "\\)"))
6310 '(2 'org-headline-done t))
6311 nil)
6312 ;; Priorities
6313 '(org-font-lock-add-priority-faces)
6314 ;; Tags
6315 '(org-font-lock-add-tag-faces)
6316 ;; Tags groups
6317 (when (and org-group-tags org-tag-groups-alist)
6318 (list (concat org-outline-regexp-bol ".+\\(:"
6319 (regexp-opt (mapcar 'car org-tag-groups-alist))
6320 ":\\).*$")
6321 '(1 'org-tag-group prepend)))
6322 ;; Special keywords
6323 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6324 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6325 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6326 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6327 ;; Emphasis
6328 (when em '(org-do-emphasis-faces))
6329 ;; Checkboxes
6330 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6331 1 'org-checkbox prepend)
6332 (when (cdr (assq 'checkbox org-list-automatic-rules))
6333 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6334 (0 (org-get-checkbox-statistics-face) t)))
6335 ;; Description list items
6336 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6337 1 'org-list-dt prepend)
6338 ;; ARCHIVEd headings
6339 (list (concat
6340 org-outline-regexp-bol
6341 "\\(.*:" org-archive-tag ":.*\\)")
6342 '(1 'org-archived prepend))
6343 ;; Specials
6344 '(org-do-latex-and-related)
6345 '(org-fontify-entities)
6346 '(org-raise-scripts)
6347 ;; Code
6348 '(org-activate-code (1 'org-code t))
6349 ;; COMMENT
6350 (list (format
6351 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6352 org-todo-regexp
6353 org-comment-string)
6354 '(9 'org-special-keyword t))
6355 ;; Blocks and meta lines
6356 '(org-fontify-meta-lines-and-blocks))))
6357 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6358 (run-hooks 'org-font-lock-set-keywords-hook)
6359 ;; Now set the full font-lock-keywords
6360 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6361 (setq-local font-lock-defaults
6362 '(org-font-lock-keywords t nil nil backward-paragraph))
6363 (kill-local-variable 'font-lock-keywords)
6364 nil))
6366 (defun org-toggle-pretty-entities ()
6367 "Toggle the composition display of entities as UTF8 characters."
6368 (interactive)
6369 (setq-local org-pretty-entities (not org-pretty-entities))
6370 (org-restart-font-lock)
6371 (if org-pretty-entities
6372 (message "Entities are now displayed as UTF8 characters")
6373 (save-restriction
6374 (widen)
6375 (decompose-region (point-min) (point-max))
6376 (message "Entities are now displayed as plain text"))))
6378 (defvar-local org-custom-properties-overlays nil
6379 "List of overlays used for custom properties.")
6381 (defun org-toggle-custom-properties-visibility ()
6382 "Display or hide properties in `org-custom-properties'."
6383 (interactive)
6384 (if org-custom-properties-overlays
6385 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6386 (setq org-custom-properties-overlays nil))
6387 (when org-custom-properties
6388 (org-with-wide-buffer
6389 (goto-char (point-min))
6390 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6391 (while (re-search-forward regexp nil t)
6392 (let ((end (cdr (save-match-data (org-get-property-block)))))
6393 (when (and end (< (point) end))
6394 ;; Hide first custom property in current drawer.
6395 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6396 (overlay-put o 'invisible t)
6397 (overlay-put o 'org-custom-property t)
6398 (push o org-custom-properties-overlays))
6399 ;; Hide additional custom properties in the same drawer.
6400 (while (re-search-forward regexp end t)
6401 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6402 (overlay-put o 'invisible t)
6403 (overlay-put o 'org-custom-property t)
6404 (push o org-custom-properties-overlays)))))
6405 ;; Each entry is limited to a single property drawer.
6406 (outline-next-heading)))))))
6408 (defun org-fontify-entities (limit)
6409 "Find an entity to fontify."
6410 (let (ee)
6411 (when org-pretty-entities
6412 (catch 'match
6413 ;; "\_ "-family is left out on purpose. Only the first one,
6414 ;; i.e., "\_ ", could be fontified anyway, and it would be
6415 ;; confusing when adding a second white space character.
6416 (while (re-search-forward
6417 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6418 limit t)
6419 (when (and (not (org-at-comment-p))
6420 (setq ee (org-entity-get (match-string 1)))
6421 (= (length (nth 6 ee)) 1))
6422 (let* ((end (if (equal (match-string 2) "{}")
6423 (match-end 2)
6424 (match-end 1))))
6425 (add-text-properties
6426 (match-beginning 0) end
6427 (list 'font-lock-fontified t))
6428 (compose-region (match-beginning 0) end
6429 (nth 6 ee) nil)
6430 (backward-char 1)
6431 (throw 'match t))))
6432 nil))))
6434 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6435 "Fontify string S like in Org mode."
6436 (with-temp-buffer
6437 (insert s)
6438 (let ((org-odd-levels-only odd-levels))
6439 (org-mode)
6440 (org-font-lock-ensure)
6441 (buffer-string))))
6443 (defvar org-m nil)
6444 (defvar org-l nil)
6445 (defvar org-f nil)
6446 (defun org-get-level-face (n)
6447 "Get the right face for match N in font-lock matching of headlines."
6448 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6449 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6450 (if org-cycle-level-faces
6451 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6452 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6453 (cond
6454 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6455 ((eq n 2) org-f)
6456 (t (unless org-level-color-stars-only org-f))))
6458 (defun org-face-from-face-or-color (context inherit face-or-color)
6459 "Create a face list that inherits INHERIT, but sets the foreground color.
6460 When FACE-OR-COLOR is not a string, just return it."
6461 (if (stringp face-or-color)
6462 (list :inherit inherit
6463 (cdr (assoc context org-faces-easy-properties))
6464 face-or-color)
6465 face-or-color))
6467 (defun org-get-todo-face (kwd)
6468 "Get the right face for a TODO keyword KWD.
6469 If KWD is a number, get the corresponding match group."
6470 (when (numberp kwd) (setq kwd (match-string kwd)))
6471 (or (org-face-from-face-or-color
6472 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6473 (and (member kwd org-done-keywords) 'org-done)
6474 'org-todo))
6476 (defun org-get-priority-face (priority)
6477 "Get the right face for PRIORITY.
6478 PRIORITY is a character."
6479 (or (org-face-from-face-or-color
6480 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6481 'org-priority))
6483 (defun org-get-tag-face (tag)
6484 "Get the right face for TAG.
6485 If TAG is a number, get the corresponding match group."
6486 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6487 (or (org-face-from-face-or-color
6488 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6489 'org-tag)))
6491 (defun org-font-lock-add-priority-faces (limit)
6492 "Add the special priority faces."
6493 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6494 (add-text-properties
6495 (match-beginning 1) (match-end 1)
6496 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6497 'font-lock-fontified t))))
6499 (defun org-font-lock-add-tag-faces (limit)
6500 "Add the special tag faces."
6501 (when (and org-tag-faces org-tags-special-faces-re)
6502 (while (re-search-forward org-tags-special-faces-re limit t)
6503 (add-text-properties (match-beginning 1) (match-end 1)
6504 (list 'face (org-get-tag-face 1)
6505 'font-lock-fontified t))
6506 (backward-char 1))))
6508 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6509 "Remove fontification and activation overlays from links."
6510 (font-lock-default-unfontify-region beg end)
6511 (let* ((buffer-undo-list t)
6512 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6513 (inhibit-modification-hooks t)
6514 deactivate-mark buffer-file-name buffer-file-truename)
6515 (decompose-region beg end)
6516 (remove-text-properties beg end
6517 '(mouse-face t keymap t org-linked-text t
6518 invisible t intangible t
6519 org-emphasis t))
6520 (org-remove-font-lock-display-properties beg end)))
6522 (defconst org-script-display '(((raise -0.3) (height 0.7))
6523 ((raise 0.3) (height 0.7))
6524 ((raise -0.5))
6525 ((raise 0.5)))
6526 "Display properties for showing superscripts and subscripts.")
6528 (defun org-remove-font-lock-display-properties (beg end)
6529 "Remove specific display properties that have been added by font lock.
6530 The will remove the raise properties that are used to show superscripts
6531 and subscripts."
6532 (let (next prop)
6533 (while (< beg end)
6534 (setq next (next-single-property-change beg 'display nil end)
6535 prop (get-text-property beg 'display))
6536 (when (member prop org-script-display)
6537 (put-text-property beg next 'display nil))
6538 (setq beg next))))
6540 (defun org-raise-scripts (limit)
6541 "Add raise properties to sub/superscripts."
6542 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6543 (re-search-forward
6544 (if (eq org-use-sub-superscripts t)
6545 org-match-substring-regexp
6546 org-match-substring-with-braces-regexp)
6547 limit t))
6548 (let* ((pos (point)) table-p comment-p
6549 (mpos (match-beginning 3))
6550 (emph-p (get-text-property mpos 'org-emphasis))
6551 (link-p (get-text-property mpos 'mouse-face))
6552 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6553 (goto-char (point-at-bol))
6554 (setq table-p (looking-at-p org-table-dataline-regexp)
6555 comment-p (looking-at-p "^[ \t]*#[ +]"))
6556 (goto-char pos)
6557 ;; Handle a_b^c
6558 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6559 (unless (or comment-p emph-p link-p keyw-p)
6560 (put-text-property (match-beginning 3) (match-end 0)
6561 'display
6562 (if (equal (char-after (match-beginning 2)) ?^)
6563 (nth (if table-p 3 1) org-script-display)
6564 (nth (if table-p 2 0) org-script-display)))
6565 (add-text-properties (match-beginning 2) (match-end 2)
6566 (list 'invisible t))
6567 (when (and (eq (char-after (match-beginning 3)) ?{)
6568 (eq (char-before (match-end 3)) ?}))
6569 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6570 (list 'invisible t))
6571 (add-text-properties (1- (match-end 3)) (match-end 3)
6572 (list 'invisible t))))
6573 t)))
6575 (defun org-remove-empty-overlays-at (pos)
6576 "Remove outline overlays that do not contain non-white stuff."
6577 (dolist (o (overlays-at pos))
6578 (and (eq 'outline (overlay-get o 'invisible))
6579 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6580 (overlay-end o))))
6581 (delete-overlay o))))
6583 (defun org-show-empty-lines-in-parent ()
6584 "Move to the parent and re-show empty lines before visible headlines."
6585 (save-excursion
6586 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6587 (org-cycle-show-empty-lines context))))
6589 (defun org-files-list ()
6590 "Return `org-agenda-files' list, plus all open Org files.
6591 This is useful for operations that need to scan all of a user's
6592 open and agenda-wise Org files."
6593 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6594 (dolist (buf (buffer-list))
6595 (with-current-buffer buf
6596 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6597 (cl-pushnew (expand-file-name (buffer-file-name)) files
6598 :test #'equal))))
6599 files))
6601 (defsubst org-entry-beginning-position ()
6602 "Return the beginning position of the current entry."
6603 (save-excursion (org-back-to-heading t) (point)))
6605 (defsubst org-entry-end-position ()
6606 "Return the end position of the current entry."
6607 (save-excursion (outline-next-heading) (point)))
6609 (defun org-subtree-end-visible-p ()
6610 "Is the end of the current subtree visible?"
6611 (pos-visible-in-window-p
6612 (save-excursion (org-end-of-subtree t) (point))))
6614 (defun org-first-headline-recenter ()
6615 "Move cursor to the first headline and recenter the headline."
6616 (let ((window (get-buffer-window)))
6617 (when window
6618 (goto-char (point-min))
6619 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6620 (set-window-start window (line-beginning-position))))))
6623 ;;; Visibility (headlines, blocks, drawers)
6625 ;;;; Headlines visibility
6627 (defun org-show-entry ()
6628 "Show the body directly following this heading.
6629 Show the heading too, if it is currently invisible."
6630 (interactive)
6631 (save-excursion
6632 (ignore-errors
6633 (org-back-to-heading t)
6634 (org-flag-region
6635 (line-end-position 0)
6636 (save-excursion
6637 (if (re-search-forward
6638 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6639 (match-beginning 1)
6640 (point-max)))
6642 'outline))))
6644 (defun org-show-children (&optional level)
6645 "Show all direct subheadings of this heading.
6646 Prefix arg LEVEL is how many levels below the current level
6647 should be shown. Default is enough to cause the following
6648 heading to appear."
6649 (interactive "p")
6650 (save-excursion
6651 (org-back-to-heading t)
6652 (let* ((current-level (funcall outline-level))
6653 (max-level (org-get-valid-level
6654 current-level
6655 (if level (prefix-numeric-value level) 1)))
6656 (end (save-excursion (org-end-of-subtree t t)))
6657 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6658 (past-first-child nil)
6659 ;; Make sure to skip inlinetasks.
6660 (re (format regexp-fmt
6661 current-level
6662 (cond
6663 ((not (featurep 'org-inlinetask)) "")
6664 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6666 (t (1- org-inlinetask-min-level))))))
6667 ;; Display parent heading.
6668 (org-flag-heading nil)
6669 (forward-line)
6670 ;; Display children. First child may be deeper than expected
6671 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6672 ;; MAX-LEVEL accordingly.
6673 (while (re-search-forward re end t)
6674 (unless past-first-child
6675 (setq re (format regexp-fmt
6676 current-level
6677 (max (funcall outline-level) max-level)))
6678 (setq past-first-child t))
6679 (org-flag-heading nil)))))
6681 (defun org-show-subtree ()
6682 "Show everything after this heading at deeper levels."
6683 (interactive)
6684 (org-flag-region
6685 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6687 ;;;; Blocks visibility
6689 (defun org-hide-block-toggle-maybe ()
6690 "Toggle visibility of block at point.
6691 Unlike to `org-hide-block-toggle', this function does not throw
6692 an error. Return a non-nil value when toggling is successful."
6693 (interactive)
6694 (ignore-errors (org-hide-block-toggle)))
6696 (defun org-hide-block-toggle (&optional force)
6697 "Toggle the visibility of the current block.
6698 When optional argument FORCE is `off', make block visible. If it
6699 is non-nil, hide it unconditionally. Throw an error when not at
6700 a block. Return a non-nil value when toggling is successful."
6701 (interactive)
6702 (let ((element (org-element-at-point)))
6703 (unless (memq (org-element-type element)
6704 '(center-block comment-block dynamic-block example-block
6705 export-block quote-block special-block
6706 src-block verse-block))
6707 (user-error "Not at a block"))
6708 (let* ((post (org-element-property :post-affiliated element))
6709 (start (save-excursion
6710 (goto-char post)
6711 (line-end-position)))
6712 (end (save-excursion
6713 (goto-char (org-element-property :end element))
6714 (skip-chars-backward " \t\n")
6715 (line-end-position))))
6716 ;; Do nothing when not before or at the block opening line or at
6717 ;; the block closing line.
6718 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6719 (cond ((eq force 'off)
6720 (org-flag-region start end nil 'org-hide-block))
6721 (force
6722 (org-flag-region start end t 'org-hide-block))
6723 ((eq (get-char-property start 'invisible) 'org-hide-block)
6724 (org-flag-region start end nil 'org-hide-block))
6726 (org-flag-region start end t 'org-hide-block)))
6727 ;; When the block is hidden away, make sure point is left in
6728 ;; a visible part of the buffer.
6729 (when (invisible-p (max (1- (point)) (point-min)))
6730 (goto-char post))
6731 ;; Signal success.
6732 t))))
6734 (defun org-hide-block-toggle-all ()
6735 "Toggle the visibility of all blocks in the current buffer."
6736 (org-block-map 'org-hide-block-toggle))
6738 (defun org-hide-block-all ()
6739 "Fold all blocks in the current buffer."
6740 (interactive)
6741 (org-show-all '(blocks))
6742 (org-block-map 'org-hide-block-toggle-maybe))
6744 ;;;; Drawers visibility
6746 (defun org-cycle-hide-drawers (state &optional exceptions)
6747 "Re-hide all drawers after a visibility state change.
6748 STATE should be one of the symbols listed in the docstring of
6749 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6750 a list of strings specifying which drawers should not be hidden."
6751 (when (and (derived-mode-p 'org-mode)
6752 (not (memq state '(overview folded contents))))
6753 (save-excursion
6754 (let* ((globalp (eq state 'all))
6755 (beg (if globalp (point-min) (point)))
6756 (end (if globalp (point-max)
6757 (if (eq state 'children)
6758 (save-excursion (outline-next-heading) (point))
6759 (org-end-of-subtree t)))))
6760 (goto-char beg)
6761 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6762 (unless (member-ignore-case (match-string 1) exceptions)
6763 (let ((drawer (org-element-at-point)))
6764 (when (memq (org-element-type drawer) '(drawer property-drawer))
6765 (org-flag-drawer t drawer)
6766 ;; Make sure to skip drawer entirely or we might flag
6767 ;; it another time when matching its ending line with
6768 ;; `org-drawer-regexp'.
6769 (goto-char (org-element-property :end drawer))))))))))
6771 (defun org-flag-drawer (flag &optional element)
6772 "When FLAG is non-nil, hide the drawer we are at.
6773 Otherwise make it visible. When optional argument ELEMENT is
6774 a parsed drawer, as returned by `org-element-at-point', hide or
6775 show that drawer instead."
6776 (let ((drawer (or element
6777 (and (save-excursion
6778 (beginning-of-line)
6779 (looking-at-p org-drawer-regexp))
6780 (org-element-at-point)))))
6781 (when (memq (org-element-type drawer) '(drawer property-drawer))
6782 (let ((post (org-element-property :post-affiliated drawer)))
6783 (org-flag-region
6784 (save-excursion (goto-char post) (line-end-position))
6785 (save-excursion (goto-char (org-element-property :end drawer))
6786 (skip-chars-backward " \t\n")
6787 (line-end-position))
6788 flag 'org-hide-drawer)
6789 ;; When the drawer is hidden away, make sure point lies in
6790 ;; a visible part of the buffer.
6791 (when (invisible-p (max (1- (point)) (point-min)))
6792 (goto-char post))))))
6794 ;;;; Visibility cycling
6796 (defvar-local org-cycle-global-status nil)
6797 (put 'org-cycle-global-status 'org-state t)
6798 (defvar-local org-cycle-subtree-status nil)
6799 (put 'org-cycle-subtree-status 'org-state t)
6801 (defun org-show-all (&optional types)
6802 "Show all contents in the visible part of the buffer.
6803 By default, the function expands headings, blocks and drawers.
6804 When optional argument TYPE is a list of symbols among `blocks',
6805 `drawers' and `headings', to only expand one specific type."
6806 (dolist (type (or types '(blocks drawers headings)))
6807 (org-flag-region (point-min) (point-max) nil
6808 (pcase type
6809 (`blocks 'org-hide-block)
6810 (`drawers 'org-hide-drawer)
6811 (`headings 'outline)
6812 (_ (error "Invalid type: %S" type))))))
6814 ;;;###autoload
6815 (defun org-cycle (&optional arg)
6816 "TAB-action and visibility cycling for Org mode.
6818 This is the command invoked in Org mode by the `TAB' key. Its main
6819 purpose is outline visibility cycling, but it also invokes other actions
6820 in special contexts.
6822 When this function is called with a `\\[universal-argument]' prefix, rotate \
6823 the entire
6824 buffer through 3 states (global cycling)
6825 1. OVERVIEW: Show only top-level headlines.
6826 2. CONTENTS: Show all headlines of all levels, but no body text.
6827 3. SHOW ALL: Show everything.
6829 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6830 switch to the startup visibility,
6831 determined by the variable `org-startup-folded', and by any VISIBILITY
6832 properties in the buffer.
6834 With a `\\[universal-argument] \\[universal-argument] \
6835 \\[universal-argument]' prefix argument, show the entire buffer, including
6836 any drawers.
6838 When inside a table, re-align the table and move to the next field.
6840 When point is at the beginning of a headline, rotate the subtree started
6841 by this line through 3 different states (local cycling)
6842 1. FOLDED: Only the main headline is shown.
6843 2. CHILDREN: The main headline and the direct children are shown.
6844 From this state, you can move to one of the children
6845 and zoom in further.
6846 3. SUBTREE: Show the entire subtree, including body text.
6847 If there is no subtree, switch directly from CHILDREN to FOLDED.
6849 When point is at the beginning of an empty headline and the variable
6850 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6851 of the headline by demoting and promoting it to likely levels. This
6852 speeds up creation document structure by pressing `TAB' once or several
6853 times right after creating a new headline.
6855 When there is a numeric prefix, go up to a heading with level ARG, do
6856 a `show-subtree' and return to the previous cursor position. If ARG
6857 is negative, go up that many levels.
6859 When point is not at the beginning of a headline, execute the global
6860 binding for `TAB', which is re-indenting the line. See the option
6861 `org-cycle-emulate-tab' for details.
6863 As a special case, if point is at the beginning of the buffer and there is
6864 no headline in line 1, this function will act as if called with prefix arg
6865 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6866 prefix arg, but only
6867 if the variable `org-cycle-global-at-bob' is t."
6868 (interactive "P")
6869 (org-load-modules-maybe)
6870 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6871 (and org-cycle-level-after-item/entry-creation
6872 (or (org-cycle-level)
6873 (org-cycle-item-indentation))))
6874 (let* ((limit-level
6875 (or org-cycle-max-level
6876 (and (boundp 'org-inlinetask-min-level)
6877 org-inlinetask-min-level
6878 (1- org-inlinetask-min-level))))
6879 (nstars (and limit-level
6880 (if org-odd-levels-only
6881 (and limit-level (1- (* limit-level 2)))
6882 limit-level)))
6883 (org-outline-regexp
6884 (if (not (derived-mode-p 'org-mode))
6885 outline-regexp
6886 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6887 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6888 (not (looking-at org-outline-regexp))))
6889 (org-cycle-hook
6890 (if bob-special
6891 (delq 'org-optimize-window-after-visibility-change
6892 (copy-sequence org-cycle-hook))
6893 org-cycle-hook))
6894 (pos (point)))
6896 (cond
6898 ((equal arg '(16))
6899 (setq last-command 'dummy)
6900 (org-set-startup-visibility)
6901 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6903 ((equal arg '(64))
6904 (org-show-all)
6905 (org-unlogged-message "Entire buffer visible, including drawers"))
6907 ((equal arg '(4)) (org-cycle-internal-global))
6909 ;; Try hiding block at point.
6910 ((org-hide-block-toggle-maybe))
6912 ;; Try cdlatex TAB completion
6913 ((org-try-cdlatex-tab))
6915 ;; Table: enter it or move to the next field.
6916 ((org-at-table-p 'any)
6917 (if (org-at-table.el-p)
6918 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6919 Use `\\[org-edit-special]' to edit table.el tables"))
6920 (if arg (org-table-edit-field t)
6921 (org-table-justify-field-maybe)
6922 (call-interactively 'org-table-next-field))))
6924 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6926 ;; Global cycling: delegate to `org-cycle-internal-global'.
6927 (bob-special (org-cycle-internal-global))
6929 ;; Drawers: delegate to `org-flag-drawer'.
6930 ((save-excursion
6931 (beginning-of-line 1)
6932 (looking-at org-drawer-regexp))
6933 (org-flag-drawer ; toggle block visibility
6934 (not (get-char-property (match-end 0) 'invisible))))
6936 ;; Show-subtree, ARG levels up from here.
6937 ((integerp arg)
6938 (save-excursion
6939 (org-back-to-heading)
6940 (outline-up-heading (if (< arg 0) (- arg)
6941 (- (funcall outline-level) arg)))
6942 (org-show-subtree)))
6944 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6945 ((and (featurep 'org-inlinetask)
6946 (org-inlinetask-at-task-p)
6947 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6948 (org-inlinetask-toggle-visibility))
6950 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6951 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6952 (save-excursion (move-beginning-of-line 1)
6953 (looking-at org-outline-regexp)))
6954 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6955 (org-cycle-internal-local))
6957 ;; From there: TAB emulation and template completion.
6958 (buffer-read-only (org-back-to-heading))
6960 ((run-hook-with-args-until-success
6961 'org-tab-after-check-for-cycling-hook))
6963 ((run-hook-with-args-until-success
6964 'org-tab-before-tab-emulation-hook))
6966 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6967 (or (not (bolp))
6968 (not (looking-at org-outline-regexp))))
6969 (call-interactively (global-key-binding "\t")))
6971 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6972 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6973 (or (and (eq org-cycle-emulate-tab 'white)
6974 (= (match-end 0) (point-at-eol)))
6975 (and (eq org-cycle-emulate-tab 'whitestart)
6976 (>= (match-end 0) pos))))
6978 (eq org-cycle-emulate-tab t))
6979 (call-interactively (global-key-binding "\t")))
6981 (t (save-excursion
6982 (org-back-to-heading)
6983 (org-cycle)))))))
6985 (defun org-cycle-internal-global ()
6986 "Do the global cycling action."
6987 ;; Hack to avoid display of messages for .org attachments in Gnus
6988 (let ((ga (string-match "\\*fontification" (buffer-name))))
6989 (cond
6990 ((and (eq last-command this-command)
6991 (eq org-cycle-global-status 'overview))
6992 ;; We just created the overview - now do table of contents
6993 ;; This can be slow in very large buffers, so indicate action
6994 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6995 (unless ga (org-unlogged-message "CONTENTS..."))
6996 (org-content)
6997 (unless ga (org-unlogged-message "CONTENTS...done"))
6998 (setq org-cycle-global-status 'contents)
6999 (run-hook-with-args 'org-cycle-hook 'contents))
7001 ((and (eq last-command this-command)
7002 (eq org-cycle-global-status 'contents))
7003 ;; We just showed the table of contents - now show everything
7004 (run-hook-with-args 'org-pre-cycle-hook 'all)
7005 (org-show-all '(headings blocks))
7006 (unless ga (org-unlogged-message "SHOW ALL"))
7007 (setq org-cycle-global-status 'all)
7008 (run-hook-with-args 'org-cycle-hook 'all))
7011 ;; Default action: go to overview
7012 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7013 (org-overview)
7014 (unless ga (org-unlogged-message "OVERVIEW"))
7015 (setq org-cycle-global-status 'overview)
7016 (run-hook-with-args 'org-cycle-hook 'overview)))))
7018 (defvar org-called-with-limited-levels nil
7019 "Non-nil when `org-with-limited-levels' is currently active.")
7021 (defun org-cycle-internal-local ()
7022 "Do the local cycling action."
7023 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7024 ;; First, determine end of headline (EOH), end of subtree or item
7025 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7026 (save-excursion
7027 (if (org-at-item-p)
7028 (progn
7029 (beginning-of-line)
7030 (setq struct (org-list-struct))
7031 (setq eoh (point-at-eol))
7032 (setq eos (org-list-get-item-end-before-blank (point) struct))
7033 (setq has-children (org-list-has-child-p (point) struct)))
7034 (org-back-to-heading)
7035 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7036 (setq eos (save-excursion (org-end-of-subtree t t)
7037 (when (bolp) (backward-char)) (point)))
7038 (setq has-children
7039 (or (save-excursion
7040 (let ((level (funcall outline-level)))
7041 (outline-next-heading)
7042 (and (org-at-heading-p t)
7043 (> (funcall outline-level) level))))
7044 (save-excursion
7045 (org-list-search-forward (org-item-beginning-re) eos t)))))
7046 ;; Determine end invisible part of buffer (EOL)
7047 (beginning-of-line 2)
7048 (while (and (not (eobp)) ;This is like `next-line'.
7049 (get-char-property (1- (point)) 'invisible))
7050 (goto-char (next-single-char-property-change (point) 'invisible))
7051 (and (eolp) (beginning-of-line 2)))
7052 (setq eol (point)))
7053 ;; Find out what to do next and set `this-command'
7054 (cond
7055 ((= eos eoh)
7056 ;; Nothing is hidden behind this heading
7057 (unless (org-before-first-heading-p)
7058 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7059 (org-unlogged-message "EMPTY ENTRY")
7060 (setq org-cycle-subtree-status nil)
7061 (save-excursion
7062 (goto-char eos)
7063 (outline-next-heading)
7064 (when (org-invisible-p) (org-flag-heading nil))))
7065 ((and (or (>= eol eos)
7066 (not (string-match "\\S-" (buffer-substring eol eos))))
7067 (or has-children
7068 (not (setq children-skipped
7069 org-cycle-skip-children-state-if-no-children))))
7070 ;; Entire subtree is hidden in one line: children view
7071 (unless (org-before-first-heading-p)
7072 (run-hook-with-args 'org-pre-cycle-hook 'children))
7073 (if (org-at-item-p)
7074 (org-list-set-item-visibility (point-at-bol) struct 'children)
7075 (org-show-entry)
7076 (org-with-limited-levels (org-show-children))
7077 (org-show-set-visibility 'canonical)
7078 ;; Fold every list in subtree to top-level items.
7079 (when (eq org-cycle-include-plain-lists 'integrate)
7080 (save-excursion
7081 (org-back-to-heading)
7082 (while (org-list-search-forward (org-item-beginning-re) eos t)
7083 (beginning-of-line 1)
7084 (let* ((struct (org-list-struct))
7085 (prevs (org-list-prevs-alist struct))
7086 (end (org-list-get-bottom-point struct)))
7087 (dolist (e (org-list-get-all-items (point) struct prevs))
7088 (org-list-set-item-visibility e struct 'folded))
7089 (goto-char (if (< end eos) end eos)))))))
7090 (org-unlogged-message "CHILDREN")
7091 (save-excursion
7092 (goto-char eos)
7093 (outline-next-heading)
7094 (when (org-invisible-p) (org-flag-heading nil)))
7095 (setq org-cycle-subtree-status 'children)
7096 (unless (org-before-first-heading-p)
7097 (run-hook-with-args 'org-cycle-hook 'children)))
7098 ((or children-skipped
7099 (and (eq last-command this-command)
7100 (eq org-cycle-subtree-status 'children)))
7101 ;; We just showed the children, or no children are there,
7102 ;; now show everything.
7103 (unless (org-before-first-heading-p)
7104 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7105 (org-flag-region eoh eos nil 'outline)
7106 (org-unlogged-message
7107 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7108 (setq org-cycle-subtree-status 'subtree)
7109 (unless (org-before-first-heading-p)
7110 (run-hook-with-args 'org-cycle-hook 'subtree)))
7112 ;; Default action: hide the subtree.
7113 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7114 (org-flag-region eoh eos t 'outline)
7115 (org-unlogged-message "FOLDED")
7116 (setq org-cycle-subtree-status 'folded)
7117 (unless (org-before-first-heading-p)
7118 (run-hook-with-args 'org-cycle-hook 'folded))))))
7120 ;;;###autoload
7121 (defun org-global-cycle (&optional arg)
7122 "Cycle the global visibility. For details see `org-cycle'.
7123 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7124 With a numeric prefix, show all headlines up to that level."
7125 (interactive "P")
7126 (let ((org-cycle-include-plain-lists
7127 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7128 (cond
7129 ((integerp arg)
7130 (org-show-all '(headings blocks))
7131 (outline-hide-sublevels arg)
7132 (setq org-cycle-global-status 'contents))
7133 ((equal arg '(4))
7134 (org-set-startup-visibility)
7135 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7137 (org-cycle '(4))))))
7139 (defun org-set-startup-visibility ()
7140 "Set the visibility required by startup options and properties."
7141 (cond
7142 ((eq org-startup-folded t)
7143 (org-overview))
7144 ((eq org-startup-folded 'content)
7145 (org-content))
7146 ((or (eq org-startup-folded 'showeverything)
7147 (eq org-startup-folded nil))
7148 (org-show-all)))
7149 (unless (eq org-startup-folded 'showeverything)
7150 (when org-hide-block-startup (org-hide-block-all))
7151 (org-set-visibility-according-to-property)
7152 (org-cycle-hide-archived-subtrees 'all)
7153 (org-cycle-hide-drawers 'all)
7154 (org-cycle-show-empty-lines t)))
7156 (defun org-set-visibility-according-to-property ()
7157 "Switch subtree visibilities according to :VISIBILITY: property."
7158 (interactive)
7159 (org-with-wide-buffer
7160 (goto-char (point-min))
7161 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7162 (if (not (org-at-property-p)) (outline-next-heading)
7163 (let ((state (match-string 3)))
7164 (save-excursion
7165 (org-back-to-heading t)
7166 (outline-hide-subtree)
7167 (org-reveal)
7168 (cond
7169 ((equal state "folded")
7170 (outline-hide-subtree))
7171 ((equal state "children")
7172 (org-show-hidden-entry)
7173 (org-show-children))
7174 ((equal state "content")
7175 (save-excursion
7176 (save-restriction
7177 (org-narrow-to-subtree)
7178 (org-content))))
7179 ((member state '("all" "showall"))
7180 (outline-show-subtree)))))))))
7182 (defun org-overview ()
7183 "Switch to overview mode, showing only top-level headlines.
7184 This shows all headlines with a level equal or greater than the level
7185 of the first headline in the buffer. This is important, because if the
7186 first headline is not level one, then (hide-sublevels 1) gives confusing
7187 results."
7188 (interactive)
7189 (save-excursion
7190 (let ((level
7191 (save-excursion
7192 (goto-char (point-min))
7193 (when (re-search-forward org-outline-regexp-bol nil t)
7194 (goto-char (match-beginning 0))
7195 (funcall outline-level)))))
7196 (and level (outline-hide-sublevels level)))))
7198 (defun org-content (&optional arg)
7199 "Show all headlines in the buffer, like a table of contents.
7200 With numerical argument N, show content up to level N."
7201 (interactive "P")
7202 (org-overview)
7203 (save-excursion
7204 ;; Visit all headings and show their offspring
7205 (and (integerp arg) (org-overview))
7206 (goto-char (point-max))
7207 (catch 'exit
7208 (while (and (progn (condition-case nil
7209 (outline-previous-visible-heading 1)
7210 (error (goto-char (point-min))))
7212 (looking-at org-outline-regexp))
7213 (if (integerp arg)
7214 (org-show-children (1- arg))
7215 (outline-show-branches))
7216 (when (bobp) (throw 'exit nil))))))
7218 (defun org-optimize-window-after-visibility-change (state)
7219 "Adjust the window after a change in outline visibility.
7220 This function is the default value of the hook `org-cycle-hook'."
7221 (when (get-buffer-window (current-buffer))
7222 (cond
7223 ((eq state 'content) nil)
7224 ((eq state 'all) nil)
7225 ((eq state 'folded) nil)
7226 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7227 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7229 (defun org-clean-visibility-after-subtree-move ()
7230 "Fix visibility issues after moving a subtree."
7231 ;; First, find a reasonable region to look at:
7232 ;; Start two siblings above, end three below
7233 (let* ((beg (save-excursion
7234 (and (org-get-last-sibling)
7235 (org-get-last-sibling))
7236 (point)))
7237 (end (save-excursion
7238 (and (org-get-next-sibling)
7239 (org-get-next-sibling)
7240 (org-get-next-sibling))
7241 (if (org-at-heading-p)
7242 (point-at-eol)
7243 (point))))
7244 (level (looking-at "\\*+"))
7245 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7246 (save-excursion
7247 (save-restriction
7248 (narrow-to-region beg end)
7249 (when re
7250 ;; Properly fold already folded siblings
7251 (goto-char (point-min))
7252 (while (re-search-forward re nil t)
7253 (when (and (not (org-invisible-p))
7254 (org-invisible-p (line-end-position)))
7255 (outline-hide-entry))))
7256 (org-cycle-hide-drawers 'all)
7257 (org-cycle-show-empty-lines 'overview)))))
7259 (defun org-cycle-show-empty-lines (state)
7260 "Show empty lines above all visible headlines.
7261 The region to be covered depends on STATE when called through
7262 `org-cycle-hook'. Lisp program can use t for STATE to get the
7263 entire buffer covered. Note that an empty line is only shown if there
7264 are at least `org-cycle-separator-lines' empty lines before the headline."
7265 (when (/= org-cycle-separator-lines 0)
7266 (save-excursion
7267 (let* ((n (abs org-cycle-separator-lines))
7268 (re (cond
7269 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7270 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7271 (t (let ((ns (number-to-string (- n 2))))
7272 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7273 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7274 beg end)
7275 (cond
7276 ((memq state '(overview contents t))
7277 (setq beg (point-min) end (point-max)))
7278 ((memq state '(children folded))
7279 (setq beg (point)
7280 end (progn (org-end-of-subtree t t)
7281 (line-beginning-position 2)))))
7282 (when beg
7283 (goto-char beg)
7284 (while (re-search-forward re end t)
7285 (unless (get-char-property (match-end 1) 'invisible)
7286 (let ((e (match-end 1))
7287 (b (if (>= org-cycle-separator-lines 0)
7288 (match-beginning 1)
7289 (save-excursion
7290 (goto-char (match-beginning 0))
7291 (skip-chars-backward " \t\n")
7292 (line-end-position)))))
7293 (org-flag-region b e nil 'outline))))))))
7294 ;; Never hide empty lines at the end of the file.
7295 (save-excursion
7296 (goto-char (point-max))
7297 (outline-previous-heading)
7298 (outline-end-of-heading)
7299 (when (and (looking-at "[ \t\n]+")
7300 (= (match-end 0) (point-max)))
7301 (org-flag-region (point) (match-end 0) nil 'outline))))
7303 ;;;; Reveal point location
7305 (defun org-show-context (&optional key)
7306 "Make sure point and context are visible.
7307 Optional argument KEY, when non-nil, is a symbol. See
7308 `org-show-context-detail' for allowed values and how much is to
7309 be shown."
7310 (org-show-set-visibility
7311 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7312 ((cdr (assq key org-show-context-detail)))
7313 (t (cdr (assq 'default org-show-context-detail))))))
7315 (defun org-show-set-visibility (detail)
7316 "Set visibility around point according to DETAIL.
7317 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7318 `tree', `canonical' or t. See `org-show-context-detail' for more
7319 information."
7320 ;; Show current heading and possibly its entry, following headline
7321 ;; or all children.
7322 (if (and (org-at-heading-p) (not (eq detail 'local)))
7323 (org-flag-heading nil)
7324 (org-show-entry)
7325 ;; If point is hidden within a drawer or a block, make sure to
7326 ;; expose it.
7327 (dolist (o (overlays-at (point)))
7328 (when (memq (overlay-get o 'invisible)
7329 '(org-hide-block org-hide-drawer outline))
7330 (delete-overlay o)))
7331 (unless (org-before-first-heading-p)
7332 (org-with-limited-levels
7333 (cl-case detail
7334 ((tree canonical t) (org-show-children))
7335 ((nil minimal ancestors))
7336 (t (save-excursion
7337 (outline-next-heading)
7338 (org-flag-heading nil)))))))
7339 ;; Show all siblings.
7340 (when (eq detail 'lineage) (org-show-siblings))
7341 ;; Show ancestors, possibly with their children.
7342 (when (memq detail '(ancestors lineage tree canonical t))
7343 (save-excursion
7344 (while (org-up-heading-safe)
7345 (org-flag-heading nil)
7346 (when (memq detail '(canonical t)) (org-show-entry))
7347 (when (memq detail '(tree canonical t)) (org-show-children))))))
7349 (defvar org-reveal-start-hook nil
7350 "Hook run before revealing a location.")
7352 (defun org-reveal (&optional siblings)
7353 "Show current entry, hierarchy above it, and the following headline.
7355 This can be used to show a consistent set of context around
7356 locations exposed with `org-show-context'.
7358 With optional argument SIBLINGS, on each level of the hierarchy all
7359 siblings are shown. This repairs the tree structure to what it would
7360 look like when opened with hierarchical calls to `org-cycle'.
7362 With a \\[universal-argument] \\[universal-argument] prefix, \
7363 go to the parent and show the entire tree."
7364 (interactive "P")
7365 (run-hooks 'org-reveal-start-hook)
7366 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7367 ((equal siblings '(16))
7368 (save-excursion
7369 (when (org-up-heading-safe)
7370 (org-show-subtree)
7371 (run-hook-with-args 'org-cycle-hook 'subtree))))
7372 (t (org-show-set-visibility 'lineage))))
7375 ;;; Indirect buffer display of subtrees
7377 (defvar org-indirect-dedicated-frame nil
7378 "This is the frame being used for indirect tree display.")
7379 (defvar org-last-indirect-buffer nil)
7381 (defun org-tree-to-indirect-buffer (&optional arg)
7382 "Create indirect buffer and narrow it to current subtree.
7384 With a numerical prefix ARG, go up to this level and then take that tree.
7385 If ARG is negative, go up that many levels.
7387 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7388 indirect buffer previously made with this command, to avoid proliferation of
7389 indirect buffers. However, when you call the command with a \
7390 `\\[universal-argument]' prefix, or
7391 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7392 so that you can work with several indirect buffers at the same time. If
7393 `org-indirect-buffer-display' is `dedicated-frame', the \
7394 `\\[universal-argument]' prefix also
7395 requests that a new frame be made for the new buffer, so that the dedicated
7396 frame is not changed."
7397 (interactive "P")
7398 (let ((cbuf (current-buffer))
7399 (cwin (selected-window))
7400 (pos (point))
7401 beg end level heading ibuf)
7402 (save-excursion
7403 (org-back-to-heading t)
7404 (when (numberp arg)
7405 (setq level (org-outline-level))
7406 (when (< arg 0) (setq arg (+ level arg)))
7407 (while (> (setq level (org-outline-level)) arg)
7408 (org-up-heading-safe)))
7409 (setq beg (point)
7410 heading (org-get-heading 'no-tags))
7411 (org-end-of-subtree t t)
7412 (when (org-at-heading-p) (backward-char 1))
7413 (setq end (point)))
7414 (when (and (buffer-live-p org-last-indirect-buffer)
7415 (not (eq org-indirect-buffer-display 'new-frame))
7416 (not arg))
7417 (kill-buffer org-last-indirect-buffer))
7418 (setq ibuf (org-get-indirect-buffer cbuf heading)
7419 org-last-indirect-buffer ibuf)
7420 (cond
7421 ((or (eq org-indirect-buffer-display 'new-frame)
7422 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7423 (select-frame (make-frame))
7424 (delete-other-windows)
7425 (pop-to-buffer-same-window ibuf)
7426 (org-set-frame-title heading))
7427 ((eq org-indirect-buffer-display 'dedicated-frame)
7428 (raise-frame
7429 (select-frame (or (and org-indirect-dedicated-frame
7430 (frame-live-p org-indirect-dedicated-frame)
7431 org-indirect-dedicated-frame)
7432 (setq org-indirect-dedicated-frame (make-frame)))))
7433 (delete-other-windows)
7434 (pop-to-buffer-same-window ibuf)
7435 (org-set-frame-title (concat "Indirect: " heading)))
7436 ((eq org-indirect-buffer-display 'current-window)
7437 (pop-to-buffer-same-window ibuf))
7438 ((eq org-indirect-buffer-display 'other-window)
7439 (pop-to-buffer ibuf))
7440 (t (error "Invalid value")))
7441 (narrow-to-region beg end)
7442 (org-show-all '(headings blocks))
7443 (goto-char pos)
7444 (run-hook-with-args 'org-cycle-hook 'all)
7445 (and (window-live-p cwin) (select-window cwin))))
7447 (defun org-get-indirect-buffer (&optional buffer heading)
7448 (setq buffer (or buffer (current-buffer)))
7449 (let ((n 1) (base (buffer-name buffer)) bname)
7450 (while (buffer-live-p
7451 (get-buffer
7452 (setq bname
7453 (concat base "-"
7454 (if heading (concat heading "-" (number-to-string n))
7455 (number-to-string n))))))
7456 (setq n (1+ n)))
7457 (condition-case nil
7458 (make-indirect-buffer buffer bname 'clone)
7459 (error (make-indirect-buffer buffer bname)))))
7461 (defun org-set-frame-title (title)
7462 "Set the title of the current frame to the string TITLE."
7463 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7465 ;;;; Structure editing
7467 ;;; Inserting headlines
7469 (defun org--line-empty-p (n)
7470 "Is the Nth next line empty?
7472 Counts the current line as N = 1 and the previous line as N = 0;
7473 see `beginning-of-line'."
7474 (save-excursion
7475 (and (not (bobp))
7476 (or (beginning-of-line n) t)
7477 (save-match-data
7478 (looking-at "[ \t]*$")))))
7480 (defun org-previous-line-empty-p ()
7481 "Is the previous line a blank line?
7482 When NEXT is non-nil, check the next line instead."
7483 (org--line-empty-p 0))
7485 (defun org-next-line-empty-p ()
7486 "Is the previous line a blank line?
7487 When NEXT is non-nil, check the next line instead."
7488 (org--line-empty-p 2))
7490 (defun org--blank-before-heading-p (&optional parent)
7491 "Non-nil when an empty line should precede a new heading here.
7492 When optional argument PARENT is non-nil, consider parent
7493 headline instead of current one."
7494 (pcase (assq 'heading org-blank-before-new-entry)
7495 (`(heading . auto)
7496 (save-excursion
7497 (org-with-limited-levels
7498 (unless (and (org-before-first-heading-p)
7499 (not (outline-next-heading)))
7500 (org-back-to-heading t)
7501 (when parent (org-up-heading-safe))
7502 (cond ((not (bobp))
7503 (org-previous-line-empty-p))
7504 ((outline-next-heading)
7505 (org-previous-line-empty-p))
7506 ;; Ignore trailing spaces on last buffer line.
7507 ((progn (skip-chars-backward " \t") (bolp))
7508 (org-previous-line-empty-p))
7509 (t nil))))))
7510 (`(heading . ,value) value)
7511 (_ nil)))
7513 (defun org-insert-heading (&optional arg invisible-ok top)
7514 "Insert a new heading or an item with the same depth at point.
7516 If point is at the beginning of a heading, insert a new heading
7517 or a new headline above the current one. When at the beginning
7518 of a regular line of text, turn it into a heading.
7520 If point is in the middle of a line, split it and create a new
7521 headline with the text in the current line after point (see
7522 `org-M-RET-may-split-line' on how to modify this behavior). As
7523 a special case, on a headline, splitting can only happen on the
7524 title itself. E.g., this excludes breaking stars or tags.
7526 With a `\\[universal-argument]' prefix, set \
7527 `org-insert-heading-respect-content' to
7528 a non-nil value for the duration of the command. This forces the
7529 insertion of a heading after the current subtree, independently
7530 on the location of point.
7532 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7533 insert the heading at the end of the tree
7534 above the current heading. For example, if point is within a
7535 2nd-level heading, then it will insert a 2nd-level heading at
7536 the end of the 1st-level parent subtree.
7538 When INVISIBLE-OK is set, stop at invisible headlines when going
7539 back. This is important for non-interactive uses of the
7540 command.
7542 When optional argument TOP is non-nil, insert a level 1 heading,
7543 unconditionally."
7544 (interactive "P")
7545 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7546 (level (org-current-level))
7547 (stars (make-string (if (and level (not top)) level 1) ?*)))
7548 (cond
7549 ((or org-insert-heading-respect-content
7550 (member arg '((4) (16)))
7551 (and (not invisible-ok)
7552 (invisible-p (max (1- (point)) (point-min)))))
7553 ;; Position point at the location of insertion.
7554 (if (not level) ;before first headline
7555 (org-with-limited-levels (outline-next-heading))
7556 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7557 ;; is nil.
7558 (org-with-limited-levels (org-back-to-heading invisible-ok))
7559 (cond ((equal arg '(16))
7560 (org-up-heading-safe)
7561 (org-end-of-subtree t t))
7563 (org-end-of-subtree t t))))
7564 (unless (bolp) (insert "\n")) ;ensure final newline
7565 (unless (and blank? (org-previous-line-empty-p))
7566 (org-N-empty-lines-before-current (if blank? 1 0)))
7567 (insert stars " \n")
7568 (forward-char -1))
7569 ;; At a headline...
7570 ((org-at-heading-p)
7571 (cond ((bolp)
7572 (when blank? (save-excursion (insert "\n")))
7573 (save-excursion (insert stars " \n"))
7574 (unless (and blank? (org-previous-line-empty-p))
7575 (org-N-empty-lines-before-current (if blank? 1 0)))
7576 (end-of-line))
7577 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7578 (org-match-line org-complex-heading-regexp)
7579 (org-pos-in-match-range (point) 4))
7580 ;; Grab the text that should moved to the new headline.
7581 ;; Preserve tags.
7582 (let ((split (delete-and-extract-region (point) (match-end 4))))
7583 (if (looking-at "[ \t]*$") (replace-match "")
7584 (org-set-tags nil t))
7585 (end-of-line)
7586 (when blank? (insert "\n"))
7587 (insert "\n" stars " ")
7588 (when (org-string-nw-p split) (insert split))
7589 (when (eobp) (save-excursion (insert "\n")))))
7591 (end-of-line)
7592 (when blank? (insert "\n"))
7593 (insert "\n" stars " ")
7594 (when (eobp) (save-excursion (insert "\n"))))))
7595 ;; On regular text, turn line into a headline or split, if
7596 ;; appropriate.
7597 ((bolp)
7598 (insert stars " ")
7599 (unless (and blank? (org-previous-line-empty-p))
7600 (org-N-empty-lines-before-current (if blank? 1 0))))
7602 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7603 (end-of-line))
7604 (insert "\n" stars " ")
7605 (unless (and blank? (org-previous-line-empty-p))
7606 (org-N-empty-lines-before-current (if blank? 1 0))))))
7607 (run-hooks 'org-insert-heading-hook))
7609 (defun org-N-empty-lines-before-current (n)
7610 "Make the number of empty lines before current exactly N.
7611 So this will delete or add empty lines."
7612 (let ((column (current-column)))
7613 (beginning-of-line)
7614 (unless (bobp)
7615 (let ((start (save-excursion
7616 (skip-chars-backward " \r\t\n")
7617 (line-end-position))))
7618 (delete-region start (line-end-position 0))))
7619 (insert (make-string n ?\n))
7620 (move-to-column column)))
7622 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7623 "Return the heading of the current entry, without the stars.
7624 When NO-TAGS is non-nil, don't include tags.
7625 When NO-TODO is non-nil, don't include TODO keywords.
7626 When NO-PRIORITY is non-nil, don't include priority cookie.
7627 When NO-COMMENT is non-nil, don't include COMMENT string."
7628 (save-excursion
7629 (org-back-to-heading t)
7630 (let ((case-fold-search nil))
7631 (looking-at org-complex-heading-regexp)
7632 (let ((todo (and (not no-todo) (match-string 2)))
7633 (priority (and (not no-priority) (match-string 3)))
7634 (headline (pcase (match-string 4)
7635 (`nil "")
7636 ((and (guard no-comment) h)
7637 (replace-regexp-in-string
7638 (eval-when-compile
7639 (format "\\`%s[ \t]+" org-comment-string))
7640 "" h))
7641 (h h)))
7642 (tags (and (not no-tags) (match-string 5))))
7643 (mapconcat #'identity
7644 (delq nil (list todo priority headline tags))
7645 " ")))))
7647 (defun org-heading-components ()
7648 "Return the components of the current heading.
7649 This is a list with the following elements:
7650 - the level as an integer
7651 - the reduced level, different if `org-odd-levels-only' is set.
7652 - the TODO keyword, or nil
7653 - the priority character, like ?A, or nil if no priority is given
7654 - the headline text itself, or the tags string if no headline text
7655 - the tags string, or nil."
7656 (save-excursion
7657 (org-back-to-heading t)
7658 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7659 (list (length (match-string 1))
7660 (org-reduced-level (length (match-string 1)))
7661 (match-string-no-properties 2)
7662 (and (match-end 3) (aref (match-string 3) 2))
7663 (match-string-no-properties 4)
7664 (match-string-no-properties 5)))))
7666 (defun org-get-entry ()
7667 "Get the entry text, after heading, entire subtree."
7668 (save-excursion
7669 (org-back-to-heading t)
7670 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7672 (defun org-edit-headline (&optional heading)
7673 "Edit the current headline.
7674 Set it to HEADING when provided."
7675 (interactive)
7676 (org-with-wide-buffer
7677 (org-back-to-heading t)
7678 (let ((case-fold-search nil))
7679 (when (looking-at org-complex-heading-regexp)
7680 (let* ((old (match-string-no-properties 4))
7681 (new (save-match-data
7682 (org-trim (or heading (read-string "Edit: " old))))))
7683 (unless (equal old new)
7684 (if old (replace-match new t t nil 4)
7685 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7686 (insert " " new))
7687 (org-set-tags nil t)
7688 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7690 (defun org-insert-heading-after-current ()
7691 "Insert a new heading with same level as current, after current subtree."
7692 (interactive)
7693 (org-back-to-heading)
7694 (org-insert-heading)
7695 (org-move-subtree-down)
7696 (end-of-line 1))
7698 (defun org-insert-heading-respect-content (&optional invisible-ok)
7699 "Insert heading with `org-insert-heading-respect-content' set to t."
7700 (interactive)
7701 (org-insert-heading '(4) invisible-ok))
7703 (defun org-insert-todo-heading-respect-content (&optional force-state)
7704 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7705 (interactive)
7706 (org-insert-todo-heading force-state '(4)))
7708 (defun org-insert-todo-heading (arg &optional force-heading)
7709 "Insert a new heading with the same level and TODO state as current heading.
7711 If the heading has no TODO state, or if the state is DONE, use
7712 the first state (TODO by default). Also with one prefix arg,
7713 force first state. With two prefix args, force inserting at the
7714 end of the parent subtree.
7716 When called at a plain list item, insert a new item with an
7717 unchecked check box."
7718 (interactive "P")
7719 (when (or force-heading (not (org-insert-item 'checkbox)))
7720 (org-insert-heading (or (and (equal arg '(16)) '(16))
7721 force-heading))
7722 (save-excursion
7723 (org-forward-heading-same-level -1)
7724 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7725 (let* ((new-mark-x
7726 (if (or (equal arg '(4))
7727 (not (match-beginning 2))
7728 (member (match-string 2) org-done-keywords))
7729 (car org-todo-keywords-1)
7730 (match-string 2)))
7731 (new-mark
7733 (run-hook-with-args-until-success
7734 'org-todo-get-default-hook new-mark-x nil)
7735 new-mark-x)))
7736 (beginning-of-line 1)
7737 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7738 (if org-treat-insert-todo-heading-as-state-change
7739 (org-todo new-mark)
7740 (insert new-mark " "))))
7741 (when org-provide-todo-statistics
7742 (org-update-parent-todo-statistics))))
7744 (defun org-insert-subheading (arg)
7745 "Insert a new subheading and demote it.
7746 Works for outline headings and for plain lists alike."
7747 (interactive "P")
7748 (org-insert-heading arg)
7749 (cond
7750 ((org-at-heading-p) (org-do-demote))
7751 ((org-at-item-p) (org-indent-item))))
7753 (defun org-insert-todo-subheading (arg)
7754 "Insert a new subheading with TODO keyword or checkbox and demote it.
7755 Works for outline headings and for plain lists alike."
7756 (interactive "P")
7757 (org-insert-todo-heading arg)
7758 (cond
7759 ((org-at-heading-p) (org-do-demote))
7760 ((org-at-item-p) (org-indent-item))))
7762 ;;; Promotion and Demotion
7764 (defvar org-after-demote-entry-hook nil
7765 "Hook run after an entry has been demoted.
7766 The cursor will be at the beginning of the entry.
7767 When a subtree is being demoted, the hook will be called for each node.")
7769 (defvar org-after-promote-entry-hook nil
7770 "Hook run after an entry has been promoted.
7771 The cursor will be at the beginning of the entry.
7772 When a subtree is being promoted, the hook will be called for each node.")
7774 (defun org-promote-subtree ()
7775 "Promote the entire subtree.
7776 See also `org-promote'."
7777 (interactive)
7778 (save-excursion
7779 (org-with-limited-levels (org-map-tree 'org-promote)))
7780 (org-fix-position-after-promote))
7782 (defun org-demote-subtree ()
7783 "Demote the entire subtree.
7784 See `org-demote' and `org-promote'."
7785 (interactive)
7786 (save-excursion
7787 (org-with-limited-levels (org-map-tree 'org-demote)))
7788 (org-fix-position-after-promote))
7790 (defun org-do-promote ()
7791 "Promote the current heading higher up the tree.
7792 If the region is active in `transient-mark-mode', promote all
7793 headings in the region."
7794 (interactive)
7795 (save-excursion
7796 (if (org-region-active-p)
7797 (org-map-region 'org-promote (region-beginning) (region-end))
7798 (org-promote)))
7799 (org-fix-position-after-promote))
7801 (defun org-do-demote ()
7802 "Demote the current heading lower down the tree.
7803 If the region is active in `transient-mark-mode', demote all
7804 headings in the region."
7805 (interactive)
7806 (save-excursion
7807 (if (org-region-active-p)
7808 (org-map-region 'org-demote (region-beginning) (region-end))
7809 (org-demote)))
7810 (org-fix-position-after-promote))
7812 (defun org-fix-position-after-promote ()
7813 "Fix cursor position and indentation after demoting/promoting."
7814 (let ((pos (point)))
7815 (when (save-excursion
7816 (beginning-of-line)
7817 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7818 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7819 (cond ((eobp) (insert " "))
7820 ((eolp) (insert " "))
7821 ((equal (char-after) ?\s) (forward-char 1))))))
7823 (defun org-current-level ()
7824 "Return the level of the current entry, or nil if before the first headline.
7825 The level is the number of stars at the beginning of the
7826 headline. Use `org-reduced-level' to remove the effect of
7827 `org-odd-levels'. Unlike to `org-outline-level', this function
7828 ignores inlinetasks."
7829 (let ((level (org-with-limited-levels (org-outline-level))))
7830 (and (> level 0) level)))
7832 (defun org-get-previous-line-level ()
7833 "Return the outline depth of the last headline before the current line.
7834 Returns 0 for the first headline in the buffer, and nil if before the
7835 first headline."
7836 (and (org-current-level)
7837 (or (and (/= (line-beginning-position) (point-min))
7838 (save-excursion (beginning-of-line 0) (org-current-level)))
7839 0)))
7841 (defun org-reduced-level (l)
7842 "Compute the effective level of a heading.
7843 This takes into account the setting of `org-odd-levels-only'."
7844 (cond
7845 ((zerop l) 0)
7846 (org-odd-levels-only (1+ (floor (/ l 2))))
7847 (t l)))
7849 (defun org-level-increment ()
7850 "Return the number of stars that will be added or removed at a
7851 time to headlines when structure editing, based on the value of
7852 `org-odd-levels-only'."
7853 (if org-odd-levels-only 2 1))
7855 (defun org-get-valid-level (level &optional change)
7856 "Rectify a level change under the influence of `org-odd-levels-only'.
7857 LEVEL is a current level, CHANGE is by how much the level should
7858 be modified. Even if CHANGE is nil, LEVEL may be returned
7859 modified because even level numbers will become the next higher
7860 odd number. Returns values greater than 0."
7861 (if org-odd-levels-only
7862 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7863 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7864 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7865 (max 1 (+ level (or change 0)))))
7867 (defun org-promote ()
7868 "Promote the current heading higher up the tree."
7869 (org-with-wide-buffer
7870 (org-back-to-heading t)
7871 (let* ((after-change-functions (remq 'flyspell-after-change-function
7872 after-change-functions))
7873 (level (save-match-data (funcall outline-level)))
7874 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7875 (diff (abs (- level (length up-head) -1))))
7876 (cond
7877 ((and (= level 1) org-allow-promoting-top-level-subtree)
7878 (replace-match "# " nil t))
7879 ((= level 1)
7880 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7881 (t (replace-match up-head nil t)))
7882 (unless (= level 1)
7883 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7884 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7885 (run-hooks 'org-after-promote-entry-hook))))
7887 (defun org-demote ()
7888 "Demote the current heading lower down the tree."
7889 (org-with-wide-buffer
7890 (org-back-to-heading t)
7891 (let* ((after-change-functions (remq 'flyspell-after-change-function
7892 after-change-functions))
7893 (level (save-match-data (funcall outline-level)))
7894 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7895 (diff (abs (- level (length down-head) -1))))
7896 (replace-match down-head nil t)
7897 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7898 (when org-adapt-indentation (org-fixup-indentation diff))
7899 (run-hooks 'org-after-demote-entry-hook))))
7901 (defun org-cycle-level ()
7902 "Cycle the level of an empty headline through possible states.
7903 This goes first to child, then to parent, level, then up the hierarchy.
7904 After top level, it switches back to sibling level."
7905 (interactive)
7906 (let ((org-adapt-indentation nil))
7907 (when (org-point-at-end-of-empty-headline)
7908 (setq this-command 'org-cycle-level) ; Only needed for caching
7909 (let ((cur-level (org-current-level))
7910 (prev-level (org-get-previous-line-level)))
7911 (cond
7912 ;; If first headline in file, promote to top-level.
7913 ((= prev-level 0)
7914 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7915 do (org-do-promote)))
7916 ;; If same level as prev, demote one.
7917 ((= prev-level cur-level)
7918 (org-do-demote))
7919 ;; If parent is top-level, promote to top level if not already.
7920 ((= prev-level 1)
7921 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7922 do (org-do-promote)))
7923 ;; If top-level, return to prev-level.
7924 ((= cur-level 1)
7925 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7926 do (org-do-demote)))
7927 ;; If less than prev-level, promote one.
7928 ((< cur-level prev-level)
7929 (org-do-promote))
7930 ;; If deeper than prev-level, promote until higher than
7931 ;; prev-level.
7932 ((> cur-level prev-level)
7933 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7934 do (org-do-promote))))
7935 t))))
7937 (defun org-map-tree (fun)
7938 "Call FUN for every heading underneath the current one."
7939 (org-back-to-heading t)
7940 (let ((level (funcall outline-level)))
7941 (save-excursion
7942 (funcall fun)
7943 (while (and (progn
7944 (outline-next-heading)
7945 (> (funcall outline-level) level))
7946 (not (eobp)))
7947 (funcall fun)))))
7949 (defun org-map-region (fun beg end)
7950 "Call FUN for every heading between BEG and END."
7951 (let ((org-ignore-region t))
7952 (save-excursion
7953 (setq end (copy-marker end))
7954 (goto-char beg)
7955 (when (and (re-search-forward org-outline-regexp-bol nil t)
7956 (< (point) end))
7957 (funcall fun))
7958 (while (and (progn
7959 (outline-next-heading)
7960 (< (point) end))
7961 (not (eobp)))
7962 (funcall fun)))))
7964 (defun org-fixup-indentation (diff)
7965 "Change the indentation in the current entry by DIFF.
7967 DIFF is an integer. Indentation is done according to the
7968 following rules:
7970 - Planning information and property drawers are always indented
7971 according to the new level of the headline;
7973 - Footnote definitions and their contents are ignored;
7975 - Inlinetasks' boundaries are not shifted;
7977 - Empty lines are ignored;
7979 - Other lines' indentation are shifted by DIFF columns, unless
7980 it would introduce a structural change in the document, in
7981 which case no shifting is done at all.
7983 Assume point is at a heading or an inlinetask beginning."
7984 (org-with-wide-buffer
7985 (narrow-to-region (line-beginning-position)
7986 (save-excursion
7987 (if (org-with-limited-levels (org-at-heading-p))
7988 (org-with-limited-levels (outline-next-heading))
7989 (org-inlinetask-goto-end))
7990 (point)))
7991 (forward-line)
7992 ;; Indent properly planning info and property drawer.
7993 (when (looking-at-p org-planning-line-re)
7994 (org-indent-line)
7995 (forward-line))
7996 (when (looking-at org-property-drawer-re)
7997 (goto-char (match-end 0))
7998 (forward-line)
7999 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8000 (catch 'no-shift
8001 (when (zerop diff) (throw 'no-shift nil))
8002 ;; If DIFF is negative, first check if a shift is possible at all
8003 ;; (e.g., it doesn't break structure). This can only happen if
8004 ;; some contents are not properly indented.
8005 (let ((case-fold-search t))
8006 (when (< diff 0)
8007 (let ((diff (- diff))
8008 (forbidden-re (concat org-outline-regexp
8009 "\\|"
8010 (substring org-footnote-definition-re 1))))
8011 (save-excursion
8012 (while (not (eobp))
8013 (cond
8014 ((looking-at-p "[ \t]*$") (forward-line))
8015 ((and (looking-at-p org-footnote-definition-re)
8016 (let ((e (org-element-at-point)))
8017 (and (eq (org-element-type e) 'footnote-definition)
8018 (goto-char (org-element-property :end e))))))
8019 ((looking-at-p org-outline-regexp) (forward-line))
8020 ;; Give up if shifting would move before column 0 or
8021 ;; if it would introduce a headline or a footnote
8022 ;; definition.
8024 (skip-chars-forward " \t")
8025 (let ((ind (current-column)))
8026 (when (or (< ind diff)
8027 (and (= ind diff) (looking-at-p forbidden-re)))
8028 (throw 'no-shift nil)))
8029 ;; Ignore contents of example blocks and source
8030 ;; blocks if their indentation is meant to be
8031 ;; preserved. Jump to block's closing line.
8032 (beginning-of-line)
8033 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8034 (let ((e (org-element-at-point)))
8035 (and (memq (org-element-type e)
8036 '(example-block src-block))
8037 (or org-src-preserve-indentation
8038 (org-element-property :preserve-indent e))
8039 (goto-char (org-element-property :end e))
8040 (progn (skip-chars-backward " \r\t\n")
8041 (beginning-of-line)
8042 t))))
8043 (forward-line))))))))
8044 ;; Shift lines but footnote definitions, inlinetasks boundaries
8045 ;; by DIFF. Also skip contents of source or example blocks
8046 ;; when indentation is meant to be preserved.
8047 (while (not (eobp))
8048 (cond
8049 ((and (looking-at-p org-footnote-definition-re)
8050 (let ((e (org-element-at-point)))
8051 (and (eq (org-element-type e) 'footnote-definition)
8052 (goto-char (org-element-property :end e))))))
8053 ((looking-at-p org-outline-regexp) (forward-line))
8054 ((looking-at-p "[ \t]*$") (forward-line))
8056 (indent-line-to (+ (org-get-indentation) diff))
8057 (beginning-of-line)
8058 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8059 (let ((e (org-element-at-point)))
8060 (and (memq (org-element-type e)
8061 '(example-block src-block))
8062 (or org-src-preserve-indentation
8063 (org-element-property :preserve-indent e))
8064 (goto-char (org-element-property :end e))
8065 (progn (skip-chars-backward " \r\t\n")
8066 (beginning-of-line)
8067 t))))
8068 (forward-line)))))))))
8070 (defun org-convert-to-odd-levels ()
8071 "Convert an Org file with all levels allowed to one with odd levels.
8072 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8073 level 5 etc."
8074 (interactive)
8075 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8076 (let ((outline-level 'org-outline-level)
8077 (org-odd-levels-only nil) n)
8078 (save-excursion
8079 (goto-char (point-min))
8080 (while (re-search-forward "^\\*\\*+ " nil t)
8081 (setq n (- (length (match-string 0)) 2))
8082 (while (>= (setq n (1- n)) 0)
8083 (org-demote))
8084 (end-of-line 1))))))
8086 (defun org-convert-to-oddeven-levels ()
8087 "Convert an Org file with only odd levels to one with odd/even levels.
8088 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8089 file contains a section with an even level, conversion would
8090 destroy the structure of the file. An error is signaled in this
8091 case."
8092 (interactive)
8093 (goto-char (point-min))
8094 ;; First check if there are no even levels
8095 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8096 (org-show-set-visibility 'canonical)
8097 (error "Not all levels are odd in this file. Conversion not possible"))
8098 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8099 (let ((outline-regexp org-outline-regexp)
8100 (outline-level 'org-outline-level)
8101 (org-odd-levels-only nil) n)
8102 (save-excursion
8103 (goto-char (point-min))
8104 (while (re-search-forward "^\\*\\*+ " nil t)
8105 (setq n (/ (1- (length (match-string 0))) 2))
8106 (while (>= (setq n (1- n)) 0)
8107 (org-promote))
8108 (end-of-line 1))))))
8110 (defun org-tr-level (n)
8111 "Make N odd if required."
8112 (if org-odd-levels-only (1+ (/ n 2)) n))
8114 ;;; Vertical tree motion, cutting and pasting of subtrees
8116 (defun org-move-subtree-up (&optional arg)
8117 "Move the current subtree up past ARG headlines of the same level."
8118 (interactive "p")
8119 (org-move-subtree-down (- (prefix-numeric-value arg))))
8121 (defun org-move-subtree-down (&optional arg)
8122 "Move the current subtree down past ARG headlines of the same level."
8123 (interactive "p")
8124 (setq arg (prefix-numeric-value arg))
8125 (org-preserve-local-variables
8126 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8127 'org-get-last-sibling))
8128 (ins-point (make-marker))
8129 (cnt (abs arg))
8130 (col (current-column))
8131 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8132 ;; Select the tree
8133 (org-back-to-heading)
8134 (setq beg0 (point))
8135 (save-excursion
8136 (setq ne-beg (org-back-over-empty-lines))
8137 (setq beg (point)))
8138 (save-match-data
8139 (save-excursion (outline-end-of-heading)
8140 (setq folded (org-invisible-p)))
8141 (progn (org-end-of-subtree nil t)
8142 (unless (eobp) (backward-char))))
8143 (outline-next-heading)
8144 (setq ne-end (org-back-over-empty-lines))
8145 (setq end (point))
8146 (goto-char beg0)
8147 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8148 ;; include less whitespace
8149 (save-excursion
8150 (goto-char beg)
8151 (forward-line (- ne-beg ne-end))
8152 (setq beg (point))))
8153 ;; Find insertion point, with error handling
8154 (while (> cnt 0)
8155 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8156 (goto-char beg0)
8157 (user-error "Cannot move past superior level or buffer limit"))
8158 (setq cnt (1- cnt)))
8159 (when (> arg 0)
8160 ;; Moving forward - still need to move over subtree
8161 (org-end-of-subtree t t)
8162 (save-excursion
8163 (org-back-over-empty-lines)
8164 (or (bolp) (newline))))
8165 (setq ne-ins (org-back-over-empty-lines))
8166 (move-marker ins-point (point))
8167 (setq txt (buffer-substring beg end))
8168 (org-save-markers-in-region beg end)
8169 (delete-region beg end)
8170 (org-remove-empty-overlays-at beg)
8171 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8172 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8173 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8174 (let ((bbb (point)))
8175 (insert-before-markers txt)
8176 (org-reinstall-markers-in-region bbb)
8177 (move-marker ins-point bbb))
8178 (or (bolp) (insert "\n"))
8179 (setq ins-end (point))
8180 (goto-char ins-point)
8181 (org-skip-whitespace)
8182 (when (and (< arg 0)
8183 (org-first-sibling-p)
8184 (> ne-ins ne-beg))
8185 ;; Move whitespace back to beginning
8186 (save-excursion
8187 (goto-char ins-end)
8188 (let ((kill-whole-line t))
8189 (kill-line (- ne-ins ne-beg)) (point)))
8190 (insert (make-string (- ne-ins ne-beg) ?\n)))
8191 (move-marker ins-point nil)
8192 (if folded
8193 (outline-hide-subtree)
8194 (org-show-entry)
8195 (org-show-children))
8196 (org-clean-visibility-after-subtree-move)
8197 ;; move back to the initial column we were at
8198 (move-to-column col))))
8200 (defvar org-subtree-clip ""
8201 "Clipboard for cut and paste of subtrees.
8202 This is actually only a copy of the kill, because we use the normal kill
8203 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8205 (defvar org-subtree-clip-folded nil
8206 "Was the last copied subtree folded?
8207 This is used to fold the tree back after pasting.")
8209 (defun org-cut-subtree (&optional n)
8210 "Cut the current subtree into the clipboard.
8211 With prefix arg N, cut this many sequential subtrees.
8212 This is a short-hand for marking the subtree and then cutting it."
8213 (interactive "p")
8214 (org-copy-subtree n 'cut))
8216 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8217 "Copy the current subtree into the clipboard.
8218 With prefix arg N, copy this many sequential subtrees.
8219 This is a short-hand for marking the subtree and then copying it.
8220 If CUT is non-nil, actually cut the subtree.
8221 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8222 of some markers in the region, even if CUT is non-nil. This is
8223 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8224 (interactive "p")
8225 (org-preserve-local-variables
8226 (let (beg end folded (beg0 (point)))
8227 (if (called-interactively-p 'any)
8228 (org-back-to-heading nil) ; take what looks like a subtree
8229 (org-back-to-heading t)) ; take what is really there
8230 (setq beg (point))
8231 (skip-chars-forward " \t\r\n")
8232 (save-match-data
8233 (if nosubtrees
8234 (outline-next-heading)
8235 (save-excursion (outline-end-of-heading)
8236 (setq folded (org-invisible-p)))
8237 (ignore-errors (org-forward-heading-same-level (1- n) t))
8238 (org-end-of-subtree t t)))
8239 ;; Include the end of an inlinetask
8240 (when (and (featurep 'org-inlinetask)
8241 (looking-at-p (concat (org-inlinetask-outline-regexp)
8242 "END[ \t]*$")))
8243 (end-of-line))
8244 (setq end (point))
8245 (goto-char beg0)
8246 (when (> end beg)
8247 (setq org-subtree-clip-folded folded)
8248 (when (or cut force-store-markers)
8249 (org-save-markers-in-region beg end))
8250 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8251 (setq org-subtree-clip (current-kill 0))
8252 (message "%s: Subtree(s) with %d characters"
8253 (if cut "Cut" "Copied")
8254 (length org-subtree-clip))))))
8256 (defun org-paste-subtree (&optional level tree for-yank remove)
8257 "Paste the clipboard as a subtree, with modification of headline level.
8259 The entire subtree is promoted or demoted in order to match a new headline
8260 level.
8262 If the cursor is at the beginning of a headline, the same level as
8263 that headline is used to paste the tree.
8265 If not, the new level is derived from the *visible* headings
8266 before and after the insertion point, and taken to be the inferior headline
8267 level of the two. So if the previous visible heading is level 3 and the
8268 next is level 4 (or vice versa), level 4 will be used for insertion.
8269 This makes sure that the subtree remains an independent subtree and does
8270 not swallow low level entries.
8272 You can also force a different level, either by using a numeric prefix
8273 argument, or by inserting the heading marker by hand. For example, if the
8274 cursor is after \"*****\", then the tree will be shifted to level 5.
8276 If optional TREE is given, use this text instead of the kill ring.
8278 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8279 move back over whitespace before inserting, and move point to the end of
8280 the inserted text when done.
8282 When REMOVE is non-nil, remove the subtree from the clipboard."
8283 (interactive "P")
8284 (setq tree (or tree (and kill-ring (current-kill 0))))
8285 (unless (org-kill-is-subtree-p tree)
8286 (user-error
8287 (substitute-command-keys
8288 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8289 (org-with-limited-levels
8290 (let* ((visp (not (org-invisible-p)))
8291 (txt tree)
8292 (old-level (if (string-match org-outline-regexp-bol txt)
8293 (- (match-end 0) (match-beginning 0) 1)
8294 -1))
8295 (force-level
8296 (cond
8297 (level (prefix-numeric-value level))
8298 ;; When point is right after the stars in an otherwise
8299 ;; empty headline, use stars as the forced level.
8300 ((and (looking-at-p "[ \t]*$")
8301 (string-match-p "^\\*+ *"
8302 (buffer-substring (line-beginning-position)
8303 (point))))
8304 (org-outline-level))
8305 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8306 (previous-level
8307 (save-excursion
8308 (org-previous-visible-heading 1)
8309 (if (org-at-heading-p) (org-outline-level) 1)))
8310 (next-level
8311 (save-excursion
8312 (if (org-at-heading-p) (org-outline-level)
8313 (org-next-visible-heading 1)
8314 (if (org-at-heading-p) (org-outline-level) 1))))
8315 (new-level (or force-level (max previous-level next-level)))
8316 (shift (if (or (= old-level -1)
8317 (= new-level -1)
8318 (= old-level new-level))
8320 (- new-level old-level)))
8321 (delta (if (> shift 0) -1 1))
8322 (func (if (> shift 0) #'org-demote #'org-promote))
8323 (org-odd-levels-only nil)
8324 beg end newend)
8325 ;; Remove the forced level indicator.
8326 (when (and force-level (not level))
8327 (delete-region (line-beginning-position) (point)))
8328 ;; Paste before the next visible heading or at end of buffer,
8329 ;; unless point is at the beginning of a headline.
8330 (unless (and (bolp) (org-at-heading-p))
8331 (org-next-visible-heading 1)
8332 (unless (bolp) (insert "\n")))
8333 (setq beg (point))
8334 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8335 (insert-before-markers txt)
8336 (unless (string-suffix-p "\n" txt) (insert "\n"))
8337 (setq newend (point))
8338 (org-reinstall-markers-in-region beg)
8339 (setq end (point))
8340 (goto-char beg)
8341 (skip-chars-forward " \t\n\r")
8342 (setq beg (point))
8343 (when (and (org-invisible-p) visp)
8344 (save-excursion (outline-show-heading)))
8345 ;; Shift if necessary.
8346 (unless (= shift 0)
8347 (save-restriction
8348 (narrow-to-region beg end)
8349 (while (not (= shift 0))
8350 (org-map-region func (point-min) (point-max))
8351 (setq shift (+ delta shift)))
8352 (goto-char (point-min))
8353 (setq newend (point-max))))
8354 (when (or for-yank (called-interactively-p 'interactive))
8355 (message "Clipboard pasted as level %d subtree" new-level))
8356 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8357 kill-ring
8358 (equal org-subtree-clip (current-kill 0))
8359 org-subtree-clip-folded)
8360 ;; The tree was folded before it was killed/copied
8361 (outline-hide-subtree))
8362 (when for-yank (goto-char newend))
8363 (when remove (pop kill-ring)))))
8365 (defun org-kill-is-subtree-p (&optional txt)
8366 "Check if the current kill is an outline subtree, or a set of trees.
8367 Returns nil if kill does not start with a headline, or if the first
8368 headline level is not the largest headline level in the tree.
8369 So this will actually accept several entries of equal levels as well,
8370 which is OK for `org-paste-subtree'.
8371 If optional TXT is given, check this string instead of the current kill."
8372 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8373 (re (org-get-limited-outline-regexp))
8374 (^re (concat "^" re))
8375 (start-level (and kill
8376 (string-match
8377 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8378 kill)
8379 (- (match-end 2) (match-beginning 2) 1)))
8380 (start (1+ (or (match-beginning 2) -1))))
8381 (if (not start-level)
8382 (progn
8383 nil) ;; does not even start with a heading
8384 (catch 'exit
8385 (while (setq start (string-match ^re kill (1+ start)))
8386 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8387 (throw 'exit nil)))
8388 t))))
8390 (defvar org-markers-to-move nil
8391 "Markers that should be moved with a cut-and-paste operation.
8392 Those markers are stored together with their positions relative to
8393 the start of the region.")
8395 (defun org-save-markers-in-region (beg end)
8396 "Check markers in region.
8397 If these markers are between BEG and END, record their position relative
8398 to BEG, so that after moving the block of text, we can put the markers back
8399 into place.
8400 This function gets called just before an entry or tree gets cut from the
8401 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8402 called immediately, to move the markers with the entries."
8403 (setq org-markers-to-move nil)
8404 (when (featurep 'org-clock)
8405 (org-clock-save-markers-for-cut-and-paste beg end))
8406 (when (featurep 'org-agenda)
8407 (org-agenda-save-markers-for-cut-and-paste beg end)))
8409 (defun org-check-and-save-marker (marker beg end)
8410 "Check if MARKER is between BEG and END.
8411 If yes, remember the marker and the distance to BEG."
8412 (when (and (marker-buffer marker)
8413 (equal (marker-buffer marker) (current-buffer))
8414 (>= marker beg) (< marker end))
8415 (push (cons marker (- marker beg)) org-markers-to-move)))
8417 (defun org-reinstall-markers-in-region (beg)
8418 "Move all remembered markers to their position relative to BEG."
8419 (dolist (x org-markers-to-move)
8420 (move-marker (car x) (+ beg (cdr x))))
8421 (setq org-markers-to-move nil))
8423 (defun org-narrow-to-subtree ()
8424 "Narrow buffer to the current subtree."
8425 (interactive)
8426 (save-excursion
8427 (save-match-data
8428 (org-with-limited-levels
8429 (narrow-to-region
8430 (progn (org-back-to-heading t) (point))
8431 (progn (org-end-of-subtree t t)
8432 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8433 (point)))))))
8435 (defun org-narrow-to-block ()
8436 "Narrow buffer to the current block."
8437 (interactive)
8438 (let* ((case-fold-search t)
8439 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8440 "^[ \t]*#\\+end_.*")))
8441 (if blockp
8442 (narrow-to-region (car blockp) (cdr blockp))
8443 (user-error "Not in a block"))))
8445 (defun org-clone-subtree-with-time-shift (n &optional shift)
8446 "Clone the task (subtree) at point N times.
8447 The clones will be inserted as siblings.
8449 In interactive use, the user will be prompted for the number of
8450 clones to be produced. If the entry has a timestamp, the user
8451 will also be prompted for a time shift, which may be a repeater
8452 as used in time stamps, for example `+3d'. To disable this,
8453 you can call the function with a universal prefix argument.
8455 When a valid repeater is given and the entry contains any time
8456 stamps, the clones will become a sequence in time, with time
8457 stamps in the subtree shifted for each clone produced. If SHIFT
8458 is nil or the empty string, time stamps will be left alone. The
8459 ID property of the original subtree is removed.
8461 In each clone, all the CLOCK entries will be removed. This
8462 prevents Org from considering that the clocked times overlap.
8464 If the original subtree did contain time stamps with a repeater,
8465 the following will happen:
8466 - the repeater will be removed in each clone
8467 - an additional clone will be produced, with the current, unshifted
8468 date(s) in the entry.
8469 - the original entry will be placed *after* all the clones, with
8470 repeater intact.
8471 - the start days in the repeater in the original entry will be shifted
8472 to past the last clone.
8473 In this way you can spell out a number of instances of a repeating task,
8474 and still retain the repeater to cover future instances of the task.
8476 As described above, N+1 clones are produced when the original
8477 subtree has a repeater. Setting N to 0, then, can be used to
8478 remove the repeater from a subtree and create a shifted clone
8479 with the original repeater."
8480 (interactive "nNumber of clones to produce: ")
8481 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8482 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8483 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8484 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8485 (shift
8486 (or shift
8487 (if (and (not (equal current-prefix-arg '(4)))
8488 (save-excursion
8489 (goto-char beg)
8490 (re-search-forward org-ts-regexp-both end-of-tree t)))
8491 (read-from-minibuffer
8492 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8493 ""))) ;No time shift
8494 (doshift
8495 (and (org-string-nw-p shift)
8496 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8497 shift)
8498 (user-error "Invalid shift specification %s" shift)))))
8499 (goto-char end-of-tree)
8500 (unless (bolp) (insert "\n"))
8501 (let* ((end (point))
8502 (template (buffer-substring beg end))
8503 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8504 (shift-what (pcase (and doshift (match-string 2 shift))
8505 (`nil nil)
8506 ("d" 'day)
8507 ("w" (setq shift-n (* 7 shift-n)) 'day)
8508 ("m" 'month)
8509 ("y" 'year)
8510 (_ (error "Unsupported time unit"))))
8511 (nmin 1)
8512 (nmax n)
8513 (n-no-remove -1)
8514 (idprop (org-entry-get nil "ID")))
8515 (when (and doshift
8516 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8517 template))
8518 (delete-region beg end)
8519 (setq end beg)
8520 (setq nmin 0)
8521 (setq nmax (1+ nmax))
8522 (setq n-no-remove nmax))
8523 (goto-char end)
8524 (cl-loop for n from nmin to nmax do
8525 (insert
8526 ;; Prepare clone.
8527 (with-temp-buffer
8528 (insert template)
8529 (org-mode)
8530 (goto-char (point-min))
8531 (org-show-subtree)
8532 (and idprop (if org-clone-delete-id
8533 (org-entry-delete nil "ID")
8534 (org-id-get-create t)))
8535 (unless (= n 0)
8536 (while (re-search-forward org-clock-line-re nil t)
8537 (delete-region (line-beginning-position)
8538 (line-beginning-position 2)))
8539 (goto-char (point-min))
8540 (while (re-search-forward org-drawer-regexp nil t)
8541 (org-remove-empty-drawer-at (point))))
8542 (goto-char (point-min))
8543 (when doshift
8544 (while (re-search-forward org-ts-regexp-both nil t)
8545 (org-timestamp-change (* n shift-n) shift-what))
8546 (unless (= n n-no-remove)
8547 (goto-char (point-min))
8548 (while (re-search-forward org-ts-regexp nil t)
8549 (save-excursion
8550 (goto-char (match-beginning 0))
8551 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8552 (delete-region (match-beginning 1) (match-end 1)))))))
8553 (buffer-string)))))
8554 (goto-char beg)))
8556 ;;; Outline Sorting
8558 (defun org-sort (&optional with-case)
8559 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8560 Optional argument WITH-CASE means sort case-sensitively."
8561 (interactive "P")
8562 (org-call-with-arg
8563 (cond ((org-at-table-p) #'org-table-sort-lines)
8564 ((org-at-item-p) #'org-sort-list)
8565 (t #'org-sort-entries))
8566 with-case))
8568 (defun org-sort-remove-invisible (s)
8569 "Remove invisible part of links and emphasis markers from string S."
8570 (remove-text-properties 0 (length s) org-rm-props s)
8571 (replace-regexp-in-string
8572 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8573 (replace-regexp-in-string
8574 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8575 (org-link-display-format s)
8576 t t) t t))
8578 (defvar org-priority-regexp) ; defined later in the file
8580 (defvar org-after-sorting-entries-or-items-hook nil
8581 "Hook that is run after a bunch of entries or items have been sorted.
8582 When children are sorted, the cursor is in the parent line when this
8583 hook gets called. When a region or a plain list is sorted, the cursor
8584 will be in the first entry of the sorted region/list.")
8586 (defun org-sort-entries
8587 (&optional with-case sorting-type getkey-func compare-func property
8588 interactive?)
8589 "Sort entries on a certain level of an outline tree.
8590 If there is an active region, the entries in the region are sorted.
8591 Else, if the cursor is before the first entry, sort the top-level items.
8592 Else, the children of the entry at point are sorted.
8594 Sorting can be alphabetically, numerically, by date/time as given by
8595 a time stamp, by a property, by priority order, or by a custom function.
8597 The command prompts for the sorting type unless it has been given to the
8598 function through the SORTING-TYPE argument, which needs to be a character,
8599 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8600 the precise meaning of each character:
8602 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8603 c By creation time, which is assumed to be the first inactive time stamp
8604 at the beginning of a line.
8605 d By deadline date/time.
8606 k By clocking time.
8607 n Numerically, by converting the beginning of the entry/item to a number.
8608 o By order of TODO keywords.
8609 p By priority according to the cookie.
8610 r By the value of a property.
8611 s By scheduled date/time.
8612 t By date/time, either the first active time stamp in the entry, or, if
8613 none exist, by the first inactive one.
8615 Capital letters will reverse the sort order.
8617 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8618 called with point at the beginning of the record. It must return a
8619 value that is compatible with COMPARE-FUNC, the function used to
8620 compare entries.
8622 Comparing entries ignores case by default. However, with an optional argument
8623 WITH-CASE, the sorting considers case as well.
8625 Sorting is done against the visible part of the headlines, it ignores hidden
8626 links.
8628 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8630 A non-nil value for INTERACTIVE? is used to signal that this
8631 function is being called interactively."
8632 (interactive (list current-prefix-arg nil nil nil nil t))
8633 (let ((case-func (if with-case 'identity 'downcase))
8634 start beg end stars re re2
8635 txt what tmp)
8636 ;; Find beginning and end of region to sort
8637 (cond
8638 ((org-region-active-p)
8639 ;; we will sort the region
8640 (setq end (region-end)
8641 what "region")
8642 (goto-char (region-beginning))
8643 (unless (org-at-heading-p) (outline-next-heading))
8644 (setq start (point)))
8645 ((or (org-at-heading-p)
8646 (ignore-errors (progn (org-back-to-heading) t)))
8647 ;; we will sort the children of the current headline
8648 (org-back-to-heading)
8649 (setq start (point)
8650 end (progn (org-end-of-subtree t t)
8651 (or (bolp) (insert "\n"))
8652 (when (>= (org-back-over-empty-lines) 1)
8653 (forward-line 1))
8654 (point))
8655 what "children")
8656 (goto-char start)
8657 (outline-show-subtree)
8658 (outline-next-heading))
8660 ;; we will sort the top-level entries in this file
8661 (goto-char (point-min))
8662 (or (org-at-heading-p) (outline-next-heading))
8663 (setq start (point))
8664 (goto-char (point-max))
8665 (beginning-of-line 1)
8666 (when (looking-at ".*?\\S-")
8667 ;; File ends in a non-white line
8668 (end-of-line 1)
8669 (insert "\n"))
8670 (setq end (point-max))
8671 (setq what "top-level")
8672 (goto-char start)
8673 (org-show-all '(headings blocks))))
8675 (setq beg (point))
8676 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8678 (looking-at "\\(\\*+\\)")
8679 (setq stars (match-string 1)
8680 re (concat "^" (regexp-quote stars) " +")
8681 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8682 txt (buffer-substring beg end))
8683 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8684 (when (and (not (equal stars "*")) (string-match re2 txt))
8685 (user-error "Region to sort contains a level above the first entry"))
8687 (unless sorting-type
8688 (message
8689 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8690 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8691 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8692 what)
8693 (setq sorting-type (read-char-exclusive)))
8695 (unless getkey-func
8696 (and (= (downcase sorting-type) ?f)
8697 (setq getkey-func
8698 (or (and interactive?
8699 (org-read-function
8700 "Function for extracting keys: "))
8701 (error "Missing key extractor")))))
8703 (and (= (downcase sorting-type) ?r)
8704 (not property)
8705 (setq property
8706 (completing-read "Property: "
8707 (mapcar #'list (org-buffer-property-keys t))
8708 nil t)))
8710 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8711 (message "Sorting entries...")
8713 (save-restriction
8714 (narrow-to-region start end)
8715 (let ((restore-clock?
8716 ;; The clock marker is lost when using `sort-subr'; mark
8717 ;; the clock with temporary `:org-clock-marker-backup'
8718 ;; text property.
8719 (when (and (eq (org-clock-is-active) (current-buffer))
8720 (<= start (marker-position org-clock-marker))
8721 (>= end (marker-position org-clock-marker)))
8722 (org-with-silent-modifications
8723 (put-text-property (1- org-clock-marker) org-clock-marker
8724 :org-clock-marker-backup t))
8726 (dcst (downcase sorting-type))
8727 (case-fold-search nil)
8728 (now (current-time)))
8729 (org-preserve-local-variables
8730 (sort-subr
8731 (/= dcst sorting-type)
8732 ;; This function moves to the beginning character of the
8733 ;; "record" to be sorted.
8734 (lambda nil
8735 (if (re-search-forward re nil t)
8736 (goto-char (match-beginning 0))
8737 (goto-char (point-max))))
8738 ;; This function moves to the last character of the "record" being
8739 ;; sorted.
8740 (lambda nil
8741 (save-match-data
8742 (condition-case nil
8743 (outline-forward-same-level 1)
8744 (error
8745 (goto-char (point-max))))))
8746 ;; This function returns the value that gets sorted against.
8747 (lambda ()
8748 (cond
8749 ((= dcst ?n)
8750 (string-to-number
8751 (org-sort-remove-invisible (org-get-heading t t t t))))
8752 ((= dcst ?a)
8753 (funcall case-func
8754 (org-sort-remove-invisible (org-get-heading t t t t))))
8755 ((= dcst ?k)
8756 (or (get-text-property (point) :org-clock-minutes) 0))
8757 ((= dcst ?t)
8758 (let ((end (save-excursion (outline-next-heading) (point))))
8759 (if (or (re-search-forward org-ts-regexp end t)
8760 (re-search-forward org-ts-regexp-both end t))
8761 (org-time-string-to-seconds (match-string 0))
8762 (float-time now))))
8763 ((= dcst ?c)
8764 (let ((end (save-excursion (outline-next-heading) (point))))
8765 (if (re-search-forward
8766 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8767 end t)
8768 (org-time-string-to-seconds (match-string 0))
8769 (float-time now))))
8770 ((= dcst ?s)
8771 (let ((end (save-excursion (outline-next-heading) (point))))
8772 (if (re-search-forward org-scheduled-time-regexp end t)
8773 (org-time-string-to-seconds (match-string 1))
8774 (float-time now))))
8775 ((= dcst ?d)
8776 (let ((end (save-excursion (outline-next-heading) (point))))
8777 (if (re-search-forward org-deadline-time-regexp end t)
8778 (org-time-string-to-seconds (match-string 1))
8779 (float-time now))))
8780 ((= dcst ?p)
8781 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8782 (string-to-char (match-string 2))
8783 org-default-priority))
8784 ((= dcst ?r)
8785 (or (org-entry-get nil property) ""))
8786 ((= dcst ?o)
8787 (when (looking-at org-complex-heading-regexp)
8788 (let* ((m (match-string 2))
8789 (s (if (member m org-done-keywords) '- '+)))
8790 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8791 ((= dcst ?f)
8792 (if getkey-func
8793 (progn
8794 (setq tmp (funcall getkey-func))
8795 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8796 tmp)
8797 (error "Invalid key function `%s'" getkey-func)))
8798 (t (error "Invalid sorting type `%c'" sorting-type))))
8800 (cond
8801 ((= dcst ?a) 'org-string-collate-lessp)
8802 ((= dcst ?f)
8803 (or compare-func
8804 (and interactive?
8805 (org-read-function
8806 (concat "Function for comparing keys "
8807 "(empty for default `sort-subr' predicate): ")
8808 'allow-empty))))
8809 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8810 (when restore-clock?
8811 (move-marker org-clock-marker
8812 (1+ (next-single-property-change
8813 start :org-clock-marker-backup)))
8814 (remove-text-properties (1- org-clock-marker) org-clock-marker
8815 '(:org-clock-marker-backup t)))))
8816 (run-hooks 'org-after-sorting-entries-or-items-hook)
8817 (message "Sorting entries...done")))
8819 (defun org-contextualize-keys (alist contexts)
8820 "Return valid elements in ALIST depending on CONTEXTS.
8822 `org-agenda-custom-commands' or `org-capture-templates' are the
8823 values used for ALIST, and `org-agenda-custom-commands-contexts'
8824 or `org-capture-templates-contexts' are the associated contexts
8825 definitions."
8826 (let ((contexts
8827 ;; normalize contexts
8828 (mapcar
8829 (lambda(c) (cond ((listp (cadr c))
8830 (list (car c) (car c) (nth 1 c)))
8831 ((string= "" (cadr c))
8832 (list (car c) (car c) (nth 2 c)))
8833 (t c)))
8834 contexts))
8835 (a alist) r s)
8836 ;; loop over all commands or templates
8837 (dolist (c a)
8838 (let (vrules repl)
8839 (cond
8840 ((not (assoc (car c) contexts))
8841 (push c r))
8842 ((and (assoc (car c) contexts)
8843 (setq vrules (org-contextualize-validate-key
8844 (car c) contexts)))
8845 (mapc (lambda (vr)
8846 (unless (equal (car vr) (cadr vr))
8847 (setq repl vr)))
8848 vrules)
8849 (if (not repl) (push c r)
8850 (push (cadr repl) s)
8851 (push
8852 (cons (car c)
8853 (cdr (or (assoc (cadr repl) alist)
8854 (error "Undefined key `%s' as contextual replacement for `%s'"
8855 (cadr repl) (car c)))))
8856 r))))))
8857 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8858 (delq
8860 (delete-dups
8861 (mapcar (lambda (x)
8862 (let ((tpl (car x)))
8863 (unless (delq
8865 (mapcar (lambda (y)
8866 (equal y tpl))
8868 x)))
8869 (reverse r))))))
8871 (defun org-contextualize-validate-key (key contexts)
8872 "Check CONTEXTS for agenda or capture KEY."
8873 (let (res)
8874 (dolist (r contexts)
8875 (dolist (rr (car (last r)))
8876 (when
8877 (and (equal key (car r))
8878 (if (functionp rr) (funcall rr)
8879 (or (and (eq (car rr) 'in-file)
8880 (buffer-file-name)
8881 (string-match (cdr rr) (buffer-file-name)))
8882 (and (eq (car rr) 'in-mode)
8883 (string-match (cdr rr) (symbol-name major-mode)))
8884 (and (eq (car rr) 'in-buffer)
8885 (string-match (cdr rr) (buffer-name)))
8886 (when (and (eq (car rr) 'not-in-file)
8887 (buffer-file-name))
8888 (not (string-match (cdr rr) (buffer-file-name))))
8889 (when (eq (car rr) 'not-in-mode)
8890 (not (string-match (cdr rr) (symbol-name major-mode))))
8891 (when (eq (car rr) 'not-in-buffer)
8892 (not (string-match (cdr rr) (buffer-name)))))))
8893 (push r res))))
8894 (delete-dups (delq nil res))))
8896 ;; Defined to provide a value for defcustom, since there is no
8897 ;; string-collate-greaterp in Emacs.
8898 (defun org-string-collate-greaterp (s1 s2)
8899 "Return non-nil if S1 is greater than S2 in collation order."
8900 (not (org-string-collate-lessp s1 s2)))
8902 ;;;###autoload
8903 (defun org-run-like-in-org-mode (cmd)
8904 "Run a command, pretending that the current buffer is in Org mode.
8905 This will temporarily bind local variables that are typically bound in
8906 Org mode to the values they have in Org mode, and then interactively
8907 call CMD."
8908 (org-load-modules-maybe)
8909 (let (binds)
8910 (dolist (var (org-get-local-variables))
8911 (when (or (not (boundp (car var)))
8912 (eq (symbol-value (car var))
8913 (default-value (car var))))
8914 (push (list (car var) `(quote ,(cadr var))) binds)))
8915 (eval `(let ,binds
8916 (call-interactively (quote ,cmd))))))
8918 (defun org-get-category (&optional pos force-refresh)
8919 "Get the category applying to position POS."
8920 (save-match-data
8921 (when force-refresh (org-refresh-category-properties))
8922 (let ((pos (or pos (point))))
8923 (or (get-text-property pos 'org-category)
8924 (progn (org-refresh-category-properties)
8925 (get-text-property pos 'org-category))))))
8927 ;;; Refresh properties
8929 (defun org-refresh-properties (dprop tprop)
8930 "Refresh buffer text properties.
8931 DPROP is the drawer property and TPROP is either the
8932 corresponding text property to set, or an alist with each element
8933 being a text property (as a symbol) and a function to apply to
8934 the value of the drawer property."
8935 (let* ((case-fold-search t)
8936 (inhibit-read-only t)
8937 (inherit? (org-property-inherit-p dprop))
8938 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
8939 (global (and inherit? (org--property-global-value dprop nil))))
8940 (org-with-silent-modifications
8941 (org-with-point-at 1
8942 ;; Set global values (e.g., values defined through
8943 ;; "#+PROPERTY:" keywords) to the whole buffer.
8944 (when global (put-text-property (point-min) (point-max) tprop global))
8945 ;; Set local values.
8946 (while (re-search-forward property-re nil t)
8947 (when (org-at-property-p)
8948 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
8949 (outline-next-heading))))))
8951 (defun org-refresh-property (tprop p &optional inherit)
8952 "Refresh the buffer text property TPROP from the drawer property P.
8953 The refresh happens only for the current headline, or the whole
8954 sub-tree if optional argument INHERIT is non-nil."
8955 (unless (org-before-first-heading-p)
8956 (save-excursion
8957 (org-back-to-heading t)
8958 (let ((start (point))
8959 (end (save-excursion
8960 (if inherit (org-end-of-subtree t t)
8961 (or (outline-next-heading) (point-max))))))
8962 (if (symbolp tprop)
8963 ;; TPROP is a text property symbol.
8964 (put-text-property start end tprop p)
8965 ;; TPROP is an alist with (property . function) elements.
8966 (pcase-dolist (`(,prop . ,f) tprop)
8967 (put-text-property start end prop (funcall f p))))))))
8969 (defun org-refresh-category-properties ()
8970 "Refresh category text properties in the buffer."
8971 (let ((case-fold-search t)
8972 (inhibit-read-only t)
8973 (default-category
8974 (cond ((null org-category)
8975 (if buffer-file-name
8976 (file-name-sans-extension
8977 (file-name-nondirectory buffer-file-name))
8978 "???"))
8979 ((symbolp org-category) (symbol-name org-category))
8980 (t org-category))))
8981 (org-with-silent-modifications
8982 (org-with-wide-buffer
8983 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
8984 ;; This is the default category for the buffer. If none is
8985 ;; found, fall-back to `org-category' or buffer file name.
8986 (put-text-property
8987 (point-min) (point-max)
8988 'org-category
8989 (catch 'buffer-category
8990 (goto-char (point-max))
8991 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
8992 (let ((element (org-element-at-point)))
8993 (when (eq (org-element-type element) 'keyword)
8994 (throw 'buffer-category
8995 (org-element-property :value element)))))
8996 default-category))
8997 ;; Set sub-tree specific categories.
8998 (goto-char (point-min))
8999 (let ((regexp (org-re-property "CATEGORY")))
9000 (while (re-search-forward regexp nil t)
9001 (let ((value (match-string-no-properties 3)))
9002 (when (org-at-property-p)
9003 (put-text-property
9004 (save-excursion (org-back-to-heading t) (point))
9005 (save-excursion (org-end-of-subtree t t) (point))
9006 'org-category
9007 value)))))))))
9009 (defun org-refresh-stats-properties ()
9010 "Refresh stats text properties in the buffer."
9011 (org-with-silent-modifications
9012 (org-with-point-at 1
9013 (let ((regexp (concat org-outline-regexp-bol
9014 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9015 (while (re-search-forward regexp nil t)
9016 (let* ((numerator (string-to-number (match-string 1)))
9017 (denominator (and (match-end 2)
9018 (string-to-number (match-string 2))))
9019 (stats (cond ((not denominator) numerator) ;percent
9020 ((= denominator 0) 0)
9021 (t (/ (* numerator 100) denominator)))))
9022 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9023 'org-stats stats)))))))
9025 (defun org-refresh-effort-properties ()
9026 "Refresh effort properties"
9027 (org-refresh-properties
9028 org-effort-property
9029 '((effort . identity)
9030 (effort-minutes . org-duration-to-minutes))))
9032 ;;;; Link Stuff
9034 ;;; Link abbreviations
9036 (defun org-link-expand-abbrev (link)
9037 "Apply replacements as defined in `org-link-abbrev-alist'."
9038 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9039 (let* ((key (match-string 1 link))
9040 (as (or (assoc key org-link-abbrev-alist-local)
9041 (assoc key org-link-abbrev-alist)))
9042 (tag (and (match-end 2) (match-string 3 link)))
9043 rpl)
9044 (if (not as)
9045 link
9046 (setq rpl (cdr as))
9047 (cond
9048 ((symbolp rpl) (funcall rpl tag))
9049 ((string-match "%(\\([^)]+\\))" rpl)
9050 (replace-match
9051 (save-match-data
9052 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9053 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9054 ((string-match "%h" rpl)
9055 (replace-match (url-hexify-string (or tag "")) t t rpl))
9056 (t (concat rpl tag)))))
9057 link))
9059 ;;; Storing and inserting links
9061 (defvar org-insert-link-history nil
9062 "Minibuffer history for links inserted with `org-insert-link'.")
9064 (defvar org-stored-links nil
9065 "Contains the links stored with `org-store-link'.")
9067 (defvar org-store-link-plist nil
9068 "Plist with info about the most recently link created with `org-store-link'.")
9070 (defun org-store-link-functions ()
9071 "Return a list of functions that are called to create and store a link.
9072 The functions defined in the :store property of
9073 `org-link-parameters'.
9075 Each function will be called in turn until one returns a non-nil
9076 value. Each function should check if it is responsible for
9077 creating this link (for example by looking at the major mode).
9078 If not, it must exit and return nil. If yes, it should return
9079 a non-nil value after calling `org-store-link-props' with a list
9080 of properties and values. Special properties are:
9082 :type The link prefix, like \"http\". This must be given.
9083 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9084 This is obligatory as well.
9085 :description Optional default description for the second pair
9086 of brackets in an Org mode link. The user can still change
9087 this when inserting this link into an Org mode buffer.
9089 In addition to these, any additional properties can be specified
9090 and then used in capture templates."
9091 (cl-loop for link in org-link-parameters
9092 with store-func
9093 do (setq store-func (org-link-get-parameter (car link) :store))
9094 if store-func
9095 collect store-func))
9097 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9098 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9100 ;;;###autoload
9101 (defun org-store-link (arg &optional interactive?)
9102 "Store an org-link to the current location.
9103 \\<org-mode-map>
9104 This link is added to `org-stored-links' and can later be inserted
9105 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9107 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9108 A single
9109 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9110 `org-gnus-prefer-web-links' for links to Usenet articles.
9112 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9113 skipping storing functions that are not
9114 part of Org core.
9116 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9117 prefix ARG forces storing a link for each line in the
9118 active region.
9120 Assume the function is called interactively if INTERACTIVE? is
9121 non-nil."
9122 (interactive "P\np")
9123 (org-load-modules-maybe)
9124 (if (and (equal arg '(64)) (org-region-active-p))
9125 (save-excursion
9126 (let ((end (region-end)))
9127 (goto-char (region-beginning))
9128 (set-mark (point))
9129 (while (< (point-at-eol) end)
9130 (move-end-of-line 1) (activate-mark)
9131 (let (current-prefix-arg)
9132 (call-interactively 'org-store-link))
9133 (move-beginning-of-line 2)
9134 (set-mark (point)))))
9135 (setq org-store-link-plist nil)
9136 (let (link cpltxt desc description search txt custom-id agenda-link)
9137 (cond
9138 ;; Store a link using an external link type, if any function is
9139 ;; available. If more than one can generate a link from current
9140 ;; location, ask which one to use.
9141 ((and (not (equal arg '(16)))
9142 (let ((results-alist nil))
9143 (dolist (f (org-store-link-functions))
9144 (when (funcall f)
9145 ;; XXX: return value is not link's plist, so we
9146 ;; store the new value before it is modified. It
9147 ;; would be cleaner to ask store link functions to
9148 ;; return the plist instead.
9149 (push (cons f (copy-sequence org-store-link-plist))
9150 results-alist)))
9151 (pcase results-alist
9152 (`nil nil)
9153 (`((,_ . ,_)) t) ;single choice: nothing to do
9154 (`((,name . ,_) . ,_)
9155 ;; Reinstate link plist associated to the chosen
9156 ;; function.
9157 (apply #'org-store-link-props
9158 (cdr (assoc-string
9159 (completing-read
9160 "Which function for creating the link? "
9161 (mapcar #'car results-alist)
9162 nil t (symbol-name name))
9163 results-alist)))
9164 t))))
9165 (setq link (plist-get org-store-link-plist :link))
9166 (setq desc (or (plist-get org-store-link-plist :description)
9167 link)))
9169 ;; Store a link from a source code buffer.
9170 ((org-src-edit-buffer-p)
9171 (let ((coderef-format (org-src-coderef-format)))
9172 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9173 (setq link (format "(%s)" (match-string-no-properties 3))))
9174 (interactive?
9175 (let ((label (read-string "Code line label: ")))
9176 (end-of-line)
9177 (setq link (format coderef-format label))
9178 (let ((gc (- 79 (length link))))
9179 (if (< (current-column) gc)
9180 (org-move-to-column gc t)
9181 (insert " ")))
9182 (insert link)
9183 (setq link (concat "(" label ")"))
9184 (setq desc nil)))
9185 (t (setq link nil)))))
9187 ;; We are in the agenda, link to referenced location
9188 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9189 (let ((m (or (get-text-property (point) 'org-hd-marker)
9190 (get-text-property (point) 'org-marker))))
9191 (when m
9192 (org-with-point-at m
9193 (setq agenda-link (org-store-link nil interactive?))))))
9195 ((eq major-mode 'calendar-mode)
9196 (let ((cd (calendar-cursor-to-date)))
9197 (setq link
9198 (format-time-string
9199 (car org-time-stamp-formats)
9200 (apply 'encode-time
9201 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9202 nil nil nil))))
9203 (org-store-link-props :type "calendar" :date cd)))
9205 ((eq major-mode 'help-mode)
9206 (setq link (concat "help:" (save-excursion
9207 (goto-char (point-min))
9208 (looking-at "^[^ ]+")
9209 (match-string 0))))
9210 (org-store-link-props :type "help"))
9212 ((eq major-mode 'w3-mode)
9213 (setq cpltxt (if (and (buffer-name)
9214 (not (string-match "Untitled" (buffer-name))))
9215 (buffer-name)
9216 (url-view-url t))
9217 link (url-view-url t))
9218 (org-store-link-props :type "w3" :url (url-view-url t)))
9220 ((eq major-mode 'image-mode)
9221 (setq cpltxt (concat "file:"
9222 (abbreviate-file-name buffer-file-name))
9223 link cpltxt)
9224 (org-store-link-props :type "image" :file buffer-file-name))
9226 ;; In dired, store a link to the file of the current line
9227 ((derived-mode-p 'dired-mode)
9228 (let ((file (dired-get-filename nil t)))
9229 (setq file (if file
9230 (abbreviate-file-name
9231 (expand-file-name (dired-get-filename nil t)))
9232 ;; otherwise, no file so use current directory.
9233 default-directory))
9234 (setq cpltxt (concat "file:" file)
9235 link cpltxt)))
9237 ((setq search (run-hook-with-args-until-success
9238 'org-create-file-search-functions))
9239 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9240 "::" search))
9241 (setq cpltxt (or description link)))
9243 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9244 (org-with-limited-levels
9245 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9246 (cond
9247 ;; Store a link using the target at point
9248 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9249 (setq cpltxt
9250 (concat "file:"
9251 (abbreviate-file-name
9252 (buffer-file-name (buffer-base-buffer)))
9253 "::" (match-string 1))
9254 link cpltxt))
9255 ((and (featurep 'org-id)
9256 (or (eq org-id-link-to-org-use-id t)
9257 (and interactive?
9258 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9259 (and (eq org-id-link-to-org-use-id
9260 'create-if-interactive-and-no-custom-id)
9261 (not custom-id))))
9262 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9263 ;; Store a link using the ID at point
9264 (setq link (condition-case nil
9265 (prog1 (org-id-store-link)
9266 (setq desc (or (plist-get org-store-link-plist
9267 :description)
9268 "")))
9269 (error
9270 ;; Probably before first headline, link only to file
9271 (concat "file:"
9272 (abbreviate-file-name
9273 (buffer-file-name (buffer-base-buffer))))))))
9275 ;; Just link to current headline
9276 (setq cpltxt (concat "file:"
9277 (abbreviate-file-name
9278 (buffer-file-name (buffer-base-buffer)))))
9279 ;; Add a context search string
9280 (when (org-xor org-context-in-file-links
9281 (equal arg '(4)))
9282 (let* ((element (org-element-at-point))
9283 (name (org-element-property :name element)))
9284 (setq txt (cond
9285 ((org-at-heading-p) nil)
9286 (name)
9287 ((org-region-active-p)
9288 (buffer-substring (region-beginning) (region-end)))))
9289 (when (or (null txt) (string-match "\\S-" txt))
9290 (setq cpltxt
9291 (concat cpltxt "::"
9292 (condition-case nil
9293 (org-make-org-heading-search-string txt)
9294 (error "")))
9295 desc (or name
9296 (nth 4 (ignore-errors (org-heading-components)))
9297 "NONE")))))
9298 (when (string-match "::\\'" cpltxt)
9299 (setq cpltxt (substring cpltxt 0 -2)))
9300 (setq link cpltxt)))))
9302 ((buffer-file-name (buffer-base-buffer))
9303 ;; Just link to this file here.
9304 (setq cpltxt (concat "file:"
9305 (abbreviate-file-name
9306 (buffer-file-name (buffer-base-buffer)))))
9307 ;; Add a context string.
9308 (when (org-xor org-context-in-file-links
9309 (equal arg '(4)))
9310 (setq txt (if (org-region-active-p)
9311 (buffer-substring (region-beginning) (region-end))
9312 (buffer-substring (point-at-bol) (point-at-eol))))
9313 ;; Only use search option if there is some text.
9314 (when (string-match "\\S-" txt)
9315 (setq cpltxt
9316 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9317 desc "NONE")))
9318 (setq link cpltxt))
9320 (interactive?
9321 (user-error "No method for storing a link from this buffer"))
9323 (t (setq link nil)))
9325 ;; We're done setting link and desc, clean up
9326 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9327 (setq link (or link cpltxt)
9328 desc (or desc cpltxt))
9329 (cond ((not desc))
9330 ((equal desc "NONE") (setq desc nil))
9331 (t (setq desc
9332 (replace-regexp-in-string
9333 org-bracket-link-analytic-regexp
9334 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9335 desc))))
9336 ;; Return the link
9337 (if (not (and interactive? link))
9338 (or agenda-link (and link (org-make-link-string link desc)))
9339 (push (list link desc) org-stored-links)
9340 (message "Stored: %s" (or desc link))
9341 (when custom-id
9342 (setq link (concat "file:" (abbreviate-file-name
9343 (buffer-file-name)) "::#" custom-id))
9344 (push (list link desc) org-stored-links))
9345 (car org-stored-links)))))
9347 (defun org-store-link-props (&rest plist)
9348 "Store link properties.
9349 The properties are pre-processed by extracting names, addresses
9350 and dates."
9351 (let ((x (plist-get plist :from)))
9352 (when x
9353 (let ((adr (mail-extract-address-components x)))
9354 (setq plist (plist-put plist :fromname (car adr)))
9355 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9356 (let ((x (plist-get plist :to)))
9357 (when x
9358 (let ((adr (mail-extract-address-components x)))
9359 (setq plist (plist-put plist :toname (car adr)))
9360 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9361 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9362 (when x
9363 (setq plist (plist-put plist :date-timestamp
9364 (format-time-string
9365 (org-time-stamp-format t) x)))
9366 (setq plist (plist-put plist :date-timestamp-inactive
9367 (format-time-string
9368 (org-time-stamp-format t t) x)))))
9369 (let ((from (plist-get plist :from))
9370 (to (plist-get plist :to)))
9371 (when (and from to org-from-is-user-regexp)
9372 (setq plist
9373 (plist-put plist :fromto
9374 (if (string-match org-from-is-user-regexp from)
9375 (concat "to %t")
9376 (concat "from %f"))))))
9377 (setq org-store-link-plist plist))
9379 (defun org-add-link-props (&rest plist)
9380 "Add these properties to the link property list."
9381 (let (key value)
9382 (while plist
9383 (setq key (pop plist) value (pop plist))
9384 (setq org-store-link-plist
9385 (plist-put org-store-link-plist key value)))))
9387 (defun org-email-link-description (&optional fmt)
9388 "Return the description part of an email link.
9389 This takes information from `org-store-link-plist' and formats it
9390 according to FMT (default from `org-email-link-description-format')."
9391 (setq fmt (or fmt org-email-link-description-format))
9392 (let* ((p org-store-link-plist)
9393 (to (plist-get p :toaddress))
9394 (from (plist-get p :fromaddress))
9395 (table
9396 (list
9397 (cons "%c" (plist-get p :fromto))
9398 (cons "%F" (plist-get p :from))
9399 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9400 (cons "%T" (plist-get p :to))
9401 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9402 (cons "%s" (plist-get p :subject))
9403 (cons "%d" (plist-get p :date))
9404 (cons "%m" (plist-get p :message-id)))))
9405 (when (string-match "%c" fmt)
9406 ;; Check if the user wrote this message
9407 (if (and org-from-is-user-regexp from to
9408 (save-match-data (string-match org-from-is-user-regexp from)))
9409 (setq fmt (replace-match "to %t" t t fmt))
9410 (setq fmt (replace-match "from %f" t t fmt))))
9411 (org-replace-escapes fmt table)))
9413 (defun org-make-org-heading-search-string (&optional string)
9414 "Make search string for the current headline or STRING."
9415 (let ((s (or string
9416 (and (derived-mode-p 'org-mode)
9417 (save-excursion
9418 (org-back-to-heading t)
9419 (org-element-property :raw-value (org-element-at-point))))))
9420 (lines org-context-in-file-links))
9421 (unless string (setq s (concat "*" s))) ;Add * for headlines
9422 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9423 (when (and string (integerp lines) (> lines 0))
9424 (let ((slines (org-split-string s "\n")))
9425 (when (< lines (length slines))
9426 (setq s (mapconcat
9427 'identity
9428 (reverse (nthcdr (- (length slines) lines)
9429 (reverse slines))) "\n")))))
9430 (mapconcat #'identity (split-string s) " ")))
9432 (defconst org-link-escape-chars
9433 ;;%20 %5B %5D %25
9434 '(?\s ?\[ ?\] ?%)
9435 "List of characters that should be escaped in a link when stored to Org.
9436 This is the list that is used for internal purposes.")
9438 (defun org-make-link-string (link &optional description)
9439 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9440 (unless (org-string-nw-p link) (error "Empty link"))
9441 (let ((uri (cond ((string-match org-link-types-re link)
9442 (concat (match-string 1 link)
9443 (org-link-escape (substring link (match-end 1)))))
9444 ((or (file-name-absolute-p link)
9445 (string-match-p "\\`\\.\\.?/" link))
9446 (org-link-escape link))
9447 ;; For readability, do not encode space characters
9448 ;; in fuzzy links.
9449 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9450 (description
9451 (and (org-string-nw-p description)
9452 ;; Remove brackets from description, as they are fatal.
9453 (replace-regexp-in-string
9454 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9455 (org-trim description)))))
9456 (format "[[%s]%s]"
9458 (if description (format "[%s]" description) ""))))
9460 (defun org-link-escape (text &optional table merge)
9461 "Return percent escaped representation of TEXT.
9462 TEXT is a string with the text to escape.
9463 Optional argument TABLE is a list with characters that should be
9464 escaped. When nil, `org-link-escape-chars' is used.
9465 If optional argument MERGE is set, merge TABLE into
9466 `org-link-escape-chars'."
9467 (let ((characters-to-encode
9468 (cond ((null table) org-link-escape-chars)
9469 (merge (append org-link-escape-chars table))
9470 (t table))))
9471 (mapconcat
9472 (lambda (c)
9473 (if (or (memq c characters-to-encode)
9474 (and org-url-hexify-p (or (< c 32) (> c 126))))
9475 (mapconcat (lambda (e) (format "%%%.2X" e))
9476 (or (encode-coding-char c 'utf-8)
9477 (error "Unable to percent escape character: %c" c))
9479 (char-to-string c)))
9480 text "")))
9482 (defun org-link-unescape (str)
9483 "Unhex hexified Unicode parts in string STR.
9484 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9485 reciprocal of `org-link-escape', which see."
9486 (if (org-string-nw-p str)
9487 (replace-regexp-in-string
9488 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9489 str))
9491 (defun org-link-unescape-compound (hex)
9492 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9493 Note: this function also decodes single byte encodings like
9494 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9495 (save-match-data
9496 (let* ((bytes (cdr (split-string hex "%")))
9497 (ret "")
9498 (eat 0)
9499 (sum 0))
9500 (while bytes
9501 (let* ((val (string-to-number (pop bytes) 16))
9502 (shift-xor
9503 (if (= 0 eat)
9504 (cond
9505 ((>= val 252) (cons 6 252))
9506 ((>= val 248) (cons 5 248))
9507 ((>= val 240) (cons 4 240))
9508 ((>= val 224) (cons 3 224))
9509 ((>= val 192) (cons 2 192))
9510 (t (cons 0 0)))
9511 (cons 6 128))))
9512 (when (>= val 192) (setq eat (car shift-xor)))
9513 (setq val (logxor val (cdr shift-xor)))
9514 (setq sum (+ (lsh sum (car shift-xor)) val))
9515 (when (> eat 0) (setq eat (- eat 1)))
9516 (cond
9517 ((= 0 eat) ;multi byte
9518 (setq ret (concat ret (char-to-string sum)))
9519 (setq sum 0))
9520 ((not bytes) ; single byte(s)
9521 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9522 ret)))
9524 (defun org-link-unescape-single-byte-sequence (hex)
9525 "Unhexify hex-encoded single byte character sequences."
9526 (mapconcat (lambda (byte)
9527 (char-to-string (string-to-number byte 16)))
9528 (cdr (split-string hex "%")) ""))
9530 (defun org-fixup-message-id-for-http (s)
9531 "Replace special characters in a message id, so it can be used in an http query."
9532 (when (string-match "%" s)
9533 (setq s (mapconcat (lambda (c)
9534 (if (eq c ?%)
9535 "%25"
9536 (char-to-string c)))
9537 s "")))
9538 (while (string-match "<" s)
9539 (setq s (replace-match "%3C" t t s)))
9540 (while (string-match ">" s)
9541 (setq s (replace-match "%3E" t t s)))
9542 (while (string-match "@" s)
9543 (setq s (replace-match "%40" t t s)))
9546 (defun org-link-prettify (link)
9547 "Return a human-readable representation of LINK.
9548 The car of LINK must be a raw link.
9549 The cdr of LINK must be either a link description or nil."
9550 (let ((desc (or (cadr link) "<no description>")))
9551 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9552 "<" (car link) ">")))
9554 ;;;###autoload
9555 (defun org-insert-link-global ()
9556 "Insert a link like Org mode does.
9557 This command can be called in any mode to insert a link in Org syntax."
9558 (interactive)
9559 (org-load-modules-maybe)
9560 (org-run-like-in-org-mode 'org-insert-link))
9562 (defun org-insert-all-links (arg &optional pre post)
9563 "Insert all links in `org-stored-links'.
9564 When a universal prefix, do not delete the links from `org-stored-links'.
9565 When `ARG' is a number, insert the last N link(s).
9566 `PRE' and `POST' are optional arguments to define a string to
9567 prepend or to append."
9568 (interactive "P")
9569 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9570 (links (copy-sequence org-stored-links))
9571 (pr (or pre "- "))
9572 (po (or post "\n"))
9573 (cnt 1) l)
9574 (if (null org-stored-links)
9575 (message "No link to insert")
9576 (while (and (or (listp arg) (>= arg cnt))
9577 (setq l (if (listp arg)
9578 (pop links)
9579 (pop org-stored-links))))
9580 (setq cnt (1+ cnt))
9581 (insert pr)
9582 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9583 (insert po)))))
9585 (defun org-insert-last-stored-link (arg)
9586 "Insert the last link stored in `org-stored-links'."
9587 (interactive "p")
9588 (org-insert-all-links arg "" "\n"))
9590 (defun org-link-fontify-links-to-this-file ()
9591 "Fontify links to the current file in `org-stored-links'."
9592 (let ((f (buffer-file-name)) a b)
9593 (setq a (mapcar (lambda(l)
9594 (let ((ll (car l)))
9595 (when (and (string-match "^file:\\(.+\\)::" ll)
9596 (equal f (expand-file-name (match-string 1 ll))))
9597 ll)))
9598 org-stored-links))
9599 (when (featurep 'org-id)
9600 (setq b (mapcar (lambda(l)
9601 (let ((ll (car l)))
9602 (when (and (string-match "^id:\\(.+\\)$" ll)
9603 (equal f (expand-file-name
9604 (or (org-id-find-id-file
9605 (match-string 1 ll)) ""))))
9606 ll)))
9607 org-stored-links)))
9608 (mapcar (lambda(l)
9609 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9610 (delq nil (append a b)))))
9612 (defvar org--links-history nil)
9613 (defun org-insert-link (&optional complete-file link-location default-description)
9614 "Insert a link. At the prompt, enter the link.
9616 Completion can be used to insert any of the link protocol prefixes in use.
9618 The history can be used to select a link previously stored with
9619 `org-store-link'. When the empty string is entered (i.e. if you just
9620 press `RET' at the prompt), the link defaults to the most recently
9621 stored link. As `SPC' triggers completion in the minibuffer, you need to
9622 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9624 You will also be prompted for a description, and if one is given, it will
9625 be displayed in the buffer instead of the link.
9627 If there is already a link at point, this command will allow you to edit
9628 link and description parts.
9630 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9631 file name can be
9632 selected using completion. The path to the file will be relative to the
9633 current directory if the file is in the current directory or a subdirectory.
9634 Otherwise, the link will be the absolute path as completed in the minibuffer
9635 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9636 option `org-link-file-path-type'.
9638 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9639 absolute path even if the file is in
9640 the current directory or below.
9642 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9643 prefix negates `org-keep-stored-link-after-insertion'.
9645 If the LINK-LOCATION parameter is non-nil, this value will be used as
9646 the link location instead of reading one interactively.
9648 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9649 be used as the default description. Otherwise, if
9650 `org-make-link-description-function' is non-nil, this function
9651 will be called with the link target, and the result will be the
9652 default link description. When called non-interactivily, don't
9653 allow to edit the default description."
9654 (interactive "P")
9655 (let* ((wcf (current-window-configuration))
9656 (origbuf (current-buffer))
9657 (region (when (org-region-active-p)
9658 (buffer-substring (region-beginning) (region-end))))
9659 (remove (and region (list (region-beginning) (region-end))))
9660 (desc region)
9661 (link link-location)
9662 (abbrevs org-link-abbrev-alist-local)
9663 entry all-prefixes auto-desc)
9664 (cond
9665 (link-location) ; specified by arg, just use it.
9666 ((org-in-regexp org-bracket-link-regexp 1)
9667 ;; We do have a link at point, and we are going to edit it.
9668 (setq remove (list (match-beginning 0) (match-end 0)))
9669 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9670 (setq link (read-string "Link: "
9671 (org-link-unescape
9672 (match-string-no-properties 1)))))
9673 ((or (org-in-regexp org-angle-link-re)
9674 (org-in-regexp org-plain-link-re))
9675 ;; Convert to bracket link
9676 (setq remove (list (match-beginning 0) (match-end 0))
9677 link (read-string "Link: "
9678 (org-unbracket-string "<" ">" (match-string 0)))))
9679 ((member complete-file '((4) (16)))
9680 ;; Completing read for file names.
9681 (setq link (org-file-complete-link complete-file)))
9683 ;; Read link, with completion for stored links.
9684 (org-link-fontify-links-to-this-file)
9685 (org-switch-to-buffer-other-window "*Org Links*")
9686 (with-current-buffer "*Org Links*"
9687 (erase-buffer)
9688 (insert "Insert a link.
9689 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9690 (when org-stored-links
9691 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9692 (insert (mapconcat 'org-link-prettify
9693 (reverse org-stored-links) "\n")))
9694 (goto-char (point-min)))
9695 (let ((cw (selected-window)))
9696 (select-window (get-buffer-window "*Org Links*" 'visible))
9697 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9698 (unless (pos-visible-in-window-p (point-max))
9699 (org-fit-window-to-buffer))
9700 (and (window-live-p cw) (select-window cw)))
9701 (setq all-prefixes (append (mapcar 'car abbrevs)
9702 (mapcar 'car org-link-abbrev-alist)
9703 (org-link-types)))
9704 (unwind-protect
9705 ;; Fake a link history, containing the stored links.
9706 (let ((org--links-history
9707 (append (mapcar #'car org-stored-links)
9708 org-insert-link-history)))
9709 (setq link
9710 (org-completing-read
9711 "Link: "
9712 (append
9713 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9714 (mapcar #'car org-stored-links))
9715 nil nil nil
9716 'org--links-history
9717 (caar org-stored-links)))
9718 (unless (org-string-nw-p link) (user-error "No link selected"))
9719 (dolist (l org-stored-links)
9720 (when (equal link (cadr l))
9721 (setq link (car l))
9722 (setq auto-desc t)))
9723 (when (or (member link all-prefixes)
9724 (and (equal ":" (substring link -1))
9725 (member (substring link 0 -1) all-prefixes)
9726 (setq link (substring link 0 -1))))
9727 (setq link (with-current-buffer origbuf
9728 (org-link-try-special-completion link)))))
9729 (set-window-configuration wcf)
9730 (kill-buffer "*Org Links*"))
9731 (setq entry (assoc link org-stored-links))
9732 (or entry (push link org-insert-link-history))
9733 (setq desc (or desc (nth 1 entry)))))
9735 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9736 (not org-keep-stored-link-after-insertion))
9737 (setq org-stored-links (delq (assoc link org-stored-links)
9738 org-stored-links)))
9740 (when (and (string-match org-plain-link-re link)
9741 (not (string-match org-ts-regexp link)))
9742 ;; URL-like link, normalize the use of angular brackets.
9743 (setq link (org-unbracket-string "<" ">" link)))
9745 ;; Check if we are linking to the current file with a search
9746 ;; option If yes, simplify the link by using only the search
9747 ;; option.
9748 (when (and buffer-file-name
9749 (let ((case-fold-search nil))
9750 (string-match "\\`file:\\(.+?\\)::" link)))
9751 (let ((path (match-string-no-properties 1 link))
9752 (search (substring-no-properties link (match-end 0))))
9753 (save-match-data
9754 (when (equal (file-truename buffer-file-name) (file-truename path))
9755 ;; We are linking to this same file, with a search option
9756 (setq link search)))))
9758 ;; Check if we can/should use a relative path. If yes, simplify
9759 ;; the link.
9760 (let ((case-fold-search nil))
9761 (when (string-match "\\`\\(file\\|docview\\):" link)
9762 (let* ((type (match-string-no-properties 0 link))
9763 (path-start (match-end 0))
9764 (search (and (string-match "::\\(.*\\)\\'" link)
9765 (match-string 1 link)))
9766 (path
9767 (if search
9768 (substring-no-properties
9769 link path-start (match-beginning 0))
9770 (substring-no-properties link (match-end 0))))
9771 (origpath path))
9772 (cond
9773 ((or (eq org-link-file-path-type 'absolute)
9774 (equal complete-file '(16)))
9775 (setq path (abbreviate-file-name (expand-file-name path))))
9776 ((eq org-link-file-path-type 'noabbrev)
9777 (setq path (expand-file-name path)))
9778 ((eq org-link-file-path-type 'relative)
9779 (setq path (file-relative-name path)))
9781 (save-match-data
9782 (if (string-match (concat "^" (regexp-quote
9783 (expand-file-name
9784 (file-name-as-directory
9785 default-directory))))
9786 (expand-file-name path))
9787 ;; We are linking a file with relative path name.
9788 (setq path (substring (expand-file-name path)
9789 (match-end 0)))
9790 (setq path (abbreviate-file-name (expand-file-name path)))))))
9791 (setq link (concat type path (and search (concat "::" search))))
9792 (when (equal desc origpath)
9793 (setq desc path)))))
9795 (unless auto-desc
9796 (let ((initial-input
9797 (cond
9798 (default-description)
9799 ((not org-make-link-description-function) desc)
9800 (t (condition-case nil
9801 (funcall org-make-link-description-function link desc)
9802 (error
9803 (message "Can't get link description from `%s'"
9804 (symbol-name org-make-link-description-function))
9805 (sit-for 2)
9806 nil))))))
9807 (setq desc (if (called-interactively-p 'any)
9808 (read-string "Description: " initial-input)
9809 initial-input))))
9811 (unless (string-match "\\S-" desc) (setq desc nil))
9812 (when remove (apply 'delete-region remove))
9813 (insert (org-make-link-string link desc))
9814 ;; Redisplay so as the new link has proper invisible characters.
9815 (sit-for 0)))
9817 (defun org-link-try-special-completion (type)
9818 "If there is completion support for link type TYPE, offer it."
9819 (let ((fun (org-link-get-parameter type :complete)))
9820 (if (functionp fun)
9821 (funcall fun)
9822 (read-string "Link (no completion support): " (concat type ":")))))
9824 (defun org-file-complete-link (&optional arg)
9825 "Create a file link using completion."
9826 (let ((file (read-file-name "File: "))
9827 (pwd (file-name-as-directory (expand-file-name ".")))
9828 (pwd1 (file-name-as-directory (abbreviate-file-name
9829 (expand-file-name ".")))))
9830 (cond ((equal arg '(16))
9831 (concat "file:"
9832 (abbreviate-file-name (expand-file-name file))))
9833 ((string-match
9834 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9835 (concat "file:" (match-string 1 file)))
9836 ((string-match
9837 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9838 (expand-file-name file))
9839 (concat "file:"
9840 (match-string 1 (expand-file-name file))))
9841 (t (concat "file:" file)))))
9844 ;;; Opening/following a link
9846 (defvar org-link-search-failed nil)
9848 (defvar org-open-link-functions nil
9849 "Hook for functions finding a plain text link.
9850 These functions must take a single argument, the link content.
9851 They will be called for links that look like [[link text][description]]
9852 when LINK TEXT does not have a protocol like \"http:\" and does not look
9853 like a filename (e.g. \"./blue.png\").
9855 These functions will be called *before* Org attempts to resolve the
9856 link by doing text searches in the current buffer - so if you want a
9857 link \"[[target]]\" to still find \"<<target>>\", your function should
9858 handle this as a special case.
9860 When the function does handle the link, it must return a non-nil value.
9861 If it decides that it is not responsible for this link, it must return
9862 nil to indicate that that Org can continue with other options like
9863 exact and fuzzy text search.")
9865 (defun org-next-link (&optional search-backward)
9866 "Move forward to the next link.
9867 If the link is in hidden text, expose it."
9868 (interactive "P")
9869 (when (and org-link-search-failed (eq this-command last-command))
9870 (goto-char (point-min))
9871 (message "Link search wrapped back to beginning of buffer"))
9872 (setq org-link-search-failed nil)
9873 (let* ((pos (point))
9874 (ct (org-context))
9875 (a (assq :link ct))
9876 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9877 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9878 ((looking-at org-any-link-re)
9879 ;; Don't stay stuck at link without an org-link face
9880 (forward-char (if search-backward -1 1))))
9881 (if (funcall srch-fun org-any-link-re nil t)
9882 (progn
9883 (goto-char (match-beginning 0))
9884 (when (org-invisible-p) (org-show-context)))
9885 (goto-char pos)
9886 (setq org-link-search-failed t)
9887 (message "No further link found"))))
9889 (defun org-previous-link ()
9890 "Move backward to the previous link.
9891 If the link is in hidden text, expose it."
9892 (interactive)
9893 (funcall 'org-next-link t))
9895 (defun org-translate-link (s)
9896 "Translate a link string if a translation function has been defined."
9897 (with-temp-buffer
9898 (insert (org-trim s))
9899 (org-trim (org-element-interpret-data (org-element-context)))))
9901 (defun org-translate-link-from-planner (type path)
9902 "Translate a link from Emacs Planner syntax so that Org can follow it.
9903 This is still an experimental function, your mileage may vary."
9904 (cond
9905 ((member type '("http" "https" "news" "ftp"))
9906 ;; standard Internet links are the same.
9907 nil)
9908 ((and (equal type "irc") (string-match "^//" path))
9909 ;; Planner has two / at the beginning of an irc link, we have 1.
9910 ;; We should have zero, actually....
9911 (setq path (substring path 1)))
9912 ((and (equal type "lisp") (string-match "^/" path))
9913 ;; Planner has a slash, we do not.
9914 (setq type "elisp" path (substring path 1)))
9915 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9916 ;; A typical message link. Planner has the id after the final slash,
9917 ;; we separate it with a hash mark
9918 (setq path (concat (match-string 1 path) "#"
9919 (org-unbracket-string "<" ">" (match-string 2 path))))))
9920 (cons type path))
9922 (defun org-find-file-at-mouse (ev)
9923 "Open file link or URL at mouse."
9924 (interactive "e")
9925 (mouse-set-point ev)
9926 (org-open-at-point 'in-emacs))
9928 (defun org-open-at-mouse (ev)
9929 "Open file link or URL at mouse.
9930 See the docstring of `org-open-file' for details."
9931 (interactive "e")
9932 (mouse-set-point ev)
9933 (when (eq major-mode 'org-agenda-mode)
9934 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9935 (org-open-at-point))
9937 (defvar org-window-config-before-follow-link nil
9938 "The window configuration before following a link.
9939 This is saved in case the need arises to restore it.")
9941 ;;;###autoload
9942 (defun org-open-at-point-global ()
9943 "Follow a link or time-stamp like Org mode does.
9944 This command can be called in any mode to follow an external link
9945 or a time-stamp that has Org mode syntax. Its behavior is
9946 undefined when called on internal links (e.g., fuzzy links).
9947 Raise an error when there is nothing to follow. "
9948 (interactive)
9949 (cond ((org-in-regexp org-any-link-re)
9950 (org-open-link-from-string (match-string-no-properties 0)))
9951 ((or (org-in-regexp org-ts-regexp-both nil t)
9952 (org-in-regexp org-tsr-regexp-both nil t))
9953 (org-follow-timestamp-link))
9954 (t (user-error "No link found"))))
9956 ;;;###autoload
9957 (defun org-open-link-from-string (s &optional arg reference-buffer)
9958 "Open a link in the string S, as if it was in Org mode."
9959 (interactive "sLink: \nP")
9960 (let ((reference-buffer (or reference-buffer (current-buffer))))
9961 (with-temp-buffer
9962 (let ((org-inhibit-startup (not reference-buffer)))
9963 (org-mode)
9964 (insert s)
9965 (goto-char (point-min))
9966 (when reference-buffer
9967 (setq org-link-abbrev-alist-local
9968 (with-current-buffer reference-buffer
9969 org-link-abbrev-alist-local)))
9970 (org-open-at-point arg reference-buffer)))))
9972 (defvar org-open-at-point-functions nil
9973 "Hook that is run when following a link at point.
9975 Functions in this hook must return t if they identify and follow
9976 a link at point. If they don't find anything interesting at point,
9977 they must return nil.")
9979 (defvar org-link-search-inhibit-query nil)
9980 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
9981 (defun org--open-doi-link (path)
9982 "Open a \"doi\" type link.
9983 PATH is a the path to search for, as a string."
9984 (browse-url (url-encode-url (concat org-doi-server-url path))))
9986 (defun org--open-elisp-link (path)
9987 "Open a \"elisp\" type link.
9988 PATH is the sexp to evaluate, as a string."
9989 (let ((cmd path))
9990 (if (or (and (org-string-nw-p
9991 org-confirm-elisp-link-not-regexp)
9992 (string-match-p org-confirm-elisp-link-not-regexp cmd))
9993 (not org-confirm-elisp-link-function)
9994 (funcall org-confirm-elisp-link-function
9995 (format "Execute \"%s\" as elisp? "
9996 (org-add-props cmd nil 'face 'org-warning))))
9997 (message "%s => %s" cmd
9998 (if (eq (string-to-char cmd) ?\()
9999 (eval (read cmd))
10000 (call-interactively (read cmd))))
10001 (user-error "Abort"))))
10003 (defun org--open-help-link (path)
10004 "Open a \"help\" type link.
10005 PATH is a symbol name, as a string."
10006 (pcase (intern path)
10007 ((and (pred fboundp) variable) (describe-function variable))
10008 ((and (pred boundp) function) (describe-variable function))
10009 (name (user-error "Unknown function or variable: %s" name))))
10011 (defun org--open-shell-link (path)
10012 "Open a \"shell\" type link.
10013 PATH is the command to execute, as a string."
10014 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10015 (cmd path))
10016 (if (or (and (org-string-nw-p
10017 org-confirm-shell-link-not-regexp)
10018 (string-match
10019 org-confirm-shell-link-not-regexp cmd))
10020 (not org-confirm-shell-link-function)
10021 (funcall org-confirm-shell-link-function
10022 (format "Execute \"%s\" in shell? "
10023 (org-add-props cmd nil
10024 'face 'org-warning))))
10025 (progn
10026 (message "Executing %s" cmd)
10027 (shell-command cmd buf)
10028 (when (featurep 'midnight)
10029 (setq clean-buffer-list-kill-buffer-names
10030 (cons (buffer-name buf)
10031 clean-buffer-list-kill-buffer-names))))
10032 (user-error "Abort"))))
10034 (defun org-open-at-point (&optional arg reference-buffer)
10035 "Open link, timestamp, footnote or tags at point.
10037 When point is on a link, follow it. Normally, files will be
10038 opened by an appropriate application. If the optional prefix
10039 argument ARG is non-nil, Emacs will visit the file. With
10040 a double prefix argument, try to open outside of Emacs, in the
10041 application the system uses for this file type.
10043 When point is on a timestamp, open the agenda at the day
10044 specified.
10046 When point is a footnote definition, move to the first reference
10047 found. If it is on a reference, move to the associated
10048 definition.
10050 When point is on a headline, display a list of every link in the
10051 entry, so it is possible to pick one, or all, of them. If point
10052 is on a tag, call `org-tags-view' instead.
10054 When optional argument REFERENCE-BUFFER is non-nil, it should
10055 specify a buffer from where the link search should happen. This
10056 is used internally by `org-open-link-from-string'.
10058 On top of syntactically correct links, this function will also
10059 try to open links and time-stamps in comments, example
10060 blocks... i.e., whenever point is on something looking like
10061 a timestamp or a link."
10062 (interactive "P")
10063 ;; On a code block, open block's results.
10064 (unless (call-interactively 'org-babel-open-src-block-result)
10065 (org-load-modules-maybe)
10066 (setq org-window-config-before-follow-link (current-window-configuration))
10067 (org-remove-occur-highlights nil nil t)
10068 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10069 (let* ((context
10070 ;; Only consider supported types, even if they are not
10071 ;; the closest one.
10072 (org-element-lineage
10073 (org-element-context)
10074 '(clock footnote-definition footnote-reference headline
10075 inlinetask link timestamp)
10077 (type (org-element-type context))
10078 (value (org-element-property :value context)))
10079 (cond
10080 ;; On a headline or an inlinetask, but not on a timestamp,
10081 ;; a link, a footnote reference.
10082 ((memq type '(headline inlinetask))
10083 (org-match-line org-complex-heading-regexp)
10084 (if (and (match-beginning 5)
10085 (>= (point) (match-beginning 5))
10086 (< (point) (match-end 5)))
10087 ;; On tags.
10088 (org-tags-view arg (substring (match-string 5) 0 -1))
10089 ;; Not on tags.
10090 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10091 (`(nil . ,_)
10092 (require 'org-attach)
10093 (org-attach-reveal 'if-exists))
10094 (`(,links . ,links-end)
10095 (dolist (link (if (stringp links) (list links) links))
10096 (search-forward link nil links-end)
10097 (goto-char (match-beginning 0))
10098 (org-open-at-point))))))
10099 ;; On a footnote reference or at definition's label.
10100 ((or (eq type 'footnote-reference)
10101 (and (eq type 'footnote-definition)
10102 (save-excursion
10103 ;; Do not validate action when point is on the
10104 ;; spaces right after the footnote label, in
10105 ;; order to be on par with behavior on links.
10106 (skip-chars-forward " \t")
10107 (let ((begin
10108 (org-element-property :contents-begin context)))
10109 (if begin (< (point) begin)
10110 (= (org-element-property :post-affiliated context)
10111 (line-beginning-position)))))))
10112 (org-footnote-action))
10113 ;; No valid context. Ignore catch-all types like `headline'.
10114 ;; If point is on something looking like a link or
10115 ;; a time-stamp, try opening it. It may be useful in
10116 ;; comments, example blocks...
10117 ((memq type '(footnote-definition headline inlinetask nil))
10118 (call-interactively #'org-open-at-point-global))
10119 ;; On a clock line, make sure point is on the timestamp
10120 ;; before opening it.
10121 ((and (eq type 'clock)
10122 value
10123 (>= (point) (org-element-property :begin value))
10124 (<= (point) (org-element-property :end value)))
10125 (org-follow-timestamp-link))
10126 ;; Do nothing on white spaces after an object.
10127 ((>= (point)
10128 (save-excursion
10129 (goto-char (org-element-property :end context))
10130 (skip-chars-backward " \t")
10131 (point)))
10132 (user-error "No link found"))
10133 ((eq type 'timestamp) (org-follow-timestamp-link))
10134 ((eq type 'link)
10135 (let ((type (org-element-property :type context))
10136 (path (org-link-unescape (org-element-property :path context))))
10137 ;; Switch back to REFERENCE-BUFFER needed when called in
10138 ;; a temporary buffer through `org-open-link-from-string'.
10139 (with-current-buffer (or reference-buffer (current-buffer))
10140 (cond
10141 ((equal type "file")
10142 (if (string-match "[*?{]" (file-name-nondirectory path))
10143 (dired path)
10144 ;; Look into `org-link-parameters' in order to find
10145 ;; a DEDICATED-FUNCTION to open file. The function
10146 ;; will be applied on raw link instead of parsed
10147 ;; link due to the limitation in `org-add-link-type'
10148 ;; ("open" function called with a single argument).
10149 ;; If no such function is found, fallback to
10150 ;; `org-open-file'.
10151 (let* ((option (org-element-property :search-option context))
10152 (app (org-element-property :application context))
10153 (dedicated-function
10154 (org-link-get-parameter
10155 (if app (concat type "+" app) type)
10156 :follow)))
10157 (if dedicated-function
10158 (funcall dedicated-function
10159 (concat path
10160 (and option (concat "::" option))))
10161 (apply #'org-open-file
10162 path
10163 (cond (arg)
10164 ((equal app "emacs") 'emacs)
10165 ((equal app "sys") 'system))
10166 (cond ((not option) nil)
10167 ((string-match-p "\\`[0-9]+\\'" option)
10168 (list (string-to-number option)))
10169 (t (list nil
10170 (org-link-unescape option)))))))))
10171 ((functionp (org-link-get-parameter type :follow))
10172 (funcall (org-link-get-parameter type :follow) path))
10173 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10174 (unless (run-hook-with-args-until-success
10175 'org-open-link-functions path)
10176 (if (not arg) (org-mark-ring-push)
10177 (switch-to-buffer-other-window
10178 (org-get-buffer-for-internal-link (current-buffer))))
10179 (let ((destination
10180 (org-with-wide-buffer
10181 (if (equal type "radio")
10182 (org-search-radio-target
10183 (org-element-property :path context))
10184 (org-link-search
10185 (if (member type '("custom-id" "coderef"))
10186 (org-element-property :raw-link context)
10187 path)
10188 ;; Prevent fuzzy links from matching
10189 ;; themselves.
10190 (and (equal type "fuzzy")
10191 (+ 2 (org-element-property :begin context)))))
10192 (point))))
10193 (unless (and (<= (point-min) destination)
10194 (>= (point-max) destination))
10195 (widen))
10196 (goto-char destination))))
10197 (t (browse-url-at-point))))))
10198 (t (user-error "No link found")))))
10199 (run-hook-with-args 'org-follow-link-hook)))
10201 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10202 "Offer links in the current entry and return the selected link.
10203 If there is only one link, return it.
10204 If NTH is an integer, return the NTH link found.
10205 If ZERO is a string, check also this string for a link, and if
10206 there is one, return it."
10207 (with-current-buffer buffer
10208 (org-with-wide-buffer
10209 (goto-char marker)
10210 (let ((cnt ?0)
10211 have-zero end links link c)
10212 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10213 (push (match-string 0 zero) links)
10214 (setq cnt (1- cnt) have-zero t))
10215 (save-excursion
10216 (org-back-to-heading t)
10217 (setq end (save-excursion (outline-next-heading) (point)))
10218 (while (re-search-forward org-any-link-re end t)
10219 (push (match-string 0) links))
10220 (setq links (org-uniquify (reverse links))))
10221 (cond
10222 ((null links)
10223 (message "No links"))
10224 ((equal (length links) 1)
10225 (setq link (car links)))
10226 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10227 (setq link (nth (if have-zero nth (1- nth)) links)))
10228 (t ; we have to select a link
10229 (save-excursion
10230 (save-window-excursion
10231 (delete-other-windows)
10232 (with-output-to-temp-buffer "*Select Link*"
10233 (dolist (l links)
10234 (cond
10235 ((not (string-match org-bracket-link-regexp l))
10236 (princ (format "[%c] %s\n" (cl-incf cnt)
10237 (org-unbracket-string "<" ">" l))))
10238 ((match-end 3)
10239 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10240 (match-string 3 l) (match-string 1 l))))
10241 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10242 (match-string 1 l)))))))
10243 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10244 (message "Select link to open, RET to open all:")
10245 (setq c (read-char-exclusive))
10246 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10247 (when (equal c ?q) (user-error "Abort"))
10248 (if (equal c ?\C-m)
10249 (setq link links)
10250 (setq nth (- c ?0))
10251 (when have-zero (setq nth (1+ nth)))
10252 (unless (and (integerp nth) (>= (length links) nth))
10253 (user-error "Invalid link selection"))
10254 (setq link (nth (1- nth) links)))))
10255 (cons link end)))))
10257 ;; TODO: These functions are deprecated since `org-open-at-point'
10258 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10259 (defun org-open-file-with-system (path)
10260 "Open file at PATH using the system way of opening it."
10261 (org-open-file path 'system))
10262 (defun org-open-file-with-emacs (path)
10263 "Open file at PATH in Emacs."
10264 (org-open-file path 'emacs))
10267 ;;; File search
10269 (defvar org-create-file-search-functions nil
10270 "List of functions to construct the right search string for a file link.
10271 These functions are called in turn with point at the location to
10272 which the link should point.
10274 A function in the hook should first test if it would like to
10275 handle this file type, for example by checking the `major-mode'
10276 or the file extension. If it decides not to handle this file, it
10277 should just return nil to give other functions a chance. If it
10278 does handle the file, it must return the search string to be used
10279 when following the link. The search string will be part of the
10280 file link, given after a double colon, and `org-open-at-point'
10281 will automatically search for it. If special measures must be
10282 taken to make the search successful, another function should be
10283 added to the companion hook `org-execute-file-search-functions',
10284 which see.
10286 A function in this hook may also use `setq' to set the variable
10287 `description' to provide a suggestion for the descriptive text to
10288 be used for this link when it gets inserted into an Org buffer
10289 with \\[org-insert-link].")
10291 (defvar org-execute-file-search-functions nil
10292 "List of functions to execute a file search triggered by a link.
10294 Functions added to this hook must accept a single argument, the
10295 search string that was part of the file link, the part after the
10296 double colon. The function must first check if it would like to
10297 handle this search, for example by checking the `major-mode' or
10298 the file extension. If it decides not to handle this search, it
10299 should just return nil to give other functions a chance. If it
10300 does handle the search, it must return a non-nil value to keep
10301 other functions from trying.
10303 Each function can access the current prefix argument through the
10304 variable `current-prefix-arg'. Note that a single prefix is used
10305 to force opening a link in Emacs, so it may be good to only use a
10306 numeric or double prefix to guide the search function.
10308 In case this is needed, a function in this hook can also restore
10309 the window configuration before `org-open-at-point' was called using:
10311 (set-window-configuration org-window-config-before-follow-link)")
10313 (defun org-search-radio-target (target)
10314 "Search a radio target matching TARGET in current buffer.
10315 White spaces are not significant."
10316 (let ((re (format "<<<%s>>>"
10317 (mapconcat #'regexp-quote
10318 (split-string target)
10319 "[ \t]+\\(?:\n[ \t]*\\)?")))
10320 (origin (point)))
10321 (goto-char (point-min))
10322 (catch :radio-match
10323 (while (re-search-forward re nil t)
10324 (backward-char)
10325 (let ((object (org-element-context)))
10326 (when (eq (org-element-type object) 'radio-target)
10327 (goto-char (org-element-property :begin object))
10328 (org-show-context 'link-search)
10329 (throw :radio-match nil))))
10330 (goto-char origin)
10331 (user-error "No match for radio target: %s" target))))
10333 (defun org-link-search (s &optional avoid-pos stealth)
10334 "Search for a search string S.
10336 If S starts with \"#\", it triggers a custom ID search.
10338 If S is enclosed within parenthesis, it initiates a coderef
10339 search.
10341 If S is surrounded by forward slashes, it is interpreted as
10342 a regular expression. In Org mode files, this will create an
10343 `org-occur' sparse tree. In ordinary files, `occur' will be used
10344 to list matches. If the current buffer is in `dired-mode', grep
10345 will be used to search in all files.
10347 When AVOID-POS is given, ignore matches near that position.
10349 When optional argument STEALTH is non-nil, do not modify
10350 visibility around point, thus ignoring `org-show-context-detail'
10351 variable.
10353 Search is case-insensitive and ignores white spaces. Return type
10354 of matched result, which is either `dedicated' or `fuzzy'."
10355 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10356 (let* ((case-fold-search t)
10357 (origin (point))
10358 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10359 (starred (eq (string-to-char normalized) ?*))
10360 (words (split-string (if starred (substring s 1) s)))
10361 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10362 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10363 type)
10364 (cond
10365 ;; Check if there are any special search functions.
10366 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10367 ((eq (string-to-char s) ?#)
10368 ;; Look for a custom ID S if S starts with "#".
10369 (let* ((id (substring normalized 1))
10370 (match (org-find-property "CUSTOM_ID" id)))
10371 (if match (progn (goto-char match) (setf type 'dedicated))
10372 (error "No match for custom ID: %s" id))))
10373 ((string-match "\\`(\\(.*\\))\\'" normalized)
10374 ;; Look for coderef targets if S is enclosed within parenthesis.
10375 (let ((coderef (match-string-no-properties 1 normalized))
10376 (re (substring s-single-re 1 -1)))
10377 (goto-char (point-min))
10378 (catch :coderef-match
10379 (while (re-search-forward re nil t)
10380 (let ((element (org-element-at-point)))
10381 (when (and (memq (org-element-type element)
10382 '(example-block src-block))
10383 ;; Build proper regexp according to current
10384 ;; block's label format.
10385 (let ((label-fmt
10386 (regexp-quote
10387 (or (org-element-property :label-fmt element)
10388 org-coderef-label-format))))
10389 (save-excursion
10390 (beginning-of-line)
10391 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10392 (format label-fmt coderef))))))
10393 (setq type 'dedicated)
10394 (goto-char (match-beginning 1))
10395 (throw :coderef-match nil))))
10396 (goto-char origin)
10397 (error "No match for coderef: %s" coderef))))
10398 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10399 ;; Look for a regular expression.
10400 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10401 (match-string 1 s)))
10402 ;; From here, we handle fuzzy links.
10404 ;; Look for targets, only if not in a headline search.
10405 ((and (not starred)
10406 (let ((target (format "<<%s>>" s-multi-re)))
10407 (catch :target-match
10408 (goto-char (point-min))
10409 (while (re-search-forward target nil t)
10410 (backward-char)
10411 (let ((context (org-element-context)))
10412 (when (eq (org-element-type context) 'target)
10413 (setq type 'dedicated)
10414 (goto-char (org-element-property :begin context))
10415 (throw :target-match t))))
10416 nil))))
10417 ;; Look for elements named after S, only if not in a headline
10418 ;; search.
10419 ((and (not starred)
10420 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10421 (catch :name-match
10422 (goto-char (point-min))
10423 (while (re-search-forward name nil t)
10424 (let ((element (org-element-at-point)))
10425 (when (equal words
10426 (split-string
10427 (org-element-property :name element)))
10428 (setq type 'dedicated)
10429 (beginning-of-line)
10430 (throw :name-match t))))
10431 nil))))
10432 ;; Regular text search. Prefer headlines in Org mode buffers.
10433 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10434 ;; statistics cookies and tags.
10435 ((and (derived-mode-p 'org-mode)
10436 (let ((title-re
10437 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10438 org-outline-regexp-bol
10439 org-comment-string
10440 (mapconcat #'regexp-quote words ".+")))
10441 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10442 (comment-re (eval-when-compile
10443 (format "\\`%s[ \t]+" org-comment-string))))
10444 (goto-char (point-min))
10445 (catch :found
10446 (while (re-search-forward title-re nil t)
10447 (when (equal words
10448 (split-string
10449 (replace-regexp-in-string
10450 cookie-re ""
10451 (replace-regexp-in-string
10452 comment-re "" (org-get-heading t t t)))))
10453 (throw :found t)))
10454 nil)))
10455 (beginning-of-line)
10456 (setq type 'dedicated))
10457 ;; Offer to create non-existent headline depending on
10458 ;; `org-link-search-must-match-exact-headline'.
10459 ((and (derived-mode-p 'org-mode)
10460 (not org-link-search-inhibit-query)
10461 (eq org-link-search-must-match-exact-headline 'query-to-create)
10462 (yes-or-no-p "No match - create this as a new heading? "))
10463 (goto-char (point-max))
10464 (unless (bolp) (newline))
10465 (org-insert-heading nil t t)
10466 (insert s "\n")
10467 (beginning-of-line 0))
10468 ;; Only headlines are looked after. No need to process
10469 ;; further: throw an error.
10470 ((and (derived-mode-p 'org-mode)
10471 (or starred org-link-search-must-match-exact-headline))
10472 (goto-char origin)
10473 (error "No match for fuzzy expression: %s" normalized))
10474 ;; Regular text search.
10475 ((catch :fuzzy-match
10476 (goto-char (point-min))
10477 (while (re-search-forward s-multi-re nil t)
10478 ;; Skip match if it contains AVOID-POS or it is included in
10479 ;; a link with a description but outside the description.
10480 (unless (or (and avoid-pos
10481 (<= (match-beginning 0) avoid-pos)
10482 (> (match-end 0) avoid-pos))
10483 (and (save-match-data
10484 (org-in-regexp org-bracket-link-regexp))
10485 (match-beginning 3)
10486 (or (> (match-beginning 3) (point))
10487 (<= (match-end 3) (point)))
10488 (org-element-lineage
10489 (save-match-data (org-element-context))
10490 '(link) t)))
10491 (goto-char (match-beginning 0))
10492 (setq type 'fuzzy)
10493 (throw :fuzzy-match t)))
10494 nil))
10495 ;; All failed. Throw an error.
10496 (t (goto-char origin)
10497 (error "No match for fuzzy expression: %s" normalized)))
10498 ;; Disclose surroundings of match, if appropriate.
10499 (when (and (derived-mode-p 'org-mode) (not stealth))
10500 (org-show-context 'link-search))
10501 type))
10503 (defun org-get-buffer-for-internal-link (buffer)
10504 "Return a buffer to be used for displaying the link target of internal links."
10505 (cond
10506 ((not org-display-internal-link-with-indirect-buffer)
10507 buffer)
10508 ((string-suffix-p "(Clone)" (buffer-name buffer))
10509 (message "Buffer is already a clone, not making another one")
10510 ;; we also do not modify visibility in this case
10511 buffer)
10512 (t ; make a new indirect buffer for displaying the link
10513 (let* ((bn (buffer-name buffer))
10514 (ibn (concat bn "(Clone)"))
10515 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10516 (with-current-buffer ib (org-overview))
10517 ib))))
10519 (defun org-do-occur (regexp &optional cleanup)
10520 "Call the Emacs command `occur'.
10521 If CLEANUP is non-nil, remove the printout of the regular expression
10522 in the *Occur* buffer. This is useful if the regex is long and not useful
10523 to read."
10524 (occur regexp)
10525 (when cleanup
10526 (let ((cwin (selected-window)) win beg end)
10527 (when (setq win (get-buffer-window "*Occur*"))
10528 (select-window win))
10529 (goto-char (point-min))
10530 (when (re-search-forward "match[a-z]+" nil t)
10531 (setq beg (match-end 0))
10532 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10533 (setq end (1- (match-beginning 0)))))
10534 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10535 (goto-char (point-min))
10536 (select-window cwin))))
10539 ;;; The Mark Ring
10541 (defvar org-mark-ring nil
10542 "Mark ring for positions before jumps in Org mode.")
10544 (defvar org-mark-ring-last-goto nil
10545 "Last position in the mark ring used to go back.")
10547 ;; Fill and close the ring
10548 (setq org-mark-ring nil)
10549 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10551 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10552 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10553 org-mark-ring)
10555 (defun org-mark-ring-push (&optional pos buffer)
10556 "Put the current position into the mark ring and rotate it.
10557 Also push position into the Emacs mark ring. If optional
10558 argument POS and BUFFER are not nil, mark this location instead."
10559 (interactive)
10560 (let ((pos (or pos (point)))
10561 (buffer (or buffer (current-buffer))))
10562 (with-current-buffer buffer
10563 (org-with-point-at pos (push-mark nil t)))
10564 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10565 (move-marker (car org-mark-ring) pos buffer))
10566 (message
10567 (substitute-command-keys
10568 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10570 (defun org-mark-ring-goto (&optional n)
10571 "Jump to the previous position in the mark ring.
10572 With prefix arg N, jump back that many stored positions. When
10573 called several times in succession, walk through the entire ring.
10574 Org mode commands jumping to a different position in the current file,
10575 or to another Org file, automatically push the old position onto the ring."
10576 (interactive "p")
10577 (let (p m)
10578 (if (eq last-command this-command)
10579 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10580 (setq p org-mark-ring))
10581 (setq org-mark-ring-last-goto p)
10582 (setq m (car p))
10583 (pop-to-buffer-same-window (marker-buffer m))
10584 (goto-char m)
10585 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10587 (defun org-add-angle-brackets (s)
10588 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10589 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10592 ;;; Following specific links
10594 (defvar org-agenda-buffer-tmp-name)
10595 (defvar org-agenda-start-on-weekday)
10596 (defun org-follow-timestamp-link ()
10597 "Open an agenda view for the time-stamp date/range at point."
10598 (cond
10599 ((org-at-date-range-p t)
10600 (let ((org-agenda-start-on-weekday)
10601 (t1 (match-string 1))
10602 (t2 (match-string 2)) tt1 tt2)
10603 (setq tt1 (time-to-days (org-time-string-to-time t1))
10604 tt2 (time-to-days (org-time-string-to-time t2)))
10605 (let ((org-agenda-buffer-tmp-name
10606 (format "*Org Agenda(a:%s)"
10607 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10608 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10609 ((org-at-timestamp-p 'lax)
10610 (let ((org-agenda-buffer-tmp-name
10611 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10612 (org-agenda-list nil (time-to-days (org-time-string-to-time
10613 (substring (match-string 1) 0 10)))
10614 1)))
10615 (t (error "This should not happen"))))
10618 ;;; Following file links
10619 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10620 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10621 (declare-function mailcap-mime-info
10622 "mailcap" (string &optional request no-decode))
10623 (defvar org-wait nil)
10624 (defun org-open-file (path &optional in-emacs line search)
10625 "Open the file at PATH.
10626 First, this expands any special file name abbreviations. Then the
10627 configuration variable `org-file-apps' is checked if it contains an
10628 entry for this file type, and if yes, the corresponding command is launched.
10630 If no application is found, Emacs simply visits the file.
10632 With optional prefix argument IN-EMACS, Emacs will visit the file.
10633 With a double \\[universal-argument] \\[universal-argument] \
10634 prefix arg, Org tries to avoid opening in Emacs
10635 and to use an external application to visit the file.
10637 Optional LINE specifies a line to go to, optional SEARCH a string
10638 to search for. If LINE or SEARCH is given, the file will be
10639 opened in Emacs, unless an entry from org-file-apps that makes
10640 use of groups in a regexp matches.
10642 If you want to change the way frames are used when following a
10643 link, please customize `org-link-frame-setup'.
10645 If the file does not exist, an error is thrown."
10646 (let* ((file (if (equal path "")
10647 buffer-file-name
10648 (substitute-in-file-name (expand-file-name path))))
10649 (file-apps (append org-file-apps (org-default-apps)))
10650 (apps (cl-remove-if
10651 'org-file-apps-entry-match-against-dlink-p file-apps))
10652 (apps-dlink (cl-remove-if-not
10653 'org-file-apps-entry-match-against-dlink-p file-apps))
10654 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10655 (dirp (unless remp (file-directory-p file)))
10656 (file (if (and dirp org-open-directory-means-index-dot-org)
10657 (concat (file-name-as-directory file) "index.org")
10658 file))
10659 (a-m-a-p (assq 'auto-mode apps))
10660 (dfile (downcase file))
10661 ;; Reconstruct the original link from the PATH, LINE and
10662 ;; SEARCH args.
10663 (link (cond (line (concat file "::" (number-to-string line)))
10664 (search (concat file "::" search))
10665 (t file)))
10666 (dlink (downcase link))
10667 (ext
10668 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10669 (match-string 1 dfile)))
10670 (save-position-maybe
10671 (let ((old-buffer (current-buffer))
10672 (old-pos (point))
10673 (old-mode major-mode))
10674 (lambda ()
10675 (and (derived-mode-p 'org-mode)
10676 (eq old-mode 'org-mode)
10677 (or (not (eq old-buffer (current-buffer)))
10678 (not (eq old-pos (point))))
10679 (org-mark-ring-push old-pos old-buffer)))))
10680 cmd link-match-data)
10681 (cond
10682 ((member in-emacs '((16) system))
10683 (setq cmd (cdr (assq 'system apps))))
10684 (in-emacs (setq cmd 'emacs))
10686 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10687 (and dirp (cdr (assq 'directory apps)))
10688 ;; First, try matching against apps-dlink if we
10689 ;; get a match here, store the match data for
10690 ;; later.
10691 (let ((match (assoc-default dlink apps-dlink
10692 'string-match)))
10693 (if match
10694 (progn (setq link-match-data (match-data))
10695 match)
10696 (progn (setq in-emacs (or in-emacs line search))
10697 nil))) ; if we have no match in apps-dlink,
10698 ; always open the file in emacs if line or search
10699 ; is given (for backwards compatibility)
10700 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10701 'string-match)
10702 (cdr (assoc ext apps))
10703 (cdr (assq t apps))))))
10704 (when (eq cmd 'system)
10705 (setq cmd (cdr (assq 'system apps))))
10706 (when (eq cmd 'default)
10707 (setq cmd (cdr (assoc t apps))))
10708 (when (eq cmd 'mailcap)
10709 (require 'mailcap)
10710 (mailcap-parse-mailcaps)
10711 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10712 (command (mailcap-mime-info mime-type)))
10713 (if (stringp command)
10714 (setq cmd command)
10715 (setq cmd 'emacs))))
10716 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10717 (not (file-exists-p file))
10718 (not org-open-non-existing-files))
10719 (user-error "No such file: %s" file))
10720 (cond
10721 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10722 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10723 (while (string-match "['\"]%s['\"]" cmd)
10724 (setq cmd (replace-match "%s" t t cmd)))
10725 (setq cmd (replace-regexp-in-string
10726 "%s"
10727 (shell-quote-argument (convert-standard-filename file))
10729 nil t))
10731 ;; Replace "%1", "%2" etc. in command with group matches from regex
10732 (save-match-data
10733 (let ((match-index 1)
10734 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10735 (set-match-data link-match-data)
10736 (while (<= match-index number-of-groups)
10737 (let ((regex (concat "%" (number-to-string match-index)))
10738 (replace-with (match-string match-index dlink)))
10739 (while (string-match regex cmd)
10740 (setq cmd (replace-match replace-with t t cmd))))
10741 (setq match-index (+ match-index 1)))))
10743 (save-window-excursion
10744 (message "Running %s...done" cmd)
10745 (start-process-shell-command cmd nil cmd)
10746 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10747 ((or (stringp cmd)
10748 (eq cmd 'emacs))
10749 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10750 (widen)
10751 (cond (line (org-goto-line line)
10752 (when (derived-mode-p 'org-mode) (org-reveal)))
10753 (search (condition-case err
10754 (org-link-search search)
10755 ;; Save position before error-ing out so user
10756 ;; can easily move back to the original buffer.
10757 (error (funcall save-position-maybe)
10758 (error (nth 1 err)))))))
10759 ((functionp cmd)
10760 (save-match-data
10761 (set-match-data link-match-data)
10762 (condition-case nil
10763 (funcall cmd file link)
10764 ;; FIXME: Remove this check when most default installations
10765 ;; of Emacs have at least Org 9.0.
10766 ((debug wrong-number-of-arguments wrong-type-argument
10767 invalid-function)
10768 (user-error "Please see Org News for version 9.0 about \
10769 `org-file-apps'--Lisp error: %S" cmd)))))
10770 ((consp cmd)
10771 ;; FIXME: Remove this check when most default installations of
10772 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10773 ;; fall back to `org-link-frame-setup' for an old usage of
10774 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10775 (user-error "Please see Org News for version 9.0 about \
10776 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10777 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10778 (funcall save-position-maybe)))
10780 (defun org-file-apps-entry-match-against-dlink-p (entry)
10781 "This function returns non-nil if `entry' uses a regular
10782 expression which should be matched against the whole link by
10783 org-open-file.
10785 It assumes that is the case when the entry uses a regular
10786 expression which has at least one grouping construct and the
10787 action is either a lisp form or a command string containing
10788 `%1', i.e. using at least one subexpression match as a
10789 parameter."
10790 (let ((selector (car entry))
10791 (action (cdr entry)))
10792 (if (stringp selector)
10793 (and (> (regexp-opt-depth selector) 0)
10794 (or (and (stringp action)
10795 (string-match "%[0-9]" action))
10796 (consp action)))
10797 nil)))
10799 (defun org-default-apps ()
10800 "Return the default applications for this operating system."
10801 (cond
10802 ((eq system-type 'darwin)
10803 org-file-apps-defaults-macosx)
10804 ((eq system-type 'windows-nt)
10805 org-file-apps-defaults-windowsnt)
10806 (t org-file-apps-defaults-gnu)))
10808 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10809 "Convert extensions to regular expressions in the cars of LIST.
10810 Also, weed out any non-string entries, because the return value is used
10811 only for regexp matching.
10812 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10813 point to the symbol `emacs', indicating that the file should
10814 be opened in Emacs."
10815 (append
10816 (delq nil
10817 (mapcar (lambda (x)
10818 (unless (not (stringp (car x)))
10819 (if (string-match "\\W" (car x))
10821 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10822 list))
10823 (when add-auto-mode
10824 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10826 (defvar ange-ftp-name-format)
10827 (defun org-file-remote-p (file)
10828 "Test whether FILE specifies a location on a remote system.
10829 Return non-nil if the location is indeed remote.
10831 For example, the filename \"/user@host:/foo\" specifies a location
10832 on the system \"/user@host:\"."
10833 (cond ((fboundp 'file-remote-p)
10834 (file-remote-p file))
10835 ((fboundp 'tramp-handle-file-remote-p)
10836 (tramp-handle-file-remote-p file))
10837 ((and (boundp 'ange-ftp-name-format)
10838 (string-match (car ange-ftp-name-format) file))
10839 t)))
10842 ;;;; Refiling
10844 (defun org-get-org-file ()
10845 "Read a filename, with default directory `org-directory'."
10846 (let ((default (or org-default-notes-file remember-data-file)))
10847 (read-file-name (format "File name [%s]: " default)
10848 (file-name-as-directory org-directory)
10849 default)))
10851 (defun org-notes-order-reversed-p ()
10852 "Check if the current file should receive notes in reversed order."
10853 (cond
10854 ((not org-reverse-note-order) nil)
10855 ((eq t org-reverse-note-order) t)
10856 ((not (listp org-reverse-note-order)) nil)
10857 (t (catch 'exit
10858 (dolist (entry org-reverse-note-order)
10859 (when (string-match (car entry) buffer-file-name)
10860 (throw 'exit (cdr entry))))))))
10862 (defvar org-refile-target-table nil
10863 "The list of refile targets, created by `org-refile'.")
10865 (defvar org-agenda-new-buffers nil
10866 "Buffers created to visit agenda files.")
10868 (defvar org-refile-cache nil
10869 "Cache for refile targets.")
10871 (defvar org-refile-markers nil
10872 "All the markers used for caching refile locations.")
10874 (defun org-refile-marker (pos)
10875 "Get a new refile marker, but only if caching is in use."
10876 (if (not org-refile-use-cache)
10878 (let ((m (make-marker)))
10879 (move-marker m pos)
10880 (push m org-refile-markers)
10881 m)))
10883 (defun org-refile-cache-clear ()
10884 "Clear the refile cache and disable all the markers."
10885 (dolist (m org-refile-markers) (move-marker m nil))
10886 (setq org-refile-markers nil)
10887 (setq org-refile-cache nil)
10888 (message "Refile cache has been cleared"))
10890 (defun org-refile-cache-check-set (set)
10891 "Check if all the markers in the cache still have live buffers."
10892 (let (marker)
10893 (catch 'exit
10894 (while (and set (setq marker (nth 3 (pop set))))
10895 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10896 (when (and marker (null (marker-buffer marker)))
10897 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10898 (sit-for 3)
10899 (throw 'exit nil)))
10900 t)))
10902 (defun org-refile-cache-put (set &rest identifiers)
10903 "Push the refile targets SET into the cache, under IDENTIFIERS."
10904 (let* ((key (sha1 (prin1-to-string identifiers)))
10905 (entry (assoc key org-refile-cache)))
10906 (if entry
10907 (setcdr entry set)
10908 (push (cons key set) org-refile-cache))))
10910 (defun org-refile-cache-get (&rest identifiers)
10911 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10912 (cond
10913 ((not org-refile-cache) nil)
10914 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10916 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10917 org-refile-cache))))
10918 (and set (org-refile-cache-check-set set) set)))))
10920 (defvar org-outline-path-cache nil
10921 "Alist between buffer positions and outline paths.
10922 It value is an alist (POSITION . PATH) where POSITION is the
10923 buffer position at the beginning of an entry and PATH is a list
10924 of strings describing the outline path for that entry, in reverse
10925 order.")
10927 (defun org-refile-get-targets (&optional default-buffer)
10928 "Produce a table with refile targets."
10929 (let ((case-fold-search nil)
10930 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10931 (entries (or org-refile-targets '((nil . (:level . 1)))))
10932 targets tgs files desc descre)
10933 (message "Getting targets...")
10934 (with-current-buffer (or default-buffer (current-buffer))
10935 (dolist (entry entries)
10936 (setq files (car entry) desc (cdr entry))
10937 (cond
10938 ((null files) (setq files (list (current-buffer))))
10939 ((eq files 'org-agenda-files)
10940 (setq files (org-agenda-files 'unrestricted)))
10941 ((and (symbolp files) (fboundp files))
10942 (setq files (funcall files)))
10943 ((and (symbolp files) (boundp files))
10944 (setq files (symbol-value files))))
10945 (when (stringp files) (setq files (list files)))
10946 (cond
10947 ((eq (car desc) :tag)
10948 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10949 ((eq (car desc) :todo)
10950 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10951 ((eq (car desc) :regexp)
10952 (setq descre (cdr desc)))
10953 ((eq (car desc) :level)
10954 (setq descre (concat "^\\*\\{" (number-to-string
10955 (if org-odd-levels-only
10956 (1- (* 2 (cdr desc)))
10957 (cdr desc)))
10958 "\\}[ \t]")))
10959 ((eq (car desc) :maxlevel)
10960 (setq descre (concat "^\\*\\{1," (number-to-string
10961 (if org-odd-levels-only
10962 (1- (* 2 (cdr desc)))
10963 (cdr desc)))
10964 "\\}[ \t]")))
10965 (t (error "Bad refiling target description %s" desc)))
10966 (dolist (f files)
10967 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
10969 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10970 (progn
10971 (when (bufferp f)
10972 (setq f (buffer-file-name (buffer-base-buffer f))))
10973 (setq f (and f (expand-file-name f)))
10974 (when (eq org-refile-use-outline-path 'file)
10975 (push (list (file-name-nondirectory f) f nil nil) tgs))
10976 (when (eq org-refile-use-outline-path 'buffer-name)
10977 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
10978 (when (eq org-refile-use-outline-path 'full-file-path)
10979 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
10980 (org-with-wide-buffer
10981 (goto-char (point-min))
10982 (setq org-outline-path-cache nil)
10983 (while (re-search-forward descre nil t)
10984 (beginning-of-line)
10985 (let ((case-fold-search nil))
10986 (looking-at org-complex-heading-regexp))
10987 (let ((begin (point))
10988 (heading (match-string-no-properties 4)))
10989 (unless (or (and
10990 org-refile-target-verify-function
10991 (not
10992 (funcall org-refile-target-verify-function)))
10993 (not heading))
10994 (let ((re (format org-complex-heading-regexp-format
10995 (regexp-quote heading)))
10996 (target
10997 (if (not org-refile-use-outline-path) heading
10998 (mapconcat
10999 #'identity
11000 (append
11001 (pcase org-refile-use-outline-path
11002 (`file (list (file-name-nondirectory
11003 (buffer-file-name
11004 (buffer-base-buffer)))))
11005 (`full-file-path
11006 (list (buffer-file-name
11007 (buffer-base-buffer))))
11008 (`buffer-name
11009 (list (buffer-name
11010 (buffer-base-buffer))))
11011 (_ nil))
11012 (mapcar (lambda (s) (replace-regexp-in-string
11013 "/" "\\/" s nil t))
11014 (org-get-outline-path t t)))
11015 "/"))))
11016 (push (list target f re (org-refile-marker (point)))
11017 tgs)))
11018 (when (= (point) begin)
11019 ;; Verification function has not moved point.
11020 (end-of-line)))))))
11021 (when org-refile-use-cache
11022 (org-refile-cache-put tgs (buffer-file-name) descre))
11023 (setq targets (append tgs targets))))))
11024 (message "Getting targets...done")
11025 (delete-dups (nreverse targets))))
11027 (defun org--get-outline-path-1 (&optional use-cache)
11028 "Return outline path to current headline.
11030 Outline path is a list of strings, in reverse order. When
11031 optional argument USE-CACHE is non-nil, make use of a cache. See
11032 `org-get-outline-path' for details.
11034 Assume buffer is widened and point is on a headline."
11035 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11036 (let ((p (point))
11037 (heading (let ((case-fold-search nil))
11038 (looking-at org-complex-heading-regexp)
11039 (if (not (match-end 4)) ""
11040 ;; Remove statistics cookies.
11041 (org-trim
11042 (org-link-display-format
11043 (replace-regexp-in-string
11044 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11045 (match-string-no-properties 4))))))))
11046 (if (org-up-heading-safe)
11047 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11048 (when use-cache
11049 (push (cons p path) org-outline-path-cache))
11050 path)
11051 ;; This is a new root node. Since we assume we are moving
11052 ;; forward, we can drop previous cache so as to limit number
11053 ;; of associations there.
11054 (let ((path (list heading)))
11055 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11056 path)))))
11058 (defun org-get-outline-path (&optional with-self use-cache)
11059 "Return the outline path to the current entry.
11061 An outline path is a list of ancestors for current headline, as
11062 a list of strings. Statistics cookies are removed and links are
11063 replaced with their description, if any, or their path otherwise.
11065 When optional argument WITH-SELF is non-nil, the path also
11066 includes the current headline.
11068 When optional argument USE-CACHE is non-nil, cache outline paths
11069 between calls to this function so as to avoid backtracking. This
11070 argument is useful when planning to find more than one outline
11071 path in the same document. In that case, there are two
11072 conditions to satisfy:
11073 - `org-outline-path-cache' is set to nil before starting the
11074 process;
11075 - outline paths are computed by increasing buffer positions."
11076 (org-with-wide-buffer
11077 (and (or (and with-self (org-back-to-heading t))
11078 (org-up-heading-safe))
11079 (reverse (org--get-outline-path-1 use-cache)))))
11081 (defun org-format-outline-path (path &optional width prefix separator)
11082 "Format the outline path PATH for display.
11083 WIDTH is the maximum number of characters that is available.
11084 PREFIX is a prefix to be included in the returned string,
11085 such as the file name.
11086 SEPARATOR is inserted between the different parts of the path,
11087 the default is \"/\"."
11088 (setq width (or width 79))
11089 (setq path (delq nil path))
11090 (unless (> width 0)
11091 (user-error "Argument `width' must be positive"))
11092 (setq separator (or separator "/"))
11093 (let* ((org-odd-levels-only nil)
11094 (fpath (concat
11095 prefix (and prefix path separator)
11096 (mapconcat
11097 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11098 (cl-loop for head in path
11099 for n from 0
11100 collect (org-add-props
11101 head nil 'face
11102 (nth (% n org-n-level-faces) org-level-faces)))
11103 separator))))
11104 (when (> (length fpath) width)
11105 (if (< width 7)
11106 ;; It's unlikely that `width' will be this small, but don't
11107 ;; waste characters by adding ".." if it is.
11108 (setq fpath (substring fpath 0 width))
11109 (setf (substring fpath (- width 2)) "..")))
11110 fpath))
11112 (defun org-display-outline-path (&optional file current separator just-return-string)
11113 "Display the current outline path in the echo area.
11115 If FILE is non-nil, prepend the output with the file name.
11116 If CURRENT is non-nil, append the current heading to the output.
11117 SEPARATOR is passed through to `org-format-outline-path'. It separates
11118 the different parts of the path and defaults to \"/\".
11119 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11120 (interactive "P")
11121 (let* (case-fold-search
11122 (bfn (buffer-file-name (buffer-base-buffer)))
11123 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11124 res)
11125 (when current (setq path (append path
11126 (save-excursion
11127 (org-back-to-heading t)
11128 (when (looking-at org-complex-heading-regexp)
11129 (list (match-string 4)))))))
11130 (setq res
11131 (org-format-outline-path
11132 path
11133 (1- (frame-width))
11134 (and file bfn (concat (file-name-nondirectory bfn) separator))
11135 separator))
11136 (if just-return-string
11137 (org-no-properties res)
11138 (org-unlogged-message "%s" res))))
11140 (defvar org-refile-history nil
11141 "History for refiling operations.")
11143 (defvar org-after-refile-insert-hook nil
11144 "Hook run after `org-refile' has inserted its stuff at the new location.
11145 Note that this is still *before* the stuff will be removed from
11146 the *old* location.")
11148 (defvar org-capture-last-stored-marker)
11149 (defvar org-refile-keep nil
11150 "Non-nil means `org-refile' will copy instead of refile.")
11152 (defun org-copy ()
11153 "Like `org-refile', but copy."
11154 (interactive)
11155 (let ((org-refile-keep t))
11156 (funcall 'org-refile nil nil nil "Copy")))
11158 (defun org-refile (&optional arg default-buffer rfloc msg)
11159 "Move the entry or entries at point to another heading.
11161 The list of target headings is compiled using the information in
11162 `org-refile-targets', which see.
11164 At the target location, the entry is filed as a subitem of the
11165 target heading. Depending on `org-reverse-note-order', the new
11166 subitem will either be the first or the last subitem.
11168 If there is an active region, all entries in that region will be
11169 refiled. However, the region must fulfill the requirement that
11170 the first heading sets the top-level of the moved text.
11172 With a `\\[universal-argument]' ARG, the command will only visit the target \
11173 location
11174 and not actually move anything.
11176 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11177 location where the last
11178 refiling operation has put the subtree.
11180 With a numeric prefix argument of `2', refile to the running clock.
11182 With a numeric prefix argument of `3', emulate `org-refile-keep'
11183 being set to t and copy to the target location, don't move it.
11184 Beware that keeping refiled entries may result in duplicated ID
11185 properties.
11187 RFLOC can be a refile location obtained in a different way.
11189 MSG is a string to replace \"Refile\" in the default prompt with
11190 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11192 See also `org-refile-use-outline-path'.
11194 If you are using target caching (see `org-refile-use-cache'), you
11195 have to clear the target cache in order to find new targets.
11196 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11197 prefix argument (`C-u C-u C-u C-c C-w')."
11198 (interactive "P")
11199 (if (member arg '(0 (64)))
11200 (org-refile-cache-clear)
11201 (let* ((actionmsg (cond (msg msg)
11202 ((equal arg 3) "Refile (and keep)")
11203 (t "Refile")))
11204 (regionp (org-region-active-p))
11205 (region-start (and regionp (region-beginning)))
11206 (region-end (and regionp (region-end)))
11207 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11208 pos it nbuf file level reversed)
11209 (setq last-command nil)
11210 (when regionp
11211 (goto-char region-start)
11212 (or (bolp) (goto-char (point-at-bol)))
11213 (setq region-start (point))
11214 (unless (or (org-kill-is-subtree-p
11215 (buffer-substring region-start region-end))
11216 (prog1 org-refile-active-region-within-subtree
11217 (let ((s (point-at-eol)))
11218 (org-toggle-heading)
11219 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11220 (user-error "The region is not a (sequence of) subtree(s)")))
11221 (if (equal arg '(16))
11222 (org-refile-goto-last-stored)
11223 (when (or
11224 (and (equal arg 2)
11225 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11226 (prog1
11227 (setq it (list (or org-clock-heading "running clock")
11228 (buffer-file-name
11229 (marker-buffer org-clock-hd-marker))
11231 (marker-position org-clock-hd-marker)))
11232 (setq arg nil)))
11233 (setq it
11234 (or rfloc
11235 (let (heading-text)
11236 (save-excursion
11237 (unless (and arg (listp arg))
11238 (org-back-to-heading t)
11239 (setq heading-text
11240 (replace-regexp-in-string
11241 org-bracket-link-regexp
11242 "\\3"
11243 (or (nth 4 (org-heading-components))
11244 ""))))
11245 (org-refile-get-location
11246 (cond ((and arg (listp arg)) "Goto")
11247 (regionp (concat actionmsg " region to"))
11248 (t (concat actionmsg " subtree \""
11249 heading-text "\" to")))
11250 default-buffer
11251 (and (not (equal '(4) arg))
11252 org-refile-allow-creating-parent-nodes)))))))
11253 (setq file (nth 1 it)
11254 pos (nth 3 it))
11255 (when (and (not arg)
11257 (equal (buffer-file-name) file)
11258 (if regionp
11259 (and (>= pos region-start)
11260 (<= pos region-end))
11261 (and (>= pos (point))
11262 (< pos (save-excursion
11263 (org-end-of-subtree t t))))))
11264 (error "Cannot refile to position inside the tree or region"))
11265 (setq nbuf (or (find-buffer-visiting file)
11266 (find-file-noselect file)))
11267 (if (and arg (not (equal arg 3)))
11268 (progn
11269 (pop-to-buffer-same-window nbuf)
11270 (goto-char (cond (pos)
11271 ((org-notes-order-reversed-p) (point-min))
11272 (t (point-max))))
11273 (org-show-context 'org-goto))
11274 (if regionp
11275 (progn
11276 (org-kill-new (buffer-substring region-start region-end))
11277 (org-save-markers-in-region region-start region-end))
11278 (org-copy-subtree 1 nil t))
11279 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11280 (find-file-noselect file)))
11281 (setq reversed (org-notes-order-reversed-p))
11282 (org-with-wide-buffer
11283 (if pos
11284 (progn
11285 (goto-char pos)
11286 (setq level (org-get-valid-level (funcall outline-level) 1))
11287 (goto-char
11288 (if reversed
11289 (or (outline-next-heading) (point-max))
11290 (or (save-excursion (org-get-next-sibling))
11291 (org-end-of-subtree t t)
11292 (point-max)))))
11293 (setq level 1)
11294 (if (not reversed)
11295 (goto-char (point-max))
11296 (goto-char (point-min))
11297 (or (outline-next-heading) (goto-char (point-max)))))
11298 (unless (bolp) (newline))
11299 (org-paste-subtree level nil nil t)
11300 (when org-log-refile
11301 (org-add-log-setup 'refile nil nil org-log-refile)
11302 (unless (eq org-log-refile 'note)
11303 (save-excursion (org-add-log-note))))
11304 (and org-auto-align-tags
11305 (let ((org-loop-over-headlines-in-active-region nil))
11306 (org-set-tags nil t)))
11307 (let ((bookmark-name (plist-get org-bookmark-names-plist
11308 :last-refile)))
11309 (when bookmark-name
11310 (with-demoted-errors
11311 (bookmark-set bookmark-name))))
11312 ;; If we are refiling for capture, make sure that the
11313 ;; last-capture pointers point here
11314 (when (bound-and-true-p org-capture-is-refiling)
11315 (let ((bookmark-name (plist-get org-bookmark-names-plist
11316 :last-capture-marker)))
11317 (when bookmark-name
11318 (with-demoted-errors
11319 (bookmark-set bookmark-name))))
11320 (move-marker org-capture-last-stored-marker (point)))
11321 (when (fboundp 'deactivate-mark) (deactivate-mark))
11322 (run-hooks 'org-after-refile-insert-hook)))
11323 (unless org-refile-keep
11324 (if regionp
11325 (delete-region (point) (+ (point) (- region-end region-start)))
11326 (org-preserve-local-variables
11327 (delete-region
11328 (and (org-back-to-heading t) (point))
11329 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11330 (when (featurep 'org-inlinetask)
11331 (org-inlinetask-remove-END-maybe))
11332 (setq org-markers-to-move nil)
11333 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11335 (defun org-refile-goto-last-stored ()
11336 "Go to the location where the last refile was stored."
11337 (interactive)
11338 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11339 (message "This is the location of the last refile"))
11341 (defun org-refile--get-location (refloc tbl)
11342 "When user refile to REFLOC, find the associated target in TBL.
11343 Also check `org-refile-target-table'."
11344 (car (delq
11346 (mapcar
11347 (lambda (r) (or (assoc r tbl)
11348 (assoc r org-refile-target-table)))
11349 (list (replace-regexp-in-string "/$" "" refloc)
11350 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11352 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11353 "Prompt the user for a refile location, using PROMPT.
11354 PROMPT should not be suffixed with a colon and a space, because
11355 this function appends the default value from
11356 `org-refile-history' automatically, if that is not empty."
11357 (let ((org-refile-targets org-refile-targets)
11358 (org-refile-use-outline-path org-refile-use-outline-path))
11359 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11360 (unless org-refile-target-table
11361 (user-error "No refile targets"))
11362 (let* ((cbuf (current-buffer))
11363 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11364 (cfunc (if (and org-refile-use-outline-path
11365 org-outline-path-complete-in-steps)
11366 #'org-olpath-completing-read
11367 #'completing-read))
11368 (extra (if org-refile-use-outline-path "/" ""))
11369 (cbnex (concat (buffer-name) extra))
11370 (filename (and cfn (expand-file-name cfn)))
11371 (tbl (mapcar
11372 (lambda (x)
11373 (if (and (not (member org-refile-use-outline-path
11374 '(file full-file-path)))
11375 (not (equal filename (nth 1 x))))
11376 (cons (concat (car x) extra " ("
11377 (file-name-nondirectory (nth 1 x)) ")")
11378 (cdr x))
11379 (cons (concat (car x) extra) (cdr x))))
11380 org-refile-target-table))
11381 (completion-ignore-case t)
11382 cdef
11383 (prompt (concat prompt
11384 (or (and (car org-refile-history)
11385 (concat " (default " (car org-refile-history) ")"))
11386 (and (assoc cbnex tbl) (setq cdef cbnex)
11387 (concat " (default " cbnex ")"))) ": "))
11388 pa answ parent-target child parent old-hist)
11389 (setq old-hist org-refile-history)
11390 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11391 nil 'org-refile-history (or cdef (car org-refile-history))))
11392 (if (setq pa (org-refile--get-location answ tbl))
11393 (progn
11394 (org-refile-check-position pa)
11395 (when (or (not org-refile-history)
11396 (not (eq old-hist org-refile-history))
11397 (not (equal (car pa) (car org-refile-history))))
11398 (setq org-refile-history
11399 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11400 org-refile-history
11401 (cdr org-refile-history))))
11402 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11403 (pop org-refile-history)))
11405 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11406 (progn
11407 (setq parent (match-string 1 answ)
11408 child (match-string 2 answ))
11409 (setq parent-target (org-refile--get-location parent tbl))
11410 (when (and parent-target
11411 (or (eq new-nodes t)
11412 (and (eq new-nodes 'confirm)
11413 (y-or-n-p (format "Create new node \"%s\"? "
11414 child)))))
11415 (org-refile-new-child parent-target child)))
11416 (user-error "Invalid target location")))))
11418 (declare-function org-string-nw-p "org-macs" (s))
11419 (defun org-refile-check-position (refile-pointer)
11420 "Check if the refile pointer matches the headline to which it points."
11421 (let* ((file (nth 1 refile-pointer))
11422 (re (nth 2 refile-pointer))
11423 (pos (nth 3 refile-pointer))
11424 buffer)
11425 (if (and (not (markerp pos)) (not file))
11426 (user-error "Please indicate a target file in the refile path")
11427 (when (org-string-nw-p re)
11428 (setq buffer (if (markerp pos)
11429 (marker-buffer pos)
11430 (or (find-buffer-visiting file)
11431 (find-file-noselect file))))
11432 (with-current-buffer buffer
11433 (org-with-wide-buffer
11434 (goto-char pos)
11435 (beginning-of-line 1)
11436 (unless (looking-at-p re)
11437 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11439 (defun org-refile-new-child (parent-target child)
11440 "Use refile target PARENT-TARGET to add new CHILD below it."
11441 (unless parent-target
11442 (error "Cannot find parent for new node"))
11443 (let ((file (nth 1 parent-target))
11444 (pos (nth 3 parent-target))
11445 level)
11446 (with-current-buffer (or (find-buffer-visiting file)
11447 (find-file-noselect file))
11448 (org-with-wide-buffer
11449 (if pos
11450 (goto-char pos)
11451 (goto-char (point-max))
11452 (unless (bolp) (newline)))
11453 (when (looking-at org-outline-regexp)
11454 (setq level (funcall outline-level))
11455 (org-end-of-subtree t t))
11456 (org-back-over-empty-lines)
11457 (insert "\n" (make-string
11458 (if pos (org-get-valid-level level 1) 1) ?*)
11459 " " child "\n")
11460 (beginning-of-line 0)
11461 (list (concat (car parent-target) "/" child) file "" (point))))))
11463 (defun org-olpath-completing-read (prompt collection &rest args)
11464 "Read an outline path like a file name."
11465 (let ((thetable collection))
11466 (apply #'completing-read
11467 prompt
11468 (lambda (string predicate &optional flag)
11469 (cond
11470 ((eq flag nil) (try-completion string thetable))
11471 ((eq flag t)
11472 (let ((l (length string)))
11473 (mapcar (lambda (x)
11474 (let ((r (substring x l))
11475 (f (if (string-match " ([^)]*)$" x)
11476 (match-string 0 x)
11477 "")))
11478 (if (string-match "/" r)
11479 (concat string (substring r 0 (match-end 0)) f)
11480 x)))
11481 (all-completions string thetable predicate))))
11482 ;; Exact match?
11483 ((eq flag 'lambda) (assoc string thetable))))
11484 args)))
11486 ;;;; Dynamic blocks
11488 (defun org-find-dblock (name)
11489 "Find the first dynamic block with name NAME in the buffer.
11490 If not found, stay at current position and return nil."
11491 (let ((case-fold-search t) pos)
11492 (save-excursion
11493 (goto-char (point-min))
11494 (setq pos (and (re-search-forward
11495 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11496 (match-beginning 0))))
11497 (when pos (goto-char pos))
11498 pos))
11500 (defun org-create-dblock (plist)
11501 "Create a dynamic block section, with parameters taken from PLIST.
11502 PLIST must contain a :name entry which is used as the name of the block."
11503 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11504 (end-of-line 1)
11505 (newline))
11506 (let ((col (current-column))
11507 (name (plist-get plist :name)))
11508 (insert "#+BEGIN: " name)
11509 (while plist
11510 (if (eq (car plist) :name)
11511 (setq plist (cddr plist))
11512 (insert " " (prin1-to-string (pop plist)))))
11513 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11514 (beginning-of-line -2)))
11516 (defun org-prepare-dblock ()
11517 "Prepare dynamic block for refresh.
11518 This empties the block, puts the cursor at the insert position and returns
11519 the property list including an extra property :name with the block name."
11520 (unless (looking-at org-dblock-start-re)
11521 (user-error "Not at a dynamic block"))
11522 (let* ((begdel (1+ (match-end 0)))
11523 (name (org-no-properties (match-string 1)))
11524 (params (append (list :name name)
11525 (read (concat "(" (match-string 3) ")")))))
11526 (save-excursion
11527 (beginning-of-line 1)
11528 (skip-chars-forward " \t")
11529 (setq params (plist-put params :indentation-column (current-column))))
11530 (unless (re-search-forward org-dblock-end-re nil t)
11531 (error "Dynamic block not terminated"))
11532 (setq params
11533 (append params
11534 (list :content (buffer-substring
11535 begdel (match-beginning 0)))))
11536 (delete-region begdel (match-beginning 0))
11537 (goto-char begdel)
11538 (open-line 1)
11539 params))
11541 (defun org-map-dblocks (&optional command)
11542 "Apply COMMAND to all dynamic blocks in the current buffer.
11543 If COMMAND is not given, use `org-update-dblock'."
11544 (let ((cmd (or command 'org-update-dblock)))
11545 (save-excursion
11546 (goto-char (point-min))
11547 (while (re-search-forward org-dblock-start-re nil t)
11548 (goto-char (match-beginning 0))
11549 (save-excursion
11550 (condition-case nil
11551 (funcall cmd)
11552 (error (message "Error during update of dynamic block"))))
11553 (unless (re-search-forward org-dblock-end-re nil t)
11554 (error "Dynamic block not terminated"))))))
11556 (defun org-dblock-update (&optional arg)
11557 "User command for updating dynamic blocks.
11558 Update the dynamic block at point. With prefix ARG, update all dynamic
11559 blocks in the buffer."
11560 (interactive "P")
11561 (if arg
11562 (org-update-all-dblocks)
11563 (or (looking-at org-dblock-start-re)
11564 (org-beginning-of-dblock))
11565 (org-update-dblock)))
11567 (defun org-update-dblock ()
11568 "Update the dynamic block at point.
11569 This means to empty the block, parse for parameters and then call
11570 the correct writing function."
11571 (interactive)
11572 (save-excursion
11573 (let* ((win (selected-window))
11574 (pos (point))
11575 (line (org-current-line))
11576 (params (org-prepare-dblock))
11577 (name (plist-get params :name))
11578 (indent (plist-get params :indentation-column))
11579 (cmd (intern (concat "org-dblock-write:" name))))
11580 (message "Updating dynamic block `%s' at line %d..." name line)
11581 (funcall cmd params)
11582 (message "Updating dynamic block `%s' at line %d...done" name line)
11583 (goto-char pos)
11584 (when (and indent (> indent 0))
11585 (setq indent (make-string indent ?\ ))
11586 (save-excursion
11587 (select-window win)
11588 (org-beginning-of-dblock)
11589 (forward-line 1)
11590 (while (not (looking-at org-dblock-end-re))
11591 (insert indent)
11592 (beginning-of-line 2))
11593 (when (looking-at org-dblock-end-re)
11594 (and (looking-at "[ \t]+")
11595 (replace-match ""))
11596 (insert indent)))))))
11598 (defun org-beginning-of-dblock ()
11599 "Find the beginning of the dynamic block at point.
11600 Error if there is no such block at point."
11601 (let ((pos (point))
11602 beg)
11603 (end-of-line 1)
11604 (if (and (re-search-backward org-dblock-start-re nil t)
11605 (setq beg (match-beginning 0))
11606 (re-search-forward org-dblock-end-re nil t)
11607 (> (match-end 0) pos))
11608 (goto-char beg)
11609 (goto-char pos)
11610 (error "Not in a dynamic block"))))
11612 (defun org-update-all-dblocks ()
11613 "Update all dynamic blocks in the buffer.
11614 This function can be used in a hook."
11615 (interactive)
11616 (when (derived-mode-p 'org-mode)
11617 (org-map-dblocks 'org-update-dblock)))
11620 ;;;; Completion
11622 (declare-function org-export-backend-options "ox" (cl-x) t)
11623 (defun org-get-export-keywords ()
11624 "Return a list of all currently understood export keywords.
11625 Export keywords include options, block names, attributes and
11626 keywords relative to each registered export back-end."
11627 (let (keywords)
11628 (dolist (backend
11629 (bound-and-true-p org-export-registered-backends)
11630 (delq nil keywords))
11631 ;; Back-end name (for keywords, like #+LATEX:)
11632 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11633 (dolist (option-entry (org-export-backend-options backend))
11634 ;; Back-end options.
11635 (push (nth 1 option-entry) keywords)))))
11637 (defconst org-options-keywords
11638 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11639 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11640 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11641 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11642 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11644 (defcustom org-structure-template-alist
11645 '(("a" . "export ascii")
11646 ("c" . "center")
11647 ("C" . "comment")
11648 ("e" . "example")
11649 ("E" . "export")
11650 ("h" . "export html")
11651 ("l" . "export latex")
11652 ("q" . "quote")
11653 ("s" . "src")
11654 ("v" . "verse"))
11655 "Structure completion elements.
11656 This is an alist of keys and block types. With
11657 `org-insert-structure-template' a block can be inserted through a
11658 menu. The block type is inserted, with \"#+BEGIN_\" and
11659 \"#+END_\" added automatically. The menukeys are determined
11660 based on the key elements in the `org-structure-template-alist'.
11661 If two entries have the keys \"a\" and \"aa\" respectively, the
11662 former will be inserted by typing \"a TAB/RET/SPC\" and the
11663 latter will be inserted by typing \"aa\". If an entry with the
11664 key \"aab\" is later added it would be inserted by typing \"ab\".
11666 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11667 block can be inserted by pressing TAB after the string \"<KEY\".
11669 :group 'org-edit-structure
11670 :type '(repeat
11671 (cons (string :tag "Key")
11672 (string :tag "Template")))
11673 :package-version '(Org . "9.2"))
11675 (defun org--insert-structure-template-mks ()
11676 "Present `org-structure-template-alist' with `org-mks'.
11678 Menus are added if keys require more than one keystroke.
11679 Tabs are added to single key entires when needing more than one stroke.
11680 Keys longer than two characters are reduced to two characters."
11681 (let* (case-fold-search
11682 (templates (append org-structure-template-alist
11683 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11684 (keys (mapcar #'car templates))
11685 (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11686 ;; Sort each element of `org-structure-template-alist' into
11687 ;; sublists according to the first letter.
11688 (superlist (mapcar (lambda (letter)
11689 (list letter
11690 (cl-remove-if-not
11691 (apply-partially #'string-match-p (concat "^" letter))
11692 templates :key #'car)))
11693 start-letters)))
11694 (org-mks
11695 (apply #'append
11696 ;; Make an `org-mks' table. If only one element is
11697 ;; present in a sublist, make it part of the top-menu,
11698 ;; otherwise make a submenu according to the starting
11699 ;; letter and populate it.
11700 (mapcar (lambda (sublist)
11701 (if (eq 1 (length (cadr sublist)))
11702 (mapcar (lambda (elm)
11703 (list (substring (car elm) 0 1)
11704 (cdr elm) ""))
11705 (cadr sublist))
11706 ;; Create submenu.
11707 (let* ((topkey (car sublist))
11708 (elms (cadr sublist))
11709 (keys (mapcar #'car elms))
11710 (long (> (length elms) 3)))
11711 (append
11712 (list
11713 ;; Make a description of the submenu.
11714 (list topkey
11715 (concat
11716 (mapconcat #'cdr
11717 (cl-subseq elms 0 (if long 3 (length elms)))
11718 ", ")
11719 (when long ", ..."))))
11720 ;; List of entries in submenu.
11721 (cl-mapcar #'list
11722 (org--insert-structure-template-unique-keys keys)
11723 (mapcar #'cdr elms)
11724 (make-list (length elms) ""))))))
11725 superlist))
11726 "Select a key\n============"
11727 "Key: ")))
11729 (defun org--insert-structure-template-unique-keys (keys)
11730 "Make list of unique, two character long elements from KEYS.
11732 Elements of length one have a tab appended. Elements of length
11733 two are kept as is. Longer elements are truncated to length two.
11735 If an element cannot be made unique an error is raised."
11736 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11737 menu-keys)
11738 (dolist (key orderd-keys)
11739 (let ((potential-key
11740 (cl-case (length key)
11741 (1 (concat key "\t"))
11742 (2 key)
11743 (otherwise
11744 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11745 (mapcar (apply-partially #'concat (substring key 0 1))
11746 (split-string (substring key 1) "" t)))))))
11747 (if (or (not potential-key) (assoc potential-key menu-keys))
11748 (user-error "Could not make unique key for %s." key)
11749 (push (cons potential-key key) menu-keys))))
11750 (mapcar #'car
11751 (cl-sort menu-keys #'<
11752 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11754 (defun org-insert-structure-template (type)
11755 "Insert a block structure of the type #+begin_foo/#+end_foo.
11756 First choose a block based on `org-structure-template-alist'.
11757 Alternatively, type RET, TAB or SPC to write the block type.
11758 With an active region, wrap the region in the block. Otherwise,
11759 insert an empty block."
11760 (interactive
11761 (list (pcase (org--insert-structure-template-mks)
11762 (`("\t" . ,_) (read-string "Structure type: "))
11763 (`(,_ ,choice . ,_) choice))))
11764 (let* ((region? (use-region-p))
11765 (col (current-indentation))
11766 (indent (make-string col ?\s))
11767 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11768 (region-string (and region?
11769 (buffer-substring (region-beginning)
11770 (region-end))))
11771 (region-end-blank (and region?
11772 (save-excursion
11773 (goto-char (region-end))
11774 (when (looking-at "[ \t]*$")
11775 (replace-match "")
11776 t))))
11778 (when region? (delete-region (region-beginning) (region-end)))
11779 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11780 (insert "\n"))
11781 (beginning-of-line)
11782 (save-excursion
11783 (insert
11784 (with-temp-buffer
11785 (when region?
11786 (insert region-string "\n")
11787 (when (string-match-p
11788 (concat "\\`" (regexp-opt '("example" "export" "src")))
11789 type)
11790 (org-escape-code-in-region (point-min) (point-max))))
11791 (goto-char (point-min))
11792 ;; Delete trailing white-lines.
11793 (when region?
11794 (while (looking-at-p "^[ \t]*$")
11795 (delete-region (line-beginning-position)
11796 (line-beginning-position 2))))
11797 (save-excursion
11798 (while (not (eobp))
11799 (unless (looking-at-p indent)
11800 (insert indent))
11801 (forward-line)))
11802 (insert
11803 indent
11804 (format "#+begin_%s%s\n" type (if special? " " "")))
11805 (unless region? (indent-to col))
11806 (setq s (point))
11807 (goto-char (point-max))
11808 (skip-chars-backward "[ \t\n]" s)
11809 (delete-region (line-end-position) (point-max))
11810 (insert "\n" indent
11811 (format "#+end_%s" (car (split-string type)))
11812 (if region-end-blank "" "\n"))
11813 (buffer-substring (point-min) (point))))
11814 (when (and (eobp) (not (bolp))) (insert "\n")))
11815 (cond (special?
11816 (end-of-line))
11818 (forward-line)
11819 (skip-chars-forward "[ \t]*")))))
11822 ;;;; TODO, DEADLINE, Comments
11824 (defun org-toggle-comment ()
11825 "Change the COMMENT state of an entry."
11826 (interactive)
11827 (save-excursion
11828 (org-back-to-heading)
11829 (let ((case-fold-search nil))
11830 (looking-at org-complex-heading-regexp))
11831 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11832 (skip-chars-forward " \t")
11833 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11834 (if (org-in-commented-heading-p t)
11835 (delete-region (point)
11836 (progn (search-forward " " (line-end-position) 'move)
11837 (skip-chars-forward " \t")
11838 (point)))
11839 (insert org-comment-string)
11840 (unless (eolp) (insert " ")))))
11842 (defvar org-last-todo-state-is-todo nil
11843 "This is non-nil when the last TODO state change led to a TODO state.
11844 If the last change removed the TODO tag or switched to DONE, then
11845 this is nil.")
11847 (defvar org-setting-tags nil) ; dynamically scoped
11849 (defvar org-todo-setup-filter-hook nil
11850 "Hook for functions that pre-filter todo specs.
11851 Each function takes a todo spec and returns either nil or the spec
11852 transformed into canonical form." )
11854 (defvar org-todo-get-default-hook nil
11855 "Hook for functions that get a default item for todo.
11856 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11857 nil or a string to be used for the todo mark." )
11859 (defvar org-agenda-headline-snapshot-before-repeat)
11861 (defun org-current-effective-time ()
11862 "Return current time adjusted for `org-extend-today-until' variable."
11863 (let* ((ct (org-current-time))
11864 (dct (decode-time ct))
11865 (ct1
11866 (cond
11867 (org-use-last-clock-out-time-as-effective-time
11868 (or (org-clock-get-last-clock-out-time) ct))
11869 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11870 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11871 (t ct))))
11872 ct1))
11874 (defun org-todo-yesterday (&optional arg)
11875 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11876 (interactive "P")
11877 (if (eq major-mode 'org-agenda-mode)
11878 (apply 'org-agenda-todo-yesterday arg)
11879 (let* ((org-use-effective-time t)
11880 (hour (nth 2 (decode-time (org-current-time))))
11881 (org-extend-today-until (1+ hour)))
11882 (org-todo arg))))
11884 (defvar org-block-entry-blocking ""
11885 "First entry preventing the TODO state change.")
11887 (defun org-cancel-repeater ()
11888 "Cancel a repeater by setting its numeric value to zero."
11889 (interactive)
11890 (save-excursion
11891 (org-back-to-heading t)
11892 (let ((bound1 (point))
11893 (bound0 (save-excursion (outline-next-heading) (point))))
11894 (when (and (re-search-forward
11895 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11896 org-deadline-time-regexp "\\)\\|\\("
11897 org-ts-regexp "\\)")
11898 bound0 t)
11899 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11900 bound1 t))
11901 (replace-match "0" t nil nil 1)))))
11903 (defvar org-state)
11904 (defvar org-blocked-by-checkboxes)
11905 (defun org-todo (&optional arg)
11906 "Change the TODO state of an item.
11908 The state of an item is given by a keyword at the start of the heading,
11909 like
11910 *** TODO Write paper
11911 *** DONE Call mom
11913 The different keywords are specified in the variable `org-todo-keywords'.
11914 By default the available states are \"TODO\" and \"DONE\". So, for this
11915 example: when the item starts with TODO, it is changed to DONE.
11916 When it starts with DONE, the DONE is removed. And when neither TODO nor
11917 DONE are present, add TODO at the beginning of the heading.
11919 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11920 state.
11921 With numeric prefix ARG, switch to that state.
11922 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11923 next set of TODO \
11924 keywords (nextset).
11925 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11926 prefix, circumvent any state blocking.
11927 With a numeric prefix arg of 0, inhibit note taking for the change.
11928 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11930 When called through ELisp, arg is also interpreted in the following way:
11931 `none' -> empty state
11932 \"\" -> switch to empty state
11933 `done' -> switch to DONE
11934 `nextset' -> switch to the next set of keywords
11935 `previousset' -> switch to the previous set of keywords
11936 \"WAITING\" -> switch to the specified keyword, but only if it
11937 really is a member of `org-todo-keywords'."
11938 (interactive "P")
11939 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11940 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11941 'region-start-level 'region))
11942 org-loop-over-headlines-in-active-region)
11943 (org-map-entries
11944 `(org-todo ,arg)
11945 org-loop-over-headlines-in-active-region
11946 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
11947 (when (equal arg '(16)) (setq arg 'nextset))
11948 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
11949 (let ((org-blocker-hook org-blocker-hook)
11950 commentp
11951 case-fold-search)
11952 (when (equal arg '(64))
11953 (setq arg nil org-blocker-hook nil))
11954 (when (and org-blocker-hook
11955 (or org-inhibit-blocking
11956 (org-entry-get nil "NOBLOCKING")))
11957 (setq org-blocker-hook nil))
11958 (save-excursion
11959 (catch 'exit
11960 (org-back-to-heading t)
11961 (when (org-in-commented-heading-p t)
11962 (org-toggle-comment)
11963 (setq commentp t))
11964 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11965 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11966 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11967 (let* ((match-data (match-data))
11968 (startpos (copy-marker (line-beginning-position)))
11969 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11970 (org-log-done org-log-done)
11971 (org-log-repeat org-log-repeat)
11972 (org-todo-log-states org-todo-log-states)
11973 (org-inhibit-logging
11974 (if (equal arg 0)
11975 (progn (setq arg nil) 'note) org-inhibit-logging))
11976 (this (match-string 1))
11977 (hl-pos (match-beginning 0))
11978 (head (org-get-todo-sequence-head this))
11979 (ass (assoc head org-todo-kwd-alist))
11980 (interpret (nth 1 ass))
11981 (done-word (nth 3 ass))
11982 (final-done-word (nth 4 ass))
11983 (org-last-state (or this ""))
11984 (completion-ignore-case t)
11985 (member (member this org-todo-keywords-1))
11986 (tail (cdr member))
11987 (org-state (cond
11988 ((and org-todo-key-trigger
11989 (or (and (equal arg '(4))
11990 (eq org-use-fast-todo-selection 'prefix))
11991 (and (not arg) org-use-fast-todo-selection
11992 (not (eq org-use-fast-todo-selection
11993 'prefix)))))
11994 ;; Use fast selection.
11995 (org-fast-todo-selection))
11996 ((and (equal arg '(4))
11997 (or (not org-use-fast-todo-selection)
11998 (not org-todo-key-trigger)))
11999 ;; Read a state with completion.
12000 (completing-read
12001 "State: " (mapcar #'list org-todo-keywords-1)
12002 nil t))
12003 ((eq arg 'right)
12004 (if this
12005 (if tail (car tail) nil)
12006 (car org-todo-keywords-1)))
12007 ((eq arg 'left)
12008 (unless (equal member org-todo-keywords-1)
12009 (if this
12010 (nth (- (length org-todo-keywords-1)
12011 (length tail) 2)
12012 org-todo-keywords-1)
12013 (org-last org-todo-keywords-1))))
12014 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12015 (setq arg nil))) ;hack to fall back to cycling
12016 (arg
12017 ;; User or caller requests a specific state.
12018 (cond
12019 ((equal arg "") nil)
12020 ((eq arg 'none) nil)
12021 ((eq arg 'done) (or done-word (car org-done-keywords)))
12022 ((eq arg 'nextset)
12023 (or (car (cdr (member head org-todo-heads)))
12024 (car org-todo-heads)))
12025 ((eq arg 'previousset)
12026 (let ((org-todo-heads (reverse org-todo-heads)))
12027 (or (car (cdr (member head org-todo-heads)))
12028 (car org-todo-heads))))
12029 ((car (member arg org-todo-keywords-1)))
12030 ((stringp arg)
12031 (user-error "State `%s' not valid in this file" arg))
12032 ((nth (1- (prefix-numeric-value arg))
12033 org-todo-keywords-1))))
12034 ((null member) (or head (car org-todo-keywords-1)))
12035 ((equal this final-done-word) nil) ;-> make empty
12036 ((null tail) nil) ;-> first entry
12037 ((memq interpret '(type priority))
12038 (if (eq this-command last-command)
12039 (car tail)
12040 (if (> (length tail) 0)
12041 (or done-word (car org-done-keywords))
12042 nil)))
12044 (car tail))))
12045 (org-state (or
12046 (run-hook-with-args-until-success
12047 'org-todo-get-default-hook org-state org-last-state)
12048 org-state))
12049 (next (if org-state (concat " " org-state " ") " "))
12050 (change-plist (list :type 'todo-state-change :from this :to org-state
12051 :position startpos))
12052 dolog now-done-p)
12053 (when org-blocker-hook
12054 (let (org-blocked-by-checkboxes block-reason)
12055 (setq org-last-todo-state-is-todo
12056 (not (member this org-done-keywords)))
12057 (unless (save-excursion
12058 (save-match-data
12059 (org-with-wide-buffer
12060 (run-hook-with-args-until-failure
12061 'org-blocker-hook change-plist))))
12062 (setq block-reason (if org-blocked-by-checkboxes
12063 "contained checkboxes"
12064 (format "\"%s\"" org-block-entry-blocking)))
12065 (if (called-interactively-p 'interactive)
12066 (user-error "TODO state change from %s to %s blocked (by %s)"
12067 this org-state block-reason)
12068 ;; Fail silently.
12069 (message "TODO state change from %s to %s blocked (by %s)"
12070 this org-state block-reason)
12071 (throw 'exit nil)))))
12072 (store-match-data match-data)
12073 (replace-match next t t)
12074 (cond ((equal this org-state)
12075 (message "TODO state was already %s" (org-trim next)))
12076 ((not (pos-visible-in-window-p hl-pos))
12077 (message "TODO state changed to %s" (org-trim next))))
12078 (unless head
12079 (setq head (org-get-todo-sequence-head org-state)
12080 ass (assoc head org-todo-kwd-alist)
12081 interpret (nth 1 ass)
12082 done-word (nth 3 ass)
12083 final-done-word (nth 4 ass)))
12084 (when (memq arg '(nextset previousset))
12085 (message "Keyword-Set %d/%d: %s"
12086 (- (length org-todo-sets) -1
12087 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12088 (length org-todo-sets)
12089 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12090 (setq org-last-todo-state-is-todo
12091 (not (member org-state org-done-keywords)))
12092 (setq now-done-p (and (member org-state org-done-keywords)
12093 (not (member this org-done-keywords))))
12094 (and logging (org-local-logging logging))
12095 (when (and (or org-todo-log-states org-log-done)
12096 (not (eq org-inhibit-logging t))
12097 (not (memq arg '(nextset previousset))))
12098 ;; We need to look at recording a time and note.
12099 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12100 (nth 2 (assoc this org-todo-log-states))))
12101 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12102 (setq dolog 'time))
12103 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12104 (and org-state
12105 (member org-state org-not-done-keywords)
12106 (not (member this org-not-done-keywords))))
12107 ;; This is now a todo state and was not one before
12108 ;; If there was a CLOSED time stamp, get rid of it.
12109 (org-add-planning-info nil nil 'closed))
12110 (when (and now-done-p org-log-done)
12111 ;; It is now done, and it was not done before.
12112 (org-add-planning-info 'closed (org-current-effective-time))
12113 (when (and (not dolog) (eq 'note org-log-done))
12114 (org-add-log-setup 'done org-state this 'note)))
12115 (when (and org-state dolog)
12116 ;; This is a non-nil state, and we need to log it.
12117 (org-add-log-setup 'state org-state this dolog)))
12118 ;; Fixup tag positioning.
12119 (org-todo-trigger-tag-changes org-state)
12120 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12121 (when org-provide-todo-statistics
12122 (org-update-parent-todo-statistics))
12123 (run-hooks 'org-after-todo-state-change-hook)
12124 (when (and arg (not (member org-state org-done-keywords)))
12125 (setq head (org-get-todo-sequence-head org-state)))
12126 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12127 ;; Do we need to trigger a repeat?
12128 (when now-done-p
12129 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12130 ;; This is for the agenda, take a snapshot of the headline.
12131 (save-match-data
12132 (setq org-agenda-headline-snapshot-before-repeat
12133 (org-get-heading))))
12134 (org-auto-repeat-maybe org-state))
12135 ;; Fixup cursor location if close to the keyword.
12136 (when (and (outline-on-heading-p)
12137 (not (bolp))
12138 (save-excursion (beginning-of-line 1)
12139 (looking-at org-todo-line-regexp))
12140 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12141 (goto-char (or (match-end 2) (match-end 1)))
12142 (and (looking-at " ") (just-one-space)))
12143 (when org-trigger-hook
12144 (save-excursion
12145 (run-hook-with-args 'org-trigger-hook change-plist)))
12146 (when commentp (org-toggle-comment))))))))
12148 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12149 "Block turning an entry into a TODO, using the hierarchy.
12150 This checks whether the current task should be blocked from state
12151 changes. Such blocking occurs when:
12153 1. The task has children which are not all in a completed state.
12155 2. A task has a parent with the property :ORDERED:, and there
12156 are siblings prior to the current task with incomplete
12157 status.
12159 3. The parent of the task is blocked because it has siblings that should
12160 be done first, or is child of a block grandparent TODO entry."
12162 (if (not org-enforce-todo-dependencies)
12163 t ; if locally turned off don't block
12164 (catch 'dont-block
12165 ;; If this is not a todo state change, or if this entry is already DONE,
12166 ;; do not block
12167 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12168 (member (plist-get change-plist :from)
12169 (cons 'done org-done-keywords))
12170 (member (plist-get change-plist :to)
12171 (cons 'todo org-not-done-keywords))
12172 (not (plist-get change-plist :to)))
12173 (throw 'dont-block t))
12174 ;; If this task has children, and any are undone, it's blocked
12175 (save-excursion
12176 (org-back-to-heading t)
12177 (let ((this-level (funcall outline-level)))
12178 (outline-next-heading)
12179 (let ((child-level (funcall outline-level)))
12180 (while (and (not (eobp))
12181 (> child-level this-level))
12182 ;; this todo has children, check whether they are all
12183 ;; completed
12184 (when (and (not (org-entry-is-done-p))
12185 (org-entry-is-todo-p))
12186 (setq org-block-entry-blocking (org-get-heading))
12187 (throw 'dont-block nil))
12188 (outline-next-heading)
12189 (setq child-level (funcall outline-level))))))
12190 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12191 ;; any previous siblings are undone, it's blocked
12192 (save-excursion
12193 (org-back-to-heading t)
12194 (let* ((pos (point))
12195 (parent-pos (and (org-up-heading-safe) (point)))
12196 (case-fold-search nil))
12197 (unless parent-pos (throw 'dont-block t)) ; no parent
12198 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12199 (forward-line 1)
12200 (re-search-forward org-not-done-heading-regexp pos t))
12201 (setq org-block-entry-blocking (match-string 0))
12202 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12203 ;; Search further up the hierarchy, to see if an ancestor is blocked
12204 (while t
12205 (goto-char parent-pos)
12206 (unless (looking-at org-not-done-heading-regexp)
12207 (throw 'dont-block t)) ; do not block, parent is not a TODO
12208 (setq pos (point))
12209 (setq parent-pos (and (org-up-heading-safe) (point)))
12210 (unless parent-pos (throw 'dont-block t)) ; no parent
12211 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12212 (forward-line 1)
12213 (re-search-forward org-not-done-heading-regexp pos t)
12214 (setq org-block-entry-blocking (org-get-heading)))
12215 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12217 (defcustom org-track-ordered-property-with-tag nil
12218 "Should the ORDERED property also be shown as a tag?
12219 The ORDERED property decides if an entry should require subtasks to be
12220 completed in sequence. Since a property is not very visible, setting
12221 this option means that toggling the ORDERED property with the command
12222 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12223 not relevant for the behavior, but it makes things more visible.
12225 Note that toggling the tag with tags commands will not change the property
12226 and therefore not influence behavior!
12228 This can be t, meaning the tag ORDERED should be used, It can also be a
12229 string to select a different tag for this task."
12230 :group 'org-todo
12231 :type '(choice
12232 (const :tag "No tracking" nil)
12233 (const :tag "Track with ORDERED tag" t)
12234 (string :tag "Use other tag")))
12236 (defun org-toggle-ordered-property ()
12237 "Toggle the ORDERED property of the current entry.
12238 For better visibility, you can track the value of this property with a tag.
12239 See variable `org-track-ordered-property-with-tag'."
12240 (interactive)
12241 (let* ((t1 org-track-ordered-property-with-tag)
12242 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12243 (save-excursion
12244 (org-back-to-heading)
12245 (if (org-entry-get nil "ORDERED")
12246 (progn
12247 (org-delete-property "ORDERED")
12248 (and tag (org-toggle-tag tag 'off))
12249 (message "Subtasks can be completed in arbitrary order"))
12250 (org-entry-put nil "ORDERED" "t")
12251 (and tag (org-toggle-tag tag 'on))
12252 (message "Subtasks must be completed in sequence")))))
12254 (defun org-block-todo-from-checkboxes (change-plist)
12255 "Block turning an entry into a TODO, using checkboxes.
12256 This checks whether the current task should be blocked from state
12257 changes because there are unchecked boxes in this entry."
12258 (if (not org-enforce-todo-checkbox-dependencies)
12259 t ; if locally turned off don't block
12260 (catch 'dont-block
12261 ;; If this is not a todo state change, or if this entry is already DONE,
12262 ;; do not block
12263 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12264 (member (plist-get change-plist :from)
12265 (cons 'done org-done-keywords))
12266 (member (plist-get change-plist :to)
12267 (cons 'todo org-not-done-keywords))
12268 (not (plist-get change-plist :to)))
12269 (throw 'dont-block t))
12270 ;; If this task has checkboxes that are not checked, it's blocked
12271 (save-excursion
12272 (org-back-to-heading t)
12273 (let ((beg (point)) end)
12274 (outline-next-heading)
12275 (setq end (point))
12276 (goto-char beg)
12277 (when (org-list-search-forward
12278 (concat (org-item-beginning-re)
12279 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12280 "\\[[- ]\\]")
12281 end t)
12282 (when (boundp 'org-blocked-by-checkboxes)
12283 (setq org-blocked-by-checkboxes t))
12284 (throw 'dont-block nil))))
12285 t))) ; do not block
12287 (defun org-entry-blocked-p ()
12288 "Non-nil if entry at point is blocked."
12289 (and (not (org-entry-get nil "NOBLOCKING"))
12290 (member (org-entry-get nil "TODO") org-not-done-keywords)
12291 (not (run-hook-with-args-until-failure
12292 'org-blocker-hook
12293 (list :type 'todo-state-change
12294 :position (point)
12295 :from 'todo
12296 :to 'done)))))
12298 (defun org-update-statistics-cookies (all)
12299 "Update the statistics cookie, either from TODO or from checkboxes.
12300 This should be called with the cursor in a line with a statistics
12301 cookie. When called with a \\[universal-argument] prefix, update
12302 all statistics cookies in the buffer."
12303 (interactive "P")
12304 (if all
12305 (progn
12306 (org-update-checkbox-count 'all)
12307 (org-map-entries 'org-update-parent-todo-statistics))
12308 (if (not (org-at-heading-p))
12309 (org-update-checkbox-count)
12310 (let ((pos (point-marker))
12311 end l1 l2)
12312 (ignore-errors (org-back-to-heading t))
12313 (if (not (org-at-heading-p))
12314 (org-update-checkbox-count)
12315 (setq l1 (org-outline-level))
12316 (setq end (save-excursion
12317 (outline-next-heading)
12318 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12319 (point)))
12320 (if (and (save-excursion
12321 (re-search-forward
12322 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12323 (not (save-excursion (re-search-forward
12324 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12325 (org-update-checkbox-count)
12326 (if (and l2 (> l2 l1))
12327 (progn
12328 (goto-char end)
12329 (org-update-parent-todo-statistics))
12330 (goto-char pos)
12331 (beginning-of-line 1)
12332 (while (re-search-forward
12333 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12334 (point-at-eol) t)
12335 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12336 (goto-char pos)
12337 (move-marker pos nil)))))
12339 (defvar org-entry-property-inherited-from) ;; defined below
12340 (defun org-update-parent-todo-statistics ()
12341 "Update any statistics cookie in the parent of the current headline.
12342 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12343 the entire subtree and this will travel up the hierarchy and update
12344 statistics everywhere."
12345 (let* ((prop (save-excursion (org-up-heading-safe)
12346 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12347 (recursive (or (not org-hierarchical-todo-statistics)
12348 (and prop (string-match "\\<recursive\\>" prop))))
12349 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12351 (first t)
12352 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12353 level ltoggle l1 new ndel
12354 (cnt-all 0) (cnt-done 0) is-percent kwd
12355 checkbox-beg cookie-present)
12356 (catch 'exit
12357 (save-excursion
12358 (beginning-of-line 1)
12359 (setq ltoggle (funcall outline-level))
12360 ;; Three situations are to consider:
12362 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12363 ;; to the top-level ancestor on the headline;
12365 ;; 2. If parent has "recursive" property, repeat up to the
12366 ;; headline setting that property, taking inheritance into
12367 ;; account;
12369 ;; 3. Else, move up to direct parent and proceed only once.
12370 (while (and (setq level (org-up-heading-safe))
12371 (or recursive first)
12372 (>= (point) lim))
12373 (setq first nil cookie-present nil)
12374 (unless (and level
12375 (not (string-match
12376 "\\<checkbox\\>"
12377 (downcase (or (org-entry-get nil "COOKIE_DATA")
12378 "")))))
12379 (throw 'exit nil))
12380 (while (re-search-forward box-re (point-at-eol) t)
12381 (setq cnt-all 0 cnt-done 0 cookie-present t)
12382 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12383 (save-match-data
12384 (unless (outline-next-heading) (throw 'exit nil))
12385 (while (and (looking-at org-complex-heading-regexp)
12386 (> (setq l1 (length (match-string 1))) level))
12387 (setq kwd (and (or recursive (= l1 ltoggle))
12388 (match-string 2)))
12389 (if (or (eq org-provide-todo-statistics 'all-headlines)
12390 (and (eq org-provide-todo-statistics t)
12391 (or (member kwd org-done-keywords)))
12392 (and (listp org-provide-todo-statistics)
12393 (stringp (car org-provide-todo-statistics))
12394 (or (member kwd org-provide-todo-statistics)
12395 (member kwd org-done-keywords)))
12396 (and (listp org-provide-todo-statistics)
12397 (listp (car org-provide-todo-statistics))
12398 (or (member kwd (car org-provide-todo-statistics))
12399 (and (member kwd org-done-keywords)
12400 (member kwd (cadr org-provide-todo-statistics))))))
12401 (setq cnt-all (1+ cnt-all))
12402 (and (eq org-provide-todo-statistics t)
12404 (setq cnt-all (1+ cnt-all))))
12405 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12406 (member kwd org-done-keywords))
12407 (and (listp org-provide-todo-statistics)
12408 (listp (car org-provide-todo-statistics))
12409 (member kwd org-done-keywords)
12410 (member kwd (cadr org-provide-todo-statistics)))
12411 (and (listp org-provide-todo-statistics)
12412 (stringp (car org-provide-todo-statistics))
12413 (member kwd org-done-keywords)))
12414 (setq cnt-done (1+ cnt-done)))
12415 (outline-next-heading)))
12416 (setq new
12417 (if is-percent
12418 (format "[%d%%]" (floor (* 100.0 cnt-done)
12419 (max 1 cnt-all)))
12420 (format "[%d/%d]" cnt-done cnt-all))
12421 ndel (- (match-end 0) checkbox-beg))
12422 (goto-char checkbox-beg)
12423 (insert new)
12424 (delete-region (point) (+ (point) ndel))
12425 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12426 (when cookie-present
12427 (run-hook-with-args 'org-after-todo-statistics-hook
12428 cnt-done (- cnt-all cnt-done))))))
12429 (run-hooks 'org-todo-statistics-hook)))
12431 (defvar org-after-todo-statistics-hook nil
12432 "Hook that is called after a TODO statistics cookie has been updated.
12433 Each function is called with two arguments: the number of not-done entries
12434 and the number of done entries.
12436 For example, the following function, when added to this hook, will switch
12437 an entry to DONE when all children are done, and back to TODO when new
12438 entries are set to a TODO status. Note that this hook is only called
12439 when there is a statistics cookie in the headline!
12441 (defun org-summary-todo (n-done n-not-done)
12442 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12443 (let (org-log-done org-log-states) ; turn off logging
12444 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12447 (defvar org-todo-statistics-hook nil
12448 "Hook that is run whenever Org thinks TODO statistics should be updated.
12449 This hook runs even if there is no statistics cookie present, in which case
12450 `org-after-todo-statistics-hook' would not run.")
12452 (defun org-todo-trigger-tag-changes (state)
12453 "Apply the changes defined in `org-todo-state-tags-triggers'."
12454 (let ((l org-todo-state-tags-triggers)
12455 changes)
12456 (when (or (not state) (equal state ""))
12457 (setq changes (append changes (cdr (assoc "" l)))))
12458 (when (and (stringp state) (> (length state) 0))
12459 (setq changes (append changes (cdr (assoc state l)))))
12460 (when (member state org-not-done-keywords)
12461 (setq changes (append changes (cdr (assq 'todo l)))))
12462 (when (member state org-done-keywords)
12463 (setq changes (append changes (cdr (assq 'done l)))))
12464 (dolist (c changes)
12465 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12467 (defun org-local-logging (value)
12468 "Get logging settings from a property VALUE."
12469 ;; Directly set the variables, they are already local.
12470 (setq org-log-done nil
12471 org-log-repeat nil
12472 org-todo-log-states nil)
12473 (dolist (w (split-string value))
12474 (let (a)
12475 (cond
12476 ((setq a (assoc w org-startup-options))
12477 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12478 (set (nth 1 a) (nth 2 a))))
12479 ((setq a (org-extract-log-state-settings w))
12480 (and (member (car a) org-todo-keywords-1)
12481 (push a org-todo-log-states)))))))
12483 (defun org-get-todo-sequence-head (kwd)
12484 "Return the head of the TODO sequence to which KWD belongs.
12485 If KWD is not set, check if there is a text property remembering the
12486 right sequence."
12487 (let (p)
12488 (cond
12489 ((not kwd)
12490 (or (get-text-property (point-at-bol) 'org-todo-head)
12491 (progn
12492 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12493 nil (point-at-eol)))
12494 (get-text-property p 'org-todo-head))))
12495 ((not (member kwd org-todo-keywords-1))
12496 (car org-todo-keywords-1))
12497 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12499 (defun org-fast-todo-selection ()
12500 "Fast TODO keyword selection with single keys.
12501 Returns the new TODO keyword, or nil if no state change should occur."
12502 (let* ((fulltable org-todo-key-alist)
12503 (done-keywords org-done-keywords) ;; needed for the faces.
12504 (maxlen (apply 'max (mapcar
12505 (lambda (x)
12506 (if (stringp (car x)) (string-width (car x)) 0))
12507 fulltable)))
12508 (expert nil)
12509 (fwidth (+ maxlen 3 1 3))
12510 (ncol (/ (- (window-width) 4) fwidth))
12511 tg cnt e c tbl
12512 groups ingroup)
12513 (save-excursion
12514 (save-window-excursion
12515 (if expert
12516 (set-buffer (get-buffer-create " *Org todo*"))
12517 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12518 (erase-buffer)
12519 (setq-local org-done-keywords done-keywords)
12520 (setq tbl fulltable cnt 0)
12521 (while (setq e (pop tbl))
12522 (cond
12523 ((equal e '(:startgroup))
12524 (push '() groups) (setq ingroup t)
12525 (unless (= cnt 0)
12526 (setq cnt 0)
12527 (insert "\n"))
12528 (insert "{ "))
12529 ((equal e '(:endgroup))
12530 (setq ingroup nil cnt 0)
12531 (insert "}\n"))
12532 ((equal e '(:newline))
12533 (unless (= cnt 0)
12534 (setq cnt 0)
12535 (insert "\n")
12536 (setq e (car tbl))
12537 (while (equal (car tbl) '(:newline))
12538 (insert "\n")
12539 (setq tbl (cdr tbl)))))
12541 (setq tg (car e) c (cdr e))
12542 (when ingroup (push tg (car groups)))
12543 (setq tg (org-add-props tg nil 'face
12544 (org-get-todo-face tg)))
12545 (when (and (= cnt 0) (not ingroup)) (insert " "))
12546 (insert "[" c "] " tg (make-string
12547 (- fwidth 4 (length tg)) ?\ ))
12548 (when (= (setq cnt (1+ cnt)) ncol)
12549 (insert "\n")
12550 (when ingroup (insert " "))
12551 (setq cnt 0)))))
12552 (insert "\n")
12553 (goto-char (point-min))
12554 (unless expert (org-fit-window-to-buffer))
12555 (message "[a-z..]:Set [SPC]:clear")
12556 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12557 (cond
12558 ((or (= c ?\C-g)
12559 (and (= c ?q) (not (rassoc c fulltable))))
12560 (setq quit-flag t))
12561 ((= c ?\ ) nil)
12562 ((setq e (rassoc c fulltable) tg (car e))
12564 (t (setq quit-flag t)))))))
12566 (defun org-entry-is-todo-p ()
12567 (member (org-get-todo-state) org-not-done-keywords))
12569 (defun org-entry-is-done-p ()
12570 (member (org-get-todo-state) org-done-keywords))
12572 (defun org-get-todo-state ()
12573 "Return the TODO keyword of the current subtree."
12574 (save-excursion
12575 (org-back-to-heading t)
12576 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12577 (match-end 2)
12578 (match-string 2))))
12580 (defun org-at-date-range-p (&optional inactive-ok)
12581 "Non-nil if point is inside a date range.
12583 When optional argument INACTIVE-OK is non-nil, also consider
12584 inactive time ranges.
12586 When this function returns a non-nil value, match data is set
12587 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12588 on INACTIVE-OK."
12589 (interactive)
12590 (save-excursion
12591 (catch 'exit
12592 (let ((pos (point)))
12593 (skip-chars-backward "^[<\r\n")
12594 (skip-chars-backward "<[")
12595 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12596 (>= (match-end 0) pos)
12597 (throw 'exit t))
12598 (skip-chars-backward "^<[\r\n")
12599 (skip-chars-backward "<[")
12600 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12601 (>= (match-end 0) pos)
12602 (throw 'exit t)))
12603 nil)))
12605 (defun org-get-repeat (&optional timestamp)
12606 "Check if there is a time-stamp with repeater in this entry.
12608 Return the repeater, as a string, or nil. Also return nil when
12609 this function is called before first heading.
12611 When optional argument TIMESTAMP is a string, extract the
12612 repeater from there instead."
12613 (save-match-data
12614 (cond (timestamp
12615 (and (string-match org-repeat-re timestamp)
12616 (match-string-no-properties 1 timestamp)))
12617 ((org-before-first-heading-p) nil)
12619 (save-excursion
12620 (org-back-to-heading t)
12621 (let ((end (org-entry-end-position)))
12622 (catch :repeat
12623 (while (re-search-forward org-repeat-re end t)
12624 (when (save-match-data (org-at-timestamp-p 'agenda))
12625 (throw :repeat (match-string-no-properties 1)))))))))))
12627 (defvar org-last-changed-timestamp)
12628 (defvar org-last-inserted-timestamp)
12629 (defvar org-log-post-message)
12630 (defvar org-log-note-purpose)
12631 (defvar org-log-note-how nil)
12632 (defvar org-log-note-extra)
12633 (defun org-auto-repeat-maybe (done-word)
12634 "Check if the current headline contains a repeated time-stamp.
12636 If yes, set TODO state back to what it was and change the base date
12637 of repeating deadline/scheduled time stamps to new date.
12639 This function is run automatically after each state change to a DONE state."
12640 (let* ((repeat (org-get-repeat))
12641 (aa (assoc org-last-state org-todo-kwd-alist))
12642 (interpret (nth 1 aa))
12643 (head (nth 2 aa))
12644 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12645 (msg "Entry repeats: ")
12646 (org-log-done nil)
12647 (org-todo-log-states nil)
12648 (end (copy-marker (org-entry-end-position))))
12649 (unwind-protect
12650 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12651 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12652 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12653 (and (stringp org-todo-repeat-to-state)
12654 org-todo-repeat-to-state)
12655 (and org-todo-repeat-to-state org-last-state))))
12656 (org-todo (cond
12657 ((and to-state (member to-state org-todo-keywords-1))
12658 to-state)
12659 ((eq interpret 'type) org-last-state)
12660 (head)
12661 (t 'none))))
12662 (org-back-to-heading t)
12663 (org-add-planning-info nil nil 'closed)
12664 ;; When `org-log-repeat' is non-nil or entry contains
12665 ;; a clock, set LAST_REPEAT property.
12666 (when (or org-log-repeat
12667 (catch :clock
12668 (save-excursion
12669 (while (re-search-forward org-clock-line-re end t)
12670 (when (org-at-clock-log-p) (throw :clock t))))))
12671 (org-entry-put nil "LAST_REPEAT" (format-time-string
12672 (org-time-stamp-format t t)
12673 (current-time))))
12674 (when org-log-repeat
12675 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12676 (memq 'org-add-log-note post-command-hook))
12677 ;; We are already setup for some record.
12678 (when (eq org-log-repeat 'note)
12679 ;; Make sure we take a note, not only a time stamp.
12680 (setq org-log-note-how 'note))
12681 ;; Set up for taking a record.
12682 (org-add-log-setup 'state
12683 (or done-word (car org-done-keywords))
12684 org-last-state
12685 org-log-repeat)))
12686 (let ((planning-re (regexp-opt
12687 (list org-scheduled-string org-deadline-string))))
12688 (while (re-search-forward org-ts-regexp end t)
12689 (let* ((ts (match-string 0))
12690 (planning? (org-at-planning-p))
12691 (type (if (not planning?) "Plain:"
12692 (save-excursion
12693 (re-search-backward
12694 planning-re (line-beginning-position) t)
12695 (match-string 0)))))
12696 (cond
12697 ;; Ignore fake time-stamps (e.g., within comments).
12698 ((not (org-at-timestamp-p 'agenda)))
12699 ;; Time-stamps without a repeater are usually
12700 ;; skipped. However, a SCHEDULED time-stamp without
12701 ;; one is removed, as they are no longer relevant.
12702 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12703 ts))
12704 (when (equal type org-scheduled-string)
12705 (org-remove-timestamp-with-keyword type)))
12707 (let ((n (string-to-number (match-string 2 ts)))
12708 (what (match-string 3 ts)))
12709 (when (equal what "w") (setq n (* n 7) what "d"))
12710 (when (and (equal what "h")
12711 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12712 ts)))
12713 (user-error
12714 "Cannot repeat in Repeat in %d hour(s) because no hour \
12715 has been set"
12717 ;; Preparation, see if we need to modify the start
12718 ;; date for the change.
12719 (when (match-end 1)
12720 (let ((time (save-match-data
12721 (org-time-string-to-time ts))))
12722 (cond
12723 ((equal (match-string 1 ts) ".")
12724 ;; Shift starting date to today
12725 (org-timestamp-change
12726 (- (org-today) (time-to-days time))
12727 'day))
12728 ((equal (match-string 1 ts) "+")
12729 (let ((nshiftmax 10)
12730 (nshift 0))
12731 (while (or (= nshift 0)
12732 (not (time-less-p (current-time) time)))
12733 (when (= (cl-incf nshift) nshiftmax)
12734 (or (y-or-n-p
12735 (format "%d repeater intervals were not \
12736 enough to shift date past today. Continue? "
12737 nshift))
12738 (user-error "Abort")))
12739 (org-timestamp-change n (cdr (assoc what whata)))
12740 (org-in-regexp org-ts-regexp3)
12741 (setq ts (match-string 1))
12742 (setq time
12743 (save-match-data
12744 (org-time-string-to-time ts)))))
12745 (org-timestamp-change (- n) (cdr (assoc what whata)))
12746 ;; Rematch, so that we have everything in place
12747 ;; for the real shift.
12748 (org-in-regexp org-ts-regexp3)
12749 (setq ts (match-string 1))
12750 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12751 ts)))))
12752 (save-excursion
12753 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12754 (setq msg
12755 (concat
12756 msg type " " org-last-changed-timestamp " "))))))))
12757 (setq org-log-post-message msg)
12758 (message "%s" msg))
12759 (set-marker end nil))))
12761 (defun org-show-todo-tree (arg)
12762 "Make a compact tree which shows all headlines marked with TODO.
12763 The tree will show the lines where the regexp matches, and all higher
12764 headlines above the match.
12765 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12766 With a numeric prefix N, construct a sparse tree for the Nth element
12767 of `org-todo-keywords-1'."
12768 (interactive "P")
12769 (let ((case-fold-search nil)
12770 (kwd-re
12771 (cond ((null arg) org-not-done-regexp)
12772 ((equal arg '(4))
12773 (let ((kwd
12774 (completing-read "Keyword (or KWD1|KWD2|...): "
12775 (mapcar #'list org-todo-keywords-1))))
12776 (concat "\\("
12777 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12778 "\\)\\>")))
12779 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12780 (regexp-quote (nth (1- (prefix-numeric-value arg))
12781 org-todo-keywords-1)))
12782 (t (user-error "Invalid prefix argument: %s" arg)))))
12783 (message "%d TODO entries found"
12784 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12786 (defun org--deadline-or-schedule (arg type time)
12787 "Insert DEADLINE or SCHEDULE information in current entry.
12788 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12789 `org-schedule' for information about ARG and TIME arguments."
12790 (let* ((deadline? (eq type 'deadline))
12791 (keyword (if deadline? org-deadline-string org-scheduled-string))
12792 (log (if deadline? org-log-redeadline org-log-reschedule))
12793 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12794 (old-date-time (and old-date (org-time-string-to-time old-date)))
12795 ;; Save repeater cookie from either TIME or current scheduled
12796 ;; time stamp. We are going to insert it back at the end of
12797 ;; the process.
12798 (repeater (or (and (org-string-nw-p time)
12799 ;; We use `org-repeat-re' because we need
12800 ;; to tell the difference between a real
12801 ;; repeater and a time delta, e.g. "+2d".
12802 (string-match org-repeat-re time)
12803 (match-string 1 time))
12804 (and (org-string-nw-p old-date)
12805 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12806 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12807 old-date)
12808 (match-string 1 old-date)))))
12809 (pcase arg
12810 (`(4)
12811 (when (and old-date log)
12812 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12813 nil old-date log))
12814 (org-remove-timestamp-with-keyword keyword)
12815 (message (if deadline? "Item no longer has a deadline."
12816 "Item is no longer scheduled.")))
12817 (`(16)
12818 (save-excursion
12819 (org-back-to-heading t)
12820 (let ((regexp (if deadline? org-deadline-time-regexp
12821 org-scheduled-time-regexp)))
12822 (if (not (re-search-forward regexp (line-end-position 2) t))
12823 (user-error (if deadline? "No deadline information to update"
12824 "No scheduled information to update"))
12825 (let* ((rpl0 (match-string 1))
12826 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12827 (msg (if deadline? "Warn starting from" "Delay until")))
12828 (replace-match
12829 (concat keyword
12830 " <" rpl
12831 (format " -%dd"
12832 (abs (- (time-to-days
12833 (save-match-data
12834 (org-read-date
12835 nil t nil msg old-date-time)))
12836 (time-to-days old-date-time))))
12837 ">") t t))))))
12839 (org-add-planning-info type time 'closed)
12840 (when (and old-date
12842 (not (equal old-date org-last-inserted-timestamp)))
12843 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12844 org-last-inserted-timestamp
12845 old-date
12846 log))
12847 (when repeater
12848 (save-excursion
12849 (org-back-to-heading t)
12850 (when (re-search-forward
12851 (concat keyword " " org-last-inserted-timestamp)
12852 (line-end-position 2)
12854 (goto-char (1- (match-end 0)))
12855 (insert " " repeater)
12856 (setq org-last-inserted-timestamp
12857 (concat (substring org-last-inserted-timestamp 0 -1)
12858 " " repeater
12859 (substring org-last-inserted-timestamp -1))))))
12860 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12861 org-last-inserted-timestamp)))))
12863 (defun org-deadline (arg &optional time)
12864 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12865 With one universal prefix argument, remove any deadline from the item.
12866 With two universal prefix arguments, prompt for a warning delay.
12867 With argument TIME, set the deadline at the corresponding date. TIME
12868 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12869 (interactive "P")
12870 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12871 (org-map-entries
12872 (lambda () (org--deadline-or-schedule arg 'deadline time))
12874 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12875 'region-start-level
12876 'region)
12877 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12878 (org--deadline-or-schedule arg 'deadline time)))
12880 (defun org-schedule (arg &optional time)
12881 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12882 With one universal prefix argument, remove any scheduling date from the item.
12883 With two universal prefix arguments, prompt for a delay cookie.
12884 With argument TIME, scheduled at the corresponding date. TIME can
12885 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12886 (interactive "P")
12887 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12888 (org-map-entries
12889 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12891 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12892 'region-start-level
12893 'region)
12894 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12895 (org--deadline-or-schedule arg 'scheduled time)))
12897 (defun org-get-scheduled-time (pom &optional inherit)
12898 "Get the scheduled time as a time tuple, of a format suitable
12899 for calling org-schedule with, or if there is no scheduling,
12900 returns nil."
12901 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12902 (when time
12903 (apply 'encode-time (org-parse-time-string time)))))
12905 (defun org-get-deadline-time (pom &optional inherit)
12906 "Get the deadline as a time tuple, of a format suitable for
12907 calling org-deadline with, or if there is no scheduling, returns
12908 nil."
12909 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12910 (when time
12911 (apply 'encode-time (org-parse-time-string time)))))
12913 (defun org-remove-timestamp-with-keyword (keyword)
12914 "Remove all time stamps with KEYWORD in the current entry."
12915 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12916 beg)
12917 (save-excursion
12918 (org-back-to-heading t)
12919 (setq beg (point))
12920 (outline-next-heading)
12921 (while (re-search-backward re beg t)
12922 (replace-match "")
12923 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12924 (equal (char-before) ?\ ))
12925 (backward-delete-char 1)
12926 (when (string-match "^[ \t]*$" (buffer-substring
12927 (point-at-bol) (point-at-eol)))
12928 (delete-region (point-at-bol)
12929 (min (point-max) (1+ (point-at-eol))))))))))
12931 (defvar org-time-was-given) ; dynamically scoped parameter
12932 (defvar org-end-time-was-given) ; dynamically scoped parameter
12934 (defun org-at-planning-p ()
12935 "Non-nil when point is on a planning info line."
12936 ;; This is as accurate and faster than `org-element-at-point' since
12937 ;; planning info location is fixed in the section.
12938 (org-with-wide-buffer
12939 (beginning-of-line)
12940 (and (looking-at-p org-planning-line-re)
12941 (eq (point)
12942 (ignore-errors
12943 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
12944 (org-back-to-heading t)
12945 (org-with-limited-levels (org-back-to-heading t)))
12946 (line-beginning-position 2))))))
12948 (defun org-add-planning-info (what &optional time &rest remove)
12949 "Insert new timestamp with keyword in the planning line.
12950 WHAT indicates what kind of time stamp to add. It is a symbol
12951 among `closed', `deadline', `scheduled' and nil. TIME indicates
12952 the time to use. If none is given, the user is prompted for
12953 a date. REMOVE indicates what kind of entries to remove. An old
12954 WHAT entry will also be removed."
12955 (let (org-time-was-given org-end-time-was-given default-time default-input)
12956 (catch 'exit
12957 (when (and (memq what '(scheduled deadline))
12958 (or (not time)
12959 (and (stringp time)
12960 (string-match "^[-+]+[0-9]" time))))
12961 ;; Try to get a default date/time from existing timestamp
12962 (save-excursion
12963 (org-back-to-heading t)
12964 (let ((end (save-excursion (outline-next-heading) (point))) ts)
12965 (when (re-search-forward (if (eq what 'scheduled)
12966 org-scheduled-time-regexp
12967 org-deadline-time-regexp)
12968 end t)
12969 (setq ts (match-string 1)
12970 default-time (apply 'encode-time (org-parse-time-string ts))
12971 default-input (and ts (org-get-compact-tod ts)))))))
12972 (when what
12973 (setq time
12974 (if (stringp time)
12975 ;; This is a string (relative or absolute), set
12976 ;; proper date.
12977 (apply #'encode-time
12978 (org-read-date-analyze
12979 time default-time (decode-time default-time)))
12980 ;; If necessary, get the time from the user
12981 (or time (org-read-date nil 'to-time nil nil
12982 default-time default-input)))))
12984 (org-with-wide-buffer
12985 (org-back-to-heading t)
12986 (forward-line)
12987 (unless (bolp) (insert "\n"))
12988 (cond ((looking-at-p org-planning-line-re)
12989 ;; Move to current indentation.
12990 (skip-chars-forward " \t")
12991 ;; Check if we have to remove something.
12992 (dolist (type (if what (cons what remove) remove))
12993 (save-excursion
12994 (when (re-search-forward
12995 (cl-case type
12996 (closed org-closed-time-regexp)
12997 (deadline org-deadline-time-regexp)
12998 (scheduled org-scheduled-time-regexp)
12999 (otherwise
13000 (error "Invalid planning type: %s" type)))
13001 (line-end-position) t)
13002 ;; Delete until next keyword or end of line.
13003 (delete-region
13004 (match-beginning 0)
13005 (if (re-search-forward org-keyword-time-not-clock-regexp
13006 (line-end-position)
13008 (match-beginning 0)
13009 (line-end-position))))))
13010 ;; If there is nothing more to add and no more keyword
13011 ;; is left, remove the line completely.
13012 (if (and (looking-at-p "[ \t]*$") (not what))
13013 (delete-region (line-beginning-position)
13014 (line-beginning-position 2))
13015 ;; If we removed last keyword, do not leave trailing
13016 ;; white space at the end of line.
13017 (let ((p (point)))
13018 (save-excursion
13019 (end-of-line)
13020 (unless (= (skip-chars-backward " \t" p) 0)
13021 (delete-region (point) (line-end-position)))))))
13022 ((not what) (throw 'exit nil)) ; Nothing to do.
13023 (t (insert-before-markers "\n")
13024 (backward-char 1)
13025 (when org-adapt-indentation
13026 (indent-to-column (1+ (org-outline-level))))))
13027 (when what
13028 ;; Insert planning keyword.
13029 (insert (cl-case what
13030 (closed org-closed-string)
13031 (deadline org-deadline-string)
13032 (scheduled org-scheduled-string)
13033 (otherwise (error "Invalid planning type: %s" what)))
13034 " ")
13035 ;; Insert associated timestamp.
13036 (let ((ts (org-insert-time-stamp
13037 time
13038 (or org-time-was-given
13039 (and (eq what 'closed) org-log-done-with-time))
13040 (eq what 'closed)
13041 nil nil (list org-end-time-was-given))))
13042 (unless (eolp) (insert " "))
13043 ts))))))
13045 (defvar org-log-note-marker (make-marker)
13046 "Marker pointing at the entry where the note is to be inserted.")
13047 (defvar org-log-note-purpose nil)
13048 (defvar org-log-note-state nil)
13049 (defvar org-log-note-previous-state nil)
13050 (defvar org-log-note-extra nil)
13051 (defvar org-log-note-window-configuration nil)
13052 (defvar org-log-note-return-to (make-marker))
13053 (defvar org-log-note-effective-time nil
13054 "Remembered current time so that dynamically scoped
13055 `org-extend-today-until' affects timestamps in state change log")
13057 (defvar org-log-post-message nil
13058 "Message to be displayed after a log note has been stored.
13059 The auto-repeater uses this.")
13061 (defun org-add-note ()
13062 "Add a note to the current entry.
13063 This is done in the same way as adding a state change note."
13064 (interactive)
13065 (org-add-log-setup 'note))
13067 (defun org-log-beginning (&optional create)
13068 "Return expected start of log notes in current entry.
13069 When optional argument CREATE is non-nil, the function creates
13070 a drawer to store notes, if necessary. Returned position ignores
13071 narrowing."
13072 (org-with-wide-buffer
13073 (let ((drawer (org-log-into-drawer)))
13074 (cond
13075 (drawer
13076 (org-end-of-meta-data)
13077 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13078 (end (if (org-at-heading-p) (point)
13079 (save-excursion (outline-next-heading) (point))))
13080 (case-fold-search t))
13081 (catch 'exit
13082 ;; Try to find existing drawer.
13083 (while (re-search-forward regexp end t)
13084 (let ((element (org-element-at-point)))
13085 (when (eq (org-element-type element) 'drawer)
13086 (let ((cend (org-element-property :contents-end element)))
13087 (when (and (not org-log-states-order-reversed) cend)
13088 (goto-char cend)))
13089 (throw 'exit nil))))
13090 ;; No drawer found. Create one, if permitted.
13091 (when create
13092 (unless (bolp) (insert "\n"))
13093 (let ((beg (point)))
13094 (insert ":" drawer ":\n:END:\n")
13095 (org-indent-region beg (point))
13096 (org-flag-region
13097 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13098 (end-of-line -1)))))
13100 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13101 (skip-chars-forward " \t\n")
13102 (beginning-of-line)
13103 (unless org-log-states-order-reversed
13104 (org-skip-over-state-notes)
13105 (skip-chars-backward " \t\n")
13106 (forward-line)))))
13107 (if (bolp) (point) (line-beginning-position 2))))
13109 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13110 "Set up the post command hook to take a note.
13111 If this is about to TODO state change, the new state is expected in STATE.
13112 HOW is an indicator what kind of note should be created.
13113 EXTRA is additional text that will be inserted into the notes buffer."
13114 (move-marker org-log-note-marker (point))
13115 (setq org-log-note-purpose purpose
13116 org-log-note-state state
13117 org-log-note-previous-state prev-state
13118 org-log-note-how how
13119 org-log-note-extra extra
13120 org-log-note-effective-time (org-current-effective-time))
13121 (add-hook 'post-command-hook 'org-add-log-note 'append))
13123 (defun org-skip-over-state-notes ()
13124 "Skip past the list of State notes in an entry."
13125 (when (ignore-errors (goto-char (org-in-item-p)))
13126 (let* ((struct (org-list-struct))
13127 (prevs (org-list-prevs-alist struct))
13128 (regexp
13129 (concat "[ \t]*- +"
13130 (replace-regexp-in-string
13131 " +" " +"
13132 (org-replace-escapes
13133 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13134 `(("%d" . ,org-ts-regexp-inactive)
13135 ("%D" . ,org-ts-regexp)
13136 ("%s" . "\"\\S-+\"")
13137 ("%S" . "\"\\S-+\"")
13138 ("%t" . ,org-ts-regexp-inactive)
13139 ("%T" . ,org-ts-regexp)
13140 ("%u" . ".*?")
13141 ("%U" . ".*?")))))))
13142 (while (looking-at-p regexp)
13143 (goto-char (or (org-list-get-next-item (point) struct prevs)
13144 (org-list-get-item-end (point) struct)))))))
13146 (defun org-add-log-note (&optional _purpose)
13147 "Pop up a window for taking a note, and add this note later."
13148 (remove-hook 'post-command-hook 'org-add-log-note)
13149 (setq org-log-note-window-configuration (current-window-configuration))
13150 (delete-other-windows)
13151 (move-marker org-log-note-return-to (point))
13152 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13153 (goto-char org-log-note-marker)
13154 (org-switch-to-buffer-other-window "*Org Note*")
13155 (erase-buffer)
13156 (if (memq org-log-note-how '(time state))
13157 (org-store-log-note)
13158 (let ((org-inhibit-startup t)) (org-mode))
13159 (insert (format "# Insert note for %s.
13160 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13161 (cond
13162 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13163 ((eq org-log-note-purpose 'done) "closed todo item")
13164 ((eq org-log-note-purpose 'state)
13165 (format "state change from \"%s\" to \"%s\""
13166 (or org-log-note-previous-state "")
13167 (or org-log-note-state "")))
13168 ((eq org-log-note-purpose 'reschedule)
13169 "rescheduling")
13170 ((eq org-log-note-purpose 'delschedule)
13171 "no longer scheduled")
13172 ((eq org-log-note-purpose 'redeadline)
13173 "changing deadline")
13174 ((eq org-log-note-purpose 'deldeadline)
13175 "removing deadline")
13176 ((eq org-log-note-purpose 'refile)
13177 "refiling")
13178 ((eq org-log-note-purpose 'note)
13179 "this entry")
13180 (t (error "This should not happen")))))
13181 (when org-log-note-extra (insert org-log-note-extra))
13182 (setq-local org-finish-function 'org-store-log-note)
13183 (run-hooks 'org-log-buffer-setup-hook)))
13185 (defvar org-note-abort nil) ; dynamically scoped
13186 (defun org-store-log-note ()
13187 "Finish taking a log note, and insert it to where it belongs."
13188 (let ((txt (prog1 (buffer-string)
13189 (kill-buffer)))
13190 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13191 lines)
13192 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13193 (setq txt (replace-match "" t t txt)))
13194 (when (string-match "\\s-+\\'" txt)
13195 (setq txt (replace-match "" t t txt)))
13196 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13197 (when (org-string-nw-p note)
13198 (setq note
13199 (org-replace-escapes
13200 note
13201 (list (cons "%u" (user-login-name))
13202 (cons "%U" user-full-name)
13203 (cons "%t" (format-time-string
13204 (org-time-stamp-format 'long 'inactive)
13205 org-log-note-effective-time))
13206 (cons "%T" (format-time-string
13207 (org-time-stamp-format 'long nil)
13208 org-log-note-effective-time))
13209 (cons "%d" (format-time-string
13210 (org-time-stamp-format nil 'inactive)
13211 org-log-note-effective-time))
13212 (cons "%D" (format-time-string
13213 (org-time-stamp-format nil nil)
13214 org-log-note-effective-time))
13215 (cons "%s" (cond
13216 ((not org-log-note-state) "")
13217 ((string-match-p org-ts-regexp
13218 org-log-note-state)
13219 (format "\"[%s]\""
13220 (substring org-log-note-state 1 -1)))
13221 (t (format "\"%s\"" org-log-note-state))))
13222 (cons "%S"
13223 (cond
13224 ((not org-log-note-previous-state) "")
13225 ((string-match-p org-ts-regexp
13226 org-log-note-previous-state)
13227 (format "\"[%s]\""
13228 (substring
13229 org-log-note-previous-state 1 -1)))
13230 (t (format "\"%s\""
13231 org-log-note-previous-state)))))))
13232 (when lines (setq note (concat note " \\\\")))
13233 (push note lines))
13234 (when (and lines (not org-note-abort))
13235 (with-current-buffer (marker-buffer org-log-note-marker)
13236 (org-with-wide-buffer
13237 ;; Find location for the new note.
13238 (goto-char org-log-note-marker)
13239 (set-marker org-log-note-marker nil)
13240 ;; Note associated to a clock is to be located right after
13241 ;; the clock. Do not move point.
13242 (unless (eq org-log-note-purpose 'clock-out)
13243 (goto-char (org-log-beginning t)))
13244 ;; Make sure point is at the beginning of an empty line.
13245 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13246 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13247 ;; In an existing list, add a new item at the top level.
13248 ;; Otherwise, indent line like a regular one.
13249 (let ((itemp (org-in-item-p)))
13250 (if itemp
13251 (indent-line-to
13252 (let ((struct (save-excursion
13253 (goto-char itemp) (org-list-struct))))
13254 (org-list-get-ind (org-list-get-top-point struct) struct)))
13255 (org-indent-line)))
13256 (insert (org-list-bullet-string "-") (pop lines))
13257 (let ((ind (org-list-item-body-column (line-beginning-position))))
13258 (dolist (line lines)
13259 (insert "\n")
13260 (indent-line-to ind)
13261 (insert line)))
13262 (message "Note stored")
13263 (org-back-to-heading t))
13264 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13265 ;; from within `org-add-log-note' because `buffer-undo-list'
13266 ;; is then modified outside of `org-with-remote-undo'.
13267 (when (eq this-command 'org-agenda-todo)
13268 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13269 ;; Don't add undo information when called from `org-agenda-todo'.
13270 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13271 (set-window-configuration org-log-note-window-configuration)
13272 (with-current-buffer (marker-buffer org-log-note-return-to)
13273 (goto-char org-log-note-return-to))
13274 (move-marker org-log-note-return-to nil)
13275 (when org-log-post-message (message "%s" org-log-post-message))))
13277 (defun org-remove-empty-drawer-at (pos)
13278 "Remove an empty drawer at position POS.
13279 POS may also be a marker."
13280 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13281 (org-with-wide-buffer
13282 (goto-char pos)
13283 (let ((drawer (org-element-at-point)))
13284 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13285 (not (org-element-property :contents-begin drawer)))
13286 (delete-region (org-element-property :begin drawer)
13287 (progn (goto-char (org-element-property :end drawer))
13288 (skip-chars-backward " \r\t\n")
13289 (forward-line)
13290 (point))))))))
13292 (defvar org-ts-type nil)
13293 (defun org-sparse-tree (&optional arg type)
13294 "Create a sparse tree, prompt for the details.
13295 This command can create sparse trees. You first need to select the type
13296 of match used to create the tree:
13298 t Show all TODO entries.
13299 T Show entries with a specific TODO keyword.
13300 m Show entries selected by a tags/property match.
13301 p Enter a property name and its value (both with completion on existing
13302 names/values) and show entries with that property.
13303 r Show entries matching a regular expression (`/' can be used as well).
13304 b Show deadlines and scheduled items before a date.
13305 a Show deadlines and scheduled items after a date.
13306 d Show deadlines due within `org-deadline-warning-days'.
13307 D Show deadlines and scheduled items between a date range."
13308 (interactive "P")
13309 (setq type (or type org-sparse-tree-default-date-type))
13310 (setq org-ts-type type)
13311 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13312 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13313 \[c]ycle through date types: %s"
13314 (cl-case type
13315 (all "all timestamps")
13316 (scheduled "only scheduled")
13317 (deadline "only deadline")
13318 (active "only active timestamps")
13319 (inactive "only inactive timestamps")
13320 (closed "with a closed time-stamp")
13321 (otherwise "scheduled/deadline")))
13322 (let ((answer (read-char-exclusive)))
13323 (cl-case answer
13325 (org-sparse-tree
13327 (cadr
13328 (memq type '(nil all scheduled deadline active inactive closed)))))
13329 (?d (call-interactively 'org-check-deadlines))
13330 (?b (call-interactively 'org-check-before-date))
13331 (?a (call-interactively 'org-check-after-date))
13332 (?D (call-interactively 'org-check-dates-range))
13333 (?t (call-interactively 'org-show-todo-tree))
13334 (?T (org-show-todo-tree '(4)))
13335 (?m (call-interactively 'org-match-sparse-tree))
13336 ((?p ?P)
13337 (let* ((kwd (completing-read
13338 "Property: " (mapcar #'list (org-buffer-property-keys))))
13339 (value (completing-read
13340 "Value: " (mapcar #'list (org-property-values kwd)))))
13341 (unless (string-match "\\`{.*}\\'" value)
13342 (setq value (concat "\"" value "\"")))
13343 (org-match-sparse-tree arg (concat kwd "=" value))))
13344 ((?r ?R ?/) (call-interactively 'org-occur))
13345 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13347 (defvar-local org-occur-highlights nil
13348 "List of overlays used for occur matches.")
13349 (defvar-local org-occur-parameters nil
13350 "Parameters of the active org-occur calls.
13351 This is a list, each call to org-occur pushes as cons cell,
13352 containing the regular expression and the callback, onto the list.
13353 The list can contain several entries if `org-occur' has been called
13354 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13355 will only contain one set of parameters. When the highlights are
13356 removed (for example with `C-c C-c', or with the next edit (depending
13357 on `org-remove-highlights-with-change'), this variable is emptied
13358 as well.")
13360 (defun org-occur (regexp &optional keep-previous callback)
13361 "Make a compact tree which shows all matches of REGEXP.
13363 The tree will show the lines where the regexp matches, and any other context
13364 defined in `org-show-context-detail', which see.
13366 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13367 done by a previous call to `org-occur' will be kept, to allow stacking of
13368 calls to this command.
13370 Optional argument CALLBACK can be a function of no argument. In this case,
13371 it is called with point at the end of the match, match data being set
13372 accordingly. Current match is shown only if the return value is non-nil.
13373 The function must neither move point nor alter narrowing."
13374 (interactive "sRegexp: \nP")
13375 (when (equal regexp "")
13376 (user-error "Regexp cannot be empty"))
13377 (unless keep-previous
13378 (org-remove-occur-highlights nil nil t))
13379 (push (cons regexp callback) org-occur-parameters)
13380 (let ((cnt 0))
13381 (save-excursion
13382 (goto-char (point-min))
13383 (when (or (not keep-previous) ; do not want to keep
13384 (not org-occur-highlights)) ; no previous matches
13385 ;; hide everything
13386 (org-overview))
13387 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13388 (isearch-no-upper-case-p regexp t)
13389 org-occur-case-fold-search)))
13390 (while (re-search-forward regexp nil t)
13391 (when (or (not callback)
13392 (save-match-data (funcall callback)))
13393 (setq cnt (1+ cnt))
13394 (when org-highlight-sparse-tree-matches
13395 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13396 (org-show-context 'occur-tree)))))
13397 (when org-remove-highlights-with-change
13398 (add-hook 'before-change-functions 'org-remove-occur-highlights
13399 nil 'local))
13400 (unless org-sparse-tree-open-archived-trees
13401 (org-hide-archived-subtrees (point-min) (point-max)))
13402 (run-hooks 'org-occur-hook)
13403 (when (called-interactively-p 'interactive)
13404 (message "%d match(es) for regexp %s" cnt regexp))
13405 cnt))
13407 (defun org-occur-next-match (&optional n _reset)
13408 "Function for `next-error-function' to find sparse tree matches.
13409 N is the number of matches to move, when negative move backwards.
13410 This function always goes back to the starting point when no
13411 match is found."
13412 (let* ((limit (if (< n 0) (point-min) (point-max)))
13413 (search-func (if (< n 0)
13414 'previous-single-char-property-change
13415 'next-single-char-property-change))
13416 (n (abs n))
13417 (pos (point))
13419 (catch 'exit
13420 (while (setq p1 (funcall search-func (point) 'org-type))
13421 (when (equal p1 limit)
13422 (goto-char pos)
13423 (user-error "No more matches"))
13424 (when (equal (get-char-property p1 'org-type) 'org-occur)
13425 (setq n (1- n))
13426 (when (= n 0)
13427 (goto-char p1)
13428 (throw 'exit (point))))
13429 (goto-char p1))
13430 (goto-char p1)
13431 (user-error "No more matches"))))
13433 (defun org-highlight-new-match (beg end)
13434 "Highlight from BEG to END and mark the highlight is an occur headline."
13435 (let ((ov (make-overlay beg end)))
13436 (overlay-put ov 'face 'secondary-selection)
13437 (overlay-put ov 'org-type 'org-occur)
13438 (push ov org-occur-highlights)))
13440 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13441 "Remove the occur highlights from the buffer.
13442 BEG and END are ignored. If NOREMOVE is nil, remove this function
13443 from the `before-change-functions' in the current buffer."
13444 (interactive)
13445 (unless org-inhibit-highlight-removal
13446 (mapc #'delete-overlay org-occur-highlights)
13447 (setq org-occur-highlights nil)
13448 (setq org-occur-parameters nil)
13449 (unless noremove
13450 (remove-hook 'before-change-functions
13451 'org-remove-occur-highlights 'local))))
13453 ;;;; Priorities
13455 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13456 "Regular expression matching the priority indicator.")
13458 (defvar org-remove-priority-next-time nil)
13460 (defun org-priority-up ()
13461 "Increase the priority of the current item."
13462 (interactive)
13463 (org-priority 'up))
13465 (defun org-priority-down ()
13466 "Decrease the priority of the current item."
13467 (interactive)
13468 (org-priority 'down))
13470 (defun org-priority (&optional action _show)
13471 "Change the priority of an item.
13472 ACTION can be `set', `up', `down', or a character."
13473 (interactive "P")
13474 (if (equal action '(4))
13475 (org-show-priority)
13476 (unless org-enable-priority-commands
13477 (user-error "Priority commands are disabled"))
13478 (setq action (or action 'set))
13479 (let (current new news have remove)
13480 (save-excursion
13481 (org-back-to-heading t)
13482 (when (looking-at org-priority-regexp)
13483 (setq current (string-to-char (match-string 2))
13484 have t))
13485 (cond
13486 ((eq action 'remove)
13487 (setq remove t new ?\ ))
13488 ((or (eq action 'set)
13489 (integerp action))
13490 (if (not (eq action 'set))
13491 (setq new action)
13492 (message "Priority %c-%c, SPC to remove: "
13493 org-highest-priority org-lowest-priority)
13494 (save-match-data
13495 (setq new (read-char-exclusive))))
13496 (when (and (= (upcase org-highest-priority) org-highest-priority)
13497 (= (upcase org-lowest-priority) org-lowest-priority))
13498 (setq new (upcase new)))
13499 (cond ((equal new ?\ ) (setq remove t))
13500 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13501 (user-error "Priority must be between `%c' and `%c'"
13502 org-highest-priority org-lowest-priority))))
13503 ((eq action 'up)
13504 (setq new (if have
13505 (1- current) ; normal cycling
13506 ;; last priority was empty
13507 (if (eq last-command this-command)
13508 org-lowest-priority ; wrap around empty to lowest
13509 ;; default
13510 (if org-priority-start-cycle-with-default
13511 org-default-priority
13512 (1- org-default-priority))))))
13513 ((eq action 'down)
13514 (setq new (if have
13515 (1+ current) ; normal cycling
13516 ;; last priority was empty
13517 (if (eq last-command this-command)
13518 org-highest-priority ; wrap around empty to highest
13519 ;; default
13520 (if org-priority-start-cycle-with-default
13521 org-default-priority
13522 (1+ org-default-priority))))))
13523 (t (user-error "Invalid action")))
13524 (when (or (< (upcase new) org-highest-priority)
13525 (> (upcase new) org-lowest-priority))
13526 (if (and (memq action '(up down))
13527 (not have) (not (eq last-command this-command)))
13528 ;; `new' is from default priority
13529 (error
13530 "The default can not be set, see `org-default-priority' why")
13531 ;; normal cycling: `new' is beyond highest/lowest priority
13532 ;; and is wrapped around to the empty priority
13533 (setq remove t)))
13534 (setq news (format "%c" new))
13535 (if have
13536 (if remove
13537 (replace-match "" t t nil 1)
13538 (replace-match news t t nil 2))
13539 (if remove
13540 (user-error "No priority cookie found in line")
13541 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13542 (if (match-end 2)
13543 (progn
13544 (goto-char (match-end 2))
13545 (insert " [#" news "]"))
13546 (goto-char (match-beginning 3))
13547 (insert "[#" news "] "))))
13548 (org-set-tags nil 'align))
13549 (if remove
13550 (message "Priority removed")
13551 (message "Priority of current item set to %s" news)))))
13553 (defun org-show-priority ()
13554 "Show the priority of the current item.
13555 This priority is composed of the main priority given with the [#A] cookies,
13556 and by additional input from the age of a schedules or deadline entry."
13557 (interactive)
13558 (let ((pri (if (eq major-mode 'org-agenda-mode)
13559 (org-get-at-bol 'priority)
13560 (save-excursion
13561 (save-match-data
13562 (beginning-of-line)
13563 (and (looking-at org-heading-regexp)
13564 (org-get-priority (match-string 0))))))))
13565 (message "Priority is %d" (if pri pri -1000))))
13567 (defun org-get-priority (s)
13568 "Find priority cookie and return priority."
13569 (save-match-data
13570 (if (functionp org-get-priority-function)
13571 (funcall org-get-priority-function)
13572 (if (not (string-match org-priority-regexp s))
13573 (* 1000 (- org-lowest-priority org-default-priority))
13574 (* 1000 (- org-lowest-priority
13575 (string-to-char (match-string 2 s))))))))
13577 ;;;; Tags
13579 (defvar org-agenda-archives-mode)
13580 (defvar org-map-continue-from nil
13581 "Position from where mapping should continue.
13582 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13584 (defvar org-scanner-tags nil
13585 "The current tag list while the tags scanner is running.")
13587 (defvar org-trust-scanner-tags nil
13588 "Should `org-get-tags-at' use the tags for the scanner.
13589 This is for internal dynamical scoping only.
13590 When this is non-nil, the function `org-get-tags-at' will return the value
13591 of `org-scanner-tags' instead of building the list by itself. This
13592 can lead to large speed-ups when the tags scanner is used in a file with
13593 many entries, and when the list of tags is retrieved, for example to
13594 obtain a list of properties. Building the tags list for each entry in such
13595 a file becomes an N^2 operation - but with this variable set, it scales
13596 as N.")
13598 (defvar org--matcher-tags-todo-only nil)
13600 (defun org-scan-tags (action matcher todo-only &optional start-level)
13601 "Scan headline tags with inheritance and produce output ACTION.
13603 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13604 or `agenda' to produce an entry list for an agenda view. It can also be
13605 a Lisp form or a function that should be called at each matched headline, in
13606 this case the return value is a list of all return values from these calls.
13608 MATCHER is a function accepting three arguments, returning
13609 a non-nil value whenever a given set of tags qualifies a headline
13610 for inclusion. See `org-make-tags-matcher' for more information.
13611 As a special case, it can also be set to t (respectively nil) in
13612 order to match all (respectively none) headline.
13614 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13615 included in the output.
13617 START-LEVEL can be a string with asterisks, reducing the scope to
13618 headlines matching this string."
13619 (require 'org-agenda)
13620 (let* ((re (concat "^"
13621 (if start-level
13622 ;; Get the correct level to match
13623 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13624 org-outline-regexp)
13625 " *\\(\\<\\("
13626 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13627 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13628 (props (list 'face 'default
13629 'done-face 'org-agenda-done
13630 'undone-face 'default
13631 'mouse-face 'highlight
13632 'org-not-done-regexp org-not-done-regexp
13633 'org-todo-regexp org-todo-regexp
13634 'org-complex-heading-regexp org-complex-heading-regexp
13635 'help-echo
13636 (format "mouse-2 or RET jump to Org file %S"
13637 (abbreviate-file-name
13638 (or (buffer-file-name (buffer-base-buffer))
13639 (buffer-name (buffer-base-buffer)))))))
13640 (org-map-continue-from nil)
13641 lspos tags tags-list
13642 (tags-alist (list (cons 0 org-file-tags)))
13643 (llast 0) rtn rtn1 level category i txt
13644 todo marker entry priority
13645 ts-date ts-date-type ts-date-pair)
13646 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13647 (setq action (list 'lambda nil action)))
13648 (save-excursion
13649 (goto-char (point-min))
13650 (when (eq action 'sparse-tree)
13651 (org-overview)
13652 (org-remove-occur-highlights))
13653 (while (let (case-fold-search)
13654 (re-search-forward re nil t))
13655 (setq org-map-continue-from nil)
13656 (catch :skip
13657 (setq todo
13658 ;; TODO: is the 1-2 difference a bug?
13659 (when (match-end 1) (match-string-no-properties 2))
13660 tags (when (match-end 4) (match-string-no-properties 4)))
13661 (goto-char (setq lspos (match-beginning 0)))
13662 (setq level (org-reduced-level (org-outline-level))
13663 category (org-get-category))
13664 (when (eq action 'agenda)
13665 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13666 ts-date (car ts-date-pair)
13667 ts-date-type (cdr ts-date-pair)))
13668 (setq i llast llast level)
13669 ;; remove tag lists from same and sublevels
13670 (while (>= i level)
13671 (when (setq entry (assoc i tags-alist))
13672 (setq tags-alist (delete entry tags-alist)))
13673 (setq i (1- i)))
13674 ;; add the next tags
13675 (when tags
13676 (setq tags (org-split-string tags ":")
13677 tags-alist
13678 (cons (cons level tags) tags-alist)))
13679 ;; compile tags for current headline
13680 (setq tags-list
13681 (if org-use-tag-inheritance
13682 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13683 tags)
13684 org-scanner-tags tags-list)
13685 (when org-use-tag-inheritance
13686 (setcdr (car tags-alist)
13687 (mapcar (lambda (x)
13688 (setq x (copy-sequence x))
13689 (org-add-prop-inherited x))
13690 (cdar tags-alist))))
13691 (when (and tags org-use-tag-inheritance
13692 (or (not (eq t org-use-tag-inheritance))
13693 org-tags-exclude-from-inheritance))
13694 ;; Selective inheritance, remove uninherited ones.
13695 (setcdr (car tags-alist)
13696 (org-remove-uninherited-tags (cdar tags-alist))))
13697 (when (and
13699 ;; eval matcher only when the todo condition is OK
13700 (and (or (not todo-only) (member todo org-todo-keywords-1))
13701 (if (functionp matcher)
13702 (let ((case-fold-search t) (org-trust-scanner-tags t))
13703 (funcall matcher todo tags-list level))
13704 matcher))
13706 ;; Call the skipper, but return t if it does not
13707 ;; skip, so that the `and' form continues evaluating.
13708 (progn
13709 (unless (eq action 'sparse-tree) (org-agenda-skip))
13712 ;; Check if timestamps are deselecting this entry
13713 (or (not todo-only)
13714 (and (member todo org-todo-keywords-1)
13715 (or (not org-agenda-tags-todo-honor-ignore-options)
13716 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13718 ;; select this headline
13719 (cond
13720 ((eq action 'sparse-tree)
13721 (and org-highlight-sparse-tree-matches
13722 (org-get-heading) (match-end 0)
13723 (org-highlight-new-match
13724 (match-beginning 1) (match-end 1)))
13725 (org-show-context 'tags-tree))
13726 ((eq action 'agenda)
13727 (setq txt (org-agenda-format-item
13729 (concat
13730 (if (eq org-tags-match-list-sublevels 'indented)
13731 (make-string (1- level) ?.) "")
13732 (org-get-heading))
13733 (make-string level ?\s)
13734 category
13735 tags-list)
13736 priority (org-get-priority txt))
13737 (goto-char lspos)
13738 (setq marker (org-agenda-new-marker))
13739 (org-add-props txt props
13740 'org-marker marker 'org-hd-marker marker 'org-category category
13741 'todo-state todo
13742 'ts-date ts-date
13743 'priority priority
13744 'type (concat "tagsmatch" ts-date-type))
13745 (push txt rtn))
13746 ((functionp action)
13747 (setq org-map-continue-from nil)
13748 (save-excursion
13749 (setq rtn1 (funcall action))
13750 (push rtn1 rtn)))
13751 (t (user-error "Invalid action")))
13753 ;; if we are to skip sublevels, jump to end of subtree
13754 (unless org-tags-match-list-sublevels
13755 (org-end-of-subtree t)
13756 (backward-char 1))))
13757 ;; Get the correct position from where to continue
13758 (if org-map-continue-from
13759 (goto-char org-map-continue-from)
13760 (and (= (point) lspos) (end-of-line 1)))))
13761 (when (and (eq action 'sparse-tree)
13762 (not org-sparse-tree-open-archived-trees))
13763 (org-hide-archived-subtrees (point-min) (point-max)))
13764 (nreverse rtn)))
13766 (defun org-remove-uninherited-tags (tags)
13767 "Remove all tags that are not inherited from the list TAGS."
13768 (cond
13769 ((eq org-use-tag-inheritance t)
13770 (if org-tags-exclude-from-inheritance
13771 (org-delete-all org-tags-exclude-from-inheritance tags)
13772 tags))
13773 ((not org-use-tag-inheritance) nil)
13774 ((stringp org-use-tag-inheritance)
13775 (delq nil (mapcar
13776 (lambda (x)
13777 (if (and (string-match org-use-tag-inheritance x)
13778 (not (member x org-tags-exclude-from-inheritance)))
13779 x nil))
13780 tags)))
13781 ((listp org-use-tag-inheritance)
13782 (delq nil (mapcar
13783 (lambda (x)
13784 (if (member x org-use-tag-inheritance) x nil))
13785 tags)))))
13787 (defun org-match-sparse-tree (&optional todo-only match)
13788 "Create a sparse tree according to tags string MATCH.
13790 MATCH is a string with match syntax. It can contain a selection
13791 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13792 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13793 those. See the manual for details.
13795 If optional argument TODO-ONLY is non-nil, only select lines that
13796 are also TODO tasks."
13797 (interactive "P")
13798 (org-agenda-prepare-buffers (list (current-buffer)))
13799 (let ((org--matcher-tags-todo-only todo-only))
13800 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13801 org--matcher-tags-todo-only)))
13803 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13805 (defvar org-cached-props nil)
13806 (defun org-cached-entry-get (pom property)
13807 (if (or (eq t org-use-property-inheritance)
13808 (and (stringp org-use-property-inheritance)
13809 (let ((case-fold-search t))
13810 (string-match-p org-use-property-inheritance property)))
13811 (and (listp org-use-property-inheritance)
13812 (member-ignore-case property org-use-property-inheritance)))
13813 ;; Caching is not possible, check it directly.
13814 (org-entry-get pom property 'inherit)
13815 ;; Get all properties, so we can do complicated checks easily.
13816 (cdr (assoc-string property
13817 (or org-cached-props
13818 (setq org-cached-props (org-entry-properties pom)))
13819 t))))
13821 (defun org-global-tags-completion-table (&optional files)
13822 "Return the list of all tags in all agenda buffer/files.
13823 Optional FILES argument is a list of files which can be used
13824 instead of the agenda files."
13825 (save-excursion
13826 (org-uniquify
13827 (delq nil
13828 (apply #'append
13829 (mapcar
13830 (lambda (file)
13831 (set-buffer (find-file-noselect file))
13832 (org-tag-add-to-alist
13833 (org-get-buffer-tags)
13834 (mapcar (lambda (x)
13835 (and (stringp (car-safe x))
13836 (list (car-safe x))))
13837 org-current-tag-alist)))
13838 (if (car-safe files) files
13839 (org-agenda-files))))))))
13841 (defun org-make-tags-matcher (match)
13842 "Create the TAGS/TODO matcher form for the selection string MATCH.
13844 Returns a cons of the selection string MATCH and a function
13845 implementing the matcher.
13847 The matcher is to be called at an Org entry, with point on the
13848 headline, and returns non-nil if the entry matches the selection
13849 string MATCH. It must be called with three arguments: the TODO
13850 keyword at the entry (or nil if none), the list of all tags at
13851 the entry including inherited ones and the reduced level of the
13852 headline. Additionally, the category of the entry, if any, must
13853 be specified as the text property `org-category' on the headline.
13855 This function sets the variable `org--matcher-tags-todo-only' to
13856 a non-nil value if the matcher restricts matching to TODO
13857 entries, otherwise it is not touched.
13859 See also `org-scan-tags'."
13860 (unless match
13861 ;; Get a new match request, with completion against the global
13862 ;; tags table and the local tags in current buffer.
13863 (let ((org-last-tags-completion-table
13864 (org-tag-add-to-alist
13865 (org-get-buffer-tags)
13866 (org-global-tags-completion-table))))
13867 (setq match
13868 (completing-read
13869 "Match: "
13870 'org-tags-completion-function nil nil nil 'org-tags-history))))
13872 (let ((match0 match)
13873 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
13874 (start 0)
13875 tagsmatch todomatch tagsmatcher todomatcher)
13877 ;; Expand group tags.
13878 (setq match (org-tags-expand match))
13880 ;; Check if there is a TODO part of this match, which would be the
13881 ;; part after a "/". To make sure that this slash is not part of
13882 ;; a property value to be matched against, we also check that
13883 ;; there is no / after that slash. First, find the last slash.
13884 (let ((s 0))
13885 (while (string-match "/+" match s)
13886 (setq start (match-beginning 0))
13887 (setq s (match-end 0))))
13888 (if (and (string-match "/+" match start)
13889 (not (string-match-p "\"" match start)))
13890 ;; Match contains also a TODO-matching request.
13891 (progn
13892 (setq tagsmatch (substring match 0 (match-beginning 0)))
13893 (setq todomatch (substring match (match-end 0)))
13894 (when (string-prefix-p "!" todomatch)
13895 (setq org--matcher-tags-todo-only t)
13896 (setq todomatch (substring todomatch 1)))
13897 (when (string-match "\\`\\s-*\\'" todomatch)
13898 (setq todomatch nil)))
13899 ;; Only matching tags.
13900 (setq tagsmatch match)
13901 (setq todomatch nil))
13903 ;; Make the tags matcher.
13904 (when (org-string-nw-p tagsmatch)
13905 (let ((orlist nil)
13906 (orterms (org-split-string tagsmatch "|"))
13907 term)
13908 (while (setq term (pop orterms))
13909 (while (and (equal (substring term -1) "\\") orterms)
13910 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13911 (while (string-match re term)
13912 (let* ((rest (substring term (match-end 0)))
13913 (minus (and (match-end 1)
13914 (equal (match-string 1 term) "-")))
13915 (tag (save-match-data
13916 (replace-regexp-in-string
13917 "\\\\-" "-" (match-string 2 term))))
13918 (regexp (eq (string-to-char tag) ?{))
13919 (levelp (match-end 4))
13920 (propp (match-end 5))
13922 (cond
13923 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13924 (levelp
13925 `(,(org-op-to-function (match-string 3 term))
13926 level
13927 ,(string-to-number (match-string 4 term))))
13928 (propp
13929 (let* ((gv (pcase (upcase (match-string 5 term))
13930 ("CATEGORY"
13931 '(get-text-property (point) 'org-category))
13932 ("TODO" 'todo)
13933 (p `(org-cached-entry-get nil ,p))))
13934 (pv (match-string 7 term))
13935 (regexp (eq (string-to-char pv) ?{))
13936 (strp (eq (string-to-char pv) ?\"))
13937 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
13938 (po (org-op-to-function (match-string 6 term)
13939 (if timep 'time strp))))
13940 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
13941 (when timep (setq pv (org-matcher-time pv)))
13942 (cond ((and regexp (eq po 'org<>))
13943 `(not (string-match ,pv (or ,gv ""))))
13944 (regexp `(string-match ,pv (or ,gv "")))
13945 (strp `(,po (or ,gv "") ,pv))
13947 `(,po
13948 (string-to-number (or ,gv ""))
13949 ,(string-to-number pv))))))
13950 (t `(member ,tag tags-list)))))
13951 (push (if minus `(not ,mm) mm) tagsmatcher)
13952 (setq term rest)))
13953 (push `(and ,@tagsmatcher) orlist)
13954 (setq tagsmatcher nil))
13955 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
13957 ;; Make the TODO matcher.
13958 (when (org-string-nw-p todomatch)
13959 (let ((orlist nil))
13960 (dolist (term (org-split-string todomatch "|"))
13961 (while (string-match re term)
13962 (let* ((minus (and (match-end 1)
13963 (equal (match-string 1 term) "-")))
13964 (kwd (match-string 2 term))
13965 (regexp (eq (string-to-char kwd) ?{))
13966 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
13967 `(equal todo ,kwd))))
13968 (push (if minus `(not ,mm) mm) todomatcher))
13969 (setq term (substring term (match-end 0))))
13970 (push (if (> (length todomatcher) 1)
13971 (cons 'and todomatcher)
13972 (car todomatcher))
13973 orlist)
13974 (setq todomatcher nil))
13975 (setq todomatcher (cons 'or orlist))))
13977 ;; Return the string and function of the matcher. If no
13978 ;; tags-specific or todo-specific matcher exists, match
13979 ;; everything.
13980 (let ((matcher (if (and tagsmatcher todomatcher)
13981 `(and ,tagsmatcher ,todomatcher)
13982 (or tagsmatcher todomatcher t))))
13983 (when org--matcher-tags-todo-only
13984 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
13985 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
13987 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
13988 "Expand group tags in MATCH.
13990 This replaces every group tag in MATCH with a regexp tag search.
13991 For example, a group tag \"Work\" defined as { Work : Lab Conf }
13992 will be replaced like this:
13994 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13995 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13996 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
13998 Replacing by a regexp preserves the structure of the match.
13999 E.g., this expansion
14001 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14003 will match anything tagged with \"Lab\" and \"Home\", or tagged
14004 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14006 A group tag in MATCH can contain regular expressions of its own.
14007 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14008 will be replaced like this:
14010 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14012 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14013 assumed to be a single group tag, and the function will return
14014 the list of tags in this group.
14016 When DOWNCASE is non-nil, expand downcased TAGS."
14017 (if org-group-tags
14018 (let* ((case-fold-search t)
14019 (stable org-mode-syntax-table)
14020 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14021 (taggroups (if downcased
14022 (mapcar (lambda (tg) (mapcar #'downcase tg))
14023 taggroups)
14024 taggroups))
14025 (taggroups-keys (mapcar #'car taggroups))
14026 (return-match (if downcased (downcase match) match))
14027 (count 0)
14028 (work-already-expanded tags-already-expanded)
14029 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14030 ;; @ and _ are allowed as word-components in tags.
14031 (modify-syntax-entry ?@ "w" stable)
14032 (modify-syntax-entry ?_ "w" stable)
14033 ;; Temporarily replace regexp-expressions in the match-expression.
14034 (while (string-match "{.+?}" return-match)
14035 (cl-incf count)
14036 (push (match-string 0 return-match) regexps-in-match)
14037 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14038 (while (and taggroups-keys
14039 (with-syntax-table stable
14040 (string-match
14041 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14042 (regexp-opt taggroups-keys) "\\>\\)")
14043 return-match)))
14044 (let* ((dir (match-string 1 return-match))
14045 (tag (match-string 2 return-match))
14046 (tag (if downcased (downcase tag) tag)))
14047 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14048 (member tag tags-already-expanded))
14049 (setq tags-in-group (assoc tag taggroups))
14050 (push tag work-already-expanded)
14051 ;; Recursively expand each tag in the group, if the tag hasn't
14052 ;; already been expanded. Restore the match-data after all recursive calls.
14053 (save-match-data
14054 (let (tags-expanded)
14055 (dolist (x (cdr tags-in-group))
14056 (if (and (member x taggroups-keys)
14057 (not (member x work-already-expanded)))
14058 (setq tags-expanded
14059 (delete-dups
14060 (append
14061 (org-tags-expand x t downcased
14062 work-already-expanded)
14063 tags-expanded)))
14064 (setq tags-expanded
14065 (append (list x) tags-expanded)))
14066 (setq work-already-expanded
14067 (delete-dups
14068 (append tags-expanded
14069 work-already-expanded))))
14070 (setq tags-in-group
14071 (delete-dups (cons (car tags-in-group)
14072 tags-expanded)))))
14073 ;; Filter tag-regexps from tags.
14074 (setq regexp-in-group-escaped
14075 (delq nil (mapcar (lambda (x)
14076 (if (stringp x)
14077 (and (equal "{" (substring x 0 1))
14078 (equal "}" (substring x -1))
14081 tags-in-group))
14082 regexp-in-group
14083 (mapcar (lambda (x)
14084 (substring x 1 -1))
14085 regexp-in-group-escaped)
14086 tags-in-group
14087 (delq nil (mapcar (lambda (x)
14088 (if (stringp x)
14089 (and (not (equal "{" (substring x 0 1)))
14090 (not (equal "}" (substring x -1)))
14093 tags-in-group)))
14094 ;; If single-as-list, do no more in the while-loop.
14095 (if (not single-as-list)
14096 (progn
14097 (when regexp-in-group
14098 (setq regexp-in-group
14099 (concat "\\|"
14100 (mapconcat 'identity regexp-in-group
14101 "\\|"))))
14102 (setq tags-in-group
14103 (concat dir
14104 "{\\<"
14105 (regexp-opt tags-in-group)
14106 "\\>"
14107 regexp-in-group
14108 "}"))
14109 (when (stringp tags-in-group)
14110 (org-add-props tags-in-group '(grouptag t)))
14111 (setq return-match
14112 (replace-match tags-in-group t t return-match)))
14113 (setq tags-in-group
14114 (append regexp-in-group-escaped tags-in-group))))
14115 (setq taggroups-keys (delete tag taggroups-keys))))
14116 ;; Add the regular expressions back into the match-expression again.
14117 (while regexps-in-match
14118 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14119 (pop regexps-in-match)
14120 return-match t t))
14121 (cl-decf count))
14122 (if single-as-list
14123 (if tags-in-group tags-in-group (list return-match))
14124 return-match))
14125 (if single-as-list
14126 (list (if downcased (downcase match) match))
14127 match)))
14129 (defun org-op-to-function (op &optional stringp)
14130 "Turn an operator into the appropriate function."
14131 (setq op
14132 (cond
14133 ((equal op "<" ) '(< org-string< org-time<))
14134 ((equal op ">" ) '(> org-string> org-time>))
14135 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14136 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14137 ((member op '("=" "==")) '(= string= org-time=))
14138 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14139 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14141 (defun org<> (a b) (not (= a b)))
14142 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14143 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14144 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14145 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14146 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14147 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14148 (defun org-2ft (s)
14149 "Convert S to a floating point time.
14150 If S is already a number, just return it. If it is a string, parse
14151 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14152 (cond
14153 ((numberp s) s)
14154 ((stringp s)
14155 (condition-case nil
14156 (float-time (apply #'encode-time (org-parse-time-string s)))
14157 (error 0.)))
14158 (t 0.)))
14160 (defun org-time-today ()
14161 "Time in seconds today at 0:00.
14162 Returns the float number of seconds since the beginning of the
14163 epoch to the beginning of today (00:00)."
14164 (float-time (apply 'encode-time
14165 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14167 (defun org-matcher-time (s)
14168 "Interpret a time comparison value."
14169 (save-match-data
14170 (cond
14171 ((string= s "<now>") (float-time))
14172 ((string= s "<today>") (org-time-today))
14173 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14174 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14175 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14176 (+ (org-time-today)
14177 (* (string-to-number (match-string 1 s))
14178 (cdr (assoc (match-string 2 s)
14179 '(("d" . 86400.0) ("w" . 604800.0)
14180 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14181 (t (org-2ft s)))))
14183 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14184 (defvar org-tags-overlay (make-overlay 1 1))
14185 (delete-overlay org-tags-overlay)
14187 (defun org-get-local-tags-at (&optional pos)
14188 "Get a list of tags defined in the current headline."
14189 (org-get-tags-at pos 'local))
14191 (defun org-get-local-tags ()
14192 "Get a list of tags defined in the current headline."
14193 (org-get-tags-at nil 'local))
14195 (defun org-get-tags-at (&optional pos local)
14196 "Get a list of all headline tags applicable at POS.
14197 POS defaults to point. If tags are inherited, the list contains
14198 the targets in the same sequence as the headlines appear, i.e.
14199 the tags of the current headline come last.
14200 When LOCAL is non-nil, only return tags from the current headline,
14201 ignore inherited ones."
14202 (interactive)
14203 (if (and org-trust-scanner-tags
14204 (or (not pos) (equal pos (point)))
14205 (not local))
14206 org-scanner-tags
14207 (let (tags ltags lastpos parent)
14208 (save-excursion
14209 (save-restriction
14210 (widen)
14211 (goto-char (or pos (point)))
14212 (save-match-data
14213 (catch 'done
14214 (condition-case nil
14215 (progn
14216 (org-back-to-heading t)
14217 (while (not (equal lastpos (point)))
14218 (setq lastpos (point))
14219 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14220 (setq ltags (org-split-string
14221 (match-string-no-properties 1) ":"))
14222 (when parent
14223 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14224 (setq tags (append
14225 (if parent
14226 (org-remove-uninherited-tags ltags)
14227 ltags)
14228 tags)))
14229 (or org-use-tag-inheritance (throw 'done t))
14230 (when local (throw 'done t))
14231 (or (org-up-heading-safe) (error nil))
14232 (setq parent t)))
14233 (error nil)))))
14234 (if local
14235 tags
14236 (reverse (delete-dups
14237 (reverse (append
14238 (org-remove-uninherited-tags
14239 org-file-tags)
14240 tags)))))))))
14242 (defun org-add-prop-inherited (s)
14243 (add-text-properties 0 (length s) '(inherited t) s)
14246 (defun org-toggle-tag (tag &optional onoff)
14247 "Toggle the tag TAG for the current line.
14248 If ONOFF is `on' or `off', don't toggle but set to this state."
14249 (save-excursion
14250 (org-back-to-heading t)
14251 (let ((current
14252 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14253 (line-end-position) t)
14254 (let ((tags (match-string 1)))
14255 ;; Clear current tags.
14256 (replace-match "")
14257 ;; Reverse the tags list so any new tag is appended to
14258 ;; the current list of tags.
14259 (nreverse (org-split-string tags ":")))))
14260 res)
14261 (pcase onoff
14262 (`off (setq current (delete tag current)))
14263 ((or `on (guard (not (member tag current))))
14264 (setq res t)
14265 (cl-pushnew tag current :test #'equal))
14266 (_ (setq current (delete tag current))))
14267 (end-of-line)
14268 (if current
14269 (progn
14270 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14271 (org-set-tags nil t))
14272 (delete-horizontal-space))
14273 (run-hooks 'org-after-tags-change-hook)
14274 res)))
14276 (defun org--align-tags-here (to-col)
14277 "Align tags on the current headline to TO-COL.
14278 Assume point is on a headline."
14279 (let ((pos (point)))
14280 (beginning-of-line)
14281 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14282 (>= pos (match-beginning 2)))
14283 ;; No tags or point within tags: do not align.
14284 (goto-char pos)
14285 (goto-char (match-beginning 1))
14286 (let ((shift (max (- (if (>= to-col 0) to-col
14287 (- (abs to-col) (string-width (match-string 2))))
14288 (current-column))
14289 1)))
14290 (replace-match (make-string shift ?\s) nil nil nil 1)
14291 ;; Preserve initial position, if possible. In any case, stop
14292 ;; before tags.
14293 (when (< pos (point)) (goto-char pos))))))
14295 (defun org-set-tags-command (&optional arg just-align)
14296 "Call the set-tags command for the current entry."
14297 (interactive "P")
14298 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14299 (org-set-tags arg just-align)
14300 (save-excursion
14301 (unless (and (org-region-active-p)
14302 org-loop-over-headlines-in-active-region)
14303 (org-back-to-heading t))
14304 (org-set-tags arg just-align))))
14306 (defun org-set-tags-to (data)
14307 "Set the tags of the current entry to DATA, replacing current tags.
14308 DATA may be a tags string like \":aa:bb:cc:\", or a list of tags.
14309 If DATA is nil or the empty string, all tags are removed."
14310 (interactive "sTags: ")
14311 (let ((data
14312 (pcase (if (stringp data) (org-trim data) data)
14313 ((or `nil "") nil)
14314 ((pred listp) (format ":%s:" (mapconcat #'identity data ":")))
14315 ((pred stringp)
14316 (format ":%s:"
14317 (mapconcat #'identity (org-split-string data ":+") ":")))
14318 (_ (error "Invalid tag specification: %S" data)))))
14319 (org-with-wide-buffer
14320 (org-back-to-heading t)
14321 (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
14322 (when (or (match-end 5) data)
14323 (goto-char (or (match-beginning 5) (line-end-position)))
14324 (skip-chars-backward " \t")
14325 (delete-region (point) (line-end-position))
14326 (when data
14327 (insert " " data)
14328 (org-set-tags nil 'align))))))
14330 (defun org-align-all-tags ()
14331 "Align the tags in all headings."
14332 (interactive)
14333 (save-excursion
14334 (or (ignore-errors (org-back-to-heading t))
14335 (outline-next-heading))
14336 (if (org-at-heading-p)
14337 (org-set-tags t)
14338 (message "No headings"))))
14340 (defvar org-indent-indentation-per-level)
14341 (defun org-set-tags (&optional arg just-align)
14342 "Set the tags for the current headline.
14343 With prefix ARG, realign all tags in headings in the current buffer.
14344 When JUST-ALIGN is non-nil, only align tags."
14345 (interactive "P")
14346 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14347 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14348 'region-start-level
14349 'region))
14350 org-loop-over-headlines-in-active-region)
14351 (org-map-entries
14352 ;; We don't use ARG and JUST-ALIGN here because these args
14353 ;; are not useful when looping over headlines.
14354 #'org-set-tags
14355 org-loop-over-headlines-in-active-region
14357 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14358 (let ((org-setting-tags t))
14359 (if arg
14360 (save-excursion
14361 (goto-char (point-min))
14362 (while (re-search-forward org-outline-regexp-bol nil t)
14363 (org-set-tags nil t)
14364 (end-of-line))
14365 (message "All tags realigned to column %d" org-tags-column))
14366 (let* ((current (org-get-tags-string))
14367 (tags
14368 (if just-align current
14369 ;; Get a new set of tags from the user.
14370 (save-excursion
14371 (let* ((table
14372 (setq
14373 org-last-tags-completion-table
14374 (org-tag-add-to-alist
14375 (and
14376 org-complete-tags-always-offer-all-agenda-tags
14377 (org-global-tags-completion-table
14378 (org-agenda-files)))
14379 (or org-current-tag-alist
14380 (org-get-buffer-tags)))))
14381 (current-tags (org-split-string current ":"))
14382 (inherited-tags
14383 (nreverse (nthcdr (length current-tags)
14384 (nreverse (org-get-tags-at))))))
14385 (replace-regexp-in-string
14386 "\\([-+&]+\\|,\\)"
14388 (if (or (eq t org-use-fast-tag-selection)
14389 (and org-use-fast-tag-selection
14390 (delq nil (mapcar #'cdr table))))
14391 (org-fast-tag-selection
14392 current-tags inherited-tags table
14393 (and org-fast-tag-selection-include-todo
14394 org-todo-key-alist))
14395 (let ((org-add-colon-after-tag-completion
14396 (< 1 (length table))))
14397 (org-trim
14398 (completing-read
14399 "Tags: "
14400 #'org-tags-completion-function
14401 nil nil current 'org-tags-history))))))))))
14403 (when org-tags-sort-function
14404 (setq tags
14405 (mapconcat
14406 #'identity
14407 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14408 org-tags-sort-function)
14409 ":")))
14411 (if (or (string= ":" tags)
14412 (string= "::" tags))
14413 (setq tags ""))
14414 (if (not (org-string-nw-p tags)) (setq tags "")
14415 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14416 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14418 ;; Insert new tags at the correct column.
14419 (unless (equal current tags)
14420 (save-excursion
14421 (beginning-of-line)
14422 (let ((case-fold-search nil))
14423 (looking-at org-complex-heading-regexp))
14424 ;; Remove current tags, if any.
14425 (when (match-end 5) (replace-match "" nil nil nil 5))
14426 ;; Insert new tags, if any. Otherwise, remove trailing
14427 ;; white spaces.
14428 (end-of-line)
14429 (if (not (equal tags ""))
14430 ;; When text is being inserted on an invisible
14431 ;; region boundary, it can be inadvertently sucked
14432 ;; into invisibility.
14433 (org-flag-region (point) (progn (insert " " tags) (point))
14435 'outline)
14436 (skip-chars-backward " \t")
14437 (delete-region (point) (line-end-position)))))
14438 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14439 ;; is on.
14440 (unless (equal tags "")
14441 (let* ((level (save-excursion
14442 (beginning-of-line)
14443 (skip-chars-forward "\\*")))
14444 (offset (if (bound-and-true-p org-indent-mode)
14445 (* (1- org-indent-indentation-per-level)
14446 (1- level))
14448 (tags-column
14449 (+ org-tags-column
14450 (if (> org-tags-column 0) (- offset) offset))))
14451 (org--align-tags-here tags-column))))
14452 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14454 (defun org-change-tag-in-region (beg end tag off)
14455 "Add or remove TAG for each entry in the region.
14456 This works in the agenda, and also in an Org buffer."
14457 (interactive
14458 (list (region-beginning) (region-end)
14459 (let ((org-last-tags-completion-table
14460 (if (derived-mode-p 'org-mode)
14461 (org-tag-add-to-alist
14462 (org-get-buffer-tags)
14463 (org-global-tags-completion-table))
14464 (org-global-tags-completion-table))))
14465 (completing-read
14466 "Tag: " 'org-tags-completion-function nil nil nil
14467 'org-tags-history))
14468 (progn
14469 (message "[s]et or [r]emove? ")
14470 (equal (read-char-exclusive) ?r))))
14471 (when (fboundp 'deactivate-mark) (deactivate-mark))
14472 (let ((agendap (equal major-mode 'org-agenda-mode))
14473 l1 l2 m buf pos newhead (cnt 0))
14474 (goto-char end)
14475 (setq l2 (1- (org-current-line)))
14476 (goto-char beg)
14477 (setq l1 (org-current-line))
14478 (cl-loop for l from l1 to l2 do
14479 (org-goto-line l)
14480 (setq m (get-text-property (point) 'org-hd-marker))
14481 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14482 (and agendap m))
14483 (setq buf (if agendap (marker-buffer m) (current-buffer))
14484 pos (if agendap m (point)))
14485 (with-current-buffer buf
14486 (save-excursion
14487 (save-restriction
14488 (goto-char pos)
14489 (setq cnt (1+ cnt))
14490 (org-toggle-tag tag (if off 'off 'on))
14491 (setq newhead (org-get-heading)))))
14492 (and agendap (org-agenda-change-all-lines newhead m))))
14493 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14495 (defun org-tags-completion-function (string _predicate &optional flag)
14496 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14497 (confirm (lambda (x) (stringp (car x)))))
14498 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14499 (setq s1 (match-string 1 string)
14500 s2 (match-string 2 string))
14501 (setq s1 "" s2 string))
14502 (cond
14503 ((eq flag nil)
14504 ;; try completion
14505 (setq rtn (try-completion s2 ctable confirm))
14506 (when (stringp rtn)
14507 (setq rtn
14508 (concat s1 s2 (substring rtn (length s2))
14509 (if (and org-add-colon-after-tag-completion
14510 (assoc rtn ctable))
14511 ":" ""))))
14512 rtn)
14513 ((eq flag t)
14514 ;; all-completions
14515 (all-completions s2 ctable confirm))
14516 ((eq flag 'lambda)
14517 ;; exact match?
14518 (assoc s2 ctable)))))
14520 (defun org-fast-tag-insert (kwd tags face &optional end)
14521 "Insert KDW, and the TAGS, the latter with face FACE.
14522 Also insert END."
14523 (insert (format "%-12s" (concat kwd ":"))
14524 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14525 (or end "")))
14527 (defun org-fast-tag-show-exit (flag)
14528 (save-excursion
14529 (org-goto-line 3)
14530 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14531 (replace-match ""))
14532 (when flag
14533 (end-of-line 1)
14534 (org-move-to-column (- (window-width) 19) t)
14535 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14537 (defun org-set-current-tags-overlay (current prefix)
14538 "Add an overlay to CURRENT tag with PREFIX."
14539 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14540 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14541 (org-overlay-display org-tags-overlay (concat prefix s))))
14543 (defvar org-last-tag-selection-key nil)
14544 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14545 "Fast tag selection with single keys.
14546 CURRENT is the current list of tags in the headline, INHERITED is the
14547 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14548 possibly with grouping information. TODO-TABLE is a similar table with
14549 TODO keywords, should these have keys assigned to them.
14550 If the keys are nil, a-z are automatically assigned.
14551 Returns the new tags string, or nil to not change the current settings."
14552 (let* ((fulltable (append table todo-table))
14553 (maxlen (apply 'max (mapcar
14554 (lambda (x)
14555 (if (stringp (car x)) (string-width (car x)) 0))
14556 fulltable)))
14557 (buf (current-buffer))
14558 (expert (eq org-fast-tag-selection-single-key 'expert))
14559 (buffer-tags nil)
14560 (fwidth (+ maxlen 3 1 3))
14561 (ncol (/ (- (window-width) 4) fwidth))
14562 (i-face 'org-done)
14563 (c-face 'org-todo)
14564 tg cnt e c char c1 c2 ntable tbl rtn
14565 ov-start ov-end ov-prefix
14566 (exit-after-next org-fast-tag-selection-single-key)
14567 (done-keywords org-done-keywords)
14568 groups ingroup intaggroup)
14569 (save-excursion
14570 (beginning-of-line 1)
14571 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14572 (setq ov-start (match-beginning 1)
14573 ov-end (match-end 1)
14574 ov-prefix "")
14575 (setq ov-start (1- (point-at-eol))
14576 ov-end (1+ ov-start))
14577 (skip-chars-forward "^\n\r")
14578 (setq ov-prefix
14579 (concat
14580 (buffer-substring (1- (point)) (point))
14581 (if (> (current-column) org-tags-column)
14583 (make-string (- org-tags-column (current-column)) ?\ ))))))
14584 (move-overlay org-tags-overlay ov-start ov-end)
14585 (save-window-excursion
14586 (if expert
14587 (set-buffer (get-buffer-create " *Org tags*"))
14588 (delete-other-windows)
14589 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14590 (org-switch-to-buffer-other-window " *Org tags*"))
14591 (erase-buffer)
14592 (setq-local org-done-keywords done-keywords)
14593 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14594 (org-fast-tag-insert "Current" current c-face "\n\n")
14595 (org-fast-tag-show-exit exit-after-next)
14596 (org-set-current-tags-overlay current ov-prefix)
14597 (setq tbl fulltable char ?a cnt 0)
14598 (while (setq e (pop tbl))
14599 (cond
14600 ((eq (car e) :startgroup)
14601 (push '() groups) (setq ingroup t)
14602 (unless (zerop cnt)
14603 (setq cnt 0)
14604 (insert "\n"))
14605 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14606 ((eq (car e) :endgroup)
14607 (setq ingroup nil cnt 0)
14608 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14609 ((eq (car e) :startgrouptag)
14610 (setq intaggroup t)
14611 (unless (zerop cnt)
14612 (setq cnt 0)
14613 (insert "\n"))
14614 (insert "[ "))
14615 ((eq (car e) :endgrouptag)
14616 (setq intaggroup nil cnt 0)
14617 (insert "]\n"))
14618 ((equal e '(:newline))
14619 (unless (zerop cnt)
14620 (setq cnt 0)
14621 (insert "\n")
14622 (setq e (car tbl))
14623 (while (equal (car tbl) '(:newline))
14624 (insert "\n")
14625 (setq tbl (cdr tbl)))))
14626 ((equal e '(:grouptags)) (insert " : "))
14628 (setq tg (copy-sequence (car e)) c2 nil)
14629 (if (cdr e)
14630 (setq c (cdr e))
14631 ;; automatically assign a character.
14632 (setq c1 (string-to-char
14633 (downcase (substring
14634 tg (if (= (string-to-char tg) ?@) 1 0)))))
14635 (if (or (rassoc c1 ntable) (rassoc c1 table))
14636 (while (or (rassoc char ntable) (rassoc char table))
14637 (setq char (1+ char)))
14638 (setq c2 c1))
14639 (setq c (or c2 char)))
14640 (when ingroup (push tg (car groups)))
14641 (setq tg (org-add-props tg nil 'face
14642 (cond
14643 ((not (assoc tg table))
14644 (org-get-todo-face tg))
14645 ((member tg current) c-face)
14646 ((member tg inherited) i-face))))
14647 (when (equal (caar tbl) :grouptags)
14648 (org-add-props tg nil 'face 'org-tag-group))
14649 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14650 (insert "[" c "] " tg (make-string
14651 (- fwidth 4 (length tg)) ?\ ))
14652 (push (cons tg c) ntable)
14653 (when (= (cl-incf cnt) ncol)
14654 (insert "\n")
14655 (when (or ingroup intaggroup) (insert " "))
14656 (setq cnt 0)))))
14657 (setq ntable (nreverse ntable))
14658 (insert "\n")
14659 (goto-char (point-min))
14660 (unless expert (org-fit-window-to-buffer))
14661 (setq rtn
14662 (catch 'exit
14663 (while t
14664 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14665 (if (not groups) "no " "")
14666 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14667 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14668 (setq org-last-tag-selection-key c)
14669 (cond
14670 ((= c ?\r) (throw 'exit t))
14671 ((= c ?!)
14672 (setq groups (not groups))
14673 (goto-char (point-min))
14674 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14675 ((= c ?\C-c)
14676 (if (not expert)
14677 (org-fast-tag-show-exit
14678 (setq exit-after-next (not exit-after-next)))
14679 (setq expert nil)
14680 (delete-other-windows)
14681 (set-window-buffer (split-window-vertically) " *Org tags*")
14682 (org-switch-to-buffer-other-window " *Org tags*")
14683 (org-fit-window-to-buffer)))
14684 ((or (= c ?\C-g)
14685 (and (= c ?q) (not (rassoc c ntable))))
14686 (delete-overlay org-tags-overlay)
14687 (setq quit-flag t))
14688 ((= c ?\ )
14689 (setq current nil)
14690 (when exit-after-next (setq exit-after-next 'now)))
14691 ((= c ?\t)
14692 (condition-case nil
14693 (setq tg (completing-read
14694 "Tag: "
14695 (or buffer-tags
14696 (with-current-buffer buf
14697 (setq buffer-tags
14698 (org-get-buffer-tags))))))
14699 (quit (setq tg "")))
14700 (when (string-match "\\S-" tg)
14701 (cl-pushnew (list tg) buffer-tags :test #'equal)
14702 (if (member tg current)
14703 (setq current (delete tg current))
14704 (push tg current)))
14705 (when exit-after-next (setq exit-after-next 'now)))
14706 ((setq e (rassoc c todo-table) tg (car e))
14707 (with-current-buffer buf
14708 (save-excursion (org-todo tg)))
14709 (when exit-after-next (setq exit-after-next 'now)))
14710 ((setq e (rassoc c ntable) tg (car e))
14711 (if (member tg current)
14712 (setq current (delete tg current))
14713 (cl-loop for g in groups do
14714 (when (member tg g)
14715 (dolist (x g) (setq current (delete x current)))))
14716 (push tg current))
14717 (when exit-after-next (setq exit-after-next 'now))))
14719 ;; Create a sorted list
14720 (setq current
14721 (sort current
14722 (lambda (a b)
14723 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14724 (when (eq exit-after-next 'now) (throw 'exit t))
14725 (goto-char (point-min))
14726 (beginning-of-line 2)
14727 (delete-region (point) (point-at-eol))
14728 (org-fast-tag-insert "Current" current c-face)
14729 (org-set-current-tags-overlay current ov-prefix)
14730 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14731 (setq tg (match-string 1))
14732 (add-text-properties
14733 (match-beginning 1) (match-end 1)
14734 (list 'face
14735 (cond
14736 ((member tg current) c-face)
14737 ((member tg inherited) i-face)
14738 (t (get-text-property (match-beginning 1) 'face))))))
14739 (goto-char (point-min)))))
14740 (delete-overlay org-tags-overlay)
14741 (if rtn
14742 (mapconcat 'identity current ":")
14743 nil))))
14745 (defun org-get-tags-string ()
14746 "Get the TAGS string in the current headline."
14747 (unless (org-at-heading-p t)
14748 (user-error "Not on a heading"))
14749 (save-excursion
14750 (beginning-of-line 1)
14751 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14752 (match-string-no-properties 1)
14753 "")))
14755 (defun org-get-tags ()
14756 "Get the list of tags specified in the current headline."
14757 (org-split-string (org-get-tags-string) ":"))
14759 (defun org-get-buffer-tags ()
14760 "Get a table of all tags used in the buffer, for completion."
14761 (org-with-wide-buffer
14762 (goto-char (point-min))
14763 (let ((tag-re (concat org-outline-regexp-bol
14764 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14765 tags)
14766 (while (re-search-forward tag-re nil t)
14767 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14768 (push tag tags)))
14769 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14771 ;;;; The mapping API
14773 (defvar org-agenda-skip-comment-trees)
14774 (defvar org-agenda-skip-function)
14775 (defun org-map-entries (func &optional match scope &rest skip)
14776 "Call FUNC at each headline selected by MATCH in SCOPE.
14778 FUNC is a function or a lisp form. The function will be called without
14779 arguments, with the cursor positioned at the beginning of the headline.
14780 The return values of all calls to the function will be collected and
14781 returned as a list.
14783 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14784 does not need to preserve point. After evaluation, the cursor will be
14785 moved to the end of the line (presumably of the headline of the
14786 processed entry) and search continues from there. Under some
14787 circumstances, this may not produce the wanted results. For example,
14788 if you have removed (e.g. archived) the current (sub)tree it could
14789 mean that the next entry will be skipped entirely. In such cases, you
14790 can specify the position from where search should continue by making
14791 FUNC set the variable `org-map-continue-from' to the desired buffer
14792 position.
14794 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14795 Only headlines that are matched by this query will be considered during
14796 the iteration. When MATCH is nil or t, all headlines will be
14797 visited by the iteration.
14799 SCOPE determines the scope of this command. It can be any of:
14801 nil The current buffer, respecting the restriction if any
14802 tree The subtree started with the entry at point
14803 region The entries within the active region, if any
14804 region-start-level
14805 The entries within the active region, but only those at
14806 the same level than the first one.
14807 file The current buffer, without restriction
14808 file-with-archives
14809 The current buffer, and any archives associated with it
14810 agenda All agenda files
14811 agenda-with-archives
14812 All agenda files with any archive files associated with them
14813 \(file1 file2 ...)
14814 If this is a list, all files in the list will be scanned
14816 The remaining args are treated as settings for the skipping facilities of
14817 the scanner. The following items can be given here:
14819 archive skip trees with the archive tag
14820 comment skip trees with the COMMENT keyword
14821 function or Emacs Lisp form:
14822 will be used as value for `org-agenda-skip-function', so
14823 whenever the function returns a position, FUNC will not be
14824 called for that entry and search will continue from the
14825 position returned
14827 If your function needs to retrieve the tags including inherited tags
14828 at the *current* entry, you can use the value of the variable
14829 `org-scanner-tags' which will be much faster than getting the value
14830 with `org-get-tags-at'. If your function gets properties with
14831 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14832 to t around the call to `org-entry-properties' to get the same speedup.
14833 Note that if your function moves around to retrieve tags and properties at
14834 a *different* entry, you cannot use these techniques."
14835 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14836 (not (org-region-active-p)))
14837 (let* ((org-agenda-archives-mode nil) ; just to make sure
14838 (org-agenda-skip-archived-trees (memq 'archive skip))
14839 (org-agenda-skip-comment-trees (memq 'comment skip))
14840 (org-agenda-skip-function
14841 (car (org-delete-all '(comment archive) skip)))
14842 (org-tags-match-list-sublevels t)
14843 (start-level (eq scope 'region-start-level))
14844 matcher res
14845 org-todo-keywords-for-agenda
14846 org-done-keywords-for-agenda
14847 org-todo-keyword-alist-for-agenda
14848 org-tag-alist-for-agenda
14849 org--matcher-tags-todo-only)
14851 (cond
14852 ((eq match t) (setq matcher t))
14853 ((eq match nil) (setq matcher t))
14854 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14856 (save-excursion
14857 (save-restriction
14858 (cond ((eq scope 'tree)
14859 (org-back-to-heading t)
14860 (org-narrow-to-subtree)
14861 (setq scope nil))
14862 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14863 (org-region-active-p))
14864 ;; If needed, set start-level to a string like "2"
14865 (when start-level
14866 (save-excursion
14867 (goto-char (region-beginning))
14868 (unless (org-at-heading-p) (outline-next-heading))
14869 (setq start-level (org-current-level))))
14870 (narrow-to-region (region-beginning)
14871 (save-excursion
14872 (goto-char (region-end))
14873 (unless (and (bolp) (org-at-heading-p))
14874 (outline-next-heading))
14875 (point)))
14876 (setq scope nil)))
14878 (if (not scope)
14879 (progn
14880 (org-agenda-prepare-buffers
14881 (and buffer-file-name (list buffer-file-name)))
14882 (setq res
14883 (org-scan-tags
14884 func matcher org--matcher-tags-todo-only start-level)))
14885 ;; Get the right scope
14886 (cond
14887 ((and scope (listp scope) (symbolp (car scope)))
14888 (setq scope (eval scope)))
14889 ((eq scope 'agenda)
14890 (setq scope (org-agenda-files t)))
14891 ((eq scope 'agenda-with-archives)
14892 (setq scope (org-agenda-files t))
14893 (setq scope (org-add-archive-files scope)))
14894 ((eq scope 'file)
14895 (setq scope (and buffer-file-name (list buffer-file-name))))
14896 ((eq scope 'file-with-archives)
14897 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14898 (org-agenda-prepare-buffers scope)
14899 (dolist (file scope)
14900 (with-current-buffer (org-find-base-buffer-visiting file)
14901 (org-with-wide-buffer
14902 (goto-char (point-min))
14903 (setq res
14904 (append
14906 (org-scan-tags
14907 func matcher org--matcher-tags-todo-only)))))))))
14908 res)))
14910 ;;; Properties API
14912 (defconst org-special-properties
14913 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14914 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14915 "The special properties valid in Org mode.
14916 These are properties that are not defined in the property drawer,
14917 but in some other way.")
14919 (defconst org-default-properties
14920 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14921 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14922 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14923 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14924 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14925 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14926 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14927 "Some properties that are used by Org mode for various purposes.
14928 Being in this list makes sure that they are offered for completion.")
14930 (defun org--valid-property-p (property)
14931 "Non nil when string PROPERTY is a valid property name."
14932 (not
14933 (or (equal property "")
14934 (string-match-p "\\s-" property))))
14936 (defun org--update-property-plist (key val props)
14937 "Associate KEY to VAL in alist PROPS.
14938 Modifications are made by side-effect. Return new alist."
14939 (let* ((appending (string= (substring key -1) "+"))
14940 (key (if appending (substring key 0 -1) key))
14941 (old (assoc-string key props t)))
14942 (if (not old) (cons (cons key val) props)
14943 (setcdr old (if appending (concat (cdr old) " " val) val))
14944 props)))
14946 (defun org-get-property-block (&optional beg force)
14947 "Return the (beg . end) range of the body of the property drawer.
14948 BEG is the beginning of the current subtree, or of the part
14949 before the first headline. If it is not given, it will be found.
14950 If the drawer does not exist, create it if FORCE is non-nil, or
14951 return nil."
14952 (org-with-wide-buffer
14953 (when beg (goto-char beg))
14954 (unless (org-before-first-heading-p)
14955 (let ((beg (cond (beg)
14956 ((or (not (featurep 'org-inlinetask))
14957 (org-inlinetask-in-task-p))
14958 (org-back-to-heading t))
14959 (t (org-with-limited-levels (org-back-to-heading t))))))
14960 (forward-line)
14961 (when (looking-at-p org-planning-line-re) (forward-line))
14962 (cond ((looking-at org-property-drawer-re)
14963 (forward-line)
14964 (cons (point) (progn (goto-char (match-end 0))
14965 (line-beginning-position))))
14966 (force
14967 (goto-char beg)
14968 (org-insert-property-drawer)
14969 (let ((pos (save-excursion (search-forward ":END:")
14970 (line-beginning-position))))
14971 (cons pos pos))))))))
14973 (defun org-at-property-p ()
14974 "Non-nil when point is inside a property drawer.
14975 See `org-property-re' for match data, if applicable."
14976 (save-excursion
14977 (beginning-of-line)
14978 (and (looking-at org-property-re)
14979 (let ((property-drawer (save-match-data (org-get-property-block))))
14980 (and property-drawer
14981 (>= (point) (car property-drawer))
14982 (< (point) (cdr property-drawer)))))))
14984 (defun org-property-action ()
14985 "Do an action on properties."
14986 (interactive)
14987 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14988 (let ((c (read-char-exclusive)))
14989 (cl-case c
14990 (?s (call-interactively #'org-set-property))
14991 (?d (call-interactively #'org-delete-property))
14992 (?D (call-interactively #'org-delete-property-globally))
14993 (?c (call-interactively #'org-compute-property-at-point))
14994 (otherwise (user-error "No such property action %c" c)))))
14996 (defun org-inc-effort ()
14997 "Increment the value of the effort property in the current entry."
14998 (interactive)
14999 (org-set-effort t))
15001 (defvar org-clock-effort) ; Defined in org-clock.el.
15002 (defvar org-clock-current-task) ; Defined in org-clock.el.
15003 (defun org-set-effort (&optional increment value)
15004 "Set the effort property of the current entry.
15005 If INCREMENT is non-nil, set the property to the next allowed
15006 value. Otherwise, if optional argument VALUE is provided, use
15007 it. Eventually, prompt for the new value if none of the previous
15008 variables is set."
15009 (interactive "P")
15010 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
15011 (current (org-entry-get nil org-effort-property))
15012 (value
15013 (cond
15014 (increment
15015 (unless allowed (user-error "Allowed effort values are not set"))
15016 (or (cl-caadr (member (list current) allowed))
15017 (user-error "Unknown value %S among allowed values" current)))
15018 (value
15019 (if (stringp value) value
15020 (error "Invalid effort value: %S" value)))
15022 (let ((must-match
15023 (and allowed
15024 (not (get-text-property 0 'org-unrestricted
15025 (caar allowed))))))
15026 (completing-read "Effort: " allowed nil must-match))))))
15027 (unless (equal current value)
15028 (org-entry-put nil org-effort-property value))
15029 (org-refresh-property '((effort . identity)
15030 (effort-minutes . org-duration-to-minutes))
15031 value)
15032 (when (equal (org-get-heading t t t t)
15033 (bound-and-true-p org-clock-current-task))
15034 (setq org-clock-effort (org-get-at-bol 'effort))
15035 (org-clock-update-mode-line))
15036 (message "%s is now %s" org-effort-property value)))
15038 (defun org-entry-properties (&optional pom which)
15039 "Get all properties of the current entry.
15041 When POM is a buffer position, get all properties from the entry
15042 there instead.
15044 This includes the TODO keyword, the tags, time strings for
15045 deadline, scheduled, and clocking, and any additional properties
15046 defined in the entry.
15048 If WHICH is nil or `all', get all properties. If WHICH is
15049 `special' or `standard', only get that subclass. If WHICH is
15050 a string, only get that property.
15052 Return value is an alist. Keys are properties, as upcased
15053 strings."
15054 (org-with-point-at pom
15055 (when (and (derived-mode-p 'org-mode)
15056 (ignore-errors (org-back-to-heading t)))
15057 (catch 'exit
15058 (let* ((beg (point))
15059 (specific (and (stringp which) (upcase which)))
15060 (which (cond ((not specific) which)
15061 ((member specific org-special-properties) 'special)
15062 (t 'standard)))
15063 props)
15064 ;; Get the special properties, like TODO and TAGS.
15065 (when (memq which '(nil all special))
15066 (when (or (not specific) (string= specific "CLOCKSUM"))
15067 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15068 (when clocksum
15069 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15070 props)))
15071 (when specific (throw 'exit props)))
15072 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15073 (let ((clocksumt (get-text-property (point)
15074 :org-clock-minutes-today)))
15075 (when clocksumt
15076 (push (cons "CLOCKSUM_T"
15077 (org-duration-from-minutes clocksumt))
15078 props)))
15079 (when specific (throw 'exit props)))
15080 (when (or (not specific) (string= specific "ITEM"))
15081 (let ((case-fold-search nil))
15082 (when (looking-at org-complex-heading-regexp)
15083 (push (cons "ITEM"
15084 (let ((title (match-string-no-properties 4)))
15085 (if (org-string-nw-p title)
15086 (org-remove-tabs title)
15087 "")))
15088 props)))
15089 (when specific (throw 'exit props)))
15090 (when (or (not specific) (string= specific "TODO"))
15091 (let ((case-fold-search nil))
15092 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15093 (push (cons "TODO" (match-string-no-properties 2)) props)))
15094 (when specific (throw 'exit props)))
15095 (when (or (not specific) (string= specific "PRIORITY"))
15096 (push (cons "PRIORITY"
15097 (if (looking-at org-priority-regexp)
15098 (match-string-no-properties 2)
15099 (char-to-string org-default-priority)))
15100 props)
15101 (when specific (throw 'exit props)))
15102 (when (or (not specific) (string= specific "FILE"))
15103 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15104 props)
15105 (when specific (throw 'exit props)))
15106 (when (or (not specific) (string= specific "TAGS"))
15107 (let ((value (org-string-nw-p (org-get-tags-string))))
15108 (when value (push (cons "TAGS" value) props)))
15109 (when specific (throw 'exit props)))
15110 (when (or (not specific) (string= specific "ALLTAGS"))
15111 (let ((value (org-get-tags-at)))
15112 (when value
15113 (push (cons "ALLTAGS"
15114 (format ":%s:" (mapconcat #'identity value ":")))
15115 props)))
15116 (when specific (throw 'exit props)))
15117 (when (or (not specific) (string= specific "BLOCKED"))
15118 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15119 (when specific (throw 'exit props)))
15120 (when (or (not specific)
15121 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15122 (forward-line)
15123 (when (looking-at-p org-planning-line-re)
15124 (end-of-line)
15125 (let ((bol (line-beginning-position))
15126 ;; Backward compatibility: time keywords used to
15127 ;; be configurable (before 8.3). Make sure we
15128 ;; get the correct keyword.
15129 (key-assoc `(("CLOSED" . ,org-closed-string)
15130 ("DEADLINE" . ,org-deadline-string)
15131 ("SCHEDULED" . ,org-scheduled-string))))
15132 (dolist (pair (if specific (list (assoc specific key-assoc))
15133 key-assoc))
15134 (save-excursion
15135 (when (search-backward (cdr pair) bol t)
15136 (goto-char (match-end 0))
15137 (skip-chars-forward " \t")
15138 (and (looking-at org-ts-regexp-both)
15139 (push (cons (car pair)
15140 (match-string-no-properties 0))
15141 props)))))))
15142 (when specific (throw 'exit props)))
15143 (when (or (not specific)
15144 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15145 (let ((find-ts
15146 (lambda (end ts)
15147 ;; Fix next time-stamp before END. TS is the
15148 ;; list of time-stamps found so far.
15149 (let ((ts ts)
15150 (regexp (cond
15151 ((string= specific "TIMESTAMP")
15152 org-ts-regexp)
15153 ((string= specific "TIMESTAMP_IA")
15154 org-ts-regexp-inactive)
15155 ((assoc "TIMESTAMP_IA" ts)
15156 org-ts-regexp)
15157 ((assoc "TIMESTAMP" ts)
15158 org-ts-regexp-inactive)
15159 (t org-ts-regexp-both))))
15160 (catch 'next
15161 (while (re-search-forward regexp end t)
15162 (backward-char)
15163 (let ((object (org-element-context)))
15164 ;; Accept to match timestamps in node
15165 ;; properties, too.
15166 (when (memq (org-element-type object)
15167 '(node-property timestamp))
15168 (let ((type
15169 (org-element-property :type object)))
15170 (cond
15171 ((and (memq type '(active active-range))
15172 (not (equal specific "TIMESTAMP_IA")))
15173 (unless (assoc "TIMESTAMP" ts)
15174 (push (cons "TIMESTAMP"
15175 (org-element-property
15176 :raw-value object))
15178 (when specific (throw 'exit ts))))
15179 ((and (memq type '(inactive inactive-range))
15180 (not (string= specific "TIMESTAMP")))
15181 (unless (assoc "TIMESTAMP_IA" ts)
15182 (push (cons "TIMESTAMP_IA"
15183 (org-element-property
15184 :raw-value object))
15186 (when specific (throw 'exit ts))))))
15187 ;; Both timestamp types are found,
15188 ;; move to next part.
15189 (when (= (length ts) 2) (throw 'next ts)))))
15190 ts)))))
15191 (goto-char beg)
15192 ;; First look for timestamps within headline.
15193 (let ((ts (funcall find-ts (line-end-position) nil)))
15194 (if (= (length ts) 2) (setq props (nconc ts props))
15195 ;; Then find timestamps in the section, skipping
15196 ;; planning line.
15197 (let ((end (save-excursion (outline-next-heading))))
15198 (forward-line)
15199 (when (looking-at-p org-planning-line-re) (forward-line))
15200 (setq props (nconc (funcall find-ts end ts) props))))))))
15201 ;; Get the standard properties, like :PROP:.
15202 (when (memq which '(nil all standard))
15203 ;; If we are looking after a specific property, delegate
15204 ;; to `org-entry-get', which is faster. However, make an
15205 ;; exception for "CATEGORY", since it can be also set
15206 ;; through keywords (i.e. #+CATEGORY).
15207 (if (and specific (not (equal specific "CATEGORY")))
15208 (let ((value (org-entry-get beg specific nil t)))
15209 (throw 'exit (and value (list (cons specific value)))))
15210 (let ((range (org-get-property-block beg)))
15211 (when range
15212 (let ((end (cdr range)) seen-base)
15213 (goto-char (car range))
15214 ;; Unlike to `org--update-property-plist', we
15215 ;; handle the case where base values is found
15216 ;; after its extension. We also forbid standard
15217 ;; properties to be named as special properties.
15218 (while (re-search-forward org-property-re end t)
15219 (let* ((key (upcase (match-string-no-properties 2)))
15220 (extendp (string-match-p "\\+\\'" key))
15221 (key-base (if extendp (substring key 0 -1) key))
15222 (value (match-string-no-properties 3)))
15223 (cond
15224 ((member-ignore-case key-base org-special-properties))
15225 (extendp
15226 (setq props
15227 (org--update-property-plist key value props)))
15228 ((member key seen-base))
15229 (t (push key seen-base)
15230 (let ((p (assoc-string key props t)))
15231 (if p (setcdr p (concat value " " (cdr p)))
15232 (push (cons key value) props))))))))))))
15233 (unless (assoc "CATEGORY" props)
15234 (push (cons "CATEGORY" (org-get-category beg)) props)
15235 (when (string= specific "CATEGORY") (throw 'exit props)))
15236 ;; Return value.
15237 props)))))
15239 (defun org--property-local-values (property literal-nil)
15240 "Return value for PROPERTY in current entry.
15241 Value is a list whose car is the base value for PROPERTY and cdr
15242 a list of accumulated values. Return nil if neither is found in
15243 the entry. Also return nil when PROPERTY is set to \"nil\",
15244 unless LITERAL-NIL is non-nil."
15245 (let ((range (org-get-property-block)))
15246 (when range
15247 (goto-char (car range))
15248 (let* ((case-fold-search t)
15249 (end (cdr range))
15250 (value
15251 ;; Base value.
15252 (save-excursion
15253 (let ((v (and (re-search-forward
15254 (org-re-property property nil t) end t)
15255 (match-string-no-properties 3))))
15256 (list (if literal-nil v (org-not-nil v)))))))
15257 ;; Find additional values.
15258 (let* ((property+ (org-re-property (concat property "+") nil t)))
15259 (while (re-search-forward property+ end t)
15260 (push (match-string-no-properties 3) value)))
15261 ;; Return final values.
15262 (and (not (equal value '(nil))) (nreverse value))))))
15264 (defun org--property-global-value (property literal-nil)
15265 "Return value for PROPERTY in current buffer.
15266 Return value is a string. Return nil if property is not set
15267 globally. Also return nil when PROPERTY is set to \"nil\",
15268 unless LITERAL-NIL is non-nil."
15269 (let ((global
15270 (cdr (or (assoc-string property org-file-properties t)
15271 (assoc-string property org-global-properties t)
15272 (assoc-string property org-global-properties-fixed t)))))
15273 (if literal-nil global (org-not-nil global))))
15275 (defun org-entry-get (pom property &optional inherit literal-nil)
15276 "Get value of PROPERTY for entry or content at point-or-marker POM.
15278 If INHERIT is non-nil and the entry does not have the property,
15279 then also check higher levels of the hierarchy. If INHERIT is
15280 the symbol `selective', use inheritance only if the setting in
15281 `org-use-property-inheritance' selects PROPERTY for inheritance.
15283 If the property is present but empty, the return value is the
15284 empty string. If the property is not present at all, nil is
15285 returned. In any other case, return the value as a string.
15286 Search is case-insensitive.
15288 If LITERAL-NIL is set, return the string value \"nil\" as
15289 a string, do not interpret it as the list atom nil. This is used
15290 for inheritance when a \"nil\" value can supersede a non-nil
15291 value higher up the hierarchy."
15292 (org-with-point-at pom
15293 (cond
15294 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15295 ;; We need a special property. Use `org-entry-properties' to
15296 ;; retrieve it, but specify the wanted property.
15297 (cdr (assoc-string property (org-entry-properties nil property))))
15298 ((and inherit
15299 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15300 (org-entry-get-with-inheritance property literal-nil))
15302 (let* ((local (org--property-local-values property literal-nil))
15303 (value (and local (mapconcat #'identity (delq nil local) " "))))
15304 (if literal-nil value (org-not-nil value)))))))
15306 (defun org-property-or-variable-value (var &optional inherit)
15307 "Check if there is a property fixing the value of VAR.
15308 If yes, return this value. If not, return the current value of the variable."
15309 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15310 (if (and prop (stringp prop) (string-match "\\S-" prop))
15311 (read prop)
15312 (symbol-value var))))
15314 (defun org-entry-delete (pom property)
15315 "Delete PROPERTY from entry at point-or-marker POM.
15316 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15317 non-nil when a property was removed."
15318 (org-with-point-at pom
15319 (pcase (org-get-property-block)
15320 (`(,begin . ,origin)
15321 (let* ((end (copy-marker origin))
15322 (re (org-re-property
15323 (concat (regexp-quote property) "\\+?") t t)))
15324 (goto-char begin)
15325 (while (re-search-forward re end t)
15326 (delete-region (match-beginning 0) (line-beginning-position 2)))
15327 ;; If drawer is empty, remove it altogether.
15328 (when (= begin end)
15329 (delete-region (line-beginning-position 0)
15330 (line-beginning-position 2)))
15331 ;; Return non-nil if some property was removed.
15332 (prog1 (/= end origin) (set-marker end nil))))
15333 (_ nil))))
15335 ;; Multi-values properties are properties that contain multiple values
15336 ;; These values are assumed to be single words, separated by whitespace.
15337 (defun org-entry-add-to-multivalued-property (pom property value)
15338 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15339 (let* ((old (org-entry-get pom property))
15340 (values (and old (split-string old))))
15341 (setq value (org-entry-protect-space value))
15342 (unless (member value values)
15343 (setq values (append values (list value)))
15344 (org-entry-put pom property (mapconcat #'identity values " ")))))
15346 (defun org-entry-remove-from-multivalued-property (pom property value)
15347 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15348 (let* ((old (org-entry-get pom property))
15349 (values (and old (split-string old))))
15350 (setq value (org-entry-protect-space value))
15351 (when (member value values)
15352 (setq values (delete value values))
15353 (org-entry-put pom property (mapconcat #'identity values " ")))))
15355 (defun org-entry-member-in-multivalued-property (pom property value)
15356 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15357 (let* ((old (org-entry-get pom property))
15358 (values (and old (split-string old))))
15359 (setq value (org-entry-protect-space value))
15360 (member value values)))
15362 (defun org-entry-get-multivalued-property (pom property)
15363 "Return a list of values in a multivalued property."
15364 (let* ((value (org-entry-get pom property))
15365 (values (and value (split-string value))))
15366 (mapcar #'org-entry-restore-space values)))
15368 (defun org-entry-put-multivalued-property (pom property &rest values)
15369 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15370 VALUES should be a list of strings. Spaces will be protected."
15371 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15372 (let* ((value (org-entry-get pom property))
15373 (values (and value (split-string value))))
15374 (mapcar #'org-entry-restore-space values)))
15376 (defun org-entry-protect-space (s)
15377 "Protect spaces and newline in string S."
15378 (while (string-match " " s)
15379 (setq s (replace-match "%20" t t s)))
15380 (while (string-match "\n" s)
15381 (setq s (replace-match "%0A" t t s)))
15384 (defun org-entry-restore-space (s)
15385 "Restore spaces and newline in string S."
15386 (while (string-match "%20" s)
15387 (setq s (replace-match " " t t s)))
15388 (while (string-match "%0A" s)
15389 (setq s (replace-match "\n" t t s)))
15392 (defvar org-entry-property-inherited-from (make-marker)
15393 "Marker pointing to the entry from where a property was inherited.
15394 Each call to `org-entry-get-with-inheritance' will set this marker to the
15395 location of the entry where the inheritance search matched. If there was
15396 no match, the marker will point nowhere.
15397 Note that also `org-entry-get' calls this function, if the INHERIT flag
15398 is set.")
15400 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15401 "Get PROPERTY of entry or content at point, search higher levels if needed.
15402 The search will stop at the first ancestor which has the property defined.
15403 If the value found is \"nil\", return nil to show that the property
15404 should be considered as undefined (this is the meaning of nil here).
15405 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15406 (move-marker org-entry-property-inherited-from nil)
15407 (org-with-wide-buffer
15408 (let (value)
15409 (catch 'exit
15410 (while t
15411 (let ((v (org--property-local-values property literal-nil)))
15412 (when v
15413 (setq value
15414 (concat (mapconcat #'identity (delq nil v) " ")
15415 (and value " ")
15416 value)))
15417 (cond
15418 ((car v)
15419 (org-back-to-heading t)
15420 (move-marker org-entry-property-inherited-from (point))
15421 (throw 'exit nil))
15422 ((org-up-heading-safe))
15424 (let ((global (org--property-global-value property literal-nil)))
15425 (cond ((not global))
15426 (value (setq value (concat global " " value)))
15427 (t (setq value global))))
15428 (throw 'exit nil))))))
15429 (if literal-nil value (org-not-nil value)))))
15431 (defvar org-property-changed-functions nil
15432 "Hook called when the value of a property has changed.
15433 Each hook function should accept two arguments, the name of the property
15434 and the new value.")
15436 (defun org-entry-put (pom property value)
15437 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15439 If the value is nil, it is converted to the empty string. If it
15440 is not a string, an error is raised. Also raise an error on
15441 invalid property names.
15443 PROPERTY can be any regular property (see
15444 `org-special-properties'). It can also be \"TODO\",
15445 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15447 For the last two properties, VALUE may have any of the special
15448 values \"earlier\" and \"later\". The function then increases or
15449 decreases scheduled or deadline date by one day."
15450 (cond ((null value) (setq value ""))
15451 ((not (stringp value)) (error "Properties values should be strings"))
15452 ((not (org--valid-property-p property))
15453 (user-error "Invalid property name: \"%s\"" property)))
15454 (org-with-point-at pom
15455 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15456 (org-back-to-heading t)
15457 (org-with-limited-levels (org-back-to-heading t)))
15458 (let ((beg (point)))
15459 (cond
15460 ((equal property "TODO")
15461 (cond ((not (org-string-nw-p value)) (setq value 'none))
15462 ((not (member value org-todo-keywords-1))
15463 (user-error "\"%s\" is not a valid TODO state" value)))
15464 (org-todo value)
15465 (org-set-tags nil 'align))
15466 ((equal property "PRIORITY")
15467 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15468 (org-set-tags nil 'align))
15469 ((equal property "SCHEDULED")
15470 (forward-line)
15471 (if (and (looking-at-p org-planning-line-re)
15472 (re-search-forward
15473 org-scheduled-time-regexp (line-end-position) t))
15474 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15475 ((string= value "later") (org-timestamp-change 1 'day))
15476 ((string= value "") (org-schedule '(4)))
15477 (t (org-schedule nil value)))
15478 (if (member value '("earlier" "later" ""))
15479 (call-interactively #'org-schedule)
15480 (org-schedule nil value))))
15481 ((equal property "DEADLINE")
15482 (forward-line)
15483 (if (and (looking-at-p org-planning-line-re)
15484 (re-search-forward
15485 org-deadline-time-regexp (line-end-position) t))
15486 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15487 ((string= value "later") (org-timestamp-change 1 'day))
15488 ((string= value "") (org-deadline '(4)))
15489 (t (org-deadline nil value)))
15490 (if (member value '("earlier" "later" ""))
15491 (call-interactively #'org-deadline)
15492 (org-deadline nil value))))
15493 ((member property org-special-properties)
15494 (error "The %s property cannot be set with `org-entry-put'" property))
15496 (let* ((range (org-get-property-block beg 'force))
15497 (end (cdr range))
15498 (case-fold-search t))
15499 (goto-char (car range))
15500 (if (re-search-forward (org-re-property property nil t) end t)
15501 (progn (delete-region (match-beginning 0) (match-end 0))
15502 (goto-char (match-beginning 0)))
15503 (goto-char end)
15504 (insert "\n")
15505 (backward-char))
15506 (insert ":" property ":")
15507 (when value (insert " " value))
15508 (org-indent-line)))))
15509 (run-hook-with-args 'org-property-changed-functions property value)))
15511 (defun org-buffer-property-keys (&optional specials defaults columns)
15512 "Get all property keys in the current buffer.
15514 When SPECIALS is non-nil, also list the special properties that
15515 reflect things like tags and TODO state.
15517 When DEFAULTS is non-nil, also include properties that has
15518 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15519 DESCRIPTION, LOCATION, and LOGGING and others.
15521 When COLUMNS in non-nil, also include property names given in
15522 COLUMN formats in the current buffer."
15523 (let ((case-fold-search t)
15524 (props (append
15525 (and specials org-special-properties)
15526 (and defaults (cons org-effort-property org-default-properties))
15527 nil)))
15528 (org-with-wide-buffer
15529 (goto-char (point-min))
15530 (while (re-search-forward org-property-start-re nil t)
15531 (catch :skip
15532 (let ((range (org-get-property-block)))
15533 (unless range (throw :skip nil))
15534 (goto-char (car range))
15535 (let ((begin (car range))
15536 (end (cdr range)))
15537 ;; Make sure that found property block is not located
15538 ;; before current point, as it would generate an infloop.
15539 ;; It can happen, for example, in the following
15540 ;; situation:
15542 ;; * Headline
15543 ;; :PROPERTIES:
15544 ;; ...
15545 ;; :END:
15546 ;; *************** Inlinetask
15547 ;; #+BEGIN_EXAMPLE
15548 ;; :PROPERTIES:
15549 ;; #+END_EXAMPLE
15551 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15552 (while (< (point) end)
15553 (let ((p (progn (looking-at org-property-re)
15554 (match-string-no-properties 2))))
15555 ;; Only add true property name, not extension symbol.
15556 (push (if (not (string-match-p "\\+\\'" p)) p
15557 (substring p 0 -1))
15558 props))
15559 (forward-line))))
15560 (outline-next-heading)))
15561 (when columns
15562 (goto-char (point-min))
15563 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15564 (let ((element (org-element-at-point)))
15565 (when (memq (org-element-type element) '(keyword node-property))
15566 (let ((value (org-element-property :value element))
15567 (start 0))
15568 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15569 \\(?:{[^}]+}\\)?"
15570 value start)
15571 (setq start (match-end 0))
15572 (let ((p (match-string-no-properties 1 value)))
15573 (unless (member-ignore-case p org-special-properties)
15574 (push p props))))))))))
15575 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15577 (defun org-property-values (key)
15578 "List all non-nil values of property KEY in current buffer."
15579 (org-with-wide-buffer
15580 (goto-char (point-min))
15581 (let ((case-fold-search t)
15582 (re (org-re-property key))
15583 values)
15584 (while (re-search-forward re nil t)
15585 (push (org-entry-get (point) key) values))
15586 (delete-dups values))))
15588 (defun org-insert-property-drawer ()
15589 "Insert a property drawer into the current entry."
15590 (org-with-wide-buffer
15591 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15592 (org-back-to-heading t)
15593 (org-with-limited-levels (org-back-to-heading t)))
15594 (forward-line)
15595 (when (looking-at-p org-planning-line-re) (forward-line))
15596 (unless (looking-at-p org-property-drawer-re)
15597 ;; Make sure we start editing a line from current entry, not from
15598 ;; next one. It prevents extending text properties or overlays
15599 ;; belonging to the latter.
15600 (when (bolp) (backward-char))
15601 (let ((begin (1+ (point)))
15602 (inhibit-read-only t))
15603 (insert "\n:PROPERTIES:\n:END:")
15604 (when (eobp) (insert "\n"))
15605 (org-indent-region begin (point))))))
15607 (defun org-insert-drawer (&optional arg drawer)
15608 "Insert a drawer at point.
15610 When optional argument ARG is non-nil, insert a property drawer.
15612 Optional argument DRAWER, when non-nil, is a string representing
15613 drawer's name. Otherwise, the user is prompted for a name.
15615 If a region is active, insert the drawer around that region
15616 instead.
15618 Point is left between drawer's boundaries."
15619 (interactive "P")
15620 (let* ((drawer (if arg "PROPERTIES"
15621 (or drawer (read-from-minibuffer "Drawer: ")))))
15622 (cond
15623 ;; With C-u, fall back on `org-insert-property-drawer'
15624 (arg (org-insert-property-drawer))
15625 ;; Check validity of suggested drawer's name.
15626 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15627 (user-error "Invalid drawer name"))
15628 ;; With an active region, insert a drawer at point.
15629 ((not (org-region-active-p))
15630 (progn
15631 (unless (bolp) (insert "\n"))
15632 (insert (format ":%s:\n\n:END:\n" drawer))
15633 (forward-line -2)))
15634 ;; Otherwise, insert the drawer at point
15636 (let ((rbeg (region-beginning))
15637 (rend (copy-marker (region-end))))
15638 (unwind-protect
15639 (progn
15640 (goto-char rbeg)
15641 (beginning-of-line)
15642 (when (save-excursion
15643 (re-search-forward org-outline-regexp-bol rend t))
15644 (user-error "Drawers cannot contain headlines"))
15645 ;; Position point at the beginning of the first
15646 ;; non-blank line in region. Insert drawer's opening
15647 ;; there, then indent it.
15648 (org-skip-whitespace)
15649 (beginning-of-line)
15650 (insert ":" drawer ":\n")
15651 (forward-line -1)
15652 (indent-for-tab-command)
15653 ;; Move point to the beginning of the first blank line
15654 ;; after the last non-blank line in region. Insert
15655 ;; drawer's closing, then indent it.
15656 (goto-char rend)
15657 (skip-chars-backward " \r\t\n")
15658 (insert "\n:END:")
15659 (deactivate-mark t)
15660 (indent-for-tab-command)
15661 (unless (eolp) (insert "\n")))
15662 ;; Clear marker, whatever the outcome of insertion is.
15663 (set-marker rend nil)))))))
15665 (defvar org-property-set-functions-alist nil
15666 "Property set function alist.
15667 Each entry should have the following format:
15669 (PROPERTY . READ-FUNCTION)
15671 The read function will be called with the same argument as
15672 `org-completing-read'.")
15674 (defun org-set-property-function (property)
15675 "Get the function that should be used to set PROPERTY.
15676 This is computed according to `org-property-set-functions-alist'."
15677 (or (cdr (assoc property org-property-set-functions-alist))
15678 'org-completing-read))
15680 (defun org-read-property-value (property)
15681 "Read PROPERTY value from user."
15682 (let* ((completion-ignore-case t)
15683 (allowed (org-property-get-allowed-values nil property 'table))
15684 (cur (org-entry-get nil property))
15685 (prompt (concat property " value"
15686 (if (and cur (string-match "\\S-" cur))
15687 (concat " [" cur "]") "") ": "))
15688 (set-function (org-set-property-function property))
15689 (val (if allowed
15690 (funcall set-function prompt allowed nil
15691 (not (get-text-property 0 'org-unrestricted
15692 (caar allowed))))
15693 (funcall set-function prompt
15694 (mapcar 'list (org-property-values property))
15695 nil nil "" nil cur))))
15696 (org-trim val)))
15698 (defvar org-last-set-property nil)
15699 (defvar org-last-set-property-value nil)
15700 (defun org-read-property-name ()
15701 "Read a property name."
15702 (let ((completion-ignore-case t)
15703 (default-prop (or (and (org-at-property-p)
15704 (match-string-no-properties 2))
15705 org-last-set-property)))
15706 (org-completing-read
15707 (concat "Property"
15708 (if default-prop (concat " [" default-prop "]") "")
15709 ": ")
15710 (mapcar #'list (org-buffer-property-keys nil t t))
15711 nil nil nil nil default-prop)))
15713 (defun org-set-property-and-value (use-last)
15714 "Allow to set [PROPERTY]: [value] direction from prompt.
15715 When use-default, don't even ask, just use the last
15716 \"[PROPERTY]: [value]\" string from the history."
15717 (interactive "P")
15718 (let* ((completion-ignore-case t)
15719 (pv (or (and use-last org-last-set-property-value)
15720 (org-completing-read
15721 "Enter a \"[Property]: [value]\" pair: "
15722 nil nil nil nil nil
15723 org-last-set-property-value)))
15724 prop val)
15725 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15726 (setq prop (match-string 1 pv)
15727 val (match-string 2 pv))
15728 (org-set-property prop val))))
15730 (defun org-set-property (property value)
15731 "In the current entry, set PROPERTY to VALUE.
15733 When called interactively, this will prompt for a property name, offering
15734 completion on existing and default properties. And then it will prompt
15735 for a value, offering completion either on allowed values (via an inherited
15736 xxx_ALL property) or on existing values in other instances of this property
15737 in the current file.
15739 Throw an error when trying to set a property with an invalid name."
15740 (interactive (list nil nil))
15741 (let ((property (or property (org-read-property-name))))
15742 ;; `org-entry-put' also makes the following check, but this one
15743 ;; avoids polluting `org-last-set-property' and
15744 ;; `org-last-set-property-value' needlessly.
15745 (unless (org--valid-property-p property)
15746 (user-error "Invalid property name: \"%s\"" property))
15747 (let ((value (or value (org-read-property-value property)))
15748 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15749 (setq org-last-set-property property)
15750 (setq org-last-set-property-value (concat property ": " value))
15751 ;; Possibly postprocess the inserted value:
15752 (when fn (setq value (funcall fn value)))
15753 (unless (equal (org-entry-get nil property) value)
15754 (org-entry-put nil property value)))))
15756 (defun org-find-property (property &optional value)
15757 "Find first entry in buffer that sets PROPERTY.
15759 When optional argument VALUE is non-nil, only consider an entry
15760 if it contains PROPERTY set to this value. If PROPERTY should be
15761 explicitly set to nil, use string \"nil\" for VALUE.
15763 Return position where the entry begins, or nil if there is no
15764 such entry. If narrowing is in effect, only search the visible
15765 part of the buffer."
15766 (save-excursion
15767 (goto-char (point-min))
15768 (let ((case-fold-search t)
15769 (re (org-re-property property nil (not value) value)))
15770 (catch 'exit
15771 (while (re-search-forward re nil t)
15772 (when (if value (org-at-property-p)
15773 (org-entry-get (point) property nil t))
15774 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15776 (defun org-delete-property (property)
15777 "In the current entry, delete PROPERTY."
15778 (interactive
15779 (let* ((completion-ignore-case t)
15780 (cat (org-entry-get (point) "CATEGORY"))
15781 (props0 (org-entry-properties nil 'standard))
15782 (props (if cat props0
15783 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15784 (prop (if (< 1 (length props))
15785 (completing-read "Property: " props nil t)
15786 (caar props))))
15787 (list prop)))
15788 (if (not property)
15789 (message "No property to delete in this entry")
15790 (org-entry-delete nil property)
15791 (message "Property \"%s\" deleted" property)))
15793 (defun org-delete-property-globally (property)
15794 "Remove PROPERTY globally, from all entries.
15795 This function ignores narrowing, if any."
15796 (interactive
15797 (let* ((completion-ignore-case t)
15798 (prop (completing-read
15799 "Globally remove property: "
15800 (mapcar #'list (org-buffer-property-keys)))))
15801 (list prop)))
15802 (org-with-wide-buffer
15803 (goto-char (point-min))
15804 (let ((count 0)
15805 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15806 (while (re-search-forward re nil t)
15807 (when (org-entry-delete (point) property) (cl-incf count)))
15808 (message "Property \"%s\" removed from %d entries" property count))))
15810 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15812 (defun org-compute-property-at-point ()
15813 "Compute the property at point.
15814 This looks for an enclosing column format, extracts the operator and
15815 then applies it to the property in the column format's scope."
15816 (interactive)
15817 (unless (org-at-property-p)
15818 (user-error "Not at a property"))
15819 (let ((prop (match-string-no-properties 2)))
15820 (org-columns-get-format-and-top-level)
15821 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15822 (user-error "No operator defined for property %s" prop))
15823 (org-columns-compute prop)))
15825 (defvar org-property-allowed-value-functions nil
15826 "Hook for functions supplying allowed values for a specific property.
15827 The functions must take a single argument, the name of the property, and
15828 return a flat list of allowed values. If \":ETC\" is one of
15829 the values, this means that these values are intended as defaults for
15830 completion, but that other values should be allowed too.
15831 The functions must return nil if they are not responsible for this
15832 property.")
15834 (defun org-property-get-allowed-values (pom property &optional table)
15835 "Get allowed values for the property PROPERTY.
15836 When TABLE is non-nil, return an alist that can directly be used for
15837 completion."
15838 (let (vals)
15839 (cond
15840 ((equal property "TODO")
15841 (setq vals (org-with-point-at pom
15842 (append org-todo-keywords-1 '("")))))
15843 ((equal property "PRIORITY")
15844 (let ((n org-lowest-priority))
15845 (while (>= n org-highest-priority)
15846 (push (char-to-string n) vals)
15847 (setq n (1- n)))))
15848 ((equal property "CATEGORY"))
15849 ((member property org-special-properties))
15850 ((setq vals (run-hook-with-args-until-success
15851 'org-property-allowed-value-functions property)))
15853 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15854 (when (and vals (string-match "\\S-" vals))
15855 (setq vals (car (read-from-string (concat "(" vals ")"))))
15856 (setq vals (mapcar (lambda (x)
15857 (cond ((stringp x) x)
15858 ((numberp x) (number-to-string x))
15859 ((symbolp x) (symbol-name x))
15860 (t "???")))
15861 vals)))))
15862 (when (member ":ETC" vals)
15863 (setq vals (remove ":ETC" vals))
15864 (org-add-props (car vals) '(org-unrestricted t)))
15865 (if table (mapcar 'list vals) vals)))
15867 (defun org-property-previous-allowed-value (&optional _previous)
15868 "Switch to the next allowed value for this property."
15869 (interactive)
15870 (org-property-next-allowed-value t))
15872 (defun org-property-next-allowed-value (&optional previous)
15873 "Switch to the next allowed value for this property."
15874 (interactive)
15875 (unless (org-at-property-p)
15876 (user-error "Not at a property"))
15877 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15878 (key (match-string 2))
15879 (value (match-string 3))
15880 (allowed (or (org-property-get-allowed-values (point) key)
15881 (and (member value '("[ ]" "[-]" "[X]"))
15882 '("[ ]" "[X]"))))
15883 (heading (save-match-data (nth 4 (org-heading-components))))
15884 nval)
15885 (unless allowed
15886 (user-error "Allowed values for this property have not been defined"))
15887 (when previous (setq allowed (reverse allowed)))
15888 (when (member value allowed)
15889 (setq nval (car (cdr (member value allowed)))))
15890 (setq nval (or nval (car allowed)))
15891 (when (equal nval value)
15892 (user-error "Only one allowed value for this property"))
15893 (org-at-property-p)
15894 (replace-match (concat " :" key ": " nval) t t)
15895 (org-indent-line)
15896 (beginning-of-line 1)
15897 (skip-chars-forward " \t")
15898 (when (equal prop org-effort-property)
15899 (org-refresh-property
15900 '((effort . identity)
15901 (effort-minutes . org-duration-to-minutes))
15902 nval)
15903 (when (string= org-clock-current-task heading)
15904 (setq org-clock-effort nval)
15905 (org-clock-update-mode-line)))
15906 (run-hook-with-args 'org-property-changed-functions key nval)))
15908 (defun org-find-olp (path &optional this-buffer)
15909 "Return a marker pointing to the entry at outline path OLP.
15910 If anything goes wrong, throw an error.
15911 You can wrap this call to catch the error like this:
15913 (condition-case msg
15914 (org-mobile-locate-entry (match-string 4))
15915 (error (nth 1 msg)))
15917 The return value will then be either a string with the error message,
15918 or a marker if everything is OK.
15920 If THIS-BUFFER is set, the outline path does not contain a file,
15921 only headings."
15922 (let* ((file (if this-buffer buffer-file-name (pop path)))
15923 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15924 (level 1)
15925 (lmin 1)
15926 (lmax 1)
15927 end found flevel)
15928 (unless buffer (error "File not found :%s" file))
15929 (with-current-buffer buffer
15930 (unless (derived-mode-p 'org-mode)
15931 (error "Buffer %s needs to be in Org mode" buffer))
15932 (org-with-wide-buffer
15933 (goto-char (point-min))
15934 (dolist (heading path)
15935 (let ((re (format org-complex-heading-regexp-format
15936 (regexp-quote heading)))
15937 (cnt 0))
15938 (while (re-search-forward re end t)
15939 (setq level (- (match-end 1) (match-beginning 1)))
15940 (when (and (>= level lmin) (<= level lmax))
15941 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15942 (when (= cnt 0)
15943 (error "Heading not found on level %d: %s" lmax heading))
15944 (when (> cnt 1)
15945 (error "Heading not unique on level %d: %s" lmax heading))
15946 (goto-char found)
15947 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15948 (setq end (save-excursion (org-end-of-subtree t t)))))
15949 (when (org-at-heading-p)
15950 (point-marker))))))
15952 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15953 "Find node HEADING in BUFFER.
15954 Return a marker to the heading if it was found, or nil if not.
15955 If POS-ONLY is set, return just the position instead of a marker.
15957 The heading text must match exact, but it may have a TODO keyword,
15958 a priority cookie and tags in the standard locations."
15959 (with-current-buffer (or buffer (current-buffer))
15960 (org-with-wide-buffer
15961 (goto-char (point-min))
15962 (let (case-fold-search)
15963 (when (re-search-forward
15964 (format org-complex-heading-regexp-format
15965 (regexp-quote heading)) nil t)
15966 (if pos-only
15967 (match-beginning 0)
15968 (move-marker (make-marker) (match-beginning 0))))))))
15970 (defun org-find-exact-heading-in-directory (heading &optional dir)
15971 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15972 When the target headline is found, return a marker to this location."
15973 (let ((files (directory-files (or dir default-directory)
15974 t "\\`[^.#].*\\.org\\'"))
15975 visiting m buffer)
15976 (catch 'found
15977 (dolist (file files)
15978 (message "trying %s" file)
15979 (setq visiting (org-find-base-buffer-visiting file))
15980 (setq buffer (or visiting (find-file-noselect file)))
15981 (setq m (org-find-exact-headline-in-buffer
15982 heading buffer))
15983 (when (and (not m) (not visiting)) (kill-buffer buffer))
15984 (and m (throw 'found m))))))
15986 (defun org-find-entry-with-id (ident)
15987 "Locate the entry that contains the ID property with exact value IDENT.
15988 IDENT can be a string, a symbol or a number, this function will search for
15989 the string representation of it.
15990 Return the position where this entry starts, or nil if there is no such entry."
15991 (interactive "sID: ")
15992 (let ((id (cond
15993 ((stringp ident) ident)
15994 ((symbolp ident) (symbol-name ident))
15995 ((numberp ident) (number-to-string ident))
15996 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15997 (org-with-wide-buffer (org-find-property "ID" id))))
15999 ;;;; Timestamps
16001 (defvar org-last-changed-timestamp nil)
16002 (defvar org-last-inserted-timestamp nil
16003 "The last time stamp inserted with `org-insert-time-stamp'.")
16005 (defun org-time-stamp (arg &optional inactive)
16006 "Prompt for a date/time and insert a time stamp.
16008 If the user specifies a time like HH:MM or if this command is
16009 called with at least one prefix argument, the time stamp contains
16010 the date and the time. Otherwise, only the date is included.
16012 All parts of a date not specified by the user are filled in from
16013 the timestamp at point, if any, or the current date/time
16014 otherwise.
16016 If there is already a timestamp at the cursor, it is replaced.
16018 With two universal prefix arguments, insert an active timestamp
16019 with the current time without prompting the user.
16021 When called from lisp, the timestamp is inactive if INACTIVE is
16022 non-nil."
16023 (interactive "P")
16024 (let* ((ts (cond
16025 ((org-at-date-range-p t)
16026 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16027 ((org-at-timestamp-p 'lax) (match-string 0))))
16028 ;; Default time is either the timestamp at point or today.
16029 ;; When entering a range, only the range start is considered.
16030 (default-time (if (not ts) (current-time)
16031 (apply #'encode-time (org-parse-time-string ts))))
16032 (default-input (and ts (org-get-compact-tod ts)))
16033 (repeater (and ts
16034 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16035 (match-string 0 ts)))
16036 org-time-was-given
16037 org-end-time-was-given
16038 (time
16039 (and (if (equal arg '(16)) (current-time)
16040 ;; Preserve `this-command' and `last-command'.
16041 (let ((this-command this-command)
16042 (last-command last-command))
16043 (org-read-date
16044 arg 'totime nil nil default-time default-input
16045 inactive))))))
16046 (cond
16047 ((and ts
16048 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16049 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16050 (insert "--")
16051 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16053 ;; Make sure we're on a timestamp. When in the middle of a date
16054 ;; range, move arbitrarily to range end.
16055 (unless (org-at-timestamp-p 'lax)
16056 (skip-chars-forward "-")
16057 (org-at-timestamp-p 'lax))
16058 (replace-match "")
16059 (setq org-last-changed-timestamp
16060 (org-insert-time-stamp
16061 time (or org-time-was-given arg)
16062 inactive nil nil (list org-end-time-was-given)))
16063 (when repeater
16064 (backward-char)
16065 (insert " " repeater)
16066 (setq org-last-changed-timestamp
16067 (concat (substring org-last-inserted-timestamp 0 -1)
16068 " " repeater ">")))
16069 (message "Timestamp updated"))
16070 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16071 (t (org-insert-time-stamp
16072 time (or org-time-was-given arg) inactive nil nil
16073 (list org-end-time-was-given))))))
16075 ;; FIXME: can we use this for something else, like computing time differences?
16076 (defun org-get-compact-tod (s)
16077 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16078 (let* ((t1 (match-string 1 s))
16079 (h1 (string-to-number (match-string 2 s)))
16080 (m1 (string-to-number (match-string 3 s)))
16081 (t2 (and (match-end 4) (match-string 5 s)))
16082 (h2 (and t2 (string-to-number (match-string 6 s))))
16083 (m2 (and t2 (string-to-number (match-string 7 s))))
16084 dh dm)
16085 (if (not t2)
16087 (setq dh (- h2 h1) dm (- m2 m1))
16088 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16089 (concat t1 "+" (number-to-string dh)
16090 (and (/= 0 dm) (format ":%02d" dm)))))))
16092 (defun org-time-stamp-inactive (&optional arg)
16093 "Insert an inactive time stamp.
16095 An inactive time stamp is enclosed in square brackets instead of angle
16096 brackets. It is inactive in the sense that it does not trigger agenda entries,
16097 does not link to the calendar and cannot be changed with the S-cursor keys.
16098 So these are more for recording a certain time/date.
16100 If the user specifies a time like HH:MM or if this command is called with
16101 at least one prefix argument, the time stamp contains the date and the time.
16102 Otherwise, only the date is included.
16104 When called with two universal prefix arguments, insert an active time stamp
16105 with the current time without prompting the user."
16106 (interactive "P")
16107 (org-time-stamp arg 'inactive))
16109 (defvar org-date-ovl (make-overlay 1 1))
16110 (overlay-put org-date-ovl 'face 'org-date-selected)
16111 (delete-overlay org-date-ovl)
16113 (defvar org-ans1) ; dynamically scoped parameter
16114 (defvar org-ans2) ; dynamically scoped parameter
16116 (defvar org-plain-time-of-day-regexp) ; defined below
16118 (defvar org-overriding-default-time nil) ; dynamically scoped
16119 (defvar org-read-date-overlay nil)
16120 (defvar org-dcst nil) ; dynamically scoped
16121 (defvar org-read-date-history nil)
16122 (defvar org-read-date-final-answer nil)
16123 (defvar org-read-date-analyze-futurep nil)
16124 (defvar org-read-date-analyze-forced-year nil)
16125 (defvar org-read-date-inactive)
16127 (defvar org-read-date-minibuffer-local-map
16128 (let* ((map (make-sparse-keymap)))
16129 (set-keymap-parent map minibuffer-local-map)
16130 (org-defkey map (kbd ".")
16131 (lambda () (interactive)
16132 ;; Are we at the beginning of the prompt?
16133 (if (looking-back "^[^:]+: "
16134 (let ((inhibit-field-text-motion t))
16135 (line-beginning-position)))
16136 (org-eval-in-calendar '(calendar-goto-today))
16137 (insert "."))))
16138 (org-defkey map (kbd "C-.")
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(calendar-goto-today))))
16141 (org-defkey map (kbd "M-S-<left>")
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-backward-month 1))))
16144 (org-defkey map (kbd "ESC S-<left>")
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-backward-month 1))))
16147 (org-defkey map (kbd "M-S-<right>")
16148 (lambda () (interactive)
16149 (org-eval-in-calendar '(calendar-forward-month 1))))
16150 (org-defkey map (kbd "ESC S-<right>")
16151 (lambda () (interactive)
16152 (org-eval-in-calendar '(calendar-forward-month 1))))
16153 (org-defkey map (kbd "M-S-<up>")
16154 (lambda () (interactive)
16155 (org-eval-in-calendar '(calendar-backward-year 1))))
16156 (org-defkey map (kbd "ESC S-<up>")
16157 (lambda () (interactive)
16158 (org-eval-in-calendar '(calendar-backward-year 1))))
16159 (org-defkey map (kbd "M-S-<down>")
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(calendar-forward-year 1))))
16162 (org-defkey map (kbd "ESC S-<down>")
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(calendar-forward-year 1))))
16165 (org-defkey map (kbd "S-<up>")
16166 (lambda () (interactive)
16167 (org-eval-in-calendar '(calendar-backward-week 1))))
16168 (org-defkey map (kbd "S-<down>")
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(calendar-forward-week 1))))
16171 (org-defkey map (kbd "S-<left>")
16172 (lambda () (interactive)
16173 (org-eval-in-calendar '(calendar-backward-day 1))))
16174 (org-defkey map (kbd "S-<right>")
16175 (lambda () (interactive)
16176 (org-eval-in-calendar '(calendar-forward-day 1))))
16177 (org-defkey map (kbd "!")
16178 (lambda () (interactive)
16179 (org-eval-in-calendar '(diary-view-entries))
16180 (message "")))
16181 (org-defkey map (kbd ">")
16182 (lambda () (interactive)
16183 (org-eval-in-calendar '(calendar-scroll-left 1))))
16184 (org-defkey map (kbd "<")
16185 (lambda () (interactive)
16186 (org-eval-in-calendar '(calendar-scroll-right 1))))
16187 (org-defkey map (kbd "C-v")
16188 (lambda () (interactive)
16189 (org-eval-in-calendar
16190 '(calendar-scroll-left-three-months 1))))
16191 (org-defkey map (kbd "M-v")
16192 (lambda () (interactive)
16193 (org-eval-in-calendar
16194 '(calendar-scroll-right-three-months 1))))
16195 map)
16196 "Keymap for minibuffer commands when using `org-read-date'.")
16198 (defvar org-def)
16199 (defvar org-defdecode)
16200 (defvar org-with-time)
16202 (defvar calendar-setup) ; Dynamically scoped.
16203 (defun org-read-date (&optional with-time to-time from-string prompt
16204 default-time default-input inactive)
16205 "Read a date, possibly a time, and make things smooth for the user.
16206 The prompt will suggest to enter an ISO date, but you can also enter anything
16207 which will at least partially be understood by `parse-time-string'.
16208 Unrecognized parts of the date will default to the current day, month, year,
16209 hour and minute. If this command is called to replace a timestamp at point,
16210 or to enter the second timestamp of a range, the default time is taken
16211 from the existing stamp. Furthermore, the command prefers the future,
16212 so if you are giving a date where the year is not given, and the day-month
16213 combination is already past in the current year, it will assume you
16214 mean next year. For details, see the manual. A few examples:
16216 3-2-5 --> 2003-02-05
16217 feb 15 --> currentyear-02-15
16218 2/15 --> currentyear-02-15
16219 sep 12 9 --> 2009-09-12
16220 12:45 --> today 12:45
16221 22 sept 0:34 --> currentyear-09-22 0:34
16222 12 --> currentyear-currentmonth-12
16223 Fri --> nearest Friday after today
16224 -Tue --> last Tuesday
16225 etc.
16227 Furthermore you can specify a relative date by giving, as the *first* thing
16228 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16229 change in days weeks, months, years.
16230 With a single plus or minus, the date is relative to today. With a double
16231 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16232 +4d --> four days from today
16233 +4 --> same as above
16234 +2w --> two weeks from today
16235 ++5 --> five days from default date
16237 The function understands only English month and weekday abbreviations.
16239 While prompting, a calendar is popped up - you can also select the
16240 date with the mouse (button 1). The calendar shows a period of three
16241 months. To scroll it to other months, use the keys `>' and `<'.
16242 If you don't like the calendar, turn it off with
16243 (setq org-read-date-popup-calendar nil)
16245 With optional argument TO-TIME, the date will immediately be converted
16246 to an internal time.
16247 With an optional argument WITH-TIME, the prompt will suggest to
16248 also insert a time. Note that when WITH-TIME is not set, you can
16249 still enter a time, and this function will inform the calling routine
16250 about this change. The calling routine may then choose to change the
16251 format used to insert the time stamp into the buffer to include the time.
16252 With optional argument FROM-STRING, read from this string instead from
16253 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16254 the time/date that is used for everything that is not specified by the
16255 user."
16256 (require 'parse-time)
16257 (let* ((org-with-time with-time)
16258 (org-time-stamp-rounding-minutes
16259 (if (equal org-with-time '(16))
16260 '(0 0)
16261 org-time-stamp-rounding-minutes))
16262 (org-dcst org-display-custom-times)
16263 (ct (org-current-time))
16264 (org-def (or org-overriding-default-time default-time ct))
16265 (org-defdecode (decode-time org-def))
16266 (cur-frame (selected-frame))
16267 (mouse-autoselect-window nil) ; Don't let the mouse jump
16268 (calendar-setup
16269 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16270 (calendar-move-hook nil)
16271 (calendar-view-diary-initially-flag nil)
16272 (calendar-view-holidays-initially-flag nil)
16273 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16274 ;; Rationalize `org-def' and `org-defdecode', if required.
16275 (when (< (nth 2 org-defdecode) org-extend-today-until)
16276 (setf (nth 2 org-defdecode) -1)
16277 (setf (nth 1 org-defdecode) 59)
16278 (setq org-def (apply #'encode-time org-defdecode))
16279 (setq org-defdecode (decode-time org-def)))
16280 (let* ((timestr (format-time-string
16281 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16282 org-def))
16283 (prompt (concat (if prompt (concat prompt " ") "")
16284 (format "Date+time [%s]: " timestr))))
16285 (cond
16286 (from-string (setq ans from-string))
16287 (org-read-date-popup-calendar
16288 (save-excursion
16289 (save-window-excursion
16290 (calendar)
16291 (when (eq calendar-setup 'calendar-only)
16292 (setq cal-frame
16293 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16294 (select-frame cal-frame))
16295 (org-eval-in-calendar '(setq cursor-type nil) t)
16296 (unwind-protect
16297 (progn
16298 (calendar-forward-day (- (time-to-days org-def)
16299 (calendar-absolute-from-gregorian
16300 (calendar-current-date))))
16301 (org-eval-in-calendar nil t)
16302 (let* ((old-map (current-local-map))
16303 (map (copy-keymap calendar-mode-map))
16304 (minibuffer-local-map
16305 (copy-keymap org-read-date-minibuffer-local-map)))
16306 (org-defkey map (kbd "RET") 'org-calendar-select)
16307 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16308 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16309 (unwind-protect
16310 (progn
16311 (use-local-map map)
16312 (setq org-read-date-inactive inactive)
16313 (add-hook 'post-command-hook 'org-read-date-display)
16314 (setq org-ans0
16315 (read-string prompt
16316 default-input
16317 'org-read-date-history
16318 nil))
16319 ;; org-ans0: from prompt
16320 ;; org-ans1: from mouse click
16321 ;; org-ans2: from calendar motion
16322 (setq ans
16323 (concat org-ans0 " " (or org-ans1 org-ans2))))
16324 (remove-hook 'post-command-hook 'org-read-date-display)
16325 (use-local-map old-map)
16326 (when org-read-date-overlay
16327 (delete-overlay org-read-date-overlay)
16328 (setq org-read-date-overlay nil)))))
16329 (bury-buffer "*Calendar*")
16330 (when cal-frame
16331 (delete-frame cal-frame)
16332 (select-frame-set-input-focus cur-frame))))))
16334 (t ; Naked prompt only
16335 (unwind-protect
16336 (setq ans (read-string prompt default-input
16337 'org-read-date-history timestr))
16338 (when org-read-date-overlay
16339 (delete-overlay org-read-date-overlay)
16340 (setq org-read-date-overlay nil))))))
16342 (setq final (org-read-date-analyze ans org-def org-defdecode))
16344 (when org-read-date-analyze-forced-year
16345 (message "Year was forced into %s"
16346 (if org-read-date-force-compatible-dates
16347 "compatible range (1970-2037)"
16348 "range representable on this machine"))
16349 (ding))
16351 ;; One round trip to get rid of 34th of August and stuff like that....
16352 (setq final (decode-time (apply 'encode-time final)))
16354 (setq org-read-date-final-answer ans)
16356 (if to-time
16357 (apply 'encode-time final)
16358 (if (and (boundp 'org-time-was-given) org-time-was-given)
16359 (format "%04d-%02d-%02d %02d:%02d"
16360 (nth 5 final) (nth 4 final) (nth 3 final)
16361 (nth 2 final) (nth 1 final))
16362 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16364 (defun org-read-date-display ()
16365 "Display the current date prompt interpretation in the minibuffer."
16366 (when org-read-date-display-live
16367 (when org-read-date-overlay
16368 (delete-overlay org-read-date-overlay))
16369 (when (minibufferp (current-buffer))
16370 (save-excursion
16371 (end-of-line 1)
16372 (while (not (equal (buffer-substring
16373 (max (point-min) (- (point) 4)) (point))
16374 " "))
16375 (insert " ")))
16376 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16377 " " (or org-ans1 org-ans2)))
16378 (org-end-time-was-given nil)
16379 (f (org-read-date-analyze ans org-def org-defdecode))
16380 (fmts (if org-dcst
16381 org-time-stamp-custom-formats
16382 org-time-stamp-formats))
16383 (fmt (if (or org-with-time
16384 (and (boundp 'org-time-was-given) org-time-was-given))
16385 (cdr fmts)
16386 (car fmts)))
16387 (txt (format-time-string fmt (apply 'encode-time f)))
16388 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16389 (txt (concat "=> " txt)))
16390 (when (and org-end-time-was-given
16391 (string-match org-plain-time-of-day-regexp txt))
16392 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16393 org-end-time-was-given
16394 (substring txt (match-end 0)))))
16395 (when org-read-date-analyze-futurep
16396 (setq txt (concat txt " (=>F)")))
16397 (setq org-read-date-overlay
16398 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16399 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16401 (defun org-read-date-analyze (ans def defdecode)
16402 "Analyze the combined answer of the date prompt."
16403 ;; FIXME: cleanup and comment
16404 ;; Pass `current-time' result to `decode-time' (instead of calling
16405 ;; without arguments) so that only `current-time' has to be
16406 ;; overridden in tests.
16407 (let ((org-def def)
16408 (org-defdecode defdecode)
16409 (nowdecode (decode-time (current-time)))
16410 delta deltan deltaw deltadef year month day
16411 hour minute second wday pm h2 m2 tl wday1
16412 iso-year iso-weekday iso-week iso-date futurep kill-year)
16413 (setq org-read-date-analyze-futurep nil
16414 org-read-date-analyze-forced-year nil)
16415 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16416 (setq ans "+0"))
16418 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16419 (setq ans (replace-match "" t t ans)
16420 deltan (car delta)
16421 deltaw (nth 1 delta)
16422 deltadef (nth 2 delta)))
16424 ;; Check if there is an iso week date in there. If yes, store the
16425 ;; info and postpone interpreting it until the rest of the parsing
16426 ;; is done.
16427 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16428 (setq iso-year (when (match-end 1)
16429 (org-small-year-to-year
16430 (string-to-number (match-string 1 ans))))
16431 iso-weekday (when (match-end 3)
16432 (string-to-number (match-string 3 ans)))
16433 iso-week (string-to-number (match-string 2 ans)))
16434 (setq ans (replace-match "" t t ans)))
16436 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16437 (when (string-match
16438 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16439 (setq year (if (match-end 2)
16440 (string-to-number (match-string 2 ans))
16441 (progn (setq kill-year t)
16442 (string-to-number (format-time-string "%Y"))))
16443 month (string-to-number (match-string 3 ans))
16444 day (string-to-number (match-string 4 ans)))
16445 (setq year (org-small-year-to-year year))
16446 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16447 t nil ans)))
16449 ;; Help matching dotted european dates
16450 (when (string-match
16451 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16452 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16453 (setq kill-year t)
16454 (string-to-number (format-time-string "%Y")))
16455 day (string-to-number (match-string 1 ans))
16456 month (string-to-number (match-string 2 ans))
16457 ans (replace-match (format "%04d-%02d-%02d" year month day)
16458 t nil ans)))
16460 ;; Help matching american dates, like 5/30 or 5/30/7
16461 (when (string-match
16462 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16463 (setq year (if (match-end 4)
16464 (string-to-number (match-string 4 ans))
16465 (progn (setq kill-year t)
16466 (string-to-number (format-time-string "%Y"))))
16467 month (string-to-number (match-string 1 ans))
16468 day (string-to-number (match-string 2 ans)))
16469 (setq year (org-small-year-to-year year))
16470 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16471 t nil ans)))
16472 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16473 ;; If there is a time with am/pm, and *no* time without it, we convert
16474 ;; so that matching will be successful.
16475 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16476 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16477 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16478 (setq hour (string-to-number (match-string 1 ans))
16479 minute (if (match-end 3)
16480 (string-to-number (match-string 3 ans))
16482 pm (equal ?p
16483 (string-to-char (downcase (match-string 4 ans)))))
16484 (if (and (= hour 12) (not pm))
16485 (setq hour 0)
16486 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16487 (setq ans (replace-match (format "%02d:%02d" hour minute)
16488 t t ans))))
16490 ;; Check if a time range is given as a duration
16491 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16492 (setq hour (string-to-number (match-string 1 ans))
16493 h2 (+ hour (string-to-number (match-string 3 ans)))
16494 minute (string-to-number (match-string 2 ans))
16495 m2 (+ minute (if (match-end 5) (string-to-number
16496 (match-string 5 ans))0)))
16497 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16498 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16499 t t ans)))
16501 ;; Check if there is a time range
16502 (when (boundp 'org-end-time-was-given)
16503 (setq org-time-was-given nil)
16504 (when (and (string-match org-plain-time-of-day-regexp ans)
16505 (match-end 8))
16506 (setq org-end-time-was-given (match-string 8 ans))
16507 (setq ans (concat (substring ans 0 (match-beginning 7))
16508 (substring ans (match-end 7))))))
16510 (setq tl (parse-time-string ans)
16511 day (or (nth 3 tl) (nth 3 org-defdecode))
16512 month
16513 (cond ((nth 4 tl))
16514 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16515 ;; Day was specified. Make sure DAY+MONTH
16516 ;; combination happens in the future.
16517 ((nth 3 tl)
16518 (setq futurep t)
16519 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16520 (nth 4 nowdecode)))
16521 (t (nth 4 org-defdecode)))
16522 year
16523 (cond ((and (not kill-year) (nth 5 tl)))
16524 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16525 ;; Month was guessed in the future and is at least
16526 ;; equal to NOWDECODE's. Fix year accordingly.
16527 (futurep
16528 (if (or (> month (nth 4 nowdecode))
16529 (>= day (nth 3 nowdecode)))
16530 (nth 5 nowdecode)
16531 (1+ (nth 5 nowdecode))))
16532 ;; Month was specified. Make sure MONTH+YEAR
16533 ;; combination happens in the future.
16534 ((nth 4 tl)
16535 (setq futurep t)
16536 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16537 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16538 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16539 (t (nth 5 nowdecode))))
16540 (t (nth 5 org-defdecode)))
16541 hour (or (nth 2 tl) (nth 2 org-defdecode))
16542 minute (or (nth 1 tl) (nth 1 org-defdecode))
16543 second (or (nth 0 tl) 0)
16544 wday (nth 6 tl))
16546 (when (and (eq org-read-date-prefer-future 'time)
16547 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16548 (equal day (nth 3 nowdecode))
16549 (equal month (nth 4 nowdecode))
16550 (equal year (nth 5 nowdecode))
16551 (nth 2 tl)
16552 (or (< (nth 2 tl) (nth 2 nowdecode))
16553 (and (= (nth 2 tl) (nth 2 nowdecode))
16554 (nth 1 tl)
16555 (< (nth 1 tl) (nth 1 nowdecode)))))
16556 (setq day (1+ day)
16557 futurep t))
16559 ;; Special date definitions below
16560 (cond
16561 (iso-week
16562 ;; There was an iso week
16563 (require 'cal-iso)
16564 (setq futurep nil)
16565 (setq year (or iso-year year)
16566 day (or iso-weekday wday 1)
16567 wday nil ; to make sure that the trigger below does not match
16568 iso-date (calendar-gregorian-from-absolute
16569 (calendar-iso-to-absolute
16570 (list iso-week day year))))
16571 ; FIXME: Should we also push ISO weeks into the future?
16572 ; (when (and org-read-date-prefer-future
16573 ; (not iso-year)
16574 ; (< (calendar-absolute-from-gregorian iso-date)
16575 ; (time-to-days (current-time))))
16576 ; (setq year (1+ year)
16577 ; iso-date (calendar-gregorian-from-absolute
16578 ; (calendar-iso-to-absolute
16579 ; (list iso-week day year)))))
16580 (setq month (car iso-date)
16581 year (nth 2 iso-date)
16582 day (nth 1 iso-date)))
16583 (deltan
16584 (setq futurep nil)
16585 (unless deltadef
16586 ;; Pass `current-time' result to `decode-time' (instead of
16587 ;; calling without arguments) so that only `current-time' has
16588 ;; to be overridden in tests.
16589 (let ((now (decode-time (current-time))))
16590 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16591 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16592 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16593 ((equal deltaw "m") (setq month (+ month deltan)))
16594 ((equal deltaw "y") (setq year (+ year deltan)))))
16595 ((and wday (not (nth 3 tl)))
16596 ;; Weekday was given, but no day, so pick that day in the week
16597 ;; on or after the derived date.
16598 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16599 (unless (equal wday wday1)
16600 (setq day (+ day (% (- wday wday1 -7) 7))))))
16601 (when (and (boundp 'org-time-was-given)
16602 (nth 2 tl))
16603 (setq org-time-was-given t))
16604 (when (< year 100) (setq year (+ 2000 year)))
16605 ;; Check of the date is representable
16606 (if org-read-date-force-compatible-dates
16607 (progn
16608 (when (< year 1970)
16609 (setq year 1970 org-read-date-analyze-forced-year t))
16610 (when (> year 2037)
16611 (setq year 2037 org-read-date-analyze-forced-year t)))
16612 (condition-case nil
16613 (ignore (encode-time second minute hour day month year))
16614 (error
16615 (setq year (nth 5 org-defdecode))
16616 (setq org-read-date-analyze-forced-year t))))
16617 (setq org-read-date-analyze-futurep futurep)
16618 (list second minute hour day month year)))
16620 (defvar parse-time-weekdays)
16621 (defun org-read-date-get-relative (s today default)
16622 "Check string S for special relative date string.
16623 TODAY and DEFAULT are internal times, for today and for a default.
16624 Return shift list (N what def-flag)
16625 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16626 N is the number of WHATs to shift.
16627 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16628 the DEFAULT date rather than TODAY."
16629 (require 'parse-time)
16630 (when (and
16631 (string-match
16632 (concat
16633 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16634 "\\([0-9]+\\)?"
16635 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16636 "\\([ \t]\\|$\\)") s)
16637 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16638 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16639 (string-to-char (substring (match-string 1 s) -1))
16640 ?+))
16641 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16642 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16643 (what (if (match-end 3) (match-string 3 s) "d"))
16644 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16645 (date (if rel default today))
16646 (wday (nth 6 (decode-time date)))
16647 delta)
16648 (if wday1
16649 (progn
16650 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16651 (when (= delta 0) (setq delta 7))
16652 (when (= dir ?-)
16653 (setq delta (- delta 7))
16654 (when (= delta 0) (setq delta -7)))
16655 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16656 (list delta "d" rel))
16657 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16659 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16660 "Turn a user-specified date into the internal representation.
16661 The internal representation needed by the calendar is (month day year).
16662 This is a wrapper to handle the brain-dead convention in calendar that
16663 user function argument order change dependent on argument order."
16664 (pcase calendar-date-style
16665 (`american (list arg1 arg2 arg3))
16666 (`european (list arg2 arg1 arg3))
16667 (`iso (list arg2 arg3 arg1))))
16669 (defun org-eval-in-calendar (form &optional keepdate)
16670 "Eval FORM in the calendar window and return to current window.
16671 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16672 (let ((sf (selected-frame))
16673 (sw (selected-window)))
16674 (select-window (get-buffer-window "*Calendar*" t))
16675 (eval form)
16676 (when (and (not keepdate) (calendar-cursor-to-date))
16677 (let* ((date (calendar-cursor-to-date))
16678 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16679 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16680 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16681 (select-window sw)
16682 (select-frame-set-input-focus sf)))
16684 (defun org-calendar-select ()
16685 "Return to `org-read-date' with the date currently selected.
16686 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16687 (interactive)
16688 (when (calendar-cursor-to-date)
16689 (let* ((date (calendar-cursor-to-date))
16690 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16691 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16692 (when (active-minibuffer-window) (exit-minibuffer))))
16694 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16695 "Insert a date stamp for the date given by the internal TIME.
16696 See `format-time-string' for the format of TIME.
16697 WITH-HM means use the stamp format that includes the time of the day.
16698 INACTIVE means use square brackets instead of angular ones, so that the
16699 stamp will not contribute to the agenda.
16700 PRE and POST are optional strings to be inserted before and after the
16701 stamp.
16702 The command returns the inserted time stamp."
16703 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16704 stamp)
16705 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16706 (insert-before-markers (or pre ""))
16707 (when (listp extra)
16708 (setq extra (car extra))
16709 (if (and (stringp extra)
16710 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16711 (setq extra (format "-%02d:%02d"
16712 (string-to-number (match-string 1 extra))
16713 (string-to-number (match-string 2 extra))))
16714 (setq extra nil)))
16715 (when extra
16716 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16717 (insert-before-markers (setq stamp (format-time-string fmt time)))
16718 (insert-before-markers (or post ""))
16719 (setq org-last-inserted-timestamp stamp)))
16721 (defun org-toggle-time-stamp-overlays ()
16722 "Toggle the use of custom time stamp formats."
16723 (interactive)
16724 (setq org-display-custom-times (not org-display-custom-times))
16725 (unless org-display-custom-times
16726 (let ((p (point-min)) (bmp (buffer-modified-p)))
16727 (while (setq p (next-single-property-change p 'display))
16728 (when (and (get-text-property p 'display)
16729 (eq (get-text-property p 'face) 'org-date))
16730 (remove-text-properties
16731 p (setq p (next-single-property-change p 'display))
16732 '(display t))))
16733 (set-buffer-modified-p bmp)))
16734 (org-restart-font-lock)
16735 (setq org-table-may-need-update t)
16736 (if org-display-custom-times
16737 (message "Time stamps are overlaid with custom format")
16738 (message "Time stamp overlays removed")))
16740 (defun org-display-custom-time (beg end)
16741 "Overlay modified time stamp format over timestamp between BEG and END."
16742 (let* ((ts (buffer-substring beg end))
16743 t1 with-hm tf time str (off 0))
16744 (save-match-data
16745 (setq t1 (org-parse-time-string ts t))
16746 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16747 (setq off (- (match-end 0) (match-beginning 0)))))
16748 (setq end (- end off))
16749 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16750 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16751 time (org-fix-decoded-time t1)
16752 str (org-add-props
16753 (format-time-string
16754 (substring tf 1 -1) (apply 'encode-time time))
16755 nil 'mouse-face 'highlight))
16756 (put-text-property beg end 'display str)))
16758 (defun org-fix-decoded-time (time)
16759 "Set 0 instead of nil for the first 6 elements of time.
16760 Don't touch the rest."
16761 (let ((n 0))
16762 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16764 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16765 "Difference between TIMESTAMP-STRING and now in days.
16766 If SECONDS is non-nil, return the difference in seconds."
16767 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16768 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16769 (funcall fdiff (current-time)))))
16771 (defun org-deadline-close-p (timestamp-string &optional ndays)
16772 "Is the time in TIMESTAMP-STRING close to the current date?"
16773 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16774 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16775 (not (org-entry-is-done-p))))
16777 (defun org-get-wdays (ts &optional delay zero-delay)
16778 "Get the deadline lead time appropriate for timestring TS.
16779 When DELAY is non-nil, get the delay time for scheduled items
16780 instead of the deadline lead time. When ZERO-DELAY is non-nil
16781 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16782 don't try to find the delay cookie in the scheduled timestamp."
16783 (let ((tv (if delay org-scheduled-delay-days
16784 org-deadline-warning-days)))
16785 (cond
16786 ((or (and delay (< tv 0))
16787 (and delay zero-delay (<= tv 0))
16788 (and (not delay) (<= tv 0)))
16789 ;; Enforce this value no matter what
16790 (- tv))
16791 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16792 ;; lead time is specified.
16793 (floor (* (string-to-number (match-string 1 ts))
16794 (cdr (assoc (match-string 2 ts)
16795 '(("d" . 1) ("w" . 7)
16796 ("m" . 30.4) ("y" . 365.25)
16797 ("h" . 0.041667)))))))
16798 ;; go for the default.
16799 (t tv))))
16801 (defun org-calendar-select-mouse (ev)
16802 "Return to `org-read-date' with the date currently selected.
16803 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16804 (interactive "e")
16805 (mouse-set-point ev)
16806 (when (calendar-cursor-to-date)
16807 (let* ((date (calendar-cursor-to-date))
16808 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16809 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16810 (when (active-minibuffer-window) (exit-minibuffer))))
16812 (defun org-check-deadlines (ndays)
16813 "Check if there are any deadlines due or past due.
16814 A deadline is considered due if it happens within `org-deadline-warning-days'
16815 days from today's date. If the deadline appears in an entry marked DONE,
16816 it is not shown. A numeric prefix argument NDAYS can be used to test that
16817 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16818 are shown."
16819 (interactive "P")
16820 (let* ((org-warn-days
16821 (cond
16822 ((equal ndays '(4)) 100000)
16823 (ndays (prefix-numeric-value ndays))
16824 (t (abs org-deadline-warning-days))))
16825 (case-fold-search nil)
16826 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16827 (callback
16828 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16829 (message "%d deadlines past-due or due within %d days"
16830 (org-occur regexp nil callback)
16831 org-warn-days)))
16833 (defsubst org-re-timestamp (type)
16834 "Return a regexp for timestamp TYPE.
16835 Allowed values for TYPE are:
16837 all: all timestamps
16838 active: only active timestamps (<...>)
16839 inactive: only inactive timestamps ([...])
16840 scheduled: only scheduled timestamps
16841 deadline: only deadline timestamps
16842 closed: only closed time-stamps
16844 When TYPE is nil, fall back on returning a regexp that matches
16845 both scheduled and deadline timestamps."
16846 (cl-case type
16847 (all org-ts-regexp-both)
16848 (active org-ts-regexp)
16849 (inactive org-ts-regexp-inactive)
16850 (scheduled org-scheduled-time-regexp)
16851 (deadline org-deadline-time-regexp)
16852 (closed org-closed-time-regexp)
16853 (otherwise
16854 (concat "\\<"
16855 (regexp-opt (list org-deadline-string org-scheduled-string))
16856 " *<\\([^>]+\\)>"))))
16858 (defun org-check-before-date (d)
16859 "Check if there are deadlines or scheduled entries before date D."
16860 (interactive (list (org-read-date)))
16861 (let* ((case-fold-search nil)
16862 (regexp (org-re-timestamp org-ts-type))
16863 (ts-type org-ts-type)
16864 (callback
16865 (lambda ()
16866 (let ((match (match-string 1)))
16867 (and (if (memq ts-type '(active inactive all))
16868 (eq (org-element-type (save-excursion
16869 (backward-char)
16870 (org-element-context)))
16871 'timestamp)
16872 (org-at-planning-p))
16873 (time-less-p
16874 (org-time-string-to-time match)
16875 (org-time-string-to-time d)))))))
16876 (message "%d entries before %s"
16877 (org-occur regexp nil callback)
16878 d)))
16880 (defun org-check-after-date (d)
16881 "Check if there are deadlines or scheduled entries after date D."
16882 (interactive (list (org-read-date)))
16883 (let* ((case-fold-search nil)
16884 (regexp (org-re-timestamp org-ts-type))
16885 (ts-type org-ts-type)
16886 (callback
16887 (lambda ()
16888 (let ((match (match-string 1)))
16889 (and (if (memq ts-type '(active inactive all))
16890 (eq (org-element-type (save-excursion
16891 (backward-char)
16892 (org-element-context)))
16893 'timestamp)
16894 (org-at-planning-p))
16895 (not (time-less-p
16896 (org-time-string-to-time match)
16897 (org-time-string-to-time d))))))))
16898 (message "%d entries after %s"
16899 (org-occur regexp nil callback)
16900 d)))
16902 (defun org-check-dates-range (start-date end-date)
16903 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16904 (interactive (list (org-read-date nil nil nil "Range starts")
16905 (org-read-date nil nil nil "Range end")))
16906 (let ((case-fold-search nil)
16907 (regexp (org-re-timestamp org-ts-type))
16908 (callback
16909 (let ((type org-ts-type))
16910 (lambda ()
16911 (let ((match (match-string 1)))
16912 (and
16913 (if (memq type '(active inactive all))
16914 (eq (org-element-type (save-excursion
16915 (backward-char)
16916 (org-element-context)))
16917 'timestamp)
16918 (org-at-planning-p))
16919 (not (time-less-p
16920 (org-time-string-to-time match)
16921 (org-time-string-to-time start-date)))
16922 (time-less-p
16923 (org-time-string-to-time match)
16924 (org-time-string-to-time end-date))))))))
16925 (message "%d entries between %s and %s"
16926 (org-occur regexp nil callback) start-date end-date)))
16928 (defun org-evaluate-time-range (&optional to-buffer)
16929 "Evaluate a time range by computing the difference between start and end.
16930 Normally the result is just printed in the echo area, but with prefix arg
16931 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16932 If the time range is actually in a table, the result is inserted into the
16933 next column.
16934 For time difference computation, a year is assumed to be exactly 365
16935 days in order to avoid rounding problems."
16936 (interactive "P")
16938 (org-clock-update-time-maybe)
16939 (save-excursion
16940 (unless (org-at-date-range-p t)
16941 (goto-char (point-at-bol))
16942 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16943 (unless (org-at-date-range-p t)
16944 (user-error "Not at a time-stamp range, and none found in current line")))
16945 (let* ((ts1 (match-string 1))
16946 (ts2 (match-string 2))
16947 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16948 (match-end (match-end 0))
16949 (time1 (org-time-string-to-time ts1))
16950 (time2 (org-time-string-to-time ts2))
16951 (t1 (float-time time1))
16952 (t2 (float-time time2))
16953 (diff (abs (- t2 t1)))
16954 (negative (< (- t2 t1) 0))
16955 ;; (ys (floor (* 365 24 60 60)))
16956 (ds (* 24 60 60))
16957 (hs (* 60 60))
16958 (fy "%dy %dd %02d:%02d")
16959 (fy1 "%dy %dd")
16960 (fd "%dd %02d:%02d")
16961 (fd1 "%dd")
16962 (fh "%02d:%02d")
16963 y d h m align)
16964 (if havetime
16965 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16967 d (floor (/ diff ds)) diff (mod diff ds)
16968 h (floor (/ diff hs)) diff (mod diff hs)
16969 m (floor (/ diff 60)))
16970 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16972 d (floor (+ (/ diff ds) 0.5))
16973 h 0 m 0))
16974 (if (not to-buffer)
16975 (message "%s" (org-make-tdiff-string y d h m))
16976 (if (org-at-table-p)
16977 (progn
16978 (goto-char match-end)
16979 (setq align t)
16980 (and (looking-at " *|") (goto-char (match-end 0))))
16981 (goto-char match-end))
16982 (when (looking-at
16983 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16984 (replace-match ""))
16985 (when negative (insert " -"))
16986 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16987 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16988 (insert " " (format fh h m))))
16989 (when align (org-table-align))
16990 (message "Time difference inserted")))))
16992 (defun org-make-tdiff-string (y d h m)
16993 (let ((fmt "")
16994 (l nil))
16995 (when (> y 0)
16996 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16997 (push y l))
16998 (when (> d 0)
16999 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17000 (push d l))
17001 (when (> h 0)
17002 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17003 (push h l))
17004 (when (> m 0)
17005 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17006 (push m l))
17007 (apply 'format fmt (nreverse l))))
17009 (defun org-time-string-to-time (s)
17010 "Convert timestamp string S into internal time."
17011 (apply #'encode-time (org-parse-time-string s)))
17013 (defun org-time-string-to-seconds (s)
17014 "Convert a timestamp string S into a number of seconds."
17015 (float-time (org-time-string-to-time s)))
17017 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17019 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17020 "Convert time stamp S to an absolute day number.
17022 If DAYNR in non-nil, and there is a specifier for a cyclic time
17023 stamp, get the closest date to DAYNR. If PREFER is
17024 `past' (respectively `future') return a date past (respectively
17025 after) or equal to DAYNR.
17027 POS is the location of time stamp S, as a buffer position in
17028 BUFFER.
17030 Diary sexp timestamps are matched against DAYNR, when non-nil.
17031 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17032 signaled."
17033 (cond
17034 ((string-match "\\`%%\\((.*)\\)" s)
17035 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17036 ;; only able to match individual dates. If it fails, raise an
17037 ;; error.
17038 (if (and daynr
17039 (org-diary-sexp-entry
17040 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17041 daynr
17042 (signal 'org-diary-sexp-no-match (list s))))
17043 (daynr (org-closest-date s daynr prefer))
17044 (t (time-to-days
17045 (condition-case errdata
17046 (apply #'encode-time (org-parse-time-string s))
17047 (error (error "Bad timestamp `%s'%s\nError was: %s"
17049 (if (not (and buffer pos)) ""
17050 (format-message " at %d in buffer `%s'" pos buffer))
17051 (cdr errdata))))))))
17053 (defun org-days-to-iso-week (days)
17054 "Return the iso week number."
17055 (require 'cal-iso)
17056 (car (calendar-iso-from-absolute days)))
17058 (defun org-small-year-to-year (year)
17059 "Convert 2-digit years into 4-digit years.
17060 YEAR is expanded into one of the 30 next years, if possible, or
17061 into a past one. Any year larger than 99 is returned unchanged."
17062 (if (>= year 100) year
17063 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17064 (century (/ current 100))
17065 (offset (- year (% current 100))))
17066 (cond ((> offset 30) (+ (* (1- century) 100) year))
17067 ((> offset -70) (+ (* century 100) year))
17068 (t (+ (* (1+ century) 100) year))))))
17070 (defun org-time-from-absolute (d)
17071 "Return the time corresponding to date D.
17072 D may be an absolute day number, or a calendar-type list (month day year)."
17073 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17074 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17076 (defvar org-agenda-current-date)
17077 (defun org-calendar-holiday ()
17078 "List of holidays, for Diary display in Org mode."
17079 (require 'holidays)
17080 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17081 (and hl (mapconcat #'identity hl "; "))))
17083 (defun org-diary-sexp-entry (sexp entry d)
17084 "Process a SEXP diary ENTRY for date D."
17085 (require 'diary-lib)
17086 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17087 ;; dynamically.
17088 (let* ((sexp `(let ((entry ,entry)
17089 (date ',d))
17090 ,(car (read-from-string sexp))))
17091 (result (if calendar-debug-sexp (eval sexp)
17092 (condition-case nil
17093 (eval sexp)
17094 (error
17095 (beep)
17096 (message "Bad sexp at line %d in %s: %s"
17097 (org-current-line)
17098 (buffer-file-name) sexp)
17099 (sleep-for 2))))))
17100 (cond ((stringp result) (split-string result "; "))
17101 ((and (consp result)
17102 (not (consp (cdr result)))
17103 (stringp (cdr result))) (cdr result))
17104 ((and (consp result)
17105 (stringp (car result))) result)
17106 (result entry))))
17108 (defun org-diary-to-ical-string (frombuf)
17109 "Get iCalendar entries from diary entries in buffer FROMBUF.
17110 This uses the icalendar.el library."
17111 (let* ((tmpdir temporary-file-directory)
17112 (tmpfile (make-temp-name
17113 (expand-file-name "orgics" tmpdir)))
17114 buf rtn b e)
17115 (with-current-buffer frombuf
17116 (icalendar-export-region (point-min) (point-max) tmpfile)
17117 (setq buf (find-buffer-visiting tmpfile))
17118 (set-buffer buf)
17119 (goto-char (point-min))
17120 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17121 (setq b (match-beginning 0)))
17122 (goto-char (point-max))
17123 (when (re-search-backward "^END:VEVENT" nil t)
17124 (setq e (match-end 0)))
17125 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17126 (kill-buffer buf)
17127 (delete-file tmpfile)
17128 rtn))
17130 (defun org-closest-date (start current prefer)
17131 "Return closest date to CURRENT starting from START.
17133 CURRENT and START are both time stamps.
17135 When PREFER is `past', return a date that is either CURRENT or
17136 past. When PREFER is `future', return a date that is either
17137 CURRENT or future.
17139 Only time stamps with a repeater are modified. Any other time
17140 stamp stay unchanged. In any case, return value is an absolute
17141 day number."
17142 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17143 ;; No repeater. Do not shift time stamp.
17144 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17145 (let ((value (string-to-number (match-string 1 start)))
17146 (type (match-string 2 start)))
17147 (if (= 0 value)
17148 ;; Repeater with a 0-value is considered as void.
17149 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17150 (let* ((base (org-date-to-gregorian start))
17151 (target (org-date-to-gregorian current))
17152 (sday (calendar-absolute-from-gregorian base))
17153 (cday (calendar-absolute-from-gregorian target))
17154 n1 n2)
17155 ;; If START is already past CURRENT, just return START.
17156 (if (<= cday sday) sday
17157 ;; Compute closest date before (N1) and closest date past
17158 ;; (N2) CURRENT.
17159 (pcase type
17160 ("h"
17161 (let ((missing-hours
17162 (mod (+ (- (* 24 (- cday sday))
17163 (nth 2 (org-parse-time-string start)))
17164 org-extend-today-until)
17165 value)))
17166 (setf n1 (if (= missing-hours 0) cday
17167 (- cday (1+ (/ missing-hours 24)))))
17168 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17169 ((or "d" "w")
17170 (let ((value (if (equal type "w") (* 7 value) value)))
17171 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17172 (setf n2 (+ n1 value))))
17173 ("m"
17174 (let* ((add-months
17175 (lambda (d n)
17176 ;; Add N months to gregorian date D, i.e.,
17177 ;; a list (MONTH DAY YEAR). Return a valid
17178 ;; gregorian date.
17179 (let ((m (+ (nth 0 d) n)))
17180 (list (mod m 12)
17181 (nth 1 d)
17182 (+ (/ m 12) (nth 2 d))))))
17183 (months ; Complete months to TARGET.
17184 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17185 (- (nth 0 target) (nth 0 base))
17186 ;; If START's day is greater than
17187 ;; TARGET's, remove incomplete month.
17188 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17189 value)
17190 value))
17191 (before (funcall add-months base months)))
17192 (setf n1 (calendar-absolute-from-gregorian before))
17193 (setf n2
17194 (calendar-absolute-from-gregorian
17195 (funcall add-months before value)))))
17197 (let* ((d (nth 1 base))
17198 (m (nth 0 base))
17199 (y (nth 2 base))
17200 (years ; Complete years to TARGET.
17201 (* (/ (- (nth 2 target)
17203 ;; If START's month and day are
17204 ;; greater than TARGET's, remove
17205 ;; incomplete year.
17206 (if (or (> (nth 0 target) m)
17207 (and (= (nth 0 target) m)
17208 (> (nth 1 target) d)))
17211 value)
17212 value))
17213 (before (list m d (+ y years))))
17214 (setf n1 (calendar-absolute-from-gregorian before))
17215 (setf n2 (calendar-absolute-from-gregorian
17216 (list m d (+ (nth 2 before) value)))))))
17217 ;; Handle PREFER parameter, if any.
17218 (cond
17219 ((eq prefer 'past) (if (= cday n2) n2 n1))
17220 ((eq prefer 'future) (if (= cday n1) n1 n2))
17221 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17223 (defun org-date-to-gregorian (d)
17224 "Turn any specification of date D into a Gregorian date for the calendar."
17225 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17226 ((and (listp d) (= (length d) 3)) d)
17227 ((stringp d)
17228 (let ((d (org-parse-time-string d)))
17229 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17230 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17232 (defun org-parse-time-string (s &optional nodefault)
17233 "Parse the standard Org time string.
17235 This should be a lot faster than the normal `parse-time-string'.
17237 If time is not given, defaults to 0:00. However, with optional
17238 NODEFAULT, hour and minute fields will be nil if not given."
17239 (cond ((string-match org-ts-regexp0 s)
17240 (list 0
17241 (when (or (match-beginning 8) (not nodefault))
17242 (string-to-number (or (match-string 8 s) "0")))
17243 (when (or (match-beginning 7) (not nodefault))
17244 (string-to-number (or (match-string 7 s) "0")))
17245 (string-to-number (match-string 4 s))
17246 (string-to-number (match-string 3 s))
17247 (string-to-number (match-string 2 s))
17248 nil nil nil))
17249 ((string-match "^<[^>]+>$" s)
17250 ;; FIXME: `decode-time' needs to be called with ZONE as its
17251 ;; second argument. However, this requires at least Emacs
17252 ;; 25.1. We can do it when we switch to this version as our
17253 ;; minimal requirement.
17254 (decode-time (seconds-to-time (org-matcher-time s))))
17255 (t (error "Not a standard Org time string: %s" s))))
17257 (defun org-timestamp-up (&optional arg)
17258 "Increase the date item at the cursor by one.
17259 If the cursor is on the year, change the year. If it is on the month,
17260 the day or the time, change that.
17261 With prefix ARG, change by that many units."
17262 (interactive "p")
17263 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17265 (defun org-timestamp-down (&optional arg)
17266 "Decrease the date item at the cursor by one.
17267 If the cursor is on the year, change the year. If it is on the month,
17268 the day or the time, change that.
17269 With prefix ARG, change by that many units."
17270 (interactive "p")
17271 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17273 (defun org-timestamp-up-day (&optional arg)
17274 "Increase the date in the time stamp by one day.
17275 With prefix ARG, change that many days."
17276 (interactive "p")
17277 (if (and (not (org-at-timestamp-p 'lax))
17278 (org-at-heading-p))
17279 (org-todo 'up)
17280 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17282 (defun org-timestamp-down-day (&optional arg)
17283 "Decrease the date in the time stamp by one day.
17284 With prefix ARG, change that many days."
17285 (interactive "p")
17286 (if (and (not (org-at-timestamp-p 'lax))
17287 (org-at-heading-p))
17288 (org-todo 'down)
17289 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17291 (defun org-at-timestamp-p (&optional extended)
17292 "Non-nil if point is inside a timestamp.
17294 By default, the function only consider syntactically valid active
17295 timestamps. However, the caller may have a broader definition
17296 for timestamps. As a consequence, optional argument EXTENDED can
17297 be set to the following values
17299 `inactive'
17301 Include also syntactically valid inactive timestamps.
17303 `agenda'
17305 Include timestamps allowed in Agenda, i.e., those in
17306 properties drawers, planning lines and clock lines.
17308 `lax'
17310 Ignore context. The function matches any part of the
17311 document looking like a timestamp. This includes comments,
17312 example blocks...
17314 For backward-compatibility with Org 9.0, every other non-nil
17315 value is equivalent to `inactive'.
17317 When at a timestamp, return the position of the point as a symbol
17318 among `bracket', `after', `year', `month', `hour', `minute',
17319 `day' or a number of character from the last know part of the
17320 time stamp.
17322 When matching, the match groups are the following:
17323 group 1: year
17324 group 2: month
17325 group 3: day number
17326 group 4: day name
17327 group 5: hours, if any
17328 group 6: minutes, if any"
17329 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17330 (pos (point))
17331 (match?
17332 (let ((boundaries (org-in-regexp regexp)))
17333 (save-match-data
17334 (cond ((null boundaries) nil)
17335 ((eq extended 'lax) t)
17337 (or (and (eq extended 'agenda)
17338 (or (org-at-planning-p)
17339 (org-at-property-p)
17340 (and (bound-and-true-p
17341 org-agenda-include-inactive-timestamps)
17342 (org-at-clock-log-p))))
17343 (eq 'timestamp
17344 (save-excursion
17345 (when (= pos (cdr boundaries)) (forward-char -1))
17346 (org-element-type (org-element-context)))))))))))
17347 (cond
17348 ((not match?) nil)
17349 ((= pos (match-beginning 0)) 'bracket)
17350 ;; Distinguish location right before the closing bracket from
17351 ;; right after it.
17352 ((= pos (1- (match-end 0))) 'bracket)
17353 ((= pos (match-end 0)) 'after)
17354 ((org-pos-in-match-range pos 2) 'year)
17355 ((org-pos-in-match-range pos 3) 'month)
17356 ((org-pos-in-match-range pos 7) 'hour)
17357 ((org-pos-in-match-range pos 8) 'minute)
17358 ((or (org-pos-in-match-range pos 4)
17359 (org-pos-in-match-range pos 5)) 'day)
17360 ((and (> pos (or (match-end 8) (match-end 5)))
17361 (< pos (match-end 0)))
17362 (- pos (or (match-end 8) (match-end 5))))
17363 (t 'day))))
17365 (defun org-toggle-timestamp-type ()
17366 "Toggle the type (<active> or [inactive]) of a time stamp."
17367 (interactive)
17368 (when (org-at-timestamp-p 'lax)
17369 (let ((beg (match-beginning 0)) (end (match-end 0))
17370 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17371 (save-excursion
17372 (goto-char beg)
17373 (while (re-search-forward "[][<>]" end t)
17374 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17375 t t)))
17376 (message "Timestamp is now %sactive"
17377 (if (equal (char-after beg) ?<) "" "in")))))
17379 (defun org-at-clock-log-p ()
17380 "Non-nil if point is on a clock log line."
17381 (and (org-match-line org-clock-line-re)
17382 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17384 (defvar org-clock-history) ; defined in org-clock.el
17385 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17386 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17387 "Change the date in the time stamp at point.
17388 The date will be changed by N times WHAT. WHAT can be `day', `month',
17389 `year', `minute', `second'. If WHAT is not given, the cursor position
17390 in the timestamp determines what will be changed.
17391 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17392 (let ((origin (point))
17393 (timestamp? (org-at-timestamp-p 'lax))
17394 origin-cat
17395 with-hm inactive
17396 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17397 extra rem
17398 ts time time0 fixnext clrgx)
17399 (unless timestamp? (user-error "Not at a timestamp"))
17400 (if (and (not what) (eq timestamp? 'bracket))
17401 (org-toggle-timestamp-type)
17402 ;; Point isn't on brackets. Remember the part of the time-stamp
17403 ;; the point was in. Indeed, size of time-stamps may change,
17404 ;; but point must be kept in the same category nonetheless.
17405 (setq origin-cat timestamp?)
17406 (when (and (not what) (not (eq timestamp? 'day))
17407 org-display-custom-times
17408 (get-text-property (point) 'display)
17409 (not (get-text-property (1- (point)) 'display)))
17410 (setq timestamp? 'day))
17411 (setq timestamp? (or what timestamp?)
17412 inactive (= (char-after (match-beginning 0)) ?\[)
17413 ts (match-string 0))
17414 (replace-match "")
17415 (when (string-match
17416 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17418 (setq extra (match-string 1 ts))
17419 (when suppress-tmp-delay
17420 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17421 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17422 (setq with-hm t))
17423 (setq time0 (org-parse-time-string ts))
17424 (when (and updown
17425 (eq timestamp? 'minute)
17426 (not current-prefix-arg))
17427 ;; This looks like s-up and s-down. Change by one rounding step.
17428 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17429 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17430 (setcar (cdr time0) (+ (nth 1 time0)
17431 (if (> n 0) (- rem) (- dm rem))))))
17432 (setq time
17433 (apply #'encode-time
17434 (or (car time0) 0)
17435 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17436 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17437 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17438 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17439 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17440 (nthcdr 6 time0)))
17441 (when (and (memq timestamp? '(hour minute))
17442 extra
17443 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17444 (setq extra (org-modify-ts-extra
17445 extra
17446 (if (eq timestamp? 'hour) 2 5)
17447 n dm)))
17448 (when (integerp timestamp?)
17449 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17450 (when (eq what 'calendar)
17451 (let ((cal-date (org-get-date-from-calendar)))
17452 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17453 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17454 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17455 (setcar time0 (or (car time0) 0))
17456 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17457 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17458 (setq time (apply 'encode-time time0))))
17459 ;; Insert the new time-stamp, and ensure point stays in the same
17460 ;; category as before (i.e. not after the last position in that
17461 ;; category).
17462 (let ((pos (point)))
17463 ;; Stay before inserted string. `save-excursion' is of no use.
17464 (setq org-last-changed-timestamp
17465 (org-insert-time-stamp time with-hm inactive nil nil extra))
17466 (goto-char pos))
17467 (save-match-data
17468 (looking-at org-ts-regexp3)
17469 (goto-char
17470 (pcase origin-cat
17471 ;; `day' category ends before `hour' if any, or at the end
17472 ;; of the day name.
17473 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17474 (`hour (min (match-end 7) origin))
17475 (`minute (min (1- (match-end 8)) origin))
17476 ((pred integerp) (min (1- (match-end 0)) origin))
17477 ;; Point was right after the time-stamp. However, the
17478 ;; time-stamp length might have changed, so refer to
17479 ;; (match-end 0) instead.
17480 (`after (match-end 0))
17481 ;; `year' and `month' have both fixed size: point couldn't
17482 ;; have moved into another part.
17483 (_ origin))))
17484 ;; Update clock if on a CLOCK line.
17485 (org-clock-update-time-maybe)
17486 ;; Maybe adjust the closest clock in `org-clock-history'
17487 (when org-clock-adjust-closest
17488 (if (not (and (org-at-clock-log-p)
17489 (< 1 (length (delq nil (mapcar 'marker-position
17490 org-clock-history))))))
17491 (message "No clock to adjust")
17492 (cond ((save-excursion ; fix previous clock?
17493 (re-search-backward org-ts-regexp0 nil t)
17494 (looking-back (concat org-clock-string " \\[")
17495 (line-beginning-position)))
17496 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17497 ((save-excursion ; fix next clock?
17498 (re-search-backward org-ts-regexp0 nil t)
17499 (looking-at (concat org-ts-regexp0 "\\] =>")))
17500 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17501 (save-window-excursion
17502 ;; Find closest clock to point, adjust the previous/next one in history
17503 (let* ((p (save-excursion (org-back-to-heading t)))
17504 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17505 (clfixnth
17506 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17507 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17508 (if (not clfixpos)
17509 (message "No clock to adjust")
17510 (save-excursion
17511 (org-goto-marker-or-bmk clfixpos)
17512 (org-show-subtree)
17513 (when (re-search-forward clrgx nil t)
17514 (goto-char (match-beginning 1))
17515 (let (org-clock-adjust-closest)
17516 (org-timestamp-change n timestamp? updown))
17517 (message "Clock adjusted in %s for heading: %s"
17518 (file-name-nondirectory (buffer-file-name))
17519 (org-get-heading t t)))))))))
17520 ;; Try to recenter the calendar window, if any.
17521 (when (and org-calendar-follow-timestamp-change
17522 (get-buffer-window "*Calendar*" t)
17523 (memq timestamp? '(day month year)))
17524 (org-recenter-calendar (time-to-days time))))))
17526 (defun org-modify-ts-extra (s pos n dm)
17527 "Change the different parts of the lead-time and repeat fields in timestamp."
17528 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17529 ng h m new rem)
17530 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17531 (cond
17532 ((or (org-pos-in-match-range pos 2)
17533 (org-pos-in-match-range pos 3))
17534 (setq m (string-to-number (match-string 3 s))
17535 h (string-to-number (match-string 2 s)))
17536 (if (org-pos-in-match-range pos 2)
17537 (setq h (+ h n))
17538 (setq n (* dm (with-no-warnings (signum n))))
17539 (unless (= 0 (setq rem (% m dm)))
17540 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17541 (setq m (+ m n)))
17542 (when (< m 0) (setq m (+ m 60) h (1- h)))
17543 (when (> m 59) (setq m (- m 60) h (1+ h)))
17544 (setq h (mod h 24))
17545 (setq ng 1 new (format "-%02d:%02d" h m)))
17546 ((org-pos-in-match-range pos 6)
17547 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17548 ((org-pos-in-match-range pos 5)
17549 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17551 ((org-pos-in-match-range pos 9)
17552 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17553 ((org-pos-in-match-range pos 8)
17554 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17556 (when ng
17557 (setq s (concat
17558 (substring s 0 (match-beginning ng))
17560 (substring s (match-end ng))))))
17563 (defun org-recenter-calendar (d)
17564 "If the calendar is visible, recenter it to date D."
17565 (let ((cwin (get-buffer-window "*Calendar*" t)))
17566 (when cwin
17567 (let ((calendar-move-hook nil))
17568 (with-selected-window cwin
17569 (calendar-goto-date
17570 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17572 (defun org-goto-calendar (&optional arg)
17573 "Go to the Emacs calendar at the current date.
17574 If there is a time stamp in the current line, go to that date.
17575 A prefix ARG can be used to force the current date."
17576 (interactive "P")
17577 (let ((calendar-move-hook nil)
17578 (calendar-view-holidays-initially-flag nil)
17579 (calendar-view-diary-initially-flag nil)
17580 diff)
17581 (when (or (org-at-timestamp-p 'lax)
17582 (org-match-line (concat ".*" org-ts-regexp)))
17583 (let ((d1 (time-to-days (current-time)))
17584 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17585 (setq diff (- d2 d1))))
17586 (calendar)
17587 (calendar-goto-today)
17588 (when (and diff (not arg)) (calendar-forward-day diff))))
17590 (defun org-get-date-from-calendar ()
17591 "Return a list (month day year) of date at point in calendar."
17592 (with-current-buffer "*Calendar*"
17593 (save-match-data
17594 (calendar-cursor-to-date))))
17596 (defun org-date-from-calendar ()
17597 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17598 If there is already a time stamp at the cursor position, update it."
17599 (interactive)
17600 (if (org-at-timestamp-p 'lax)
17601 (org-timestamp-change 0 'calendar)
17602 (let ((cal-date (org-get-date-from-calendar)))
17603 (org-insert-time-stamp
17604 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17606 (defcustom org-effort-durations
17607 `(("min" . 1)
17608 ("h" . 60)
17609 ("d" . ,(* 60 8))
17610 ("w" . ,(* 60 8 5))
17611 ("m" . ,(* 60 8 5 4))
17612 ("y" . ,(* 60 8 5 40)))
17613 "Conversion factor to minutes for an effort modifier.
17615 Each entry has the form (MODIFIER . MINUTES).
17617 In an effort string, a number followed by MODIFIER is multiplied
17618 by the specified number of MINUTES to obtain an effort in
17619 minutes.
17621 For example, if the value of this variable is ((\"hours\" . 60)), then an
17622 effort string \"2hours\" is equivalent to 120 minutes."
17623 :group 'org-agenda
17624 :version "26.1"
17625 :package-version '(Org . "8.3")
17626 :type '(alist :key-type (string :tag "Modifier")
17627 :value-type (number :tag "Minutes")))
17629 (defcustom org-image-actual-width t
17630 "Should we use the actual width of images when inlining them?
17632 When set to t, always use the image width.
17634 When set to a number, use imagemagick (when available) to set
17635 the image's width to this value.
17637 When set to a number in a list, try to get the width from any
17638 #+ATTR.* keyword if it matches a width specification like
17640 #+ATTR_HTML: :width 300px
17642 and fall back on that number if none is found.
17644 When set to nil, try to get the width from an #+ATTR.* keyword
17645 and fall back on the original width if none is found.
17647 This requires Emacs >= 24.1, build with imagemagick support."
17648 :group 'org-appearance
17649 :version "24.4"
17650 :package-version '(Org . "8.0")
17651 :type '(choice
17652 (const :tag "Use the image width" t)
17653 (integer :tag "Use a number of pixels")
17654 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17655 (const :tag "Use #+ATTR* or don't resize" nil)))
17657 (defcustom org-agenda-inhibit-startup nil
17658 "Inhibit startup when preparing agenda buffers.
17659 When this variable is t, the initialization of the Org agenda
17660 buffers is inhibited: e.g. the visibility state is not set, the
17661 tables are not re-aligned, etc."
17662 :type 'boolean
17663 :version "24.3"
17664 :group 'org-agenda)
17666 (defcustom org-agenda-ignore-properties nil
17667 "Avoid updating text properties when building the agenda.
17668 Properties are used to prepare buffers for effort estimates,
17669 appointments, statistics and subtree-local categories.
17670 If you don't use these in the agenda, you can add them to this
17671 list and agenda building will be a bit faster.
17672 The value is a list, with zero or more of the symbols `effort', `appt',
17673 `stats' or `category'."
17674 :type '(set :greedy t
17675 (const effort)
17676 (const appt)
17677 (const stats)
17678 (const category))
17679 :version "26.1"
17680 :package-version '(Org . "8.3")
17681 :group 'org-agenda)
17683 ;;;; Files
17685 (defun org-save-all-org-buffers ()
17686 "Save all Org buffers without user confirmation."
17687 (interactive)
17688 (message "Saving all Org buffers...")
17689 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17690 (when (featurep 'org-id) (org-id-locations-save))
17691 (message "Saving all Org buffers... done"))
17693 (defun org-revert-all-org-buffers ()
17694 "Revert all Org buffers.
17695 Prompt for confirmation when there are unsaved changes.
17696 Be sure you know what you are doing before letting this function
17697 overwrite your changes.
17699 This function is useful in a setup where one tracks Org files
17700 with a version control system, to revert on one machine after pulling
17701 changes from another. I believe the procedure must be like this:
17703 1. M-x org-save-all-org-buffers
17704 2. Pull changes from the other machine, resolve conflicts
17705 3. M-x org-revert-all-org-buffers"
17706 (interactive)
17707 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17708 (user-error "Abort"))
17709 (save-excursion
17710 (save-window-excursion
17711 (dolist (b (buffer-list))
17712 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17713 (with-current-buffer b buffer-file-name))
17714 (pop-to-buffer-same-window b)
17715 (revert-buffer t 'no-confirm)))
17716 (when (and (featurep 'org-id) org-id-track-globally)
17717 (org-id-locations-load)))))
17719 ;;;; Agenda files
17721 ;;;###autoload
17722 (defun org-switchb (&optional arg)
17723 "Switch between Org buffers.
17725 With `\\[universal-argument]' prefix, restrict available buffers to files.
17727 With `\\[universal-argument] \\[universal-argument]' \
17728 prefix, restrict available buffers to agenda files."
17729 (interactive "P")
17730 (let ((blist (org-buffer-list
17731 (cond ((equal arg '(4)) 'files)
17732 ((equal arg '(16)) 'agenda)))))
17733 (pop-to-buffer-same-window
17734 (completing-read "Org buffer: "
17735 (mapcar #'list (mapcar #'buffer-name blist))
17736 nil t))))
17738 (defun org-buffer-list (&optional predicate exclude-tmp)
17739 "Return a list of Org buffers.
17740 PREDICATE can be `export', `files' or `agenda'.
17742 export restrict the list to Export buffers.
17743 files restrict the list to buffers visiting Org files.
17744 agenda restrict the list to buffers visiting agenda files.
17746 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17747 (let* ((bfn nil)
17748 (agenda-files (and (eq predicate 'agenda)
17749 (mapcar 'file-truename (org-agenda-files t))))
17750 (filter
17751 (cond
17752 ((eq predicate 'files)
17753 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17754 ((eq predicate 'export)
17755 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17756 ((eq predicate 'agenda)
17757 (lambda (b)
17758 (with-current-buffer b
17759 (and (derived-mode-p 'org-mode)
17760 (setq bfn (buffer-file-name b))
17761 (member (file-truename bfn) agenda-files)))))
17762 (t (lambda (b) (with-current-buffer b
17763 (or (derived-mode-p 'org-mode)
17764 (string-match "\\*Org .*Export"
17765 (buffer-name b)))))))))
17766 (delq nil
17767 (mapcar
17768 (lambda(b)
17769 (if (and (funcall filter b)
17770 (or (not exclude-tmp)
17771 (not (string-match "tmp" (buffer-name b)))))
17773 nil))
17774 (buffer-list)))))
17776 (defun org-agenda-files (&optional unrestricted archives)
17777 "Get the list of agenda files.
17778 Optional UNRESTRICTED means return the full list even if a restriction
17779 is currently in place.
17780 When ARCHIVES is t, include all archive files that are really being
17781 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17782 `org-agenda-archives-mode' is t."
17783 (let ((files
17784 (cond
17785 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17786 ((stringp org-agenda-files) (org-read-agenda-file-list))
17787 ((listp org-agenda-files) org-agenda-files)
17788 (t (error "Invalid value of `org-agenda-files'")))))
17789 (setq files (apply 'append
17790 (mapcar (lambda (f)
17791 (if (file-directory-p f)
17792 (directory-files
17793 f t org-agenda-file-regexp)
17794 (list f)))
17795 files)))
17796 (when org-agenda-skip-unavailable-files
17797 (setq files (delq nil
17798 (mapcar (function
17799 (lambda (file)
17800 (and (file-readable-p file) file)))
17801 files))))
17802 (when (or (eq archives t)
17803 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17804 (setq files (org-add-archive-files files)))
17805 files))
17807 (defun org-agenda-file-p (&optional file)
17808 "Return non-nil, if FILE is an agenda file.
17809 If FILE is omitted, use the file associated with the current
17810 buffer."
17811 (let ((fname (or file (buffer-file-name))))
17812 (and fname
17813 (member (file-truename fname)
17814 (mapcar #'file-truename (org-agenda-files t))))))
17816 (defun org-edit-agenda-file-list ()
17817 "Edit the list of agenda files.
17818 Depending on setup, this either uses customize to edit the variable
17819 `org-agenda-files', or it visits the file that is holding the list. In the
17820 latter case, the buffer is set up in a way that saving it automatically kills
17821 the buffer and restores the previous window configuration."
17822 (interactive)
17823 (if (stringp org-agenda-files)
17824 (let ((cw (current-window-configuration)))
17825 (find-file org-agenda-files)
17826 (setq-local org-window-configuration cw)
17827 (add-hook 'after-save-hook
17828 (lambda ()
17829 (set-window-configuration
17830 (prog1 org-window-configuration
17831 (kill-buffer (current-buffer))))
17832 (org-install-agenda-files-menu)
17833 (message "New agenda file list installed"))
17834 nil 'local)
17835 (message "%s" (substitute-command-keys
17836 "Edit list and finish with \\[save-buffer]")))
17837 (customize-variable 'org-agenda-files)))
17839 (defun org-store-new-agenda-file-list (list)
17840 "Set new value for the agenda file list and save it correctly."
17841 (if (stringp org-agenda-files)
17842 (let ((fe (org-read-agenda-file-list t)) b u)
17843 (while (setq b (find-buffer-visiting org-agenda-files))
17844 (kill-buffer b))
17845 (with-temp-file org-agenda-files
17846 (insert
17847 (mapconcat
17848 (lambda (f) ;; Keep un-expanded entries.
17849 (if (setq u (assoc f fe))
17850 (cdr u)
17852 list "\n")
17853 "\n")))
17854 (let ((org-mode-hook nil) (org-inhibit-startup t)
17855 (org-insert-mode-line-in-empty-file nil))
17856 (setq org-agenda-files list)
17857 (customize-save-variable 'org-agenda-files org-agenda-files))))
17859 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17860 "Read the list of agenda files from a file.
17861 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17862 filenames, used by `org-store-new-agenda-file-list' to write back
17863 un-expanded file names."
17864 (when (file-directory-p org-agenda-files)
17865 (error "`org-agenda-files' cannot be a single directory"))
17866 (when (stringp org-agenda-files)
17867 (with-temp-buffer
17868 (insert-file-contents org-agenda-files)
17869 (mapcar
17870 (lambda (f)
17871 (let ((e (expand-file-name (substitute-in-file-name f)
17872 org-directory)))
17873 (if pair-with-expansion
17874 (cons e f)
17875 e)))
17876 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17878 ;;;###autoload
17879 (defun org-cycle-agenda-files ()
17880 "Cycle through the files in `org-agenda-files'.
17881 If the current buffer visits an agenda file, find the next one in the list.
17882 If the current buffer does not, find the first agenda file."
17883 (interactive)
17884 (let* ((fs (or (org-agenda-files t)
17885 (user-error "No agenda files")))
17886 (files (copy-sequence fs))
17887 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17888 file)
17889 (when tcf
17890 (while (and (setq file (pop files))
17891 (not (equal (file-truename file) tcf)))))
17892 (find-file (car (or files fs)))
17893 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17895 (defun org-agenda-file-to-front (&optional to-end)
17896 "Move/add the current file to the top of the agenda file list.
17897 If the file is not present in the list, it is added to the front. If it is
17898 present, it is moved there. With optional argument TO-END, add/move to the
17899 end of the list."
17900 (interactive "P")
17901 (let ((org-agenda-skip-unavailable-files nil)
17902 (file-alist (mapcar (lambda (x)
17903 (cons (file-truename x) x))
17904 (org-agenda-files t)))
17905 (ctf (file-truename
17906 (or buffer-file-name
17907 (user-error "Please save the current buffer to a file"))))
17908 x had)
17909 (setq x (assoc ctf file-alist) had x)
17911 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17912 (if to-end
17913 (setq file-alist (append (delq x file-alist) (list x)))
17914 (setq file-alist (cons x (delq x file-alist))))
17915 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17916 (org-install-agenda-files-menu)
17917 (message "File %s to %s of agenda file list"
17918 (if had "moved" "added") (if to-end "end" "front"))))
17920 (defun org-remove-file (&optional file)
17921 "Remove current file from the list of files in variable `org-agenda-files'.
17922 These are the files which are being checked for agenda entries.
17923 Optional argument FILE means use this file instead of the current."
17924 (interactive)
17925 (let* ((org-agenda-skip-unavailable-files nil)
17926 (file (or file buffer-file-name
17927 (user-error "Current buffer does not visit a file")))
17928 (true-file (file-truename file))
17929 (afile (abbreviate-file-name file))
17930 (files (delq nil (mapcar
17931 (lambda (x)
17932 (unless (equal true-file
17933 (file-truename x))
17935 (org-agenda-files t)))))
17936 (if (not (= (length files) (length (org-agenda-files t))))
17937 (progn
17938 (org-store-new-agenda-file-list files)
17939 (org-install-agenda-files-menu)
17940 (message "Removed from Org Agenda list: %s" afile))
17941 (message "File was not in list: %s (not removed)" afile))))
17943 (defun org-file-menu-entry (file)
17944 (vector file (list 'find-file file) t))
17946 (defun org-check-agenda-file (file)
17947 "Make sure FILE exists. If not, ask user what to do."
17948 (unless (file-exists-p file)
17949 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17950 (abbreviate-file-name file))
17951 (let ((r (downcase (read-char-exclusive))))
17952 (cond
17953 ((equal r ?r)
17954 (org-remove-file file)
17955 (throw 'nextfile t))
17956 (t (user-error "Abort"))))))
17958 (defun org-get-agenda-file-buffer (file)
17959 "Get an agenda buffer visiting FILE.
17960 If the buffer needs to be created, add it to the list of buffers
17961 which might be released later."
17962 (let ((buf (org-find-base-buffer-visiting file)))
17963 (if buf
17964 buf ; just return it
17965 ;; Make a new buffer and remember it
17966 (setq buf (find-file-noselect file))
17967 (when buf (push buf org-agenda-new-buffers))
17968 buf)))
17970 (defun org-release-buffers (blist)
17971 "Release all buffers in list, asking the user for confirmation when needed.
17972 When a buffer is unmodified, it is just killed. When modified, it is saved
17973 \(if the user agrees) and then killed."
17974 (let (file)
17975 (dolist (buf blist)
17976 (setq file (buffer-file-name buf))
17977 (when (and (buffer-modified-p buf)
17978 file
17979 (y-or-n-p (format "Save file %s? " file)))
17980 (with-current-buffer buf (save-buffer)))
17981 (kill-buffer buf))))
17983 (defun org-agenda-prepare-buffers (files)
17984 "Create buffers for all agenda files, protect archived trees and comments."
17985 (interactive)
17986 (let ((pa '(:org-archived t))
17987 (pc '(:org-comment t))
17988 (pall '(:org-archived t :org-comment t))
17989 (inhibit-read-only t)
17990 (org-inhibit-startup org-agenda-inhibit-startup)
17991 (rea (concat ":" org-archive-tag ":"))
17992 re pos)
17993 (setq org-tag-alist-for-agenda nil
17994 org-tag-groups-alist-for-agenda nil)
17995 (save-excursion
17996 (save-restriction
17997 (dolist (file files)
17998 (catch 'nextfile
17999 (if (bufferp file)
18000 (set-buffer file)
18001 (org-check-agenda-file file)
18002 (set-buffer (org-get-agenda-file-buffer file)))
18003 (widen)
18004 (org-set-regexps-and-options 'tags-only)
18005 (setq pos (point))
18006 (or (memq 'category org-agenda-ignore-properties)
18007 (org-refresh-category-properties))
18008 (or (memq 'stats org-agenda-ignore-properties)
18009 (org-refresh-stats-properties))
18010 (or (memq 'effort org-agenda-ignore-properties)
18011 (org-refresh-effort-properties))
18012 (or (memq 'appt org-agenda-ignore-properties)
18013 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18014 (setq org-todo-keywords-for-agenda
18015 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18016 (setq org-done-keywords-for-agenda
18017 (append org-done-keywords-for-agenda org-done-keywords))
18018 (setq org-todo-keyword-alist-for-agenda
18019 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18020 (setq org-tag-alist-for-agenda
18021 (org-tag-add-to-alist
18022 org-tag-alist-for-agenda
18023 org-current-tag-alist))
18024 ;; Merge current file's tag groups into global
18025 ;; `org-tag-groups-alist-for-agenda'.
18026 (when org-group-tags
18027 (dolist (alist org-tag-groups-alist)
18028 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18029 (if old
18030 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18031 (push alist org-tag-groups-alist-for-agenda)))))
18032 (org-with-silent-modifications
18033 (save-excursion
18034 (remove-text-properties (point-min) (point-max) pall)
18035 (when org-agenda-skip-archived-trees
18036 (goto-char (point-min))
18037 (while (re-search-forward rea nil t)
18038 (when (org-at-heading-p t)
18039 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18040 (goto-char (point-min))
18041 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18042 (while (re-search-forward re nil t)
18043 (when (save-match-data (org-in-commented-heading-p t))
18044 (add-text-properties
18045 (match-beginning 0) (org-end-of-subtree t) pc)))))
18046 (goto-char pos)))))
18047 (setq org-todo-keywords-for-agenda
18048 (org-uniquify org-todo-keywords-for-agenda))
18049 (setq org-todo-keyword-alist-for-agenda
18050 (org-uniquify org-todo-keyword-alist-for-agenda))))
18053 ;;;; CDLaTeX minor mode
18055 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18056 "Keymap for the minor `org-cdlatex-mode'.")
18058 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
18059 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
18060 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
18061 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
18062 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
18064 (defvar org-cdlatex-texmathp-advice-is-done nil
18065 "Flag remembering if we have applied the advice to texmathp already.")
18067 (define-minor-mode org-cdlatex-mode
18068 "Toggle the minor `org-cdlatex-mode'.
18069 This mode supports entering LaTeX environment and math in LaTeX fragments
18070 in Org mode.
18071 \\{org-cdlatex-mode-map}"
18072 nil " OCDL" nil
18073 (when org-cdlatex-mode
18074 (require 'cdlatex)
18075 (run-hooks 'cdlatex-mode-hook)
18076 (cdlatex-compute-tables))
18077 (unless org-cdlatex-texmathp-advice-is-done
18078 (setq org-cdlatex-texmathp-advice-is-done t)
18079 (defadvice texmathp (around org-math-always-on activate)
18080 "Always return t in Org buffers.
18081 This is because we want to insert math symbols without dollars even outside
18082 the LaTeX math segments. If Org mode thinks that point is actually inside
18083 an embedded LaTeX fragment, let `texmathp' do its job.
18084 `\\[org-cdlatex-mode-map]'"
18085 (interactive)
18086 (let (p)
18087 (cond
18088 ((not (derived-mode-p 'org-mode)) ad-do-it)
18089 ((eq this-command 'cdlatex-math-symbol)
18090 (setq ad-return-value t
18091 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18093 (let ((p (org-inside-LaTeX-fragment-p)))
18094 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18095 (setq ad-return-value t
18096 texmathp-why '("Org mode embedded math" . 0))
18097 (when p ad-do-it)))))))))
18099 (defun turn-on-org-cdlatex ()
18100 "Unconditionally turn on `org-cdlatex-mode'."
18101 (org-cdlatex-mode 1))
18103 (defun org-try-cdlatex-tab ()
18104 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18105 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18106 - inside a LaTeX fragment, or
18107 - after the first word in a line, where an abbreviation expansion could
18108 insert a LaTeX environment."
18109 (when org-cdlatex-mode
18110 (cond
18111 ;; Before any word on the line: No expansion possible.
18112 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18113 ;; Just after first word on the line: Expand it. Make sure it
18114 ;; cannot happen on headlines, though.
18115 ((save-excursion
18116 (skip-chars-backward "a-zA-Z0-9*")
18117 (skip-chars-backward " \t")
18118 (and (bolp) (not (org-at-heading-p))))
18119 (cdlatex-tab) t)
18120 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18122 (defun org-cdlatex-underscore-caret (&optional _arg)
18123 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18124 Revert to the normal definition outside of these fragments."
18125 (interactive "P")
18126 (if (org-inside-LaTeX-fragment-p)
18127 (call-interactively 'cdlatex-sub-superscript)
18128 (let (org-cdlatex-mode)
18129 (call-interactively (key-binding (vector last-input-event))))))
18131 (defun org-cdlatex-math-modify (&optional _arg)
18132 "Execute `cdlatex-math-modify' in LaTeX fragments.
18133 Revert to the normal definition outside of these fragments."
18134 (interactive "P")
18135 (if (org-inside-LaTeX-fragment-p)
18136 (call-interactively 'cdlatex-math-modify)
18137 (let (org-cdlatex-mode)
18138 (call-interactively (key-binding (vector last-input-event))))))
18140 (defun org-cdlatex-environment-indent (&optional environment item)
18141 "Execute `cdlatex-environment' and indent the inserted environment.
18143 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18145 The inserted environment is indented to current indentation
18146 unless point is at the beginning of the line, in which the
18147 environment remains unintended."
18148 (interactive)
18149 ;; cdlatex-environment always return nil. Therefore, capture output
18150 ;; first and determine if an environment was selected.
18151 (let* ((beg (point-marker))
18152 (end (copy-marker (point) t))
18153 (inserted (progn
18154 (ignore-errors (cdlatex-environment environment item))
18155 (< beg end)))
18156 ;; Figure out how many lines to move forward after the
18157 ;; environment has been inserted.
18158 (lines (when inserted
18159 (save-excursion
18160 (- (cl-loop while (< beg (point))
18161 with x = 0
18162 do (forward-line -1)
18163 (cl-incf x)
18164 finally return x)
18165 (if (progn (goto-char beg)
18166 (and (progn (skip-chars-forward " \t") (eolp))
18167 (progn (skip-chars-backward " \t") (bolp))))
18168 1 0)))))
18169 (env (org-trim (delete-and-extract-region beg end))))
18170 (when inserted
18171 ;; Get indentation of next line unless at column 0.
18172 (let ((ind (if (bolp) 0
18173 (save-excursion
18174 (org-return-indent)
18175 (prog1 (org-get-indentation)
18176 (when (progn (skip-chars-forward " \t") (eolp))
18177 (delete-region beg (point)))))))
18178 (bol (progn (skip-chars-backward " \t") (bolp))))
18179 ;; Insert a newline before environment unless at column zero
18180 ;; to "escape" the current line. Insert a newline if
18181 ;; something is one the same line as \end{ENVIRONMENT}.
18182 (insert
18183 (concat (unless bol "\n") env
18184 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18185 (unless (zerop ind)
18186 (save-excursion
18187 (goto-char beg)
18188 (while (< (point) end)
18189 (unless (eolp) (indent-line-to ind))
18190 (forward-line))))
18191 (goto-char beg)
18192 (forward-line lines)
18193 (indent-line-to ind)))
18194 (set-marker beg nil)
18195 (set-marker end nil)))
18198 ;;;; LaTeX fragments
18200 (defun org-inside-LaTeX-fragment-p ()
18201 "Test if point is inside a LaTeX fragment.
18202 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18203 sequence appearing also before point.
18204 Even though the matchers for math are configurable, this function assumes
18205 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18206 delimiters are skipped when they have been removed by customization.
18207 The return value is nil, or a cons cell with the delimiter and the
18208 position of this delimiter.
18210 This function does a reasonably good job, but can locally be fooled by
18211 for example currency specifications. For example it will assume being in
18212 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18213 fragments that are properly closed, but during editing, we have to live
18214 with the uncertainty caused by missing closing delimiters. This function
18215 looks only before point, not after."
18216 (catch 'exit
18217 (let ((pos (point))
18218 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18219 (lim (save-excursion (org-backward-paragraph) (point)))
18220 dd-on str (start 0) m re)
18221 (goto-char pos)
18222 (when dodollar
18223 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18224 re (nth 1 (assoc "$" org-latex-regexps)))
18225 (while (string-match re str start)
18226 (cond
18227 ((= (match-end 0) (length str))
18228 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18229 ((= (match-end 0) (- (length str) 5))
18230 (throw 'exit nil))
18231 (t (setq start (match-end 0))))))
18232 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18233 (goto-char pos)
18234 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18235 (and (match-beginning 2) (throw 'exit nil))
18236 ;; count $$
18237 (while (re-search-backward "\\$\\$" lim t)
18238 (setq dd-on (not dd-on)))
18239 (goto-char pos)
18240 (when dd-on (cons "$$" m))))))
18242 (defun org-inside-latex-macro-p ()
18243 "Is point inside a LaTeX macro or its arguments?"
18244 (save-match-data
18245 (org-in-regexp
18246 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18248 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18249 "Build an overlay between BEG and END using IMAGE file.
18250 Argument IMAGETYPE is the extension of the displayed image,
18251 as a string. It defaults to \"png\"."
18252 (let ((ov (make-overlay beg end))
18253 (imagetype (or (intern imagetype) 'png)))
18254 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18255 (overlay-put ov 'evaporate t)
18256 (overlay-put ov
18257 'modification-hooks
18258 (list (lambda (o _flag _beg _end &optional _l)
18259 (delete-overlay o))))
18260 (overlay-put ov
18261 'display
18262 (list 'image :type imagetype :file image :ascent 'center))))
18264 (defun org--list-latex-overlays (&optional beg end)
18265 "List all Org LaTeX overlays in current buffer.
18266 Limit to overlays between BEG and END when those are provided."
18267 (cl-remove-if-not
18268 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18269 (overlays-in (or beg (point-min)) (or end (point-max)))))
18271 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18272 "Remove all overlays with LaTeX fragment images in current buffer.
18273 When optional arguments BEG and END are non-nil, remove all
18274 overlays between them instead. Return a non-nil value when some
18275 overlays were removed, nil otherwise."
18276 (let ((overlays (org--list-latex-overlays beg end)))
18277 (mapc #'delete-overlay overlays)
18278 overlays))
18280 (defun org-toggle-latex-fragment (&optional arg)
18281 "Preview the LaTeX fragment at point, or all locally or globally.
18283 If the cursor is on a LaTeX fragment, create the image and overlay
18284 it over the source code, if there is none. Remove it otherwise.
18285 If there is no fragment at point, display all fragments in the
18286 current section.
18288 With prefix ARG, preview or clear image for all fragments in the
18289 current subtree or in the whole buffer when used before the first
18290 headline. With a prefix ARG `\\[universal-argument] \
18291 \\[universal-argument]' preview or clear images
18292 for all fragments in the buffer."
18293 (interactive "P")
18294 (when (display-graphic-p)
18295 (catch 'exit
18296 (save-excursion
18297 (let (beg end msg)
18298 (cond
18299 ((or (equal arg '(16))
18300 (and (equal arg '(4))
18301 (org-with-limited-levels (org-before-first-heading-p))))
18302 (if (org-remove-latex-fragment-image-overlays)
18303 (progn (message "LaTeX fragments images removed from buffer")
18304 (throw 'exit nil))
18305 (setq msg "Creating images for buffer...")))
18306 ((equal arg '(4))
18307 (org-with-limited-levels (org-back-to-heading t))
18308 (setq beg (point))
18309 (setq end (progn (org-end-of-subtree t) (point)))
18310 (if (org-remove-latex-fragment-image-overlays beg end)
18311 (progn
18312 (message "LaTeX fragment images removed from subtree")
18313 (throw 'exit nil))
18314 (setq msg "Creating images for subtree...")))
18315 ((let ((datum (org-element-context)))
18316 (when (memq (org-element-type datum)
18317 '(latex-environment latex-fragment))
18318 (setq beg (org-element-property :begin datum))
18319 (setq end (org-element-property :end datum))
18320 (if (org-remove-latex-fragment-image-overlays beg end)
18321 (progn (message "LaTeX fragment image removed")
18322 (throw 'exit nil))
18323 (setq msg "Creating image...")))))
18325 (org-with-limited-levels
18326 (setq beg (if (org-at-heading-p) (line-beginning-position)
18327 (outline-previous-heading)
18328 (point)))
18329 (setq end (progn (outline-next-heading) (point)))
18330 (if (org-remove-latex-fragment-image-overlays beg end)
18331 (progn
18332 (message "LaTeX fragment images removed from section")
18333 (throw 'exit nil))
18334 (setq msg "Creating images for section...")))))
18335 (let ((file (buffer-file-name (buffer-base-buffer))))
18336 (org-format-latex
18337 (concat org-preview-latex-image-directory "org-ltximg")
18338 beg end
18339 ;; Emacs cannot overlay images from remote hosts. Create
18340 ;; it in `temporary-file-directory' instead.
18341 (if (or (not file) (file-remote-p file))
18342 temporary-file-directory
18343 default-directory)
18344 'overlays msg 'forbuffer org-preview-latex-default-process))
18345 (message (concat msg "done")))))))
18347 (defun org-format-latex
18348 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18349 "Replace LaTeX fragments with links to an image.
18351 The function takes care of creating the replacement image.
18353 Only consider fragments between BEG and END when those are
18354 provided.
18356 When optional argument OVERLAYS is non-nil, display the image on
18357 top of the fragment instead of replacing it.
18359 PROCESSING-TYPE is the conversion method to use, as a symbol.
18361 Some of the options can be changed using the variable
18362 `org-format-latex-options', which see."
18363 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18364 (unless (eq processing-type 'verbatim)
18365 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18366 (cnt 0)
18367 checkdir-flag)
18368 (goto-char (or beg (point-min)))
18369 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18370 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18371 (overlay-recenter (or end (point-max))))
18372 (while (re-search-forward math-regexp end t)
18373 (unless (and overlays
18374 (eq (get-char-property (point) 'org-overlay-type)
18375 'org-latex-overlay))
18376 (let* ((context (org-element-context))
18377 (type (org-element-type context)))
18378 (when (memq type '(latex-environment latex-fragment))
18379 (let ((block-type (eq type 'latex-environment))
18380 (value (org-element-property :value context))
18381 (beg (org-element-property :begin context))
18382 (end (save-excursion
18383 (goto-char (org-element-property :end context))
18384 (skip-chars-backward " \r\t\n")
18385 (point))))
18386 (cond
18387 ((eq processing-type 'mathjax)
18388 ;; Prepare for MathJax processing.
18389 (if (not (string-match "\\`\\$\\$?" value))
18390 (goto-char end)
18391 (delete-region beg end)
18392 (if (string= (match-string 0 value) "$$")
18393 (insert "\\[" (substring value 2 -2) "\\]")
18394 (insert "\\(" (substring value 1 -1) "\\)"))))
18395 ((assq processing-type org-preview-latex-process-alist)
18396 ;; Process to an image.
18397 (cl-incf cnt)
18398 (goto-char beg)
18399 (let* ((processing-info
18400 (cdr (assq processing-type org-preview-latex-process-alist)))
18401 (face (face-at-point))
18402 ;; Get the colors from the face at point.
18404 (let ((color (plist-get org-format-latex-options
18405 :foreground)))
18406 (if (and forbuffer (eq color 'auto))
18407 (face-attribute face :foreground nil 'default)
18408 color)))
18410 (let ((color (plist-get org-format-latex-options
18411 :background)))
18412 (if (and forbuffer (eq color 'auto))
18413 (face-attribute face :background nil 'default)
18414 color)))
18415 (hash (sha1 (prin1-to-string
18416 (list org-format-latex-header
18417 org-latex-default-packages-alist
18418 org-latex-packages-alist
18419 org-format-latex-options
18420 forbuffer value fg bg))))
18421 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18422 (absprefix (expand-file-name prefix dir))
18423 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18424 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18425 (sep (and block-type "\n\n"))
18426 (link (concat sep "[[file:" linkfile "]]" sep))
18427 (options
18428 (org-combine-plists
18429 org-format-latex-options
18430 `(:foreground ,fg :background ,bg))))
18431 (when msg (message msg cnt))
18432 (unless checkdir-flag ; Ensure the directory exists.
18433 (setq checkdir-flag t)
18434 (let ((todir (file-name-directory absprefix)))
18435 (unless (file-directory-p todir)
18436 (make-directory todir t))))
18437 (unless (file-exists-p movefile)
18438 (org-create-formula-image
18439 value movefile options forbuffer processing-type))
18440 (if overlays
18441 (progn
18442 (dolist (o (overlays-in beg end))
18443 (when (eq (overlay-get o 'org-overlay-type)
18444 'org-latex-overlay)
18445 (delete-overlay o)))
18446 (org--format-latex-make-overlay beg end movefile imagetype)
18447 (goto-char end))
18448 (delete-region beg end)
18449 (insert
18450 (org-add-props link
18451 (list 'org-latex-src
18452 (replace-regexp-in-string "\"" "" value)
18453 'org-latex-src-embed-type
18454 (if block-type 'paragraph 'character)))))))
18455 ((eq processing-type 'mathml)
18456 ;; Process to MathML.
18457 (unless (org-format-latex-mathml-available-p)
18458 (user-error "LaTeX to MathML converter not configured"))
18459 (cl-incf cnt)
18460 (when msg (message msg cnt))
18461 (goto-char beg)
18462 (delete-region beg end)
18463 (insert (org-format-latex-as-mathml
18464 value block-type prefix dir)))
18466 (error "Unknown conversion process %s for LaTeX fragments"
18467 processing-type)))))))))))
18469 (defun org-create-math-formula (latex-frag &optional mathml-file)
18470 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18471 Use `org-latex-to-mathml-convert-command'. If the conversion is
18472 sucessful, return the portion between \"<math...> </math>\"
18473 elements otherwise return nil. When MATHML-FILE is specified,
18474 write the results in to that file. When invoked as an
18475 interactive command, prompt for LATEX-FRAG, with initial value
18476 set to the current active region and echo the results for user
18477 inspection."
18478 (interactive (list (let ((frag (when (org-region-active-p)
18479 (buffer-substring-no-properties
18480 (region-beginning) (region-end)))))
18481 (read-string "LaTeX Fragment: " frag nil frag))))
18482 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18483 (let* ((tmp-in-file
18484 (let ((file (file-relative-name
18485 (make-temp-name (expand-file-name "ltxmathml-in")))))
18486 (write-region latex-frag nil file)
18487 file))
18488 (tmp-out-file (file-relative-name
18489 (make-temp-name (expand-file-name "ltxmathml-out"))))
18490 (cmd (format-spec
18491 org-latex-to-mathml-convert-command
18492 `((?j . ,(and org-latex-to-mathml-jar-file
18493 (shell-quote-argument
18494 (expand-file-name
18495 org-latex-to-mathml-jar-file))))
18496 (?I . ,(shell-quote-argument tmp-in-file))
18497 (?i . ,latex-frag)
18498 (?o . ,(shell-quote-argument tmp-out-file)))))
18499 mathml shell-command-output)
18500 (when (called-interactively-p 'any)
18501 (unless (org-format-latex-mathml-available-p)
18502 (user-error "LaTeX to MathML converter not configured")))
18503 (message "Running %s" cmd)
18504 (setq shell-command-output (shell-command-to-string cmd))
18505 (setq mathml
18506 (when (file-readable-p tmp-out-file)
18507 (with-current-buffer (find-file-noselect tmp-out-file t)
18508 (goto-char (point-min))
18509 (when (re-search-forward
18510 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18511 (regexp-quote
18512 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18513 nil t)
18514 (prog1 (match-string 0) (kill-buffer))))))
18515 (cond
18516 (mathml
18517 (setq mathml
18518 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18519 (when mathml-file
18520 (write-region mathml nil mathml-file))
18521 (when (called-interactively-p 'any)
18522 (message mathml)))
18523 ((message "LaTeX to MathML conversion failed")
18524 (message shell-command-output)))
18525 (delete-file tmp-in-file)
18526 (when (file-exists-p tmp-out-file)
18527 (delete-file tmp-out-file))
18528 mathml))
18530 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18531 prefix &optional dir)
18532 "Use `org-create-math-formula' but check local cache first."
18533 (let* ((absprefix (expand-file-name prefix dir))
18534 (print-length nil) (print-level nil)
18535 (formula-id (concat
18536 "formula-"
18537 (sha1
18538 (prin1-to-string
18539 (list latex-frag
18540 org-latex-to-mathml-convert-command)))))
18541 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18542 (formula-cache-dir (file-name-directory formula-cache)))
18544 (unless (file-directory-p formula-cache-dir)
18545 (make-directory formula-cache-dir t))
18547 (unless (file-exists-p formula-cache)
18548 (org-create-math-formula latex-frag formula-cache))
18550 (if (file-exists-p formula-cache)
18551 ;; Successful conversion. Return the link to MathML file.
18552 (org-add-props
18553 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18554 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18555 'org-latex-src-embed-type (if latex-frag-type
18556 'paragraph 'character)))
18557 ;; Failed conversion. Return the LaTeX fragment verbatim
18558 latex-frag)))
18560 (defun org--get-display-dpi ()
18561 "Get the DPI of the display.
18562 The function assumes that the display has the same pixel width in
18563 the horizontal and vertical directions."
18564 (if (display-graphic-p)
18565 (round (/ (display-pixel-height)
18566 (/ (display-mm-height) 25.4)))
18567 (error "Attempt to calculate the dpi of a non-graphic display")))
18569 (defun org-create-formula-image
18570 (string tofile options buffer &optional processing-type)
18571 "Create an image from LaTeX source using external processes.
18573 The LaTeX STRING is saved to a temporary LaTeX file, then
18574 converted to an image file by process PROCESSING-TYPE defined in
18575 `org-preview-latex-process-alist'. A nil value defaults to
18576 `org-preview-latex-default-process'.
18578 The generated image file is eventually moved to TOFILE.
18580 The OPTIONS argument controls the size, foreground color and
18581 background color of the generated image.
18583 When BUFFER non-nil, this function is used for LaTeX previewing.
18584 Otherwise, it is used to deal with LaTeX snippets showed in
18585 a HTML file."
18586 (let* ((processing-type (or processing-type
18587 org-preview-latex-default-process))
18588 (processing-info
18589 (cdr (assq processing-type org-preview-latex-process-alist)))
18590 (programs (plist-get processing-info :programs))
18591 (error-message (or (plist-get processing-info :message) ""))
18592 (use-xcolor (plist-get processing-info :use-xcolor))
18593 (image-input-type (plist-get processing-info :image-input-type))
18594 (image-output-type (plist-get processing-info :image-output-type))
18595 (post-clean (or (plist-get processing-info :post-clean)
18596 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18597 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18598 (latex-header
18599 (or (plist-get processing-info :latex-header)
18600 (org-latex-make-preamble
18601 (org-export-get-environment (org-export-get-backend 'latex))
18602 org-format-latex-header
18603 'snippet)))
18604 (latex-compiler (plist-get processing-info :latex-compiler))
18605 (image-converter (plist-get processing-info :image-converter))
18606 (tmpdir temporary-file-directory)
18607 (texfilebase (make-temp-name
18608 (expand-file-name "orgtex" tmpdir)))
18609 (texfile (concat texfilebase ".tex"))
18610 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18611 '(1.0 . 1.0)))
18612 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18613 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18614 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18615 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18616 "Black"))
18617 (bg (or (plist-get options (if buffer :background :html-background))
18618 "Transparent"))
18619 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18620 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18621 (dolist (program programs)
18622 (org-check-external-command program error-message))
18623 (if use-xcolor
18624 (progn (if (eq fg 'default)
18625 (setq fg (org-latex-color :foreground))
18626 (setq fg (org-latex-color-format fg)))
18627 (if (eq bg 'default)
18628 (setq bg (org-latex-color :background))
18629 (setq bg (org-latex-color-format
18630 (if (string= bg "Transparent") "white" bg))))
18631 (with-temp-file texfile
18632 (insert latex-header)
18633 (insert "\n\\begin{document}\n"
18634 "\\definecolor{fg}{rgb}{" fg "}\n"
18635 "\\definecolor{bg}{rgb}{" bg "}\n"
18636 "\n\\pagecolor{bg}\n"
18637 "\n{\\color{fg}\n"
18638 string
18639 "\n}\n"
18640 "\n\\end{document}\n")))
18641 (if (eq fg 'default)
18642 (setq fg (org-dvipng-color :foreground))
18643 (unless (string= fg "Transparent")
18644 (setq fg (org-dvipng-color-format fg))))
18645 (if (eq bg 'default)
18646 (setq bg (org-dvipng-color :background))
18647 (unless (string= bg "Transparent")
18648 (setq bg (org-dvipng-color-format bg))))
18649 (with-temp-file texfile
18650 (insert latex-header)
18651 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18653 (let* ((err-msg (format "Please adjust `%s' part of \
18654 `org-preview-latex-process-alist'."
18655 processing-type))
18656 (image-input-file
18657 (org-compile-file
18658 texfile latex-compiler image-input-type err-msg log-buf))
18659 (image-output-file
18660 (org-compile-file
18661 image-input-file image-converter image-output-type err-msg log-buf
18662 `((?F . ,(shell-quote-argument fg))
18663 (?B . ,(shell-quote-argument bg))
18664 (?D . ,(shell-quote-argument (format "%s" dpi)))
18665 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18666 (copy-file image-output-file tofile 'replace)
18667 (dolist (e post-clean)
18668 (when (file-exists-p (concat texfilebase e))
18669 (delete-file (concat texfilebase e))))
18670 image-output-file)))
18672 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18673 "Fill a LaTeX header template TPL.
18674 In the template, the following place holders will be recognized:
18676 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18677 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18678 [PACKAGES] \\usepackage statements for PKG
18679 [NO-PACKAGES] do not include PKG
18680 [EXTRA] the string EXTRA
18681 [NO-EXTRA] do not include EXTRA
18683 For backward compatibility, if both the positive and the negative place
18684 holder is missing, the positive one (without the \"NO-\") will be
18685 assumed to be present at the end of the template.
18686 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18687 EXTRA is a string.
18688 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18689 (let (rpl (end ""))
18690 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18691 (setq rpl (if (or (match-end 1) (not def-pkg))
18692 "" (org-latex-packages-to-string def-pkg snippets-p t))
18693 tpl (replace-match rpl t t tpl))
18694 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18696 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18697 (setq rpl (if (or (match-end 1) (not pkg))
18698 "" (org-latex-packages-to-string pkg snippets-p t))
18699 tpl (replace-match rpl t t tpl))
18700 (when pkg (setq end
18701 (concat end "\n"
18702 (org-latex-packages-to-string pkg snippets-p)))))
18704 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18705 (setq rpl (if (or (match-end 1) (not extra))
18706 "" (concat extra "\n"))
18707 tpl (replace-match rpl t t tpl))
18708 (when (and extra (string-match "\\S-" extra))
18709 (setq end (concat end "\n" extra))))
18711 (if (string-match "\\S-" end)
18712 (concat tpl "\n" end)
18713 tpl)))
18715 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18716 "Turn an alist of packages into a string with the \\usepackage macros."
18717 (setq pkg (mapconcat (lambda(p)
18718 (cond
18719 ((stringp p) p)
18720 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18721 (format "%% Package %s omitted" (cadr p)))
18722 ((equal "" (car p))
18723 (format "\\usepackage{%s}" (cadr p)))
18725 (format "\\usepackage[%s]{%s}"
18726 (car p) (cadr p)))))
18728 "\n"))
18729 (if newline (concat pkg "\n") pkg))
18731 (defun org-dvipng-color (attr)
18732 "Return a RGB color specification for dvipng."
18733 (org-dvipng-color-format (face-attribute 'default attr nil)))
18735 (defun org-dvipng-color-format (color-name)
18736 "Convert COLOR-NAME to a RGB color value for dvipng."
18737 (apply #'format "rgb %s %s %s"
18738 (mapcar 'org-normalize-color
18739 (color-values color-name))))
18741 (defun org-latex-color (attr)
18742 "Return a RGB color for the LaTeX color package."
18743 (org-latex-color-format (face-attribute 'default attr nil)))
18745 (defun org-latex-color-format (color-name)
18746 "Convert COLOR-NAME to a RGB color value."
18747 (apply #'format "%s,%s,%s"
18748 (mapcar 'org-normalize-color
18749 (color-values color-name))))
18751 (defun org-normalize-color (value)
18752 "Return string to be used as color value for an RGB component."
18753 (format "%g" (/ value 65535.0)))
18756 ;; Image display
18758 (defvar-local org-inline-image-overlays nil)
18760 (defun org-toggle-inline-images (&optional include-linked)
18761 "Toggle the display of inline images.
18762 INCLUDE-LINKED is passed to `org-display-inline-images'."
18763 (interactive "P")
18764 (if org-inline-image-overlays
18765 (progn
18766 (org-remove-inline-images)
18767 (when (called-interactively-p 'interactive)
18768 (message "Inline image display turned off")))
18769 (org-display-inline-images include-linked)
18770 (when (called-interactively-p 'interactive)
18771 (message (if org-inline-image-overlays
18772 (format "%d images displayed inline"
18773 (length org-inline-image-overlays))
18774 "No images to display inline")))))
18776 (defun org-redisplay-inline-images ()
18777 "Refresh the display of inline images."
18778 (interactive)
18779 (if (not org-inline-image-overlays)
18780 (org-toggle-inline-images)
18781 (org-toggle-inline-images)
18782 (org-toggle-inline-images)))
18784 (defun org-display-inline-images (&optional include-linked refresh beg end)
18785 "Display inline images.
18787 An inline image is a link which follows either of these
18788 conventions:
18790 1. Its path is a file with an extension matching return value
18791 from `image-file-name-regexp' and it has no contents.
18793 2. Its description consists in a single link of the previous
18794 type.
18796 When optional argument INCLUDE-LINKED is non-nil, also links with
18797 a text description part will be inlined. This can be nice for
18798 a quick look at those images, but it does not reflect what
18799 exported files will look like.
18801 When optional argument REFRESH is non-nil, refresh existing
18802 images between BEG and END. This will create new image displays
18803 only if necessary. BEG and END default to the buffer
18804 boundaries."
18805 (interactive "P")
18806 (when (display-graphic-p)
18807 (unless refresh
18808 (org-remove-inline-images)
18809 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18810 (org-with-wide-buffer
18811 (goto-char (or beg (point-min)))
18812 (let* ((case-fold-search t)
18813 (file-extension-re (image-file-name-regexp))
18814 (link-abbrevs (mapcar #'car
18815 (append org-link-abbrev-alist-local
18816 org-link-abbrev-alist)))
18817 ;; Check absolute, relative file names and explicit
18818 ;; "file:" links. Also check link abbreviations since
18819 ;; some might expand to "file" links.
18820 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18821 (if (not link-abbrevs) ""
18822 (format "\\|\\(?:%s:\\)"
18823 (regexp-opt link-abbrevs))))))
18824 (while (re-search-forward file-types-re end t)
18825 (let ((link (save-match-data (org-element-context))))
18826 ;; Check if we're at an inline image, i.e., an image file
18827 ;; link without a description (unless INCLUDE-LINKED is
18828 ;; non-nil).
18829 (when (and (equal "file" (org-element-property :type link))
18830 (or include-linked
18831 (null (org-element-contents link)))
18832 (string-match-p file-extension-re
18833 (org-element-property :path link)))
18834 (let ((file (expand-file-name
18835 (org-link-unescape
18836 (org-element-property :path link)))))
18837 (when (file-exists-p file)
18838 (let ((width
18839 ;; Apply `org-image-actual-width' specifications.
18840 (cond
18841 ((not (image-type-available-p 'imagemagick)) nil)
18842 ((eq org-image-actual-width t) nil)
18843 ((listp org-image-actual-width)
18845 ;; First try to find a width among
18846 ;; attributes associated to the paragraph
18847 ;; containing link.
18848 (let ((paragraph
18849 (let ((e link))
18850 (while (and (setq e (org-element-property
18851 :parent e))
18852 (not (eq (org-element-type e)
18853 'paragraph))))
18854 e)))
18855 (when paragraph
18856 (save-excursion
18857 (goto-char (org-element-property :begin paragraph))
18858 (when
18859 (re-search-forward
18860 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18861 (org-element-property
18862 :post-affiliated paragraph)
18864 (string-to-number (match-string 1))))))
18865 ;; Otherwise, fall-back to provided number.
18866 (car org-image-actual-width)))
18867 ((numberp org-image-actual-width)
18868 org-image-actual-width)))
18869 (old (get-char-property-and-overlay
18870 (org-element-property :begin link)
18871 'org-image-overlay)))
18872 (if (and (car-safe old) refresh)
18873 (image-refresh (overlay-get (cdr old) 'display))
18874 (let ((image (create-image file
18875 (and width 'imagemagick)
18877 :width width)))
18878 (when image
18879 (let ((ov (make-overlay
18880 (org-element-property :begin link)
18881 (progn
18882 (goto-char
18883 (org-element-property :end link))
18884 (skip-chars-backward " \t")
18885 (point)))))
18886 (overlay-put ov 'display image)
18887 (overlay-put ov 'face 'default)
18888 (overlay-put ov 'org-image-overlay t)
18889 (overlay-put
18890 ov 'modification-hooks
18891 (list 'org-display-inline-remove-overlay))
18892 (push ov org-inline-image-overlays)))))))))))))))
18894 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18895 "Remove inline-display overlay if a corresponding region is modified."
18896 (let ((inhibit-modification-hooks t))
18897 (when (and ov after)
18898 (delete ov org-inline-image-overlays)
18899 (delete-overlay ov))))
18901 (defun org-remove-inline-images ()
18902 "Remove inline display of images."
18903 (interactive)
18904 (mapc #'delete-overlay org-inline-image-overlays)
18905 (setq org-inline-image-overlays nil))
18908 ;;; Key bindings
18910 (defun org-remap (map &rest commands)
18911 "In MAP, remap the functions given in COMMANDS.
18912 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18913 (let (new old)
18914 (while commands
18915 (setq old (pop commands) new (pop commands))
18916 (org-defkey map (vector 'remap old) new))))
18918 ;;;; Outline functions that can be remapped in Org
18919 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18920 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18921 (define-key org-mode-map [remap outline-forward-same-level]
18922 #'org-forward-heading-same-level)
18923 (define-key org-mode-map [remap outline-backward-same-level]
18924 #'org-backward-heading-same-level)
18925 (define-key org-mode-map [remap outline-show-branches]
18926 #'org-kill-note-or-show-branches)
18927 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18928 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18929 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18930 (define-key org-mode-map [remap outline-next-visible-heading]
18931 #'org-next-visible-heading)
18932 (define-key org-mode-map [remap outline-previous-visible-heading]
18933 #'org-previous-visible-heading)
18934 (define-key org-mode-map [remap show-children] #'org-show-children)
18936 ;;;; Make `C-c C-x' a prefix key
18937 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18939 ;;;; TAB key with modifiers
18940 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18941 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18942 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18943 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18944 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18946 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18947 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18948 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18950 ;;;; RET key with modifiers
18951 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18952 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18953 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18954 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18955 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18957 ;;;; Cursor keys with modifiers
18958 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18959 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18960 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18961 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18962 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18963 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18964 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18966 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18967 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18968 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18969 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18970 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18971 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18972 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18973 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18974 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18975 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18977 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18978 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18979 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18980 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18982 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18983 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18984 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18985 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18987 ;;;; Babel keys
18988 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18989 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18990 (define-key org-babel-map key def))
18992 ;;;; Extra keys for TTY access.
18994 ;; We only set them when really needed because otherwise the
18995 ;; menus don't show the simple keys
18997 (when (or org-use-extra-keys (not window-system))
18998 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18999 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
19000 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
19001 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
19002 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
19003 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
19004 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
19005 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
19006 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
19007 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
19008 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
19009 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
19010 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
19011 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
19012 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
19013 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
19014 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
19015 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
19016 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
19017 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
19018 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
19020 ;;;; Narrow map
19021 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
19022 (org-defkey narrow-map "b" #'org-narrow-to-block)
19023 (org-defkey narrow-map "e" #'org-narrow-to-element)
19025 ;;;; Remap usual Emacs bindings
19026 (org-remap org-mode-map
19027 'self-insert-command 'org-self-insert-command
19028 'delete-char 'org-delete-char
19029 'delete-backward-char 'org-delete-backward-char
19030 'kill-line 'org-kill-line
19031 'open-line 'org-open-line
19032 'yank 'org-yank
19033 'comment-dwim 'org-comment-dwim
19034 'move-beginning-of-line 'org-beginning-of-line
19035 'move-end-of-line 'org-end-of-line
19036 'forward-paragraph 'org-forward-paragraph
19037 'backward-paragraph 'org-backward-paragraph
19038 'backward-sentence 'org-backward-sentence
19039 'forward-sentence 'org-forward-sentence
19040 'fill-paragraph 'org-fill-paragraph
19041 'delete-indentation 'org-delete-indentation
19042 'transpose-words 'org-transpose-words)
19044 ;;;; All the other keys
19045 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
19046 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
19047 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
19048 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
19049 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
19050 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
19051 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
19052 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
19053 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
19054 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
19055 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
19056 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
19057 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
19058 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
19059 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
19060 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
19061 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
19062 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
19063 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
19064 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
19065 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
19066 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
19067 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19068 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19069 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19070 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19071 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19072 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19073 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19074 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19075 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19076 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19077 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19078 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19079 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19080 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19081 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19082 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19083 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19084 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19085 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19086 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19087 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19088 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19089 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19090 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19091 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19092 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19093 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19094 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19095 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19096 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19097 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19098 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19099 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19100 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19101 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19102 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19103 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19104 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19105 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19106 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19107 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19108 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19109 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19110 (org-defkey org-mode-map (kbd "RET") #'org-return)
19111 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19112 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19113 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19114 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19115 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19116 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19117 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19118 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19119 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19120 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19121 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19122 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19123 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19124 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19125 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19126 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19127 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19128 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19129 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19130 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19131 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19132 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19133 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19135 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19136 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19137 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19139 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19140 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19141 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19142 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19143 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19144 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19145 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19146 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19147 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19148 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19149 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19150 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19151 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19152 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19153 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19154 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19155 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19156 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19157 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19158 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19159 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19160 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19161 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19162 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19163 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19164 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19165 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19166 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19168 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19170 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19172 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19173 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19175 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19178 ;;; Speed commands
19180 (defconst org-speed-commands-default
19182 ("Outline Navigation")
19183 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19184 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19185 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19186 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19187 ("F" . org-next-block)
19188 ("B" . org-previous-block)
19189 ("u" . (org-speed-move-safe 'outline-up-heading))
19190 ("j" . org-goto)
19191 ("g" . (org-refile t))
19192 ("Outline Visibility")
19193 ("c" . org-cycle)
19194 ("C" . org-shifttab)
19195 (" " . org-display-outline-path)
19196 ("s" . org-narrow-to-subtree)
19197 ("=" . org-columns)
19198 ("Outline Structure Editing")
19199 ("U" . org-metaup)
19200 ("D" . org-metadown)
19201 ("r" . org-metaright)
19202 ("l" . org-metaleft)
19203 ("R" . org-shiftmetaright)
19204 ("L" . org-shiftmetaleft)
19205 ("i" . (progn (forward-char 1) (call-interactively
19206 'org-insert-heading-respect-content)))
19207 ("^" . org-sort)
19208 ("w" . org-refile)
19209 ("a" . org-archive-subtree-default-with-confirmation)
19210 ("@" . org-mark-subtree)
19211 ("#" . org-toggle-comment)
19212 ("Clock Commands")
19213 ("I" . org-clock-in)
19214 ("O" . org-clock-out)
19215 ("Meta Data Editing")
19216 ("t" . org-todo)
19217 ("," . (org-priority))
19218 ("0" . (org-priority ?\ ))
19219 ("1" . (org-priority ?A))
19220 ("2" . (org-priority ?B))
19221 ("3" . (org-priority ?C))
19222 (":" . org-set-tags-command)
19223 ("e" . org-set-effort)
19224 ("E" . org-inc-effort)
19225 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19226 (org-entry-put (point) "APPT_WARNTIME" m)))
19227 ("Agenda Views etc")
19228 ("v" . org-agenda)
19229 ("/" . org-sparse-tree)
19230 ("Misc")
19231 ("o" . org-open-at-point)
19232 ("?" . org-speed-command-help)
19233 ("<" . (org-agenda-set-restriction-lock 'subtree))
19234 (">" . (org-agenda-remove-restriction-lock))
19236 "The default speed commands.")
19238 (defun org-print-speed-command (e)
19239 (if (> (length (car e)) 1)
19240 (progn
19241 (princ "\n")
19242 (princ (car e))
19243 (princ "\n")
19244 (princ (make-string (length (car e)) ?-))
19245 (princ "\n"))
19246 (princ (car e))
19247 (princ " ")
19248 (if (symbolp (cdr e))
19249 (princ (symbol-name (cdr e)))
19250 (prin1 (cdr e)))
19251 (princ "\n")))
19253 (defun org-speed-command-help ()
19254 "Show the available speed commands."
19255 (interactive)
19256 (if (not org-use-speed-commands)
19257 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19258 (with-output-to-temp-buffer "*Help*"
19259 (princ "User-defined Speed commands\n===========================\n")
19260 (mapc #'org-print-speed-command org-speed-commands-user)
19261 (princ "\n")
19262 (princ "Built-in Speed commands\n=======================\n")
19263 (mapc #'org-print-speed-command org-speed-commands-default))
19264 (with-current-buffer "*Help*"
19265 (setq truncate-lines t))))
19267 (defun org-speed-move-safe (cmd)
19268 "Execute CMD, but make sure that the cursor always ends up in a headline.
19269 If not, return to the original position and throw an error."
19270 (interactive)
19271 (let ((pos (point)))
19272 (call-interactively cmd)
19273 (unless (and (bolp) (org-at-heading-p))
19274 (goto-char pos)
19275 (error "Boundary reached while executing %s" cmd))))
19277 (defvar org-self-insert-command-undo-counter 0)
19279 (defvar org-table-auto-blank-field) ; defined in org-table.el
19280 (defvar org-speed-command nil)
19282 (defun org-speed-command-activate (keys)
19283 "Hook for activating single-letter speed commands.
19284 `org-speed-commands-default' specifies a minimal command set.
19285 Use `org-speed-commands-user' for further customization."
19286 (when (or (and (bolp) (looking-at org-outline-regexp))
19287 (and (functionp org-use-speed-commands)
19288 (funcall org-use-speed-commands)))
19289 (cdr (assoc keys (append org-speed-commands-user
19290 org-speed-commands-default)))))
19292 (defun org-babel-speed-command-activate (keys)
19293 "Hook for activating single-letter code block commands."
19294 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19295 (cdr (assoc keys org-babel-key-bindings))))
19297 (defcustom org-speed-command-hook
19298 '(org-speed-command-activate org-babel-speed-command-activate)
19299 "Hook for activating speed commands at strategic locations.
19300 Hook functions are called in sequence until a valid handler is
19301 found.
19303 Each hook takes a single argument, a user-pressed command key
19304 which is also a `self-insert-command' from the global map.
19306 Within the hook, examine the cursor position and the command key
19307 and return nil or a valid handler as appropriate. Handler could
19308 be one of an interactive command, a function, or a form.
19310 Set `org-use-speed-commands' to non-nil value to enable this
19311 hook. The default setting is `org-speed-command-activate'."
19312 :group 'org-structure
19313 :version "24.1"
19314 :type 'hook)
19316 (defun org-self-insert-command (N)
19317 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19318 If the cursor is in a table looking at whitespace, the whitespace is
19319 overwritten, and the table is not marked as requiring realignment."
19320 (interactive "p")
19321 (org-check-before-invisible-edit 'insert)
19322 (cond
19323 ((and org-use-speed-commands
19324 (let ((kv (this-command-keys-vector)))
19325 (setq org-speed-command
19326 (run-hook-with-args-until-success
19327 'org-speed-command-hook
19328 (make-string 1 (aref kv (1- (length kv))))))))
19329 (cond
19330 ((commandp org-speed-command)
19331 (setq this-command org-speed-command)
19332 (call-interactively org-speed-command))
19333 ((functionp org-speed-command)
19334 (funcall org-speed-command))
19335 ((and org-speed-command (listp org-speed-command))
19336 (eval org-speed-command))
19337 (t (let (org-use-speed-commands)
19338 (call-interactively 'org-self-insert-command)))))
19339 ((and
19340 (= N 1)
19341 (not (org-region-active-p))
19342 (org-at-table-p)
19343 (progn
19344 ;; Check if we blank the field, and if that triggers align.
19345 (and (featurep 'org-table)
19346 org-table-auto-blank-field
19347 (memq last-command
19348 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19349 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19350 ;; Got extra space, this field does not determine
19351 ;; column width.
19352 (let (org-table-may-need-update) (org-table-blank-field))
19353 ;; No extra space, this field may determine column
19354 ;; width.
19355 (org-table-blank-field)))
19357 (looking-at "[^|\n]* |"))
19358 ;; There is room for insertion without re-aligning the table.
19359 (self-insert-command N)
19360 (org-table-with-shrunk-field
19361 (save-excursion
19362 (skip-chars-forward "^|")
19363 ;; Do not delete last space, which is
19364 ;; `org-table-separator-space', but the regular space before
19365 ;; it.
19366 (delete-region (- (point) 2) (1- (point))))))
19368 (setq org-table-may-need-update t)
19369 (self-insert-command N)
19370 (org-fix-tags-on-the-fly)
19371 (when org-self-insert-cluster-for-undo
19372 (if (not (eq last-command 'org-self-insert-command))
19373 (setq org-self-insert-command-undo-counter 1)
19374 (if (>= org-self-insert-command-undo-counter 20)
19375 (setq org-self-insert-command-undo-counter 1)
19376 (and (> org-self-insert-command-undo-counter 0)
19377 buffer-undo-list (listp buffer-undo-list)
19378 (not (cadr buffer-undo-list)) ; remove nil entry
19379 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19380 (setq org-self-insert-command-undo-counter
19381 (1+ org-self-insert-command-undo-counter))))))))
19383 (defun org-check-before-invisible-edit (kind)
19384 "Check is editing if kind KIND would be dangerous with invisible text around.
19385 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19386 ;; First, try to get out of here as quickly as possible, to reduce overhead
19387 (when (and org-catch-invisible-edits
19388 (or (not (boundp 'visible-mode)) (not visible-mode))
19389 (or (get-char-property (point) 'invisible)
19390 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19391 ;; OK, we need to take a closer look. Do not consider
19392 ;; invisibility obtained through text properties (e.g., link
19393 ;; fontification), as it cannot be toggled.
19394 (let* ((invisible-at-point
19395 (pcase (get-char-property-and-overlay (point) 'invisible)
19396 (`(,_ . ,(and (pred overlayp) o)) o)))
19397 ;; Assume that point cannot land in the middle of an
19398 ;; overlay, or between two overlays.
19399 (invisible-before-point
19400 (and (not invisible-at-point)
19401 (not (bobp))
19402 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19403 (`(,_ . ,(and (pred overlayp) o)) o))))
19404 (border-and-ok-direction
19406 ;; Check if we are acting predictably before invisible
19407 ;; text.
19408 (and invisible-at-point
19409 (memq kind '(insert delete-backward)))
19410 ;; Check if we are acting predictably after invisible text
19411 ;; This works not well, and I have turned it off. It seems
19412 ;; better to always show and stop after invisible text.
19413 ;; (and (not invisible-at-point) invisible-before-point
19414 ;; (memq kind '(insert delete)))
19416 (when (or invisible-at-point invisible-before-point)
19417 (when (eq org-catch-invisible-edits 'error)
19418 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19419 (if (and org-custom-properties-overlays
19420 (y-or-n-p "Display invisible properties in this buffer? "))
19421 (org-toggle-custom-properties-visibility)
19422 ;; Make the area visible
19423 (save-excursion
19424 (when invisible-before-point
19425 (goto-char
19426 (previous-single-char-property-change (point) 'invisible)))
19427 ;; Remove whatever overlay is currently making yet-to-be
19428 ;; edited text invisible. Also remove nested invisibility
19429 ;; related overlays.
19430 (delete-overlay (or invisible-at-point invisible-before-point))
19431 (let ((origin (if invisible-at-point (point) (1- (point)))))
19432 (while (pcase (get-char-property-and-overlay origin 'invisible)
19433 (`(,_ . ,(and (pred overlayp) o))
19434 (delete-overlay o)
19435 t)))))
19436 (cond
19437 ((eq org-catch-invisible-edits 'show)
19438 ;; That's it, we do the edit after showing
19439 (message
19440 "Unfolding invisible region around point before editing")
19441 (sit-for 1))
19442 ((and (eq org-catch-invisible-edits 'smart)
19443 border-and-ok-direction)
19444 (message "Unfolding invisible region around point before editing"))
19446 ;; Don't do the edit, make the user repeat it in full visibility
19447 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19449 (defun org-fix-tags-on-the-fly ()
19450 "Align tags in headline at point.
19451 Unlike to `org-set-tags', it ignores region and sorting."
19452 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19453 (org-at-heading-p))
19454 (let ((org-ignore-region t)
19455 (org-tags-sort-function nil))
19456 (org-set-tags nil t))))
19458 (defun org-delete-backward-char (N)
19459 "Like `delete-backward-char', insert whitespace at field end in tables.
19460 When deleting backwards, in tables this function will insert whitespace in
19461 front of the next \"|\" separator, to keep the table aligned. The table will
19462 still be marked for re-alignment if the field did fill the entire column,
19463 because, in this case the deletion might narrow the column."
19464 (interactive "p")
19465 (save-match-data
19466 (org-check-before-invisible-edit 'delete-backward)
19467 (if (and (= N 1)
19468 (not overwrite-mode)
19469 (not (org-region-active-p))
19470 (not (eq (char-before) ?|))
19471 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19472 (looking-at-p ".*?|")
19473 (org-at-table-p))
19474 (progn (forward-char -1) (org-delete-char 1))
19475 (backward-delete-char N)
19476 (org-fix-tags-on-the-fly))))
19478 (defun org-delete-char (N)
19479 "Like `delete-char', but insert whitespace at field end in tables.
19480 When deleting characters, in tables this function will insert whitespace in
19481 front of the next \"|\" separator, to keep the table aligned. The table will
19482 still be marked for re-alignment if the field did fill the entire column,
19483 because, in this case the deletion might narrow the column."
19484 (interactive "p")
19485 (save-match-data
19486 (org-check-before-invisible-edit 'delete)
19487 (cond
19488 ((or (/= N 1)
19489 (eq (char-after) ?|)
19490 (save-excursion (skip-chars-backward " \t") (bolp))
19491 (not (org-at-table-p)))
19492 (delete-char N)
19493 (org-fix-tags-on-the-fly))
19494 ((looking-at ".\\(.*?\\)|")
19495 (let* ((update? org-table-may-need-update)
19496 (noalign (looking-at-p ".*? |")))
19497 (delete-char 1)
19498 (org-table-with-shrunk-field
19499 (save-excursion
19500 ;; Last space is `org-table-separator-space', so insert
19501 ;; a regular one before it instead.
19502 (goto-char (- (match-end 0) 2))
19503 (insert " ")))
19504 ;; If there were two spaces at the end, this field does not
19505 ;; determine the width of the column.
19506 (when noalign (setq org-table-may-need-update update?))))
19508 (delete-char N)))))
19510 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19511 (put 'org-self-insert-command 'delete-selection
19512 (lambda ()
19513 (not (run-hook-with-args-until-success
19514 'self-insert-uses-region-functions))))
19515 (put 'orgtbl-self-insert-command 'delete-selection
19516 (lambda ()
19517 (not (run-hook-with-args-until-success
19518 'self-insert-uses-region-functions))))
19519 (put 'org-delete-char 'delete-selection 'supersede)
19520 (put 'org-delete-backward-char 'delete-selection 'supersede)
19521 (put 'org-yank 'delete-selection 'yank)
19523 ;; Make `flyspell-mode' delay after some commands
19524 (put 'org-self-insert-command 'flyspell-delayed t)
19525 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19526 (put 'org-delete-char 'flyspell-delayed t)
19527 (put 'org-delete-backward-char 'flyspell-delayed t)
19529 ;; Make pabbrev-mode expand after Org mode commands
19530 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19531 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19533 (defun org-transpose-words ()
19534 "Transpose words for Org.
19535 This uses the `org-mode-transpose-word-syntax-table' syntax
19536 table, which interprets characters in `org-emphasis-alist' as
19537 word constituents."
19538 (interactive)
19539 (with-syntax-table org-mode-transpose-word-syntax-table
19540 (call-interactively 'transpose-words)))
19542 (defvar org-ctrl-c-ctrl-c-hook nil
19543 "Hook for functions attaching themselves to `C-c C-c'.
19545 This can be used to add additional functionality to the C-c C-c
19546 key which executes context-dependent commands. This hook is run
19547 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19548 run after the last test.
19550 Each function will be called with no arguments. The function
19551 must check if the context is appropriate for it to act. If yes,
19552 it should do its thing and then return a non-nil value. If the
19553 context is wrong, just do nothing and return nil.")
19555 (defvar org-ctrl-c-ctrl-c-final-hook nil
19556 "Hook for functions attaching themselves to `C-c C-c'.
19558 This can be used to add additional functionality to the C-c C-c
19559 key which executes context-dependent commands. This hook is run
19560 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19561 before the first test.
19563 Each function will be called with no arguments. The function
19564 must check if the context is appropriate for it to act. If yes,
19565 it should do its thing and then return a non-nil value. If the
19566 context is wrong, just do nothing and return nil.")
19568 (defvar org-tab-first-hook nil
19569 "Hook for functions to attach themselves to TAB.
19570 See `org-ctrl-c-ctrl-c-hook' for more information.
19571 This hook runs as the first action when TAB is pressed, even before
19572 `org-cycle' messes around with the `outline-regexp' to cater for
19573 inline tasks and plain list item folding.
19574 If any function in this hook returns t, any other actions that
19575 would have been caused by TAB (such as table field motion or visibility
19576 cycling) will not occur.")
19578 (defvar org-tab-after-check-for-table-hook nil
19579 "Hook for functions to attach themselves to TAB.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.
19581 This hook runs after it has been established that the cursor is not in a
19582 table, but before checking if the cursor is in a headline or if global cycling
19583 should be done.
19584 If any function in this hook returns t, not other actions like visibility
19585 cycling will be done.")
19587 (defvar org-tab-after-check-for-cycling-hook nil
19588 "Hook for functions to attach themselves to TAB.
19589 See `org-ctrl-c-ctrl-c-hook' for more information.
19590 This hook runs after it has been established that not table field motion and
19591 not visibility should be done because of current context. This is probably
19592 the place where a package like yasnippets can hook in.")
19594 (defvar org-tab-before-tab-emulation-hook nil
19595 "Hook for functions to attach themselves to TAB.
19596 See `org-ctrl-c-ctrl-c-hook' for more information.
19597 This hook runs after every other options for TAB have been exhausted, but
19598 before indentation and \t insertion takes place.")
19600 (defvar org-metaleft-hook nil
19601 "Hook for functions attaching themselves to `M-left'.
19602 See `org-ctrl-c-ctrl-c-hook' for more information.")
19603 (defvar org-metaright-hook nil
19604 "Hook for functions attaching themselves to `M-right'.
19605 See `org-ctrl-c-ctrl-c-hook' for more information.")
19606 (defvar org-metaup-hook nil
19607 "Hook for functions attaching themselves to `M-up'.
19608 See `org-ctrl-c-ctrl-c-hook' for more information.")
19609 (defvar org-metadown-hook nil
19610 "Hook for functions attaching themselves to `M-down'.
19611 See `org-ctrl-c-ctrl-c-hook' for more information.")
19612 (defvar org-shiftmetaleft-hook nil
19613 "Hook for functions attaching themselves to `M-S-left'.
19614 See `org-ctrl-c-ctrl-c-hook' for more information.")
19615 (defvar org-shiftmetaright-hook nil
19616 "Hook for functions attaching themselves to `M-S-right'.
19617 See `org-ctrl-c-ctrl-c-hook' for more information.")
19618 (defvar org-shiftmetaup-hook nil
19619 "Hook for functions attaching themselves to `M-S-up'.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.")
19621 (defvar org-shiftmetadown-hook nil
19622 "Hook for functions attaching themselves to `M-S-down'.
19623 See `org-ctrl-c-ctrl-c-hook' for more information.")
19624 (defvar org-metareturn-hook nil
19625 "Hook for functions attaching themselves to `M-RET'.
19626 See `org-ctrl-c-ctrl-c-hook' for more information.")
19627 (defvar org-shiftup-hook nil
19628 "Hook for functions attaching themselves to `S-up'.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.")
19630 (defvar org-shiftup-final-hook nil
19631 "Hook for functions attaching themselves to `S-up'.
19632 This one runs after all other options except shift-select have been excluded.
19633 See `org-ctrl-c-ctrl-c-hook' for more information.")
19634 (defvar org-shiftdown-hook nil
19635 "Hook for functions attaching themselves to `S-down'.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.")
19637 (defvar org-shiftdown-final-hook nil
19638 "Hook for functions attaching themselves to `S-down'.
19639 This one runs after all other options except shift-select have been excluded.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.")
19641 (defvar org-shiftleft-hook nil
19642 "Hook for functions attaching themselves to `S-left'.
19643 See `org-ctrl-c-ctrl-c-hook' for more information.")
19644 (defvar org-shiftleft-final-hook nil
19645 "Hook for functions attaching themselves to `S-left'.
19646 This one runs after all other options except shift-select have been excluded.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.")
19648 (defvar org-shiftright-hook nil
19649 "Hook for functions attaching themselves to `S-right'.
19650 See `org-ctrl-c-ctrl-c-hook' for more information.")
19651 (defvar org-shiftright-final-hook nil
19652 "Hook for functions attaching themselves to `S-right'.
19653 This one runs after all other options except shift-select have been excluded.
19654 See `org-ctrl-c-ctrl-c-hook' for more information.")
19656 (defun org-modifier-cursor-error ()
19657 "Throw an error, a modified cursor command was applied in wrong context."
19658 (user-error "This command is active in special context like tables, headlines or items"))
19660 (defun org-shiftselect-error ()
19661 "Throw an error because Shift-Cursor command was applied in wrong context."
19662 (if (and (boundp 'shift-select-mode) shift-select-mode)
19663 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19664 (user-error "This command works only in special context like headlines or timestamps")))
19666 (defun org-call-for-shift-select (cmd)
19667 (let ((this-command-keys-shift-translated t))
19668 (call-interactively cmd)))
19670 (defun org-shifttab (&optional arg)
19671 "Global visibility cycling or move to previous table field.
19672 Call `org-table-previous-field' within a table.
19673 When ARG is nil, cycle globally through visibility states.
19674 When ARG is a numeric prefix, show contents of this level."
19675 (interactive "P")
19676 (cond
19677 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19678 ((integerp arg)
19679 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19680 (message "Content view to level: %d" arg)
19681 (org-content (prefix-numeric-value arg2))
19682 (org-cycle-show-empty-lines t)
19683 (setq org-cycle-global-status 'overview)))
19684 (t (call-interactively 'org-global-cycle))))
19686 (defun org-shiftmetaleft ()
19687 "Promote subtree or delete table column.
19688 Calls `org-promote-subtree', `org-outdent-item-tree', or
19689 `org-table-delete-column', depending on context. See the
19690 individual commands for more information."
19691 (interactive)
19692 (cond
19693 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19694 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19695 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19696 ((if (not (org-region-active-p)) (org-at-item-p)
19697 (save-excursion (goto-char (region-beginning))
19698 (org-at-item-p)))
19699 (call-interactively 'org-outdent-item-tree))
19700 (t (org-modifier-cursor-error))))
19702 (defun org-shiftmetaright ()
19703 "Demote subtree or insert table column.
19704 Calls `org-demote-subtree', `org-indent-item-tree', or
19705 `org-table-insert-column', depending on context. See the
19706 individual commands for more information."
19707 (interactive)
19708 (cond
19709 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19710 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19711 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19712 ((if (not (org-region-active-p)) (org-at-item-p)
19713 (save-excursion (goto-char (region-beginning))
19714 (org-at-item-p)))
19715 (call-interactively 'org-indent-item-tree))
19716 (t (org-modifier-cursor-error))))
19718 (defun org-shiftmetaup (&optional _arg)
19719 "Drag the line at point up.
19720 In a table, kill the current row.
19721 On a clock timestamp, update the value of the timestamp like `S-<up>'
19722 but also adjust the previous clocked item in the clock history.
19723 Everywhere else, drag the line at point up."
19724 (interactive "P")
19725 (cond
19726 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19727 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19728 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19729 (call-interactively 'org-timestamp-up)))
19730 (t (call-interactively 'org-drag-line-backward))))
19732 (defun org-shiftmetadown (&optional _arg)
19733 "Drag the line at point down.
19734 In a table, insert an empty row at the current line.
19735 On a clock timestamp, update the value of the timestamp like `S-<down>'
19736 but also adjust the previous clocked item in the clock history.
19737 Everywhere else, drag the line at point down."
19738 (interactive "P")
19739 (cond
19740 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19741 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19742 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19743 (call-interactively 'org-timestamp-down)))
19744 (t (call-interactively 'org-drag-line-forward))))
19746 (defsubst org-hidden-tree-error ()
19747 (user-error
19748 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19750 (defun org-metaleft (&optional _arg)
19751 "Promote heading, list item at point or move table column left.
19753 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19754 depending on context. With no specific context, calls the Emacs
19755 default `backward-word'. See the individual commands for more
19756 information.
19758 This function runs the hook `org-metaleft-hook' as a first step,
19759 and returns at first non-nil value."
19760 (interactive "P")
19761 (cond
19762 ((run-hook-with-args-until-success 'org-metaleft-hook))
19763 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19764 ((org-with-limited-levels
19765 (or (org-at-heading-p)
19766 (and (org-region-active-p)
19767 (save-excursion
19768 (goto-char (region-beginning))
19769 (org-at-heading-p)))))
19770 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19771 (call-interactively 'org-do-promote))
19772 ;; At an inline task.
19773 ((org-at-heading-p)
19774 (call-interactively 'org-inlinetask-promote))
19775 ((or (org-at-item-p)
19776 (and (org-region-active-p)
19777 (save-excursion
19778 (goto-char (region-beginning))
19779 (org-at-item-p))))
19780 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19781 (call-interactively 'org-outdent-item))
19782 (t (call-interactively 'backward-word))))
19784 (defun org-metaright (&optional _arg)
19785 "Demote heading, list item at point or move table column right.
19787 In front of a drawer or a block keyword, indent it correctly.
19789 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19790 `org-indent-drawer' or `org-indent-block' depending on context.
19791 With no specific context, calls the Emacs default `forward-word'.
19792 See the individual commands for more information.
19794 This function runs the hook `org-metaright-hook' as a first step,
19795 and returns at first non-nil value."
19796 (interactive "P")
19797 (cond
19798 ((run-hook-with-args-until-success 'org-metaright-hook))
19799 ((org-at-table-p) (call-interactively 'org-table-move-column))
19800 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19801 ((org-at-block-p) (call-interactively 'org-indent-block))
19802 ((org-with-limited-levels
19803 (or (org-at-heading-p)
19804 (and (org-region-active-p)
19805 (save-excursion
19806 (goto-char (region-beginning))
19807 (org-at-heading-p)))))
19808 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19809 (call-interactively 'org-do-demote))
19810 ;; At an inline task.
19811 ((org-at-heading-p)
19812 (call-interactively 'org-inlinetask-demote))
19813 ((or (org-at-item-p)
19814 (and (org-region-active-p)
19815 (save-excursion
19816 (goto-char (region-beginning))
19817 (org-at-item-p))))
19818 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19819 (call-interactively 'org-indent-item))
19820 (t (call-interactively 'forward-word))))
19822 (defun org-check-for-hidden (what)
19823 "Check if there are hidden headlines/items in the current visual line.
19824 WHAT can be either `headlines' or `items'. If the current line is
19825 an outline or item heading and it has a folded subtree below it,
19826 this function returns t, nil otherwise."
19827 (let ((re (cond
19828 ((eq what 'headlines) org-outline-regexp-bol)
19829 ((eq what 'items) (org-item-beginning-re))
19830 (t (error "This should not happen"))))
19831 beg end)
19832 (save-excursion
19833 (catch 'exit
19834 (unless (org-region-active-p)
19835 (setq beg (point-at-bol))
19836 (beginning-of-line 2)
19837 (while (and (not (eobp)) ;; this is like `next-line'
19838 (get-char-property (1- (point)) 'invisible))
19839 (beginning-of-line 2))
19840 (setq end (point))
19841 (goto-char beg)
19842 (goto-char (point-at-eol))
19843 (setq end (max end (point)))
19844 (while (re-search-forward re end t)
19845 (when (get-char-property (match-beginning 0) 'invisible)
19846 (throw 'exit t))))
19847 nil))))
19849 (defun org-metaup (&optional _arg)
19850 "Move subtree up or move table row up.
19851 Calls `org-move-subtree-up' or `org-table-move-row' or
19852 `org-move-item-up', depending on context. See the individual commands
19853 for more information."
19854 (interactive "P")
19855 (cond
19856 ((run-hook-with-args-until-success 'org-metaup-hook))
19857 ((org-region-active-p)
19858 (let* ((a (min (region-beginning) (region-end)))
19859 (b (1- (max (region-beginning) (region-end))))
19860 (c (save-excursion (goto-char a)
19861 (move-beginning-of-line 0)))
19862 (d (save-excursion (goto-char a)
19863 (move-end-of-line 0) (point))))
19864 (transpose-regions a b c d)
19865 (goto-char c)))
19866 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19867 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19868 ((org-at-item-p) (call-interactively 'org-move-item-up))
19869 (t (org-drag-element-backward))))
19871 (defun org-metadown (&optional _arg)
19872 "Move subtree down or move table row down.
19873 Calls `org-move-subtree-down' or `org-table-move-row' or
19874 `org-move-item-down', depending on context. See the individual
19875 commands for more information."
19876 (interactive "P")
19877 (cond
19878 ((run-hook-with-args-until-success 'org-metadown-hook))
19879 ((org-region-active-p)
19880 (let* ((a (min (region-beginning) (region-end)))
19881 (b (max (region-beginning) (region-end)))
19882 (c (save-excursion (goto-char b)
19883 (move-beginning-of-line 1)))
19884 (d (save-excursion (goto-char b)
19885 (move-end-of-line 1) (1+ (point)))))
19886 (transpose-regions a b c d)
19887 (goto-char d)))
19888 ((org-at-table-p) (call-interactively 'org-table-move-row))
19889 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19890 ((org-at-item-p) (call-interactively 'org-move-item-down))
19891 (t (org-drag-element-forward))))
19893 (defun org-shiftup (&optional arg)
19894 "Increase item in timestamp or increase priority of current headline.
19895 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19896 depending on context. See the individual commands for more information."
19897 (interactive "P")
19898 (cond
19899 ((run-hook-with-args-until-success 'org-shiftup-hook))
19900 ((and org-support-shift-select (org-region-active-p))
19901 (org-call-for-shift-select 'previous-line))
19902 ((org-at-timestamp-p 'lax)
19903 (call-interactively (if org-edit-timestamp-down-means-later
19904 'org-timestamp-down 'org-timestamp-up)))
19905 ((and (not (eq org-support-shift-select 'always))
19906 org-enable-priority-commands
19907 (org-at-heading-p))
19908 (call-interactively 'org-priority-up))
19909 ((and (not org-support-shift-select) (org-at-item-p))
19910 (call-interactively 'org-previous-item))
19911 ((org-clocktable-try-shift 'up arg))
19912 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19913 (org-support-shift-select
19914 (org-call-for-shift-select 'previous-line))
19915 (t (org-shiftselect-error))))
19917 (defun org-shiftdown (&optional arg)
19918 "Decrease item in timestamp or decrease priority of current headline.
19919 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19920 depending on context. See the individual commands for more information."
19921 (interactive "P")
19922 (cond
19923 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19924 ((and org-support-shift-select (org-region-active-p))
19925 (org-call-for-shift-select 'next-line))
19926 ((org-at-timestamp-p 'lax)
19927 (call-interactively (if org-edit-timestamp-down-means-later
19928 'org-timestamp-up 'org-timestamp-down)))
19929 ((and (not (eq org-support-shift-select 'always))
19930 org-enable-priority-commands
19931 (org-at-heading-p))
19932 (call-interactively 'org-priority-down))
19933 ((and (not org-support-shift-select) (org-at-item-p))
19934 (call-interactively 'org-next-item))
19935 ((org-clocktable-try-shift 'down arg))
19936 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19937 (org-support-shift-select
19938 (org-call-for-shift-select 'next-line))
19939 (t (org-shiftselect-error))))
19941 (defun org-shiftright (&optional arg)
19942 "Cycle the thing at point or in the current line, depending on context.
19943 Depending on context, this does one of the following:
19945 - switch a timestamp at point one day into the future
19946 - on a headline, switch to the next TODO keyword.
19947 - on an item, switch entire list to the next bullet type
19948 - on a property line, switch to the next allowed value
19949 - on a clocktable definition line, move time block into the future"
19950 (interactive "P")
19951 (cond
19952 ((run-hook-with-args-until-success 'org-shiftright-hook))
19953 ((and org-support-shift-select (org-region-active-p))
19954 (org-call-for-shift-select 'forward-char))
19955 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19956 ((and (not (eq org-support-shift-select 'always))
19957 (org-at-heading-p))
19958 (let ((org-inhibit-logging
19959 (not org-treat-S-cursor-todo-selection-as-state-change))
19960 (org-inhibit-blocking
19961 (not org-treat-S-cursor-todo-selection-as-state-change)))
19962 (org-call-with-arg 'org-todo 'right)))
19963 ((or (and org-support-shift-select
19964 (not (eq org-support-shift-select 'always))
19965 (org-at-item-bullet-p))
19966 (and (not org-support-shift-select) (org-at-item-p)))
19967 (org-call-with-arg 'org-cycle-list-bullet nil))
19968 ((and (not (eq org-support-shift-select 'always))
19969 (org-at-property-p))
19970 (call-interactively 'org-property-next-allowed-value))
19971 ((org-clocktable-try-shift 'right arg))
19972 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19973 (org-support-shift-select
19974 (org-call-for-shift-select 'forward-char))
19975 (t (org-shiftselect-error))))
19977 (defun org-shiftleft (&optional arg)
19978 "Cycle the thing at point or in the current line, depending on context.
19979 Depending on context, this does one of the following:
19981 - switch a timestamp at point one day into the past
19982 - on a headline, switch to the previous TODO keyword.
19983 - on an item, switch entire list to the previous bullet type
19984 - on a property line, switch to the previous allowed value
19985 - on a clocktable definition line, move time block into the past"
19986 (interactive "P")
19987 (cond
19988 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19989 ((and org-support-shift-select (org-region-active-p))
19990 (org-call-for-shift-select 'backward-char))
19991 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19992 ((and (not (eq org-support-shift-select 'always))
19993 (org-at-heading-p))
19994 (let ((org-inhibit-logging
19995 (not org-treat-S-cursor-todo-selection-as-state-change))
19996 (org-inhibit-blocking
19997 (not org-treat-S-cursor-todo-selection-as-state-change)))
19998 (org-call-with-arg 'org-todo 'left)))
19999 ((or (and org-support-shift-select
20000 (not (eq org-support-shift-select 'always))
20001 (org-at-item-bullet-p))
20002 (and (not org-support-shift-select) (org-at-item-p)))
20003 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20004 ((and (not (eq org-support-shift-select 'always))
20005 (org-at-property-p))
20006 (call-interactively 'org-property-previous-allowed-value))
20007 ((org-clocktable-try-shift 'left arg))
20008 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20009 (org-support-shift-select
20010 (org-call-for-shift-select 'backward-char))
20011 (t (org-shiftselect-error))))
20013 (defun org-shiftcontrolright ()
20014 "Switch to next TODO set."
20015 (interactive)
20016 (cond
20017 ((and org-support-shift-select (org-region-active-p))
20018 (org-call-for-shift-select 'forward-word))
20019 ((and (not (eq org-support-shift-select 'always))
20020 (org-at-heading-p))
20021 (org-call-with-arg 'org-todo 'nextset))
20022 (org-support-shift-select
20023 (org-call-for-shift-select 'forward-word))
20024 (t (org-shiftselect-error))))
20026 (defun org-shiftcontrolleft ()
20027 "Switch to previous TODO set."
20028 (interactive)
20029 (cond
20030 ((and org-support-shift-select (org-region-active-p))
20031 (org-call-for-shift-select 'backward-word))
20032 ((and (not (eq org-support-shift-select 'always))
20033 (org-at-heading-p))
20034 (org-call-with-arg 'org-todo 'previousset))
20035 (org-support-shift-select
20036 (org-call-for-shift-select 'backward-word))
20037 (t (org-shiftselect-error))))
20039 (defun org-shiftcontrolup (&optional n)
20040 "Change timestamps synchronously up in CLOCK log lines.
20041 Optional argument N tells to change by that many units."
20042 (interactive "P")
20043 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20044 (let (org-support-shift-select)
20045 (org-clock-timestamps-up n))
20046 (user-error "Not at a clock log")))
20048 (defun org-shiftcontroldown (&optional n)
20049 "Change timestamps synchronously down in CLOCK log lines.
20050 Optional argument N tells to change by that many units."
20051 (interactive "P")
20052 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20053 (let (org-support-shift-select)
20054 (org-clock-timestamps-down n))
20055 (user-error "Not at a clock log")))
20057 (defun org-increase-number-at-point (&optional inc)
20058 "Increment the number at point.
20059 With an optional prefix numeric argument INC, increment using
20060 this numeric value."
20061 (interactive "p")
20062 (if (not (number-at-point))
20063 (user-error "Not on a number")
20064 (unless inc (setq inc 1))
20065 (let ((pos (point))
20066 (beg (skip-chars-backward "-+^/*0-9eE."))
20067 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20068 (setq nap (buffer-substring-no-properties
20069 (+ pos beg) (+ pos beg end)))
20070 (delete-region (+ pos beg) (+ pos beg end))
20071 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20072 (when (org-at-table-p)
20073 (org-table-align)
20074 (org-table-end-of-field 1))))
20076 (defun org-decrease-number-at-point (&optional inc)
20077 "Decrement the number at point.
20078 With an optional prefix numeric argument INC, decrement using
20079 this numeric value."
20080 (interactive "p")
20081 (org-increase-number-at-point (- (or inc 1))))
20083 (defun org-ctrl-c-ret ()
20084 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20085 (interactive)
20086 (cond
20087 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20088 (t (call-interactively 'org-insert-heading))))
20090 (defun org-find-visible ()
20091 (let ((s (point)))
20092 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20093 (get-char-property s 'invisible)))
20095 (defun org-find-invisible ()
20096 (let ((s (point)))
20097 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20098 (not (get-char-property s 'invisible))))
20101 (defun org-copy-visible (beg end)
20102 "Copy the visible parts of the region."
20103 (interactive "r")
20104 (let ((result ""))
20105 (while (/= beg end)
20106 (when (get-char-property beg 'invisible)
20107 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20108 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20109 (setq result (concat result (buffer-substring beg next)))
20110 (setq beg next)))
20111 (kill-new result)))
20113 (defun org-copy-special ()
20114 "Copy region in table or copy current subtree.
20115 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20116 context. See the individual commands for more information."
20117 (interactive)
20118 (call-interactively
20119 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20121 (defun org-cut-special ()
20122 "Cut region in table or cut current subtree.
20123 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20124 context. See the individual commands for more information."
20125 (interactive)
20126 (call-interactively
20127 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20129 (defun org-paste-special (arg)
20130 "Paste rectangular region into table, or past subtree relative to level.
20131 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20132 See the individual commands for more information."
20133 (interactive "P")
20134 (if (org-at-table-p)
20135 (org-table-paste-rectangle)
20136 (org-paste-subtree arg)))
20138 (defun org-edit-special (&optional arg)
20139 "Call a special editor for the element at point.
20140 When at a table, call the formula editor with `org-table-edit-formulas'.
20141 When in a source code block, call `org-edit-src-code'.
20142 When in a fixed-width region, call `org-edit-fixed-width-region'.
20143 When in an export block, call `org-edit-export-block'.
20144 When in a LaTeX environment, call `org-edit-latex-environment'.
20145 When at an #+INCLUDE keyword, visit the included file.
20146 When at a footnote reference, call `org-edit-footnote-reference'
20147 On a link, call `ffap' to visit the link at point.
20148 Otherwise, return a user error."
20149 (interactive "P")
20150 (let ((element (org-element-at-point)))
20151 (barf-if-buffer-read-only)
20152 (pcase (org-element-type element)
20153 (`src-block
20154 (if (not arg) (org-edit-src-code)
20155 (let* ((info (org-babel-get-src-block-info))
20156 (lang (nth 0 info))
20157 (params (nth 2 info))
20158 (session (cdr (assq :session params))))
20159 (if (not session) (org-edit-src-code)
20160 ;; At a src-block with a session and function called with
20161 ;; an ARG: switch to the buffer related to the inferior
20162 ;; process.
20163 (switch-to-buffer
20164 (funcall (intern (concat "org-babel-prep-session:" lang))
20165 session params))))))
20166 (`keyword
20167 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20168 (org-open-link-from-string
20169 (format "[[%s]]"
20170 (expand-file-name
20171 (let ((value (org-element-property :value element)))
20172 (cond ((org-file-url-p value)
20173 (user-error "The file is specified as a URL, cannot be edited"))
20174 ((not (org-string-nw-p value))
20175 (user-error "No file to edit"))
20176 ((string-match "\\`\"\\(.*?\\)\"" value)
20177 (match-string 1 value))
20178 ((string-match "\\`[^ \t\"]\\S-*" value)
20179 (match-string 0 value))
20180 (t (user-error "No valid file specified")))))))
20181 (user-error "No special environment to edit here")))
20182 (`table
20183 (if (eq (org-element-property :type element) 'table.el)
20184 (org-edit-table.el)
20185 (call-interactively 'org-table-edit-formulas)))
20186 ;; Only Org tables contain `table-row' type elements.
20187 (`table-row (call-interactively 'org-table-edit-formulas))
20188 (`example-block (org-edit-src-code))
20189 (`export-block (org-edit-export-block))
20190 (`fixed-width (org-edit-fixed-width-region))
20191 (`latex-environment (org-edit-latex-environment))
20193 ;; No notable element at point. Though, we may be at a link or
20194 ;; a footnote reference, which are objects. Thus, scan deeper.
20195 (let ((context (org-element-context element)))
20196 (pcase (org-element-type context)
20197 (`footnote-reference (org-edit-footnote-reference))
20198 (`inline-src-block (org-edit-inline-src-code))
20199 (`link (call-interactively #'ffap))
20200 (_ (user-error "No special environment to edit here"))))))))
20202 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20203 (defun org-ctrl-c-ctrl-c (&optional arg)
20204 "Set tags in headline, or update according to changed information at point.
20206 This command does many different things, depending on context:
20208 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20209 this is what we do.
20211 - If the cursor is on a statistics cookie, update it.
20213 - If the cursor is in a headline, prompt for tags and insert them
20214 into the current line, aligned to `org-tags-column'. When called
20215 with prefix arg, realign all tags in the current buffer.
20217 - If the cursor is in one of the special #+KEYWORD lines, this
20218 triggers scanning the buffer for these lines and updating the
20219 information.
20221 - If the cursor is inside a table, realign the table. This command
20222 works even if the automatic table editor has been turned off.
20224 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20225 the entire table.
20227 - If the cursor is at a footnote reference or definition, jump to
20228 the corresponding definition or references, respectively.
20230 - If the cursor is a the beginning of a dynamic block, update it.
20232 - If the current buffer is a capture buffer, close note and file it.
20234 - If the cursor is on a <<<target>>>, update radio targets and
20235 corresponding links in this buffer.
20237 - If the cursor is on a numbered item in a plain list, renumber the
20238 ordered list.
20240 - If the cursor is on a checkbox, toggle it.
20242 - If the cursor is on a code block, evaluate it. The variable
20243 `org-confirm-babel-evaluate' can be used to control prompting
20244 before code block evaluation, by default every code block
20245 evaluation requires confirmation. Code block evaluation can be
20246 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20247 (interactive "P")
20248 (cond
20249 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20250 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20251 (org-remove-occur-highlights)
20252 (message "Temporary highlights/overlays removed from current buffer"))
20253 ((and (local-variable-p 'org-finish-function)
20254 (fboundp org-finish-function))
20255 (funcall org-finish-function))
20256 ((org-babel-hash-at-point))
20257 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20259 (let* ((context
20260 (org-element-lineage
20261 (org-element-context)
20262 ;; Limit to supported contexts.
20263 '(babel-call clock dynamic-block footnote-definition
20264 footnote-reference inline-babel-call inline-src-block
20265 inlinetask item keyword node-property paragraph
20266 plain-list planning property-drawer radio-target
20267 src-block statistics-cookie table table-cell table-row
20268 timestamp)
20270 (type (org-element-type context)))
20271 ;; For convenience: at the first line of a paragraph on the same
20272 ;; line as an item, apply function on that item instead.
20273 (when (eq type 'paragraph)
20274 (let ((parent (org-element-property :parent context)))
20275 (when (and (eq (org-element-type parent) 'item)
20276 (= (line-beginning-position)
20277 (org-element-property :begin parent)))
20278 (setq context parent)
20279 (setq type 'item))))
20280 ;; Act according to type of element or object at point.
20282 ;; Do nothing on a blank line, except if it is contained in
20283 ;; a src block. Hence, we first check if point is in such
20284 ;; a block and then if it is at a blank line.
20285 (pcase type
20286 ((or `inline-src-block `src-block)
20287 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20288 (org-babel-eval-wipe-error-buffer)
20289 (org-babel-execute-src-block
20290 current-prefix-arg (org-babel-get-src-block-info nil context))))
20291 ((guard (org-match-line "[ \t]*$"))
20292 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20293 (user-error
20294 (substitute-command-keys
20295 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20296 ((or `babel-call `inline-babel-call)
20297 (let ((info (org-babel-lob-get-info context)))
20298 (when info (org-babel-execute-src-block nil info))))
20299 (`clock (org-clock-update-time-maybe))
20300 (`dynamic-block
20301 (save-excursion
20302 (goto-char (org-element-property :post-affiliated context))
20303 (org-update-dblock)))
20304 (`footnote-definition
20305 (goto-char (org-element-property :post-affiliated context))
20306 (call-interactively 'org-footnote-action))
20307 (`footnote-reference (call-interactively #'org-footnote-action))
20308 ((or `headline `inlinetask)
20309 (save-excursion (goto-char (org-element-property :begin context))
20310 (call-interactively #'org-set-tags)))
20311 (`item
20312 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20313 ;; unconditionally, whereas `C-u' will toggle its presence.
20314 ;; Without a universal argument, if the item has a checkbox,
20315 ;; toggle it. Otherwise repair the list.
20316 (let* ((box (org-element-property :checkbox context))
20317 (struct (org-element-property :structure context))
20318 (old-struct (copy-tree struct))
20319 (parents (org-list-parents-alist struct))
20320 (prevs (org-list-prevs-alist struct))
20321 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20322 (org-list-set-checkbox
20323 (org-element-property :begin context) struct
20324 (cond ((equal arg '(16)) "[-]")
20325 ((and (not box) (equal arg '(4))) "[ ]")
20326 ((or (not box) (equal arg '(4))) nil)
20327 ((eq box 'on) "[ ]")
20328 (t "[X]")))
20329 ;; Mimic `org-list-write-struct' but with grabbing a return
20330 ;; value from `org-list-struct-fix-box'.
20331 (org-list-struct-fix-ind struct parents 2)
20332 (org-list-struct-fix-item-end struct)
20333 (org-list-struct-fix-bul struct prevs)
20334 (org-list-struct-fix-ind struct parents)
20335 (let ((block-item
20336 (org-list-struct-fix-box struct parents prevs orderedp)))
20337 (if (and box (equal struct old-struct))
20338 (if (equal arg '(16))
20339 (message "Checkboxes already reset")
20340 (user-error "Cannot toggle this checkbox: %s"
20341 (if (eq box 'on)
20342 "all subitems checked"
20343 "unchecked subitems")))
20344 (org-list-struct-apply-struct struct old-struct)
20345 (org-update-checkbox-count-maybe))
20346 (when block-item
20347 (message "Checkboxes were removed due to empty box at line %d"
20348 (org-current-line block-item))))))
20349 (`keyword
20350 (let ((org-inhibit-startup-visibility-stuff t)
20351 (org-startup-align-all-tables nil))
20352 (when (boundp 'org-table-coordinate-overlays)
20353 (mapc #'delete-overlay org-table-coordinate-overlays)
20354 (setq org-table-coordinate-overlays nil))
20355 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20356 (message "Local setup has been refreshed"))
20357 (`plain-list
20358 ;; At a plain list, with a double C-u argument, set
20359 ;; checkboxes of each item to "[-]", whereas a single one
20360 ;; will toggle their presence according to the state of the
20361 ;; first item in the list. Without an argument, repair the
20362 ;; list.
20363 (let* ((begin (org-element-property :contents-begin context))
20364 (struct (org-element-property :structure context))
20365 (old-struct (copy-tree struct))
20366 (first-box (save-excursion
20367 (goto-char begin)
20368 (looking-at org-list-full-item-re)
20369 (match-string-no-properties 3)))
20370 (new-box (cond ((equal arg '(16)) "[-]")
20371 ((equal arg '(4)) (unless first-box "[ ]"))
20372 ((equal first-box "[X]") "[ ]")
20373 (t "[X]"))))
20374 (cond
20375 (arg
20376 (dolist (pos
20377 (org-list-get-all-items
20378 begin struct (org-list-prevs-alist struct)))
20379 (org-list-set-checkbox pos struct new-box)))
20380 ((and first-box (eq (point) begin))
20381 ;; For convenience, when point is at bol on the first
20382 ;; item of the list and no argument is provided, simply
20383 ;; toggle checkbox of that item, if any.
20384 (org-list-set-checkbox begin struct new-box)))
20385 (org-list-write-struct
20386 struct (org-list-parents-alist struct) old-struct)
20387 (org-update-checkbox-count-maybe)))
20388 ((or `property-drawer `node-property)
20389 (call-interactively #'org-property-action))
20390 (`radio-target
20391 (call-interactively #'org-update-radio-target-regexp))
20392 (`statistics-cookie
20393 (call-interactively #'org-update-statistics-cookies))
20394 ((or `table `table-cell `table-row)
20395 ;; At a table, recalculate every field and align it. Also
20396 ;; send the table if necessary. If the table has
20397 ;; a `table.el' type, just give up. At a table row or cell,
20398 ;; maybe recalculate line but always align table.
20399 (if (eq (org-element-property :type context) 'table.el)
20400 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20401 Use `\\[org-edit-special]' to edit table.el tables"))
20402 (if (or (eq type 'table)
20403 ;; Check if point is at a TBLFM line.
20404 (and (eq type 'table-row)
20405 (= (point) (org-element-property :end context))))
20406 (save-excursion
20407 (if (org-at-TBLFM-p)
20408 (progn (require 'org-table)
20409 (org-table-calc-current-TBLFM))
20410 (goto-char (org-element-property :contents-begin context))
20411 (org-call-with-arg 'org-table-recalculate (or arg t))
20412 (orgtbl-send-table 'maybe)))
20413 (org-table-maybe-eval-formula)
20414 (cond (arg (call-interactively #'org-table-recalculate))
20415 ((org-table-maybe-recalculate-line))
20416 (t (org-table-align))))))
20417 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20418 (org-timestamp-change 0 'day))
20419 ((and `nil (guard (org-at-heading-p)))
20420 ;; When point is on an unsupported object type, we can miss
20421 ;; the fact that it also is at a heading. Handle it here.
20422 (call-interactively #'org-set-tags))
20423 ((guard
20424 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20426 (user-error
20427 (substitute-command-keys
20428 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20430 (defun org-mode-restart ()
20431 (interactive)
20432 (let ((indent-status (bound-and-true-p org-indent-mode)))
20433 (funcall major-mode)
20434 (hack-local-variables)
20435 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20436 (org-indent-mode -1))
20437 (org-reset-file-cache))
20438 (message "%s restarted" major-mode))
20440 (defun org-kill-note-or-show-branches ()
20441 "Abort storing current note, or call `outline-show-branches'."
20442 (interactive)
20443 (if (not org-finish-function)
20444 (save-excursion
20445 (save-restriction
20446 (org-narrow-to-subtree)
20447 (org-flag-subtree t)
20448 (call-interactively 'outline-show-branches)
20449 (org-hide-archived-subtrees (point-min) (point-max))))
20450 (let ((org-note-abort t))
20451 (funcall org-finish-function))))
20453 (defun org-delete-indentation (&optional arg)
20454 "Join current line to previous and fix whitespace at join.
20456 If previous line is a headline add to headline title. Otherwise
20457 the function calls `delete-indentation'.
20459 With a non-nil optional argument, join it to the following one."
20460 (interactive "*P")
20461 (if (save-excursion
20462 (beginning-of-line (if arg 1 0))
20463 (let ((case-fold-search nil))
20464 (looking-at org-complex-heading-regexp)))
20465 ;; At headline.
20466 (let ((tags-column (when (match-beginning 5)
20467 (save-excursion (goto-char (match-beginning 5))
20468 (current-column))))
20469 (string (concat " " (progn (when arg (forward-line 1))
20470 (org-trim (delete-and-extract-region
20471 (line-beginning-position)
20472 (line-end-position)))))))
20473 (unless (bobp) (delete-region (point) (1- (point))))
20474 (goto-char (or (match-end 4)
20475 (match-beginning 5)
20476 (match-end 0)))
20477 (skip-chars-backward " \t")
20478 (save-excursion (insert string))
20479 ;; Adjust alignment of tags.
20480 (cond
20481 ((not tags-column)) ;no tags
20482 (org-auto-align-tags (org-set-tags nil t))
20483 (t (org--align-tags-here tags-column)))) ;preserve tags column
20484 (delete-indentation arg)))
20486 (defun org-open-line (n)
20487 "Insert a new row in tables, call `open-line' elsewhere.
20488 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20489 As a special case, when a document starts with a table, allow to
20490 call `open-line' on the very first character."
20491 (interactive "*p")
20492 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20493 (org-table-insert-row)
20494 (open-line n)))
20496 (defun org-return (&optional indent)
20497 "Goto next table row or insert a newline.
20499 Calls `org-table-next-row' or `newline', depending on context.
20501 When optional INDENT argument is non-nil, call
20502 `newline-and-indent' instead of `newline'.
20504 When `org-return-follows-link' is non-nil and point is on
20505 a timestamp or a link, call `org-open-at-point'. However, it
20506 will not happen if point is in a table or on a \"dead\"
20507 object (e.g., within a comment). In these case, you need to use
20508 `org-open-at-point' directly."
20509 (interactive)
20510 (let ((context (if org-return-follows-link (org-element-context)
20511 (org-element-at-point))))
20512 (cond
20513 ;; In a table, call `org-table-next-row'. However, before first
20514 ;; column or after last one, split the table.
20515 ((or (and (eq (org-element-type context) 'table)
20516 (>= (point) (org-element-property :contents-begin context))
20517 (< (point) (org-element-property :contents-end context)))
20518 (org-element-lineage context '(table-row table-cell) t))
20519 (if (or (looking-at-p "[ \t]*$")
20520 (save-excursion (skip-chars-backward " \t") (bolp)))
20521 (insert "\n")
20522 (org-table-justify-field-maybe)
20523 (call-interactively #'org-table-next-row)))
20524 ;; On a link or a timestamp, call `org-open-at-point' if
20525 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20526 ;; locations, e.g., in a comment, as `org-open-at-point'.
20527 ((and org-return-follows-link
20528 (or (and (eq 'link (org-element-type context))
20529 ;; Ensure point is not on the white spaces after
20530 ;; the link.
20531 (let ((origin (point)))
20532 (org-with-point-at (org-element-property :end context)
20533 (skip-chars-backward " \t")
20534 (> (point) origin))))
20535 (org-in-regexp org-ts-regexp-both nil t)
20536 (org-in-regexp org-tsr-regexp-both nil t)
20537 (org-in-regexp org-any-link-re nil t)))
20538 (call-interactively #'org-open-at-point))
20539 ;; Insert newline in heading, but preserve tags.
20540 ((and (not (bolp))
20541 (save-excursion (beginning-of-line)
20542 (let ((case-fold-search nil))
20543 (looking-at org-complex-heading-regexp))))
20544 ;; At headline. Split line. However, if point is on keyword,
20545 ;; priority cookie or tags, do not break any of them: add
20546 ;; a newline after the headline instead.
20547 (let ((tags-column (and (match-beginning 5)
20548 (save-excursion (goto-char (match-beginning 5))
20549 (current-column))))
20550 (string
20551 (when (and (match-end 4) (org-point-in-group (point) 4))
20552 (delete-and-extract-region (point) (match-end 4)))))
20553 ;; Adjust tag alignment.
20554 (cond
20555 ((not (and tags-column string)))
20556 (org-auto-align-tags (org-set-tags nil t))
20557 (t (org--align-tags-here tags-column))) ;preserve tags column
20558 (end-of-line)
20559 (org-show-entry)
20560 (if indent (newline-and-indent) (newline))
20561 (when string (save-excursion (insert (org-trim string))))))
20562 ;; In a list, make sure indenting keeps trailing text within.
20563 ((and indent
20564 (not (eolp))
20565 (org-element-lineage context '(item)))
20566 (let ((trailing-data
20567 (delete-and-extract-region (point) (line-end-position))))
20568 (newline-and-indent)
20569 (save-excursion (insert trailing-data))))
20571 ;; Do not auto-fill when point is in an Org property drawer.
20572 (let ((auto-fill-function (and (not (org-at-property-p))
20573 auto-fill-function)))
20574 (if indent
20575 (newline-and-indent)
20576 (newline)))))))
20578 (defun org-return-indent ()
20579 "Goto next table row or insert a newline and indent.
20580 Calls `org-table-next-row' or `newline-and-indent', depending on
20581 context. See the individual commands for more information."
20582 (interactive)
20583 (org-return t))
20585 (defun org-ctrl-c-tab (&optional _arg)
20586 "Toggle columns width in a table, or show children.
20587 Call `org-table-toggle-column-width' if point is in a table.
20588 Otherwise, call `org-show-children'."
20589 (interactive "p")
20590 (call-interactively
20591 (if (org-at-table-p) #'org-table-toggle-column-width
20592 #'org-show-children)))
20594 (defun org-ctrl-c-star ()
20595 "Compute table, or change heading status of lines.
20596 Calls `org-table-recalculate' or `org-toggle-heading',
20597 depending on context."
20598 (interactive)
20599 (cond
20600 ((org-at-table-p)
20601 (call-interactively 'org-table-recalculate))
20603 ;; Convert all lines in region to list items
20604 (call-interactively 'org-toggle-heading))))
20606 (defun org-ctrl-c-minus ()
20607 "Insert separator line in table or modify bullet status of line.
20608 Also turns a plain line or a region of lines into list items.
20609 Calls `org-table-insert-hline', `org-toggle-item', or
20610 `org-cycle-list-bullet', depending on context."
20611 (interactive)
20612 (cond
20613 ((org-at-table-p)
20614 (call-interactively 'org-table-insert-hline))
20615 ((org-region-active-p)
20616 (call-interactively 'org-toggle-item))
20617 ((org-in-item-p)
20618 (call-interactively 'org-cycle-list-bullet))
20620 (call-interactively 'org-toggle-item))))
20622 (defun org-toggle-heading (&optional nstars)
20623 "Convert headings to normal text, or items or text to headings.
20624 If there is no active region, only convert the current line.
20626 With a `\\[universal-argument]' prefix, convert the whole list at
20627 point into heading.
20629 In a region:
20631 - If the first non blank line is a headline, remove the stars
20632 from all headlines in the region.
20634 - If it is a normal line, turn each and every normal line (i.e.,
20635 not an heading or an item) in the region into headings. If you
20636 want to convert only the first line of this region, use one
20637 universal prefix argument.
20639 - If it is a plain list item, turn all plain list items into headings.
20641 When converting a line into a heading, the number of stars is chosen
20642 such that the lines become children of the current entry. However,
20643 when a numeric prefix argument is given, its value determines the
20644 number of stars to add."
20645 (interactive "P")
20646 (let ((skip-blanks
20647 (function
20648 ;; Return beginning of first non-blank line, starting from
20649 ;; line at POS.
20650 (lambda (pos)
20651 (save-excursion
20652 (goto-char pos)
20653 (while (org-at-comment-p) (forward-line))
20654 (skip-chars-forward " \r\t\n")
20655 (point-at-bol)))))
20656 beg end toggled)
20657 ;; Determine boundaries of changes. If a universal prefix has
20658 ;; been given, put the list in a region. If region ends at a bol,
20659 ;; do not consider the last line to be in the region.
20661 (when (and current-prefix-arg (org-at-item-p))
20662 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20663 (org-mark-element))
20665 (if (org-region-active-p)
20666 (setq beg (funcall skip-blanks (region-beginning))
20667 end (copy-marker (save-excursion
20668 (goto-char (region-end))
20669 (if (bolp) (point) (point-at-eol)))))
20670 (setq beg (funcall skip-blanks (point-at-bol))
20671 end (copy-marker (point-at-eol))))
20672 ;; Ensure inline tasks don't count as headings.
20673 (org-with-limited-levels
20674 (save-excursion
20675 (goto-char beg)
20676 (cond
20677 ;; Case 1. Started at an heading: de-star headings.
20678 ((org-at-heading-p)
20679 (while (< (point) end)
20680 (when (org-at-heading-p t)
20681 (looking-at org-outline-regexp) (replace-match "")
20682 (setq toggled t))
20683 (forward-line)))
20684 ;; Case 2. Started at an item: change items into headlines.
20685 ;; One star will be added by `org-list-to-subtree'.
20686 ((org-at-item-p)
20687 (while (< (point) end)
20688 (when (org-at-item-p)
20689 ;; Pay attention to cases when region ends before list.
20690 (let* ((struct (org-list-struct))
20691 (list-end
20692 (min (org-list-get-bottom-point struct) (1+ end))))
20693 (save-restriction
20694 (narrow-to-region (point) list-end)
20695 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20696 (setq toggled t))
20697 (forward-line)))
20698 ;; Case 3. Started at normal text: make every line an heading,
20699 ;; skipping headlines and items.
20700 (t (let* ((stars
20701 (make-string
20702 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20703 (add-stars
20704 (cond (nstars "") ; stars from prefix only
20705 ((equal stars "") "*") ; before first heading
20706 (org-odd-levels-only "**") ; inside heading, odd
20707 (t "*"))) ; inside heading, oddeven
20708 (rpl (concat stars add-stars " "))
20709 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20710 (while (< (point) (if (equal nstars '(4)) lend end))
20711 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20712 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20713 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20714 (forward-line)))))))
20715 (unless toggled (message "Cannot toggle heading from here"))))
20717 (defun org-meta-return (&optional arg)
20718 "Insert a new heading or wrap a region in a table.
20719 Calls `org-insert-heading', `org-insert-item' or
20720 `org-table-wrap-region', depending on context. When called with
20721 an argument, unconditionally call `org-insert-heading'."
20722 (interactive "P")
20723 (org-check-before-invisible-edit 'insert)
20724 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20725 (call-interactively (cond (arg #'org-insert-heading)
20726 ((org-at-table-p) #'org-table-wrap-region)
20727 ((org-in-item-p) #'org-insert-item)
20728 (t #'org-insert-heading)))))
20730 ;;; Menu entries
20732 (defsubst org-in-subtree-not-table-p ()
20733 "Are we in a subtree and not in a table?"
20734 (and (not (org-before-first-heading-p))
20735 (not (org-at-table-p))))
20737 ;; Define the Org mode menus
20738 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20739 '("Tbl"
20740 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20741 ["Next Field" org-cycle (org-at-table-p)]
20742 ["Previous Field" org-shifttab (org-at-table-p)]
20743 ["Next Row" org-return (org-at-table-p)]
20744 "--"
20745 ["Blank Field" org-table-blank-field (org-at-table-p)]
20746 ["Edit Field" org-table-edit-field (org-at-table-p)]
20747 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20748 "--"
20749 ("Column"
20750 ["Move Column Left" org-metaleft (org-at-table-p)]
20751 ["Move Column Right" org-metaright (org-at-table-p)]
20752 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20753 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20754 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20755 ("Row"
20756 ["Move Row Up" org-metaup (org-at-table-p)]
20757 ["Move Row Down" org-metadown (org-at-table-p)]
20758 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20759 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20760 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20761 "--"
20762 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20763 ("Rectangle"
20764 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20765 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20766 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20767 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20768 "--"
20769 ("Calculate"
20770 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20771 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20772 ["Edit Formulas" org-edit-special (org-at-table-p)]
20773 "--"
20774 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20775 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20776 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20777 "--"
20778 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20779 "--"
20780 ["Sum Column/Rectangle" org-table-sum
20781 (or (org-at-table-p) (org-region-active-p))]
20782 ["Which Column?" org-table-current-column (org-at-table-p)])
20783 ["Debug Formulas"
20784 org-table-toggle-formula-debugger
20785 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20786 ["Show Col/Row Numbers"
20787 org-table-toggle-coordinate-overlays
20788 :style toggle
20789 :selected (bound-and-true-p org-table-overlay-coordinates)]
20790 "--"
20791 ["Create" org-table-create (not (org-at-table-p))]
20792 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20793 ["Import from File" org-table-import (not (org-at-table-p))]
20794 ["Export to File" org-table-export (org-at-table-p)]
20795 "--"
20796 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20797 "--"
20798 ("Plot"
20799 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20800 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20802 (easy-menu-define org-org-menu org-mode-map "Org menu"
20803 '("Org"
20804 ("Show/Hide"
20805 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20806 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20807 ["Sparse Tree..." org-sparse-tree t]
20808 ["Reveal Context" org-reveal t]
20809 ["Show All" org-show-all t]
20810 "--"
20811 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20812 "--"
20813 ["New Heading" org-insert-heading t]
20814 ("Navigate Headings"
20815 ["Up" outline-up-heading t]
20816 ["Next" outline-next-visible-heading t]
20817 ["Previous" outline-previous-visible-heading t]
20818 ["Next Same Level" outline-forward-same-level t]
20819 ["Previous Same Level" outline-backward-same-level t]
20820 "--"
20821 ["Jump" org-goto t])
20822 ("Edit Structure"
20823 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20824 "--"
20825 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20826 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20827 "--"
20828 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20829 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20830 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20831 "--"
20832 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20833 "--"
20834 ["Copy visible text" org-copy-visible t]
20835 "--"
20836 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20837 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20838 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20839 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20840 "--"
20841 ["Sort Region/Children" org-sort t]
20842 "--"
20843 ["Convert to odd levels" org-convert-to-odd-levels t]
20844 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20845 ("Editing"
20846 ["Emphasis..." org-emphasize t]
20847 ["Edit Source Example" org-edit-special t]
20848 "--"
20849 ["Footnote new/jump" org-footnote-action t]
20850 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20851 ("Archive"
20852 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20853 "--"
20854 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20855 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20856 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20858 "--"
20859 ("Hyperlinks"
20860 ["Store Link (Global)" org-store-link t]
20861 ["Find existing link to here" org-occur-link-in-agenda-files t]
20862 ["Insert Link" org-insert-link t]
20863 ["Follow Link" org-open-at-point t]
20864 "--"
20865 ["Next link" org-next-link t]
20866 ["Previous link" org-previous-link t]
20867 "--"
20868 ["Descriptive Links"
20869 org-toggle-link-display
20870 :style radio
20871 :selected org-descriptive-links
20873 ["Literal Links"
20874 org-toggle-link-display
20875 :style radio
20876 :selected (not org-descriptive-links)])
20877 "--"
20878 ("TODO Lists"
20879 ["TODO/DONE/-" org-todo t]
20880 ("Select keyword"
20881 ["Next keyword" org-shiftright (org-at-heading-p)]
20882 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20883 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20884 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20885 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20886 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20887 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20888 "--"
20889 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20890 :selected org-enforce-todo-dependencies :style toggle :active t]
20891 "Settings for tree at point"
20892 ["Do Children sequentially" org-toggle-ordered-property :style radio
20893 :selected (org-entry-get nil "ORDERED")
20894 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20895 ["Do Children parallel" org-toggle-ordered-property :style radio
20896 :selected (not (org-entry-get nil "ORDERED"))
20897 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20898 "--"
20899 ["Set Priority" org-priority t]
20900 ["Priority Up" org-shiftup t]
20901 ["Priority Down" org-shiftdown t]
20902 "--"
20903 ["Get news from all feeds" org-feed-update-all t]
20904 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20905 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20906 ("TAGS and Properties"
20907 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20908 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20909 "--"
20910 ["Set property" org-set-property (not (org-before-first-heading-p))]
20911 ["Column view of properties" org-columns t]
20912 ["Insert Column View DBlock" org-columns-insert-dblock t])
20913 ("Dates and Scheduling"
20914 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20915 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20916 ("Change Date"
20917 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20918 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20919 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20920 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20921 ["Compute Time Range" org-evaluate-time-range t]
20922 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20923 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20924 "--"
20925 ["Custom time format" org-toggle-time-stamp-overlays
20926 :style radio :selected org-display-custom-times]
20927 "--"
20928 ["Goto Calendar" org-goto-calendar t]
20929 ["Date from Calendar" org-date-from-calendar t]
20930 "--"
20931 ["Start/Restart Timer" org-timer-start t]
20932 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20933 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20934 ["Insert Timer String" org-timer t]
20935 ["Insert Timer Item" org-timer-item t])
20936 ("Logging work"
20937 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20938 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20939 ["Clock out" org-clock-out t]
20940 ["Clock cancel" org-clock-cancel t]
20941 "--"
20942 ["Mark as default task" org-clock-mark-default-task t]
20943 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20944 ["Goto running clock" org-clock-goto t]
20945 "--"
20946 ["Display times" org-clock-display t]
20947 ["Create clock table" org-clock-report t]
20948 "--"
20949 ["Record DONE time"
20950 (progn (setq org-log-done (not org-log-done))
20951 (message "Switching to %s will %s record a timestamp"
20952 (car org-done-keywords)
20953 (if org-log-done "automatically" "not")))
20954 :style toggle :selected org-log-done])
20955 "--"
20956 ["Agenda Command..." org-agenda t]
20957 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20958 ("File List for Agenda")
20959 ("Special views current file"
20960 ["TODO Tree" org-show-todo-tree t]
20961 ["Check Deadlines" org-check-deadlines t]
20962 ["Tags/Property tree" org-match-sparse-tree t])
20963 "--"
20964 ["Export/Publish..." org-export-dispatch t]
20965 ("LaTeX"
20966 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20967 :style toggle :selected org-cdlatex-mode]
20968 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20969 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20970 ["Modify math symbol" org-cdlatex-math-modify
20971 (org-inside-LaTeX-fragment-p)]
20972 ["Insert citation" org-reftex-citation t])
20973 "--"
20974 ("MobileOrg"
20975 ["Push Files and Views" org-mobile-push t]
20976 ["Get Captured and Flagged" org-mobile-pull t]
20977 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20978 "--"
20979 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20980 "--"
20981 ("Documentation"
20982 ["Show Version" org-version t]
20983 ["Info Documentation" org-info t])
20984 ("Customize"
20985 ["Browse Org Group" org-customize t]
20986 "--"
20987 ["Expand This Menu" org-create-customize-menu
20988 (fboundp 'customize-menu-create)])
20989 ["Send bug report" org-submit-bug-report t]
20990 "--"
20991 ("Refresh/Reload"
20992 ["Refresh setup current buffer" org-mode-restart t]
20993 ["Reload Org (after update)" org-reload t]
20994 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20997 (defun org-info (&optional node)
20998 "Read documentation for Org in the info system.
20999 With optional NODE, go directly to that node."
21000 (interactive)
21001 (info (format "(org)%s" (or node ""))))
21003 ;;;###autoload
21004 (defun org-submit-bug-report ()
21005 "Submit a bug report on Org via mail.
21007 Don't hesitate to report any problems or inaccurate documentation.
21009 If you don't have setup sending mail from (X)Emacs, please copy the
21010 output buffer into your mail program, as it gives us important
21011 information about your Org version and configuration."
21012 (interactive)
21013 (require 'reporter)
21014 (defvar reporter-prompt-for-summary-p)
21015 (org-load-modules-maybe)
21016 (org-require-autoloaded-modules)
21017 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21018 (reporter-submit-bug-report
21019 "emacs-orgmode@gnu.org"
21020 (org-version nil 'full)
21021 (let (list)
21022 (save-window-excursion
21023 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21024 (delete-other-windows)
21025 (erase-buffer)
21026 (insert "You are about to submit a bug report to the Org mailing list.
21028 We would like to add your full Org and Outline configuration to the
21029 bug report. This greatly simplifies the work of the maintainer and
21030 other experts on the mailing list.
21032 HOWEVER, some variables you have customized may contain private
21033 information. The names of customers, colleagues, or friends, might
21034 appear in the form of file names, tags, todo states, or search strings.
21035 If you answer yes to the prompt, you might want to check and remove
21036 such private information before sending the email.")
21037 (add-text-properties (point-min) (point-max) '(face org-warning))
21038 (when (yes-or-no-p "Include your Org configuration ")
21039 (mapatoms
21040 (lambda (v)
21041 (and (boundp v)
21042 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21043 (or (and (symbol-value v)
21044 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21045 (and
21046 (get v 'custom-type) (get v 'standard-value)
21047 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21048 (push v list)))))
21049 (kill-buffer (get-buffer "*Warn about privacy*"))
21050 list))
21051 nil nil
21052 "Remember to cover the basics, that is, what you expected to happen and
21053 what in fact did happen. You don't know how to make a good report? See
21055 https://orgmode.org/manual/Feedback.html#Feedback
21057 Your bug report will be posted to the Org mailing list.
21058 ------------------------------------------------------------------------")
21059 (save-excursion
21060 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21061 (replace-match "\\1Bug: \\3 [\\2]")))))
21064 (defun org-install-agenda-files-menu ()
21065 (let ((bl (buffer-list)))
21066 (save-excursion
21067 (while bl
21068 (set-buffer (pop bl))
21069 (when (derived-mode-p 'org-mode) (setq bl nil)))
21070 (when (derived-mode-p 'org-mode)
21071 (easy-menu-change
21072 '("Org") "File List for Agenda"
21073 (append
21074 (list
21075 ["Edit File List" (org-edit-agenda-file-list) t]
21076 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21077 ["Remove Current File from List" org-remove-file t]
21078 ["Cycle through agenda files" org-cycle-agenda-files t]
21079 ["Occur in all agenda files" org-occur-in-agenda-files t]
21080 "--")
21081 (mapcar 'org-file-menu-entry
21082 ;; Prevent initialization from failing.
21083 (ignore-errors (org-agenda-files t)))))))))
21085 ;;;; Documentation
21087 (defun org-require-autoloaded-modules ()
21088 (interactive)
21089 (mapc #'require
21090 '(org-agenda org-archive org-attach org-clock org-colview org-id
21091 org-table org-timer)))
21093 ;;;###autoload
21094 (defun org-reload (&optional uncompiled)
21095 "Reload all Org Lisp files.
21096 With prefix arg UNCOMPILED, load the uncompiled versions."
21097 (interactive "P")
21098 (require 'loadhist)
21099 (let* ((org-dir (org-find-library-dir "org"))
21100 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21101 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21102 (remove-re (format "\\`%s\\'"
21103 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21104 (feats (delete-dups
21105 (mapcar 'file-name-sans-extension
21106 (mapcar 'file-name-nondirectory
21107 (delq nil
21108 (mapcar 'feature-file
21109 features))))))
21110 (lfeat (append
21111 (sort
21112 (setq feats
21113 (delq nil (mapcar
21114 (lambda (f)
21115 (if (and (string-match feature-re f)
21116 (not (string-match remove-re f)))
21117 f nil))
21118 feats)))
21119 'string-lessp)
21120 (list "org-version" "org")))
21121 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21122 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21123 load-uncore load-misses)
21124 (setq load-misses
21125 (delq 't
21126 (mapcar (lambda (f)
21127 (or (org-load-noerror-mustsuffix (concat org-dir f))
21128 (and (string= org-dir contrib-dir)
21129 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21130 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21131 (add-to-list 'load-uncore f 'append)
21134 lfeat)))
21135 (when load-uncore
21136 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21137 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21138 (if load-misses
21139 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21140 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21141 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21143 ;;;###autoload
21144 (defun org-customize ()
21145 "Call the customize function with org as argument."
21146 (interactive)
21147 (org-load-modules-maybe)
21148 (org-require-autoloaded-modules)
21149 (customize-browse 'org))
21151 (defun org-create-customize-menu ()
21152 "Create a full customization menu for Org mode, insert it into the menu."
21153 (interactive)
21154 (org-load-modules-maybe)
21155 (org-require-autoloaded-modules)
21156 (if (fboundp 'customize-menu-create)
21157 (progn
21158 (easy-menu-change
21159 '("Org") "Customize"
21160 `(["Browse Org group" org-customize t]
21161 "--"
21162 ,(customize-menu-create 'org)
21163 ["Set" Custom-set t]
21164 ["Save" Custom-save t]
21165 ["Reset to Current" Custom-reset-current t]
21166 ["Reset to Saved" Custom-reset-saved t]
21167 ["Reset to Standard Settings" Custom-reset-standard t]))
21168 (message "\"Org\"-menu now contains full customization menu"))
21169 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21171 ;;;; Miscellaneous stuff
21173 ;;; Generally useful functions
21175 (defun org-link-display-format (s)
21176 "Replace links in string S with their description.
21177 If there is no description, use the link target."
21178 (save-match-data
21179 (replace-regexp-in-string
21180 org-bracket-link-analytic-regexp
21181 (lambda (m)
21182 (if (match-end 5) (match-string 5 m)
21183 (concat (match-string 1 m) (match-string 3 m))))
21184 s nil t)))
21186 (defun org-toggle-link-display ()
21187 "Toggle the literal or descriptive display of links."
21188 (interactive)
21189 (if org-descriptive-links
21190 (progn (org-remove-from-invisibility-spec '(org-link))
21191 (org-restart-font-lock)
21192 (setq org-descriptive-links nil))
21193 (progn (add-to-invisibility-spec '(org-link))
21194 (org-restart-font-lock)
21195 (setq org-descriptive-links t))))
21197 (defun org-in-clocktable-p ()
21198 "Check if the cursor is in a clocktable."
21199 (let ((pos (point)) start)
21200 (save-excursion
21201 (end-of-line 1)
21202 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21203 (setq start (match-beginning 0))
21204 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21205 (>= (match-end 0) pos)
21206 start))))
21208 (defun org-in-verbatim-emphasis ()
21209 (save-match-data
21210 (and (org-in-regexp org-verbatim-re 2)
21211 (>= (point) (match-beginning 3))
21212 (<= (point) (match-end 4)))))
21214 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21215 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21216 (if (and marker (marker-buffer marker)
21217 (buffer-live-p (marker-buffer marker)))
21218 (progn
21219 (pop-to-buffer-same-window (marker-buffer marker))
21220 (when (or (> marker (point-max)) (< marker (point-min)))
21221 (widen))
21222 (goto-char marker)
21223 (org-show-context 'org-goto))
21224 (if bookmark
21225 (bookmark-jump bookmark)
21226 (error "Cannot find location"))))
21228 (defun org-quote-csv-field (s)
21229 "Quote field for inclusion in CSV material."
21230 (if (string-match "[\",]" s)
21231 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21234 (defun org-force-self-insert (N)
21235 "Needed to enforce self-insert under remapping."
21236 (interactive "p")
21237 (self-insert-command N))
21239 (defun org-fill-template (template alist)
21240 "Find each %key of ALIST in TEMPLATE and replace it."
21241 (let ((case-fold-search nil))
21242 (dolist (entry (sort (copy-sequence alist)
21243 (lambda (a b) (< (length (car a)) (length (car b))))))
21244 (setq template
21245 (replace-regexp-in-string
21246 (concat "%" (regexp-quote (car entry)))
21247 (or (cdr entry) "") template t t)))
21248 template))
21250 (defun org-quote-vert (s)
21251 "Replace \"|\" with \"\\vert\"."
21252 (while (string-match "|" s)
21253 (setq s (replace-match "\\vert" t t s)))
21256 (defun org-uuidgen-p (s)
21257 "Is S an ID created by UUIDGEN?"
21258 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21260 (defun org-in-src-block-p (&optional inside)
21261 "Whether point is in a code source block.
21262 When INSIDE is non-nil, don't consider we are within a src block
21263 when point is at #+BEGIN_SRC or #+END_SRC."
21264 (let ((case-fold-search t))
21265 (or (and (eq (get-char-property (point) 'src-block) t))
21266 (and (not inside)
21267 (save-match-data
21268 (save-excursion
21269 (beginning-of-line)
21270 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21272 (defun org-context ()
21273 "Return a list of contexts of the current cursor position.
21274 If several contexts apply, all are returned.
21275 Each context entry is a list with a symbol naming the context, and
21276 two positions indicating start and end of the context. Possible
21277 contexts are:
21279 :headline anywhere in a headline
21280 :headline-stars on the leading stars in a headline
21281 :todo-keyword on a TODO keyword (including DONE) in a headline
21282 :tags on the TAGS in a headline
21283 :priority on the priority cookie in a headline
21284 :item on the first line of a plain list item
21285 :item-bullet on the bullet/number of a plain list item
21286 :checkbox on the checkbox in a plain list item
21287 :table in an Org table
21288 :table-special on a special filed in a table
21289 :table-table in a table.el table
21290 :clocktable in a clocktable
21291 :src-block in a source block
21292 :link on a hyperlink
21293 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21294 :target on a <<target>>
21295 :radio-target on a <<<radio-target>>>
21296 :latex-fragment on a LaTeX fragment
21297 :latex-preview on a LaTeX fragment with overlaid preview image
21299 This function expects the position to be visible because it uses font-lock
21300 faces as a help to recognize the following contexts: :table-special, :link,
21301 and :keyword."
21302 (let* ((f (get-text-property (point) 'face))
21303 (faces (if (listp f) f (list f)))
21304 (case-fold-search t)
21305 (p (point)) clist o)
21306 ;; First the large context
21307 (cond
21308 ((org-at-heading-p t)
21309 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21310 (when (progn
21311 (beginning-of-line 1)
21312 (looking-at org-todo-line-tags-regexp))
21313 (push (org-point-in-group p 1 :headline-stars) clist)
21314 (push (org-point-in-group p 2 :todo-keyword) clist)
21315 (push (org-point-in-group p 4 :tags) clist))
21316 (goto-char p)
21317 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21318 (when (looking-at "\\[#[A-Z0-9]\\]")
21319 (push (org-point-in-group p 0 :priority) clist)))
21321 ((org-at-item-p)
21322 (push (org-point-in-group p 2 :item-bullet) clist)
21323 (push (list :item (point-at-bol)
21324 (save-excursion (org-end-of-item) (point)))
21325 clist)
21326 (and (org-at-item-checkbox-p)
21327 (push (org-point-in-group p 0 :checkbox) clist)))
21329 ((org-at-table-p)
21330 (push (list :table (org-table-begin) (org-table-end)) clist)
21331 (when (memq 'org-formula faces)
21332 (push (list :table-special
21333 (previous-single-property-change p 'face)
21334 (next-single-property-change p 'face)) clist)))
21335 ((org-at-table-p 'any)
21336 (push (list :table-table) clist)))
21337 (goto-char p)
21339 (let ((case-fold-search t))
21340 ;; New the "medium" contexts: clocktables, source blocks
21341 (cond ((org-in-clocktable-p)
21342 (push (list :clocktable
21343 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21344 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21345 (match-beginning 1))
21346 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21347 (match-end 0))) clist))
21348 ((org-in-src-block-p)
21349 (push (list :src-block
21350 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21351 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21352 (match-beginning 1))
21353 (and (search-forward "#+END_SRC" nil t)
21354 (match-beginning 0))) clist))))
21355 (goto-char p)
21357 ;; Now the small context
21358 (cond
21359 ((org-at-timestamp-p)
21360 (push (org-point-in-group p 0 :timestamp) clist))
21361 ((memq 'org-link faces)
21362 (push (list :link
21363 (previous-single-property-change p 'face)
21364 (next-single-property-change p 'face)) clist))
21365 ((memq 'org-special-keyword faces)
21366 (push (list :keyword
21367 (previous-single-property-change p 'face)
21368 (next-single-property-change p 'face)) clist))
21369 ((org-at-target-p)
21370 (push (org-point-in-group p 0 :target) clist)
21371 (goto-char (1- (match-beginning 0)))
21372 (when (looking-at org-radio-target-regexp)
21373 (push (org-point-in-group p 0 :radio-target) clist))
21374 (goto-char p))
21375 ((setq o (cl-some
21376 (lambda (o)
21377 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21379 (overlays-at (point))))
21380 (push (list :latex-fragment
21381 (overlay-start o) (overlay-end o)) clist)
21382 (push (list :latex-preview
21383 (overlay-start o) (overlay-end o)) clist))
21384 ((org-inside-LaTeX-fragment-p)
21385 ;; FIXME: positions wrong.
21386 (push (list :latex-fragment (point) (point)) clist)))
21388 (setq clist (nreverse (delq nil clist)))
21389 clist))
21391 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21392 "Non-nil when point is between matches of START-RE and END-RE.
21394 Also return a non-nil value when point is on one of the matches.
21396 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21397 buffer positions. Default values are the positions of headlines
21398 surrounding the point.
21400 The functions returns a cons cell whose car (resp. cdr) is the
21401 position before START-RE (resp. after END-RE)."
21402 (save-match-data
21403 (let ((pos (point))
21404 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21405 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21406 beg end)
21407 (save-excursion
21408 ;; Point is on a block when on START-RE or if START-RE can be
21409 ;; found before it...
21410 (and (or (org-in-regexp start-re)
21411 (re-search-backward start-re limit-up t))
21412 (setq beg (match-beginning 0))
21413 ;; ... and END-RE after it...
21414 (goto-char (match-end 0))
21415 (re-search-forward end-re limit-down t)
21416 (> (setq end (match-end 0)) pos)
21417 ;; ... without another START-RE in-between.
21418 (goto-char (match-beginning 0))
21419 (not (re-search-backward start-re (1+ beg) t))
21420 ;; Return value.
21421 (cons beg end))))))
21423 (defun org-in-block-p (names)
21424 "Non-nil when point belongs to a block whose name belongs to NAMES.
21426 NAMES is a list of strings containing names of blocks.
21428 Return first block name matched, or nil. Beware that in case of
21429 nested blocks, the returned name may not belong to the closest
21430 block from point."
21431 (save-match-data
21432 (catch 'exit
21433 (let ((case-fold-search t)
21434 (lim-up (save-excursion (outline-previous-heading)))
21435 (lim-down (save-excursion (outline-next-heading))))
21436 (dolist (name names)
21437 (let ((n (regexp-quote name)))
21438 (when (org-between-regexps-p
21439 (concat "^[ \t]*#\\+begin_" n)
21440 (concat "^[ \t]*#\\+end_" n)
21441 lim-up lim-down)
21442 (throw 'exit n)))))
21443 nil)))
21445 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21446 "Call `multi-occur' with buffers for all agenda files."
21447 (interactive "sOrg-files matching: ")
21448 (let* ((files (org-agenda-files))
21449 (tnames (mapcar #'file-truename files))
21450 (extra org-agenda-text-search-extra-files))
21451 (when (eq (car extra) 'agenda-archives)
21452 (setq extra (cdr extra))
21453 (setq files (org-add-archive-files files)))
21454 (dolist (f extra)
21455 (unless (member (file-truename f) tnames)
21456 (unless (member f files) (setq files (append files (list f))))
21457 (setq tnames (append tnames (list (file-truename f))))))
21458 (multi-occur
21459 (mapcar (lambda (x)
21460 (with-current-buffer
21461 ;; FIXME: Why not just (find-file-noselect x)?
21462 ;; Is it to avoid the "revert buffer" prompt?
21463 (or (get-file-buffer x) (find-file-noselect x))
21464 (widen)
21465 (current-buffer)))
21466 files)
21467 regexp)))
21469 (add-hook 'occur-mode-find-occurrence-hook
21470 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21472 (defun org-occur-link-in-agenda-files ()
21473 "Create a link and search for it in the agendas.
21474 The link is not stored in `org-stored-links', it is just created
21475 for the search purpose."
21476 (interactive)
21477 (let ((link (condition-case nil
21478 (org-store-link nil)
21479 (error "Unable to create a link to here"))))
21480 (org-occur-in-agenda-files (regexp-quote link))))
21482 (defun org-back-over-empty-lines ()
21483 "Move backwards over whitespace, to the beginning of the first empty line.
21484 Returns the number of empty lines passed."
21485 (let ((pos (point)))
21486 (if (cdr (assq 'heading org-blank-before-new-entry))
21487 (skip-chars-backward " \t\n\r")
21488 (unless (eobp)
21489 (forward-line -1)))
21490 (beginning-of-line 2)
21491 (goto-char (min (point) pos))
21492 (count-lines (point) pos)))
21494 (defun org-switch-to-buffer-other-window (&rest args)
21495 "Switch to buffer in a second window on the current frame.
21496 In particular, do not allow pop-up frames.
21497 Returns the newly created buffer."
21498 (org-no-popups
21499 (apply 'switch-to-buffer-other-window args)))
21501 (defun org-replace-escapes (string table)
21502 "Replace %-escapes in STRING with values in TABLE.
21503 TABLE is an association list with keys like \"%a\" and string values.
21504 The sequences in STRING may contain normal field width and padding information,
21505 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21506 so values can contain further %-escapes if they are define later in TABLE."
21507 (let ((tbl (copy-alist table))
21508 (case-fold-search nil)
21509 (pchg 0)
21510 re rpl)
21511 (dolist (e tbl)
21512 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21513 (when (and (cdr e) (string-match re (cdr e)))
21514 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21515 (safe "SREF"))
21516 (add-text-properties 0 3 (list 'sref sref) safe)
21517 (setcdr e (replace-match safe t t (cdr e)))))
21518 (while (string-match re string)
21519 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21520 (cdr e)))
21521 (setq string (replace-match rpl t t string))))
21522 (while (setq pchg (next-property-change pchg string))
21523 (let ((sref (get-text-property pchg 'sref string)))
21524 (when (and sref (string-match "SREF" string pchg))
21525 (setq string (replace-match sref t t string)))))
21526 string))
21528 ;;; TODO: Only called once, from ox-odt which should probably use
21529 ;;; org-export-inline-image-p or something.
21530 (defun org-file-image-p (file)
21531 "Return non-nil if FILE is an image."
21532 (save-match-data
21533 (string-match (image-file-name-regexp) file)))
21535 (defun org-get-cursor-date (&optional with-time)
21536 "Return the date at cursor in as a time.
21537 This works in the calendar and in the agenda, anywhere else it just
21538 returns the current time.
21539 If WITH-TIME is non-nil, returns the time of the event at point (in
21540 the agenda) or the current time of the day."
21541 (let (date day defd tp hod mod)
21542 (when with-time
21543 (setq tp (get-text-property (point) 'time))
21544 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21545 (setq hod (string-to-number (match-string 1 tp))
21546 mod (string-to-number (match-string 2 tp))))
21547 (or tp (let ((now (decode-time)))
21548 (setq hod (nth 2 now)
21549 mod (nth 1 now)))))
21550 (cond
21551 ((eq major-mode 'calendar-mode)
21552 (setq date (calendar-cursor-to-date)
21553 defd (encode-time 0 (or mod 0) (or hod 0)
21554 (nth 1 date) (nth 0 date) (nth 2 date))))
21555 ((eq major-mode 'org-agenda-mode)
21556 (setq day (get-text-property (point) 'day))
21557 (when day
21558 (setq date (calendar-gregorian-from-absolute day)
21559 defd (encode-time 0 (or mod 0) (or hod 0)
21560 (nth 1 date) (nth 0 date) (nth 2 date))))))
21561 (or defd (current-time))))
21563 (defun org-mark-subtree (&optional up)
21564 "Mark the current subtree.
21565 This puts point at the start of the current subtree, and mark at
21566 the end. If a numeric prefix UP is given, move up into the
21567 hierarchy of headlines by UP levels before marking the subtree."
21568 (interactive "P")
21569 (org-with-limited-levels
21570 (cond ((org-at-heading-p) (beginning-of-line))
21571 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21572 (t (outline-previous-visible-heading 1))))
21573 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21574 (if (called-interactively-p 'any)
21575 (call-interactively 'org-mark-element)
21576 (org-mark-element)))
21578 (defun org-file-newer-than-p (file time)
21579 "Non-nil if FILE is newer than TIME.
21580 FILE is a filename, as a string, TIME is a list of integers, as
21581 returned by, e.g., `current-time'."
21582 (and (file-exists-p file)
21583 ;; Only compare times up to whole seconds as some file-systems
21584 ;; (e.g. HFS+) do not retain any finer granularity. As
21585 ;; a consequence, make sure we return non-nil when the two
21586 ;; times are equal.
21587 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21588 (cl-subseq time 0 2)))))
21590 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21591 "Compile a SOURCE file using PROCESS.
21593 PROCESS is either a function or a list of shell commands, as
21594 strings. EXT is a file extension, without the leading dot, as
21595 a string. It is used to check if the process actually succeeded.
21597 PROCESS must create a file with the same base name and directory
21598 as SOURCE, but ending with EXT. The function then returns its
21599 filename. Otherwise, it raises an error. The error message can
21600 then be refined by providing string ERR-MSG, which is appended to
21601 the standard message.
21603 If PROCESS is a function, it is called with a single argument:
21604 the SOURCE file.
21606 If it is a list of commands, each of them is called using
21607 `shell-command'. By default, in each command, %b, %f, %F, %o and
21608 %O are replaced with, respectively, SOURCE base name, name, full
21609 name, directory and absolute output file name. It is possible,
21610 however, to use more place-holders by specifying them in optional
21611 argument SPEC, as an alist following the pattern
21613 (CHARACTER . REPLACEMENT-STRING).
21615 When PROCESS is a list of commands, optional argument LOG-BUF can
21616 be set to a buffer or a buffer name. `shell-command' then uses
21617 it for output."
21618 (let* ((base-name (file-name-base source))
21619 (full-name (file-truename source))
21620 (out-dir (or (file-name-directory source) "./"))
21621 (output (expand-file-name (concat base-name "." ext) out-dir))
21622 (time (current-time))
21623 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21624 (save-window-excursion
21625 (pcase process
21626 ((pred functionp) (funcall process (shell-quote-argument source)))
21627 ((pred consp)
21628 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21629 (spec (append spec
21630 `((?b . ,(shell-quote-argument base-name))
21631 (?f . ,(shell-quote-argument source))
21632 (?F . ,(shell-quote-argument full-name))
21633 (?o . ,(shell-quote-argument out-dir))
21634 (?O . ,(shell-quote-argument output))))))
21635 (dolist (command process)
21636 (shell-command (format-spec command spec) log-buf))
21637 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21638 (_ (error "No valid command to process %S%s" source err-msg))))
21639 ;; Check for process failure. Output file is expected to be
21640 ;; located in the same directory as SOURCE.
21641 (unless (org-file-newer-than-p output time)
21642 (error (format "File %S wasn't produced%s" output err-msg)))
21643 output))
21645 ;;; Indentation
21647 (defvar org-element-greater-elements)
21648 (defun org--get-expected-indentation (element contentsp)
21649 "Expected indentation column for current line, according to ELEMENT.
21650 ELEMENT is an element containing point. CONTENTSP is non-nil
21651 when indentation is to be computed according to contents of
21652 ELEMENT."
21653 (let ((type (org-element-type element))
21654 (start (org-element-property :begin element))
21655 (post-affiliated (org-element-property :post-affiliated element)))
21656 (org-with-wide-buffer
21657 (cond
21658 (contentsp
21659 (cl-case type
21660 ((diary-sexp footnote-definition) 0)
21661 ((headline inlinetask nil)
21662 (if (not org-adapt-indentation) 0
21663 (let ((level (org-current-level)))
21664 (if level (1+ level) 0))))
21665 ((item plain-list) (org-list-item-body-column post-affiliated))
21667 (goto-char start)
21668 (org-get-indentation))))
21669 ((memq type '(headline inlinetask nil))
21670 (if (org-match-line "[ \t]*$")
21671 (org--get-expected-indentation element t)
21673 ((memq type '(diary-sexp footnote-definition)) 0)
21674 ;; First paragraph of a footnote definition or an item.
21675 ;; Indent like parent.
21676 ((< (line-beginning-position) start)
21677 (org--get-expected-indentation
21678 (org-element-property :parent element) t))
21679 ;; At first line: indent according to previous sibling, if any,
21680 ;; ignoring footnote definitions and inline tasks, or parent's
21681 ;; contents.
21682 ((= (line-beginning-position) start)
21683 (catch 'exit
21684 (while t
21685 (if (= (point-min) start) (throw 'exit 0)
21686 (goto-char (1- start))
21687 (let* ((previous (org-element-at-point))
21688 (parent previous))
21689 (while (and parent (<= (org-element-property :end parent) start))
21690 (setq previous parent
21691 parent (org-element-property :parent parent)))
21692 (cond
21693 ((not previous) (throw 'exit 0))
21694 ((> (org-element-property :end previous) start)
21695 (throw 'exit (org--get-expected-indentation previous t)))
21696 ((memq (org-element-type previous)
21697 '(footnote-definition inlinetask))
21698 (setq start (org-element-property :begin previous)))
21699 (t (goto-char (org-element-property :begin previous))
21700 (throw 'exit
21701 (if (bolp) (org-get-indentation)
21702 ;; At first paragraph in an item or
21703 ;; a footnote definition.
21704 (org--get-expected-indentation
21705 (org-element-property :parent previous) t))))))))))
21706 ;; Otherwise, move to the first non-blank line above.
21708 (beginning-of-line)
21709 (let ((pos (point)))
21710 (skip-chars-backward " \r\t\n")
21711 (cond
21712 ;; Two blank lines end a footnote definition or a plain
21713 ;; list. When we indent an empty line after them, the
21714 ;; containing list or footnote definition is over, so it
21715 ;; qualifies as a previous sibling. Therefore, we indent
21716 ;; like its first line.
21717 ((and (memq type '(footnote-definition plain-list))
21718 (> (count-lines (point) pos) 2))
21719 (goto-char start)
21720 (org-get-indentation))
21721 ;; Line above is the first one of a paragraph at the
21722 ;; beginning of an item or a footnote definition. Indent
21723 ;; like parent.
21724 ((< (line-beginning-position) start)
21725 (org--get-expected-indentation
21726 (org-element-property :parent element) t))
21727 ;; Line above is the beginning of an element, i.e., point
21728 ;; was originally on the blank lines between element's start
21729 ;; and contents.
21730 ((= (line-beginning-position) post-affiliated)
21731 (org--get-expected-indentation element t))
21732 ;; POS is after contents in a greater element. Indent like
21733 ;; the beginning of the element.
21734 ((and (memq type org-element-greater-elements)
21735 (let ((cend (org-element-property :contents-end element)))
21736 (and cend (<= cend pos))))
21737 ;; As a special case, if point is at the end of a footnote
21738 ;; definition or an item, indent like the very last element
21739 ;; within. If that last element is an item, indent like
21740 ;; its contents.
21741 (if (memq type '(footnote-definition item plain-list))
21742 (let ((last (org-element-at-point)))
21743 (goto-char pos)
21744 (org--get-expected-indentation
21745 last (eq (org-element-type last) 'item)))
21746 (goto-char start)
21747 (org-get-indentation)))
21748 ;; In any other case, indent like the current line.
21749 (t (org-get-indentation)))))))))
21751 (defun org--align-node-property ()
21752 "Align node property at point.
21753 Alignment is done according to `org-property-format', which see."
21754 (when (save-excursion
21755 (beginning-of-line)
21756 (looking-at org-property-re))
21757 (replace-match
21758 (concat (match-string 4)
21759 (org-trim
21760 (format org-property-format (match-string 1) (match-string 3))))
21761 t t)))
21763 (defun org-indent-line ()
21764 "Indent line depending on context.
21766 Indentation is done according to the following rules:
21768 - Footnote definitions, diary sexps, headlines and inline tasks
21769 have to start at column 0.
21771 - On the very first line of an element, consider, in order, the
21772 next rules until one matches:
21774 1. If there's a sibling element before, ignoring footnote
21775 definitions and inline tasks, indent like its first line.
21777 2. If element has a parent, indent like its contents. More
21778 precisely, if parent is an item, indent after the
21779 description part, if any, or the bullet (see
21780 `org-list-description-max-indent'). Else, indent like
21781 parent's first line.
21783 3. Otherwise, indent relatively to current level, if
21784 `org-adapt-indentation' is non-nil, or to left margin.
21786 - On a blank line at the end of an element, indent according to
21787 the type of the element. More precisely
21789 1. If element is a plain list, an item, or a footnote
21790 definition, indent like the very last element within.
21792 2. If element is a paragraph, indent like its last non blank
21793 line.
21795 3. Otherwise, indent like its very first line.
21797 - In the code part of a source block, use language major mode
21798 to indent current line if `org-src-tab-acts-natively' is
21799 non-nil. If it is nil, do nothing.
21801 - Otherwise, indent like the first non-blank line above.
21803 The function doesn't indent an item as it could break the whole
21804 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21805 `\\[org-shiftmetaright]'.
21807 Also align node properties according to `org-property-format'."
21808 (interactive)
21809 (cond
21810 ((org-at-heading-p) 'noindent)
21812 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21813 (type (org-element-type element)))
21814 (cond ((and (memq type '(plain-list item))
21815 (= (line-beginning-position)
21816 (org-element-property :post-affiliated element)))
21817 'noindent)
21818 ((and (eq type 'latex-environment)
21819 (>= (point) (org-element-property :post-affiliated element))
21820 (< (point) (org-with-wide-buffer
21821 (goto-char (org-element-property :end element))
21822 (skip-chars-backward " \r\t\n")
21823 (line-beginning-position 2))))
21824 'noindent)
21825 ((and (eq type 'src-block)
21826 org-src-tab-acts-natively
21827 (> (line-beginning-position)
21828 (org-element-property :post-affiliated element))
21829 (< (line-beginning-position)
21830 (org-with-wide-buffer
21831 (goto-char (org-element-property :end element))
21832 (skip-chars-backward " \r\t\n")
21833 (line-beginning-position))))
21834 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21836 (let ((column (org--get-expected-indentation element nil)))
21837 ;; Preserve current column.
21838 (if (<= (current-column) (current-indentation))
21839 (indent-line-to column)
21840 (save-excursion (indent-line-to column))))
21841 ;; Align node property. Also preserve current column.
21842 (when (eq type 'node-property)
21843 (let ((column (current-column)))
21844 (org--align-node-property)
21845 (org-move-to-column column)))))))))
21847 (defun org-indent-region (start end)
21848 "Indent each non-blank line in the region.
21849 Called from a program, START and END specify the region to
21850 indent. The function will not indent contents of example blocks,
21851 verse blocks and export blocks as leading white spaces are
21852 assumed to be significant there."
21853 (interactive "r")
21854 (save-excursion
21855 (goto-char start)
21856 (skip-chars-forward " \r\t\n")
21857 (unless (eobp) (beginning-of-line))
21858 (let ((indent-to
21859 (lambda (ind pos)
21860 ;; Set IND as indentation for all lines between point and
21861 ;; POS. Blank lines are ignored. Leave point after POS
21862 ;; once done.
21863 (let ((limit (copy-marker pos)))
21864 (while (< (point) limit)
21865 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21866 (forward-line))
21867 (set-marker limit nil))))
21868 (end (copy-marker end)))
21869 (while (< (point) end)
21870 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21871 (let* ((element (org-element-at-point))
21872 (type (org-element-type element))
21873 (element-end (copy-marker (org-element-property :end element)))
21874 (ind (org--get-expected-indentation element nil)))
21875 (cond
21876 ;; Element indented as a single block. Example blocks
21877 ;; preserving indentation are a special case since the
21878 ;; "contents" must not be indented whereas the block
21879 ;; boundaries can.
21880 ((or (memq type '(export-block latex-environment))
21881 (and (eq type 'example-block)
21882 (not
21883 (or org-src-preserve-indentation
21884 (org-element-property :preserve-indent element)))))
21885 (let ((offset (- ind (org-get-indentation))))
21886 (unless (zerop offset)
21887 (indent-rigidly (org-element-property :begin element)
21888 (org-element-property :end element)
21889 offset)))
21890 (goto-char element-end))
21891 ;; Elements indented line wise. Be sure to exclude
21892 ;; example blocks (preserving indentation) and source
21893 ;; blocks from this category as they are treated
21894 ;; specially later.
21895 ((or (memq type '(paragraph table table-row))
21896 (not (or (org-element-property :contents-begin element)
21897 (memq type '(example-block src-block)))))
21898 (when (eq type 'node-property)
21899 (org--align-node-property)
21900 (beginning-of-line))
21901 (funcall indent-to ind (min element-end end)))
21902 ;; Elements consisting of three parts: before the
21903 ;; contents, the contents, and after the contents. The
21904 ;; contents are treated specially, according to the
21905 ;; element type, or not indented at all. Other parts are
21906 ;; indented as a single block.
21908 (let* ((post (copy-marker
21909 (org-element-property :post-affiliated element)))
21910 (cbeg
21911 (copy-marker
21912 (cond
21913 ((not (org-element-property :contents-begin element))
21914 ;; Fake contents for source blocks.
21915 (org-with-wide-buffer
21916 (goto-char post)
21917 (line-beginning-position 2)))
21918 ((memq type '(footnote-definition item plain-list))
21919 ;; Contents in these elements could start on
21920 ;; the same line as the beginning of the
21921 ;; element. Make sure we start indenting
21922 ;; from the second line.
21923 (org-with-wide-buffer
21924 (goto-char post)
21925 (end-of-line)
21926 (skip-chars-forward " \r\t\n")
21927 (if (eobp) (point) (line-beginning-position))))
21928 (t (org-element-property :contents-begin element)))))
21929 (cend (copy-marker
21930 (or (org-element-property :contents-end element)
21931 ;; Fake contents for source blocks.
21932 (org-with-wide-buffer
21933 (goto-char element-end)
21934 (skip-chars-backward " \r\t\n")
21935 (line-beginning-position)))
21936 t)))
21937 ;; Do not change items indentation individually as it
21938 ;; might break the list as a whole. On the other
21939 ;; hand, when at a plain list, indent it as a whole.
21940 (cond ((eq type 'plain-list)
21941 (let ((offset (- ind (org-get-indentation))))
21942 (unless (zerop offset)
21943 (indent-rigidly (org-element-property :begin element)
21944 (org-element-property :end element)
21945 offset))
21946 (goto-char cbeg)))
21947 ((eq type 'item) (goto-char cbeg))
21948 (t (funcall indent-to ind (min cbeg end))))
21949 (when (< (point) end)
21950 (cl-case type
21951 ((example-block verse-block))
21952 (src-block
21953 ;; In a source block, indent source code
21954 ;; according to language major mode, but only if
21955 ;; `org-src-tab-acts-natively' is non-nil.
21956 (when (and (< (point) end) org-src-tab-acts-natively)
21957 (ignore-errors
21958 (org-babel-do-in-edit-buffer
21959 (indent-region (point-min) (point-max))))))
21960 (t (org-indent-region (point) (min cend end))))
21961 (goto-char (min cend end))
21962 (when (< (point) end)
21963 (funcall indent-to ind (min element-end end))))
21964 (set-marker post nil)
21965 (set-marker cbeg nil)
21966 (set-marker cend nil))))
21967 (set-marker element-end nil))))
21968 (set-marker end nil))))
21970 (defun org-indent-drawer ()
21971 "Indent the drawer at point."
21972 (interactive)
21973 (unless (save-excursion
21974 (beginning-of-line)
21975 (looking-at-p org-drawer-regexp))
21976 (user-error "Not at a drawer"))
21977 (let ((element (org-element-at-point)))
21978 (unless (memq (org-element-type element) '(drawer property-drawer))
21979 (user-error "Not at a drawer"))
21980 (org-with-wide-buffer
21981 (org-indent-region (org-element-property :begin element)
21982 (org-element-property :end element))))
21983 (message "Drawer at point indented"))
21985 (defun org-indent-block ()
21986 "Indent the block at point."
21987 (interactive)
21988 (unless (save-excursion
21989 (beginning-of-line)
21990 (let ((case-fold-search t))
21991 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21992 (user-error "Not at a block"))
21993 (let ((element (org-element-at-point)))
21994 (unless (memq (org-element-type element)
21995 '(comment-block center-block dynamic-block example-block
21996 export-block quote-block special-block
21997 src-block verse-block))
21998 (user-error "Not at a block"))
21999 (org-with-wide-buffer
22000 (org-indent-region (org-element-property :begin element)
22001 (org-element-property :end element))))
22002 (message "Block at point indented"))
22005 ;;; Filling
22007 ;; We use our own fill-paragraph and auto-fill functions.
22009 ;; `org-fill-paragraph' relies on adaptive filling and context
22010 ;; checking. Appropriate `fill-prefix' is computed with
22011 ;; `org-adaptive-fill-function'.
22013 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22014 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22015 ;; `org-adaptive-fill-function' value. Internally,
22016 ;; `org-comment-line-break-function' breaks the line.
22018 ;; `org-setup-filling' installs filling and auto-filling related
22019 ;; variables during `org-mode' initialization.
22021 (defun org-setup-filling ()
22022 (require 'org-element)
22023 ;; Prevent auto-fill from inserting unwanted new items.
22024 (when (boundp 'fill-nobreak-predicate)
22025 (setq-local
22026 fill-nobreak-predicate
22027 (org-uniquify
22028 (append fill-nobreak-predicate
22029 '(org-fill-line-break-nobreak-p
22030 org-fill-n-macro-as-item-nobreak-p
22031 org-fill-paragraph-with-timestamp-nobreak-p)))))
22032 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22033 (setq-local paragraph-start paragraph-ending)
22034 (setq-local paragraph-separate paragraph-ending))
22035 (setq-local fill-paragraph-function 'org-fill-paragraph)
22036 (setq-local auto-fill-inhibit-regexp nil)
22037 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22038 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22039 (setq-local comment-line-break-function 'org-comment-line-break-function))
22041 (defun org-fill-line-break-nobreak-p ()
22042 "Non-nil when a new line at point would create an Org line break."
22043 (save-excursion
22044 (skip-chars-backward "[ \t]")
22045 (skip-chars-backward "\\\\")
22046 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22048 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22049 "Non-nil when a new line at point would split a timestamp."
22050 (and (org-at-timestamp-p 'lax)
22051 (not (looking-at org-ts-regexp-both))))
22053 (defun org-fill-n-macro-as-item-nobreak-p ()
22054 "Non-nil when a new line at point would create a new list."
22055 ;; During export, a "n" macro followed by a dot or a closing
22056 ;; parenthesis can end up being parsed as a new list item.
22057 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22059 (defvar orgtbl-line-start-regexp) ; From org-table.el
22060 (defun org-adaptive-fill-function ()
22061 "Compute a fill prefix for the current line.
22062 Return fill prefix, as a string, or nil if current line isn't
22063 meant to be filled. For convenience, if `adaptive-fill-regexp'
22064 matches in paragraphs or comments, use it."
22065 (org-with-wide-buffer
22066 (unless (org-at-heading-p)
22067 (let* ((p (line-beginning-position))
22068 (element (save-excursion
22069 (beginning-of-line)
22070 (org-element-at-point)))
22071 (type (org-element-type element))
22072 (post-affiliated (org-element-property :post-affiliated element)))
22073 (unless (< p post-affiliated)
22074 (cl-case type
22075 (comment
22076 (save-excursion
22077 (beginning-of-line)
22078 (looking-at "[ \t]*")
22079 (concat (match-string 0) "# ")))
22080 (footnote-definition "")
22081 ((item plain-list)
22082 (make-string (org-list-item-body-column post-affiliated) ?\s))
22083 (paragraph
22084 ;; Fill prefix is usually the same as the current line,
22085 ;; unless the paragraph is at the beginning of an item.
22086 (let ((parent (org-element-property :parent element)))
22087 (save-excursion
22088 (beginning-of-line)
22089 (cond ((eq (org-element-type parent) 'item)
22090 (make-string (org-list-item-body-column
22091 (org-element-property :begin parent))
22092 ?\s))
22093 ((and adaptive-fill-regexp
22094 ;; Locally disable
22095 ;; `adaptive-fill-function' to let
22096 ;; `fill-context-prefix' handle
22097 ;; `adaptive-fill-regexp' variable.
22098 (let (adaptive-fill-function)
22099 (fill-context-prefix
22100 post-affiliated
22101 (org-element-property :end element)))))
22102 ((looking-at "[ \t]+") (match-string 0))
22103 (t "")))))
22104 (comment-block
22105 ;; Only fill contents if P is within block boundaries.
22106 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22107 (forward-line)
22108 (point)))
22109 (cend (save-excursion
22110 (goto-char (org-element-property :end element))
22111 (skip-chars-backward " \r\t\n")
22112 (line-beginning-position))))
22113 (when (and (>= p cbeg) (< p cend))
22114 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22115 (match-string 0)
22116 ""))))))))))
22118 (defun org-fill-element (&optional justify)
22119 "Fill element at point, when applicable.
22121 This function only applies to comment blocks, comments, example
22122 blocks and paragraphs. Also, as a special case, re-align table
22123 when point is at one.
22125 If JUSTIFY is non-nil (interactively, with prefix argument),
22126 justify as well. If `sentence-end-double-space' is non-nil, then
22127 period followed by one space does not end a sentence, so don't
22128 break a line there. The variable `fill-column' controls the
22129 width for filling.
22131 For convenience, when point is at a plain list, an item or
22132 a footnote definition, try to fill the first paragraph within."
22133 (with-syntax-table org-mode-transpose-word-syntax-table
22134 ;; Move to end of line in order to get the first paragraph within
22135 ;; a plain list or a footnote definition.
22136 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22137 ;; First check if point is in a blank line at the beginning of
22138 ;; the buffer. In that case, ignore filling.
22139 (cl-case (org-element-type element)
22140 ;; Use major mode filling function is src blocks.
22141 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22142 ;; Align Org tables, leave table.el tables as-is.
22143 (table-row (org-table-align) t)
22144 (table
22145 (when (eq (org-element-property :type element) 'org)
22146 (save-excursion
22147 (goto-char (org-element-property :post-affiliated element))
22148 (org-table-align)))
22150 (paragraph
22151 ;; Paragraphs may contain `line-break' type objects.
22152 (let ((beg (max (point-min)
22153 (org-element-property :contents-begin element)))
22154 (end (min (point-max)
22155 (org-element-property :contents-end element))))
22156 ;; Do nothing if point is at an affiliated keyword.
22157 (if (< (line-end-position) beg) t
22158 ;; Fill paragraph, taking line breaks into account.
22159 (save-excursion
22160 (goto-char beg)
22161 (let ((cuts (list beg)))
22162 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22163 (when (eq 'line-break
22164 (org-element-type
22165 (save-excursion (backward-char)
22166 (org-element-context))))
22167 (push (point) cuts)))
22168 (dolist (c (delq end cuts))
22169 (fill-region-as-paragraph c end justify)
22170 (setq end c))))
22171 t)))
22172 ;; Contents of `comment-block' type elements should be
22173 ;; filled as plain text, but only if point is within block
22174 ;; markers.
22175 (comment-block
22176 (let* ((case-fold-search t)
22177 (beg (save-excursion
22178 (goto-char (org-element-property :begin element))
22179 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22180 (forward-line)
22181 (point)))
22182 (end (save-excursion
22183 (goto-char (org-element-property :end element))
22184 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22185 (line-beginning-position))))
22186 (if (or (< (point) beg) (> (point) end)) t
22187 (fill-region-as-paragraph
22188 (save-excursion (end-of-line)
22189 (re-search-backward "^[ \t]*$" beg 'move)
22190 (line-beginning-position))
22191 (save-excursion (beginning-of-line)
22192 (re-search-forward "^[ \t]*$" end 'move)
22193 (line-beginning-position))
22194 justify))))
22195 ;; Fill comments.
22196 (comment
22197 (let ((begin (org-element-property :post-affiliated element))
22198 (end (org-element-property :end element)))
22199 (when (and (>= (point) begin) (<= (point) end))
22200 (let ((begin (save-excursion
22201 (end-of-line)
22202 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22203 (progn (forward-line) (point))
22204 begin)))
22205 (end (save-excursion
22206 (end-of-line)
22207 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22208 (1- (line-beginning-position))
22209 (skip-chars-backward " \r\t\n")
22210 (line-end-position)))))
22211 ;; Do not fill comments when at a blank line.
22212 (when (> end begin)
22213 (let ((fill-prefix
22214 (save-excursion
22215 (beginning-of-line)
22216 (looking-at "[ \t]*#")
22217 (let ((comment-prefix (match-string 0)))
22218 (goto-char (match-end 0))
22219 (if (looking-at adaptive-fill-regexp)
22220 (concat comment-prefix (match-string 0))
22221 (concat comment-prefix " "))))))
22222 (save-excursion
22223 (fill-region-as-paragraph begin end justify))))))
22225 ;; Ignore every other element.
22226 (otherwise t)))))
22228 (defun org-fill-paragraph (&optional justify region)
22229 "Fill element at point, when applicable.
22231 This function only applies to comment blocks, comments, example
22232 blocks and paragraphs. Also, as a special case, re-align table
22233 when point is at one.
22235 For convenience, when point is at a plain list, an item or
22236 a footnote definition, try to fill the first paragraph within.
22238 If JUSTIFY is non-nil (interactively, with prefix argument),
22239 justify as well. If `sentence-end-double-space' is non-nil, then
22240 period followed by one space does not end a sentence, so don't
22241 break a line there. The variable `fill-column' controls the
22242 width for filling.
22244 The REGION argument is non-nil if called interactively; in that
22245 case, if Transient Mark mode is enabled and the mark is active,
22246 fill each of the elements in the active region, instead of just
22247 filling the current element."
22248 (interactive (progn
22249 (barf-if-buffer-read-only)
22250 (list (if current-prefix-arg 'full) t)))
22251 (cond
22252 ((and region transient-mark-mode mark-active
22253 (not (eq (region-beginning) (region-end))))
22254 (let ((origin (point-marker))
22255 (start (region-beginning)))
22256 (unwind-protect
22257 (progn
22258 (goto-char (region-end))
22259 (while (> (point) start)
22260 (org-backward-paragraph)
22261 (org-fill-element justify)))
22262 (goto-char origin)
22263 (set-marker origin nil))))
22264 (t (org-fill-element justify))))
22266 (defun org-auto-fill-function ()
22267 "Auto-fill function."
22268 ;; Check if auto-filling is meaningful.
22269 (let ((fc (current-fill-column)))
22270 (when (and fc (> (current-column) fc))
22271 (let* ((fill-prefix (org-adaptive-fill-function))
22272 ;; Enforce empty fill prefix, if required. Otherwise, it
22273 ;; will be computed again.
22274 (adaptive-fill-mode (not (equal fill-prefix ""))))
22275 (when fill-prefix (do-auto-fill))))))
22277 (defun org-comment-line-break-function (&optional soft)
22278 "Break line at point and indent, continuing comment if within one.
22279 The inserted newline is marked hard if variable
22280 `use-hard-newlines' is true, unless optional argument SOFT is
22281 non-nil."
22282 (if soft (insert-and-inherit ?\n) (newline 1))
22283 (save-excursion (forward-char -1) (delete-horizontal-space))
22284 (delete-horizontal-space)
22285 (indent-to-left-margin)
22286 (insert-before-markers-and-inherit fill-prefix))
22289 ;;; Fixed Width Areas
22291 (defun org-toggle-fixed-width ()
22292 "Toggle fixed-width markup.
22294 Add or remove fixed-width markup on current line, whenever it
22295 makes sense. Return an error otherwise.
22297 If a region is active and if it contains only fixed-width areas
22298 or blank lines, remove all fixed-width markup in it. If the
22299 region contains anything else, convert all non-fixed-width lines
22300 to fixed-width ones.
22302 Blank lines at the end of the region are ignored unless the
22303 region only contains such lines."
22304 (interactive)
22305 (if (not (org-region-active-p))
22306 ;; No region:
22308 ;; Remove fixed width marker only in a fixed-with element.
22310 ;; Add fixed width maker in paragraphs, in blank lines after
22311 ;; elements or at the beginning of a headline or an inlinetask,
22312 ;; and before any one-line elements (e.g., a clock).
22313 (progn
22314 (beginning-of-line)
22315 (let* ((element (org-element-at-point))
22316 (type (org-element-type element)))
22317 (cond
22318 ((and (eq type 'fixed-width)
22319 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22320 (replace-match
22321 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22322 ((and (memq type '(babel-call clock comment diary-sexp headline
22323 horizontal-rule keyword paragraph
22324 planning))
22325 (<= (org-element-property :post-affiliated element) (point)))
22326 (skip-chars-forward " \t")
22327 (insert ": "))
22328 ((and (looking-at-p "[ \t]*$")
22329 (or (eq type 'inlinetask)
22330 (save-excursion
22331 (skip-chars-forward " \r\t\n")
22332 (<= (org-element-property :end element) (point)))))
22333 (delete-region (point) (line-end-position))
22334 (org-indent-line)
22335 (insert ": "))
22336 (t (user-error "Cannot insert a fixed-width line here")))))
22337 ;; Region active.
22338 (let* ((begin (save-excursion
22339 (goto-char (region-beginning))
22340 (line-beginning-position)))
22341 (end (copy-marker
22342 (save-excursion
22343 (goto-char (region-end))
22344 (unless (eolp) (beginning-of-line))
22345 (if (save-excursion (re-search-backward "\\S-" begin t))
22346 (progn (skip-chars-backward " \r\t\n") (point))
22347 (point)))))
22348 (all-fixed-width-p
22349 (catch 'not-all-p
22350 (save-excursion
22351 (goto-char begin)
22352 (skip-chars-forward " \r\t\n")
22353 (when (eobp) (throw 'not-all-p nil))
22354 (while (< (point) end)
22355 (let ((element (org-element-at-point)))
22356 (if (eq (org-element-type element) 'fixed-width)
22357 (goto-char (org-element-property :end element))
22358 (throw 'not-all-p nil))))
22359 t))))
22360 (if all-fixed-width-p
22361 (save-excursion
22362 (goto-char begin)
22363 (while (< (point) end)
22364 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22365 (replace-match
22366 "" nil nil nil
22367 (if (= (line-end-position) (match-end 0)) 0 1)))
22368 (forward-line)))
22369 (let ((min-ind (point-max)))
22370 ;; Find minimum indentation across all lines.
22371 (save-excursion
22372 (goto-char begin)
22373 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22374 (setq min-ind 0)
22375 (catch 'zerop
22376 (while (< (point) end)
22377 (unless (looking-at-p "[ \t]*$")
22378 (let ((ind (org-get-indentation)))
22379 (setq min-ind (min min-ind ind))
22380 (when (zerop ind) (throw 'zerop t))))
22381 (forward-line)))))
22382 ;; Loop over all lines and add fixed-width markup everywhere
22383 ;; but in fixed-width lines.
22384 (save-excursion
22385 (goto-char begin)
22386 (while (< (point) end)
22387 (cond
22388 ((org-at-heading-p)
22389 (insert ": ")
22390 (forward-line)
22391 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22392 (insert ":")
22393 (forward-line)))
22394 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22395 (let* ((element (org-element-at-point))
22396 (element-end (org-element-property :end element)))
22397 (if (eq (org-element-type element) 'fixed-width)
22398 (progn (goto-char element-end)
22399 (skip-chars-backward " \r\t\n")
22400 (forward-line))
22401 (let ((limit (min end element-end)))
22402 (while (< (point) limit)
22403 (org-move-to-column min-ind t)
22404 (insert ": ")
22405 (forward-line))))))
22407 (org-move-to-column min-ind t)
22408 (insert ": ")
22409 (forward-line)))))))
22410 (set-marker end nil))))
22413 ;;; Blocks
22415 (defun org-block-map (function &optional start end)
22416 "Call FUNCTION at the head of all source blocks in the current buffer.
22417 Optional arguments START and END can be used to limit the range."
22418 (let ((start (or start (point-min)))
22419 (end (or end (point-max))))
22420 (save-excursion
22421 (goto-char start)
22422 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22423 (save-excursion
22424 (save-match-data
22425 (goto-char (match-beginning 0))
22426 (funcall function)))))))
22428 (defun org-next-block (arg &optional backward block-regexp)
22429 "Jump to the next block.
22431 With a prefix argument ARG, jump forward ARG many blocks.
22433 When BACKWARD is non-nil, jump to the previous block.
22435 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22436 Match data is set according to this regexp when the function
22437 returns.
22439 Return point at beginning of the opening line of found block.
22440 Throw an error if no block is found."
22441 (interactive "p")
22442 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22443 (case-fold-search t)
22444 (search-fn (if backward #'re-search-backward #'re-search-forward))
22445 (count (or arg 1))
22446 (origin (point))
22447 last-element)
22448 (if backward (beginning-of-line) (end-of-line))
22449 (while (and (> count 0) (funcall search-fn re nil t))
22450 (let ((element (save-excursion
22451 (goto-char (match-beginning 0))
22452 (save-match-data (org-element-at-point)))))
22453 (when (and (memq (org-element-type element)
22454 '(center-block comment-block dynamic-block
22455 example-block export-block quote-block
22456 special-block src-block verse-block))
22457 (<= (match-beginning 0)
22458 (org-element-property :post-affiliated element)))
22459 (setq last-element element)
22460 (cl-decf count))))
22461 (if (= count 0)
22462 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22463 (save-match-data (org-show-context)))
22464 (goto-char origin)
22465 (user-error "No %s code blocks" (if backward "previous" "further")))))
22467 (defun org-previous-block (arg &optional block-regexp)
22468 "Jump to the previous block.
22469 With a prefix argument ARG, jump backward ARG many source blocks.
22470 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22471 (interactive "p")
22472 (org-next-block arg t block-regexp))
22475 ;;; Comments
22477 ;; Org comments syntax is quite complex. It requires the entire line
22478 ;; to be just a comment. Also, even with the right syntax at the
22479 ;; beginning of line, some elements (e.g., verse-block or
22480 ;; example-block) don't accept comments. Usual Emacs comment commands
22481 ;; cannot cope with those requirements. Therefore, Org replaces them.
22483 ;; Org still relies on `comment-dwim', but cannot trust
22484 ;; `comment-only-p'. So, `comment-region-function' and
22485 ;; `uncomment-region-function' both point
22486 ;; to`org-comment-or-uncomment-region'. Eventually,
22487 ;; `org-insert-comment' takes care of insertion of comments at the
22488 ;; beginning of line.
22490 ;; `org-setup-comments-handling' install comments related variables
22491 ;; during `org-mode' initialization.
22493 (defun org-setup-comments-handling ()
22494 (interactive)
22495 (setq-local comment-use-syntax nil)
22496 (setq-local comment-start "# ")
22497 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22498 (setq-local comment-insert-comment-function 'org-insert-comment)
22499 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22500 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22502 (defun org-insert-comment ()
22503 "Insert an empty comment above current line.
22504 If the line is empty, insert comment at its beginning. When
22505 point is within a source block, comment according to the related
22506 major mode."
22507 (if (let ((element (org-element-at-point)))
22508 (and (eq (org-element-type element) 'src-block)
22509 (< (save-excursion
22510 (goto-char (org-element-property :post-affiliated element))
22511 (line-end-position))
22512 (point))
22513 (> (save-excursion
22514 (goto-char (org-element-property :end element))
22515 (skip-chars-backward " \r\t\n")
22516 (line-beginning-position))
22517 (point))))
22518 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22519 (beginning-of-line)
22520 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22521 (open-line 1))
22522 (org-indent-line)
22523 (insert "# ")))
22525 (defvar comment-empty-lines) ; From newcomment.el.
22526 (defun org-comment-or-uncomment-region (beg end &rest _)
22527 "Comment or uncomment each non-blank line in the region.
22528 Uncomment each non-blank line between BEG and END if it only
22529 contains commented lines. Otherwise, comment them. If region is
22530 strictly within a source block, use appropriate comment syntax."
22531 (if (let ((element (org-element-at-point)))
22532 (and (eq (org-element-type element) 'src-block)
22533 (< (save-excursion
22534 (goto-char (org-element-property :post-affiliated element))
22535 (line-end-position))
22536 beg)
22537 (>= (save-excursion
22538 (goto-char (org-element-property :end element))
22539 (skip-chars-backward " \r\t\n")
22540 (line-beginning-position))
22541 end)))
22542 ;; Translate region boundaries for the Org buffer to the source
22543 ;; buffer.
22544 (let ((offset (- end beg)))
22545 (save-excursion
22546 (goto-char beg)
22547 (org-babel-do-in-edit-buffer
22548 (comment-or-uncomment-region (point) (+ offset (point))))))
22549 (save-restriction
22550 ;; Restrict region
22551 (narrow-to-region (save-excursion (goto-char beg)
22552 (skip-chars-forward " \r\t\n" end)
22553 (line-beginning-position))
22554 (save-excursion (goto-char end)
22555 (skip-chars-backward " \r\t\n" beg)
22556 (line-end-position)))
22557 (let ((uncommentp
22558 ;; UNCOMMENTP is non-nil when every non blank line between
22559 ;; BEG and END is a comment.
22560 (save-excursion
22561 (goto-char (point-min))
22562 (while (and (not (eobp))
22563 (let ((element (org-element-at-point)))
22564 (and (eq (org-element-type element) 'comment)
22565 (goto-char (min (point-max)
22566 (org-element-property
22567 :end element)))))))
22568 (eobp))))
22569 (if uncommentp
22570 ;; Only blank lines and comments in region: uncomment it.
22571 (save-excursion
22572 (goto-char (point-min))
22573 (while (not (eobp))
22574 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22575 (replace-match "" nil nil nil 1))
22576 (forward-line)))
22577 ;; Comment each line in region.
22578 (let ((min-indent (point-max)))
22579 ;; First find the minimum indentation across all lines.
22580 (save-excursion
22581 (goto-char (point-min))
22582 (while (and (not (eobp)) (not (zerop min-indent)))
22583 (unless (looking-at "[ \t]*$")
22584 (setq min-indent (min min-indent (current-indentation))))
22585 (forward-line)))
22586 ;; Then loop over all lines.
22587 (save-excursion
22588 (goto-char (point-min))
22589 (while (not (eobp))
22590 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22591 ;; Don't get fooled by invisible text (e.g. link path)
22592 ;; when moving to column MIN-INDENT.
22593 (let ((buffer-invisibility-spec nil))
22594 (org-move-to-column min-indent t))
22595 (insert comment-start))
22596 (forward-line)))))))))
22598 (defun org-comment-dwim (_arg)
22599 "Call the comment command you mean.
22600 Call `org-toggle-comment' if on a heading, otherwise call
22601 `comment-dwim', within a source edit buffer if needed."
22602 (interactive "*P")
22603 (cond ((org-at-heading-p)
22604 (call-interactively #'org-toggle-comment))
22605 ((org-in-src-block-p)
22606 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22607 (t (call-interactively #'comment-dwim))))
22610 ;;; Timestamps API
22612 ;; This section contains tools to operate on, or create, timestamp
22613 ;; objects, as returned by, e.g. `org-element-context'.
22615 (defun org-timestamp-from-string (s)
22616 "Convert Org timestamp S, as a string, into a timestamp object.
22617 Return nil if S is not a valid timestamp string."
22618 (when (org-string-nw-p s)
22619 (with-temp-buffer
22620 (save-excursion (insert s))
22621 (org-element-timestamp-parser))))
22623 (defun org-timestamp-from-time (time &optional with-time inactive)
22624 "Convert a time value into a timestamp object.
22626 TIME is an Emacs internal time representation, as returned, e.g.,
22627 by `current-time'.
22629 When optional argument WITH-TIME is non-nil, return a timestamp
22630 object with a time part, i.e., with hours and minutes.
22632 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22633 return an active timestamp."
22634 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22635 (org-element-create 'timestamp
22636 (list :type (if inactive 'inactive 'active)
22637 :year-start year
22638 :month-start month
22639 :day-start day
22640 :hour-start (and with-time hour)
22641 :minute-start (and with-time minute)))))
22643 (defun org-timestamp-to-time (timestamp &optional end)
22644 "Convert TIMESTAMP object into an Emacs internal time value.
22645 Use end of date range or time range when END is non-nil.
22646 Otherwise, use its start."
22647 (apply #'encode-time
22648 (cons 0
22649 (mapcar
22650 (lambda (prop) (or (org-element-property prop timestamp) 0))
22651 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22652 '(:minute-start :hour-start :day-start :month-start
22653 :year-start))))))
22655 (defun org-timestamp-has-time-p (timestamp)
22656 "Non-nil when TIMESTAMP has a time specified."
22657 (org-element-property :hour-start timestamp))
22659 (defun org-timestamp-format (timestamp format &optional end utc)
22660 "Format a TIMESTAMP object into a string.
22662 FORMAT is a format specifier to be passed to
22663 `format-time-string'.
22665 When optional argument END is non-nil, use end of date-range or
22666 time-range, if possible.
22668 When optional argument UTC is non-nil, time is be expressed as
22669 Universal Time."
22670 (format-time-string format (org-timestamp-to-time timestamp end)
22671 (and utc t)))
22673 (defun org-timestamp-split-range (timestamp &optional end)
22674 "Extract a TIMESTAMP object from a date or time range.
22676 END, when non-nil, means extract the end of the range.
22677 Otherwise, extract its start.
22679 Return a new timestamp object."
22680 (let ((type (org-element-property :type timestamp)))
22681 (if (memq type '(active inactive diary)) timestamp
22682 (let ((split-ts (org-element-copy timestamp)))
22683 ;; Set new type.
22684 (org-element-put-property
22685 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22686 ;; Copy start properties over end properties if END is
22687 ;; non-nil. Otherwise, copy end properties over `start' ones.
22688 (let ((p-alist '((:minute-start . :minute-end)
22689 (:hour-start . :hour-end)
22690 (:day-start . :day-end)
22691 (:month-start . :month-end)
22692 (:year-start . :year-end))))
22693 (dolist (p-cell p-alist)
22694 (org-element-put-property
22695 split-ts
22696 (funcall (if end #'car #'cdr) p-cell)
22697 (org-element-property
22698 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22699 ;; Eventually refresh `:raw-value'.
22700 (org-element-put-property split-ts :raw-value nil)
22701 (org-element-put-property
22702 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22704 (defun org-timestamp-translate (timestamp &optional boundary)
22705 "Translate TIMESTAMP object to custom format.
22707 Format string is defined in `org-time-stamp-custom-formats',
22708 which see.
22710 When optional argument BOUNDARY is non-nil, it is either the
22711 symbol `start' or `end'. In this case, only translate the
22712 starting or ending part of TIMESTAMP if it is a date or time
22713 range. Otherwise, translate both parts.
22715 Return timestamp as-is if `org-display-custom-times' is nil or if
22716 it has a `diary' type."
22717 (let ((type (org-element-property :type timestamp)))
22718 (if (or (not org-display-custom-times) (eq type 'diary))
22719 (org-element-interpret-data timestamp)
22720 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22721 org-time-stamp-custom-formats)))
22722 (if (and (not boundary) (memq type '(active-range inactive-range)))
22723 (concat (org-timestamp-format timestamp fmt)
22724 "--"
22725 (org-timestamp-format timestamp fmt t))
22726 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22728 ;;; Other stuff
22730 (defvar reftex-docstruct-symbol)
22731 (defvar org--rds)
22733 (defun org-reftex-citation ()
22734 "Use reftex-citation to insert a citation into the buffer.
22735 This looks for a line like
22737 #+BIBLIOGRAPHY: foo plain option:-d
22739 and derives from it that foo.bib is the bibliography file relevant
22740 for this document. It then installs the necessary environment for RefTeX
22741 to work in this buffer and calls `reftex-citation' to insert a citation
22742 into the buffer.
22744 Export of such citations to both LaTeX and HTML is handled by the contributed
22745 package ox-bibtex by Taru Karttunen."
22746 (interactive)
22747 (let ((reftex-docstruct-symbol 'org--rds)
22748 org--rds bib)
22749 (org-with-wide-buffer
22750 (let ((case-fold-search t)
22751 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22752 (if (not (save-excursion
22753 (or (re-search-forward re nil t)
22754 (re-search-backward re nil t))))
22755 (user-error "No bibliography defined in file")
22756 (setq bib (concat (match-string 1) ".bib")
22757 org--rds (list (list 'bib bib))))))
22758 (call-interactively 'reftex-citation)))
22760 ;;;; Functions extending outline functionality
22762 (defun org-beginning-of-line (&optional n)
22763 "Go to the beginning of the current visible line.
22765 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22766 symbol `reversed', on the first attempt move to where the
22767 headline text starts, and only move to beginning of line when the
22768 cursor is already before the start of the text of the headline.
22770 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22771 start of the text on the second attempt.
22773 With argument N not nil or 1, move forward N - 1 lines first."
22774 (interactive "^p")
22775 (let ((origin (point))
22776 (special (pcase org-special-ctrl-a/e
22777 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22778 deactivate-mark)
22779 ;; First move to a visible line.
22780 (if (bound-and-true-p visual-line-mode)
22781 (beginning-of-visual-line n)
22782 (move-beginning-of-line n)
22783 ;; `move-beginning-of-line' may leave point after invisible
22784 ;; characters if line starts with such of these (e.g., with
22785 ;; a link at column 0). Really move to the beginning of the
22786 ;; current visible line.
22787 (beginning-of-line))
22788 (cond
22789 ;; No special behavior. Point is already at the beginning of
22790 ;; a line, logical or visual.
22791 ((not special))
22792 ;; `beginning-of-visual-line' left point before logical beginning
22793 ;; of line: point is at the beginning of a visual line. Bail
22794 ;; out.
22795 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22796 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22797 ;; At a headline, special position is before the title, but
22798 ;; after any TODO keyword or priority cookie.
22799 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22800 (line-end-position)))
22801 (bol (point)))
22802 (if (eq special 'reversed)
22803 (when (and (= origin bol) (eq last-command this-command))
22804 (goto-char refpos))
22805 (when (or (> origin refpos) (= origin bol))
22806 (goto-char refpos)))))
22807 ((and (looking-at org-list-full-item-re)
22808 (memq (org-element-type (save-match-data (org-element-at-point)))
22809 '(item plain-list)))
22810 ;; Set special position at first white space character after
22811 ;; bullet, and check-box, if any.
22812 (let ((after-bullet
22813 (let ((box (match-end 3)))
22814 (cond ((not box) (match-end 1))
22815 ((eq (char-after box) ?\s) (1+ box))
22816 (t box)))))
22817 (if (eq special 'reversed)
22818 (when (and (= (point) origin) (eq last-command this-command))
22819 (goto-char after-bullet))
22820 (when (or (> origin after-bullet) (= (point) origin))
22821 (goto-char after-bullet)))))
22822 ;; No special context. Point is already at beginning of line.
22823 (t nil))))
22825 (defun org-end-of-line (&optional n)
22826 "Go to the end of the line, but before ellipsis, if any.
22828 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22829 symbol `reversed', ignore tags on the first attempt, and only
22830 move to after the tags when the cursor is already beyond the end
22831 of the headline.
22833 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22834 on the second attempt.
22836 With argument N not nil or 1, move forward N - 1 lines first."
22837 (interactive "^p")
22838 (let ((origin (point))
22839 (special (pcase org-special-ctrl-a/e
22840 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22841 deactivate-mark)
22842 ;; First move to a visible line.
22843 (if (bound-and-true-p visual-line-mode)
22844 (beginning-of-visual-line n)
22845 (move-beginning-of-line n))
22846 (cond
22847 ;; At a headline, with tags.
22848 ((and special
22849 (save-excursion
22850 (beginning-of-line)
22851 (let ((case-fold-search nil))
22852 (looking-at org-complex-heading-regexp)))
22853 (match-end 5))
22854 (let ((tags (save-excursion
22855 (goto-char (match-beginning 5))
22856 (skip-chars-backward " \t")
22857 (point)))
22858 (visual-end (and (bound-and-true-p visual-line-mode)
22859 (save-excursion
22860 (end-of-visual-line)
22861 (point)))))
22862 ;; If `end-of-visual-line' brings us before end of line or
22863 ;; even tags, i.e., the headline spans over multiple visual
22864 ;; lines, move there.
22865 (cond ((and visual-end
22866 (< visual-end tags)
22867 (<= origin visual-end))
22868 (goto-char visual-end))
22869 ((eq special 'reversed)
22870 (if (and (= origin (line-end-position))
22871 (eq this-command last-command))
22872 (goto-char tags)
22873 (end-of-line)))
22875 (if (or (< origin tags) (= origin (line-end-position)))
22876 (goto-char tags)
22877 (end-of-line))))))
22878 ((bound-and-true-p visual-line-mode)
22879 (let ((bol (line-beginning-position)))
22880 (end-of-visual-line)
22881 ;; If `end-of-visual-line' gets us past the ellipsis at the
22882 ;; end of a line, backtrack and use `end-of-line' instead.
22883 (when (/= bol (line-beginning-position))
22884 (goto-char bol)
22885 (end-of-line))))
22886 (t (end-of-line)))))
22888 (defun org-backward-sentence (&optional _arg)
22889 "Go to beginning of sentence, or beginning of table field.
22890 This will call `backward-sentence' or `org-table-beginning-of-field',
22891 depending on context."
22892 (interactive)
22893 (let* ((element (org-element-at-point))
22894 (contents-begin (org-element-property :contents-begin element))
22895 (table (org-element-lineage element '(table) t)))
22896 (if (and table
22897 (> (point) contents-begin)
22898 (<= (point) (org-element-property :contents-end table)))
22899 (call-interactively #'org-table-beginning-of-field)
22900 (save-restriction
22901 (when (and contents-begin
22902 (< (point-min) contents-begin)
22903 (> (point) contents-begin))
22904 (narrow-to-region contents-begin
22905 (org-element-property :contents-end element)))
22906 (call-interactively #'backward-sentence)))))
22908 (defun org-forward-sentence (&optional _arg)
22909 "Go to end of sentence, or end of table field.
22910 This will call `forward-sentence' or `org-table-end-of-field',
22911 depending on context."
22912 (interactive)
22913 (if (and (org-at-heading-p)
22914 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22915 (save-restriction
22916 (narrow-to-region (line-beginning-position) (line-end-position))
22917 (call-interactively #'forward-sentence))
22918 (let* ((element (org-element-at-point))
22919 (contents-end (org-element-property :contents-end element))
22920 (table (org-element-lineage element '(table) t)))
22921 (if (and table
22922 (>= (point) (org-element-property :contents-begin table))
22923 (< (point) contents-end))
22924 (call-interactively #'org-table-end-of-field)
22925 (save-restriction
22926 (when (and contents-end
22927 (> (point-max) contents-end)
22928 ;; Skip blank lines between elements.
22929 (< (org-element-property :end element)
22930 (save-excursion (goto-char contents-end)
22931 (skip-chars-forward " \r\t\n"))))
22932 (narrow-to-region (org-element-property :contents-begin element)
22933 contents-end))
22934 ;; End of heading is considered as the end of a sentence.
22935 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22936 (call-interactively #'forward-sentence)))))))
22938 (defun org-kill-line (&optional _arg)
22939 "Kill line, to tags or end of line."
22940 (interactive)
22941 (cond
22942 ((or (not org-special-ctrl-k)
22943 (bolp)
22944 (not (org-at-heading-p)))
22945 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22946 org-ctrl-k-protect-subtree
22947 (or (eq org-ctrl-k-protect-subtree 'error)
22948 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22949 (user-error "C-k aborted as it would kill a hidden subtree"))
22950 (call-interactively
22951 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22952 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
22953 (kill-region (point) (match-beginning 1))
22954 (org-set-tags nil t))
22955 (t (kill-region (point) (point-at-eol)))))
22957 (defun org-yank (&optional arg)
22958 "Yank. If the kill is a subtree, treat it specially.
22959 This command will look at the current kill and check if is a single
22960 subtree, or a series of subtrees[1]. If it passes the test, and if the
22961 cursor is at the beginning of a line or after the stars of a currently
22962 empty headline, then the yank is handled specially. How exactly depends
22963 on the value of the following variables.
22965 `org-yank-folded-subtrees'
22966 By default, this variable is non-nil, which results in
22967 subtree(s) being folded after insertion, except if doing so
22968 would swallow text after the yanked text.
22970 `org-yank-adjusted-subtrees'
22971 When non-nil (the default value is nil), the subtree will be
22972 promoted or demoted in order to fit into the local outline tree
22973 structure, which means that the level will be adjusted so that it
22974 becomes the smaller one of the two *visible* surrounding headings.
22976 Any prefix to this command will cause `yank' to be called directly with
22977 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22978 will just
22979 plainly yank the text as it is.
22981 \[1] The test checks if the first non-white line is a heading
22982 and if there are no other headings with fewer stars."
22983 (interactive "P")
22984 (org-yank-generic 'yank arg))
22986 (defun org-yank-generic (command arg)
22987 "Perform some yank-like command.
22989 This function implements the behavior described in the `org-yank'
22990 documentation. However, it has been generalized to work for any
22991 interactive command with similar behavior."
22993 ;; pretend to be command COMMAND
22994 (setq this-command command)
22996 (if arg
22997 (call-interactively command)
22999 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23000 (and (org-kill-is-subtree-p)
23001 (or (bolp)
23002 (and (looking-at "[ \t]*$")
23003 (string-match
23004 "\\`\\*+\\'"
23005 (buffer-substring (point-at-bol) (point)))))))
23006 swallowp)
23007 (cond
23008 ((and subtreep org-yank-folded-subtrees)
23009 (let ((beg (point))
23010 end)
23011 (if (and subtreep org-yank-adjusted-subtrees)
23012 (org-paste-subtree nil nil 'for-yank)
23013 (call-interactively command))
23015 (setq end (point))
23016 (goto-char beg)
23017 (when (and (bolp) subtreep
23018 (not (setq swallowp
23019 (org-yank-folding-would-swallow-text beg end))))
23020 (org-with-limited-levels
23021 (or (looking-at org-outline-regexp)
23022 (re-search-forward org-outline-regexp-bol end t))
23023 (while (and (< (point) end) (looking-at org-outline-regexp))
23024 (outline-hide-subtree)
23025 (org-cycle-show-empty-lines 'folded)
23026 (condition-case nil
23027 (outline-forward-same-level 1)
23028 (error (goto-char end))))))
23029 (when swallowp
23030 (message
23031 "Inserted text not folded because that would swallow text"))
23033 (goto-char end)
23034 (skip-chars-forward " \t\n\r")
23035 (beginning-of-line 1)
23036 (push-mark beg 'nomsg)))
23037 ((and subtreep org-yank-adjusted-subtrees)
23038 (let ((beg (point-at-bol)))
23039 (org-paste-subtree nil nil 'for-yank)
23040 (push-mark beg 'nomsg)))
23042 (call-interactively command))))))
23044 (defun org-yank-folding-would-swallow-text (beg end)
23045 "Would hide-subtree at BEG swallow any text after END?"
23046 (let (level)
23047 (org-with-limited-levels
23048 (save-excursion
23049 (goto-char beg)
23050 (when (or (looking-at org-outline-regexp)
23051 (re-search-forward org-outline-regexp-bol end t))
23052 (setq level (org-outline-level)))
23053 (goto-char end)
23054 (skip-chars-forward " \t\r\n\v\f")
23055 (not (or (eobp)
23056 (and (bolp) (looking-at-p org-outline-regexp)
23057 (<= (org-outline-level) level))))))))
23059 (defun org-back-to-heading (&optional invisible-ok)
23060 "Call `outline-back-to-heading', but provide a better error message."
23061 (condition-case nil
23062 (outline-back-to-heading invisible-ok)
23063 (error (error "Before first headline at position %d in buffer %s"
23064 (point) (current-buffer)))))
23066 (defun org-before-first-heading-p ()
23067 "Before first heading?"
23068 (save-excursion
23069 (end-of-line)
23070 (null (re-search-backward org-outline-regexp-bol nil t))))
23072 (defun org-at-heading-p (&optional ignored)
23073 (outline-on-heading-p t))
23075 (defun org-in-commented-heading-p (&optional no-inheritance)
23076 "Non-nil if point is under a commented heading.
23077 This function also checks ancestors of the current headline,
23078 unless optional argument NO-INHERITANCE is non-nil."
23079 (cond
23080 ((org-before-first-heading-p) nil)
23081 ((let ((headline (nth 4 (org-heading-components))))
23082 (and headline
23083 (let ((case-fold-search nil))
23084 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23085 headline)))))
23086 (no-inheritance nil)
23088 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23090 (defun org-at-comment-p nil
23091 "Is cursor in a commented line?"
23092 (save-excursion
23093 (save-match-data
23094 (beginning-of-line)
23095 (looking-at "^[ \t]*# "))))
23097 (defun org-at-drawer-p nil
23098 "Is cursor at a drawer keyword?"
23099 (save-excursion
23100 (move-beginning-of-line 1)
23101 (looking-at org-drawer-regexp)))
23103 (defun org-at-block-p nil
23104 "Is cursor at a block keyword?"
23105 (save-excursion
23106 (move-beginning-of-line 1)
23107 (looking-at org-block-regexp)))
23109 (defun org-point-at-end-of-empty-headline ()
23110 "If point is at the end of an empty headline, return t, else nil.
23111 If the heading only contains a TODO keyword, it is still still considered
23112 empty."
23113 (let ((case-fold-search nil))
23114 (and (looking-at "[ \t]*$")
23115 org-todo-line-regexp
23116 (save-excursion
23117 (beginning-of-line)
23118 (looking-at org-todo-line-regexp)
23119 (string= (match-string 3) "")))))
23121 (defun org-at-heading-or-item-p ()
23122 (or (org-at-heading-p) (org-at-item-p)))
23124 (defun org-at-target-p ()
23125 (or (org-in-regexp org-radio-target-regexp)
23126 (org-in-regexp org-target-regexp)))
23127 ;; Compatibility alias with Org versions < 7.8.03
23128 (defalias 'org-on-target-p 'org-at-target-p)
23130 (defun org-up-heading-all (arg)
23131 "Move to the heading line of which the present line is a subheading.
23132 This function considers both visible and invisible heading lines.
23133 With argument, move up ARG levels."
23134 (outline-up-heading arg t))
23136 (defun org-up-heading-safe ()
23137 "Move to the heading line of which the present line is a subheading.
23138 This version will not throw an error. It will return the level of the
23139 headline found, or nil if no higher level is found.
23141 Also, this function will be a lot faster than `outline-up-heading',
23142 because it relies on stars being the outline starters. This can really
23143 make a significant difference in outlines with very many siblings."
23144 (when (ignore-errors (org-back-to-heading t))
23145 (let ((level-up (1- (funcall outline-level))))
23146 (and (> level-up 0)
23147 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23148 (funcall outline-level)))))
23150 (defun org-first-sibling-p ()
23151 "Is this heading the first child of its parents?"
23152 (interactive)
23153 (let ((re org-outline-regexp-bol)
23154 level l)
23155 (unless (org-at-heading-p t)
23156 (user-error "Not at a heading"))
23157 (setq level (funcall outline-level))
23158 (save-excursion
23159 (if (not (re-search-backward re nil t))
23161 (setq l (funcall outline-level))
23162 (< l level)))))
23164 (defun org-goto-sibling (&optional previous)
23165 "Goto the next sibling, even if it is invisible.
23166 When PREVIOUS is set, go to the previous sibling instead. Returns t
23167 when a sibling was found. When none is found, return nil and don't
23168 move point."
23169 (let ((fun (if previous 're-search-backward 're-search-forward))
23170 (pos (point))
23171 (re org-outline-regexp-bol)
23172 level l)
23173 (when (ignore-errors (org-back-to-heading t))
23174 (setq level (funcall outline-level))
23175 (catch 'exit
23176 (or previous (forward-char 1))
23177 (while (funcall fun re nil t)
23178 (setq l (funcall outline-level))
23179 (when (< l level) (goto-char pos) (throw 'exit nil))
23180 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23181 (goto-char pos)
23182 nil))))
23184 (defun org-show-siblings ()
23185 "Show all siblings of the current headline."
23186 (save-excursion
23187 (while (org-goto-sibling) (org-flag-heading nil)))
23188 (save-excursion
23189 (while (org-goto-sibling 'previous)
23190 (org-flag-heading nil))))
23192 (defun org-goto-first-child ()
23193 "Goto the first child, even if it is invisible.
23194 Return t when a child was found. Otherwise don't move point and
23195 return nil."
23196 (let (level (pos (point)) (re org-outline-regexp-bol))
23197 (when (ignore-errors (org-back-to-heading t))
23198 (setq level (outline-level))
23199 (forward-char 1)
23200 (if (and (re-search-forward re nil t) (> (outline-level) level))
23201 (progn (goto-char (match-beginning 0)) t)
23202 (goto-char pos) nil))))
23204 (defun org-show-hidden-entry ()
23205 "Show an entry where even the heading is hidden."
23206 (save-excursion
23207 (org-show-entry)))
23209 (defun org-flag-heading (flag &optional entry)
23210 "Flag the current heading. FLAG non-nil means make invisible.
23211 When ENTRY is non-nil, show the entire entry."
23212 (save-excursion
23213 (org-back-to-heading t)
23214 ;; Check if we should show the entire entry
23215 (if (not entry)
23216 (org-flag-region
23217 (line-end-position 0) (line-end-position) flag 'outline)
23218 (org-show-entry)
23219 (save-excursion
23220 (and (outline-next-heading)
23221 (org-flag-heading nil))))))
23223 (defun org-get-next-sibling ()
23224 "Move to next heading of the same level, and return point.
23225 If there is no such heading, return nil.
23226 This is like outline-next-sibling, but invisible headings are ok."
23227 (let ((level (funcall outline-level)))
23228 (outline-next-heading)
23229 (while (and (not (eobp)) (> (funcall outline-level) level))
23230 (outline-next-heading))
23231 (unless (or (eobp) (< (funcall outline-level) level))
23232 (point))))
23234 (defun org-get-last-sibling ()
23235 "Move to previous heading of the same level, and return point.
23236 If there is no such heading, return nil."
23237 (let ((opoint (point))
23238 (level (funcall outline-level)))
23239 (outline-previous-heading)
23240 (when (and (/= (point) opoint) (outline-on-heading-p t))
23241 (while (and (> (funcall outline-level) level)
23242 (not (bobp)))
23243 (outline-previous-heading))
23244 (unless (< (funcall outline-level) level)
23245 (point)))))
23247 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23248 "Goto to the end of a subtree."
23249 ;; This contains an exact copy of the original function, but it uses
23250 ;; `org-back-to-heading', to make it work also in invisible
23251 ;; trees. And is uses an invisible-ok argument.
23252 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23253 ;; Furthermore, when used inside Org, finding the end of a large subtree
23254 ;; with many children and grandchildren etc, this can be much faster
23255 ;; than the outline version.
23256 (org-back-to-heading invisible-ok)
23257 (let ((first t)
23258 (level (funcall outline-level)))
23259 (if (and (derived-mode-p 'org-mode) (< level 1000))
23260 ;; A true heading (not a plain list item), in Org
23261 ;; This means we can easily find the end by looking
23262 ;; only for the right number of stars. Using a regexp to do
23263 ;; this is so much faster than using a Lisp loop.
23264 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23265 (forward-char 1)
23266 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23267 ;; something else, do it the slow way
23268 (while (and (not (eobp))
23269 (or first (> (funcall outline-level) level)))
23270 (setq first nil)
23271 (outline-next-heading)))
23272 (unless to-heading
23273 (when (memq (preceding-char) '(?\n ?\^M))
23274 ;; Go to end of line before heading
23275 (forward-char -1)
23276 (when (memq (preceding-char) '(?\n ?\^M))
23277 ;; leave blank line before heading
23278 (forward-char -1)))))
23279 (point))
23281 (defun org-end-of-meta-data (&optional full)
23282 "Skip planning line and properties drawer in current entry.
23283 When optional argument FULL is non-nil, also skip empty lines,
23284 clocking lines and regular drawers at the beginning of the
23285 entry."
23286 (org-back-to-heading t)
23287 (forward-line)
23288 (when (looking-at-p org-planning-line-re) (forward-line))
23289 (when (looking-at org-property-drawer-re)
23290 (goto-char (match-end 0))
23291 (forward-line))
23292 (when (and full (not (org-at-heading-p)))
23293 (catch 'exit
23294 (let ((end (save-excursion (outline-next-heading) (point)))
23295 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23296 (while (not (eobp))
23297 (cond ((looking-at-p org-drawer-regexp)
23298 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23299 (forward-line)
23300 (throw 'exit t)))
23301 ((looking-at-p re) (forward-line))
23302 (t (throw 'exit t))))))))
23304 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23305 "Move forward to the ARG'th subheading at same level as this one.
23306 Stop at the first and last subheadings of a superior heading.
23307 Normally this only looks at visible headings, but when INVISIBLE-OK is
23308 non-nil it will also look at invisible ones."
23309 (interactive "p")
23310 (let ((backward? (and arg (< arg 0))))
23311 (if (org-before-first-heading-p)
23312 (if backward? (goto-char (point-min)) (outline-next-heading))
23313 (org-back-to-heading invisible-ok)
23314 (unless backward? (end-of-line)) ;do not match current headline
23315 (let ((level (- (match-end 0) (match-beginning 0) 1))
23316 (f (if backward? #'re-search-backward #'re-search-forward))
23317 (count (if arg (abs arg) 1))
23318 (result (point)))
23319 (while (and (> count 0)
23320 (funcall f org-outline-regexp-bol nil 'move))
23321 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23322 (cond ((< l level) (setq count 0))
23323 ((and (= l level)
23324 (or invisible-ok
23325 (not (org-invisible-p
23326 (line-beginning-position)))))
23327 (cl-decf count)
23328 (when (= l level) (setq result (point)))))))
23329 (goto-char result))
23330 (beginning-of-line))))
23332 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23333 "Move backward to the ARG'th subheading at same level as this one.
23334 Stop at the first and last subheadings of a superior heading."
23335 (interactive "p")
23336 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23338 (defun org-next-visible-heading (arg)
23339 "Move to the next visible heading.
23341 This function wraps `outline-next-visible-heading' with
23342 `org-with-limited-levels' in order to skip over inline tasks and
23343 respect customization of `org-odd-levels-only'."
23344 (interactive "p")
23345 (org-with-limited-levels
23346 (outline-next-visible-heading arg)))
23348 (defun org-previous-visible-heading (arg)
23349 "Move to the previous visible heading.
23351 This function wraps `outline-previous-visible-heading' with
23352 `org-with-limited-levels' in order to skip over inline tasks and
23353 respect customization of `org-odd-levels-only'."
23354 (interactive "p")
23355 (org-with-limited-levels
23356 (outline-previous-visible-heading arg)))
23358 (defun org-forward-paragraph ()
23359 "Move forward to beginning of next paragraph or equivalent.
23361 The function moves point to the beginning of the next visible
23362 structural element, which can be a paragraph, a table, a list
23363 item, etc. It also provides some special moves for convenience:
23365 - On an affiliated keyword, jump to the beginning of the
23366 relative element.
23367 - On an item or a footnote definition, move to the second
23368 element inside, if any.
23369 - On a table or a property drawer, jump after it.
23370 - On a verse or source block, stop after blank lines."
23371 (interactive)
23372 (unless (eobp)
23373 (let* ((deactivate-mark nil)
23374 (element (org-element-at-point))
23375 (type (org-element-type element))
23376 (post-affiliated (org-element-property :post-affiliated element))
23377 (contents-begin (org-element-property :contents-begin element))
23378 (contents-end (org-element-property :contents-end element))
23379 (end (let ((end (org-element-property :end element)) (parent element))
23380 (while (and (setq parent (org-element-property :parent parent))
23381 (= (org-element-property :contents-end parent) end))
23382 (setq end (org-element-property :end parent)))
23383 end)))
23384 (cond ((not element)
23385 (skip-chars-forward " \r\t\n")
23386 (or (eobp) (beginning-of-line)))
23387 ;; On affiliated keywords, move to element's beginning.
23388 ((< (point) post-affiliated)
23389 (goto-char post-affiliated))
23390 ;; At a table row, move to the end of the table. Similarly,
23391 ;; at a node property, move to the end of the property
23392 ;; drawer.
23393 ((memq type '(node-property table-row))
23394 (goto-char (org-element-property
23395 :end (org-element-property :parent element))))
23396 ((memq type '(property-drawer table)) (goto-char end))
23397 ;; Consider blank lines as separators in verse and source
23398 ;; blocks to ease editing.
23399 ((memq type '(src-block verse-block))
23400 (when (eq type 'src-block)
23401 (setq contents-end
23402 (save-excursion (goto-char end)
23403 (skip-chars-backward " \r\t\n")
23404 (line-beginning-position))))
23405 (beginning-of-line)
23406 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23407 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23408 (goto-char end)
23409 (skip-chars-forward " \r\t\n")
23410 (if (= (point) contents-end) (goto-char end)
23411 (beginning-of-line))))
23412 ;; With no contents, just skip element.
23413 ((not contents-begin) (goto-char end))
23414 ;; If contents are invisible, skip the element altogether.
23415 ((org-invisible-p (line-end-position))
23416 (cl-case type
23417 (headline
23418 (org-with-limited-levels (outline-next-visible-heading 1)))
23419 ;; At a plain list, make sure we move to the next item
23420 ;; instead of skipping the whole list.
23421 (plain-list (forward-char)
23422 (org-forward-paragraph))
23423 (otherwise (goto-char end))))
23424 ((>= (point) contents-end) (goto-char end))
23425 ((>= (point) contents-begin)
23426 ;; This can only happen on paragraphs and plain lists.
23427 (cl-case type
23428 (paragraph (goto-char end))
23429 ;; At a plain list, try to move to second element in
23430 ;; first item, if possible.
23431 (plain-list (end-of-line)
23432 (org-forward-paragraph))))
23433 ;; When contents start on the middle of a line (e.g. in
23434 ;; items and footnote definitions), try to reach first
23435 ;; element starting after current line.
23436 ((> (line-end-position) contents-begin)
23437 (end-of-line)
23438 (org-forward-paragraph))
23439 (t (goto-char contents-begin))))))
23441 (defun org-backward-paragraph ()
23442 "Move backward to start of previous paragraph or equivalent.
23444 The function moves point to the beginning of the current
23445 structural element, which can be a paragraph, a table, a list
23446 item, etc., or to the beginning of the previous visible one if
23447 point is already there. It also provides some special moves for
23448 convenience:
23450 - On an affiliated keyword, jump to the first one.
23451 - On a table or a property drawer, move to its beginning.
23452 - On comment, example, export, src and verse blocks, stop
23453 before blank lines."
23454 (interactive)
23455 (unless (bobp)
23456 (let* ((deactivate-mark nil)
23457 (element (org-element-at-point))
23458 (type (org-element-type element))
23459 (contents-end (org-element-property :contents-end element))
23460 (post-affiliated (org-element-property :post-affiliated element))
23461 (begin (org-element-property :begin element))
23462 (special? ;blocks handled specially
23463 (memq type '(comment-block example-block export-block src-block
23464 verse-block)))
23465 (contents-begin
23466 (if special?
23467 ;; These types have no proper contents. Fake line
23468 ;; below the block opening line as contents beginning.
23469 (save-excursion (goto-char begin) (line-beginning-position 2))
23470 (org-element-property :contents-begin element))))
23471 (cond
23472 ((not element) (goto-char (point-min)))
23473 ((= (point) begin)
23474 (backward-char)
23475 (org-backward-paragraph))
23476 ((<= (point) post-affiliated) (goto-char begin))
23477 ;; Special behavior: on a table or a property drawer, move to
23478 ;; its beginning.
23479 ((memq type '(node-property table-row))
23480 (goto-char (org-element-property
23481 :post-affiliated (org-element-property :parent element))))
23482 (special?
23483 (if (<= (point) contents-begin) (goto-char post-affiliated)
23484 ;; Inside a verse block, see blank lines as paragraph
23485 ;; separators.
23486 (let ((origin (point)))
23487 (skip-chars-backward " \r\t\n" contents-begin)
23488 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23489 (skip-chars-forward " \r\t\n" origin)
23490 (if (= (point) origin) (goto-char contents-begin)
23491 (beginning-of-line))))))
23492 ((eq type 'paragraph) (goto-char contents-begin)
23493 ;; When at first paragraph in an item or a footnote definition,
23494 ;; move directly to beginning of line.
23495 (let ((parent-contents
23496 (org-element-property
23497 :contents-begin (org-element-property :parent element))))
23498 (when (and parent-contents (= parent-contents contents-begin))
23499 (beginning-of-line))))
23500 ;; At the end of a greater element, move to the beginning of
23501 ;; the last element within.
23502 ((and contents-end (>= (point) contents-end))
23503 (goto-char (1- contents-end))
23504 (org-backward-paragraph))
23505 (t (goto-char (or post-affiliated begin))))
23506 ;; Ensure we never leave point invisible.
23507 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23509 (defun org-forward-element ()
23510 "Move forward by one element.
23511 Move to the next element at the same level, when possible."
23512 (interactive)
23513 (cond ((eobp) (user-error "Cannot move further down"))
23514 ((org-with-limited-levels (org-at-heading-p))
23515 (let ((origin (point)))
23516 (goto-char (org-end-of-subtree nil t))
23517 (unless (org-with-limited-levels (org-at-heading-p))
23518 (goto-char origin)
23519 (user-error "Cannot move further down"))))
23521 (let* ((elem (org-element-at-point))
23522 (end (org-element-property :end elem))
23523 (parent (org-element-property :parent elem)))
23524 (cond ((and parent (= (org-element-property :contents-end parent) end))
23525 (goto-char (org-element-property :end parent)))
23526 ((integer-or-marker-p end) (goto-char end))
23527 (t (message "No element at point")))))))
23529 (defun org-backward-element ()
23530 "Move backward by one element.
23531 Move to the previous element at the same level, when possible."
23532 (interactive)
23533 (cond ((bobp) (user-error "Cannot move further up"))
23534 ((org-with-limited-levels (org-at-heading-p))
23535 ;; At a headline, move to the previous one, if any, or stay
23536 ;; here.
23537 (let ((origin (point)))
23538 (org-with-limited-levels (org-backward-heading-same-level 1))
23539 ;; When current headline has no sibling above, move to its
23540 ;; parent.
23541 (when (= (point) origin)
23542 (or (org-with-limited-levels (org-up-heading-safe))
23543 (progn (goto-char origin)
23544 (user-error "Cannot move further up"))))))
23546 (let* ((elem (org-element-at-point))
23547 (beg (org-element-property :begin elem)))
23548 (cond
23549 ;; Move to beginning of current element if point isn't
23550 ;; there already.
23551 ((null beg) (message "No element at point"))
23552 ((/= (point) beg) (goto-char beg))
23553 (t (goto-char beg)
23554 (skip-chars-backward " \r\t\n")
23555 (unless (bobp)
23556 (let ((prev (org-element-at-point)))
23557 (goto-char (org-element-property :begin prev))
23558 (while (and (setq prev (org-element-property :parent prev))
23559 (<= (org-element-property :end prev) beg))
23560 (goto-char (org-element-property :begin prev)))))))))))
23562 (defun org-up-element ()
23563 "Move to upper element."
23564 (interactive)
23565 (if (org-with-limited-levels (org-at-heading-p))
23566 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23567 (let* ((elem (org-element-at-point))
23568 (parent (org-element-property :parent elem)))
23569 (if parent (goto-char (org-element-property :begin parent))
23570 (if (org-with-limited-levels (org-before-first-heading-p))
23571 (user-error "No surrounding element")
23572 (org-with-limited-levels (org-back-to-heading)))))))
23574 (defun org-down-element ()
23575 "Move to inner element."
23576 (interactive)
23577 (let ((element (org-element-at-point)))
23578 (cond
23579 ((memq (org-element-type element) '(plain-list table))
23580 (goto-char (org-element-property :contents-begin element))
23581 (forward-char))
23582 ((memq (org-element-type element) org-element-greater-elements)
23583 ;; If contents are hidden, first disclose them.
23584 (when (org-invisible-p (line-end-position)) (org-cycle))
23585 (goto-char (or (org-element-property :contents-begin element)
23586 (user-error "No content for this element"))))
23587 (t (user-error "No inner element")))))
23589 (defun org-drag-element-backward ()
23590 "Move backward element at point."
23591 (interactive)
23592 (let ((elem (or (org-element-at-point)
23593 (user-error "No element at point"))))
23594 (if (eq (org-element-type elem) 'headline)
23595 ;; Preserve point when moving a whole tree, even if point was
23596 ;; on blank lines below the headline.
23597 (let ((offset (skip-chars-backward " \t\n")))
23598 (unwind-protect (org-move-subtree-up)
23599 (forward-char (- offset))))
23600 (let ((prev-elem
23601 (save-excursion
23602 (goto-char (org-element-property :begin elem))
23603 (skip-chars-backward " \r\t\n")
23604 (unless (bobp)
23605 (let* ((beg (org-element-property :begin elem))
23606 (prev (org-element-at-point))
23607 (up prev))
23608 (while (and (setq up (org-element-property :parent up))
23609 (<= (org-element-property :end up) beg))
23610 (setq prev up))
23611 prev)))))
23612 ;; Error out if no previous element or previous element is
23613 ;; a parent of the current one.
23614 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23615 (user-error "Cannot drag element backward")
23616 (let ((pos (point)))
23617 (org-element-swap-A-B prev-elem elem)
23618 (goto-char (+ (org-element-property :begin prev-elem)
23619 (- pos (org-element-property :begin elem))))))))))
23621 (defun org-drag-element-forward ()
23622 "Move forward element at point."
23623 (interactive)
23624 (let* ((pos (point))
23625 (elem (or (org-element-at-point)
23626 (user-error "No element at point"))))
23627 (when (= (point-max) (org-element-property :end elem))
23628 (user-error "Cannot drag element forward"))
23629 (goto-char (org-element-property :end elem))
23630 (let ((next-elem (org-element-at-point)))
23631 (when (or (org-element-nested-p elem next-elem)
23632 (and (eq (org-element-type next-elem) 'headline)
23633 (not (eq (org-element-type elem) 'headline))))
23634 (goto-char pos)
23635 (user-error "Cannot drag element forward"))
23636 ;; Compute new position of point: it's shifted by NEXT-ELEM
23637 ;; body's length (without final blanks) and by the length of
23638 ;; blanks between ELEM and NEXT-ELEM.
23639 (let ((size-next (- (save-excursion
23640 (goto-char (org-element-property :end next-elem))
23641 (skip-chars-backward " \r\t\n")
23642 (forward-line)
23643 ;; Small correction if buffer doesn't end
23644 ;; with a newline character.
23645 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23646 (org-element-property :begin next-elem)))
23647 (size-blank (- (org-element-property :end elem)
23648 (save-excursion
23649 (goto-char (org-element-property :end elem))
23650 (skip-chars-backward " \r\t\n")
23651 (forward-line)
23652 (point)))))
23653 (org-element-swap-A-B elem next-elem)
23654 (goto-char (+ pos size-next size-blank))))))
23656 (defun org-drag-line-forward (arg)
23657 "Drag the line at point ARG lines forward."
23658 (interactive "p")
23659 (dotimes (_ (abs arg))
23660 (let ((c (current-column)))
23661 (if (< 0 arg)
23662 (progn
23663 (beginning-of-line 2)
23664 (transpose-lines 1)
23665 (beginning-of-line 0))
23666 (transpose-lines 1)
23667 (beginning-of-line -1))
23668 (org-move-to-column c))))
23670 (defun org-drag-line-backward (arg)
23671 "Drag the line at point ARG lines backward."
23672 (interactive "p")
23673 (org-drag-line-forward (- arg)))
23675 (defun org-mark-element ()
23676 "Put point at beginning of this element, mark at end.
23678 Interactively, if this command is repeated or (in Transient Mark
23679 mode) if the mark is active, it marks the next element after the
23680 ones already marked."
23681 (interactive)
23682 (let (deactivate-mark)
23683 (if (and (called-interactively-p 'any)
23684 (or (and (eq last-command this-command) (mark t))
23685 (and transient-mark-mode mark-active)))
23686 (set-mark
23687 (save-excursion
23688 (goto-char (mark))
23689 (goto-char (org-element-property :end (org-element-at-point)))))
23690 (let ((element (org-element-at-point)))
23691 (end-of-line)
23692 (push-mark (org-element-property :end element) t t)
23693 (goto-char (org-element-property :begin element))))))
23695 (defun org-narrow-to-element ()
23696 "Narrow buffer to current element."
23697 (interactive)
23698 (let ((elem (org-element-at-point)))
23699 (cond
23700 ((eq (car elem) 'headline)
23701 (narrow-to-region
23702 (org-element-property :begin elem)
23703 (org-element-property :end elem)))
23704 ((memq (car elem) org-element-greater-elements)
23705 (narrow-to-region
23706 (org-element-property :contents-begin elem)
23707 (org-element-property :contents-end elem)))
23709 (narrow-to-region
23710 (org-element-property :begin elem)
23711 (org-element-property :end elem))))))
23713 (defun org-transpose-element ()
23714 "Transpose current and previous elements, keeping blank lines between.
23715 Point is moved after both elements."
23716 (interactive)
23717 (org-skip-whitespace)
23718 (let ((end (org-element-property :end (org-element-at-point))))
23719 (org-drag-element-backward)
23720 (goto-char end)))
23722 (defun org-unindent-buffer ()
23723 "Un-indent the visible part of the buffer.
23724 Relative indentation (between items, inside blocks, etc.) isn't
23725 modified."
23726 (interactive)
23727 (unless (eq major-mode 'org-mode)
23728 (user-error "Cannot un-indent a buffer not in Org mode"))
23729 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23730 (unindent-tree
23731 (lambda (contents)
23732 (dolist (element (reverse contents))
23733 (if (memq (org-element-type element) '(headline section))
23734 (funcall unindent-tree (org-element-contents element))
23735 (save-excursion
23736 (save-restriction
23737 (narrow-to-region
23738 (org-element-property :begin element)
23739 (org-element-property :end element))
23740 (org-do-remove-indentation))))))))
23741 (funcall unindent-tree (org-element-contents parse-tree))))
23743 (defun org-make-options-regexp (kwds &optional extra)
23744 "Make a regular expression for keyword lines.
23745 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23746 when non-nil, is a regexp matching keywords names."
23747 (concat "^[ \t]*#\\+\\("
23748 (regexp-opt kwds)
23749 (and extra (concat (and kwds "\\|") extra))
23750 "\\):[ \t]*\\(.*\\)"))
23753 ;;; Finish up
23755 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23756 (lambda () (add-hook 'change-major-mode-hook
23757 'org-show-all 'append 'local)))
23759 (provide 'org)
23761 (run-hooks 'org-load-hook)
23763 ;;; org.el ends here