Move `org-xor' into "org-macs.el"
[org-mode.git] / lisp / org.el
blobe3b4ccef1ccdfd6eaee4bc38aa1d7b631b6c0c16
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp) ;Silence byte-compiler
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (eval-and-compile
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'."))
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
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-mode" 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 (defgroup org-startup nil
919 "Options concerning startup of Org mode."
920 :tag "Org Startup"
921 :group 'org)
923 (defcustom org-startup-folded t
924 "Non-nil means entering Org mode will switch to OVERVIEW.
926 This can also be configured on a per-file basis by adding one of
927 the following lines anywhere in the buffer:
929 #+STARTUP: fold (or `overview', this is equivalent)
930 #+STARTUP: nofold (or `showall', this is equivalent)
931 #+STARTUP: content
932 #+STARTUP: showeverything
934 Set `org-agenda-inhibit-startup' to a non-nil value if you want
935 to ignore this option when Org opens agenda files for the first
936 time."
937 :group 'org-startup
938 :type '(choice
939 (const :tag "nofold: show all" nil)
940 (const :tag "fold: overview" t)
941 (const :tag "content: all headlines" content)
942 (const :tag "show everything, even drawers" showeverything)))
944 (defcustom org-startup-truncated t
945 "Non-nil means entering Org mode will set `truncate-lines'.
946 This is useful since some lines containing links can be very long and
947 uninteresting. Also tables look terrible when wrapped.
949 The variable `org-startup-truncated' allows to configure
950 truncation for Org mode different to the other modes that use the
951 variable `truncate-lines' and as a shortcut instead of putting
952 the variable `truncate-lines' into the `org-mode-hook'. If one
953 wants to configure truncation for Org mode not statically but
954 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
955 the variable `truncate-lines' has to be used because in such a
956 case it is too late to set the variable `org-startup-truncated'."
957 :group 'org-startup
958 :type 'boolean)
960 (defcustom org-startup-indented nil
961 "Non-nil means turn on `org-indent-mode' on startup.
962 This can also be configured on a per-file basis by adding one of
963 the following lines anywhere in the buffer:
965 #+STARTUP: indent
966 #+STARTUP: noindent"
967 :group 'org-structure
968 :type '(choice
969 (const :tag "Not" nil)
970 (const :tag "Globally (slow on startup in large files)" t)))
972 (defcustom org-use-sub-superscripts t
973 "Non-nil means interpret \"_\" and \"^\" for display.
975 If you want to control how Org exports those characters, see
976 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
977 used to be an alias for `org-export-with-sub-superscripts' in
978 Org <8.0, it is not anymore.
980 When this option is turned on, you can use TeX-like syntax for
981 sub- and superscripts within the buffer. Several characters after
982 \"_\" or \"^\" will be considered as a single item - so grouping
983 with {} is normally not needed. For example, the following things
984 will be parsed as single sub- or superscripts:
986 10^24 or 10^tau several digits will be considered 1 item.
987 10^-12 or 10^-tau a leading sign with digits or a word
988 x^2-y^3 will be read as x^2 - y^3, because items are
989 terminated by almost any nonword/nondigit char.
990 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
992 Still, ambiguity is possible. So when in doubt, use {} to enclose
993 the sub/superscript. If you set this variable to the symbol `{}',
994 the braces are *required* in order to trigger interpretations as
995 sub/superscript. This can be helpful in documents that need \"_\"
996 frequently in plain text."
997 :group 'org-startup
998 :version "24.4"
999 :package-version '(Org . "8.0")
1000 :type '(choice
1001 (const :tag "Always interpret" t)
1002 (const :tag "Only with braces" {})
1003 (const :tag "Never interpret" nil)))
1005 (defcustom org-startup-with-beamer-mode nil
1006 "Non-nil means turn on `org-beamer-mode' on startup.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1010 #+STARTUP: beamer"
1011 :group 'org-startup
1012 :version "24.1"
1013 :type 'boolean)
1015 (defcustom org-startup-align-all-tables nil
1016 "Non-nil means align all tables when visiting a file.
1017 This can also be configured on a per-file basis by adding one of
1018 the following lines anywhere in the buffer:
1019 #+STARTUP: align
1020 #+STARTUP: noalign"
1021 :group 'org-startup
1022 :type 'boolean)
1024 (defcustom org-startup-shrink-all-tables nil
1025 "Non-nil means shrink all table columns with a width cookie.
1026 This can also be configured on a per-file basis by adding one of
1027 the following lines anywhere in the buffer:
1028 #+STARTUP: shrink"
1029 :group 'org-startup
1030 :type 'boolean
1031 :version "27.1"
1032 :package-version '(Org . "9.2")
1033 :safe #'booleanp)
1035 (defcustom org-startup-with-inline-images nil
1036 "Non-nil means show inline images when loading a new Org file.
1037 This can also be configured on a per-file basis by adding one of
1038 the following lines anywhere in the buffer:
1039 #+STARTUP: inlineimages
1040 #+STARTUP: noinlineimages"
1041 :group 'org-startup
1042 :version "24.1"
1043 :type 'boolean)
1045 (defcustom org-startup-with-latex-preview nil
1046 "Non-nil means preview LaTeX fragments when loading a new Org file.
1048 This can also be configured on a per-file basis by adding one of
1049 the following lines anywhere in the buffer:
1050 #+STARTUP: latexpreview
1051 #+STARTUP: nolatexpreview"
1052 :group 'org-startup
1053 :version "24.4"
1054 :package-version '(Org . "8.0")
1055 :type 'boolean)
1057 (defcustom org-insert-mode-line-in-empty-file nil
1058 "Non-nil means insert the first line setting Org mode in empty files.
1059 When the function `org-mode' is called interactively in an empty file, this
1060 normally means that the file name does not automatically trigger Org mode.
1061 To ensure that the file will always be in Org mode in the future, a
1062 line enforcing Org mode will be inserted into the buffer, if this option
1063 has been set."
1064 :group 'org-startup
1065 :type 'boolean)
1067 (defcustom org-replace-disputed-keys nil
1068 "Non-nil means use alternative key bindings for some keys.
1069 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1070 These keys are also used by other packages like shift-selection-mode'
1071 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1072 If you want to use Org mode together with one of these other modes,
1073 or more generally if you would like to move some Org mode commands to
1074 other keys, set this variable and configure the keys with the variable
1075 `org-disputed-keys'.
1077 This option is only relevant at load-time of Org mode, and must be set
1078 *before* org.el is loaded. Changing it requires a restart of Emacs to
1079 become effective."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defcustom org-use-extra-keys nil
1084 "Non-nil means use extra key sequence definitions for certain commands.
1085 This happens automatically if `window-system' is nil. This
1086 variable lets you do the same manually. You must set it before
1087 loading Org."
1088 :group 'org-startup
1089 :type 'boolean)
1091 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1093 (defcustom org-disputed-keys
1094 '(([(shift up)] . [(meta p)])
1095 ([(shift down)] . [(meta n)])
1096 ([(shift left)] . [(meta -)])
1097 ([(shift right)] . [(meta +)])
1098 ([(control shift right)] . [(meta shift +)])
1099 ([(control shift left)] . [(meta shift -)]))
1100 "Keys for which Org mode and other modes compete.
1101 This is an alist, cars are the default keys, second element specifies
1102 the alternative to use when `org-replace-disputed-keys' is t.
1104 Keys can be specified in any syntax supported by `define-key'.
1105 The value of this option takes effect only at Org mode startup,
1106 therefore you'll have to restart Emacs to apply it after changing."
1107 :group 'org-startup
1108 :type 'alist)
1110 (defun org-key (key)
1111 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1112 Or return the original if not disputed."
1113 (when org-replace-disputed-keys
1114 (let* ((nkey (key-description key))
1115 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1116 org-disputed-keys)))
1117 (setq key (if x (cdr x) key))))
1118 key)
1120 (defun org-defkey (keymap key def)
1121 "Define a key, possibly translated, as returned by `org-key'."
1122 (define-key keymap (org-key key) def))
1124 (defcustom org-ellipsis nil
1125 "The ellipsis to use in the Org mode outline.
1127 When nil, just use the standard three dots. When a non-empty string,
1128 use that string instead.
1130 The change affects only Org mode (which will then use its own display table).
1131 Changing this requires executing `\\[org-mode]' in a buffer to become
1132 effective."
1133 :group 'org-startup
1134 :type '(choice (const :tag "Default" nil)
1135 (string :tag "String" :value "...#"))
1136 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1138 (defvar org-display-table nil
1139 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1141 (defgroup org-keywords nil
1142 "Keywords in Org mode."
1143 :tag "Org Keywords"
1144 :group 'org)
1146 (defcustom org-closed-keep-when-no-todo nil
1147 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1148 :group 'org-todo
1149 :group 'org-keywords
1150 :version "24.4"
1151 :package-version '(Org . "8.0")
1152 :type 'boolean)
1154 (defgroup org-structure nil
1155 "Options concerning the general structure of Org files."
1156 :tag "Org Structure"
1157 :group 'org)
1159 (defgroup org-reveal-location nil
1160 "Options about how to make context of a location visible."
1161 :tag "Org Reveal Location"
1162 :group 'org-structure)
1164 (defcustom org-show-context-detail '((agenda . local)
1165 (bookmark-jump . lineage)
1166 (isearch . lineage)
1167 (default . ancestors))
1168 "Alist between context and visibility span when revealing a location.
1170 \\<org-mode-map>Some actions may move point into invisible
1171 locations. As a consequence, Org always expose a neighborhood
1172 around point. How much is shown depends on the initial action,
1173 or context. Valid contexts are
1175 agenda when exposing an entry from the agenda
1176 org-goto when using the command `org-goto' (`\\[org-goto]')
1177 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1178 tags-tree when constructing a sparse tree based on tags matches
1179 link-search when exposing search matches associated with a link
1180 mark-goto when exposing the jump goal of a mark
1181 bookmark-jump when exposing a bookmark location
1182 isearch when exiting from an incremental search
1183 default default for all contexts not set explicitly
1185 Allowed visibility spans are
1187 minimal show current headline; if point is not on headline,
1188 also show entry
1190 local show current headline, entry and next headline
1192 ancestors show current headline and its direct ancestors; if
1193 point is not on headline, also show entry
1195 lineage show current headline, its direct ancestors and all
1196 their children; if point is not on headline, also show
1197 entry and first child
1199 tree show current headline, its direct ancestors and all
1200 their children; if point is not on headline, also show
1201 entry and all children
1203 canonical show current headline, its direct ancestors along with
1204 their entries and children; if point is not located on
1205 the headline, also show current entry and all children
1207 As special cases, a nil or t value means show all contexts in
1208 `minimal' or `canonical' view, respectively.
1210 Some views can make displayed information very compact, but also
1211 make it harder to edit the location of the match. In such
1212 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1213 more context."
1214 :group 'org-reveal-location
1215 :version "26.1"
1216 :package-version '(Org . "9.0")
1217 :type '(choice
1218 (const :tag "Canonical" t)
1219 (const :tag "Minimal" nil)
1220 (repeat :greedy t :tag "Individual contexts"
1221 (cons
1222 (choice :tag "Context"
1223 (const agenda)
1224 (const org-goto)
1225 (const occur-tree)
1226 (const tags-tree)
1227 (const link-search)
1228 (const mark-goto)
1229 (const bookmark-jump)
1230 (const isearch)
1231 (const default))
1232 (choice :tag "Detail level"
1233 (const minimal)
1234 (const local)
1235 (const ancestors)
1236 (const lineage)
1237 (const tree)
1238 (const canonical))))))
1240 (defcustom org-indirect-buffer-display 'other-window
1241 "How should indirect tree buffers be displayed?
1243 This applies to indirect buffers created with the commands
1244 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1246 Valid values are:
1247 current-window Display in the current window
1248 other-window Just display in another window.
1249 dedicated-frame Create one new frame, and re-use it each time.
1250 new-frame Make a new frame each time. Note that in this case
1251 previously-made indirect buffers are kept, and you need to
1252 kill these buffers yourself."
1253 :group 'org-structure
1254 :group 'org-agenda-windows
1255 :type '(choice
1256 (const :tag "In current window" current-window)
1257 (const :tag "In current frame, other window" other-window)
1258 (const :tag "Each time a new frame" new-frame)
1259 (const :tag "One dedicated frame" dedicated-frame)))
1261 (defcustom org-use-speed-commands nil
1262 "Non-nil means activate single letter commands at beginning of a headline.
1263 This may also be a function to test for appropriate locations where speed
1264 commands should be active.
1266 For example, to activate speed commands when the point is on any
1267 star at the beginning of the headline, you can do this:
1269 (setq org-use-speed-commands
1270 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1271 :group 'org-structure
1272 :type '(choice
1273 (const :tag "Never" nil)
1274 (const :tag "At beginning of headline stars" t)
1275 (function)))
1277 (defcustom org-speed-commands-user nil
1278 "Alist of additional speed commands.
1279 This list will be checked before `org-speed-commands-default'
1280 when the variable `org-use-speed-commands' is non-nil
1281 and when the cursor is at the beginning of a headline.
1282 The car if each entry is a string with a single letter, which must
1283 be assigned to `self-insert-command' in the global map.
1284 The cdr is either a command to be called interactively, a function
1285 to be called, or a form to be evaluated.
1286 An entry that is just a list with a single string will be interpreted
1287 as a descriptive headline that will be added when listing the speed
1288 commands in the Help buffer using the `?' speed command."
1289 :group 'org-structure
1290 :type '(repeat :value ("k" . ignore)
1291 (choice :value ("k" . ignore)
1292 (list :tag "Descriptive Headline" (string :tag "Headline"))
1293 (cons :tag "Letter and Command"
1294 (string :tag "Command letter")
1295 (choice
1296 (function)
1297 (sexp))))))
1299 (defcustom org-bookmark-names-plist
1300 '(:last-capture "org-capture-last-stored"
1301 :last-refile "org-refile-last-stored"
1302 :last-capture-marker "org-capture-last-stored-marker")
1303 "Names for bookmarks automatically set by some Org commands.
1304 This can provide strings as names for a number of bookmarks Org sets
1305 automatically. The following keys are currently implemented:
1306 :last-capture
1307 :last-capture-marker
1308 :last-refile
1309 When a key does not show up in the property list, the corresponding bookmark
1310 is not set."
1311 :group 'org-structure
1312 :type 'plist)
1314 (defgroup org-cycle nil
1315 "Options concerning visibility cycling in Org mode."
1316 :tag "Org Cycle"
1317 :group 'org-structure)
1319 (defcustom org-cycle-skip-children-state-if-no-children t
1320 "Non-nil means skip CHILDREN state in entries that don't have any."
1321 :group 'org-cycle
1322 :type 'boolean)
1324 (defcustom org-cycle-max-level nil
1325 "Maximum level which should still be subject to visibility cycling.
1326 Levels higher than this will, for cycling, be treated as text, not a headline.
1327 When `org-odd-levels-only' is set, a value of N in this variable actually
1328 means 2N-1 stars as the limiting headline.
1329 When nil, cycle all levels.
1330 Note that the limiting level of cycling is also influenced by
1331 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1332 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1333 than its value."
1334 :group 'org-cycle
1335 :type '(choice
1336 (const :tag "No limit" nil)
1337 (integer :tag "Maximum level")))
1339 (defcustom org-hide-block-startup nil
1340 "Non-nil means entering Org mode will fold all blocks.
1341 This can also be set in on a per-file basis with
1343 #+STARTUP: hideblocks
1344 #+STARTUP: showblocks"
1345 :group 'org-startup
1346 :group 'org-cycle
1347 :type 'boolean)
1349 (defcustom org-cycle-global-at-bob nil
1350 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1352 This makes it possible to do global cycling without having to use `S-TAB'
1353 or `\\[universal-argument] TAB'. For this special case to work, the first \
1354 line of the buffer
1355 must not be a headline -- it may be empty or some other text.
1357 When used in this way, `org-cycle-hook' is disabled temporarily to make
1358 sure the cursor stays at the beginning of the buffer.
1360 When this option is nil, don't do anything special at the beginning of
1361 the buffer."
1362 :group 'org-cycle
1363 :type 'boolean)
1365 (defcustom org-cycle-level-after-item/entry-creation t
1366 "Non-nil means cycle entry level or item indentation in new empty entries.
1368 When the cursor is at the end of an empty headline, i.e., with only stars
1369 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1370 and then all possible ancestor states, before returning to the original state.
1371 This makes data entry extremely fast: M-RET to create a new headline,
1372 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1374 When the cursor is at the end of an empty plain list item, one TAB will
1375 make it a subitem, two or more tabs will back up to make this an item
1376 higher up in the item hierarchy."
1377 :group 'org-cycle
1378 :type 'boolean)
1380 (defcustom org-cycle-emulate-tab t
1381 "Where should `org-cycle' emulate TAB.
1382 nil Never
1383 white Only in completely white lines
1384 whitestart Only at the beginning of lines, before the first non-white char
1385 t Everywhere except in headlines
1386 exc-hl-bol Everywhere except at the start of a headline
1387 If TAB is used in a place where it does not emulate TAB, the current subtree
1388 visibility is cycled."
1389 :group 'org-cycle
1390 :type '(choice (const :tag "Never" nil)
1391 (const :tag "Only in completely white lines" white)
1392 (const :tag "Before first char in a line" whitestart)
1393 (const :tag "Everywhere except in headlines" t)
1394 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1396 (defcustom org-cycle-separator-lines 2
1397 "Number of empty lines needed to keep an empty line between collapsed trees.
1398 If you leave an empty line between the end of a subtree and the following
1399 headline, this empty line is hidden when the subtree is folded.
1400 Org mode will leave (exactly) one empty line visible if the number of
1401 empty lines is equal or larger to the number given in this variable.
1402 So the default 2 means at least 2 empty lines after the end of a subtree
1403 are needed to produce free space between a collapsed subtree and the
1404 following headline.
1406 If the number is negative, and the number of empty lines is at least -N,
1407 all empty lines are shown.
1409 Special case: when 0, never leave empty lines in collapsed view."
1410 :group 'org-cycle
1411 :type 'integer)
1412 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1414 (defcustom org-pre-cycle-hook nil
1415 "Hook that is run before visibility cycling is happening.
1416 The function(s) in this hook must accept a single argument which indicates
1417 the new state that will be set right after running this hook. The
1418 argument is a symbol. Before a global state change, it can have the values
1419 `overview', `content', or `all'. Before a local state change, it can have
1420 the values `folded', `children', or `subtree'."
1421 :group 'org-cycle
1422 :type 'hook)
1424 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1425 org-cycle-hide-drawers
1426 org-cycle-show-empty-lines
1427 org-optimize-window-after-visibility-change)
1428 "Hook that is run after `org-cycle' has changed the buffer visibility.
1429 The function(s) in this hook must accept a single argument which indicates
1430 the new state that was set by the most recent `org-cycle' command. The
1431 argument is a symbol. After a global state change, it can have the values
1432 `overview', `contents', or `all'. After a local state change, it can have
1433 the values `folded', `children', or `subtree'."
1434 :group 'org-cycle
1435 :type 'hook
1436 :version "26.1"
1437 :package-version '(Org . "8.3"))
1439 (defgroup org-edit-structure nil
1440 "Options concerning structure editing in Org mode."
1441 :tag "Org Edit Structure"
1442 :group 'org-structure)
1444 (defcustom org-odd-levels-only nil
1445 "Non-nil means skip even levels and only use odd levels for the outline.
1446 This has the effect that two stars are being added/taken away in
1447 promotion/demotion commands. It also influences how levels are
1448 handled by the exporters.
1449 Changing it requires restart of `font-lock-mode' to become effective
1450 for fontification also in regions already fontified.
1451 You may also set this on a per-file basis by adding one of the following
1452 lines to the buffer:
1454 #+STARTUP: odd
1455 #+STARTUP: oddeven"
1456 :group 'org-edit-structure
1457 :group 'org-appearance
1458 :type 'boolean)
1460 (defcustom org-adapt-indentation t
1461 "Non-nil means adapt indentation to outline node level.
1463 When this variable is set, Org assumes that you write outlines by
1464 indenting text in each node to align with the headline (after the
1465 stars). The following issues are influenced by this variable:
1467 - The indentation is increased by one space in a demotion
1468 command, and decreased by one in a promotion command. However,
1469 in the latter case, if shifting some line in the entry body
1470 would alter document structure (e.g., insert a new headline),
1471 indentation is not changed at all.
1473 - Property drawers and planning information is inserted indented
1474 when this variable is set. When nil, they will not be indented.
1476 - TAB indents a line relative to current level. The lines below
1477 a headline will be indented when this variable is set.
1479 Note that this is all about true indentation, by adding and
1480 removing space characters. See also `org-indent.el' which does
1481 level-dependent indentation in a virtual way, i.e. at display
1482 time in Emacs."
1483 :group 'org-edit-structure
1484 :type 'boolean)
1486 (defcustom org-special-ctrl-a/e nil
1487 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1489 When t, `C-a' will bring back the cursor to the beginning of the
1490 headline text, i.e. after the stars and after a possible TODO
1491 keyword. In an item, this will be the position after bullet and
1492 check-box, if any. When the cursor is already at that position,
1493 another `C-a' will bring it to the beginning of the line.
1495 `C-e' will jump to the end of the headline, ignoring the presence
1496 of tags in the headline. A second `C-e' will then jump to the
1497 true end of the line, after any tags. This also means that, when
1498 this variable is non-nil, `C-e' also will never jump beyond the
1499 end of the heading of a folded section, i.e. not after the
1500 ellipses.
1502 When set to the symbol `reversed', the first `C-a' or `C-e' works
1503 normally, going to the true line boundary first. Only a directly
1504 following, identical keypress will bring the cursor to the
1505 special positions.
1507 This may also be a cons cell where the behavior for `C-a' and
1508 `C-e' is set separately."
1509 :group 'org-edit-structure
1510 :type '(choice
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet and before tags first" t)
1513 (const :tag "reversed: true line boundary first" reversed)
1514 (cons :tag "Set C-a and C-e separately"
1515 (choice :tag "Special C-a"
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet first" t)
1518 (const :tag "reversed: before stars/bullet first" reversed))
1519 (choice :tag "Special C-e"
1520 (const :tag "off" nil)
1521 (const :tag "on: before tags first" t)
1522 (const :tag "reversed: after tags first" reversed)))))
1523 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1525 (defcustom org-special-ctrl-k nil
1526 "Non-nil means `C-k' will behave specially in headlines.
1527 When nil, `C-k' will call the default `kill-line' command.
1528 When t, the following will happen while the cursor is in the headline:
1530 - When the cursor is at the beginning of a headline, kill the entire
1531 line and possible the folded subtree below the line.
1532 - When in the middle of the headline text, kill the headline up to the tags.
1533 - When after the headline text, kill the tags."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-ctrl-k-protect-subtree nil
1538 "Non-nil means, do not delete a hidden subtree with C-k.
1539 When set to the symbol `error', simply throw an error when C-k is
1540 used to kill (part-of) a headline that has hidden text behind it.
1541 Any other non-nil value will result in a query to the user, if it is
1542 OK to kill that hidden subtree. When nil, kill without remorse."
1543 :group 'org-edit-structure
1544 :version "24.1"
1545 :type '(choice
1546 (const :tag "Do not protect hidden subtrees" nil)
1547 (const :tag "Protect hidden subtrees with a security query" t)
1548 (const :tag "Never kill a hidden subtree with C-k" error)))
1550 (defcustom org-special-ctrl-o t
1551 "Non-nil means, make `C-o' insert a row in tables."
1552 :group 'org-edit-structure
1553 :type 'boolean)
1555 (defcustom org-catch-invisible-edits nil
1556 "Check if in invisible region before inserting or deleting a character.
1557 Valid values are:
1559 nil Do not check, so just do invisible edits.
1560 error Throw an error and do nothing.
1561 show Make point visible, and do the requested edit.
1562 show-and-error Make point visible, then throw an error and abort the edit.
1563 smart Make point visible, and do insertion/deletion if it is
1564 adjacent to visible text and the change feels predictable.
1565 Never delete a previously invisible character or add in the
1566 middle or right after an invisible region. Basically, this
1567 allows insertion and backward-delete right before ellipses.
1568 FIXME: maybe in this case we should not even show?"
1569 :group 'org-edit-structure
1570 :version "24.1"
1571 :type '(choice
1572 (const :tag "Do not check" nil)
1573 (const :tag "Throw error when trying to edit" error)
1574 (const :tag "Unhide, but do not do the edit" show-and-error)
1575 (const :tag "Show invisible part and do the edit" show)
1576 (const :tag "Be smart and do the right thing" smart)))
1578 (defcustom org-yank-folded-subtrees t
1579 "Non-nil means when yanking subtrees, fold them.
1580 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1581 it starts with a heading and all other headings in it are either children
1582 or siblings, then fold all the subtrees. However, do this only if no
1583 text after the yank would be swallowed into a folded tree by this action."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-yank-adjusted-subtrees nil
1588 "Non-nil means when yanking subtrees, adjust the level.
1589 With this setting, `org-paste-subtree' is used to insert the subtree, see
1590 this function for details."
1591 :group 'org-edit-structure
1592 :type 'boolean)
1594 (defcustom org-M-RET-may-split-line '((default . t))
1595 "Non-nil means M-RET will split the line at the cursor position.
1596 When nil, it will go to the end of the line before making a
1597 new line.
1598 You may also set this option in a different way for different
1599 contexts. Valid contexts are:
1601 headline when creating a new headline
1602 item when creating a new item
1603 table in a table field
1604 default the value to be used for all contexts not explicitly
1605 customized"
1606 :group 'org-structure
1607 :group 'org-table
1608 :type '(choice
1609 (const :tag "Always" t)
1610 (const :tag "Never" nil)
1611 (repeat :greedy t :tag "Individual contexts"
1612 (cons
1613 (choice :tag "Context"
1614 (const headline)
1615 (const item)
1616 (const table)
1617 (const default))
1618 (boolean)))))
1621 (defcustom org-insert-heading-respect-content nil
1622 "Non-nil means insert new headings after the current subtree.
1623 \\<org-mode-map>
1624 When nil, the new heading is created directly after the current line.
1625 The commands `\\[org-insert-heading-respect-content]' and \
1626 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1627 for the duration of the command."
1628 :group 'org-structure
1629 :type 'boolean)
1631 (defcustom org-blank-before-new-entry '((heading . auto)
1632 (plain-list-item . auto))
1633 "Should `org-insert-heading' leave a blank line before new heading/item?
1634 The value is an alist, with `heading' and `plain-list-item' as CAR,
1635 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1636 which case Org will look at the surrounding headings/items and try to
1637 make an intelligent decision whether to insert a blank line or not."
1638 :group 'org-edit-structure
1639 :type '(list
1640 (cons (const heading)
1641 (choice (const :tag "Never" nil)
1642 (const :tag "Always" t)
1643 (const :tag "Auto" auto)))
1644 (cons (const plain-list-item)
1645 (choice (const :tag "Never" nil)
1646 (const :tag "Always" t)
1647 (const :tag "Auto" auto)))))
1649 (defcustom org-insert-heading-hook nil
1650 "Hook being run after inserting a new heading."
1651 :group 'org-edit-structure
1652 :type 'hook)
1654 (defcustom org-enable-fixed-width-editor t
1655 "Non-nil means lines starting with \":\" are treated as fixed-width.
1656 This currently only means they are never auto-wrapped.
1657 When nil, such lines will be treated like ordinary lines."
1658 :group 'org-edit-structure
1659 :type 'boolean)
1661 (defcustom org-goto-auto-isearch t
1662 "Non-nil means typing characters in `org-goto' starts incremental search.
1663 When nil, you can use these keybindings to navigate the buffer:
1665 q Quit the org-goto interface
1666 n Go to the next visible heading
1667 p Go to the previous visible heading
1668 f Go one heading forward on same level
1669 b Go one heading backward on same level
1670 u Go one heading up"
1671 :group 'org-edit-structure
1672 :type 'boolean)
1674 (defgroup org-sparse-trees nil
1675 "Options concerning sparse trees in Org mode."
1676 :tag "Org Sparse Trees"
1677 :group 'org-structure)
1679 (defcustom org-highlight-sparse-tree-matches t
1680 "Non-nil means highlight all matches that define a sparse tree.
1681 The highlights will automatically disappear the next time the buffer is
1682 changed by an edit command."
1683 :group 'org-sparse-trees
1684 :type 'boolean)
1686 (defcustom org-remove-highlights-with-change t
1687 "Non-nil means any change to the buffer will remove temporary highlights.
1688 \\<org-mode-map>\
1689 Such highlights are created by `org-occur' and `org-clock-display'.
1690 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1691 to get rid of the highlights.
1692 The highlights created by `org-toggle-latex-fragment' always need
1693 `\\[org-toggle-latex-fragment]' to be removed."
1694 :group 'org-sparse-trees
1695 :group 'org-time
1696 :type 'boolean)
1698 (defcustom org-occur-case-fold-search t
1699 "Non-nil means `org-occur' should be case-insensitive.
1700 If set to `smart' the search will be case-insensitive only if it
1701 doesn't specify any upper case character."
1702 :group 'org-sparse-trees
1703 :version "26.1"
1704 :type '(choice
1705 (const :tag "Case-sensitive" nil)
1706 (const :tag "Case-insensitive" t)
1707 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1709 (defcustom org-occur-hook '(org-first-headline-recenter)
1710 "Hook that is run after `org-occur' has constructed a sparse tree.
1711 This can be used to recenter the window to show as much of the structure
1712 as possible."
1713 :group 'org-sparse-trees
1714 :type 'hook)
1716 (defgroup org-imenu-and-speedbar nil
1717 "Options concerning imenu and speedbar in Org mode."
1718 :tag "Org Imenu and Speedbar"
1719 :group 'org-structure)
1721 (defcustom org-imenu-depth 2
1722 "The maximum level for Imenu access to Org headlines.
1723 This also applied for speedbar access."
1724 :group 'org-imenu-and-speedbar
1725 :type 'integer)
1727 (defgroup org-table nil
1728 "Options concerning tables in Org mode."
1729 :tag "Org Table"
1730 :group 'org)
1732 (defcustom org-self-insert-cluster-for-undo nil
1733 "Non-nil means cluster self-insert commands for undo when possible.
1734 If this is set, then, like in the Emacs command loop, 20 consecutive
1735 characters will be undone together.
1736 This is configurable, because there is some impact on typing performance."
1737 :group 'org-table
1738 :type 'boolean)
1740 (defcustom org-table-tab-recognizes-table.el t
1741 "Non-nil means TAB will automatically notice a table.el table.
1742 When it sees such a table, it moves point into it and - if necessary -
1743 calls `table-recognize-table'."
1744 :group 'org-table-editing
1745 :type 'boolean)
1747 (defgroup org-link nil
1748 "Options concerning links in Org mode."
1749 :tag "Org Link"
1750 :group 'org)
1752 (defvar-local org-link-abbrev-alist-local nil
1753 "Buffer-local version of `org-link-abbrev-alist', which see.
1754 The value of this is taken from the #+LINK lines.")
1756 (defcustom org-link-parameters
1757 '(("doi" :follow org--open-doi-link)
1758 ("elisp" :follow org--open-elisp-link)
1759 ("file" :complete org-file-complete-link)
1760 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1761 ("help" :follow org--open-help-link)
1762 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1763 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1764 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1765 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1766 ("shell" :follow org--open-shell-link))
1767 "An alist of properties that defines all the links in Org mode.
1768 The key in each association is a string of the link type.
1769 Subsequent optional elements make up a p-list of link properties.
1771 :follow - A function that takes the link path as an argument.
1773 :export - A function that takes the link path, description and
1774 export-backend as arguments.
1776 :store - A function responsible for storing the link. See the
1777 function `org-store-link-functions'.
1779 :complete - A function that inserts a link with completion. The
1780 function takes one optional prefix arg.
1782 :face - A face for the link, or a function that returns a face.
1783 The function takes one argument which is the link path. The
1784 default face is `org-link'.
1786 :mouse-face - The mouse-face. The default is `highlight'.
1788 :display - `full' will not fold the link in descriptive
1789 display. Default is `org-link'.
1791 :help-echo - A string or function that takes (window object position)
1792 as arguments and returns a string.
1794 :keymap - A keymap that is active on the link. The default is
1795 `org-mouse-map'.
1797 :htmlize-link - A function for the htmlize-link. Defaults
1798 to (list :uri \"type:path\")
1800 :activate-func - A function to run at the end of font-lock
1801 activation. The function must accept (link-start link-end path bracketp)
1802 as arguments."
1803 :group 'org-link
1804 :type '(alist :tag "Link display parameters"
1805 :value-type plist)
1806 :version "26.1"
1807 :package-version '(Org . "9.1"))
1809 (defun org-link-get-parameter (type key)
1810 "Get TYPE link property for KEY.
1811 TYPE is a string and KEY is a plist keyword."
1812 (plist-get
1813 (cdr (assoc type org-link-parameters))
1814 key))
1816 (defun org-link-set-parameters (type &rest parameters)
1817 "Set link TYPE properties to PARAMETERS.
1818 PARAMETERS should be :key val pairs."
1819 (let ((data (assoc type org-link-parameters)))
1820 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1821 (push (cons type parameters) org-link-parameters)
1822 (org-make-link-regexps)
1823 (org-element-update-syntax))))
1825 (defun org-link-types ()
1826 "Return a list of known link types."
1827 (mapcar #'car org-link-parameters))
1829 (defcustom org-link-abbrev-alist nil
1830 "Alist of link abbreviations.
1831 The car of each element is a string, to be replaced at the start of a link.
1832 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1833 links in Org buffers can have an optional tag after a double colon, e.g.,
1835 [[linkkey:tag][description]]
1837 The `linkkey' must be a single word, starting with a letter, followed
1838 by letters, numbers, `-' or `_'.
1840 If REPLACE is a string, the tag will simply be appended to create the link.
1841 If the string contains \"%s\", the tag will be inserted there. If the string
1842 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1843 at that point (see the function `url-hexify-string'). If the string contains
1844 the specifier \"%(my-function)\", then the custom function `my-function' will
1845 be invoked: this function takes the tag as its only argument and must return
1846 a string.
1848 REPLACE may also be a function that will be called with the tag as the
1849 only argument to create the link, which should be returned as a string.
1851 See the manual for examples."
1852 :group 'org-link
1853 :type '(repeat
1854 (cons
1855 (string :tag "Protocol")
1856 (choice
1857 (string :tag "Format")
1858 (function)))))
1860 (defcustom org-descriptive-links t
1861 "Non-nil means Org will display descriptive links.
1862 E.g. [[http://orgmode.org][Org website]] will be displayed as
1863 \"Org Website\", hiding the link itself and just displaying its
1864 description. When set to nil, Org will display the full links
1865 literally.
1867 You can interactively set the value of this variable by calling
1868 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1869 :group 'org-link
1870 :type 'boolean)
1872 (defcustom org-link-file-path-type 'adaptive
1873 "How the path name in file links should be stored.
1874 Valid values are:
1876 relative Relative to the current directory, i.e. the directory of the file
1877 into which the link is being inserted.
1878 absolute Absolute path, if possible with ~ for home directory.
1879 noabbrev Absolute path, no abbreviation of home directory.
1880 adaptive Use relative path for files in the current directory and sub-
1881 directories of it. For other files, use an absolute path."
1882 :group 'org-link
1883 :type '(choice
1884 (const relative)
1885 (const absolute)
1886 (const noabbrev)
1887 (const adaptive)))
1889 (defvaralias 'org-activate-links 'org-highlight-links)
1890 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1891 "Types of links that should be highlighted in Org files.
1893 This is a list of symbols, each one of them leading to the
1894 highlighting of a certain link type.
1896 You can still open links that are not highlighted.
1898 In principle, it does not hurt to turn on highlighting for all
1899 link types. There may be a small gain when turning off unused
1900 link types. The types are:
1902 bracket The recommended [[link][description]] or [[link]] links with hiding.
1903 angle Links in angular brackets that may contain whitespace like
1904 <bbdb:Carsten Dominik>.
1905 plain Plain links in normal text, no whitespace, like http://google.com.
1906 radio Text that is matched by a radio target, see manual for details.
1907 tag Tag settings in a headline (link to tag search).
1908 date Time stamps (link to calendar).
1909 footnote Footnote labels.
1911 If you set this variable during an Emacs session, use `org-mode-restart'
1912 in the Org buffer so that the change takes effect."
1913 :group 'org-link
1914 :group 'org-appearance
1915 :type '(set :greedy t
1916 (const :tag "Double bracket links" bracket)
1917 (const :tag "Angular bracket links" angle)
1918 (const :tag "Plain text links" plain)
1919 (const :tag "Radio target matches" radio)
1920 (const :tag "Tags" tag)
1921 (const :tag "Timestamps" date)
1922 (const :tag "Footnotes" footnote)))
1924 (defcustom org-make-link-description-function nil
1925 "Function to use for generating link descriptions from links.
1926 This function must take two parameters: the first one is the
1927 link, the second one is the description generated by
1928 `org-insert-link'. The function should return the description to
1929 use."
1930 :group 'org-link
1931 :type '(choice (const nil) (function)))
1933 (defgroup org-link-store nil
1934 "Options concerning storing links in Org mode."
1935 :tag "Org Store Link"
1936 :group 'org-link)
1938 (defcustom org-url-hexify-p t
1939 "When non-nil, hexify URL when creating a link."
1940 :type 'boolean
1941 :version "24.3"
1942 :group 'org-link-store)
1944 (defcustom org-email-link-description-format "Email %c: %.30s"
1945 "Format of the description part of a link to an email or usenet message.
1946 The following %-escapes will be replaced by corresponding information:
1948 %F full \"From\" field
1949 %f name, taken from \"From\" field, address if no name
1950 %T full \"To\" field
1951 %t first name in \"To\" field, address if no name
1952 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1953 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1954 %s subject
1955 %d date
1956 %m message-id.
1958 You may use normal field width specification between the % and the letter.
1959 This is for example useful to limit the length of the subject.
1961 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1962 :group 'org-link-store
1963 :type 'string)
1965 (defcustom org-from-is-user-regexp
1966 (let (r1 r2)
1967 (when (and user-mail-address (not (string= user-mail-address "")))
1968 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1969 (when (and user-full-name (not (string= user-full-name "")))
1970 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1971 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1972 "Regexp matched against the \"From:\" header of an email or usenet message.
1973 It should match if the message is from the user him/herself."
1974 :group 'org-link-store
1975 :type 'regexp)
1977 (defcustom org-context-in-file-links t
1978 "Non-nil means file links from `org-store-link' contain context.
1979 \\<org-mode-map>
1980 A search string will be added to the file name with :: as separator
1981 and used to find the context when the link is activated by the command
1982 `org-open-at-point'. When this option is t, the entire active region
1983 will be placed in the search string of the file link. If set to a
1984 positive integer, only the first n lines of context will be stored.
1986 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1987 \\[org-store-link]')
1988 negates this setting for the duration of the command."
1989 :group 'org-link-store
1990 :type '(choice boolean integer))
1992 (defcustom org-keep-stored-link-after-insertion nil
1993 "Non-nil means keep link in list for entire session.
1994 \\<org-mode-map>
1995 The command `org-store-link' adds a link pointing to the current
1996 location to an internal list. These links accumulate during a session.
1997 The command `org-insert-link' can be used to insert links into any
1998 Org file (offering completion for all stored links).
2000 When this option is nil, every link which has been inserted once using
2001 `\\[org-insert-link]' will be removed from the list, to make completing the \
2002 unused
2003 links more efficient."
2004 :group 'org-link-store
2005 :type 'boolean)
2007 (defgroup org-link-follow nil
2008 "Options concerning following links in Org mode."
2009 :tag "Org Follow Link"
2010 :group 'org-link)
2012 (defcustom org-link-translation-function nil
2013 "Function to translate links with different syntax to Org syntax.
2014 This can be used to translate links created for example by the Planner
2015 or emacs-wiki packages to Org syntax.
2016 The function must accept two parameters, a TYPE containing the link
2017 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2018 which is everything after the link protocol. It should return a cons
2019 with possibly modified values of type and path.
2020 Org contains a function for this, so if you set this variable to
2021 `org-translate-link-from-planner', you should be able follow many
2022 links created by planner."
2023 :group 'org-link-follow
2024 :type '(choice (const nil) (function)))
2026 (defcustom org-follow-link-hook nil
2027 "Hook that is run after a link has been followed."
2028 :group 'org-link-follow
2029 :type 'hook)
2031 (defcustom org-tab-follows-link nil
2032 "Non-nil means on links TAB will follow the link.
2033 Needs to be set before org.el is loaded.
2034 This really should not be used, it does not make sense, and the
2035 implementation is bad."
2036 :group 'org-link-follow
2037 :type 'boolean)
2039 (defcustom org-return-follows-link nil
2040 "Non-nil means on links RET will follow the link.
2041 In tables, the special behavior of RET has precedence."
2042 :group 'org-link-follow
2043 :type 'boolean)
2045 (defcustom org-mouse-1-follows-link
2046 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2047 "Non-nil means mouse-1 on a link will follow the link.
2048 A longer mouse click will still set point. Needs to be set
2049 before org.el is loaded."
2050 :group 'org-link-follow
2051 :version "26.1"
2052 :package-version '(Org . "8.3")
2053 :type '(choice
2054 (const :tag "A double click follows the link" double)
2055 (const :tag "Unconditionally follow the link with mouse-1" t)
2056 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2058 (defcustom org-mark-ring-length 4
2059 "Number of different positions to be recorded in the ring.
2060 Changing this requires a restart of Emacs to work correctly."
2061 :group 'org-link-follow
2062 :type 'integer)
2064 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2065 "Non-nil means internal fuzzy links can only match headlines.
2067 When nil, the a fuzzy link may point to a target or a named
2068 construct in the document. When set to the special value
2069 `query-to-create', offer to create a new headline when none
2070 matched.
2072 Spaces and statistics cookies are ignored during heading searches."
2073 :group 'org-link-follow
2074 :version "24.1"
2075 :type '(choice
2076 (const :tag "Use fuzzy text search" nil)
2077 (const :tag "Match only exact headline" t)
2078 (const :tag "Match exact headline or query to create it"
2079 query-to-create))
2080 :safe #'symbolp)
2082 (defcustom org-link-frame-setup
2083 '((vm . vm-visit-folder-other-frame)
2084 (vm-imap . vm-visit-imap-folder-other-frame)
2085 (gnus . org-gnus-no-new-news)
2086 (file . find-file-other-window)
2087 (wl . wl-other-frame))
2088 "Setup the frame configuration for following links.
2089 When following a link with Emacs, it may often be useful to display
2090 this link in another window or frame. This variable can be used to
2091 set this up for the different types of links.
2092 For VM, use any of
2093 `vm-visit-folder'
2094 `vm-visit-folder-other-window'
2095 `vm-visit-folder-other-frame'
2096 For Gnus, use any of
2097 `gnus'
2098 `gnus-other-frame'
2099 `org-gnus-no-new-news'
2100 For FILE, use any of
2101 `find-file'
2102 `find-file-other-window'
2103 `find-file-other-frame'
2104 For Wanderlust use any of
2105 `wl'
2106 `wl-other-frame'
2107 For the calendar, use the variable `calendar-setup'.
2108 For BBDB, it is currently only possible to display the matches in
2109 another window."
2110 :group 'org-link-follow
2111 :type '(list
2112 (cons (const vm)
2113 (choice
2114 (const vm-visit-folder)
2115 (const vm-visit-folder-other-window)
2116 (const vm-visit-folder-other-frame)))
2117 (cons (const vm-imap)
2118 (choice
2119 (const vm-visit-imap-folder)
2120 (const vm-visit-imap-folder-other-window)
2121 (const vm-visit-imap-folder-other-frame)))
2122 (cons (const gnus)
2123 (choice
2124 (const gnus)
2125 (const gnus-other-frame)
2126 (const org-gnus-no-new-news)))
2127 (cons (const file)
2128 (choice
2129 (const find-file)
2130 (const find-file-other-window)
2131 (const find-file-other-frame)))
2132 (cons (const wl)
2133 (choice
2134 (const wl)
2135 (const wl-other-frame)))))
2137 (defcustom org-display-internal-link-with-indirect-buffer nil
2138 "Non-nil means use indirect buffer to display infile links.
2139 Activating internal links (from one location in a file to another location
2140 in the same file) normally just jumps to the location. When the link is
2141 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2142 is displayed in
2143 another window. When this option is set, the other window actually displays
2144 an indirect buffer clone of the current buffer, to avoid any visibility
2145 changes to the current buffer."
2146 :group 'org-link-follow
2147 :type 'boolean)
2149 (defcustom org-open-non-existing-files nil
2150 "Non-nil means `org-open-file' will open non-existing files.
2151 When nil, an error will be generated.
2152 This variable applies only to external applications because they
2153 might choke on non-existing files. If the link is to a file that
2154 will be opened in Emacs, the variable is ignored."
2155 :group 'org-link-follow
2156 :type 'boolean)
2158 (defcustom org-open-directory-means-index-dot-org nil
2159 "Non-nil means a link to a directory really means to index.org.
2160 When nil, following a directory link will run dired or open a finder/explorer
2161 window on that directory."
2162 :group 'org-link-follow
2163 :type 'boolean)
2165 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2166 "Non-nil means ask for confirmation before executing shell links.
2167 Shell links can be dangerous: just think about a link
2169 [[shell:rm -rf ~/*][Google Search]]
2171 This link would show up in your Org document as \"Google Search\",
2172 but really it would remove your entire home directory.
2173 Therefore we advise against setting this variable to nil.
2174 Just change it to `y-or-n-p' if you want to confirm with a
2175 single keystroke rather than having to type \"yes\"."
2176 :group 'org-link-follow
2177 :type '(choice
2178 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2179 (const :tag "with y-or-n (faster)" y-or-n-p)
2180 (const :tag "no confirmation (dangerous)" nil)))
2181 (put 'org-confirm-shell-link-function
2182 'safe-local-variable
2183 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2185 (defcustom org-confirm-shell-link-not-regexp ""
2186 "A regexp to skip confirmation for shell links."
2187 :group 'org-link-follow
2188 :version "24.1"
2189 :type 'regexp)
2191 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2192 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2193 Elisp links can be dangerous: just think about a link
2195 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2197 This link would show up in your Org document as \"Google Search\",
2198 but really it would remove your entire home directory.
2199 Therefore we advise against setting this variable to nil.
2200 Just change it to `y-or-n-p' if you want to confirm with a
2201 single keystroke rather than having to type \"yes\"."
2202 :group 'org-link-follow
2203 :type '(choice
2204 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2205 (const :tag "with y-or-n (faster)" y-or-n-p)
2206 (const :tag "no confirmation (dangerous)" nil)))
2207 (put 'org-confirm-shell-link-function
2208 'safe-local-variable
2209 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2211 (defcustom org-confirm-elisp-link-not-regexp ""
2212 "A regexp to skip confirmation for Elisp links."
2213 :group 'org-link-follow
2214 :version "24.1"
2215 :type 'regexp)
2217 (defconst org-file-apps-defaults-gnu
2218 '((remote . emacs)
2219 (system . mailcap)
2220 (t . mailcap))
2221 "Default file applications on a UNIX or GNU/Linux system.
2222 See `org-file-apps'.")
2224 (defconst org-file-apps-defaults-macosx
2225 '((remote . emacs)
2226 (system . "open %s")
2227 ("ps.gz" . "gv %s")
2228 ("eps.gz" . "gv %s")
2229 ("dvi" . "xdvi %s")
2230 ("fig" . "xfig %s")
2231 (t . "open %s"))
2232 "Default file applications on a macOS system.
2233 The system \"open\" is known as a default, but we use X11 applications
2234 for some files for which the OS does not have a good default.
2235 See `org-file-apps'.")
2237 (defconst org-file-apps-defaults-windowsnt
2238 (list '(remote . emacs)
2239 (cons 'system (lambda (file _path)
2240 (with-no-warnings (w32-shell-execute "open" file))))
2241 (cons t (lambda (file _path)
2242 (with-no-warnings (w32-shell-execute "open" file)))))
2243 "Default file applications on a Windows NT system.
2244 The system \"open\" is used for most files.
2245 See `org-file-apps'.")
2247 (defcustom org-file-apps
2248 '((auto-mode . emacs)
2249 ("\\.mm\\'" . default)
2250 ("\\.x?html?\\'" . default)
2251 ("\\.pdf\\'" . default))
2252 "External applications for opening `file:path' items in a document.
2253 \\<org-mode-map>\
2255 Org mode uses system defaults for different file types, but
2256 you can use this variable to set the application for a given file
2257 extension. The entries in this list are cons cells where the car identifies
2258 files and the cdr the corresponding command.
2260 Possible values for the file identifier are:
2262 \"string\" A string as a file identifier can be interpreted in different
2263 ways, depending on its contents:
2265 - Alphanumeric characters only:
2266 Match links with this file extension.
2267 Example: (\"pdf\" . \"evince %s\")
2268 to open PDFs with evince.
2270 - Regular expression: Match links where the
2271 filename matches the regexp. If you want to
2272 use groups here, use shy groups.
2274 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2275 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2276 to open *.html and *.xhtml with firefox.
2278 - Regular expression which contains (non-shy) groups:
2279 Match links where the whole link, including \"::\", and
2280 anything after that, matches the regexp.
2281 In a custom command string, %1, %2, etc. are replaced with
2282 the parts of the link that were matched by the groups.
2283 For backwards compatibility, if a command string is given
2284 that does not use any of the group matches, this case is
2285 handled identically to the second one (i.e. match against
2286 file name only).
2287 In a custom function, you can access the group matches with
2288 (match-string n link).
2290 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2291 \"evince -p %1 %s\")
2292 to open [[file:document.pdf::5]] with evince at page 5.
2294 `directory' Matches a directory
2295 `remote' Matches a remote file, accessible through tramp or efs.
2296 Remote files most likely should be visited through Emacs
2297 because external applications cannot handle such paths.
2298 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2299 so all files Emacs knows how to handle. Using this with
2300 command `emacs' will open most files in Emacs. Beware that this
2301 will also open html files inside Emacs, unless you add
2302 (\"html\" . default) to the list as well.
2303 `system' The system command to open files, like `open' on Windows
2304 and macOS, and mailcap under GNU/Linux. This is the command
2305 that will be selected if you call `org-open-at-point' with a
2306 double prefix argument (`\\[universal-argument] \
2307 \\[universal-argument] \\[org-open-at-point]').
2308 t Default for files not matched by any of the other options.
2310 Possible values for the command are:
2312 `emacs' The file will be visited by the current Emacs process.
2313 `default' Use the default application for this file type, which is the
2314 association for t in the list, most likely in the system-specific
2315 part. This can be used to overrule an unwanted setting in the
2316 system-specific variable.
2317 `system' Use the system command for opening files, like \"open\".
2318 This command is specified by the entry whose car is `system'.
2319 Most likely, the system-specific version of this variable
2320 does define this command, but you can overrule/replace it
2321 here.
2322 `mailcap' Use command specified in the mailcaps.
2323 string A command to be executed by a shell; %s will be replaced
2324 by the path to the file.
2325 function A Lisp function, which will be called with two arguments:
2326 the file path and the original link string, without the
2327 \"file:\" prefix.
2329 For more examples, see the system specific constants
2330 `org-file-apps-defaults-macosx'
2331 `org-file-apps-defaults-windowsnt'
2332 `org-file-apps-defaults-gnu'."
2333 :group 'org-link-follow
2334 :type '(repeat
2335 (cons (choice :value ""
2336 (string :tag "Extension")
2337 (const :tag "System command to open files" system)
2338 (const :tag "Default for unrecognized files" t)
2339 (const :tag "Remote file" remote)
2340 (const :tag "Links to a directory" directory)
2341 (const :tag "Any files that have Emacs modes"
2342 auto-mode))
2343 (choice :value ""
2344 (const :tag "Visit with Emacs" emacs)
2345 (const :tag "Use default" default)
2346 (const :tag "Use the system command" system)
2347 (string :tag "Command")
2348 (function :tag "Function")))))
2350 (defcustom org-doi-server-url "http://dx.doi.org/"
2351 "The URL of the DOI server."
2352 :type 'string
2353 :version "24.3"
2354 :group 'org-link-follow)
2356 (defgroup org-refile nil
2357 "Options concerning refiling entries in Org mode."
2358 :tag "Org Refile"
2359 :group 'org)
2361 (defcustom org-directory "~/org"
2362 "Directory with Org files.
2363 This is just a default location to look for Org files. There is no need
2364 at all to put your files into this directory. It is used in the
2365 following situations:
2367 1. When a capture template specifies a target file that is not an
2368 absolute path. The path will then be interpreted relative to
2369 `org-directory'
2370 2. When the value of variable `org-agenda-files' is a single file, any
2371 relative paths in this file will be taken as relative to
2372 `org-directory'."
2373 :group 'org-refile
2374 :group 'org-capture
2375 :type 'directory)
2377 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2378 "Default target for storing notes.
2379 Used as a fall back file for org-capture.el, for templates that
2380 do not specify a target file."
2381 :group 'org-refile
2382 :group 'org-capture
2383 :type 'file)
2385 (defcustom org-goto-interface 'outline
2386 "The default interface to be used for `org-goto'.
2387 Allowed values are:
2388 outline The interface shows an outline of the relevant file
2389 and the correct heading is found by moving through
2390 the outline or by searching with incremental search.
2391 outline-path-completion Headlines in the current buffer are offered via
2392 completion. This is the interface also used by
2393 the refile command."
2394 :group 'org-refile
2395 :type '(choice
2396 (const :tag "Outline" outline)
2397 (const :tag "Outline-path-completion" outline-path-completion)))
2399 (defcustom org-goto-max-level 5
2400 "Maximum target level when running `org-goto' with refile interface."
2401 :group 'org-refile
2402 :type 'integer)
2404 (defcustom org-reverse-note-order nil
2405 "Non-nil means store new notes at the beginning of a file or entry.
2406 When nil, new notes will be filed to the end of a file or entry.
2407 This can also be a list with cons cells of regular expressions that
2408 are matched against file names, and values."
2409 :group 'org-capture
2410 :group 'org-refile
2411 :type '(choice
2412 (const :tag "Reverse always" t)
2413 (const :tag "Reverse never" nil)
2414 (repeat :tag "By file name regexp"
2415 (cons regexp boolean))))
2417 (defcustom org-log-refile nil
2418 "Information to record when a task is refiled.
2420 Possible values are:
2422 nil Don't add anything
2423 time Add a time stamp to the task
2424 note Prompt for a note and add it with template `org-log-note-headings'
2426 This option can also be set with on a per-file-basis with
2428 #+STARTUP: nologrefile
2429 #+STARTUP: logrefile
2430 #+STARTUP: lognoterefile
2432 You can have local logging settings for a subtree by setting the LOGGING
2433 property to one or more of these keywords.
2435 When bulk-refiling from the agenda, the value `note' is forbidden and
2436 will temporarily be changed to `time'."
2437 :group 'org-refile
2438 :group 'org-progress
2439 :version "24.1"
2440 :type '(choice
2441 (const :tag "No logging" nil)
2442 (const :tag "Record timestamp" time)
2443 (const :tag "Record timestamp with note." note)))
2445 (defcustom org-refile-targets nil
2446 "Targets for refiling entries with `\\[org-refile]'.
2447 This is a list of cons cells. Each cell contains:
2448 - a specification of the files to be considered, either a list of files,
2449 or a symbol whose function or variable value will be used to retrieve
2450 a file name or a list of file names. If you use `org-agenda-files' for
2451 that, all agenda files will be scanned for targets. Nil means consider
2452 headings in the current buffer.
2453 - A specification of how to find candidate refile targets. This may be
2454 any of:
2455 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2456 This tag has to be present in all target headlines, inheritance will
2457 not be considered.
2458 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2459 todo keyword.
2460 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2461 headlines that are refiling targets.
2462 - a cons cell (:level . N). Any headline of level N is considered a target.
2463 Note that, when `org-odd-levels-only' is set, level corresponds to
2464 order in hierarchy, not to the number of stars.
2465 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2466 Note that, when `org-odd-levels-only' is set, level corresponds to
2467 order in hierarchy, not to the number of stars.
2469 Each element of this list generates a set of possible targets.
2470 The union of these sets is presented (with completion) to
2471 the user by `org-refile'.
2473 You can set the variable `org-refile-target-verify-function' to a function
2474 to verify each headline found by the simple criteria above.
2476 When this variable is nil, all top-level headlines in the current buffer
2477 are used, equivalent to the value `((nil . (:level . 1))'."
2478 :group 'org-refile
2479 :type '(repeat
2480 (cons
2481 (choice :value org-agenda-files
2482 (const :tag "All agenda files" org-agenda-files)
2483 (const :tag "Current buffer" nil)
2484 (function) (variable) (file))
2485 (choice :tag "Identify target headline by"
2486 (cons :tag "Specific tag" (const :value :tag) (string))
2487 (cons :tag "TODO keyword" (const :value :todo) (string))
2488 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2489 (cons :tag "Level number" (const :value :level) (integer))
2490 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2492 (defcustom org-refile-target-verify-function nil
2493 "Function to verify if the headline at point should be a refile target.
2494 The function will be called without arguments, with point at the
2495 beginning of the headline. It should return t and leave point
2496 where it is if the headline is a valid target for refiling.
2498 If the target should not be selected, the function must return nil.
2499 In addition to this, it may move point to a place from where the search
2500 should be continued. For example, the function may decide that the entire
2501 subtree of the current entry should be excluded and move point to the end
2502 of the subtree."
2503 :group 'org-refile
2504 :type '(choice
2505 (const nil)
2506 (function)))
2508 (defcustom org-refile-use-cache nil
2509 "Non-nil means cache refile targets to speed up the process.
2510 \\<org-mode-map>\
2511 The cache for a particular file will be updated automatically when
2512 the buffer has been killed, or when any of the marker used for flagging
2513 refile targets no longer points at a live buffer.
2514 If you have added new entries to a buffer that might themselves be targets,
2515 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2516 if you find that easier, \
2517 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2518 \\[org-refile]'."
2519 :group 'org-refile
2520 :version "24.1"
2521 :type 'boolean)
2523 (defcustom org-refile-use-outline-path nil
2524 "Non-nil means provide refile targets as paths.
2525 So a level 3 headline will be available as level1/level2/level3.
2527 When the value is `file', also include the file name (without directory)
2528 into the path. In this case, you can also stop the completion after
2529 the file name, to get entries inserted as top level in the file.
2531 When `full-file-path', include the full file path.
2533 When `buffer-name', use the buffer name."
2534 :group 'org-refile
2535 :type '(choice
2536 (const :tag "Not" nil)
2537 (const :tag "Yes" t)
2538 (const :tag "Start with file name" file)
2539 (const :tag "Start with full file path" full-file-path)
2540 (const :tag "Start with buffer name" buffer-name)))
2542 (defcustom org-outline-path-complete-in-steps t
2543 "Non-nil means complete the outline path in hierarchical steps.
2544 When Org uses the refile interface to select an outline path (see
2545 `org-refile-use-outline-path'), the completion of the path can be
2546 done in a single go, or it can be done in steps down the headline
2547 hierarchy. Going in steps is probably the best if you do not use
2548 a special completion package like `ido' or `icicles'. However,
2549 when using these packages, going in one step can be very fast,
2550 while still showing the whole path to the entry."
2551 :group 'org-refile
2552 :type 'boolean)
2554 (defcustom org-refile-allow-creating-parent-nodes nil
2555 "Non-nil means allow the creation of new nodes as refile targets.
2556 New nodes are then created by adding \"/new node name\" to the completion
2557 of an existing node. When the value of this variable is `confirm',
2558 new node creation must be confirmed by the user (recommended).
2559 When nil, the completion must match an existing entry.
2561 Note that, if the new heading is not seen by the criteria
2562 listed in `org-refile-targets', multiple instances of the same
2563 heading would be created by trying again to file under the new
2564 heading."
2565 :group 'org-refile
2566 :type '(choice
2567 (const :tag "Never" nil)
2568 (const :tag "Always" t)
2569 (const :tag "Prompt for confirmation" confirm)))
2571 (defcustom org-refile-active-region-within-subtree nil
2572 "Non-nil means also refile active region within a subtree.
2574 By default `org-refile' doesn't allow refiling regions if they
2575 don't contain a set of subtrees, but it might be convenient to
2576 do so sometimes: in that case, the first line of the region is
2577 converted to a headline before refiling."
2578 :group 'org-refile
2579 :version "24.1"
2580 :type 'boolean)
2582 (defgroup org-todo nil
2583 "Options concerning TODO items in Org mode."
2584 :tag "Org TODO"
2585 :group 'org)
2587 (defgroup org-progress nil
2588 "Options concerning Progress logging in Org mode."
2589 :tag "Org Progress"
2590 :group 'org-time)
2592 (defvar org-todo-interpretation-widgets
2593 '((:tag "Sequence (cycling hits every state)" sequence)
2594 (:tag "Type (cycling directly to DONE)" type))
2595 "The available interpretation symbols for customizing `org-todo-keywords'.
2596 Interested libraries should add to this list.")
2598 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2599 "List of TODO entry keyword sequences and their interpretation.
2600 \\<org-mode-map>This is a list of sequences.
2602 Each sequence starts with a symbol, either `sequence' or `type',
2603 indicating if the keywords should be interpreted as a sequence of
2604 action steps, or as different types of TODO items. The first
2605 keywords are states requiring action - these states will select a headline
2606 for inclusion into the global TODO list Org produces. If one of the
2607 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2608 signify that no further action is necessary. If \"|\" is not found,
2609 the last keyword is treated as the only DONE state of the sequence.
2611 The command `\\[org-todo]' cycles an entry through these states, and one
2612 additional state where no keyword is present. For details about this
2613 cycling, see the manual.
2615 TODO keywords and interpretation can also be set on a per-file basis with
2616 the special #+SEQ_TODO and #+TYP_TODO lines.
2618 Each keyword can optionally specify a character for fast state selection
2619 \(in combination with the variable `org-use-fast-todo-selection')
2620 and specifiers for state change logging, using the same syntax that
2621 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2622 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2623 indicates to record a time stamp each time this state is selected.
2625 Each keyword may also specify if a timestamp or a note should be
2626 recorded when entering or leaving the state, by adding additional
2627 characters in the parenthesis after the keyword. This looks like this:
2628 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2629 record only the time of the state change. With X and Y being either
2630 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2631 Y when leaving the state if and only if the *target* state does not
2632 define X. You may omit any of the fast-selection key or X or /Y,
2633 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2635 For backward compatibility, this variable may also be just a list
2636 of keywords. In this case the interpretation (sequence or type) will be
2637 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2638 :group 'org-todo
2639 :group 'org-keywords
2640 :type '(choice
2641 (repeat :tag "Old syntax, just keywords"
2642 (string :tag "Keyword"))
2643 (repeat :tag "New syntax"
2644 (cons
2645 (choice
2646 :tag "Interpretation"
2647 ;;Quick and dirty way to see
2648 ;;`org-todo-interpretations'. This takes the
2649 ;;place of item arguments
2650 :convert-widget
2651 (lambda (widget)
2652 (widget-put widget
2653 :args (mapcar
2654 (lambda (x)
2655 (widget-convert
2656 (cons 'const x)))
2657 org-todo-interpretation-widgets))
2658 widget))
2659 (repeat
2660 (string :tag "Keyword"))))))
2662 (defvar-local org-todo-keywords-1 nil
2663 "All TODO and DONE keywords active in a buffer.")
2664 (defvar org-todo-keywords-for-agenda nil)
2665 (defvar org-done-keywords-for-agenda nil)
2666 (defvar org-todo-keyword-alist-for-agenda nil)
2667 (defvar org-tag-alist-for-agenda nil
2668 "Alist of all tags from all agenda files.")
2669 (defvar org-tag-groups-alist-for-agenda nil
2670 "Alist of all groups tags from all current agenda files.")
2671 (defvar-local org-tag-groups-alist nil)
2672 (defvar org-agenda-contributing-files nil)
2673 (defvar-local org-current-tag-alist nil
2674 "Alist of all tag groups in current buffer.
2675 This variable takes into consideration `org-tag-alist',
2676 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2677 (defvar-local org-not-done-keywords nil)
2678 (defvar-local org-done-keywords nil)
2679 (defvar-local org-todo-heads nil)
2680 (defvar-local org-todo-sets nil)
2681 (defvar-local org-todo-log-states nil)
2682 (defvar-local org-todo-kwd-alist nil)
2683 (defvar-local org-todo-key-alist nil)
2684 (defvar-local org-todo-key-trigger nil)
2686 (defcustom org-todo-interpretation 'sequence
2687 "Controls how TODO keywords are interpreted.
2688 This variable is in principle obsolete and is only used for
2689 backward compatibility, if the interpretation of todo keywords is
2690 not given already in `org-todo-keywords'. See that variable for
2691 more information."
2692 :group 'org-todo
2693 :group 'org-keywords
2694 :type '(choice (const sequence)
2695 (const type)))
2697 (defcustom org-use-fast-todo-selection t
2698 "\\<org-mode-map>\
2699 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2700 This variable describes if and under what circumstances the cycling
2701 mechanism for TODO keywords will be replaced by a single-key, direct
2702 selection scheme.
2704 When nil, fast selection is never used.
2706 When the symbol `prefix', it will be used when `org-todo' is called
2707 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2708 in an Org buffer, and
2709 `\\[universal-argument] t' in an agenda buffer.
2711 When t, fast selection is used by default. In this case, the prefix
2712 argument forces cycling instead.
2714 In all cases, the special interface is only used if access keys have
2715 actually been assigned by the user, i.e. if keywords in the configuration
2716 are followed by a letter in parenthesis, like TODO(t)."
2717 :group 'org-todo
2718 :type '(choice
2719 (const :tag "Never" nil)
2720 (const :tag "By default" t)
2721 (const :tag "Only with C-u C-c C-t" prefix)))
2723 (defcustom org-provide-todo-statistics t
2724 "Non-nil means update todo statistics after insert and toggle.
2725 ALL-HEADLINES means update todo statistics by including headlines
2726 with no TODO keyword as well, counting them as not done.
2727 A list of TODO keywords means the same, but skip keywords that are
2728 not in this list.
2729 When set to a list of two lists, the first list contains keywords
2730 to consider as TODO keywords, the second list contains keywords
2731 to consider as DONE keywords.
2733 When this is set, todo statistics is updated in the parent of the
2734 current entry each time a todo state is changed."
2735 :group 'org-todo
2736 :type '(choice
2737 (const :tag "Yes, only for TODO entries" t)
2738 (const :tag "Yes, including all entries" all-headlines)
2739 (repeat :tag "Yes, for TODOs in this list"
2740 (string :tag "TODO keyword"))
2741 (list :tag "Yes, for TODOs and DONEs in these lists"
2742 (repeat (string :tag "TODO keyword"))
2743 (repeat (string :tag "DONE keyword")))
2744 (other :tag "No TODO statistics" nil)))
2746 (defcustom org-hierarchical-todo-statistics t
2747 "Non-nil means TODO statistics covers just direct children.
2748 When nil, all entries in the subtree are considered.
2749 This has only an effect if `org-provide-todo-statistics' is set.
2750 To set this to nil for only a single subtree, use a COOKIE_DATA
2751 property and include the word \"recursive\" into the value."
2752 :group 'org-todo
2753 :type 'boolean)
2755 (defcustom org-after-todo-state-change-hook nil
2756 "Hook which is run after the state of a TODO item was changed.
2757 The new state (a string with a TODO keyword, or nil) is available in the
2758 Lisp variable `org-state'."
2759 :group 'org-todo
2760 :type 'hook)
2762 (defvar org-blocker-hook nil
2763 "Hook for functions that are allowed to block a state change.
2765 Functions in this hook should not modify the buffer.
2766 Each function gets as its single argument a property list,
2767 see `org-trigger-hook' for more information about this list.
2769 If any of the functions in this hook returns nil, the state change
2770 is blocked.")
2772 (defvar org-trigger-hook nil
2773 "Hook for functions that are triggered by a state change.
2775 Each function gets as its single argument a property list with at
2776 least the following elements:
2778 (:type type-of-change :position pos-at-entry-start
2779 :from old-state :to new-state)
2781 Depending on the type, more properties may be present.
2783 This mechanism is currently implemented for:
2785 TODO state changes
2786 ------------------
2787 :type todo-state-change
2788 :from previous state (keyword as a string), or nil, or a symbol
2789 `todo' or `done', to indicate the general type of state.
2790 :to new state, like in :from")
2792 (defcustom org-enforce-todo-dependencies nil
2793 "Non-nil means undone TODO entries will block switching the parent to DONE.
2794 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2795 be blocked if any prior sibling is not yet done.
2796 Finally, if the parent is blocked because of ordered siblings of its own,
2797 the child will also be blocked."
2798 :set (lambda (var val)
2799 (set var val)
2800 (if val
2801 (add-hook 'org-blocker-hook
2802 'org-block-todo-from-children-or-siblings-or-parent)
2803 (remove-hook 'org-blocker-hook
2804 'org-block-todo-from-children-or-siblings-or-parent)))
2805 :group 'org-todo
2806 :type 'boolean)
2808 (defcustom org-enforce-todo-checkbox-dependencies nil
2809 "Non-nil means unchecked boxes will block switching the parent to DONE.
2810 When this is nil, checkboxes have no influence on switching TODO states.
2811 When non-nil, you first need to check off all check boxes before the TODO
2812 entry can be switched to DONE.
2813 This variable needs to be set before org.el is loaded, and you need to
2814 restart Emacs after a change to make the change effective. The only way
2815 to change is while Emacs is running is through the customize interface."
2816 :set (lambda (var val)
2817 (set var val)
2818 (if val
2819 (add-hook 'org-blocker-hook
2820 'org-block-todo-from-checkboxes)
2821 (remove-hook 'org-blocker-hook
2822 'org-block-todo-from-checkboxes)))
2823 :group 'org-todo
2824 :type 'boolean)
2826 (defcustom org-treat-insert-todo-heading-as-state-change nil
2827 "Non-nil means inserting a TODO heading is treated as state change.
2828 So when the command `\\[org-insert-todo-heading]' is used, state change
2829 logging will apply if appropriate. When nil, the new TODO item will
2830 be inserted directly, and no logging will take place."
2831 :group 'org-todo
2832 :type 'boolean)
2834 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2835 "Non-nil means switching TODO states with S-cursor counts as state change.
2836 This is the default behavior. However, setting this to nil allows a
2837 convenient way to select a TODO state and bypass any logging associated
2838 with that."
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-todo-state-tags-triggers nil
2843 "Tag changes that should be triggered by TODO state changes.
2844 This is a list. Each entry is
2846 (state-change (tag . flag) .......)
2848 State-change can be a string with a state, and empty string to indicate the
2849 state that has no TODO keyword, or it can be one of the symbols `todo'
2850 or `done', meaning any not-done or done state, respectively."
2851 :group 'org-todo
2852 :group 'org-tags
2853 :type '(repeat
2854 (cons (choice :tag "When changing to"
2855 (const :tag "Not-done state" todo)
2856 (const :tag "Done state" done)
2857 (string :tag "State"))
2858 (repeat
2859 (cons :tag "Tag action"
2860 (string :tag "Tag")
2861 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2863 (defcustom org-log-done nil
2864 "Information to record when a task moves to the DONE state.
2866 Possible values are:
2868 nil Don't add anything, just change the keyword
2869 time Add a time stamp to the task
2870 note Prompt for a note and add it with template `org-log-note-headings'
2872 This option can also be set with on a per-file-basis with
2874 #+STARTUP: nologdone
2875 #+STARTUP: logdone
2876 #+STARTUP: lognotedone
2878 You can have local logging settings for a subtree by setting the LOGGING
2879 property to one or more of these keywords."
2880 :group 'org-todo
2881 :group 'org-progress
2882 :type '(choice
2883 (const :tag "No logging" nil)
2884 (const :tag "Record CLOSED timestamp" time)
2885 (const :tag "Record CLOSED timestamp with note." note)))
2887 ;; Normalize old uses of org-log-done.
2888 (cond
2889 ((eq org-log-done t) (setq org-log-done 'time))
2890 ((and (listp org-log-done) (memq 'done org-log-done))
2891 (setq org-log-done 'note)))
2893 (defcustom org-log-reschedule nil
2894 "Information to record when the scheduling date of a tasks is modified.
2896 Possible values are:
2898 nil Don't add anything, just change the date
2899 time Add a time stamp to the task
2900 note Prompt for a note and add it with template `org-log-note-headings'
2902 This option can also be set with on a per-file-basis with
2904 #+STARTUP: nologreschedule
2905 #+STARTUP: logreschedule
2906 #+STARTUP: lognotereschedule"
2907 :group 'org-todo
2908 :group 'org-progress
2909 :type '(choice
2910 (const :tag "No logging" nil)
2911 (const :tag "Record timestamp" time)
2912 (const :tag "Record timestamp with note." note)))
2914 (defcustom org-log-redeadline nil
2915 "Information to record when the deadline date of a tasks is modified.
2917 Possible values are:
2919 nil Don't add anything, just change the date
2920 time Add a time stamp to the task
2921 note Prompt for a note and add it with template `org-log-note-headings'
2923 This option can also be set with on a per-file-basis with
2925 #+STARTUP: nologredeadline
2926 #+STARTUP: logredeadline
2927 #+STARTUP: lognoteredeadline
2929 You can have local logging settings for a subtree by setting the LOGGING
2930 property to one or more of these keywords."
2931 :group 'org-todo
2932 :group 'org-progress
2933 :type '(choice
2934 (const :tag "No logging" nil)
2935 (const :tag "Record timestamp" time)
2936 (const :tag "Record timestamp with note." note)))
2938 (defcustom org-log-note-clock-out nil
2939 "Non-nil means record a note when clocking out of an item.
2940 This can also be configured on a per-file basis by adding one of
2941 the following lines anywhere in the buffer:
2943 #+STARTUP: lognoteclock-out
2944 #+STARTUP: nolognoteclock-out"
2945 :group 'org-todo
2946 :group 'org-progress
2947 :type 'boolean)
2949 (defcustom org-log-done-with-time t
2950 "Non-nil means the CLOSED time stamp will contain date and time.
2951 When nil, only the date will be recorded."
2952 :group 'org-progress
2953 :type 'boolean)
2955 (defcustom org-log-note-headings
2956 '((done . "CLOSING NOTE %t")
2957 (state . "State %-12s from %-12S %t")
2958 (note . "Note taken on %t")
2959 (reschedule . "Rescheduled from %S on %t")
2960 (delschedule . "Not scheduled, was %S on %t")
2961 (redeadline . "New deadline from %S on %t")
2962 (deldeadline . "Removed deadline, was %S on %t")
2963 (refile . "Refiled on %t")
2964 (clock-out . ""))
2965 "Headings for notes added to entries.
2967 The value is an alist, with the car being a symbol indicating the
2968 note context, and the cdr is the heading to be used. The heading
2969 may also be the empty string. The following placeholders can be
2970 used:
2972 %t a time stamp.
2973 %T an active time stamp instead the default inactive one
2974 %d a short-format time stamp.
2975 %D an active short-format time stamp.
2976 %s the new TODO state or time stamp (inactive), in double quotes.
2977 %S the old TODO state or time stamp (inactive), in double quotes.
2978 %u the user name.
2979 %U full user name.
2981 In fact, it is not a good idea to change the `state' entry,
2982 because Agenda Log mode depends on the format of these entries."
2983 :group 'org-todo
2984 :group 'org-progress
2985 :type '(list :greedy t
2986 (cons (const :tag "Heading when closing an item" done) string)
2987 (cons (const :tag
2988 "Heading when changing todo state (todo sequence only)"
2989 state) string)
2990 (cons (const :tag "Heading when just taking a note" note) string)
2991 (cons (const :tag "Heading when rescheduling" reschedule) string)
2992 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2993 (cons (const :tag "Heading when changing deadline" redeadline) string)
2994 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2995 (cons (const :tag "Heading when refiling" refile) string)
2996 (cons (const :tag "Heading when clocking out" clock-out) string)))
2998 (unless (assq 'note org-log-note-headings)
2999 (push '(note . "%t") org-log-note-headings))
3001 (defcustom org-log-into-drawer nil
3002 "Non-nil means insert state change notes and time stamps into a drawer.
3003 When nil, state changes notes will be inserted after the headline and
3004 any scheduling and clock lines, but not inside a drawer.
3006 The value of this variable should be the name of the drawer to use.
3007 LOGBOOK is proposed as the default drawer for this purpose, you can
3008 also set this to a string to define the drawer of your choice.
3010 A value of t is also allowed, representing \"LOGBOOK\".
3012 A value of t or nil can also be set with on a per-file-basis with
3014 #+STARTUP: logdrawer
3015 #+STARTUP: nologdrawer
3017 If this variable is set, `org-log-state-notes-insert-after-drawers'
3018 will be ignored.
3020 You can set the property LOG_INTO_DRAWER to overrule this setting for
3021 a subtree.
3023 Do not check directly this variable in a Lisp program. Call
3024 function `org-log-into-drawer' instead."
3025 :group 'org-todo
3026 :group 'org-progress
3027 :type '(choice
3028 (const :tag "Not into a drawer" nil)
3029 (const :tag "LOGBOOK" t)
3030 (string :tag "Other")))
3032 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3034 (defun org-log-into-drawer ()
3035 "Name of the log drawer, as a string, or nil.
3036 This is the value of `org-log-into-drawer'. However, if the
3037 current entry has or inherits a LOG_INTO_DRAWER property, it will
3038 be used instead of the default value."
3039 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3040 (cond ((equal p "nil") nil)
3041 ((equal p "t") "LOGBOOK")
3042 ((stringp p) p)
3043 (p "LOGBOOK")
3044 ((stringp org-log-into-drawer) org-log-into-drawer)
3045 (org-log-into-drawer "LOGBOOK"))))
3047 (defcustom org-log-state-notes-insert-after-drawers nil
3048 "Non-nil means insert state change notes after any drawers in entry.
3049 Only the drawers that *immediately* follow the headline and the
3050 deadline/scheduled line are skipped.
3051 When nil, insert notes right after the heading and perhaps the line
3052 with deadline/scheduling if present.
3054 This variable will have no effect if `org-log-into-drawer' is
3055 set."
3056 :group 'org-todo
3057 :group 'org-progress
3058 :type 'boolean)
3060 (defcustom org-log-states-order-reversed t
3061 "Non-nil means the latest state note will be directly after heading.
3062 When nil, the state change notes will be ordered according to time.
3064 This option can also be set with on a per-file-basis with
3066 #+STARTUP: logstatesreversed
3067 #+STARTUP: nologstatesreversed"
3068 :group 'org-todo
3069 :group 'org-progress
3070 :type 'boolean)
3072 (defcustom org-todo-repeat-to-state nil
3073 "The TODO state to which a repeater should return the repeating task.
3074 By default this is the first task in a TODO sequence, or the previous state
3075 in a TODO_TYP set. But you can specify another task here.
3076 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3077 :group 'org-todo
3078 :version "24.1"
3079 :type '(choice (const :tag "Head of sequence" nil)
3080 (string :tag "Specific state")))
3082 (defcustom org-log-repeat 'time
3083 "Non-nil means record moving through the DONE state when triggering repeat.
3084 An auto-repeating task is immediately switched back to TODO when
3085 marked DONE. If you are not logging state changes (by adding \"@\"
3086 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3087 record a closing note, there will be no record of the task moving
3088 through DONE. This variable forces taking a note anyway.
3090 nil Don't force a record
3091 time Record a time stamp
3092 note Prompt for a note and add it with template `org-log-note-headings'
3094 This option can also be set with on a per-file-basis with
3096 #+STARTUP: nologrepeat
3097 #+STARTUP: logrepeat
3098 #+STARTUP: lognoterepeat
3100 You can have local logging settings for a subtree by setting the LOGGING
3101 property to one or more of these keywords."
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type '(choice
3105 (const :tag "Don't force a record" nil)
3106 (const :tag "Force recording the DONE state" time)
3107 (const :tag "Force recording a note with the DONE state" note)))
3110 (defgroup org-priorities nil
3111 "Priorities in Org mode."
3112 :tag "Org Priorities"
3113 :group 'org-todo)
3115 (defcustom org-enable-priority-commands t
3116 "Non-nil means priority commands are active.
3117 When nil, these commands will be disabled, so that you never accidentally
3118 set a priority."
3119 :group 'org-priorities
3120 :type 'boolean)
3122 (defcustom org-highest-priority ?A
3123 "The highest priority of TODO items. A character like ?A, ?B etc.
3124 Must have a smaller ASCII number than `org-lowest-priority'."
3125 :group 'org-priorities
3126 :type 'character)
3128 (defcustom org-lowest-priority ?C
3129 "The lowest priority of TODO items. A character like ?A, ?B etc.
3130 Must have a larger ASCII number than `org-highest-priority'."
3131 :group 'org-priorities
3132 :type 'character)
3134 (defcustom org-default-priority ?B
3135 "The default priority of TODO items.
3136 This is the priority an item gets if no explicit priority is given.
3137 When starting to cycle on an empty priority the first step in the cycle
3138 depends on `org-priority-start-cycle-with-default'. The resulting first
3139 step priority must not exceed the range from `org-highest-priority' to
3140 `org-lowest-priority' which means that `org-default-priority' has to be
3141 in this range exclusive or inclusive the range boundaries. Else the
3142 first step refuses to set the default and the second will fall back
3143 to (depending on the command used) the highest or lowest priority."
3144 :group 'org-priorities
3145 :type 'character)
3147 (defcustom org-priority-start-cycle-with-default t
3148 "Non-nil means start with default priority when starting to cycle.
3149 When this is nil, the first step in the cycle will be (depending on the
3150 command used) one higher or lower than the default priority.
3151 See also `org-default-priority'."
3152 :group 'org-priorities
3153 :type 'boolean)
3155 (defcustom org-get-priority-function nil
3156 "Function to extract the priority from a string.
3157 The string is normally the headline. If this is nil Org computes the
3158 priority from the priority cookie like [#A] in the headline. It returns
3159 an integer, increasing by 1000 for each priority level.
3160 The user can set a different function here, which should take a string
3161 as an argument and return the numeric priority."
3162 :group 'org-priorities
3163 :version "24.1"
3164 :type '(choice
3165 (const nil)
3166 (function)))
3168 (defgroup org-time nil
3169 "Options concerning time stamps and deadlines in Org mode."
3170 :tag "Org Time"
3171 :group 'org)
3173 (defcustom org-time-stamp-rounding-minutes '(0 5)
3174 "Number of minutes to round time stamps to.
3175 \\<org-mode-map>\
3176 These are two values, the first applies when first creating a time stamp.
3177 The second applies when changing it with the commands `S-up' and `S-down'.
3178 When changing the time stamp, this means that it will change in steps
3179 of N minutes, as given by the second value.
3181 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3182 numbers should be factors of 60, so for example 5, 10, 15.
3184 When this is larger than 1, you can still force an exact time stamp by using
3185 a double prefix argument to a time stamp command like \
3186 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3187 and by using a prefix arg to `S-up/down' to specify the exact number
3188 of minutes to shift."
3189 :group 'org-time
3190 :get (lambda (var) ; Make sure both elements are there
3191 (if (integerp (default-value var))
3192 (list (default-value var) 5)
3193 (default-value var)))
3194 :type '(list
3195 (integer :tag "when inserting times")
3196 (integer :tag "when modifying times")))
3198 ;; Normalize old customizations of this variable.
3199 (when (integerp org-time-stamp-rounding-minutes)
3200 (setq org-time-stamp-rounding-minutes
3201 (list org-time-stamp-rounding-minutes
3202 org-time-stamp-rounding-minutes)))
3204 (defcustom org-display-custom-times nil
3205 "Non-nil means overlay custom formats over all time stamps.
3206 The formats are defined through the variable `org-time-stamp-custom-formats'.
3207 To turn this on on a per-file basis, insert anywhere in the file:
3208 #+STARTUP: customtime"
3209 :group 'org-time
3210 :set 'set-default
3211 :type 'sexp)
3212 (make-variable-buffer-local 'org-display-custom-times)
3214 (defcustom org-time-stamp-custom-formats
3215 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3216 "Custom formats for time stamps. See `format-time-string' for the syntax.
3217 These are overlaid over the default ISO format if the variable
3218 `org-display-custom-times' is set. Time like %H:%M should be at the
3219 end of the second format. The custom formats are also honored by export
3220 commands, if custom time display is turned on at the time of export."
3221 :group 'org-time
3222 :type 'sexp)
3224 (defun org-time-stamp-format (&optional long inactive)
3225 "Get the right format for a time string."
3226 (let ((f (if long (cdr org-time-stamp-formats)
3227 (car org-time-stamp-formats))))
3228 (if inactive
3229 (concat "[" (substring f 1 -1) "]")
3230 f)))
3232 (defcustom org-deadline-warning-days 14
3233 "Number of days before expiration during which a deadline becomes active.
3234 This variable governs the display in sparse trees and in the agenda.
3235 When 0 or negative, it means use this number (the absolute value of it)
3236 even if a deadline has a different individual lead time specified.
3238 Custom commands can set this variable in the options section."
3239 :group 'org-time
3240 :group 'org-agenda-daily/weekly
3241 :type 'integer)
3243 (defcustom org-scheduled-delay-days 0
3244 "Number of days before a scheduled item becomes active.
3245 This variable governs the display in sparse trees and in the agenda.
3246 The default value (i.e. 0) means: don't delay scheduled item.
3247 When negative, it means use this number (the absolute value of it)
3248 even if a scheduled item has a different individual delay time
3249 specified.
3251 Custom commands can set this variable in the options section."
3252 :group 'org-time
3253 :group 'org-agenda-daily/weekly
3254 :version "24.4"
3255 :package-version '(Org . "8.0")
3256 :type 'integer)
3258 (defcustom org-read-date-prefer-future t
3259 "Non-nil means assume future for incomplete date input from user.
3260 This affects the following situations:
3261 1. The user gives a month but not a year.
3262 For example, if it is April and you enter \"feb 2\", this will be read
3263 as Feb 2, *next* year. \"May 5\", however, will be this year.
3264 2. The user gives a day, but no month.
3265 For example, if today is the 15th, and you enter \"3\", Org will read
3266 this as the third of *next* month. However, if you enter \"17\",
3267 it will be considered as *this* month.
3269 If you set this variable to the symbol `time', then also the following
3270 will work:
3272 3. If the user gives a time.
3273 If the time is before now, it will be interpreted as tomorrow.
3275 Currently none of this works for ISO week specifications.
3277 When this option is nil, the current day, month and year will always be
3278 used as defaults.
3280 See also `org-agenda-jump-prefer-future'."
3281 :group 'org-time
3282 :type '(choice
3283 (const :tag "Never" nil)
3284 (const :tag "Check month and day" t)
3285 (const :tag "Check month, day, and time" time)))
3287 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3288 "Should the agenda jump command prefer the future for incomplete dates?
3289 The default is to do the same as configured in `org-read-date-prefer-future'.
3290 But you can also set a deviating value here.
3291 This may t or nil, or the symbol `org-read-date-prefer-future'."
3292 :group 'org-agenda
3293 :group 'org-time
3294 :version "24.1"
3295 :type '(choice
3296 (const :tag "Use org-read-date-prefer-future"
3297 org-read-date-prefer-future)
3298 (const :tag "Never" nil)
3299 (const :tag "Always" t)))
3301 (defcustom org-read-date-force-compatible-dates t
3302 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3304 Depending on the system Emacs is running on, certain dates cannot
3305 be represented with the type used internally to represent time.
3306 Dates between 1970-1-1 and 2038-1-1 can always be represented
3307 correctly. Some systems allow for earlier dates, some for later,
3308 some for both. One way to find out it to insert any date into an
3309 Org buffer, putting the cursor on the year and hitting S-up and
3310 S-down to test the range.
3312 When this variable is set to t, the date/time prompt will not let
3313 you specify dates outside the 1970-2037 range, so it is certain that
3314 these dates will work in whatever version of Emacs you are
3315 running, and also that you can move a file from one Emacs implementation
3316 to another. WHenever Org is forcing the year for you, it will display
3317 a message and beep.
3319 When this variable is nil, Org will check if the date is
3320 representable in the specific Emacs implementation you are using.
3321 If not, it will force a year, usually the current year, and beep
3322 to remind you. Currently this setting is not recommended because
3323 the likelihood that you will open your Org files in an Emacs that
3324 has limited date range is not negligible.
3326 A workaround for this problem is to use diary sexp dates for time
3327 stamps outside of this range."
3328 :group 'org-time
3329 :version "24.1"
3330 :type 'boolean)
3332 (defcustom org-read-date-display-live t
3333 "Non-nil means display current interpretation of date prompt live.
3334 This display will be in an overlay, in the minibuffer."
3335 :group 'org-time
3336 :type 'boolean)
3338 (defcustom org-read-date-popup-calendar t
3339 "Non-nil means pop up a calendar when prompting for a date.
3340 In the calendar, the date can be selected with mouse-1. However, the
3341 minibuffer will also be active, and you can simply enter the date as well.
3342 When nil, only the minibuffer will be available."
3343 :group 'org-time
3344 :type 'boolean)
3345 (defvaralias 'org-popup-calendar-for-date-prompt
3346 'org-read-date-popup-calendar)
3348 (defcustom org-extend-today-until 0
3349 "The hour when your day really ends. Must be an integer.
3350 This has influence for the following applications:
3351 - When switching the agenda to \"today\". It it is still earlier than
3352 the time given here, the day recognized as TODAY is actually yesterday.
3353 - When a date is read from the user and it is still before the time given
3354 here, the current date and time will be assumed to be yesterday, 23:59.
3355 Also, timestamps inserted in capture templates follow this rule.
3357 IMPORTANT: This is a feature whose implementation is and likely will
3358 remain incomplete. Really, it is only here because past midnight seems to
3359 be the favorite working time of John Wiegley :-)"
3360 :group 'org-time
3361 :type 'integer)
3363 (defcustom org-use-effective-time nil
3364 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3365 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3366 \"effective time\" of any timestamps between midnight and 8am will be
3367 23:59 of the previous day."
3368 :group 'org-time
3369 :version "24.1"
3370 :type 'boolean)
3372 (defcustom org-use-last-clock-out-time-as-effective-time nil
3373 "When non-nil, use the last clock out time for `org-todo'.
3374 Note that this option has precedence over the combined use of
3375 `org-use-effective-time' and `org-extend-today-until'."
3376 :group 'org-time
3377 :version "24.4"
3378 :package-version '(Org . "8.0")
3379 :type 'boolean)
3381 (defcustom org-edit-timestamp-down-means-later nil
3382 "Non-nil means S-down will increase the time in a time stamp.
3383 When nil, S-up will increase."
3384 :group 'org-time
3385 :type 'boolean)
3387 (defcustom org-calendar-follow-timestamp-change t
3388 "Non-nil means make the calendar window follow timestamp changes.
3389 When a timestamp is modified and the calendar window is visible, it will be
3390 moved to the new date."
3391 :group 'org-time
3392 :type 'boolean)
3394 (defgroup org-tags nil
3395 "Options concerning tags in Org mode."
3396 :tag "Org Tags"
3397 :group 'org)
3399 (defcustom org-tag-alist nil
3400 "Default tags available in Org files.
3402 The value of this variable is an alist. Associations either:
3404 (TAG)
3405 (TAG . SELECT)
3406 (SPECIAL)
3408 where TAG is a tag as a string, SELECT is character, used to
3409 select that tag through the fast tag selection interface, and
3410 SPECIAL is one of the following keywords: `:startgroup',
3411 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3412 `:newline'. These keywords are used to define a hierarchy of
3413 tags. See manual for details.
3415 When this variable is nil, Org mode bases tag input on what is
3416 already in the buffer. The value can be overridden locally by
3417 using a TAGS keyword, e.g.,
3419 #+TAGS: tag1 tag2
3421 See also `org-tag-persistent-alist' to sidestep this behavior."
3422 :group 'org-tags
3423 :type '(repeat
3424 (choice
3425 (cons :tag "Tag with key"
3426 (string :tag "Tag name")
3427 (character :tag "Access char"))
3428 (list :tag "Tag" (string :tag "Tag name"))
3429 (const :tag "Start radio group" (:startgroup))
3430 (const :tag "Start tag group, non distinct" (:startgrouptag))
3431 (const :tag "Group tags delimiter" (:grouptags))
3432 (const :tag "End radio group" (:endgroup))
3433 (const :tag "End tag group, non distinct" (:endgrouptag))
3434 (const :tag "New line" (:newline)))))
3436 (defcustom org-tag-persistent-alist nil
3437 "Tags always available in Org files.
3439 The value of this variable is an alist. Associations either:
3441 (TAG)
3442 (TAG . SELECT)
3443 (SPECIAL)
3445 where TAG is a tag as a string, SELECT is a character, used to
3446 select that tag through the fast tag selection interface, and
3447 SPECIAL is one of the following keywords: `:startgroup',
3448 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3449 `:newline'. These keywords are used to define a hierarchy of
3450 tags. See manual for details.
3452 Unlike to `org-tag-alist', tags defined in this variable do not
3453 depend on a local TAGS keyword. Instead, to disable these tags
3454 on a per-file basis, insert anywhere in the file:
3456 #+STARTUP: noptag"
3457 :group 'org-tags
3458 :type '(repeat
3459 (choice
3460 (cons :tag "Tag with key"
3461 (string :tag "Tag name")
3462 (character :tag "Access char"))
3463 (list :tag "Tag" (string :tag "Tag name"))
3464 (const :tag "Start radio group" (:startgroup))
3465 (const :tag "Start tag group, non distinct" (:startgrouptag))
3466 (const :tag "Group tags delimiter" (:grouptags))
3467 (const :tag "End radio group" (:endgroup))
3468 (const :tag "End tag group, non distinct" (:endgrouptag))
3469 (const :tag "New line" (:newline)))))
3471 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3472 "If non-nil, always offer completion for all tags of all agenda files.
3473 Instead of customizing this variable directly, you might want to
3474 set it locally for capture buffers, because there no list of
3475 tags in that file can be created dynamically (there are none).
3477 (add-hook \\='org-capture-mode-hook
3478 (lambda ()
3479 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3480 :group 'org-tags
3481 :version "24.1"
3482 :type 'boolean)
3484 (defvar org-file-tags nil
3485 "List of tags that can be inherited by all entries in the file.
3486 The tags will be inherited if the variable `org-use-tag-inheritance'
3487 says they should be.
3488 This variable is populated from #+FILETAGS lines.")
3490 (defcustom org-use-fast-tag-selection 'auto
3491 "Non-nil means use fast tag selection scheme.
3492 This is a special interface to select and deselect tags with single keys.
3493 When nil, fast selection is never used.
3494 When the symbol `auto', fast selection is used if and only if selection
3495 characters for tags have been configured, either through the variable
3496 `org-tag-alist' or through a #+TAGS line in the buffer.
3497 When t, fast selection is always used and selection keys are assigned
3498 automatically if necessary."
3499 :group 'org-tags
3500 :type '(choice
3501 (const :tag "Always" t)
3502 (const :tag "Never" nil)
3503 (const :tag "When selection characters are configured" auto)))
3505 (defcustom org-fast-tag-selection-single-key nil
3506 "Non-nil means fast tag selection exits after first change.
3507 When nil, you have to press RET to exit it.
3508 During fast tag selection, you can toggle this flag with `C-c'.
3509 This variable can also have the value `expert'. In this case, the window
3510 displaying the tags menu is not even shown, until you press C-c again."
3511 :group 'org-tags
3512 :type '(choice
3513 (const :tag "No" nil)
3514 (const :tag "Yes" t)
3515 (const :tag "Expert" expert)))
3517 (defvar org-fast-tag-selection-include-todo nil
3518 "Non-nil means fast tags selection interface will also offer TODO states.
3519 This is an undocumented feature, you should not rely on it.")
3521 (defcustom org-tags-column -77
3522 "The column to which tags should be indented in a headline.
3523 If this number is positive, it specifies the column. If it is negative,
3524 it means that the tags should be flushright to that column. For example,
3525 -80 works well for a normal 80 character screen.
3526 When 0, place tags directly after headline text, with only one space in
3527 between."
3528 :group 'org-tags
3529 :type 'integer)
3531 (defcustom org-auto-align-tags t
3532 "Non-nil keeps tags aligned when modifying headlines.
3533 Some operations (i.e. demoting) change the length of a headline and
3534 therefore shift the tags around. With this option turned on, after
3535 each such operation the tags are again aligned to `org-tags-column'."
3536 :group 'org-tags
3537 :type 'boolean)
3539 (defcustom org-use-tag-inheritance t
3540 "Non-nil means tags in levels apply also for sublevels.
3541 When nil, only the tags directly given in a specific line apply there.
3542 This may also be a list of tags that should be inherited, or a regexp that
3543 matches tags that should be inherited. Additional control is possible
3544 with the variable `org-tags-exclude-from-inheritance' which gives an
3545 explicit list of tags to be excluded from inheritance, even if the value of
3546 `org-use-tag-inheritance' would select it for inheritance.
3548 If this option is t, a match early-on in a tree can lead to a large
3549 number of matches in the subtree when constructing the agenda or creating
3550 a sparse tree. If you only want to see the first match in a tree during
3551 a search, check out the variable `org-tags-match-list-sublevels'."
3552 :group 'org-tags
3553 :type '(choice
3554 (const :tag "Not" nil)
3555 (const :tag "Always" t)
3556 (repeat :tag "Specific tags" (string :tag "Tag"))
3557 (regexp :tag "Tags matched by regexp")))
3559 (defcustom org-tags-exclude-from-inheritance nil
3560 "List of tags that should never be inherited.
3561 This is a way to exclude a few tags from inheritance. For way to do
3562 the opposite, to actively allow inheritance for selected tags,
3563 see the variable `org-use-tag-inheritance'."
3564 :group 'org-tags
3565 :type '(repeat (string :tag "Tag")))
3567 (defun org-tag-inherit-p (tag)
3568 "Check if TAG is one that should be inherited."
3569 (cond
3570 ((member tag org-tags-exclude-from-inheritance) nil)
3571 ((eq org-use-tag-inheritance t) t)
3572 ((not org-use-tag-inheritance) nil)
3573 ((stringp org-use-tag-inheritance)
3574 (string-match org-use-tag-inheritance tag))
3575 ((listp org-use-tag-inheritance)
3576 (member tag org-use-tag-inheritance))
3577 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3579 (defcustom org-tags-match-list-sublevels t
3580 "Non-nil means list also sublevels of headlines matching a search.
3581 This variable applies to tags/property searches, and also to stuck
3582 projects because this search is based on a tags match as well.
3584 When set to the symbol `indented', sublevels are indented with
3585 leading dots.
3587 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3588 the sublevels of a headline matching a tag search often also match
3589 the same search. Listing all of them can create very long lists.
3590 Setting this variable to nil causes subtrees of a match to be skipped.
3592 This variable is semi-obsolete and probably should always be true. It
3593 is better to limit inheritance to certain tags using the variables
3594 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3595 :group 'org-tags
3596 :type '(choice
3597 (const :tag "No, don't list them" nil)
3598 (const :tag "Yes, do list them" t)
3599 (const :tag "List them, indented with leading dots" indented)))
3601 (defcustom org-tags-sort-function nil
3602 "When set, tags are sorted using this function as a comparator."
3603 :group 'org-tags
3604 :type '(choice
3605 (const :tag "No sorting" nil)
3606 (const :tag "Alphabetical" string<)
3607 (const :tag "Reverse alphabetical" string>)
3608 (function :tag "Custom function" nil)))
3610 (defvar org-tags-history nil
3611 "History of minibuffer reads for tags.")
3612 (defvar org-last-tags-completion-table nil
3613 "The last used completion table for tags.")
3614 (defvar org-after-tags-change-hook nil
3615 "Hook that is run after the tags in a line have changed.")
3617 (defgroup org-properties nil
3618 "Options concerning properties in Org mode."
3619 :tag "Org Properties"
3620 :group 'org)
3622 (defcustom org-property-format "%-10s %s"
3623 "How property key/value pairs should be formatted by `indent-line'.
3624 When `indent-line' hits a property definition, it will format the line
3625 according to this format, mainly to make sure that the values are
3626 lined-up with respect to each other."
3627 :group 'org-properties
3628 :type 'string)
3630 (defcustom org-properties-postprocess-alist nil
3631 "Alist of properties and functions to adjust inserted values.
3632 Elements of this alist must be of the form
3634 ([string] [function])
3636 where [string] must be a property name and [function] must be a
3637 lambda expression: this lambda expression must take one argument,
3638 the value to adjust, and return the new value as a string.
3640 For example, this element will allow the property \"Remaining\"
3641 to be updated wrt the relation between the \"Effort\" property
3642 and the clock summary:
3644 ((\"Remaining\" (lambda(value)
3645 (let ((clocksum (org-clock-sum-current-item))
3646 (effort (org-duration-to-minutes
3647 (org-entry-get (point) \"Effort\"))))
3648 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3649 :group 'org-properties
3650 :version "24.1"
3651 :type '(alist :key-type (string :tag "Property")
3652 :value-type (function :tag "Function")))
3654 (defcustom org-use-property-inheritance nil
3655 "Non-nil means properties apply also for sublevels.
3657 This setting is chiefly used during property searches. Turning it on can
3658 cause significant overhead when doing a search, which is why it is not
3659 on by default.
3661 When nil, only the properties directly given in the current entry count.
3662 When t, every property is inherited. The value may also be a list of
3663 properties that should have inheritance, or a regular expression matching
3664 properties that should be inherited.
3666 However, note that some special properties use inheritance under special
3667 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3668 and the properties ending in \"_ALL\" when they are used as descriptor
3669 for valid values of a property.
3671 Note for programmers:
3672 When querying an entry with `org-entry-get', you can control if inheritance
3673 should be used. By default, `org-entry-get' looks only at the local
3674 properties. You can request inheritance by setting the inherit argument
3675 to t (to force inheritance) or to `selective' (to respect the setting
3676 in this variable)."
3677 :group 'org-properties
3678 :type '(choice
3679 (const :tag "Not" nil)
3680 (const :tag "Always" t)
3681 (repeat :tag "Specific properties" (string :tag "Property"))
3682 (regexp :tag "Properties matched by regexp")))
3684 (defun org-property-inherit-p (property)
3685 "Return a non-nil value if PROPERTY should be inherited."
3686 (cond
3687 ((eq org-use-property-inheritance t) t)
3688 ((not org-use-property-inheritance) nil)
3689 ((stringp org-use-property-inheritance)
3690 (string-match org-use-property-inheritance property))
3691 ((listp org-use-property-inheritance)
3692 (member-ignore-case property org-use-property-inheritance))
3693 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3695 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3696 "The default column format, if no other format has been defined.
3697 This variable can be set on the per-file basis by inserting a line
3699 #+COLUMNS: %25ITEM ....."
3700 :group 'org-properties
3701 :type 'string)
3703 (defcustom org-columns-ellipses ".."
3704 "The ellipses to be used when a field in column view is truncated.
3705 When this is the empty string, as many characters as possible are shown,
3706 but then there will be no visual indication that the field has been truncated.
3707 When this is a string of length N, the last N characters of a truncated
3708 field are replaced by this string. If the column is narrower than the
3709 ellipses string, only part of the ellipses string will be shown."
3710 :group 'org-properties
3711 :type 'string)
3713 (defconst org-global-properties-fixed
3714 '(("VISIBILITY_ALL" . "folded children content all")
3715 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3716 "List of property/value pairs that can be inherited by any entry.
3718 These are fixed values, for the preset properties. The user variable
3719 that can be used to add to this list is `org-global-properties'.
3721 The entries in this list are cons cells where the car is a property
3722 name and cdr is a string with the value. If the value represents
3723 multiple items like an \"_ALL\" property, separate the items by
3724 spaces.")
3726 (defcustom org-global-properties nil
3727 "List of property/value pairs that can be inherited by any entry.
3729 This list will be combined with the constant `org-global-properties-fixed'.
3731 The entries in this list are cons cells where the car is a property
3732 name and cdr is a string with the value.
3734 You can set buffer-local values for the same purpose in the variable
3735 `org-file-properties' this by adding lines like
3737 #+PROPERTY: NAME VALUE"
3738 :group 'org-properties
3739 :type '(repeat
3740 (cons (string :tag "Property")
3741 (string :tag "Value"))))
3743 (defvar-local org-file-properties nil
3744 "List of property/value pairs that can be inherited by any entry.
3745 Valid for the current buffer.
3746 This variable is populated from #+PROPERTY lines.")
3748 (defgroup org-agenda nil
3749 "Options concerning agenda views in Org mode."
3750 :tag "Org Agenda"
3751 :group 'org)
3753 (defvar-local org-category nil
3754 "Variable used by org files to set a category for agenda display.
3755 Such files should use a file variable to set it, for example
3757 # -*- mode: org; org-category: \"ELisp\"
3759 or contain a special line
3761 #+CATEGORY: ELisp
3763 If the file does not specify a category, then file's base name
3764 is used instead.")
3765 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3767 (defcustom org-agenda-files nil
3768 "The files to be used for agenda display.
3770 If an entry is a directory, all files in that directory that are matched
3771 by `org-agenda-file-regexp' will be part of the file list.
3773 If the value of the variable is not a list but a single file name, then
3774 the list of agenda files is actually stored and maintained in that file,
3775 one agenda file per line. In this file paths can be given relative to
3776 `org-directory'. Tilde expansion and environment variable substitution
3777 are also made.
3779 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3780 and removed with `\\[org-remove-file]'."
3781 :group 'org-agenda
3782 :type '(choice
3783 (repeat :tag "List of files and directories" file)
3784 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3786 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3787 "Regular expression to match files for `org-agenda-files'.
3788 If any element in the list in that variable contains a directory instead
3789 of a normal file, all files in that directory that are matched by this
3790 regular expression will be included."
3791 :group 'org-agenda
3792 :type 'regexp)
3794 (defcustom org-agenda-text-search-extra-files nil
3795 "List of extra files to be searched by text search commands.
3796 These files will be searched in addition to the agenda files by the
3797 commands `org-search-view' (`\\[org-agenda] s') \
3798 and `org-occur-in-agenda-files'.
3799 Note that these files will only be searched for text search commands,
3800 not for the other agenda views like todo lists, tag searches or the weekly
3801 agenda. This variable is intended to list notes and possibly archive files
3802 that should also be searched by these two commands.
3803 In fact, if the first element in the list is the symbol `agenda-archives',
3804 then all archive files of all agenda files will be added to the search
3805 scope."
3806 :group 'org-agenda
3807 :type '(set :greedy t
3808 (const :tag "Agenda Archives" agenda-archives)
3809 (repeat :inline t (file))))
3811 (defvaralias 'org-agenda-multi-occur-extra-files
3812 'org-agenda-text-search-extra-files)
3814 (defcustom org-agenda-skip-unavailable-files nil
3815 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3816 A nil value means to remove them, after a query, from the list."
3817 :group 'org-agenda
3818 :type 'boolean)
3820 (defcustom org-calendar-to-agenda-key [?c]
3821 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3822 The command `org-calendar-goto-agenda' will be bound to this key. The
3823 default is the character `c' because then `c' can be used to switch back and
3824 forth between agenda and calendar."
3825 :group 'org-agenda
3826 :type 'sexp)
3828 (defcustom org-calendar-insert-diary-entry-key [?i]
3829 "The key to be installed in `calendar-mode-map' for adding diary entries.
3830 This option is irrelevant until `org-agenda-diary-file' has been configured
3831 to point to an Org file. When that is the case, the command
3832 `org-agenda-diary-entry' will be bound to the key given here, by default
3833 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3834 if you want to continue doing this, you need to change this to a different
3835 key."
3836 :group 'org-agenda
3837 :type 'sexp)
3839 (defcustom org-agenda-diary-file 'diary-file
3840 "File to which to add new entries with the `i' key in agenda and calendar.
3841 When this is the symbol `diary-file', the functionality in the Emacs
3842 calendar will be used to add entries to the `diary-file'. But when this
3843 points to a file, `org-agenda-diary-entry' will be used instead."
3844 :group 'org-agenda
3845 :type '(choice
3846 (const :tag "The standard Emacs diary file" diary-file)
3847 (file :tag "Special Org file diary entries")))
3849 (eval-after-load "calendar"
3850 '(progn
3851 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3852 'org-calendar-goto-agenda)
3853 (add-hook 'calendar-mode-hook
3854 (lambda ()
3855 (unless (eq org-agenda-diary-file 'diary-file)
3856 (define-key calendar-mode-map
3857 org-calendar-insert-diary-entry-key
3858 'org-agenda-diary-entry))))))
3860 (defgroup org-latex nil
3861 "Options for embedding LaTeX code into Org mode."
3862 :tag "Org LaTeX"
3863 :group 'org)
3865 (defcustom org-format-latex-options
3866 '(:foreground default :background default :scale 1.0
3867 :html-foreground "Black" :html-background "Transparent"
3868 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3869 "Options for creating images from LaTeX fragments.
3870 This is a property list with the following properties:
3871 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3872 `default' means use the foreground of the default face.
3873 `auto' means use the foreground from the text face.
3874 :background the background color, or \"Transparent\".
3875 `default' means use the background of the default face.
3876 `auto' means use the background from the text face.
3877 :scale a scaling factor for the size of the images, to get more pixels
3878 :html-foreground, :html-background, :html-scale
3879 the same numbers for HTML export.
3880 :matchers a list indicating which matchers should be used to
3881 find LaTeX fragments. Valid members of this list are:
3882 \"begin\" find environments
3883 \"$1\" find single characters surrounded by $.$
3884 \"$\" find math expressions surrounded by $...$
3885 \"$$\" find math expressions surrounded by $$....$$
3886 \"\\(\" find math expressions surrounded by \\(...\\)
3887 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3888 :group 'org-latex
3889 :type 'plist)
3891 (defcustom org-format-latex-signal-error t
3892 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3893 When nil, just push out a message."
3894 :group 'org-latex
3895 :version "24.1"
3896 :type 'boolean)
3898 (defcustom org-latex-to-mathml-jar-file nil
3899 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3900 Use this to specify additional executable file say a jar file.
3902 When using MathToWeb as the converter, specify the full-path to
3903 your mathtoweb.jar file."
3904 :group 'org-latex
3905 :version "24.1"
3906 :type '(choice
3907 (const :tag "None" nil)
3908 (file :tag "JAR file" :must-match t)))
3910 (defcustom org-latex-to-mathml-convert-command nil
3911 "Command to convert LaTeX fragments to MathML.
3912 Replace format-specifiers in the command as noted below and use
3913 `shell-command' to convert LaTeX to MathML.
3914 %j: Executable file in fully expanded form as specified by
3915 `org-latex-to-mathml-jar-file'.
3916 %I: Input LaTeX file in fully expanded form.
3917 %i: The latex fragment to be converted.
3918 %o: Output MathML file.
3920 This command is used by `org-create-math-formula'.
3922 When using MathToWeb as the converter, set this option to
3923 \"java -jar %j -unicode -force -df %o %I\".
3925 When using LaTeXML set this option to
3926 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3927 :group 'org-latex
3928 :version "24.1"
3929 :type '(choice
3930 (const :tag "None" nil)
3931 (string :tag "\nShell command")))
3933 (defcustom org-preview-latex-default-process 'dvipng
3934 "The default process to convert LaTeX fragments to image files.
3935 All available processes and theirs documents can be found in
3936 `org-preview-latex-process-alist', which see."
3937 :group 'org-latex
3938 :version "26.1"
3939 :package-version '(Org . "9.0")
3940 :type 'symbol)
3942 (defcustom org-preview-latex-process-alist
3943 '((dvipng
3944 :programs ("latex" "dvipng")
3945 :description "dvi > png"
3946 :message "you need to install the programs: latex and dvipng."
3947 :image-input-type "dvi"
3948 :image-output-type "png"
3949 :image-size-adjust (1.0 . 1.0)
3950 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3951 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3952 (dvisvgm
3953 :programs ("latex" "dvisvgm")
3954 :description "dvi > svg"
3955 :message "you need to install the programs: latex and dvisvgm."
3956 :use-xcolor t
3957 :image-input-type "dvi"
3958 :image-output-type "svg"
3959 :image-size-adjust (1.7 . 1.5)
3960 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3961 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3962 (imagemagick
3963 :programs ("latex" "convert")
3964 :description "pdf > png"
3965 :message "you need to install the programs: latex and imagemagick."
3966 :use-xcolor t
3967 :image-input-type "pdf"
3968 :image-output-type "png"
3969 :image-size-adjust (1.0 . 1.0)
3970 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3971 :image-converter
3972 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3973 "Definitions of external processes for LaTeX previewing.
3974 Org mode can use some external commands to generate TeX snippet's images for
3975 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3976 `org-create-formula-image' how to call them.
3978 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3979 PROPERTIES accepts the following attributes:
3981 :programs list of strings, required programs.
3982 :description string, describe the process.
3983 :message string, message it when required programs cannot be found.
3984 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3985 :image-output-type string, output file type of image converter (e.g., \"png\").
3986 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3987 deal with background and foreground color of image.
3988 Otherwise, dvipng style background and foreground color
3989 format are generated. You may then refer to them in
3990 command options with \"%F\" and \"%B\".
3991 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3992 image size showed in buffer and the cdr element is for
3993 HTML file. This option is only useful for process
3994 developers, users should use variable
3995 `org-format-latex-options' instead.
3996 :post-clean list of strings, files matched are to be cleaned up once
3997 the image is generated. When nil, the files with \".dvi\",
3998 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3999 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4000 be cleaned up.
4001 :latex-header list of strings, the LaTeX header of the snippet file.
4002 When nil, the fallback value is used instead, which is
4003 controlled by `org-format-latex-header',
4004 `org-latex-default-packages-alist' and
4005 `org-latex-packages-alist', which see.
4006 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4007 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4008 replaced with values defined below.
4009 :image-converter list of image converter commands strings. Each of them is
4010 given to the shell and supports any of the following
4011 place-holders defined below.
4013 Place-holders used by `:image-converter' and `:latex-compiler':
4015 %f input file name
4016 %b base name of input file
4017 %o base directory of input file
4018 %O absolute output file name
4020 Place-holders only used by `:image-converter':
4022 %F foreground of image
4023 %B background of image
4024 %D dpi, which is used to adjust image size by some processing commands.
4025 %S the image size scale ratio, which is used to adjust image size by some
4026 processing commands."
4027 :group 'org-latex
4028 :version "26.1"
4029 :package-version '(Org . "9.0")
4030 :type '(alist :tag "LaTeX to image backends"
4031 :value-type (plist)))
4033 (defcustom org-preview-latex-image-directory "ltximg/"
4034 "Path to store latex preview images.
4035 A relative path here creates many directories relative to the
4036 processed org files paths. An absolute path puts all preview
4037 images at the same place."
4038 :group 'org-latex
4039 :version "26.1"
4040 :package-version '(Org . "9.0")
4041 :type 'string)
4043 (defun org-format-latex-mathml-available-p ()
4044 "Return t if `org-latex-to-mathml-convert-command' is usable."
4045 (save-match-data
4046 (when (and (boundp 'org-latex-to-mathml-convert-command)
4047 org-latex-to-mathml-convert-command)
4048 (let ((executable (car (split-string
4049 org-latex-to-mathml-convert-command))))
4050 (when (executable-find executable)
4051 (if (string-match
4052 "%j" org-latex-to-mathml-convert-command)
4053 (file-readable-p org-latex-to-mathml-jar-file)
4054 t))))))
4056 (defcustom org-format-latex-header "\\documentclass{article}
4057 \\usepackage[usenames]{color}
4058 \[PACKAGES]
4059 \[DEFAULT-PACKAGES]
4060 \\pagestyle{empty} % do not remove
4061 % The settings below are copied from fullpage.sty
4062 \\setlength{\\textwidth}{\\paperwidth}
4063 \\addtolength{\\textwidth}{-3cm}
4064 \\setlength{\\oddsidemargin}{1.5cm}
4065 \\addtolength{\\oddsidemargin}{-2.54cm}
4066 \\setlength{\\evensidemargin}{\\oddsidemargin}
4067 \\setlength{\\textheight}{\\paperheight}
4068 \\addtolength{\\textheight}{-\\headheight}
4069 \\addtolength{\\textheight}{-\\headsep}
4070 \\addtolength{\\textheight}{-\\footskip}
4071 \\addtolength{\\textheight}{-3cm}
4072 \\setlength{\\topmargin}{1.5cm}
4073 \\addtolength{\\topmargin}{-2.54cm}"
4074 "The document header used for processing LaTeX fragments.
4075 It is imperative that this header make sure that no page number
4076 appears on the page. The package defined in the variables
4077 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4078 will either replace the placeholder \"[PACKAGES]\" in this
4079 header, or they will be appended."
4080 :group 'org-latex
4081 :type 'string)
4083 (defun org-set-packages-alist (var val)
4084 "Set the packages alist and make sure it has 3 elements per entry."
4085 (set var (mapcar (lambda (x)
4086 (if (and (consp x) (= (length x) 2))
4087 (list (car x) (nth 1 x) t)
4089 val)))
4091 (defun org-get-packages-alist (var)
4092 "Get the packages alist and make sure it has 3 elements per entry."
4093 (mapcar (lambda (x)
4094 (if (and (consp x) (= (length x) 2))
4095 (list (car x) (nth 1 x) t)
4097 (default-value var)))
4099 (defcustom org-latex-default-packages-alist
4100 '(("AUTO" "inputenc" t ("pdflatex"))
4101 ("T1" "fontenc" t ("pdflatex"))
4102 ("" "graphicx" t)
4103 ("" "grffile" t)
4104 ("" "longtable" nil)
4105 ("" "wrapfig" nil)
4106 ("" "rotating" nil)
4107 ("normalem" "ulem" t)
4108 ("" "amsmath" t)
4109 ("" "textcomp" t)
4110 ("" "amssymb" t)
4111 ("" "capt-of" nil)
4112 ("" "hyperref" nil))
4113 "Alist of default packages to be inserted in the header.
4115 Change this only if one of the packages here causes an
4116 incompatibility with another package you are using.
4118 The packages in this list are needed by one part or another of
4119 Org mode to function properly:
4121 - inputenc, fontenc: for basic font and character selection
4122 - graphicx: for including images
4123 - grffile: allow periods and spaces in graphics file names
4124 - longtable: For multipage tables
4125 - wrapfig: for figure placement
4126 - rotating: for sideways figures and tables
4127 - ulem: for underline and strike-through
4128 - amsmath: for subscript and superscript and math environments
4129 - textcomp, amssymb: for various symbols used
4130 for interpreting the entities in `org-entities'. You can skip
4131 some of these packages if you don't use any of their symbols.
4132 - capt-of: for captions outside of floats
4133 - hyperref: for cross references
4135 Therefore you should not modify this variable unless you know
4136 what you are doing. The one reason to change it anyway is that
4137 you might be loading some other package that conflicts with one
4138 of the default packages. Each element is either a cell or
4139 a string.
4141 A cell is of the format
4143 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4145 If SNIPPET-FLAG is non-nil, the package also needs to be included
4146 when compiling LaTeX snippets into images for inclusion into
4147 non-LaTeX output. COMPILERS is a list of compilers that should
4148 include the package, see `org-latex-compiler'. If the document
4149 compiler is not in the list, and the list is non-nil, the package
4150 will not be inserted in the final document.
4152 A string will be inserted as-is in the header of the document."
4153 :group 'org-latex
4154 :group 'org-export-latex
4155 :set 'org-set-packages-alist
4156 :get 'org-get-packages-alist
4157 :version "26.1"
4158 :package-version '(Org . "8.3")
4159 :type '(repeat
4160 (choice
4161 (list :tag "options/package pair"
4162 (string :tag "options")
4163 (string :tag "package")
4164 (boolean :tag "Snippet"))
4165 (string :tag "A line of LaTeX"))))
4167 (defcustom org-latex-packages-alist nil
4168 "Alist of packages to be inserted in every LaTeX header.
4170 These will be inserted after `org-latex-default-packages-alist'.
4171 Each element is either a cell or a string.
4173 A cell is of the format:
4175 (\"options\" \"package\" SNIPPET-FLAG)
4177 SNIPPET-FLAG, when non-nil, indicates that this package is also
4178 needed when turning LaTeX snippets into images for inclusion into
4179 non-LaTeX output.
4181 A string will be inserted as-is in the header of the document.
4183 Make sure that you only list packages here which:
4185 - you want in every file;
4186 - do not conflict with the setup in `org-format-latex-header';
4187 - do not conflict with the default packages in
4188 `org-latex-default-packages-alist'."
4189 :group 'org-latex
4190 :group 'org-export-latex
4191 :set 'org-set-packages-alist
4192 :get 'org-get-packages-alist
4193 :type '(repeat
4194 (choice
4195 (list :tag "options/package pair"
4196 (string :tag "options")
4197 (string :tag "package")
4198 (boolean :tag "Snippet"))
4199 (string :tag "A line of LaTeX"))))
4201 (defgroup org-appearance nil
4202 "Settings for Org mode appearance."
4203 :tag "Org Appearance"
4204 :group 'org)
4206 (defcustom org-level-color-stars-only nil
4207 "Non-nil means fontify only the stars in each headline.
4208 When nil, the entire headline is fontified.
4209 Changing it requires restart of `font-lock-mode' to become effective
4210 also in regions already fontified."
4211 :group 'org-appearance
4212 :type 'boolean)
4214 (defcustom org-hide-leading-stars nil
4215 "Non-nil means hide the first N-1 stars in a headline.
4216 This works by using the face `org-hide' for these stars. This
4217 face is white for a light background, and black for a dark
4218 background. You may have to customize the face `org-hide' to
4219 make this work.
4220 Changing it requires restart of `font-lock-mode' to become effective
4221 also in regions already fontified.
4222 You may also set this on a per-file basis by adding one of the following
4223 lines to the buffer:
4225 #+STARTUP: hidestars
4226 #+STARTUP: showstars"
4227 :group 'org-appearance
4228 :type 'boolean)
4230 (defcustom org-hidden-keywords nil
4231 "List of symbols corresponding to keywords to be hidden the org buffer.
4232 For example, a value \\='(title) for this list will make the document's title
4233 appear in the buffer without the initial #+TITLE: keyword."
4234 :group 'org-appearance
4235 :version "24.1"
4236 :type '(set (const :tag "#+AUTHOR" author)
4237 (const :tag "#+DATE" date)
4238 (const :tag "#+EMAIL" email)
4239 (const :tag "#+TITLE" title)))
4241 (defcustom org-custom-properties nil
4242 "List of properties (as strings) with a special meaning.
4243 The default use of these custom properties is to let the user
4244 hide them with `org-toggle-custom-properties-visibility'."
4245 :group 'org-properties
4246 :group 'org-appearance
4247 :version "24.3"
4248 :type '(repeat (string :tag "Property Name")))
4250 (defcustom org-fontify-done-headline nil
4251 "Non-nil means change the face of a headline if it is marked DONE.
4252 Normally, only the TODO/DONE keyword indicates the state of a headline.
4253 When this is non-nil, the headline after the keyword is set to the
4254 `org-headline-done' as an additional indication."
4255 :group 'org-appearance
4256 :type 'boolean)
4258 (defcustom org-fontify-emphasized-text t
4259 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4260 Changing this variable requires a restart of Emacs to take effect."
4261 :group 'org-appearance
4262 :type 'boolean)
4264 (defcustom org-fontify-whole-heading-line nil
4265 "Non-nil means fontify the whole line for headings.
4266 This is useful when setting a background color for the
4267 org-level-* faces."
4268 :group 'org-appearance
4269 :type 'boolean)
4271 (defcustom org-highlight-latex-and-related nil
4272 "Non-nil means highlight LaTeX related syntax in the buffer.
4273 When non nil, the value should be a list containing any of the
4274 following symbols:
4275 `latex' Highlight LaTeX snippets and environments.
4276 `script' Highlight subscript and superscript.
4277 `entities' Highlight entities."
4278 :group 'org-appearance
4279 :version "24.4"
4280 :package-version '(Org . "8.0")
4281 :type '(choice
4282 (const :tag "No highlighting" nil)
4283 (set :greedy t :tag "Highlight"
4284 (const :tag "LaTeX snippets and environments" latex)
4285 (const :tag "Subscript and superscript" script)
4286 (const :tag "Entities" entities))))
4288 (defcustom org-hide-emphasis-markers nil
4289 "Non-nil mean font-lock should hide the emphasis marker characters."
4290 :group 'org-appearance
4291 :type 'boolean)
4293 (defcustom org-hide-macro-markers nil
4294 "Non-nil mean font-lock should hide the brackets marking macro calls."
4295 :group 'org-appearance
4296 :type 'boolean)
4298 (defcustom org-pretty-entities nil
4299 "Non-nil means show entities as UTF8 characters.
4300 When nil, the \\name form remains in the buffer."
4301 :group 'org-appearance
4302 :version "24.1"
4303 :type 'boolean)
4305 (defcustom org-pretty-entities-include-sub-superscripts t
4306 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4307 :group 'org-appearance
4308 :version "24.1"
4309 :type 'boolean)
4311 (defvar org-emph-re nil
4312 "Regular expression for matching emphasis.
4313 After a match, the match groups contain these elements:
4314 0 The match of the full regular expression, including the characters
4315 before and after the proper match
4316 1 The character before the proper match, or empty at beginning of line
4317 2 The proper match, including the leading and trailing markers
4318 3 The leading marker like * or /, indicating the type of highlighting
4319 4 The text between the emphasis markers, not including the markers
4320 5 The character after the match, empty at the end of a line")
4322 (defvar org-verbatim-re nil
4323 "Regular expression for matching verbatim text.")
4325 (defvar org-emphasis-regexp-components) ; defined just below
4326 (defvar org-emphasis-alist) ; defined just below
4327 (defun org-set-emph-re (var val)
4328 "Set variable and compute the emphasis regular expression."
4329 (set var val)
4330 (when (and (boundp 'org-emphasis-alist)
4331 (boundp 'org-emphasis-regexp-components)
4332 org-emphasis-alist org-emphasis-regexp-components)
4333 (pcase-let*
4334 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4335 (body (if (<= nl 0) body
4336 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4337 (template
4338 (format (concat "\\([%s]\\|^\\)" ;before markers
4339 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4340 "\\([%s]\\|$\\)") ;after markers
4341 pre border border body border post)))
4342 (setq org-emph-re (format template "*/_+"))
4343 (setq org-verbatim-re (format template "=~")))))
4345 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4346 ;; set this option proved cumbersome. See this message/thread:
4347 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4348 (defvar org-emphasis-regexp-components
4349 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4350 "Components used to build the regular expression for emphasis.
4351 This is a list with five entries. Terminology: In an emphasis string
4352 like \" *strong word* \", we call the initial space PREMATCH, the final
4353 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4354 and \"trong wor\" is the body. The different components in this variable
4355 specify what is allowed/forbidden in each part:
4357 pre Chars allowed as prematch. Beginning of line will be allowed too.
4358 post Chars allowed as postmatch. End of line will be allowed too.
4359 border The chars *forbidden* as border characters.
4360 body-regexp A regexp like \".\" to match a body character. Don't use
4361 non-shy groups here, and don't allow newline here.
4362 newline The maximum number of newlines allowed in an emphasis exp.
4364 You need to reload Org or to restart Emacs after setting this.")
4366 (defcustom org-emphasis-alist
4367 '(("*" bold)
4368 ("/" italic)
4369 ("_" underline)
4370 ("=" org-verbatim verbatim)
4371 ("~" org-code verbatim)
4372 ("+" (:strike-through t)))
4373 "Alist of characters and faces to emphasize text.
4374 Text starting and ending with a special character will be emphasized,
4375 for example *bold*, _underlined_ and /italic/. This variable sets the
4376 marker characters and the face to be used by font-lock for highlighting
4377 in Org buffers.
4379 You need to reload Org or to restart Emacs after customizing this."
4380 :group 'org-appearance
4381 :set 'org-set-emph-re
4382 :version "24.4"
4383 :package-version '(Org . "8.0")
4384 :type '(repeat
4385 (list
4386 (string :tag "Marker character")
4387 (choice
4388 (face :tag "Font-lock-face")
4389 (plist :tag "Face property list"))
4390 (option (const verbatim)))))
4392 (defvar org-protecting-blocks '("src" "example" "export")
4393 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4394 This is needed for font-lock setup.")
4396 ;;; Functions and variables from their packages
4397 ;; Declared here to avoid compiler warnings
4398 (defvar mark-active)
4400 ;; Various packages
4401 (declare-function calc-eval "calc" (str &optional separator &rest args))
4402 (declare-function calendar-forward-day "cal-move" (arg))
4403 (declare-function calendar-goto-date "cal-move" (date))
4404 (declare-function calendar-goto-today "cal-move" ())
4405 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4406 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4407 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4408 (declare-function cdlatex-tab "ext:cdlatex" ())
4409 (declare-function dired-get-filename
4410 "dired"
4411 (&optional localp no-error-if-not-filep))
4412 (declare-function iswitchb-read-buffer
4413 "iswitchb"
4414 (prompt &optional
4415 default require-match _predicate start matches-set))
4416 (declare-function org-agenda-change-all-lines
4417 "org-agenda"
4418 (newhead hdmarker &optional fixface just-this))
4419 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4420 "org-agenda"
4421 (&optional end))
4422 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4423 (declare-function org-agenda-format-item
4424 "org-agenda"
4425 (extra txt &optional level category tags dotime
4426 remove-re habitp))
4427 (declare-function org-agenda-maybe-redo "org-agenda" ())
4428 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4429 (declare-function org-agenda-save-markers-for-cut-and-paste
4430 "org-agenda"
4431 (beg end))
4432 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4433 (declare-function org-agenda-skip "org-agenda" ())
4434 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4435 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4436 (declare-function org-indent-mode "org-indent" (&optional arg))
4437 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4438 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4439 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4440 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4441 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4442 (declare-function parse-time-string "parse-time" (string))
4443 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4445 (defvar align-mode-rules-list)
4446 (defvar calc-embedded-close-formula)
4447 (defvar calc-embedded-open-formula)
4448 (defvar calc-embedded-open-mode)
4449 (defvar font-lock-unfontify-region-function)
4450 (defvar iswitchb-temp-buflist)
4451 (defvar org-agenda-tags-todo-honor-ignore-options)
4452 (defvar remember-data-file)
4453 (defvar texmathp-why)
4455 ;;;###autoload
4456 (defun turn-on-orgtbl ()
4457 "Unconditionally turn on `orgtbl-mode'."
4458 (require 'org-table)
4459 (orgtbl-mode 1))
4461 (defun org-at-table-p (&optional table-type)
4462 "Non-nil if the cursor is inside an Org table.
4463 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4464 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4465 (or (not (derived-mode-p 'org-mode))
4466 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4467 (and e (or table-type
4468 (eq 'org (org-element-property :type e))))))))
4470 (defun org-at-table.el-p ()
4471 "Non-nil when point is at a table.el table."
4472 (and (org-match-line "[ \t]*[|+]")
4473 (let ((element (org-element-at-point)))
4474 (and (eq (org-element-type element) 'table)
4475 (eq (org-element-property :type element) 'table.el)))))
4477 (defun org-at-table-hline-p ()
4478 "Non-nil when point is inside a hline in a table.
4479 Assume point is already in a table."
4480 (org-match-line org-table-hline-regexp))
4482 (defun org-table-map-tables (function &optional quietly)
4483 "Apply FUNCTION to the start of all tables in the buffer."
4484 (org-with-wide-buffer
4485 (goto-char (point-min))
4486 (while (re-search-forward org-table-any-line-regexp nil t)
4487 (unless quietly
4488 (message "Mapping tables: %d%%"
4489 (floor (* 100.0 (point)) (buffer-size))))
4490 (beginning-of-line 1)
4491 (when (and (looking-at org-table-line-regexp)
4492 ;; Exclude tables in src/example/verbatim/clocktable blocks
4493 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4494 (save-excursion (funcall function))
4495 (or (looking-at org-table-line-regexp)
4496 (forward-char 1)))
4497 (re-search-forward org-table-any-border-regexp nil 1)))
4498 (unless quietly (message "Mapping tables: done")))
4500 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4501 (declare-function org-clock-update-mode-line "org-clock" ())
4502 (declare-function org-resolve-clocks "org-clock"
4503 (&optional also-non-dangling-p prompt last-valid))
4505 (defun org-at-TBLFM-p (&optional pos)
4506 "Non-nil when point (or POS) is in #+TBLFM line."
4507 (save-excursion
4508 (goto-char (or pos (point)))
4509 (beginning-of-line)
4510 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4511 (eq (org-element-type (org-element-at-point)) 'table))))
4513 (defvar org-clock-start-time)
4514 (defvar org-clock-marker (make-marker)
4515 "Marker recording the last clock-in.")
4516 (defvar org-clock-hd-marker (make-marker)
4517 "Marker recording the last clock-in, but the headline position.")
4518 (defvar org-clock-heading ""
4519 "The heading of the current clock entry.")
4520 (defun org-clock-is-active ()
4521 "Return the buffer where the clock is currently running.
4522 Return nil if no clock is running."
4523 (marker-buffer org-clock-marker))
4525 (defun org-check-running-clock ()
4526 "Check if the current buffer contains the running clock.
4527 If yes, offer to stop it and to save the buffer with the changes."
4528 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4529 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4530 (buffer-name))))
4531 (org-clock-out)
4532 (when (y-or-n-p "Save changed buffer?")
4533 (save-buffer))))
4535 (defun org-clocktable-try-shift (dir n)
4536 "Check if this line starts a clock table, if yes, shift the time block."
4537 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4538 (org-clocktable-shift dir n)))
4540 ;;;###autoload
4541 (defun org-clock-persistence-insinuate ()
4542 "Set up hooks for clock persistence."
4543 (require 'org-clock)
4544 (add-hook 'org-mode-hook 'org-clock-load)
4545 (add-hook 'kill-emacs-hook 'org-clock-save))
4547 (defgroup org-archive nil
4548 "Options concerning archiving in Org mode."
4549 :tag "Org Archive"
4550 :group 'org-structure)
4552 (defcustom org-archive-location "%s_archive::"
4553 "The location where subtrees should be archived.
4555 The value of this variable is a string, consisting of two parts,
4556 separated by a double-colon. The first part is a filename and
4557 the second part is a headline.
4559 When the filename is omitted, archiving happens in the same file.
4560 %s in the filename will be replaced by the current file
4561 name (without the directory part). Archiving to a different file
4562 is useful to keep archived entries from contributing to the
4563 Org Agenda.
4565 The archived entries will be filed as subtrees of the specified
4566 headline. When the headline is omitted, the subtrees are simply
4567 filed away at the end of the file, as top-level entries. Also in
4568 the heading you can use %s to represent the file name, this can be
4569 useful when using the same archive for a number of different files.
4571 Here are a few examples:
4572 \"%s_archive::\"
4573 If the current file is Projects.org, archive in file
4574 Projects.org_archive, as top-level trees. This is the default.
4576 \"::* Archived Tasks\"
4577 Archive in the current file, under the top-level headline
4578 \"* Archived Tasks\".
4580 \"~/org/archive.org::\"
4581 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4583 \"~/org/archive.org::* From %s\"
4584 Archive in file ~/org/archive.org (absolute path), under headlines
4585 \"From FILENAME\" where file name is the current file name.
4587 \"~/org/datetree.org::datetree/* Finished Tasks\"
4588 The \"datetree/\" string is special, signifying to archive
4589 items to the datetree. Items are placed in either the CLOSED
4590 date of the item, or the current date if there is no CLOSED date.
4591 The heading will be a subentry to the current date. There doesn't
4592 need to be a heading, but there always needs to be a slash after
4593 datetree. For example, to store archived items directly in the
4594 datetree, use \"~/org/datetree.org::datetree/\".
4596 \"basement::** Finished Tasks\"
4597 Archive in file ./basement (relative path), as level 3 trees
4598 below the level 2 heading \"** Finished Tasks\".
4600 You may set this option on a per-file basis by adding to the buffer a
4601 line like
4603 #+ARCHIVE: basement::** Finished Tasks
4605 You may also define it locally for a subtree by setting an ARCHIVE property
4606 in the entry. If such a property is found in an entry, or anywhere up
4607 the hierarchy, it will be used."
4608 :group 'org-archive
4609 :type 'string)
4611 (defcustom org-agenda-skip-archived-trees t
4612 "Non-nil means the agenda will skip any items located in archived trees.
4613 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4614 variable is no longer recommended, you should leave it at the value t.
4615 Instead, use the key `v' to cycle the archives-mode in the agenda."
4616 :group 'org-archive
4617 :group 'org-agenda-skip
4618 :type 'boolean)
4620 (defcustom org-columns-skip-archived-trees t
4621 "Non-nil means ignore archived trees when creating column view."
4622 :group 'org-archive
4623 :group 'org-properties
4624 :type 'boolean)
4626 (defcustom org-cycle-open-archived-trees nil
4627 "Non-nil means `org-cycle' will open archived trees.
4628 An archived tree is a tree marked with the tag ARCHIVE.
4629 When nil, archived trees will stay folded. You can still open them with
4630 normal outline commands like `show-all', but not with the cycling commands."
4631 :group 'org-archive
4632 :group 'org-cycle
4633 :type 'boolean)
4635 (defcustom org-sparse-tree-open-archived-trees nil
4636 "Non-nil means sparse tree construction shows matches in archived trees.
4637 When nil, matches in these trees are highlighted, but the trees are kept in
4638 collapsed state."
4639 :group 'org-archive
4640 :group 'org-sparse-trees
4641 :type 'boolean)
4643 (defcustom org-sparse-tree-default-date-type nil
4644 "The default date type when building a sparse tree.
4645 When this is nil, a date is a scheduled or a deadline timestamp.
4646 Otherwise, these types are allowed:
4648 all: all timestamps
4649 active: only active timestamps (<...>)
4650 inactive: only inactive timestamps ([...])
4651 scheduled: only scheduled timestamps
4652 deadline: only deadline timestamps"
4653 :type '(choice (const :tag "Scheduled or deadline" nil)
4654 (const :tag "All timestamps" all)
4655 (const :tag "Only active timestamps" active)
4656 (const :tag "Only inactive timestamps" inactive)
4657 (const :tag "Only scheduled timestamps" scheduled)
4658 (const :tag "Only deadline timestamps" deadline)
4659 (const :tag "Only closed timestamps" closed))
4660 :version "26.1"
4661 :package-version '(Org . "8.3")
4662 :group 'org-sparse-trees)
4664 (defun org-cycle-hide-archived-subtrees (state)
4665 "Re-hide all archived subtrees after a visibility state change.
4666 STATE should be one of the symbols listed in the docstring of
4667 `org-cycle-hook'."
4668 (when (and (not org-cycle-open-archived-trees)
4669 (not (memq state '(overview folded))))
4670 (save-excursion
4671 (let* ((globalp (memq state '(contents all)))
4672 (beg (if globalp (point-min) (point)))
4673 (end (if globalp (point-max) (org-end-of-subtree t))))
4674 (org-hide-archived-subtrees beg end)
4675 (goto-char beg)
4676 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4677 (message "%s" (substitute-command-keys
4678 "Subtree is archived and stays closed. Use \
4679 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4681 (defun org-force-cycle-archived ()
4682 "Cycle subtree even if it is archived."
4683 (interactive)
4684 (setq this-command 'org-cycle)
4685 (let ((org-cycle-open-archived-trees t))
4686 (call-interactively 'org-cycle)))
4688 (defun org-hide-archived-subtrees (beg end)
4689 "Re-hide all archived subtrees after a visibility state change."
4690 (org-with-wide-buffer
4691 (let ((case-fold-search nil)
4692 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4693 (goto-char beg)
4694 ;; Include headline point is currently on.
4695 (beginning-of-line)
4696 (while (and (< (point) end) (re-search-forward re end t))
4697 (when (member org-archive-tag (org-get-tags))
4698 (org-flag-subtree t)
4699 (org-end-of-subtree t))))))
4701 (declare-function outline-end-of-heading "outline" ())
4702 (declare-function outline-flag-region "outline" (from to flag))
4703 (defun org-flag-subtree (flag)
4704 (save-excursion
4705 (org-back-to-heading t)
4706 (outline-end-of-heading)
4707 (outline-flag-region (point)
4708 (progn (org-end-of-subtree t) (point))
4709 flag)))
4711 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4713 ;; Declare Column View Code
4715 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4716 (declare-function org-columns-compute "org-colview" (property))
4718 ;; Declare ID code
4720 (declare-function org-id-store-link "org-id")
4721 (declare-function org-id-locations-load "org-id")
4722 (declare-function org-id-locations-save "org-id")
4723 (defvar org-id-track-globally)
4725 ;;; Variables for pre-computed regular expressions, all buffer local
4727 (defvar-local org-todo-regexp nil
4728 "Matches any of the TODO state keywords.
4729 Since TODO keywords are case-sensitive, `case-fold-search' is
4730 expected to be bound to nil when matching against this regexp.")
4732 (defvar-local org-not-done-regexp nil
4733 "Matches any of the TODO state keywords except the last one.
4734 Since TODO keywords are case-sensitive, `case-fold-search' is
4735 expected to be bound to nil when matching against this regexp.")
4737 (defvar-local org-not-done-heading-regexp nil
4738 "Matches a TODO headline that is not done.
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-todo-line-regexp nil
4743 "Matches a headline and puts TODO state into group 2 if present.
4744 Since TODO keywords are case-sensitive, `case-fold-search' is
4745 expected to be bound to nil when matching against this regexp.")
4747 (defvar-local org-complex-heading-regexp nil
4748 "Matches a headline and puts everything into groups:
4750 group 1: Stars
4751 group 2: The TODO keyword, maybe
4752 group 3: Priority cookie
4753 group 4: True headline
4754 group 5: Tags
4756 Since TODO keywords are case-sensitive, `case-fold-search' is
4757 expected to be bound to nil when matching against this regexp.")
4759 (defvar-local org-complex-heading-regexp-format nil
4760 "Printf format to make regexp to match an exact headline.
4761 This regexp will match the headline of any node which has the
4762 exact headline text that is put into the format, but may have any
4763 TODO state, priority and tags.")
4765 (defvar-local org-todo-line-tags-regexp nil
4766 "Matches a headline and puts TODO state into group 2 if present.
4767 Also put tags into group 4 if tags are present.")
4769 (defconst org-plain-time-of-day-regexp
4770 (concat
4771 "\\(\\<[012]?[0-9]"
4772 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4773 "\\(--?"
4774 "\\(\\<[012]?[0-9]"
4775 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4776 "\\)?")
4777 "Regular expression to match a plain time or time range.
4778 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4779 groups carry important information:
4780 0 the full match
4781 1 the first time, range or not
4782 8 the second time, if it is a range.")
4784 (defconst org-plain-time-extension-regexp
4785 (concat
4786 "\\(\\<[012]?[0-9]"
4787 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4788 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4789 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4790 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4791 groups carry important information:
4792 0 the full match
4793 7 hours of duration
4794 9 minutes of duration")
4796 (defconst org-stamp-time-of-day-regexp
4797 (concat
4798 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4799 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4800 "\\(--?"
4801 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4802 "Regular expression to match a timestamp time or time range.
4803 After a match, the following groups carry important information:
4804 0 the full match
4805 1 date plus weekday, for back referencing to make sure both times are on the same day
4806 2 the first time, range or not
4807 4 the second time, if it is a range.")
4809 (defconst org-startup-options
4810 '(("fold" org-startup-folded t)
4811 ("overview" org-startup-folded t)
4812 ("nofold" org-startup-folded nil)
4813 ("showall" org-startup-folded nil)
4814 ("showeverything" org-startup-folded showeverything)
4815 ("content" org-startup-folded content)
4816 ("indent" org-startup-indented t)
4817 ("noindent" org-startup-indented nil)
4818 ("hidestars" org-hide-leading-stars t)
4819 ("showstars" org-hide-leading-stars nil)
4820 ("odd" org-odd-levels-only t)
4821 ("oddeven" org-odd-levels-only nil)
4822 ("align" org-startup-align-all-tables t)
4823 ("noalign" org-startup-align-all-tables nil)
4824 ("shrink" org-startup-shrink-all-tables t)
4825 ("inlineimages" org-startup-with-inline-images t)
4826 ("noinlineimages" org-startup-with-inline-images nil)
4827 ("latexpreview" org-startup-with-latex-preview t)
4828 ("nolatexpreview" org-startup-with-latex-preview nil)
4829 ("customtime" org-display-custom-times t)
4830 ("logdone" org-log-done time)
4831 ("lognotedone" org-log-done note)
4832 ("nologdone" org-log-done nil)
4833 ("lognoteclock-out" org-log-note-clock-out t)
4834 ("nolognoteclock-out" org-log-note-clock-out nil)
4835 ("logrepeat" org-log-repeat state)
4836 ("lognoterepeat" org-log-repeat note)
4837 ("logdrawer" org-log-into-drawer t)
4838 ("nologdrawer" org-log-into-drawer nil)
4839 ("logstatesreversed" org-log-states-order-reversed t)
4840 ("nologstatesreversed" org-log-states-order-reversed nil)
4841 ("nologrepeat" org-log-repeat nil)
4842 ("logreschedule" org-log-reschedule time)
4843 ("lognotereschedule" org-log-reschedule note)
4844 ("nologreschedule" org-log-reschedule nil)
4845 ("logredeadline" org-log-redeadline time)
4846 ("lognoteredeadline" org-log-redeadline note)
4847 ("nologredeadline" org-log-redeadline nil)
4848 ("logrefile" org-log-refile time)
4849 ("lognoterefile" org-log-refile note)
4850 ("nologrefile" org-log-refile nil)
4851 ("fninline" org-footnote-define-inline t)
4852 ("nofninline" org-footnote-define-inline nil)
4853 ("fnlocal" org-footnote-section nil)
4854 ("fnauto" org-footnote-auto-label t)
4855 ("fnprompt" org-footnote-auto-label nil)
4856 ("fnconfirm" org-footnote-auto-label confirm)
4857 ("fnplain" org-footnote-auto-label plain)
4858 ("fnadjust" org-footnote-auto-adjust t)
4859 ("nofnadjust" org-footnote-auto-adjust nil)
4860 ("constcgs" constants-unit-system cgs)
4861 ("constSI" constants-unit-system SI)
4862 ("noptag" org-tag-persistent-alist nil)
4863 ("hideblocks" org-hide-block-startup t)
4864 ("nohideblocks" org-hide-block-startup nil)
4865 ("beamer" org-startup-with-beamer-mode t)
4866 ("entitiespretty" org-pretty-entities t)
4867 ("entitiesplain" org-pretty-entities nil))
4868 "Variable associated with STARTUP options for org-mode.
4869 Each element is a list of three items: the startup options (as written
4870 in the #+STARTUP line), the corresponding variable, and the value to set
4871 this variable to if the option is found. An optional forth element PUSH
4872 means to push this value onto the list in the variable.")
4874 (defcustom org-group-tags t
4875 "When non-nil (the default), use group tags.
4876 This can be turned on/off through `org-toggle-tags-groups'."
4877 :group 'org-tags
4878 :group 'org-startup
4879 :type 'boolean)
4881 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4883 (defun org-toggle-tags-groups ()
4884 "Toggle support for group tags.
4885 Support for group tags is controlled by the option
4886 `org-group-tags', which is non-nil by default."
4887 (interactive)
4888 (setq org-group-tags (not org-group-tags))
4889 (cond ((and (derived-mode-p 'org-agenda-mode)
4890 org-group-tags)
4891 (org-agenda-redo))
4892 ((derived-mode-p 'org-mode)
4893 (let ((org-inhibit-startup t)) (org-mode))))
4894 (message "Groups tags support has been turned %s"
4895 (if org-group-tags "on" "off")))
4897 (defun org-set-regexps-and-options (&optional tags-only)
4898 "Precompute regular expressions used in the current buffer.
4899 When optional argument TAGS-ONLY is non-nil, only compute tags
4900 related expressions."
4901 (when (derived-mode-p 'org-mode)
4902 (let ((alist (org--setup-collect-keywords
4903 (org-make-options-regexp
4904 (append '("FILETAGS" "TAGS" "SETUPFILE")
4905 (and (not tags-only)
4906 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4907 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4908 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4909 ;; Startup options. Get this early since it does change
4910 ;; behavior for other options (e.g., tags).
4911 (let ((startup (cdr (assq 'startup alist))))
4912 (dolist (option startup)
4913 (let ((entry (assoc-string option org-startup-options t)))
4914 (when entry
4915 (let ((var (nth 1 entry))
4916 (val (nth 2 entry)))
4917 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4918 (unless (listp (symbol-value var))
4919 (set (make-local-variable var) nil))
4920 (add-to-list var val)))))))
4921 (setq-local org-file-tags
4922 (mapcar #'org-add-prop-inherited
4923 (cdr (assq 'filetags alist))))
4924 (setq org-current-tag-alist
4925 (append org-tag-persistent-alist
4926 (let ((tags (cdr (assq 'tags alist))))
4927 (if tags (org-tag-string-to-alist tags)
4928 org-tag-alist))))
4929 (setq org-tag-groups-alist
4930 (org-tag-alist-to-groups org-current-tag-alist))
4931 (unless tags-only
4932 ;; File properties.
4933 (setq-local org-file-properties (cdr (assq 'property alist)))
4934 ;; Archive location.
4935 (let ((archive (cdr (assq 'archive alist))))
4936 (when archive (setq-local org-archive-location archive)))
4937 ;; Category.
4938 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4939 (when cat
4940 (setq-local org-category (intern cat))
4941 (setq-local org-file-properties
4942 (org--update-property-plist
4943 "CATEGORY" cat org-file-properties))))
4944 ;; Columns.
4945 (let ((column (cdr (assq 'columns alist))))
4946 (when column (setq-local org-columns-default-format column)))
4947 ;; Constants.
4948 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4949 ;; Link abbreviations.
4950 (let ((links (cdr (assq 'link alist))))
4951 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4952 ;; Priorities.
4953 (let ((priorities (cdr (assq 'priorities alist))))
4954 (when priorities
4955 (setq-local org-highest-priority (nth 0 priorities))
4956 (setq-local org-lowest-priority (nth 1 priorities))
4957 (setq-local org-default-priority (nth 2 priorities))))
4958 ;; Scripts.
4959 (let ((scripts (assq 'scripts alist)))
4960 (when scripts
4961 (setq-local org-use-sub-superscripts (cdr scripts))))
4962 ;; TODO keywords.
4963 (setq-local org-todo-kwd-alist nil)
4964 (setq-local org-todo-key-alist nil)
4965 (setq-local org-todo-key-trigger nil)
4966 (setq-local org-todo-keywords-1 nil)
4967 (setq-local org-done-keywords nil)
4968 (setq-local org-todo-heads nil)
4969 (setq-local org-todo-sets nil)
4970 (setq-local org-todo-log-states nil)
4971 (let ((todo-sequences
4972 (or (nreverse (cdr (assq 'todo alist)))
4973 (let ((d (default-value 'org-todo-keywords)))
4974 (if (not (stringp (car d))) d
4975 ;; XXX: Backward compatibility code.
4976 (list (cons org-todo-interpretation d)))))))
4977 (dolist (sequence todo-sequences)
4978 (let* ((sequence (or (run-hook-with-args-until-success
4979 'org-todo-setup-filter-hook sequence)
4980 sequence))
4981 (sequence-type (car sequence))
4982 (keywords (cdr sequence))
4983 (sep (member "|" keywords))
4984 names alist)
4985 (dolist (k (remove "|" keywords))
4986 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4988 (error "Invalid TODO keyword %s" k))
4989 (let ((name (match-string 1 k))
4990 (key (match-string 2 k))
4991 (log (org-extract-log-state-settings k)))
4992 (push name names)
4993 (push (cons name (and key (string-to-char key))) alist)
4994 (when log (push log org-todo-log-states))))
4995 (let* ((names (nreverse names))
4996 (done (if sep (org-remove-keyword-keys (cdr sep))
4997 (last names)))
4998 (head (car names))
4999 (tail (list sequence-type head (car done) (org-last done))))
5000 (add-to-list 'org-todo-heads head 'append)
5001 (push names org-todo-sets)
5002 (setq org-done-keywords (append org-done-keywords done nil))
5003 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5004 (setq org-todo-key-alist
5005 (append org-todo-key-alist
5006 (and alist
5007 (append '((:startgroup))
5008 (nreverse alist)
5009 '((:endgroup))))))
5010 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5011 (setq org-todo-sets (nreverse org-todo-sets)
5012 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5013 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5014 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5015 ;; Compute the regular expressions and other local variables.
5016 ;; Using `org-outline-regexp-bol' would complicate them much,
5017 ;; because of the fixed white space at the end of that string.
5018 (unless org-done-keywords
5019 (setq org-done-keywords
5020 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5021 (setq org-not-done-keywords
5022 (org-delete-all org-done-keywords
5023 (copy-sequence org-todo-keywords-1))
5024 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5025 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5026 org-not-done-heading-regexp
5027 (format org-heading-keyword-regexp-format org-not-done-regexp)
5028 org-todo-line-regexp
5029 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5030 org-complex-heading-regexp
5031 (concat "^\\(\\*+\\)"
5032 "\\(?: +" org-todo-regexp "\\)?"
5033 "\\(?: +\\(\\[#.\\]\\)\\)?"
5034 "\\(?: +\\(.*?\\)\\)??"
5035 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5036 "[ \t]*$")
5037 org-complex-heading-regexp-format
5038 (concat "^\\(\\*+\\)"
5039 "\\(?: +" org-todo-regexp "\\)?"
5040 "\\(?: +\\(\\[#.\\]\\)\\)?"
5041 "\\(?: +"
5042 ;; Stats cookies can be stuck to body.
5043 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5044 "\\(%s\\)"
5045 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5046 "\\)"
5047 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5048 "[ \t]*$")
5049 org-todo-line-tags-regexp
5050 (concat "^\\(\\*+\\)"
5051 "\\(?: +" org-todo-regexp "\\)?"
5052 "\\(?: +\\(.*?\\)\\)??"
5053 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5054 "[ \t]*$"))
5055 (org-compute-latex-and-related-regexp)))))
5057 (defun org--setup-collect-keywords (regexp &optional files alist)
5058 "Return setup keywords values as an alist.
5060 REGEXP matches a subset of setup keywords. FILES is a list of
5061 file names already visited. It is used to avoid circular setup
5062 files. ALIST, when non-nil, is the alist computed so far.
5064 Return value contains the following keys: `archive', `category',
5065 `columns', `constants', `filetags', `link', `priorities',
5066 `property', `scripts', `startup', `tags' and `todo'."
5067 (org-with-wide-buffer
5068 (goto-char (point-min))
5069 (let ((case-fold-search t))
5070 (while (re-search-forward regexp nil t)
5071 (let ((element (org-element-at-point)))
5072 (when (eq (org-element-type element) 'keyword)
5073 (let ((key (org-element-property :key element))
5074 (value (org-element-property :value element)))
5075 (cond
5076 ((equal key "ARCHIVE")
5077 (when (org-string-nw-p value)
5078 (push (cons 'archive value) alist)))
5079 ((equal key "CATEGORY") (push (cons 'category value) alist))
5080 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5081 ((equal key "CONSTANTS")
5082 (let* ((constants (assq 'constants alist))
5083 (store (cdr constants)))
5084 (dolist (pair (split-string value))
5085 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5086 pair)
5087 (let* ((name (match-string 1 pair))
5088 (value (match-string 2 pair))
5089 (old (assoc name store)))
5090 (if old (setcdr old value)
5091 (push (cons name value) store)))))
5092 (if constants (setcdr constants store)
5093 (push (cons 'constants store) alist))))
5094 ((equal key "FILETAGS")
5095 (when (org-string-nw-p value)
5096 (let ((old (assq 'filetags alist))
5097 (new (apply #'nconc
5098 (mapcar (lambda (x) (org-split-string x ":"))
5099 (split-string value)))))
5100 (if old (setcdr old (append new (cdr old)))
5101 (push (cons 'filetags new) alist)))))
5102 ((equal key "LINK")
5103 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5104 (let ((links (assq 'link alist))
5105 (pair (cons (match-string-no-properties 1 value)
5106 (match-string-no-properties 2 value))))
5107 (if links (push pair (cdr links))
5108 (push (list 'link pair) alist)))))
5109 ((equal key "OPTIONS")
5110 (when (and (org-string-nw-p value)
5111 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5112 (push (cons 'scripts (read (match-string 1 value))) alist)))
5113 ((equal key "PRIORITIES")
5114 (push (cons 'priorities
5115 (let ((prio (split-string value)))
5116 (if (< (length prio) 3) '(?A ?C ?B)
5117 (mapcar #'string-to-char prio))))
5118 alist))
5119 ((equal key "PROPERTY")
5120 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5121 (let* ((property (assq 'property alist))
5122 (value (org--update-property-plist
5123 (match-string-no-properties 1 value)
5124 (match-string-no-properties 2 value)
5125 (cdr property))))
5126 (if property (setcdr property value)
5127 (push (cons 'property value) alist)))))
5128 ((equal key "STARTUP")
5129 (let ((startup (assq 'startup alist)))
5130 (if startup
5131 (setcdr startup
5132 (append (cdr startup) (split-string value)))
5133 (push (cons 'startup (split-string value)) alist))))
5134 ((equal key "TAGS")
5135 (let ((tag-cell (assq 'tags alist)))
5136 (if tag-cell
5137 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5138 (push (cons 'tags value) alist))))
5139 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5140 (let ((todo (assq 'todo alist))
5141 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5142 (split-string value))))
5143 (if todo (push value (cdr todo))
5144 (push (list 'todo value) alist))))
5145 ((equal key "SETUPFILE")
5146 (unless buffer-read-only ; Do not check in Gnus messages.
5147 (let ((f (and (org-string-nw-p value)
5148 (expand-file-name
5149 (org-unbracket-string "\"" "\"" value)))))
5150 (when (and f (file-readable-p f) (not (member f files)))
5151 (with-temp-buffer
5152 (setq default-directory (file-name-directory f))
5153 (insert-file-contents f)
5154 (setq alist
5155 ;; Fake Org mode to benefit from cache
5156 ;; without recurring needlessly.
5157 (let ((major-mode 'org-mode))
5158 (org--setup-collect-keywords
5159 regexp (cons f files) alist)))))))))))))))
5160 alist)
5162 (defun org-tag-string-to-alist (s)
5163 "Return tag alist associated to string S.
5164 S is a value for TAGS keyword or produced with
5165 `org-tag-alist-to-string'. Return value is an alist suitable for
5166 `org-tag-alist' or `org-tag-persistent-alist'."
5167 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5168 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5169 "\\|{.+?}\\)" ; regular expression
5170 "\\(?:(\\(.\\))\\)?\\'"))
5171 alist group-flag)
5172 (dolist (tokens lines (cdr (nreverse alist)))
5173 (push '(:newline) alist)
5174 (while tokens
5175 (let ((token (pop tokens)))
5176 (pcase token
5177 ("{"
5178 (push '(:startgroup) alist)
5179 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5180 ("}"
5181 (push '(:endgroup) alist)
5182 (setq group-flag nil))
5183 ("["
5184 (push '(:startgrouptag) alist)
5185 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5186 ("]"
5187 (push '(:endgrouptag) alist)
5188 (setq group-flag nil))
5189 (":"
5190 (push '(:grouptags) alist))
5191 ((guard (string-match tag-re token))
5192 (let ((tag (match-string 1 token))
5193 (key (and (match-beginning 2)
5194 (string-to-char (match-string 2 token)))))
5195 ;; Push all tags in groups, no matter if they already
5196 ;; appear somewhere else in the list.
5197 (when (or group-flag (not (assoc tag alist)))
5198 (push (cons tag key) alist))))))))))
5200 (defun org-tag-alist-to-string (alist &optional skip-key)
5201 "Return tag string associated to ALIST.
5203 ALIST is an alist, as defined in `org-tag-alist' or
5204 `org-tag-persistent-alist', or produced with
5205 `org-tag-string-to-alist'.
5207 Return value is a string suitable as a value for \"TAGS\"
5208 keyword.
5210 When optional argument SKIP-KEY is non-nil, skip selection keys
5211 next to tags."
5212 (mapconcat (lambda (token)
5213 (pcase token
5214 (`(:startgroup) "{")
5215 (`(:endgroup) "}")
5216 (`(:startgrouptag) "[")
5217 (`(:endgrouptag) "]")
5218 (`(:grouptags) ":")
5219 (`(:newline) "\\n")
5220 ((and
5221 (guard (not skip-key))
5222 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5223 (format "%s(%c)" tag key))
5224 (`(,(and tag (pred stringp)) . ,_) tag)
5225 (_ (user-error "Invalid tag token: %S" token))))
5226 alist
5227 " "))
5229 (defun org-tag-alist-to-groups (alist)
5230 "Return group alist from tag ALIST.
5231 ALIST is an alist, as defined in `org-tag-alist' or
5232 `org-tag-persistent-alist', or produced with
5233 `org-tag-string-to-alist'. Return value is an alist following
5234 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5235 a string, summarizing TAGS, as a list of strings."
5236 (let (groups group-status current-group)
5237 (dolist (token alist (nreverse groups))
5238 (pcase token
5239 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5240 (`(,(or :endgroup :endgrouptag))
5241 (when (eq group-status 'append)
5242 (push (nreverse current-group) groups))
5243 (setq group-status nil))
5244 (`(:grouptags) (setq group-status 'append))
5245 ((and `(,tag . ,_) (guard group-status))
5246 (if (eq group-status 'append) (push tag current-group)
5247 (setq current-group (list tag))))
5248 (_ nil)))))
5250 (defvar org--file-cache (make-hash-table :test #'equal)
5251 "Hash table to store contents of files referenced via a URL.
5252 This is the cache of file URLs read using `org-file-contents'.")
5254 (defun org-reset-file-cache ()
5255 "Reset the cache of files downloaded by `org-file-contents'."
5256 (clrhash org--file-cache))
5258 (defun org-file-url-p (file)
5259 "Non-nil if FILE is a URL."
5260 (require 'ffap)
5261 (string-match-p ffap-url-regexp file))
5263 (defun org-file-contents (file &optional noerror nocache)
5264 "Return the contents of FILE, as a string.
5266 FILE can be a file name or URL.
5268 If FILE is a URL, download the contents. If the URL contents are
5269 already cached in the `org--file-cache' hash table, the download step
5270 is skipped.
5272 If NOERROR is non-nil, ignore the error when unable to read the FILE
5273 from file or URL.
5275 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5276 is available. This option applies only if FILE is a URL."
5277 (let* ((is-url (org-file-url-p file))
5278 (cache (and is-url
5279 (not nocache)
5280 (gethash file org--file-cache))))
5281 (cond
5282 (cache)
5283 (is-url
5284 (with-current-buffer (url-retrieve-synchronously file)
5285 (goto-char (point-min))
5286 ;; Move point to after the url-retrieve header.
5287 (search-forward "\n\n" nil :move)
5288 ;; Search for the success code only in the url-retrieve header.
5289 (if (save-excursion
5290 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5291 ;; Update the cache `org--file-cache' and return contents.
5292 (puthash file
5293 (buffer-substring-no-properties (point) (point-max))
5294 org--file-cache)
5295 (funcall (if noerror #'message #'user-error)
5296 "Unable to fetch file from %S"
5297 file))))
5299 (with-temp-buffer
5300 (condition-case nil
5301 (progn
5302 (insert-file-contents file)
5303 (buffer-string))
5304 (file-error
5305 (funcall (if noerror #'message #'user-error)
5306 "Unable to read file %S"
5307 file))))))))
5309 (defun org-extract-log-state-settings (x)
5310 "Extract the log state setting from a TODO keyword string.
5311 This will extract info from a string like \"WAIT(w@/!)\"."
5312 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5313 (let ((kw (match-string 1 x))
5314 (log1 (and (match-end 3) (match-string 3 x)))
5315 (log2 (and (match-end 4) (match-string 4 x))))
5316 (and (or log1 log2)
5317 (list kw
5318 (and log1 (if (equal log1 "!") 'time 'note))
5319 (and log2 (if (equal log2 "!") 'time 'note)))))))
5321 (defun org-remove-keyword-keys (list)
5322 "Remove a pair of parenthesis at the end of each string in LIST."
5323 (mapcar (lambda (x)
5324 (if (string-match "(.*)$" x)
5325 (substring x 0 (match-beginning 0))
5327 list))
5329 (defun org-assign-fast-keys (alist)
5330 "Assign fast keys to a keyword-key alist.
5331 Respect keys that are already there."
5332 (let (new e (alt ?0))
5333 (while (setq e (pop alist))
5334 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5335 (cdr e)) ;; Key already assigned.
5336 (push e new)
5337 (let ((clist (string-to-list (downcase (car e))))
5338 (used (append new alist)))
5339 (when (= (car clist) ?@)
5340 (pop clist))
5341 (while (and clist (rassoc (car clist) used))
5342 (pop clist))
5343 (unless clist
5344 (while (rassoc alt used)
5345 (cl-incf alt)))
5346 (push (cons (car e) (or (car clist) alt)) new))))
5347 (nreverse new)))
5349 ;;; Some variables used in various places
5351 (defvar org-window-configuration nil
5352 "Used in various places to store a window configuration.")
5353 (defvar org-selected-window nil
5354 "Used in various places to store a window configuration.")
5355 (defvar org-finish-function nil
5356 "Function to be called when `C-c C-c' is used.
5357 This is for getting out of special buffers like capture.")
5358 (defvar org-last-state)
5360 ;; Defined somewhere in this file, but used before definition.
5361 (defvar org-entities) ;; defined in org-entities.el
5362 (defvar org-struct-menu)
5363 (defvar org-org-menu)
5364 (defvar org-tbl-menu)
5366 ;;;; Define the Org mode
5368 ;; We use a before-change function to check if a table might need
5369 ;; an update.
5370 (defvar org-table-may-need-update t
5371 "Indicates that a table might need an update.
5372 This variable is set by `org-before-change-function'.
5373 `org-table-align' sets it back to nil.")
5374 (defun org-before-change-function (_beg _end)
5375 "Every change indicates that a table might need an update."
5376 (setq org-table-may-need-update t))
5377 (defvar org-mode-map)
5378 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5379 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5380 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5381 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5382 (defvar org-table-buffer-is-an nil)
5384 (defvar bidi-paragraph-direction)
5385 (defvar buffer-face-mode-face)
5387 (require 'outline)
5389 ;; Other stuff we need.
5390 (require 'time-date)
5391 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5392 (require 'easymenu)
5393 (autoload 'easy-menu-add "easymenu")
5394 (require 'overlay)
5396 ;; (require 'org-macs) moved higher up in the file before it is first used
5397 (require 'org-entities)
5398 ;; (require 'org-compat) moved higher up in the file before it is first used
5399 (require 'org-faces)
5400 (require 'org-list)
5401 (require 'org-pcomplete)
5402 (require 'org-src)
5403 (require 'org-footnote)
5404 (require 'org-macro)
5406 ;; babel
5407 (require 'ob)
5409 ;;;###autoload
5410 (define-derived-mode org-mode outline-mode "Org"
5411 "Outline-based notes management and organizer, alias
5412 \"Carsten's outline-mode for keeping track of everything.\"
5414 Org mode develops organizational tasks around a NOTES file which
5415 contains information about projects as plain text. Org mode is
5416 implemented on top of Outline mode, which is ideal to keep the content
5417 of large files well structured. It supports ToDo items, deadlines and
5418 time stamps, which magically appear in the diary listing of the Emacs
5419 calendar. Tables are easily created with a built-in table editor.
5420 Plain text URL-like links connect to websites, emails (VM), Usenet
5421 messages (Gnus), BBDB entries, and any files related to the project.
5422 For printing and sharing of notes, an Org file (or a part of it)
5423 can be exported as a structured ASCII or HTML file.
5425 The following commands are available:
5427 \\{org-mode-map}"
5429 ;; Get rid of Outline menus, they are not needed
5430 ;; Need to do this here because define-derived-mode sets up
5431 ;; the keymap so late. Still, it is a waste to call this each time
5432 ;; we switch another buffer into Org mode.
5433 (define-key org-mode-map [menu-bar headings] 'undefined)
5434 (define-key org-mode-map [menu-bar hide] 'undefined)
5435 (define-key org-mode-map [menu-bar show] 'undefined)
5437 (org-load-modules-maybe)
5438 (org-install-agenda-files-menu)
5439 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5440 (add-to-invisibility-spec '(org-hide-block . t))
5441 (setq-local outline-regexp org-outline-regexp)
5442 (setq-local outline-level 'org-outline-level)
5443 (setq bidi-paragraph-direction 'left-to-right)
5444 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5445 (unless org-display-table
5446 (setq org-display-table (make-display-table)))
5447 (set-display-table-slot
5448 org-display-table 4
5449 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5450 org-ellipsis)))
5451 (setq buffer-display-table org-display-table))
5452 (org-set-regexps-and-options)
5453 (org-set-font-lock-defaults)
5454 (when (and org-tag-faces (not org-tags-special-faces-re))
5455 ;; tag faces set outside customize.... force initialization.
5456 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5457 ;; Calc embedded
5458 (setq-local calc-embedded-open-mode "# ")
5459 ;; Modify a few syntax entries
5460 (modify-syntax-entry ?@ "w")
5461 (modify-syntax-entry ?\" "\"")
5462 (modify-syntax-entry ?\\ "_")
5463 (modify-syntax-entry ?~ "_")
5464 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5465 ;; Activate before-change-function
5466 (setq-local org-table-may-need-update t)
5467 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5468 ;; Check for running clock before killing a buffer
5469 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5470 ;; Initialize macros templates.
5471 (org-macro-initialize-templates)
5472 ;; Initialize radio targets.
5473 (org-update-radio-target-regexp)
5474 ;; Indentation.
5475 (setq-local indent-line-function 'org-indent-line)
5476 (setq-local indent-region-function 'org-indent-region)
5477 ;; Filling and auto-filling.
5478 (org-setup-filling)
5479 ;; Comments.
5480 (org-setup-comments-handling)
5481 ;; Initialize cache.
5482 (org-element-cache-reset)
5483 ;; Beginning/end of defun
5484 (setq-local beginning-of-defun-function 'org-backward-element)
5485 (setq-local end-of-defun-function
5486 (lambda ()
5487 (if (not (org-at-heading-p))
5488 (org-forward-element)
5489 (org-forward-element)
5490 (forward-char -1))))
5491 ;; Next error for sparse trees
5492 (setq-local next-error-function 'org-occur-next-match)
5493 ;; Make sure dependence stuff works reliably, even for users who set it
5494 ;; too late :-(
5495 (if org-enforce-todo-dependencies
5496 (add-hook 'org-blocker-hook
5497 'org-block-todo-from-children-or-siblings-or-parent)
5498 (remove-hook 'org-blocker-hook
5499 'org-block-todo-from-children-or-siblings-or-parent))
5500 (if org-enforce-todo-checkbox-dependencies
5501 (add-hook 'org-blocker-hook
5502 'org-block-todo-from-checkboxes)
5503 (remove-hook 'org-blocker-hook
5504 'org-block-todo-from-checkboxes))
5506 ;; Align options lines
5507 (setq-local
5508 align-mode-rules-list
5509 '((org-in-buffer-settings
5510 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5511 (modes . '(org-mode)))))
5513 ;; Imenu
5514 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5516 ;; Make isearch reveal context
5517 (setq-local outline-isearch-open-invisible-function
5518 (lambda (&rest _) (org-show-context 'isearch)))
5520 ;; Setup the pcomplete hooks
5521 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5522 (setq-local pcomplete-command-name-function 'org-command-at-point)
5523 (setq-local pcomplete-default-completion-function 'ignore)
5524 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5525 (setq-local pcomplete-termination-string "")
5526 (setq-local buffer-face-mode-face 'org-default)
5528 ;; If empty file that did not turn on Org mode automatically, make
5529 ;; it to.
5530 (when (and org-insert-mode-line-in-empty-file
5531 (called-interactively-p 'any)
5532 (= (point-min) (point-max)))
5533 (insert "# -*- mode: org -*-\n\n"))
5534 (unless org-inhibit-startup
5535 (org-unmodified
5536 (when org-startup-with-beamer-mode (org-beamer-mode))
5537 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5538 (org-table-map-tables
5539 (cond ((and org-startup-align-all-tables
5540 org-startup-shrink-all-tables)
5541 (lambda () (org-table-align) (org-table-shrink)))
5542 (org-startup-align-all-tables #'org-table-align)
5543 (t #'org-table-shrink))
5545 (when org-startup-with-inline-images (org-display-inline-images))
5546 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5547 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5548 (when org-startup-truncated (setq truncate-lines t))
5549 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5550 (org-refresh-effort-properties)))
5551 ;; Try to set `org-hide' face correctly.
5552 (let ((foreground (org-find-invisible-foreground)))
5553 (when foreground
5554 (set-face-foreground 'org-hide foreground))))
5556 ;; Update `customize-package-emacs-version-alist'
5557 (add-to-list 'customize-package-emacs-version-alist
5558 '(Org ("8.0" . "24.4")
5559 ("8.1" . "24.4")
5560 ("8.2" . "24.4")
5561 ("8.2.7" . "24.4")
5562 ("8.3" . "26.1")
5563 ("9.0" . "26.1")
5564 ("9.1" . "26.1")
5565 ("9.2" . "27.1")))
5567 (defvar org-mode-transpose-word-syntax-table
5568 (let ((st (make-syntax-table text-mode-syntax-table)))
5569 (dolist (c org-emphasis-alist st)
5570 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5572 (when (fboundp 'abbrev-table-put)
5573 (abbrev-table-put org-mode-abbrev-table
5574 :parents (list text-mode-abbrev-table)))
5576 (defun org-find-invisible-foreground ()
5577 (let ((candidates (remove
5578 "unspecified-bg"
5579 (nconc
5580 (list (face-background 'default)
5581 (face-background 'org-default))
5582 (mapcar
5583 (lambda (alist)
5584 (when (boundp alist)
5585 (cdr (assq 'background-color (symbol-value alist)))))
5586 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5587 (list (face-foreground 'org-hide))))))
5588 (car (remove nil candidates))))
5590 (defun org-current-time (&optional rounding-minutes past)
5591 "Current time, possibly rounded to ROUNDING-MINUTES.
5592 When ROUNDING-MINUTES is not an integer, fall back on the car of
5593 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5594 the rounding returns a past time."
5595 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5596 (car org-time-stamp-rounding-minutes)))
5597 (time (decode-time)) res)
5598 (if (< r 1)
5599 (current-time)
5600 (setq res
5601 (apply 'encode-time
5602 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5603 (nthcdr 2 time))))
5604 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5605 (seconds-to-time (- (float-time res) (* r 60)))
5606 res))))
5608 (defun org-today ()
5609 "Return today date, considering `org-extend-today-until'."
5610 (time-to-days
5611 (time-subtract (current-time)
5612 (list 0 (* 3600 org-extend-today-until) 0))))
5614 ;;;; Font-Lock stuff, including the activators
5616 (defvar org-mouse-map (make-sparse-keymap))
5617 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5618 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5619 (when org-mouse-1-follows-link
5620 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5621 (when org-tab-follows-link
5622 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5623 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5625 (require 'font-lock)
5627 (defconst org-non-link-chars "]\t\n\r<>")
5628 (defvar org-link-types-re nil
5629 "Matches a link that has a url-like prefix like \"http:\"")
5630 (defvar org-link-re-with-space nil
5631 "Matches a link with spaces, optional angular brackets around it.")
5632 (defvar org-link-re-with-space2 nil
5633 "Matches a link with spaces, optional angular brackets around it.")
5634 (defvar org-link-re-with-space3 nil
5635 "Matches a link with spaces, only for internal part in bracket links.")
5636 (defvar org-angle-link-re nil
5637 "Matches link with angular brackets, spaces are allowed.")
5638 (defvar org-plain-link-re nil
5639 "Matches plain link, without spaces.")
5640 (defvar org-bracket-link-regexp nil
5641 "Matches a link in double brackets.")
5642 (defvar org-bracket-link-analytic-regexp nil
5643 "Regular expression used to analyze links.
5644 Here is what the match groups contain after a match:
5645 1: http:
5646 2: http
5647 3: path
5648 4: [desc]
5649 5: desc")
5650 (defvar org-bracket-link-analytic-regexp++ nil
5651 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5652 (defvar org-any-link-re nil
5653 "Regular expression matching any link.")
5655 (defconst org-match-sexp-depth 3
5656 "Number of stacked braces for sub/superscript matching.")
5658 (defun org-create-multibrace-regexp (left right n)
5659 "Create a regular expression which will match a balanced sexp.
5660 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5661 as single character strings.
5662 The regexp returned will match the entire expression including the
5663 delimiters. It will also define a single group which contains the
5664 match except for the outermost delimiters. The maximum depth of
5665 stacked delimiters is N. Escaping delimiters is not possible."
5666 (let* ((nothing (concat "[^" left right "]*?"))
5667 (or "\\|")
5668 (re nothing)
5669 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5670 (while (> n 1)
5671 (setq n (1- n)
5672 re (concat re or next)
5673 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5674 (concat left "\\(" re "\\)" right)))
5676 (defconst org-match-substring-regexp
5677 (concat
5678 "\\(\\S-\\)\\([_^]\\)\\("
5679 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5680 "\\|"
5681 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5682 "\\|"
5683 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5684 "The regular expression matching a sub- or superscript.")
5686 (defconst org-match-substring-with-braces-regexp
5687 (concat
5688 "\\(\\S-\\)\\([_^]\\)"
5689 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5690 "The regular expression matching a sub- or superscript, forcing braces.")
5692 (defun org-make-link-regexps ()
5693 "Update the link regular expressions.
5694 This should be called after the variable `org-link-parameters' has changed."
5695 (let ((types-re (regexp-opt (org-link-types) t)))
5696 (setq org-link-types-re
5697 (concat "\\`" types-re ":")
5698 org-link-re-with-space
5699 (concat "<?" types-re ":"
5700 "\\([^" org-non-link-chars " ]"
5701 "[^" org-non-link-chars "]*"
5702 "[^" org-non-link-chars " ]\\)>?")
5703 org-link-re-with-space2
5704 (concat "<?" types-re ":"
5705 "\\([^" org-non-link-chars " ]"
5706 "[^\t\n\r]*"
5707 "[^" org-non-link-chars " ]\\)>?")
5708 org-link-re-with-space3
5709 (concat "<?" types-re ":"
5710 "\\([^" org-non-link-chars " ]"
5711 "[^\t\n\r]*\\)")
5712 org-angle-link-re
5713 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5714 types-re)
5715 org-plain-link-re
5716 (concat
5717 "\\<" types-re ":"
5718 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5719 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5720 org-bracket-link-regexp
5721 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5722 org-bracket-link-analytic-regexp
5723 (concat
5724 "\\[\\["
5725 "\\(" types-re ":\\)?"
5726 "\\([^]]+\\)"
5727 "\\]"
5728 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5729 "\\]")
5730 org-bracket-link-analytic-regexp++
5731 (concat
5732 "\\[\\["
5733 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5734 "\\([^]]+\\)"
5735 "\\]"
5736 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5737 "\\]")
5738 org-any-link-re
5739 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5740 org-angle-link-re "\\)\\|\\("
5741 org-plain-link-re "\\)"))))
5743 (org-make-link-regexps)
5745 (defvar org-emph-face nil)
5747 (defun org-do-emphasis-faces (limit)
5748 "Run through the buffer and emphasize strings."
5749 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5750 (car org-emphasis-regexp-components))))
5751 (catch :exit
5752 (while (re-search-forward quick-re limit t)
5753 (let* ((marker (match-string 2))
5754 (verbatim? (member marker '("~" "="))))
5755 (when (save-excursion
5756 (goto-char (match-beginning 0))
5757 ;; Do not match headline stars. Do not consider
5758 ;; stars of a headline as closing marker for bold
5759 ;; markup either. Do not match table hlines.
5760 (and
5761 (not (looking-at-p org-outline-regexp-bol))
5762 (not (and (equal marker "+")
5763 (org-match-line
5764 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5765 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5766 (not (string-match-p
5767 (concat org-outline-regexp-bol "\\'")
5768 (match-string 0)))))
5769 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5770 (font-lock-prepend-text-property
5771 (match-beginning 2) (match-end 2) 'face face)
5772 (when verbatim?
5773 (org-remove-flyspell-overlays-in
5774 (match-beginning 0) (match-end 0)))
5775 (add-text-properties (match-beginning 2) (match-end 2)
5776 '(font-lock-multiline t org-emphasis t))
5777 (when org-hide-emphasis-markers
5778 (add-text-properties (match-end 4) (match-beginning 5)
5779 '(invisible org-link))
5780 (add-text-properties (match-beginning 3) (match-end 3)
5781 '(invisible org-link)))
5782 (throw :exit t))))))))
5784 (defun org-emphasize (&optional char)
5785 "Insert or change an emphasis, i.e. a font like bold or italic.
5786 If there is an active region, change that region to a new emphasis.
5787 If there is no region, just insert the marker characters and position
5788 the cursor between them.
5789 CHAR should be the marker character. If it is a space, it means to
5790 remove the emphasis of the selected region.
5791 If CHAR is not given (for example in an interactive call) it will be
5792 prompted for."
5793 (interactive)
5794 (let ((erc org-emphasis-regexp-components)
5795 (string "") beg end move s)
5796 (if (org-region-active-p)
5797 (setq beg (region-beginning)
5798 end (region-end)
5799 string (buffer-substring beg end))
5800 (setq move t))
5802 (unless char
5803 (message "Emphasis marker or tag: [%s]"
5804 (mapconcat #'car org-emphasis-alist ""))
5805 (setq char (read-char-exclusive)))
5806 (if (equal char ?\s)
5807 (setq s ""
5808 move nil)
5809 (unless (assoc (char-to-string char) org-emphasis-alist)
5810 (user-error "No such emphasis marker: \"%c\"" char))
5811 (setq s (char-to-string char)))
5812 (while (and (> (length string) 1)
5813 (equal (substring string 0 1) (substring string -1))
5814 (assoc (substring string 0 1) org-emphasis-alist))
5815 (setq string (substring string 1 -1)))
5816 (setq string (concat s string s))
5817 (when beg (delete-region beg end))
5818 (unless (or (bolp)
5819 (string-match (concat "[" (nth 0 erc) "\n]")
5820 (char-to-string (char-before (point)))))
5821 (insert " "))
5822 (unless (or (eobp)
5823 (string-match (concat "[" (nth 1 erc) "\n]")
5824 (char-to-string (char-after (point)))))
5825 (insert " ") (backward-char 1))
5826 (insert string)
5827 (and move (backward-char 1))))
5829 (defconst org-nonsticky-props
5830 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5832 (defsubst org-rear-nonsticky-at (pos)
5833 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5835 (defun org-activate-links (limit)
5836 "Add link properties to links.
5837 This includes angle, plain, and bracket links."
5838 (catch :exit
5839 (while (re-search-forward org-any-link-re limit t)
5840 (let* ((start (match-beginning 0))
5841 (end (match-end 0))
5842 (style (cond ((eq ?< (char-after start)) 'angle)
5843 ((eq ?\[ (char-after (1+ start))) 'bracket)
5844 (t 'plain))))
5845 (when (and (memq style org-highlight-links)
5846 ;; Do not confuse plain links with tags.
5847 (not (and (eq style 'plain)
5848 (let ((face (get-text-property
5849 (max (1- start) (point-min)) 'face)))
5850 (if (consp face) (memq 'org-tag face)
5851 (eq 'org-tag face))))))
5852 (let* ((link-object (save-excursion
5853 (goto-char start)
5854 (save-match-data (org-element-link-parser))))
5855 (link (org-element-property :raw-link link-object))
5856 (type (org-element-property :type link-object))
5857 (path (org-element-property :path link-object))
5858 (properties ;for link's visible part
5859 (list
5860 'face (pcase (org-link-get-parameter type :face)
5861 ((and (pred functionp) face) (funcall face path))
5862 ((and (pred facep) face) face)
5863 ((and (pred consp) face) face) ;anonymous
5864 (_ 'org-link))
5865 'mouse-face (or (org-link-get-parameter type :mouse-face)
5866 'highlight)
5867 'keymap (or (org-link-get-parameter type :keymap)
5868 org-mouse-map)
5869 'help-echo (pcase (org-link-get-parameter type :help-echo)
5870 ((and (pred stringp) echo) echo)
5871 ((and (pred functionp) echo) echo)
5872 (_ (concat "LINK: " link)))
5873 'htmlize-link (pcase (org-link-get-parameter type
5874 :htmlize-link)
5875 ((and (pred functionp) f) (funcall f))
5876 (_ `(:uri ,link)))
5877 'font-lock-multiline t)))
5878 (org-remove-flyspell-overlays-in start end)
5879 (org-rear-nonsticky-at end)
5880 (if (not (eq 'bracket style))
5881 (add-text-properties start end properties)
5882 ;; Handle invisible parts in bracket links.
5883 (remove-text-properties start end '(invisible nil))
5884 (let ((hidden
5885 (append `(invisible
5886 ,(or (org-link-get-parameter type :display)
5887 'org-link))
5888 properties))
5889 (visible-start (or (match-beginning 4) (match-beginning 2)))
5890 (visible-end (or (match-end 4) (match-end 2))))
5891 (add-text-properties start visible-start hidden)
5892 (add-text-properties visible-start visible-end properties)
5893 (add-text-properties visible-end end hidden)
5894 (org-rear-nonsticky-at visible-start)
5895 (org-rear-nonsticky-at visible-end)))
5896 (let ((f (org-link-get-parameter type :activate-func)))
5897 (when (functionp f)
5898 (funcall f start end path (eq style 'bracket))))
5899 (throw :exit t))))) ;signal success
5900 nil))
5902 (defun org-activate-code (limit)
5903 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (remove-text-properties (match-beginning 0) (match-end 0)
5906 '(display t invisible t intangible t))
5909 (defcustom org-src-fontify-natively t
5910 "When non-nil, fontify code in code blocks.
5911 See also the `org-block' face."
5912 :type 'boolean
5913 :version "26.1"
5914 :package-version '(Org . "8.3")
5915 :group 'org-appearance
5916 :group 'org-babel)
5918 (defcustom org-allow-promoting-top-level-subtree nil
5919 "When non-nil, allow promoting a top level subtree.
5920 The leading star of the top level headline will be replaced
5921 by a #."
5922 :type 'boolean
5923 :version "24.1"
5924 :group 'org-appearance)
5926 (defun org-fontify-meta-lines-and-blocks (limit)
5927 (condition-case nil
5928 (org-fontify-meta-lines-and-blocks-1 limit)
5929 (error (message "org-mode fontification error in %S at %d"
5930 (current-buffer)
5931 (line-number-at-pos)))))
5933 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5934 "Fontify #+ lines and blocks."
5935 (let ((case-fold-search t))
5936 (when (re-search-forward
5937 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5938 limit t)
5939 (let ((beg (match-beginning 0))
5940 (block-start (match-end 0))
5941 (block-end nil)
5942 (lang (match-string 7))
5943 (beg1 (line-beginning-position 2))
5944 (dc1 (downcase (match-string 2)))
5945 (dc3 (downcase (match-string 3)))
5946 end end1 quoting block-type)
5947 (cond
5948 ((and (match-end 4) (equal dc3 "+begin"))
5949 ;; Truly a block
5950 (setq block-type (downcase (match-string 5))
5951 quoting (member block-type org-protecting-blocks))
5952 (when (re-search-forward
5953 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5954 nil t) ;; on purpose, we look further than LIMIT
5955 (setq end (min (point-max) (match-end 0))
5956 end1 (min (point-max) (1- (match-beginning 0))))
5957 (setq block-end (match-beginning 0))
5958 (when quoting
5959 (org-remove-flyspell-overlays-in beg1 end1)
5960 (remove-text-properties beg end
5961 '(display t invisible t intangible t)))
5962 (add-text-properties
5963 beg end '(font-lock-fontified t font-lock-multiline t))
5964 (add-text-properties beg beg1 '(face org-meta-line))
5965 (org-remove-flyspell-overlays-in beg beg1)
5966 (add-text-properties ; For end_src
5967 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5968 (org-remove-flyspell-overlays-in end1 end)
5969 (cond
5970 ((and lang (not (string= lang "")) org-src-fontify-natively)
5971 (org-src-font-lock-fontify-block lang block-start block-end)
5972 (add-text-properties beg1 block-end '(src-block t)))
5973 (quoting
5974 (add-text-properties beg1 (min (point-max) (1+ end1))
5975 (list 'face
5976 (list :inherit
5977 (let ((face-name
5978 (intern (format "org-block-%s" lang))))
5979 (append (and (facep face-name) (list face-name))
5980 '(org-block))))))) ; end of source block
5981 ((not org-fontify-quote-and-verse-blocks))
5982 ((string= block-type "quote")
5983 (add-face-text-property
5984 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5985 ((string= block-type "verse")
5986 (add-face-text-property
5987 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5988 (add-text-properties beg beg1 '(face org-block-begin-line))
5989 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5990 '(face org-block-end-line))
5992 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5993 (org-remove-flyspell-overlays-in
5994 (match-beginning 0)
5995 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5996 (add-text-properties
5997 beg (match-end 3)
5998 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5999 '(font-lock-fontified t invisible t)
6000 '(font-lock-fontified t face org-document-info-keyword)))
6001 (add-text-properties
6002 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6003 (if (string-equal dc1 "+title:")
6004 '(font-lock-fontified t face org-document-title)
6005 '(font-lock-fontified t face org-document-info))))
6006 ((string-prefix-p "+caption" dc1)
6007 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6008 (remove-text-properties (match-beginning 0) (match-end 0)
6009 '(display t invisible t intangible t))
6010 ;; Handle short captions.
6011 (save-excursion
6012 (beginning-of-line)
6013 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6014 (add-text-properties (line-beginning-position) (match-end 1)
6015 '(font-lock-fontified t face org-meta-line))
6016 (add-text-properties (match-end 0) (line-end-position)
6017 '(font-lock-fontified t face org-block))
6019 ((member dc3 '(" " ""))
6020 (org-remove-flyspell-overlays-in beg (match-end 0))
6021 (add-text-properties
6022 beg (match-end 0)
6023 '(font-lock-fontified t face font-lock-comment-face)))
6024 (t ;; just any other in-buffer setting, but not indented
6025 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6026 (remove-text-properties (match-beginning 0) (match-end 0)
6027 '(display t invisible t intangible t))
6028 (add-text-properties beg (match-end 0)
6029 '(font-lock-fontified t face org-meta-line))
6030 t))))))
6032 (defun org-fontify-drawers (limit)
6033 "Fontify drawers."
6034 (when (re-search-forward org-drawer-regexp limit t)
6035 (add-text-properties
6036 (match-beginning 0) (match-end 0)
6037 '(font-lock-fontified t face org-special-keyword))
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (defun org-fontify-macros (limit)
6042 "Fontify macros."
6043 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6044 (add-text-properties
6045 (match-beginning 0) (match-end 0)
6046 '(font-lock-fontified t face org-macro))
6047 (when org-hide-macro-markers
6048 (add-text-properties (match-end 2) (match-beginning 2)
6049 '(invisible t))
6050 (add-text-properties (match-beginning 1) (match-end 1)
6051 '(invisible t)))
6052 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6055 (defun org-activate-footnote-links (limit)
6056 "Add text properties for footnotes."
6057 (let ((fn (org-footnote-next-reference-or-definition limit)))
6058 (when fn
6059 (let* ((beg (nth 1 fn))
6060 (end (nth 2 fn))
6061 (label (car fn))
6062 (referencep (/= (line-beginning-position) beg)))
6063 (when (and referencep (nth 3 fn))
6064 (save-excursion
6065 (goto-char beg)
6066 (search-forward (or label "fn:"))
6067 (org-remove-flyspell-overlays-in beg (match-end 0))))
6068 (add-text-properties beg end
6069 (list 'mouse-face 'highlight
6070 'keymap org-mouse-map
6071 'help-echo
6072 (if referencep "Footnote reference"
6073 "Footnote definition")
6074 'font-lock-fontified t
6075 'font-lock-multiline t
6076 'face 'org-footnote))))))
6078 (defun org-activate-dates (limit)
6079 "Add text properties for dates."
6080 (when (and (re-search-forward org-tsr-regexp-both limit t)
6081 (not (equal (char-before (match-beginning 0)) 91)))
6082 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6083 (add-text-properties (match-beginning 0) (match-end 0)
6084 (list 'mouse-face 'highlight
6085 'keymap org-mouse-map))
6086 (org-rear-nonsticky-at (match-end 0))
6087 (when org-display-custom-times
6088 ;; If it's a date range, activate custom time for second date.
6089 (when (match-end 3)
6090 (org-display-custom-time (match-beginning 3) (match-end 3)))
6091 (org-display-custom-time (match-beginning 1) (match-end 1)))
6094 (defvar-local org-target-link-regexp nil
6095 "Regular expression matching radio targets in plain text.")
6097 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6098 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6099 border border border))
6100 "Regular expression matching a link target.")
6102 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6103 "Regular expression matching a radio target.")
6105 (defconst org-any-target-regexp
6106 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6107 "Regular expression matching any target.")
6109 (defun org-activate-target-links (limit)
6110 "Add text properties for target matches."
6111 (when org-target-link-regexp
6112 (let ((case-fold-search t))
6113 (when (re-search-forward org-target-link-regexp limit t)
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map
6118 'help-echo "Radio target link"
6119 'org-linked-text t))
6120 (org-rear-nonsticky-at (match-end 1))
6121 t))))
6123 (defun org-update-radio-target-regexp ()
6124 "Find all radio targets in this file and update the regular expression.
6125 Also refresh fontification if needed."
6126 (interactive)
6127 (let ((old-regexp org-target-link-regexp)
6128 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6129 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6130 (targets
6131 (org-with-wide-buffer
6132 (goto-char (point-min))
6133 (let (rtn)
6134 (while (re-search-forward org-radio-target-regexp nil t)
6135 ;; Make sure point is really within the object.
6136 (backward-char)
6137 (let ((obj (org-element-context)))
6138 (when (eq (org-element-type obj) 'radio-target)
6139 (cl-pushnew (org-element-property :value obj) rtn
6140 :test #'equal))))
6141 rtn))))
6142 (setq org-target-link-regexp
6143 (and targets
6144 (concat before-re
6145 (mapconcat
6146 (lambda (x)
6147 (replace-regexp-in-string
6148 " +" "\\s-+" (regexp-quote x) t t))
6149 targets
6150 "\\|")
6151 after-re)))
6152 (unless (equal old-regexp org-target-link-regexp)
6153 ;; Clean-up cache.
6154 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6155 ((not org-target-link-regexp) old-regexp)
6157 (concat before-re
6158 (mapconcat
6159 (lambda (re)
6160 (substring re (length before-re)
6161 (- (length after-re))))
6162 (list old-regexp org-target-link-regexp)
6163 "\\|")
6164 after-re)))))
6165 (org-with-wide-buffer
6166 (goto-char (point-min))
6167 (while (re-search-forward regexp nil t)
6168 (org-element-cache-refresh (match-beginning 1)))))
6169 ;; Re fontify buffer.
6170 (when (memq 'radio org-highlight-links)
6171 (org-restart-font-lock)))))
6173 (defvar org-latex-and-related-regexp nil
6174 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6176 (defun org-compute-latex-and-related-regexp ()
6177 "Compute regular expression for LaTeX, entities and sub/superscript.
6178 Result depends on variable `org-highlight-latex-and-related'."
6179 (setq-local
6180 org-latex-and-related-regexp
6181 (let* ((re-sub
6182 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6183 ((eq org-use-sub-superscripts '{})
6184 (list org-match-substring-with-braces-regexp))
6185 (org-use-sub-superscripts (list org-match-substring-regexp))))
6186 (re-latex
6187 (when (memq 'latex org-highlight-latex-and-related)
6188 (let ((matchers (plist-get org-format-latex-options :matchers)))
6189 (delq nil
6190 (mapcar (lambda (x)
6191 (and (member (car x) matchers) (nth 1 x)))
6192 org-latex-regexps)))))
6193 (re-entities
6194 (when (memq 'entities org-highlight-latex-and-related)
6195 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6196 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6198 (defun org-do-latex-and-related (limit)
6199 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6200 LIMIT bounds the search for syntax to highlight. Stop at first
6201 highlighted object, if any. Return t if some highlighting was
6202 done, nil otherwise."
6203 (when (org-string-nw-p org-latex-and-related-regexp)
6204 (catch 'found
6205 (while (re-search-forward org-latex-and-related-regexp limit t)
6206 (unless
6207 (cl-some
6208 (lambda (f)
6209 (memq f '(org-code org-verbatim underline org-special-keyword)))
6210 (save-excursion
6211 (goto-char (1+ (match-beginning 0)))
6212 (face-at-point nil t)))
6213 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6214 '(?_ ?^))
6216 0)))
6217 (font-lock-prepend-text-property
6218 (+ offset (match-beginning 0)) (match-end 0)
6219 'face 'org-latex-and-related)
6220 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6221 '(font-lock-multiline t)))
6222 (throw 'found t)))
6223 nil)))
6225 (defun org-restart-font-lock ()
6226 "Restart `font-lock-mode', to force refontification."
6227 (when (and (boundp 'font-lock-mode) font-lock-mode)
6228 (font-lock-mode -1)
6229 (font-lock-mode 1)))
6231 (defun org-activate-tags (limit)
6232 (when (re-search-forward
6233 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6234 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6235 (add-text-properties (match-beginning 1) (match-end 1)
6236 (list 'mouse-face 'highlight
6237 'keymap org-mouse-map))
6238 (org-rear-nonsticky-at (match-end 1))
6241 (defun org-outline-level ()
6242 "Compute the outline level of the heading at point.
6244 If this is called at a normal headline, the level is the number
6245 of stars. Use `org-reduced-level' to remove the effect of
6246 `org-odd-levels'. Unlike to `org-current-level', this function
6247 takes into consideration inlinetasks."
6248 (org-with-wide-buffer
6249 (end-of-line)
6250 (if (re-search-backward org-outline-regexp-bol nil t)
6251 (1- (- (match-end 0) (match-beginning 0)))
6252 0)))
6254 (defvar org-font-lock-keywords nil)
6256 (defsubst org-re-property (property &optional literal allow-null value)
6257 "Return a regexp matching a PROPERTY line.
6259 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6260 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6261 non-nil, match properties even without a value.
6263 Match group 3 is set to the value when it exists. If there is no
6264 value and ALLOW-NULL is non-nil, it is set to the empty string.
6266 With optional argument VALUE, match only property lines with
6267 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6268 unless LITERAL is non-nil."
6269 (concat
6270 "^\\(?4:[ \t]*\\)"
6271 (format "\\(?1::\\(?2:%s\\):\\)"
6272 (if literal property (regexp-quote property)))
6273 (cond (value
6274 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6275 (if literal value (regexp-quote value))))
6276 (allow-null
6277 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6279 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6281 (defconst org-property-re
6282 (org-re-property "\\S-+" 'literal t)
6283 "Regular expression matching a property line.
6284 There are four matching groups:
6285 1: :PROPKEY: including the leading and trailing colon,
6286 2: PROPKEY without the leading and trailing colon,
6287 3: PROPVAL without leading or trailing spaces,
6288 4: the indentation of the current line,
6289 5: trailing whitespace.")
6291 (defvar org-font-lock-hook nil
6292 "Functions to be called for special font lock stuff.")
6294 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6296 (defvar org-font-lock-set-keywords-hook nil
6297 "Functions that can manipulate `org-font-lock-extra-keywords'.
6298 This is called after `org-font-lock-extra-keywords' is defined, but before
6299 it is installed to be used by font lock. This can be useful if something
6300 needs to be inserted at a specific position in the font-lock sequence.")
6302 (defun org-font-lock-hook (limit)
6303 "Run `org-font-lock-hook' within LIMIT."
6304 (run-hook-with-args 'org-font-lock-hook limit))
6306 (defun org-set-font-lock-defaults ()
6307 "Set font lock defaults for the current buffer."
6308 (let* ((em org-fontify-emphasized-text)
6309 (lk org-highlight-links)
6310 (org-font-lock-extra-keywords
6311 (list
6312 ;; Call the hook
6313 '(org-font-lock-hook)
6314 ;; Headlines
6315 `(,(if org-fontify-whole-heading-line
6316 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6317 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6318 (1 (org-get-level-face 1))
6319 (2 (org-get-level-face 2))
6320 (3 (org-get-level-face 3)))
6321 ;; Table lines
6322 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6323 (1 'org-table t))
6324 ;; Table internals
6325 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6326 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6327 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6328 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6329 ;; Drawers
6330 '(org-fontify-drawers)
6331 ;; Properties
6332 (list org-property-re
6333 '(1 'org-special-keyword t)
6334 '(3 'org-property-value t))
6335 ;; Link related fontification.
6336 '(org-activate-links)
6337 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6338 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6339 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6340 (when (memq 'footnote lk) '(org-activate-footnote-links))
6341 ;; Targets.
6342 (list org-any-target-regexp '(0 'org-target t))
6343 ;; Diary sexps.
6344 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6345 ;; Macro
6346 '(org-fontify-macros)
6347 ;; TODO keyword
6348 (list (format org-heading-keyword-regexp-format
6349 org-todo-regexp)
6350 '(2 (org-get-todo-face 2) t))
6351 ;; DONE
6352 (if org-fontify-done-headline
6353 (list (format org-heading-keyword-regexp-format
6354 (concat
6355 "\\(?:"
6356 (mapconcat 'regexp-quote org-done-keywords "\\|")
6357 "\\)"))
6358 '(2 'org-headline-done t))
6359 nil)
6360 ;; Priorities
6361 '(org-font-lock-add-priority-faces)
6362 ;; Tags
6363 '(org-font-lock-add-tag-faces)
6364 ;; Tags groups
6365 (when (and org-group-tags org-tag-groups-alist)
6366 (list (concat org-outline-regexp-bol ".+\\(:"
6367 (regexp-opt (mapcar 'car org-tag-groups-alist))
6368 ":\\).*$")
6369 '(1 'org-tag-group prepend)))
6370 ;; Special keywords
6371 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6372 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6373 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6374 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6375 ;; Emphasis
6376 (when em '(org-do-emphasis-faces))
6377 ;; Checkboxes
6378 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6379 1 'org-checkbox prepend)
6380 (when (cdr (assq 'checkbox org-list-automatic-rules))
6381 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6382 (0 (org-get-checkbox-statistics-face) t)))
6383 ;; Description list items
6384 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6385 1 'org-list-dt prepend)
6386 ;; ARCHIVEd headings
6387 (list (concat
6388 org-outline-regexp-bol
6389 "\\(.*:" org-archive-tag ":.*\\)")
6390 '(1 'org-archived prepend))
6391 ;; Specials
6392 '(org-do-latex-and-related)
6393 '(org-fontify-entities)
6394 '(org-raise-scripts)
6395 ;; Code
6396 '(org-activate-code (1 'org-code t))
6397 ;; COMMENT
6398 (list (format
6399 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6400 org-todo-regexp
6401 org-comment-string)
6402 '(9 'org-special-keyword t))
6403 ;; Blocks and meta lines
6404 '(org-fontify-meta-lines-and-blocks))))
6405 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6406 (run-hooks 'org-font-lock-set-keywords-hook)
6407 ;; Now set the full font-lock-keywords
6408 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6409 (setq-local font-lock-defaults
6410 '(org-font-lock-keywords t nil nil backward-paragraph))
6411 (kill-local-variable 'font-lock-keywords)
6412 nil))
6414 (defun org-toggle-pretty-entities ()
6415 "Toggle the composition display of entities as UTF8 characters."
6416 (interactive)
6417 (setq-local org-pretty-entities (not org-pretty-entities))
6418 (org-restart-font-lock)
6419 (if org-pretty-entities
6420 (message "Entities are now displayed as UTF8 characters")
6421 (save-restriction
6422 (widen)
6423 (decompose-region (point-min) (point-max))
6424 (message "Entities are now displayed as plain text"))))
6426 (defvar-local org-custom-properties-overlays nil
6427 "List of overlays used for custom properties.")
6429 (defun org-toggle-custom-properties-visibility ()
6430 "Display or hide properties in `org-custom-properties'."
6431 (interactive)
6432 (if org-custom-properties-overlays
6433 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6434 (setq org-custom-properties-overlays nil))
6435 (when org-custom-properties
6436 (org-with-wide-buffer
6437 (goto-char (point-min))
6438 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6439 (while (re-search-forward regexp nil t)
6440 (let ((end (cdr (save-match-data (org-get-property-block)))))
6441 (when (and end (< (point) end))
6442 ;; Hide first custom property in current drawer.
6443 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6444 (overlay-put o 'invisible t)
6445 (overlay-put o 'org-custom-property t)
6446 (push o org-custom-properties-overlays))
6447 ;; Hide additional custom properties in the same drawer.
6448 (while (re-search-forward regexp end t)
6449 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6450 (overlay-put o 'invisible t)
6451 (overlay-put o 'org-custom-property t)
6452 (push o org-custom-properties-overlays)))))
6453 ;; Each entry is limited to a single property drawer.
6454 (outline-next-heading)))))))
6456 (defun org-fontify-entities (limit)
6457 "Find an entity to fontify."
6458 (let (ee)
6459 (when org-pretty-entities
6460 (catch 'match
6461 ;; "\_ "-family is left out on purpose. Only the first one,
6462 ;; i.e., "\_ ", could be fontified anyway, and it would be
6463 ;; confusing when adding a second white space character.
6464 (while (re-search-forward
6465 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6466 limit t)
6467 (when (and (not (org-at-comment-p))
6468 (setq ee (org-entity-get (match-string 1)))
6469 (= (length (nth 6 ee)) 1))
6470 (let* ((end (if (equal (match-string 2) "{}")
6471 (match-end 2)
6472 (match-end 1))))
6473 (add-text-properties
6474 (match-beginning 0) end
6475 (list 'font-lock-fontified t))
6476 (compose-region (match-beginning 0) end
6477 (nth 6 ee) nil)
6478 (backward-char 1)
6479 (throw 'match t))))
6480 nil))))
6482 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6483 "Fontify string S like in Org mode."
6484 (with-temp-buffer
6485 (insert s)
6486 (let ((org-odd-levels-only odd-levels))
6487 (org-mode)
6488 (org-font-lock-ensure)
6489 (buffer-string))))
6491 (defvar org-m nil)
6492 (defvar org-l nil)
6493 (defvar org-f nil)
6494 (defun org-get-level-face (n)
6495 "Get the right face for match N in font-lock matching of headlines."
6496 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6497 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6498 (if org-cycle-level-faces
6499 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6500 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6501 (cond
6502 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6503 ((eq n 2) org-f)
6504 (t (unless org-level-color-stars-only org-f))))
6506 (defun org-face-from-face-or-color (context inherit face-or-color)
6507 "Create a face list that inherits INHERIT, but sets the foreground color.
6508 When FACE-OR-COLOR is not a string, just return it."
6509 (if (stringp face-or-color)
6510 (list :inherit inherit
6511 (cdr (assoc context org-faces-easy-properties))
6512 face-or-color)
6513 face-or-color))
6515 (defun org-get-todo-face (kwd)
6516 "Get the right face for a TODO keyword KWD.
6517 If KWD is a number, get the corresponding match group."
6518 (when (numberp kwd) (setq kwd (match-string kwd)))
6519 (or (org-face-from-face-or-color
6520 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6521 (and (member kwd org-done-keywords) 'org-done)
6522 'org-todo))
6524 (defun org-get-priority-face (priority)
6525 "Get the right face for PRIORITY.
6526 PRIORITY is a character."
6527 (or (org-face-from-face-or-color
6528 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6529 'org-priority))
6531 (defun org-get-tag-face (tag)
6532 "Get the right face for TAG.
6533 If TAG is a number, get the corresponding match group."
6534 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6535 (or (org-face-from-face-or-color
6536 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6537 'org-tag)))
6539 (defun org-font-lock-add-priority-faces (limit)
6540 "Add the special priority faces."
6541 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6542 (add-text-properties
6543 (match-beginning 1) (match-end 1)
6544 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6545 'font-lock-fontified t))))
6547 (defun org-font-lock-add-tag-faces (limit)
6548 "Add the special tag faces."
6549 (when (and org-tag-faces org-tags-special-faces-re)
6550 (while (re-search-forward org-tags-special-faces-re limit t)
6551 (add-text-properties (match-beginning 1) (match-end 1)
6552 (list 'face (org-get-tag-face 1)
6553 'font-lock-fontified t))
6554 (backward-char 1))))
6556 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6557 "Remove fontification and activation overlays from links."
6558 (font-lock-default-unfontify-region beg end)
6559 (let* ((buffer-undo-list t)
6560 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6561 (inhibit-modification-hooks t)
6562 deactivate-mark buffer-file-name buffer-file-truename)
6563 (decompose-region beg end)
6564 (remove-text-properties beg end
6565 '(mouse-face t keymap t org-linked-text t
6566 invisible t intangible t
6567 org-emphasis t))
6568 (org-remove-font-lock-display-properties beg end)))
6570 (defconst org-script-display '(((raise -0.3) (height 0.7))
6571 ((raise 0.3) (height 0.7))
6572 ((raise -0.5))
6573 ((raise 0.5)))
6574 "Display properties for showing superscripts and subscripts.")
6576 (defun org-remove-font-lock-display-properties (beg end)
6577 "Remove specific display properties that have been added by font lock.
6578 The will remove the raise properties that are used to show superscripts
6579 and subscripts."
6580 (let (next prop)
6581 (while (< beg end)
6582 (setq next (next-single-property-change beg 'display nil end)
6583 prop (get-text-property beg 'display))
6584 (when (member prop org-script-display)
6585 (put-text-property beg next 'display nil))
6586 (setq beg next))))
6588 (defun org-raise-scripts (limit)
6589 "Add raise properties to sub/superscripts."
6590 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6591 (re-search-forward
6592 (if (eq org-use-sub-superscripts t)
6593 org-match-substring-regexp
6594 org-match-substring-with-braces-regexp)
6595 limit t))
6596 (let* ((pos (point)) table-p comment-p
6597 (mpos (match-beginning 3))
6598 (emph-p (get-text-property mpos 'org-emphasis))
6599 (link-p (get-text-property mpos 'mouse-face))
6600 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6601 (goto-char (point-at-bol))
6602 (setq table-p (looking-at-p org-table-dataline-regexp)
6603 comment-p (looking-at-p "^[ \t]*#[ +]"))
6604 (goto-char pos)
6605 ;; Handle a_b^c
6606 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6607 (unless (or comment-p emph-p link-p keyw-p)
6608 (put-text-property (match-beginning 3) (match-end 0)
6609 'display
6610 (if (equal (char-after (match-beginning 2)) ?^)
6611 (nth (if table-p 3 1) org-script-display)
6612 (nth (if table-p 2 0) org-script-display)))
6613 (add-text-properties (match-beginning 2) (match-end 2)
6614 (list 'invisible t))
6615 (when (and (eq (char-after (match-beginning 3)) ?{)
6616 (eq (char-before (match-end 3)) ?}))
6617 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6618 (list 'invisible t))
6619 (add-text-properties (1- (match-end 3)) (match-end 3)
6620 (list 'invisible t))))
6621 t)))
6623 ;;;; Visibility cycling, including org-goto and indirect buffer
6625 ;;; Cycling
6627 (defvar-local org-cycle-global-status nil)
6628 (put 'org-cycle-global-status 'org-state t)
6629 (defvar-local org-cycle-subtree-status nil)
6630 (put 'org-cycle-subtree-status 'org-state t)
6632 (defvar org-inlinetask-min-level)
6634 (defun org-unlogged-message (&rest args)
6635 "Display a message, but avoid logging it in the *Messages* buffer."
6636 (let ((message-log-max nil))
6637 (apply 'message args)))
6639 ;;;###autoload
6640 (defun org-cycle (&optional arg)
6641 "TAB-action and visibility cycling for Org mode.
6643 This is the command invoked in Org mode by the `TAB' key. Its main
6644 purpose is outline visibility cycling, but it also invokes other actions
6645 in special contexts.
6647 When this function is called with a `\\[universal-argument]' prefix, rotate \
6648 the entire
6649 buffer through 3 states (global cycling)
6650 1. OVERVIEW: Show only top-level headlines.
6651 2. CONTENTS: Show all headlines of all levels, but no body text.
6652 3. SHOW ALL: Show everything.
6654 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6655 switch to the startup visibility,
6656 determined by the variable `org-startup-folded', and by any VISIBILITY
6657 properties in the buffer.
6659 With a `\\[universal-argument] \\[universal-argument] \
6660 \\[universal-argument]' prefix argument, show the entire buffer, including
6661 any drawers.
6663 When inside a table, re-align the table and move to the next field.
6665 When point is at the beginning of a headline, rotate the subtree started
6666 by this line through 3 different states (local cycling)
6667 1. FOLDED: Only the main headline is shown.
6668 2. CHILDREN: The main headline and the direct children are shown.
6669 From this state, you can move to one of the children
6670 and zoom in further.
6671 3. SUBTREE: Show the entire subtree, including body text.
6672 If there is no subtree, switch directly from CHILDREN to FOLDED.
6674 When point is at the beginning of an empty headline and the variable
6675 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6676 of the headline by demoting and promoting it to likely levels. This
6677 speeds up creation document structure by pressing `TAB' once or several
6678 times right after creating a new headline.
6680 When there is a numeric prefix, go up to a heading with level ARG, do
6681 a `show-subtree' and return to the previous cursor position. If ARG
6682 is negative, go up that many levels.
6684 When point is not at the beginning of a headline, execute the global
6685 binding for `TAB', which is re-indenting the line. See the option
6686 `org-cycle-emulate-tab' for details.
6688 As a special case, if point is at the beginning of the buffer and there is
6689 no headline in line 1, this function will act as if called with prefix arg
6690 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6691 prefix arg, but only
6692 if the variable `org-cycle-global-at-bob' is t."
6693 (interactive "P")
6694 (org-load-modules-maybe)
6695 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6696 (and org-cycle-level-after-item/entry-creation
6697 (or (org-cycle-level)
6698 (org-cycle-item-indentation))))
6699 (let* ((limit-level
6700 (or org-cycle-max-level
6701 (and (boundp 'org-inlinetask-min-level)
6702 org-inlinetask-min-level
6703 (1- org-inlinetask-min-level))))
6704 (nstars (and limit-level
6705 (if org-odd-levels-only
6706 (and limit-level (1- (* limit-level 2)))
6707 limit-level)))
6708 (org-outline-regexp
6709 (if (not (derived-mode-p 'org-mode))
6710 outline-regexp
6711 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6712 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6713 (not (looking-at org-outline-regexp))))
6714 (org-cycle-hook
6715 (if bob-special
6716 (delq 'org-optimize-window-after-visibility-change
6717 (copy-sequence org-cycle-hook))
6718 org-cycle-hook))
6719 (pos (point)))
6721 (cond
6723 ((equal arg '(16))
6724 (setq last-command 'dummy)
6725 (org-set-startup-visibility)
6726 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6728 ((equal arg '(64))
6729 (outline-show-all)
6730 (org-unlogged-message "Entire buffer visible, including drawers"))
6732 ((equal arg '(4)) (org-cycle-internal-global))
6734 ;; Try hiding block at point.
6735 ((org-hide-block-toggle-maybe))
6737 ;; Try cdlatex TAB completion
6738 ((org-try-cdlatex-tab))
6740 ;; Table: enter it or move to the next field.
6741 ((org-at-table-p 'any)
6742 (if (org-at-table.el-p)
6743 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6744 Use `\\[org-edit-special]' to edit table.el tables"))
6745 (if arg (org-table-edit-field t)
6746 (org-table-justify-field-maybe)
6747 (call-interactively 'org-table-next-field))))
6749 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6751 ;; Global cycling: delegate to `org-cycle-internal-global'.
6752 (bob-special (org-cycle-internal-global))
6754 ;; Drawers: delegate to `org-flag-drawer'.
6755 ((save-excursion
6756 (beginning-of-line 1)
6757 (looking-at org-drawer-regexp))
6758 (org-flag-drawer ; toggle block visibility
6759 (not (get-char-property (match-end 0) 'invisible))))
6761 ;; Show-subtree, ARG levels up from here.
6762 ((integerp arg)
6763 (save-excursion
6764 (org-back-to-heading)
6765 (outline-up-heading (if (< arg 0) (- arg)
6766 (- (funcall outline-level) arg)))
6767 (org-show-subtree)))
6769 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6770 ((and (featurep 'org-inlinetask)
6771 (org-inlinetask-at-task-p)
6772 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6773 (org-inlinetask-toggle-visibility))
6775 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6776 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6777 (save-excursion (move-beginning-of-line 1)
6778 (looking-at org-outline-regexp)))
6779 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6780 (org-cycle-internal-local))
6782 ;; From there: TAB emulation and template completion.
6783 (buffer-read-only (org-back-to-heading))
6785 ((run-hook-with-args-until-success
6786 'org-tab-after-check-for-cycling-hook))
6788 ((org-try-structure-completion))
6790 ((run-hook-with-args-until-success
6791 'org-tab-before-tab-emulation-hook))
6793 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6794 (or (not (bolp))
6795 (not (looking-at org-outline-regexp))))
6796 (call-interactively (global-key-binding "\t")))
6798 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6799 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6800 (or (and (eq org-cycle-emulate-tab 'white)
6801 (= (match-end 0) (point-at-eol)))
6802 (and (eq org-cycle-emulate-tab 'whitestart)
6803 (>= (match-end 0) pos))))
6805 (eq org-cycle-emulate-tab t))
6806 (call-interactively (global-key-binding "\t")))
6808 (t (save-excursion
6809 (org-back-to-heading)
6810 (org-cycle)))))))
6812 (defun org-cycle-internal-global ()
6813 "Do the global cycling action."
6814 ;; Hack to avoid display of messages for .org attachments in Gnus
6815 (let ((ga (string-match "\\*fontification" (buffer-name))))
6816 (cond
6817 ((and (eq last-command this-command)
6818 (eq org-cycle-global-status 'overview))
6819 ;; We just created the overview - now do table of contents
6820 ;; This can be slow in very large buffers, so indicate action
6821 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6822 (unless ga (org-unlogged-message "CONTENTS..."))
6823 (org-content)
6824 (unless ga (org-unlogged-message "CONTENTS...done"))
6825 (setq org-cycle-global-status 'contents)
6826 (run-hook-with-args 'org-cycle-hook 'contents))
6828 ((and (eq last-command this-command)
6829 (eq org-cycle-global-status 'contents))
6830 ;; We just showed the table of contents - now show everything
6831 (run-hook-with-args 'org-pre-cycle-hook 'all)
6832 (outline-show-all)
6833 (unless ga (org-unlogged-message "SHOW ALL"))
6834 (setq org-cycle-global-status 'all)
6835 (run-hook-with-args 'org-cycle-hook 'all))
6838 ;; Default action: go to overview
6839 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6840 (org-overview)
6841 (unless ga (org-unlogged-message "OVERVIEW"))
6842 (setq org-cycle-global-status 'overview)
6843 (run-hook-with-args 'org-cycle-hook 'overview)))))
6845 (defvar org-called-with-limited-levels nil
6846 "Non-nil when `org-with-limited-levels' is currently active.")
6848 (defun org-invisible-p (&optional pos)
6849 "Non-nil if the character after POS is invisible.
6850 If POS is nil, use `point' instead."
6851 (get-char-property (or pos (point)) 'invisible))
6853 (defun org-cycle-internal-local ()
6854 "Do the local cycling action."
6855 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6856 ;; First, determine end of headline (EOH), end of subtree or item
6857 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6858 (save-excursion
6859 (if (org-at-item-p)
6860 (progn
6861 (beginning-of-line)
6862 (setq struct (org-list-struct))
6863 (setq eoh (point-at-eol))
6864 (setq eos (org-list-get-item-end-before-blank (point) struct))
6865 (setq has-children (org-list-has-child-p (point) struct)))
6866 (org-back-to-heading)
6867 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6868 (setq eos (save-excursion (org-end-of-subtree t t)
6869 (when (bolp) (backward-char)) (point)))
6870 (setq has-children
6871 (or (save-excursion
6872 (let ((level (funcall outline-level)))
6873 (outline-next-heading)
6874 (and (org-at-heading-p t)
6875 (> (funcall outline-level) level))))
6876 (save-excursion
6877 (org-list-search-forward (org-item-beginning-re) eos t)))))
6878 ;; Determine end invisible part of buffer (EOL)
6879 (beginning-of-line 2)
6880 (while (and (not (eobp)) ;This is like `next-line'.
6881 (get-char-property (1- (point)) 'invisible))
6882 (goto-char (next-single-char-property-change (point) 'invisible))
6883 (and (eolp) (beginning-of-line 2)))
6884 (setq eol (point)))
6885 ;; Find out what to do next and set `this-command'
6886 (cond
6887 ((= eos eoh)
6888 ;; Nothing is hidden behind this heading
6889 (unless (org-before-first-heading-p)
6890 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6891 (org-unlogged-message "EMPTY ENTRY")
6892 (setq org-cycle-subtree-status nil)
6893 (save-excursion
6894 (goto-char eos)
6895 (outline-next-heading)
6896 (when (org-invisible-p) (org-flag-heading nil))))
6897 ((and (or (>= eol eos)
6898 (not (string-match "\\S-" (buffer-substring eol eos))))
6899 (or has-children
6900 (not (setq children-skipped
6901 org-cycle-skip-children-state-if-no-children))))
6902 ;; Entire subtree is hidden in one line: children view
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-pre-cycle-hook 'children))
6905 (if (org-at-item-p)
6906 (org-list-set-item-visibility (point-at-bol) struct 'children)
6907 (org-show-entry)
6908 (org-with-limited-levels (org-show-children))
6909 ;; FIXME: This slows down the func way too much.
6910 ;; How keep drawers hidden in subtree anyway?
6911 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6912 ;; (org-cycle-hide-drawers 'subtree))
6914 ;; Fold every list in subtree to top-level items.
6915 (when (eq org-cycle-include-plain-lists 'integrate)
6916 (save-excursion
6917 (org-back-to-heading)
6918 (while (org-list-search-forward (org-item-beginning-re) eos t)
6919 (beginning-of-line 1)
6920 (let* ((struct (org-list-struct))
6921 (prevs (org-list-prevs-alist struct))
6922 (end (org-list-get-bottom-point struct)))
6923 (dolist (e (org-list-get-all-items (point) struct prevs))
6924 (org-list-set-item-visibility e struct 'folded))
6925 (goto-char (if (< end eos) end eos)))))))
6926 (org-unlogged-message "CHILDREN")
6927 (save-excursion
6928 (goto-char eos)
6929 (outline-next-heading)
6930 (when (org-invisible-p) (org-flag-heading nil)))
6931 (setq org-cycle-subtree-status 'children)
6932 (unless (org-before-first-heading-p)
6933 (run-hook-with-args 'org-cycle-hook 'children)))
6934 ((or children-skipped
6935 (and (eq last-command this-command)
6936 (eq org-cycle-subtree-status 'children)))
6937 ;; We just showed the children, or no children are there,
6938 ;; now show everything.
6939 (unless (org-before-first-heading-p)
6940 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6941 (outline-flag-region eoh eos nil)
6942 (org-unlogged-message
6943 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6944 (setq org-cycle-subtree-status 'subtree)
6945 (unless (org-before-first-heading-p)
6946 (run-hook-with-args 'org-cycle-hook 'subtree)))
6948 ;; Default action: hide the subtree.
6949 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6950 (outline-flag-region eoh eos t)
6951 (org-unlogged-message "FOLDED")
6952 (setq org-cycle-subtree-status 'folded)
6953 (unless (org-before-first-heading-p)
6954 (run-hook-with-args 'org-cycle-hook 'folded))))))
6956 ;;;###autoload
6957 (defun org-global-cycle (&optional arg)
6958 "Cycle the global visibility. For details see `org-cycle'.
6959 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6960 With a numeric prefix, show all headlines up to that level."
6961 (interactive "P")
6962 (let ((org-cycle-include-plain-lists
6963 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6964 (cond
6965 ((integerp arg)
6966 (outline-show-all)
6967 (outline-hide-sublevels arg)
6968 (setq org-cycle-global-status 'contents))
6969 ((equal arg '(4))
6970 (org-set-startup-visibility)
6971 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6973 (org-cycle '(4))))))
6975 (defun org-set-startup-visibility ()
6976 "Set the visibility required by startup options and properties."
6977 (cond
6978 ((eq org-startup-folded t)
6979 (org-overview))
6980 ((eq org-startup-folded 'content)
6981 (org-content))
6982 ((or (eq org-startup-folded 'showeverything)
6983 (eq org-startup-folded nil))
6984 (outline-show-all)))
6985 (unless (eq org-startup-folded 'showeverything)
6986 (when org-hide-block-startup (org-hide-block-all))
6987 (org-set-visibility-according-to-property 'no-cleanup)
6988 (org-cycle-hide-archived-subtrees 'all)
6989 (org-cycle-hide-drawers 'all)
6990 (org-cycle-show-empty-lines t)))
6992 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6993 "Switch subtree visibilities according to :VISIBILITY: property."
6994 (interactive)
6995 (org-with-wide-buffer
6996 (goto-char (point-min))
6997 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6998 (if (not (org-at-property-p)) (outline-next-heading)
6999 (let ((state (match-string 3)))
7000 (save-excursion
7001 (org-back-to-heading t)
7002 (outline-hide-subtree)
7003 (org-reveal)
7004 (cond
7005 ((equal state "folded")
7006 (outline-hide-subtree))
7007 ((equal state "children")
7008 (org-show-hidden-entry)
7009 (org-show-children))
7010 ((equal state "content")
7011 (save-excursion
7012 (save-restriction
7013 (org-narrow-to-subtree)
7014 (org-content))))
7015 ((member state '("all" "showall"))
7016 (outline-show-subtree)))))))
7017 (unless no-cleanup
7018 (org-cycle-hide-archived-subtrees 'all)
7019 (org-cycle-hide-drawers 'all)
7020 (org-cycle-show-empty-lines 'all))))
7022 ;; This function uses outline-regexp instead of the more fundamental
7023 ;; org-outline-regexp so that org-cycle-global works outside of Org
7024 ;; buffers, where outline-regexp is needed.
7025 (defun org-overview ()
7026 "Switch to overview mode, showing only top-level headlines.
7027 This shows all headlines with a level equal or greater than the level
7028 of the first headline in the buffer. This is important, because if the
7029 first headline is not level one, then (hide-sublevels 1) gives confusing
7030 results."
7031 (interactive)
7032 (save-excursion
7033 (let ((level
7034 (save-excursion
7035 (goto-char (point-min))
7036 (when (re-search-forward (concat "^" outline-regexp) nil t)
7037 (goto-char (match-beginning 0))
7038 (funcall outline-level)))))
7039 (and level (outline-hide-sublevels level)))))
7041 (defun org-content (&optional arg)
7042 "Show all headlines in the buffer, like a table of contents.
7043 With numerical argument N, show content up to level N."
7044 (interactive "P")
7045 (org-overview)
7046 (save-excursion
7047 ;; Visit all headings and show their offspring
7048 (and (integerp arg) (org-overview))
7049 (goto-char (point-max))
7050 (catch 'exit
7051 (while (and (progn (condition-case nil
7052 (outline-previous-visible-heading 1)
7053 (error (goto-char (point-min))))
7055 (looking-at org-outline-regexp))
7056 (if (integerp arg)
7057 (org-show-children (1- arg))
7058 (outline-show-branches))
7059 (when (bobp) (throw 'exit nil))))))
7061 (defun org-optimize-window-after-visibility-change (state)
7062 "Adjust the window after a change in outline visibility.
7063 This function is the default value of the hook `org-cycle-hook'."
7064 (when (get-buffer-window (current-buffer))
7065 (cond
7066 ((eq state 'content) nil)
7067 ((eq state 'all) nil)
7068 ((eq state 'folded) nil)
7069 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7070 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7072 (defun org-remove-empty-overlays-at (pos)
7073 "Remove outline overlays that do not contain non-white stuff."
7074 (dolist (o (overlays-at pos))
7075 (and (eq 'outline (overlay-get o 'invisible))
7076 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7077 (overlay-end o))))
7078 (delete-overlay o))))
7080 (defun org-clean-visibility-after-subtree-move ()
7081 "Fix visibility issues after moving a subtree."
7082 ;; First, find a reasonable region to look at:
7083 ;; Start two siblings above, end three below
7084 (let* ((beg (save-excursion
7085 (and (org-get-last-sibling)
7086 (org-get-last-sibling))
7087 (point)))
7088 (end (save-excursion
7089 (and (org-get-next-sibling)
7090 (org-get-next-sibling)
7091 (org-get-next-sibling))
7092 (if (org-at-heading-p)
7093 (point-at-eol)
7094 (point))))
7095 (level (looking-at "\\*+"))
7096 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7097 (save-excursion
7098 (save-restriction
7099 (narrow-to-region beg end)
7100 (when re
7101 ;; Properly fold already folded siblings
7102 (goto-char (point-min))
7103 (while (re-search-forward re nil t)
7104 (when (and (not (org-invisible-p))
7105 (save-excursion
7106 (goto-char (point-at-eol)) (org-invisible-p)))
7107 (outline-hide-entry))))
7108 (org-cycle-show-empty-lines 'overview)
7109 (org-cycle-hide-drawers 'overview)))))
7111 (defun org-cycle-show-empty-lines (state)
7112 "Show empty lines above all visible headlines.
7113 The region to be covered depends on STATE when called through
7114 `org-cycle-hook'. Lisp program can use t for STATE to get the
7115 entire buffer covered. Note that an empty line is only shown if there
7116 are at least `org-cycle-separator-lines' empty lines before the headline."
7117 (when (/= org-cycle-separator-lines 0)
7118 (save-excursion
7119 (let* ((n (abs org-cycle-separator-lines))
7120 (re (cond
7121 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7122 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7123 (t (let ((ns (number-to-string (- n 2))))
7124 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7125 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7126 beg end)
7127 (cond
7128 ((memq state '(overview contents t))
7129 (setq beg (point-min) end (point-max)))
7130 ((memq state '(children folded))
7131 (setq beg (point)
7132 end (progn (org-end-of-subtree t t)
7133 (line-beginning-position 2)))))
7134 (when beg
7135 (goto-char beg)
7136 (while (re-search-forward re end t)
7137 (unless (get-char-property (match-end 1) 'invisible)
7138 (let ((e (match-end 1))
7139 (b (if (>= org-cycle-separator-lines 0)
7140 (match-beginning 1)
7141 (save-excursion
7142 (goto-char (match-beginning 0))
7143 (skip-chars-backward " \t\n")
7144 (line-end-position)))))
7145 (outline-flag-region b e nil))))))))
7146 ;; Never hide empty lines at the end of the file.
7147 (save-excursion
7148 (goto-char (point-max))
7149 (outline-previous-heading)
7150 (outline-end-of-heading)
7151 (when (and (looking-at "[ \t\n]+")
7152 (= (match-end 0) (point-max)))
7153 (outline-flag-region (point) (match-end 0) nil))))
7155 (defun org-show-empty-lines-in-parent ()
7156 "Move to the parent and re-show empty lines before visible headlines."
7157 (save-excursion
7158 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7159 (org-cycle-show-empty-lines context))))
7161 (defun org-files-list ()
7162 "Return `org-agenda-files' list, plus all open Org files.
7163 This is useful for operations that need to scan all of a user's
7164 open and agenda-wise Org files."
7165 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7166 (dolist (buf (buffer-list))
7167 (with-current-buffer buf
7168 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7169 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7170 files))
7172 (defsubst org-entry-beginning-position ()
7173 "Return the beginning position of the current entry."
7174 (save-excursion (org-back-to-heading t) (point)))
7176 (defsubst org-entry-end-position ()
7177 "Return the end position of the current entry."
7178 (save-excursion (outline-next-heading) (point)))
7180 (defun org-cycle-hide-drawers (state &optional exceptions)
7181 "Re-hide all drawers after a visibility state change.
7182 STATE should be one of the symbols listed in the docstring of
7183 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7184 a list of strings specifying which drawers should not be hidden."
7185 (when (and (derived-mode-p 'org-mode)
7186 (not (memq state '(overview folded contents))))
7187 (save-excursion
7188 (let* ((globalp (eq state 'all))
7189 (beg (if globalp (point-min) (point)))
7190 (end (if globalp (point-max)
7191 (if (eq state 'children)
7192 (save-excursion (outline-next-heading) (point))
7193 (org-end-of-subtree t)))))
7194 (goto-char beg)
7195 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7196 (unless (member-ignore-case (match-string 1) exceptions)
7197 (let ((drawer (org-element-at-point)))
7198 (when (memq (org-element-type drawer) '(drawer property-drawer))
7199 (org-flag-drawer t drawer)
7200 ;; Make sure to skip drawer entirely or we might flag
7201 ;; it another time when matching its ending line with
7202 ;; `org-drawer-regexp'.
7203 (goto-char (org-element-property :end drawer))))))))))
7205 (defun org-flag-drawer (flag &optional element)
7206 "When FLAG is non-nil, hide the drawer we are at.
7207 Otherwise make it visible. When optional argument ELEMENT is
7208 a parsed drawer, as returned by `org-element-at-point', hide or
7209 show that drawer instead."
7210 (let ((drawer (or element
7211 (and (save-excursion
7212 (beginning-of-line)
7213 (looking-at-p org-drawer-regexp))
7214 (org-element-at-point)))))
7215 (when (memq (org-element-type drawer) '(drawer property-drawer))
7216 (let ((post (org-element-property :post-affiliated drawer)))
7217 (save-excursion
7218 (outline-flag-region
7219 (progn (goto-char post) (line-end-position))
7220 (progn (goto-char (org-element-property :end drawer))
7221 (skip-chars-backward " \r\t\n")
7222 (line-end-position))
7223 flag))
7224 ;; When the drawer is hidden away, make sure point lies in
7225 ;; a visible part of the buffer.
7226 (when (and flag (> (line-beginning-position) post))
7227 (goto-char post))))))
7229 (defun org-subtree-end-visible-p ()
7230 "Is the end of the current subtree visible?"
7231 (pos-visible-in-window-p
7232 (save-excursion (org-end-of-subtree t) (point))))
7234 (defun org-first-headline-recenter ()
7235 "Move cursor to the first headline and recenter the headline."
7236 (let ((window (get-buffer-window)))
7237 (when window
7238 (goto-char (point-min))
7239 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7240 (set-window-start window (line-beginning-position))))))
7242 ;;; Saving and restoring visibility
7244 (defun org-outline-overlay-data (&optional use-markers)
7245 "Return a list of the locations of all outline overlays.
7246 These are overlays with the `invisible' property value `outline'.
7247 The return value is a list of cons cells, with start and stop
7248 positions for each overlay.
7249 If USE-MARKERS is set, return the positions as markers."
7250 (let (beg end)
7251 (org-with-wide-buffer
7252 (delq nil
7253 (mapcar (lambda (o)
7254 (when (eq (overlay-get o 'invisible) 'outline)
7255 (setq beg (overlay-start o)
7256 end (overlay-end o))
7257 (and beg end (> end beg)
7258 (if use-markers
7259 (cons (copy-marker beg)
7260 (copy-marker end t))
7261 (cons beg end)))))
7262 (overlays-in (point-min) (point-max)))))))
7264 (defun org-set-outline-overlay-data (data)
7265 "Create visibility overlays for all positions in DATA.
7266 DATA should have been made by `org-outline-overlay-data'."
7267 (org-with-wide-buffer
7268 (outline-show-all)
7269 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7271 ;;; Folding of blocks
7273 (defvar-local org-hide-block-overlays nil
7274 "Overlays hiding blocks.")
7276 (defun org-block-map (function &optional start end)
7277 "Call FUNCTION at the head of all source blocks in the current buffer.
7278 Optional arguments START and END can be used to limit the range."
7279 (let ((start (or start (point-min)))
7280 (end (or end (point-max))))
7281 (save-excursion
7282 (goto-char start)
7283 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7284 (save-excursion
7285 (save-match-data
7286 (goto-char (match-beginning 0))
7287 (funcall function)))))))
7289 (defun org-hide-block-toggle-all ()
7290 "Toggle the visibility of all blocks in the current buffer."
7291 (org-block-map 'org-hide-block-toggle))
7293 (defun org-hide-block-all ()
7294 "Fold all blocks in the current buffer."
7295 (interactive)
7296 (org-show-block-all)
7297 (org-block-map 'org-hide-block-toggle-maybe))
7299 (defun org-show-block-all ()
7300 "Unfold all blocks in the current buffer."
7301 (interactive)
7302 (mapc #'delete-overlay org-hide-block-overlays)
7303 (setq org-hide-block-overlays nil))
7305 (defun org-hide-block-toggle-maybe ()
7306 "Toggle visibility of block at point.
7307 Unlike to `org-hide-block-toggle', this function does not throw
7308 an error. Return a non-nil value when toggling is successful."
7309 (interactive)
7310 (ignore-errors (org-hide-block-toggle)))
7312 (defun org-hide-block-toggle (&optional force)
7313 "Toggle the visibility of the current block.
7314 When optional argument FORCE is `off', make block visible. If it
7315 is non-nil, hide it unconditionally. Throw an error when not at
7316 a block. Return a non-nil value when toggling is successful."
7317 (interactive)
7318 (let ((element (org-element-at-point)))
7319 (unless (memq (org-element-type element)
7320 '(center-block comment-block dynamic-block example-block
7321 export-block quote-block special-block
7322 src-block verse-block))
7323 (user-error "Not at a block"))
7324 (let* ((start (save-excursion
7325 (goto-char (org-element-property :post-affiliated element))
7326 (line-end-position)))
7327 (end (save-excursion
7328 (goto-char (org-element-property :end element))
7329 (skip-chars-backward " \r\t\n")
7330 (line-end-position)))
7331 (overlays (overlays-at start)))
7332 (cond
7333 ;; Do nothing when not before or at the block opening line or
7334 ;; at the block closing line.
7335 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7336 ((and (not (eq force 'off))
7337 (not (memq t (mapcar
7338 (lambda (o)
7339 (eq (overlay-get o 'invisible) 'org-hide-block))
7340 overlays))))
7341 (let ((ov (make-overlay start end)))
7342 (overlay-put ov 'invisible 'org-hide-block)
7343 ;; Make the block accessible to `isearch'.
7344 (overlay-put
7345 ov 'isearch-open-invisible
7346 (lambda (ov)
7347 (when (memq ov org-hide-block-overlays)
7348 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7349 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7350 (delete-overlay ov))))
7351 (push ov org-hide-block-overlays)
7352 ;; When the block is hidden away, make sure point is left in
7353 ;; a visible part of the buffer.
7354 (when (> (line-beginning-position) start)
7355 (goto-char start)
7356 (beginning-of-line))
7357 ;; Signal successful toggling.
7359 ((or (not force) (eq force 'off))
7360 (dolist (ov overlays t)
7361 (when (memq ov org-hide-block-overlays)
7362 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7363 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7364 (delete-overlay ov))))))))
7366 ;; Remove overlays when changing major mode
7367 (add-hook 'org-mode-hook
7368 (lambda () (add-hook 'change-major-mode-hook
7369 'org-show-block-all 'append 'local)))
7371 ;;; Org-goto
7373 (defvar org-goto-window-configuration nil)
7374 (defvar org-goto-marker nil)
7375 (defvar org-goto-map)
7376 (defun org-goto-map ()
7377 "Set the keymap `org-goto'."
7378 (setq org-goto-map
7379 (let ((map (make-sparse-keymap)))
7380 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7381 mouse-drag-region universal-argument org-occur)))
7382 (dolist (cmd cmds)
7383 (substitute-key-definition cmd cmd map global-map)))
7384 (suppress-keymap map)
7385 (org-defkey map "\C-m" 'org-goto-ret)
7386 (org-defkey map [(return)] 'org-goto-ret)
7387 (org-defkey map [(left)] 'org-goto-left)
7388 (org-defkey map [(right)] 'org-goto-right)
7389 (org-defkey map [(control ?g)] 'org-goto-quit)
7390 (org-defkey map "\C-i" 'org-cycle)
7391 (org-defkey map [(tab)] 'org-cycle)
7392 (org-defkey map [(down)] 'outline-next-visible-heading)
7393 (org-defkey map [(up)] 'outline-previous-visible-heading)
7394 (if org-goto-auto-isearch
7395 (if (fboundp 'define-key-after)
7396 (define-key-after map [t] 'org-goto-local-auto-isearch)
7397 nil)
7398 (org-defkey map "q" 'org-goto-quit)
7399 (org-defkey map "n" 'outline-next-visible-heading)
7400 (org-defkey map "p" 'outline-previous-visible-heading)
7401 (org-defkey map "f" 'outline-forward-same-level)
7402 (org-defkey map "b" 'outline-backward-same-level)
7403 (org-defkey map "u" 'outline-up-heading))
7404 (org-defkey map "/" 'org-occur)
7405 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7406 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7407 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7408 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7409 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7410 map)))
7412 (defconst org-goto-help
7413 "Browse buffer copy, to find location or copy text.%s
7414 RET=jump to location C-g=quit and return to previous location
7415 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7417 (defvar org-goto-start-pos) ; dynamically scoped parameter
7419 (defun org-goto (&optional alternative-interface)
7420 "Look up a different location in the current file, keeping current visibility.
7422 When you want look-up or go to a different location in a
7423 document, the fastest way is often to fold the entire buffer and
7424 then dive into the tree. This method has the disadvantage, that
7425 the previous location will be folded, which may not be what you
7426 want.
7428 This command works around this by showing a copy of the current
7429 buffer in an indirect buffer, in overview mode. You can dive
7430 into the tree in that copy, use org-occur and incremental search
7431 to find a location. When pressing RET or `Q', the command
7432 returns to the original buffer in which the visibility is still
7433 unchanged. After RET it will also jump to the location selected
7434 in the indirect buffer and expose the headline hierarchy above.
7436 With a prefix argument, use the alternative interface: e.g., if
7437 `org-goto-interface' is `outline' use `outline-path-completion'."
7438 (interactive "P")
7439 (org-goto-map)
7440 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7441 (org-refile-use-outline-path t)
7442 (org-refile-target-verify-function nil)
7443 (interface
7444 (if (not alternative-interface)
7445 org-goto-interface
7446 (if (eq org-goto-interface 'outline)
7447 'outline-path-completion
7448 'outline)))
7449 (org-goto-start-pos (point))
7450 (selected-point
7451 (if (eq interface 'outline)
7452 (car (org-get-location (current-buffer) org-goto-help))
7453 (let ((pa (org-refile-get-location "Goto")))
7454 (org-refile-check-position pa)
7455 (nth 3 pa)))))
7456 (if selected-point
7457 (progn
7458 (org-mark-ring-push org-goto-start-pos)
7459 (goto-char selected-point)
7460 (when (or (org-invisible-p) (org-invisible-p2))
7461 (org-show-context 'org-goto)))
7462 (message "Quit"))))
7464 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7465 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7466 (defvar org-goto-local-auto-isearch-map) ; defined below
7468 (defun org-get-location (_buf help)
7469 "Let the user select a location in current buffer.
7470 This function uses a recursive edit. It returns the selected position
7471 or nil."
7472 (org-no-popups
7473 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7474 (isearch-hide-immediately nil)
7475 (isearch-search-fun-function
7476 (lambda () 'org-goto-local-search-headings))
7477 (org-goto-selected-point org-goto-exit-command))
7478 (save-excursion
7479 (save-window-excursion
7480 (delete-other-windows)
7481 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7482 (pop-to-buffer-same-window
7483 (condition-case nil
7484 (make-indirect-buffer (current-buffer) "*org-goto*")
7485 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7486 (with-output-to-temp-buffer "*Org Help*"
7487 (princ (format help (if org-goto-auto-isearch
7488 " Just type for auto-isearch."
7489 " n/p/f/b/u to navigate, q to quit."))))
7490 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7491 (setq buffer-read-only nil)
7492 (let ((org-startup-truncated t)
7493 (org-startup-folded nil)
7494 (org-startup-align-all-tables nil))
7495 (org-mode)
7496 (org-overview))
7497 (setq buffer-read-only t)
7498 (if (and (boundp 'org-goto-start-pos)
7499 (integer-or-marker-p org-goto-start-pos))
7500 (progn (goto-char org-goto-start-pos)
7501 (when (org-invisible-p)
7502 (org-show-set-visibility 'lineage)))
7503 (goto-char (point-min)))
7504 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7505 (message "Select location and press RET")
7506 (use-local-map org-goto-map)
7507 (recursive-edit)))
7508 (kill-buffer "*org-goto*")
7509 (cons org-goto-selected-point org-goto-exit-command))))
7511 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7512 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7513 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7514 (if (fboundp 'isearch-other-control-char)
7515 (progn
7516 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7517 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7518 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7519 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7520 (define-key org-goto-local-auto-isearch-map [return] nil))
7522 (defun org-goto-local-search-headings (string bound noerror)
7523 "Search and make sure that any matches are in headlines."
7524 (catch 'return
7525 (while (if isearch-forward
7526 (search-forward string bound noerror)
7527 (search-backward string bound noerror))
7528 (when (save-match-data
7529 (and (save-excursion
7530 (beginning-of-line)
7531 (looking-at org-complex-heading-regexp))
7532 (or (not (match-beginning 5))
7533 (< (point) (match-beginning 5)))))
7534 (throw 'return (point))))))
7536 (defun org-goto-local-auto-isearch ()
7537 "Start isearch."
7538 (interactive)
7539 (goto-char (point-min))
7540 (let ((keys (this-command-keys)))
7541 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7542 (isearch-mode t)
7543 (isearch-process-search-char (string-to-char keys)))))
7545 (defun org-goto-ret (&optional _arg)
7546 "Finish `org-goto' by going to the new location."
7547 (interactive "P")
7548 (setq org-goto-selected-point (point))
7549 (setq org-goto-exit-command 'return)
7550 (throw 'exit nil))
7552 (defun org-goto-left ()
7553 "Finish `org-goto' by going to the new location."
7554 (interactive)
7555 (if (org-at-heading-p)
7556 (progn
7557 (beginning-of-line 1)
7558 (setq org-goto-selected-point (point)
7559 org-goto-exit-command 'left)
7560 (throw 'exit nil))
7561 (user-error "Not on a heading")))
7563 (defun org-goto-right ()
7564 "Finish `org-goto' by going to the new location."
7565 (interactive)
7566 (if (org-at-heading-p)
7567 (progn
7568 (setq org-goto-selected-point (point)
7569 org-goto-exit-command 'right)
7570 (throw 'exit nil))
7571 (user-error "Not on a heading")))
7573 (defun org-goto-quit ()
7574 "Finish `org-goto' without cursor motion."
7575 (interactive)
7576 (setq org-goto-selected-point nil)
7577 (setq org-goto-exit-command 'quit)
7578 (throw 'exit nil))
7580 ;;; Indirect buffer display of subtrees
7582 (defvar org-indirect-dedicated-frame nil
7583 "This is the frame being used for indirect tree display.")
7584 (defvar org-last-indirect-buffer nil)
7586 (defun org-tree-to-indirect-buffer (&optional arg)
7587 "Create indirect buffer and narrow it to current subtree.
7589 With a numerical prefix ARG, go up to this level and then take that tree.
7590 If ARG is negative, go up that many levels.
7592 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7593 indirect buffer previously made with this command, to avoid proliferation of
7594 indirect buffers. However, when you call the command with a \
7595 `\\[universal-argument]' prefix, or
7596 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7597 so that you can work with several indirect buffers at the same time. If
7598 `org-indirect-buffer-display' is `dedicated-frame', the \
7599 `\\[universal-argument]' prefix also
7600 requests that a new frame be made for the new buffer, so that the dedicated
7601 frame is not changed."
7602 (interactive "P")
7603 (let ((cbuf (current-buffer))
7604 (cwin (selected-window))
7605 (pos (point))
7606 beg end level heading ibuf)
7607 (save-excursion
7608 (org-back-to-heading t)
7609 (when (numberp arg)
7610 (setq level (org-outline-level))
7611 (when (< arg 0) (setq arg (+ level arg)))
7612 (while (> (setq level (org-outline-level)) arg)
7613 (org-up-heading-safe)))
7614 (setq beg (point)
7615 heading (org-get-heading 'no-tags))
7616 (org-end-of-subtree t t)
7617 (when (org-at-heading-p) (backward-char 1))
7618 (setq end (point)))
7619 (when (and (buffer-live-p org-last-indirect-buffer)
7620 (not (eq org-indirect-buffer-display 'new-frame))
7621 (not arg))
7622 (kill-buffer org-last-indirect-buffer))
7623 (setq ibuf (org-get-indirect-buffer cbuf heading)
7624 org-last-indirect-buffer ibuf)
7625 (cond
7626 ((or (eq org-indirect-buffer-display 'new-frame)
7627 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7628 (select-frame (make-frame))
7629 (delete-other-windows)
7630 (pop-to-buffer-same-window ibuf)
7631 (org-set-frame-title heading))
7632 ((eq org-indirect-buffer-display 'dedicated-frame)
7633 (raise-frame
7634 (select-frame (or (and org-indirect-dedicated-frame
7635 (frame-live-p org-indirect-dedicated-frame)
7636 org-indirect-dedicated-frame)
7637 (setq org-indirect-dedicated-frame (make-frame)))))
7638 (delete-other-windows)
7639 (pop-to-buffer-same-window ibuf)
7640 (org-set-frame-title (concat "Indirect: " heading)))
7641 ((eq org-indirect-buffer-display 'current-window)
7642 (pop-to-buffer-same-window ibuf))
7643 ((eq org-indirect-buffer-display 'other-window)
7644 (pop-to-buffer ibuf))
7645 (t (error "Invalid value")))
7646 (narrow-to-region beg end)
7647 (outline-show-all)
7648 (goto-char pos)
7649 (run-hook-with-args 'org-cycle-hook 'all)
7650 (and (window-live-p cwin) (select-window cwin))))
7652 (defun org-get-indirect-buffer (&optional buffer heading)
7653 (setq buffer (or buffer (current-buffer)))
7654 (let ((n 1) (base (buffer-name buffer)) bname)
7655 (while (buffer-live-p
7656 (get-buffer
7657 (setq bname
7658 (concat base "-"
7659 (if heading (concat heading "-" (number-to-string n))
7660 (number-to-string n))))))
7661 (setq n (1+ n)))
7662 (condition-case nil
7663 (make-indirect-buffer buffer bname 'clone)
7664 (error (make-indirect-buffer buffer bname)))))
7666 (defun org-set-frame-title (title)
7667 "Set the title of the current frame to the string TITLE."
7668 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7670 ;;;; Structure editing
7672 ;;; Inserting headlines
7674 (defun org--line-empty-p (n)
7675 "Is the Nth next line empty?
7677 Counts the current line as N = 1 and the previous line as N = 0;
7678 see `beginning-of-line'."
7679 (save-excursion
7680 (and (not (bobp))
7681 (or (beginning-of-line n) t)
7682 (save-match-data
7683 (looking-at "[ \t]*$")))))
7685 (defun org-previous-line-empty-p ()
7686 "Is the previous line a blank line?
7687 When NEXT is non-nil, check the next line instead."
7688 (org--line-empty-p 0))
7690 (defun org-next-line-empty-p ()
7691 "Is the previous line a blank line?
7692 When NEXT is non-nil, check the next line instead."
7693 (org--line-empty-p 2))
7695 (defun org--blank-before-heading-p (&optional parent)
7696 "Non-nil when an empty line should precede a new heading here.
7697 When optional argument PARENT is non-nil, consider parent
7698 headline instead of current one."
7699 (pcase (assq 'heading org-blank-before-new-entry)
7700 (`(heading . auto)
7701 (save-excursion
7702 (org-with-limited-levels
7703 (unless (and (org-before-first-heading-p)
7704 (not (outline-next-heading)))
7705 (org-back-to-heading t)
7706 (when parent (org-up-heading-safe))
7707 (cond ((not (bobp))
7708 (org-previous-line-empty-p))
7709 ((outline-next-heading)
7710 (org-previous-line-empty-p))
7711 ;; Ignore trailing spaces on last buffer line.
7712 ((progn (skip-chars-backward " \t") (bolp))
7713 (org-previous-line-empty-p))
7714 (t nil))))))
7715 (`(heading . ,value) value)
7716 (_ nil)))
7718 (defun org-insert-heading (&optional arg invisible-ok top)
7719 "Insert a new heading or an item with the same depth at point.
7721 If point is at the beginning of a heading, insert a new heading
7722 or a new headline above the current one. When at the beginning
7723 of a regular line of text, turn it into a heading.
7725 If point is in the middle of a line, split it and create a new
7726 headline with the text in the current line after point (see
7727 `org-M-RET-may-split-line' on how to modify this behavior). As
7728 a special case, on a headline, splitting can only happen on the
7729 title itself. E.g., this excludes breaking stars or tags.
7731 With a `\\[universal-argument]' prefix, set \
7732 `org-insert-heading-respect-content' to
7733 a non-nil value for the duration of the command. This forces the
7734 insertion of a heading after the current subtree, independently
7735 on the location of point.
7737 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7738 insert the heading at the end of the tree
7739 above the current heading. For example, if point is within a
7740 2nd-level heading, then it will insert a 2nd-level heading at
7741 the end of the 1st-level parent subtree.
7743 When INVISIBLE-OK is set, stop at invisible headlines when going
7744 back. This is important for non-interactive uses of the
7745 command.
7747 When optional argument TOP is non-nil, insert a level 1 heading,
7748 unconditionally."
7749 (interactive "P")
7750 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7751 (level (org-current-level))
7752 (stars (make-string (if (and level (not top)) level 1) ?*)))
7753 (cond
7754 ((or org-insert-heading-respect-content
7755 (member arg '((4) (16)))
7756 (and (not invisible-ok)
7757 (invisible-p (max (1- (point)) (point-min)))))
7758 ;; Position point at the location of insertion.
7759 (if (not level) ;before first headline
7760 (org-with-limited-levels (outline-next-heading))
7761 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7762 ;; is nil.
7763 (org-with-limited-levels (org-back-to-heading invisible-ok))
7764 (cond ((equal arg '(16))
7765 (org-up-heading-safe)
7766 (org-end-of-subtree t t))
7768 (org-end-of-subtree t t))))
7769 (unless (bolp) (insert "\n")) ;ensure final newline
7770 (unless (and blank? (org-previous-line-empty-p))
7771 (org-N-empty-lines-before-current (if blank? 1 0)))
7772 (insert stars " \n")
7773 (forward-char -1))
7774 ;; At a headline...
7775 ((org-at-heading-p)
7776 (cond ((bolp)
7777 (when blank? (save-excursion (insert "\n")))
7778 (save-excursion (insert stars " \n"))
7779 (unless (and blank? (org-previous-line-empty-p))
7780 (org-N-empty-lines-before-current (if blank? 1 0)))
7781 (end-of-line))
7782 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7783 (org-match-line org-complex-heading-regexp)
7784 (org-pos-in-match-range (point) 4))
7785 ;; Grab the text that should moved to the new headline.
7786 ;; Preserve tags.
7787 (let ((split (delete-and-extract-region (point) (match-end 4))))
7788 (if (looking-at "[ \t]*$") (replace-match "")
7789 (org-set-tags nil t))
7790 (end-of-line)
7791 (when blank? (insert "\n"))
7792 (insert "\n" stars " ")
7793 (when (org-string-nw-p split) (insert split))
7794 (when (eobp) (save-excursion (insert "\n")))))
7796 (end-of-line)
7797 (when blank? (insert "\n"))
7798 (insert "\n" stars " ")
7799 (when (eobp) (save-excursion (insert "\n"))))))
7800 ;; On regular text, turn line into a headline or split, if
7801 ;; appropriate.
7802 ((bolp)
7803 (insert stars " ")
7804 (unless (and blank? (org-previous-line-empty-p))
7805 (org-N-empty-lines-before-current (if blank? 1 0))))
7807 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7808 (end-of-line))
7809 (insert "\n" stars " ")
7810 (unless (and blank? (org-previous-line-empty-p))
7811 (org-N-empty-lines-before-current (if blank? 1 0))))))
7812 (run-hooks 'org-insert-heading-hook))
7814 (defun org-N-empty-lines-before-current (n)
7815 "Make the number of empty lines before current exactly N.
7816 So this will delete or add empty lines."
7817 (let ((column (current-column)))
7818 (beginning-of-line)
7819 (unless (bobp)
7820 (let ((start (save-excursion
7821 (skip-chars-backward " \r\t\n")
7822 (line-end-position))))
7823 (delete-region start (line-end-position 0))))
7824 (insert (make-string n ?\n))
7825 (move-to-column column)))
7827 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7828 "Return the heading of the current entry, without the stars.
7829 When NO-TAGS is non-nil, don't include tags.
7830 When NO-TODO is non-nil, don't include TODO keywords.
7831 When NO-PRIORITY is non-nil, don't include priority cookie.
7832 When NO-COMMENT is non-nil, don't include COMMENT string."
7833 (save-excursion
7834 (org-back-to-heading t)
7835 (let ((case-fold-search nil))
7836 (looking-at org-complex-heading-regexp)
7837 (let ((todo (and (not no-todo) (match-string 2)))
7838 (priority (and (not no-priority) (match-string 3)))
7839 (headline (pcase (match-string 4)
7840 (`nil "")
7841 ((and (guard no-comment) h)
7842 (replace-regexp-in-string
7843 (eval-when-compile
7844 (format "\\`%s[ \t]+" org-comment-string))
7845 "" h))
7846 (h h)))
7847 (tags (and (not no-tags) (match-string 5))))
7848 (mapconcat #'identity
7849 (delq nil (list todo priority headline tags))
7850 " ")))))
7852 (defvar orgstruct-mode) ; defined below
7854 (defun org-heading-components ()
7855 "Return the components of the current heading.
7856 This is a list with the following elements:
7857 - the level as an integer
7858 - the reduced level, different if `org-odd-levels-only' is set.
7859 - the TODO keyword, or nil
7860 - the priority character, like ?A, or nil if no priority is given
7861 - the headline text itself, or the tags string if no headline text
7862 - the tags string, or nil."
7863 (save-excursion
7864 (org-back-to-heading t)
7865 (when (let (case-fold-search)
7866 (looking-at
7867 (if orgstruct-mode
7868 org-heading-regexp
7869 org-complex-heading-regexp)))
7870 (if orgstruct-mode
7871 (list (length (match-string 1))
7872 (org-reduced-level (length (match-string 1)))
7875 (match-string 2)
7876 nil)
7877 (list (length (match-string 1))
7878 (org-reduced-level (length (match-string 1)))
7879 (match-string-no-properties 2)
7880 (and (match-end 3) (aref (match-string 3) 2))
7881 (match-string-no-properties 4)
7882 (match-string-no-properties 5))))))
7884 (defun org-get-entry ()
7885 "Get the entry text, after heading, entire subtree."
7886 (save-excursion
7887 (org-back-to-heading t)
7888 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7890 (defun org-edit-headline (&optional heading)
7891 "Edit the current headline.
7892 Set it to HEADING when provided."
7893 (interactive)
7894 (org-with-wide-buffer
7895 (org-back-to-heading t)
7896 (let ((case-fold-search nil))
7897 (when (looking-at org-complex-heading-regexp)
7898 (let* ((old (match-string-no-properties 4))
7899 (new (save-match-data
7900 (org-trim (or heading (read-string "Edit: " old))))))
7901 (unless (equal old new)
7902 (if old (replace-match new t t nil 4)
7903 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7904 (insert " " new))
7905 (org-set-tags nil t)
7906 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7908 (defun org-insert-heading-after-current ()
7909 "Insert a new heading with same level as current, after current subtree."
7910 (interactive)
7911 (org-back-to-heading)
7912 (org-insert-heading)
7913 (org-move-subtree-down)
7914 (end-of-line 1))
7916 (defun org-insert-heading-respect-content (&optional invisible-ok)
7917 "Insert heading with `org-insert-heading-respect-content' set to t."
7918 (interactive)
7919 (org-insert-heading '(4) invisible-ok))
7921 (defun org-insert-todo-heading-respect-content (&optional force-state)
7922 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7923 (interactive)
7924 (org-insert-todo-heading force-state '(4)))
7926 (defun org-insert-todo-heading (arg &optional force-heading)
7927 "Insert a new heading with the same level and TODO state as current heading.
7929 If the heading has no TODO state, or if the state is DONE, use
7930 the first state (TODO by default). Also with one prefix arg,
7931 force first state. With two prefix args, force inserting at the
7932 end of the parent subtree.
7934 When called at a plain list item, insert a new item with an
7935 unchecked check box."
7936 (interactive "P")
7937 (when (or force-heading (not (org-insert-item 'checkbox)))
7938 (org-insert-heading (or (and (equal arg '(16)) '(16))
7939 force-heading))
7940 (save-excursion
7941 (org-back-to-heading)
7942 (outline-previous-heading)
7943 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7944 (let* ((new-mark-x
7945 (if (or (equal arg '(4))
7946 (not (match-beginning 2))
7947 (member (match-string 2) org-done-keywords))
7948 (car org-todo-keywords-1)
7949 (match-string 2)))
7950 (new-mark
7952 (run-hook-with-args-until-success
7953 'org-todo-get-default-hook new-mark-x nil)
7954 new-mark-x)))
7955 (beginning-of-line 1)
7956 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7957 (if org-treat-insert-todo-heading-as-state-change
7958 (org-todo new-mark)
7959 (insert new-mark " "))))
7960 (when org-provide-todo-statistics
7961 (org-update-parent-todo-statistics))))
7963 (defun org-insert-subheading (arg)
7964 "Insert a new subheading and demote it.
7965 Works for outline headings and for plain lists alike."
7966 (interactive "P")
7967 (org-insert-heading arg)
7968 (cond
7969 ((org-at-heading-p) (org-do-demote))
7970 ((org-at-item-p) (org-indent-item))))
7972 (defun org-insert-todo-subheading (arg)
7973 "Insert a new subheading with TODO keyword or checkbox and demote it.
7974 Works for outline headings and for plain lists alike."
7975 (interactive "P")
7976 (org-insert-todo-heading arg)
7977 (cond
7978 ((org-at-heading-p) (org-do-demote))
7979 ((org-at-item-p) (org-indent-item))))
7981 ;;; Promotion and Demotion
7983 (defvar org-after-demote-entry-hook nil
7984 "Hook run after an entry has been demoted.
7985 The cursor will be at the beginning of the entry.
7986 When a subtree is being demoted, the hook will be called for each node.")
7988 (defvar org-after-promote-entry-hook nil
7989 "Hook run after an entry has been promoted.
7990 The cursor will be at the beginning of the entry.
7991 When a subtree is being promoted, the hook will be called for each node.")
7993 (defun org-promote-subtree ()
7994 "Promote the entire subtree.
7995 See also `org-promote'."
7996 (interactive)
7997 (save-excursion
7998 (org-with-limited-levels (org-map-tree 'org-promote)))
7999 (org-fix-position-after-promote))
8001 (defun org-demote-subtree ()
8002 "Demote the entire subtree.
8003 See `org-demote' and `org-promote'."
8004 (interactive)
8005 (save-excursion
8006 (org-with-limited-levels (org-map-tree 'org-demote)))
8007 (org-fix-position-after-promote))
8009 (defun org-do-promote ()
8010 "Promote the current heading higher up the tree.
8011 If the region is active in `transient-mark-mode', promote all
8012 headings in the region."
8013 (interactive)
8014 (save-excursion
8015 (if (org-region-active-p)
8016 (org-map-region 'org-promote (region-beginning) (region-end))
8017 (org-promote)))
8018 (org-fix-position-after-promote))
8020 (defun org-do-demote ()
8021 "Demote the current heading lower down the tree.
8022 If the region is active in `transient-mark-mode', demote all
8023 headings in the region."
8024 (interactive)
8025 (save-excursion
8026 (if (org-region-active-p)
8027 (org-map-region 'org-demote (region-beginning) (region-end))
8028 (org-demote)))
8029 (org-fix-position-after-promote))
8031 (defun org-fix-position-after-promote ()
8032 "Fix cursor position and indentation after demoting/promoting."
8033 (let ((pos (point)))
8034 (when (save-excursion
8035 (beginning-of-line)
8036 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8037 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8038 (cond ((eobp) (insert " "))
8039 ((eolp) (insert " "))
8040 ((equal (char-after) ?\s) (forward-char 1))))))
8042 (defun org-current-level ()
8043 "Return the level of the current entry, or nil if before the first headline.
8044 The level is the number of stars at the beginning of the
8045 headline. Use `org-reduced-level' to remove the effect of
8046 `org-odd-levels'. Unlike to `org-outline-level', this function
8047 ignores inlinetasks."
8048 (let ((level (org-with-limited-levels (org-outline-level))))
8049 (and (> level 0) level)))
8051 (defun org-get-previous-line-level ()
8052 "Return the outline depth of the last headline before the current line.
8053 Returns 0 for the first headline in the buffer, and nil if before the
8054 first headline."
8055 (and (org-current-level)
8056 (or (and (/= (line-beginning-position) (point-min))
8057 (save-excursion (beginning-of-line 0) (org-current-level)))
8058 0)))
8060 (defun org-reduced-level (l)
8061 "Compute the effective level of a heading.
8062 This takes into account the setting of `org-odd-levels-only'."
8063 (cond
8064 ((zerop l) 0)
8065 (org-odd-levels-only (1+ (floor (/ l 2))))
8066 (t l)))
8068 (defun org-level-increment ()
8069 "Return the number of stars that will be added or removed at a
8070 time to headlines when structure editing, based on the value of
8071 `org-odd-levels-only'."
8072 (if org-odd-levels-only 2 1))
8074 (defun org-get-valid-level (level &optional change)
8075 "Rectify a level change under the influence of `org-odd-levels-only'.
8076 LEVEL is a current level, CHANGE is by how much the level should
8077 be modified. Even if CHANGE is nil, LEVEL may be returned
8078 modified because even level numbers will become the next higher
8079 odd number. Returns values greater than 0."
8080 (if org-odd-levels-only
8081 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8082 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8083 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8084 (max 1 (+ level (or change 0)))))
8086 (defun org-promote ()
8087 "Promote the current heading higher up the tree."
8088 (org-with-wide-buffer
8089 (org-back-to-heading t)
8090 (let* ((after-change-functions (remq 'flyspell-after-change-function
8091 after-change-functions))
8092 (level (save-match-data (funcall outline-level)))
8093 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8094 (diff (abs (- level (length up-head) -1))))
8095 (cond
8096 ((and (= level 1) org-allow-promoting-top-level-subtree)
8097 (replace-match "# " nil t))
8098 ((= level 1)
8099 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8100 (t (replace-match up-head nil t)))
8101 (unless (= level 1)
8102 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8103 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8104 (run-hooks 'org-after-promote-entry-hook))))
8106 (defun org-demote ()
8107 "Demote the current heading lower down the tree."
8108 (org-with-wide-buffer
8109 (org-back-to-heading t)
8110 (let* ((after-change-functions (remq 'flyspell-after-change-function
8111 after-change-functions))
8112 (level (save-match-data (funcall outline-level)))
8113 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8114 (diff (abs (- level (length down-head) -1))))
8115 (replace-match down-head nil t)
8116 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8117 (when org-adapt-indentation (org-fixup-indentation diff))
8118 (run-hooks 'org-after-demote-entry-hook))))
8120 (defun org-cycle-level ()
8121 "Cycle the level of an empty headline through possible states.
8122 This goes first to child, then to parent, level, then up the hierarchy.
8123 After top level, it switches back to sibling level."
8124 (interactive)
8125 (let ((org-adapt-indentation nil))
8126 (when (org-point-at-end-of-empty-headline)
8127 (setq this-command 'org-cycle-level) ; Only needed for caching
8128 (let ((cur-level (org-current-level))
8129 (prev-level (org-get-previous-line-level)))
8130 (cond
8131 ;; If first headline in file, promote to top-level.
8132 ((= prev-level 0)
8133 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8134 do (org-do-promote)))
8135 ;; If same level as prev, demote one.
8136 ((= prev-level cur-level)
8137 (org-do-demote))
8138 ;; If parent is top-level, promote to top level if not already.
8139 ((= prev-level 1)
8140 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8141 do (org-do-promote)))
8142 ;; If top-level, return to prev-level.
8143 ((= cur-level 1)
8144 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8145 do (org-do-demote)))
8146 ;; If less than prev-level, promote one.
8147 ((< cur-level prev-level)
8148 (org-do-promote))
8149 ;; If deeper than prev-level, promote until higher than
8150 ;; prev-level.
8151 ((> cur-level prev-level)
8152 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8153 do (org-do-promote))))
8154 t))))
8156 (defun org-map-tree (fun)
8157 "Call FUN for every heading underneath the current one."
8158 (org-back-to-heading t)
8159 (let ((level (funcall outline-level)))
8160 (save-excursion
8161 (funcall fun)
8162 (while (and (progn
8163 (outline-next-heading)
8164 (> (funcall outline-level) level))
8165 (not (eobp)))
8166 (funcall fun)))))
8168 (defun org-map-region (fun beg end)
8169 "Call FUN for every heading between BEG and END."
8170 (let ((org-ignore-region t))
8171 (save-excursion
8172 (setq end (copy-marker end))
8173 (goto-char beg)
8174 (when (and (re-search-forward org-outline-regexp-bol nil t)
8175 (< (point) end))
8176 (funcall fun))
8177 (while (and (progn
8178 (outline-next-heading)
8179 (< (point) end))
8180 (not (eobp)))
8181 (funcall fun)))))
8183 (defun org-fixup-indentation (diff)
8184 "Change the indentation in the current entry by DIFF.
8186 DIFF is an integer. Indentation is done according to the
8187 following rules:
8189 - Planning information and property drawers are always indented
8190 according to the new level of the headline;
8192 - Footnote definitions and their contents are ignored;
8194 - Inlinetasks' boundaries are not shifted;
8196 - Empty lines are ignored;
8198 - Other lines' indentation are shifted by DIFF columns, unless
8199 it would introduce a structural change in the document, in
8200 which case no shifting is done at all.
8202 Assume point is at a heading or an inlinetask beginning."
8203 (org-with-wide-buffer
8204 (narrow-to-region (line-beginning-position)
8205 (save-excursion
8206 (if (org-with-limited-levels (org-at-heading-p))
8207 (org-with-limited-levels (outline-next-heading))
8208 (org-inlinetask-goto-end))
8209 (point)))
8210 (forward-line)
8211 ;; Indent properly planning info and property drawer.
8212 (when (looking-at-p org-planning-line-re)
8213 (org-indent-line)
8214 (forward-line))
8215 (when (looking-at org-property-drawer-re)
8216 (goto-char (match-end 0))
8217 (forward-line)
8218 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8219 (catch 'no-shift
8220 (when (zerop diff) (throw 'no-shift nil))
8221 ;; If DIFF is negative, first check if a shift is possible at all
8222 ;; (e.g., it doesn't break structure). This can only happen if
8223 ;; some contents are not properly indented.
8224 (let ((case-fold-search t))
8225 (when (< diff 0)
8226 (let ((diff (- diff))
8227 (forbidden-re (concat org-outline-regexp
8228 "\\|"
8229 (substring org-footnote-definition-re 1))))
8230 (save-excursion
8231 (while (not (eobp))
8232 (cond
8233 ((looking-at-p "[ \t]*$") (forward-line))
8234 ((and (looking-at-p org-footnote-definition-re)
8235 (let ((e (org-element-at-point)))
8236 (and (eq (org-element-type e) 'footnote-definition)
8237 (goto-char (org-element-property :end e))))))
8238 ((looking-at-p org-outline-regexp) (forward-line))
8239 ;; Give up if shifting would move before column 0 or
8240 ;; if it would introduce a headline or a footnote
8241 ;; definition.
8243 (skip-chars-forward " \t")
8244 (let ((ind (current-column)))
8245 (when (or (< ind diff)
8246 (and (= ind diff) (looking-at-p forbidden-re)))
8247 (throw 'no-shift nil)))
8248 ;; Ignore contents of example blocks and source
8249 ;; blocks if their indentation is meant to be
8250 ;; preserved. Jump to block's closing line.
8251 (beginning-of-line)
8252 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8253 (let ((e (org-element-at-point)))
8254 (and (memq (org-element-type e)
8255 '(example-block src-block))
8256 (or org-src-preserve-indentation
8257 (org-element-property :preserve-indent e))
8258 (goto-char (org-element-property :end e))
8259 (progn (skip-chars-backward " \r\t\n")
8260 (beginning-of-line)
8261 t))))
8262 (forward-line))))))))
8263 ;; Shift lines but footnote definitions, inlinetasks boundaries
8264 ;; by DIFF. Also skip contents of source or example blocks
8265 ;; when indentation is meant to be preserved.
8266 (while (not (eobp))
8267 (cond
8268 ((and (looking-at-p org-footnote-definition-re)
8269 (let ((e (org-element-at-point)))
8270 (and (eq (org-element-type e) 'footnote-definition)
8271 (goto-char (org-element-property :end e))))))
8272 ((looking-at-p org-outline-regexp) (forward-line))
8273 ((looking-at-p "[ \t]*$") (forward-line))
8275 (indent-line-to (+ (org-get-indentation) diff))
8276 (beginning-of-line)
8277 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8278 (let ((e (org-element-at-point)))
8279 (and (memq (org-element-type e)
8280 '(example-block src-block))
8281 (or org-src-preserve-indentation
8282 (org-element-property :preserve-indent e))
8283 (goto-char (org-element-property :end e))
8284 (progn (skip-chars-backward " \r\t\n")
8285 (beginning-of-line)
8286 t))))
8287 (forward-line)))))))))
8289 (defun org-convert-to-odd-levels ()
8290 "Convert an Org file with all levels allowed to one with odd levels.
8291 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8292 level 5 etc."
8293 (interactive)
8294 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8295 (let ((outline-level 'org-outline-level)
8296 (org-odd-levels-only nil) n)
8297 (save-excursion
8298 (goto-char (point-min))
8299 (while (re-search-forward "^\\*\\*+ " nil t)
8300 (setq n (- (length (match-string 0)) 2))
8301 (while (>= (setq n (1- n)) 0)
8302 (org-demote))
8303 (end-of-line 1))))))
8305 (defun org-convert-to-oddeven-levels ()
8306 "Convert an Org file with only odd levels to one with odd/even levels.
8307 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8308 file contains a section with an even level, conversion would
8309 destroy the structure of the file. An error is signaled in this
8310 case."
8311 (interactive)
8312 (goto-char (point-min))
8313 ;; First check if there are no even levels
8314 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8315 (org-show-set-visibility 'canonical)
8316 (error "Not all levels are odd in this file. Conversion not possible"))
8317 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8318 (let ((outline-regexp org-outline-regexp)
8319 (outline-level 'org-outline-level)
8320 (org-odd-levels-only nil) n)
8321 (save-excursion
8322 (goto-char (point-min))
8323 (while (re-search-forward "^\\*\\*+ " nil t)
8324 (setq n (/ (1- (length (match-string 0))) 2))
8325 (while (>= (setq n (1- n)) 0)
8326 (org-promote))
8327 (end-of-line 1))))))
8329 (defun org-tr-level (n)
8330 "Make N odd if required."
8331 (if org-odd-levels-only (1+ (/ n 2)) n))
8333 ;;; Vertical tree motion, cutting and pasting of subtrees
8335 (defun org-move-subtree-up (&optional arg)
8336 "Move the current subtree up past ARG headlines of the same level."
8337 (interactive "p")
8338 (org-move-subtree-down (- (prefix-numeric-value arg))))
8340 (defun org-move-subtree-down (&optional arg)
8341 "Move the current subtree down past ARG headlines of the same level."
8342 (interactive "p")
8343 (setq arg (prefix-numeric-value arg))
8344 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8345 'org-get-last-sibling))
8346 (ins-point (make-marker))
8347 (cnt (abs arg))
8348 (col (current-column))
8349 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8350 ;; Select the tree
8351 (org-back-to-heading)
8352 (setq beg0 (point))
8353 (save-excursion
8354 (setq ne-beg (org-back-over-empty-lines))
8355 (setq beg (point)))
8356 (save-match-data
8357 (save-excursion (outline-end-of-heading)
8358 (setq folded (org-invisible-p)))
8359 (progn (org-end-of-subtree nil t)
8360 (unless (eobp) (backward-char))))
8361 (outline-next-heading)
8362 (setq ne-end (org-back-over-empty-lines))
8363 (setq end (point))
8364 (goto-char beg0)
8365 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8366 ;; include less whitespace
8367 (save-excursion
8368 (goto-char beg)
8369 (forward-line (- ne-beg ne-end))
8370 (setq beg (point))))
8371 ;; Find insertion point, with error handling
8372 (while (> cnt 0)
8373 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8374 (progn (goto-char beg0)
8375 (user-error "Cannot move past superior level or buffer limit")))
8376 (setq cnt (1- cnt)))
8377 (when (> arg 0)
8378 ;; Moving forward - still need to move over subtree
8379 (org-end-of-subtree t t)
8380 (save-excursion
8381 (org-back-over-empty-lines)
8382 (or (bolp) (newline))))
8383 (setq ne-ins (org-back-over-empty-lines))
8384 (move-marker ins-point (point))
8385 (setq txt (buffer-substring beg end))
8386 (org-save-markers-in-region beg end)
8387 (delete-region beg end)
8388 (org-remove-empty-overlays-at beg)
8389 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8390 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8391 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8392 (let ((bbb (point)))
8393 (insert-before-markers txt)
8394 (org-reinstall-markers-in-region bbb)
8395 (move-marker ins-point bbb))
8396 (or (bolp) (insert "\n"))
8397 (setq ins-end (point))
8398 (goto-char ins-point)
8399 (org-skip-whitespace)
8400 (when (and (< arg 0)
8401 (org-first-sibling-p)
8402 (> ne-ins ne-beg))
8403 ;; Move whitespace back to beginning
8404 (save-excursion
8405 (goto-char ins-end)
8406 (let ((kill-whole-line t))
8407 (kill-line (- ne-ins ne-beg)) (point)))
8408 (insert (make-string (- ne-ins ne-beg) ?\n)))
8409 (move-marker ins-point nil)
8410 (if folded
8411 (outline-hide-subtree)
8412 (org-show-entry)
8413 (org-show-children)
8414 (org-cycle-hide-drawers 'children))
8415 (org-clean-visibility-after-subtree-move)
8416 ;; move back to the initial column we were at
8417 (move-to-column col)))
8419 (defvar org-subtree-clip ""
8420 "Clipboard for cut and paste of subtrees.
8421 This is actually only a copy of the kill, because we use the normal kill
8422 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8424 (defvar org-subtree-clip-folded nil
8425 "Was the last copied subtree folded?
8426 This is used to fold the tree back after pasting.")
8428 (defun org-cut-subtree (&optional n)
8429 "Cut the current subtree into the clipboard.
8430 With prefix arg N, cut this many sequential subtrees.
8431 This is a short-hand for marking the subtree and then cutting it."
8432 (interactive "p")
8433 (org-copy-subtree n 'cut))
8435 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8436 "Copy the current subtree it in the clipboard.
8437 With prefix arg N, copy this many sequential subtrees.
8438 This is a short-hand for marking the subtree and then copying it.
8439 If CUT is non-nil, actually cut the subtree.
8440 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8441 of some markers in the region, even if CUT is non-nil. This is
8442 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8443 (interactive "p")
8444 (let (beg end folded (beg0 (point)))
8445 (if (called-interactively-p 'any)
8446 (org-back-to-heading nil) ; take what looks like a subtree
8447 (org-back-to-heading t)) ; take what is really there
8448 (setq beg (point))
8449 (skip-chars-forward " \t\r\n")
8450 (save-match-data
8451 (if nosubtrees
8452 (outline-next-heading)
8453 (save-excursion (outline-end-of-heading)
8454 (setq folded (org-invisible-p)))
8455 (ignore-errors (org-forward-heading-same-level (1- n) t))
8456 (org-end-of-subtree t t)))
8457 ;; Include the end of an inlinetask
8458 (when (and (featurep 'org-inlinetask)
8459 (looking-at-p (concat (org-inlinetask-outline-regexp)
8460 "END[ \t]*$")))
8461 (end-of-line))
8462 (setq end (point))
8463 (goto-char beg0)
8464 (when (> end beg)
8465 (setq org-subtree-clip-folded folded)
8466 (when (or cut force-store-markers)
8467 (org-save-markers-in-region beg end))
8468 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8469 (setq org-subtree-clip (current-kill 0))
8470 (message "%s: Subtree(s) with %d characters"
8471 (if cut "Cut" "Copied")
8472 (length org-subtree-clip)))))
8474 (defun org-paste-subtree (&optional level tree for-yank remove)
8475 "Paste the clipboard as a subtree, with modification of headline level.
8476 The entire subtree is promoted or demoted in order to match a new headline
8477 level.
8479 If the cursor is at the beginning of a headline, the same level as
8480 that headline is used to paste the tree.
8482 If not, the new level is derived from the *visible* headings
8483 before and after the insertion point, and taken to be the inferior headline
8484 level of the two. So if the previous visible heading is level 3 and the
8485 next is level 4 (or vice versa), level 4 will be used for insertion.
8486 This makes sure that the subtree remains an independent subtree and does
8487 not swallow low level entries.
8489 You can also force a different level, either by using a numeric prefix
8490 argument, or by inserting the heading marker by hand. For example, if the
8491 cursor is after \"*****\", then the tree will be shifted to level 5.
8493 If optional TREE is given, use this text instead of the kill ring.
8495 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8496 move back over whitespace before inserting, and move point to the end of
8497 the inserted text when done.
8499 When REMOVE is non-nil, remove the subtree from the clipboard."
8500 (interactive "P")
8501 (setq tree (or tree (and kill-ring (current-kill 0))))
8502 (unless (org-kill-is-subtree-p tree)
8503 (user-error "%s"
8504 (substitute-command-keys
8505 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8506 (org-with-limited-levels
8507 (let* ((visp (not (org-invisible-p)))
8508 (txt tree)
8509 (^re_ "\\(\\*+\\)[ \t]*")
8510 (old-level (if (string-match org-outline-regexp-bol txt)
8511 (- (match-end 0) (match-beginning 0) 1)
8512 -1))
8513 (force-level (cond (level (prefix-numeric-value level))
8514 ((and (looking-at "[ \t]*$")
8515 (string-match
8516 "^\\*+$" (buffer-substring
8517 (point-at-bol) (point))))
8518 (- (match-end 0) (match-beginning 0)))
8519 ((and (bolp)
8520 (looking-at org-outline-regexp))
8521 (- (match-end 0) (point) 1))))
8522 (previous-level (save-excursion
8523 (condition-case nil
8524 (progn
8525 (outline-previous-visible-heading 1)
8526 (if (looking-at ^re_)
8527 (- (match-end 0) (match-beginning 0) 1)
8529 (error 1))))
8530 (next-level (save-excursion
8531 (condition-case nil
8532 (progn
8533 (or (looking-at org-outline-regexp)
8534 (outline-next-visible-heading 1))
8535 (if (looking-at ^re_)
8536 (- (match-end 0) (match-beginning 0) 1)
8538 (error 1))))
8539 (new-level (or force-level (max previous-level next-level)))
8540 (shift (if (or (= old-level -1)
8541 (= new-level -1)
8542 (= old-level new-level))
8544 (- new-level old-level)))
8545 (delta (if (> shift 0) -1 1))
8546 (func (if (> shift 0) 'org-demote 'org-promote))
8547 (org-odd-levels-only nil)
8548 beg end newend)
8549 ;; Remove the forced level indicator
8550 (when force-level
8551 (delete-region (point-at-bol) (point)))
8552 ;; Paste
8553 (beginning-of-line (if (bolp) 1 2))
8554 (setq beg (point))
8555 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8556 (insert-before-markers txt)
8557 (unless (string-suffix-p "\n" txt) (insert "\n"))
8558 (setq newend (point))
8559 (org-reinstall-markers-in-region beg)
8560 (setq end (point))
8561 (goto-char beg)
8562 (skip-chars-forward " \t\n\r")
8563 (setq beg (point))
8564 (when (and (org-invisible-p) visp)
8565 (save-excursion (outline-show-heading)))
8566 ;; Shift if necessary
8567 (unless (= shift 0)
8568 (save-restriction
8569 (narrow-to-region beg end)
8570 (while (not (= shift 0))
8571 (org-map-region func (point-min) (point-max))
8572 (setq shift (+ delta shift)))
8573 (goto-char (point-min))
8574 (setq newend (point-max))))
8575 (when (or (called-interactively-p 'interactive) for-yank)
8576 (message "Clipboard pasted as level %d subtree" new-level))
8577 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8578 kill-ring
8579 (eq org-subtree-clip (current-kill 0))
8580 org-subtree-clip-folded)
8581 ;; The tree was folded before it was killed/copied
8582 (outline-hide-subtree))
8583 (and for-yank (goto-char newend))
8584 (and remove (setq kill-ring (cdr kill-ring))))))
8586 (defun org-kill-is-subtree-p (&optional txt)
8587 "Check if the current kill is an outline subtree, or a set of trees.
8588 Returns nil if kill does not start with a headline, or if the first
8589 headline level is not the largest headline level in the tree.
8590 So this will actually accept several entries of equal levels as well,
8591 which is OK for `org-paste-subtree'.
8592 If optional TXT is given, check this string instead of the current kill."
8593 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8594 (re (org-get-limited-outline-regexp))
8595 (^re (concat "^" re))
8596 (start-level (and kill
8597 (string-match
8598 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8599 kill)
8600 (- (match-end 2) (match-beginning 2) 1)))
8601 (start (1+ (or (match-beginning 2) -1))))
8602 (if (not start-level)
8603 (progn
8604 nil) ;; does not even start with a heading
8605 (catch 'exit
8606 (while (setq start (string-match ^re kill (1+ start)))
8607 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8608 (throw 'exit nil)))
8609 t))))
8611 (defvar org-markers-to-move nil
8612 "Markers that should be moved with a cut-and-paste operation.
8613 Those markers are stored together with their positions relative to
8614 the start of the region.")
8616 (defun org-save-markers-in-region (beg end)
8617 "Check markers in region.
8618 If these markers are between BEG and END, record their position relative
8619 to BEG, so that after moving the block of text, we can put the markers back
8620 into place.
8621 This function gets called just before an entry or tree gets cut from the
8622 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8623 called immediately, to move the markers with the entries."
8624 (setq org-markers-to-move nil)
8625 (when (featurep 'org-clock)
8626 (org-clock-save-markers-for-cut-and-paste beg end))
8627 (when (featurep 'org-agenda)
8628 (org-agenda-save-markers-for-cut-and-paste beg end)))
8630 (defun org-check-and-save-marker (marker beg end)
8631 "Check if MARKER is between BEG and END.
8632 If yes, remember the marker and the distance to BEG."
8633 (when (and (marker-buffer marker)
8634 (equal (marker-buffer marker) (current-buffer))
8635 (>= marker beg) (< marker end))
8636 (push (cons marker (- marker beg)) org-markers-to-move)))
8638 (defun org-reinstall-markers-in-region (beg)
8639 "Move all remembered markers to their position relative to BEG."
8640 (dolist (x org-markers-to-move)
8641 (move-marker (car x) (+ beg (cdr x))))
8642 (setq org-markers-to-move nil))
8644 (defun org-narrow-to-subtree ()
8645 "Narrow buffer to the current subtree."
8646 (interactive)
8647 (save-excursion
8648 (save-match-data
8649 (org-with-limited-levels
8650 (narrow-to-region
8651 (progn (org-back-to-heading t) (point))
8652 (progn (org-end-of-subtree t t)
8653 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8654 (point)))))))
8656 (defun org-narrow-to-block ()
8657 "Narrow buffer to the current block."
8658 (interactive)
8659 (let* ((case-fold-search t)
8660 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8661 "^[ \t]*#\\+end_.*")))
8662 (if blockp
8663 (narrow-to-region (car blockp) (cdr blockp))
8664 (user-error "Not in a block"))))
8666 (defun org-clone-subtree-with-time-shift (n &optional shift)
8667 "Clone the task (subtree) at point N times.
8668 The clones will be inserted as siblings.
8670 In interactive use, the user will be prompted for the number of
8671 clones to be produced. If the entry has a timestamp, the user
8672 will also be prompted for a time shift, which may be a repeater
8673 as used in time stamps, for example `+3d'. To disable this,
8674 you can call the function with a universal prefix argument.
8676 When a valid repeater is given and the entry contains any time
8677 stamps, the clones will become a sequence in time, with time
8678 stamps in the subtree shifted for each clone produced. If SHIFT
8679 is nil or the empty string, time stamps will be left alone. The
8680 ID property of the original subtree is removed.
8682 In each clone, all the CLOCK entries will be removed. This
8683 prevents Org from considering that the clocked times overlap.
8685 If the original subtree did contain time stamps with a repeater,
8686 the following will happen:
8687 - the repeater will be removed in each clone
8688 - an additional clone will be produced, with the current, unshifted
8689 date(s) in the entry.
8690 - the original entry will be placed *after* all the clones, with
8691 repeater intact.
8692 - the start days in the repeater in the original entry will be shifted
8693 to past the last clone.
8694 In this way you can spell out a number of instances of a repeating task,
8695 and still retain the repeater to cover future instances of the task.
8697 As described above, N+1 clones are produced when the original
8698 subtree has a repeater. Setting N to 0, then, can be used to
8699 remove the repeater from a subtree and create a shifted clone
8700 with the original repeater."
8701 (interactive "nNumber of clones to produce: ")
8702 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8703 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8704 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8705 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8706 (shift
8707 (or shift
8708 (if (and (not (equal current-prefix-arg '(4)))
8709 (save-excursion
8710 (goto-char beg)
8711 (re-search-forward org-ts-regexp-both end-of-tree t)))
8712 (read-from-minibuffer
8713 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8714 ""))) ;No time shift
8715 (doshift
8716 (and (org-string-nw-p shift)
8717 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8718 shift)
8719 (user-error "Invalid shift specification %s" shift)))))
8720 (goto-char end-of-tree)
8721 (unless (bolp) (insert "\n"))
8722 (let* ((end (point))
8723 (template (buffer-substring beg end))
8724 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8725 (shift-what (pcase (and doshift (match-string 2 shift))
8726 (`nil nil)
8727 ("d" 'day)
8728 ("w" (setq shift-n (* 7 shift-n)) 'day)
8729 ("m" 'month)
8730 ("y" 'year)
8731 (_ (error "Unsupported time unit"))))
8732 (nmin 1)
8733 (nmax n)
8734 (n-no-remove -1)
8735 (idprop (org-entry-get nil "ID")))
8736 (when (and doshift
8737 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8738 template))
8739 (delete-region beg end)
8740 (setq end beg)
8741 (setq nmin 0)
8742 (setq nmax (1+ nmax))
8743 (setq n-no-remove nmax))
8744 (goto-char end)
8745 (cl-loop for n from nmin to nmax do
8746 (insert
8747 ;; Prepare clone.
8748 (with-temp-buffer
8749 (insert template)
8750 (org-mode)
8751 (goto-char (point-min))
8752 (org-show-subtree)
8753 (and idprop (if org-clone-delete-id
8754 (org-entry-delete nil "ID")
8755 (org-id-get-create t)))
8756 (unless (= n 0)
8757 (while (re-search-forward org-clock-line-re nil t)
8758 (delete-region (line-beginning-position)
8759 (line-beginning-position 2)))
8760 (goto-char (point-min))
8761 (while (re-search-forward org-drawer-regexp nil t)
8762 (org-remove-empty-drawer-at (point))))
8763 (goto-char (point-min))
8764 (when doshift
8765 (while (re-search-forward org-ts-regexp-both nil t)
8766 (org-timestamp-change (* n shift-n) shift-what))
8767 (unless (= n n-no-remove)
8768 (goto-char (point-min))
8769 (while (re-search-forward org-ts-regexp nil t)
8770 (save-excursion
8771 (goto-char (match-beginning 0))
8772 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8773 (delete-region (match-beginning 1) (match-end 1)))))))
8774 (buffer-string)))))
8775 (goto-char beg)))
8777 ;;; Outline Sorting
8779 (defun org-sort (&optional with-case)
8780 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8781 Optional argument WITH-CASE means sort case-sensitively."
8782 (interactive "P")
8783 (org-call-with-arg
8784 (cond ((org-at-table-p) #'org-table-sort-lines)
8785 ((org-at-item-p) #'org-sort-list)
8786 (t #'org-sort-entries))
8787 with-case))
8789 (defun org-sort-remove-invisible (s)
8790 "Remove invisible part of links and emphasis markers from string S."
8791 (remove-text-properties 0 (length s) org-rm-props s)
8792 (replace-regexp-in-string
8793 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8794 (replace-regexp-in-string
8795 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8796 (org-link-display-format s)
8797 t t) t t))
8799 (defvar org-priority-regexp) ; defined later in the file
8801 (defvar org-after-sorting-entries-or-items-hook nil
8802 "Hook that is run after a bunch of entries or items have been sorted.
8803 When children are sorted, the cursor is in the parent line when this
8804 hook gets called. When a region or a plain list is sorted, the cursor
8805 will be in the first entry of the sorted region/list.")
8807 (defun org-sort-entries
8808 (&optional with-case sorting-type getkey-func compare-func property
8809 interactive?)
8810 "Sort entries on a certain level of an outline tree.
8811 If there is an active region, the entries in the region are sorted.
8812 Else, if the cursor is before the first entry, sort the top-level items.
8813 Else, the children of the entry at point are sorted.
8815 Sorting can be alphabetically, numerically, by date/time as given by
8816 a time stamp, by a property, by priority order, or by a custom function.
8818 The command prompts for the sorting type unless it has been given to the
8819 function through the SORTING-TYPE argument, which needs to be a character,
8820 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8821 the precise meaning of each character:
8823 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8824 c By creation time, which is assumed to be the first inactive time stamp
8825 at the beginning of a line.
8826 d By deadline date/time.
8827 k By clocking time.
8828 n Numerically, by converting the beginning of the entry/item to a number.
8829 o By order of TODO keywords.
8830 p By priority according to the cookie.
8831 r By the value of a property.
8832 s By scheduled date/time.
8833 t By date/time, either the first active time stamp in the entry, or, if
8834 none exist, by the first inactive one.
8836 Capital letters will reverse the sort order.
8838 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8839 called with point at the beginning of the record. It must return a
8840 value that is compatible with COMPARE-FUNC, the function used to
8841 compare entries.
8843 Comparing entries ignores case by default. However, with an optional argument
8844 WITH-CASE, the sorting considers case as well.
8846 Sorting is done against the visible part of the headlines, it ignores hidden
8847 links.
8849 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8851 A non-nil value for INTERACTIVE? is used to signal that this
8852 function is being called interactively."
8853 (interactive (list current-prefix-arg nil nil nil nil t))
8854 (let ((case-func (if with-case 'identity 'downcase))
8855 start beg end stars re re2
8856 txt what tmp)
8857 ;; Find beginning and end of region to sort
8858 (cond
8859 ((org-region-active-p)
8860 ;; we will sort the region
8861 (setq end (region-end)
8862 what "region")
8863 (goto-char (region-beginning))
8864 (unless (org-at-heading-p) (outline-next-heading))
8865 (setq start (point)))
8866 ((or (org-at-heading-p)
8867 (ignore-errors (progn (org-back-to-heading) t)))
8868 ;; we will sort the children of the current headline
8869 (org-back-to-heading)
8870 (setq start (point)
8871 end (progn (org-end-of-subtree t t)
8872 (or (bolp) (insert "\n"))
8873 (when (>= (org-back-over-empty-lines) 1)
8874 (forward-line 1))
8875 (point))
8876 what "children")
8877 (goto-char start)
8878 (outline-show-subtree)
8879 (outline-next-heading))
8881 ;; we will sort the top-level entries in this file
8882 (goto-char (point-min))
8883 (or (org-at-heading-p) (outline-next-heading))
8884 (setq start (point))
8885 (goto-char (point-max))
8886 (beginning-of-line 1)
8887 (when (looking-at ".*?\\S-")
8888 ;; File ends in a non-white line
8889 (end-of-line 1)
8890 (insert "\n"))
8891 (setq end (point-max))
8892 (setq what "top-level")
8893 (goto-char start)
8894 (outline-show-all)))
8896 (setq beg (point))
8897 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8899 (looking-at "\\(\\*+\\)")
8900 (setq stars (match-string 1)
8901 re (concat "^" (regexp-quote stars) " +")
8902 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8903 txt (buffer-substring beg end))
8904 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8905 (when (and (not (equal stars "*")) (string-match re2 txt))
8906 (user-error "Region to sort contains a level above the first entry"))
8908 (unless sorting-type
8909 (message
8910 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8911 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8912 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8913 what)
8914 (setq sorting-type (read-char-exclusive)))
8916 (unless getkey-func
8917 (and (= (downcase sorting-type) ?f)
8918 (setq getkey-func
8919 (or (and interactive?
8920 (org-read-function
8921 "Function for extracting keys: "))
8922 (error "Missing key extractor")))))
8924 (and (= (downcase sorting-type) ?r)
8925 (not property)
8926 (setq property
8927 (completing-read "Property: "
8928 (mapcar #'list (org-buffer-property-keys t))
8929 nil t)))
8931 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8932 (message "Sorting entries...")
8934 (save-restriction
8935 (narrow-to-region start end)
8936 (let ((restore-clock?
8937 ;; The clock marker is lost when using `sort-subr'; mark
8938 ;; the clock with temporary `:org-clock-marker-backup'
8939 ;; text property.
8940 (when (and (eq (org-clock-is-active) (current-buffer))
8941 (<= start (marker-position org-clock-marker))
8942 (>= end (marker-position org-clock-marker)))
8943 (org-with-silent-modifications
8944 (put-text-property (1- org-clock-marker) org-clock-marker
8945 :org-clock-marker-backup t))
8947 (dcst (downcase sorting-type))
8948 (case-fold-search nil)
8949 (now (current-time)))
8950 (sort-subr
8951 (/= dcst sorting-type)
8952 ;; This function moves to the beginning character of the "record" to
8953 ;; be sorted.
8954 (lambda nil
8955 (if (re-search-forward re nil t)
8956 (goto-char (match-beginning 0))
8957 (goto-char (point-max))))
8958 ;; This function moves to the last character of the "record" being
8959 ;; sorted.
8960 (lambda nil
8961 (save-match-data
8962 (condition-case nil
8963 (outline-forward-same-level 1)
8964 (error
8965 (goto-char (point-max))))))
8966 ;; This function returns the value that gets sorted against.
8967 (lambda nil
8968 (cond
8969 ((= dcst ?n)
8970 (if (looking-at org-complex-heading-regexp)
8971 (string-to-number (org-sort-remove-invisible (match-string 4)))
8972 nil))
8973 ((= dcst ?a)
8974 (if (looking-at org-complex-heading-regexp)
8975 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8976 nil))
8977 ((= dcst ?k)
8978 (or (get-text-property (point) :org-clock-minutes) 0))
8979 ((= dcst ?t)
8980 (let ((end (save-excursion (outline-next-heading) (point))))
8981 (if (or (re-search-forward org-ts-regexp end t)
8982 (re-search-forward org-ts-regexp-both end t))
8983 (org-time-string-to-seconds (match-string 0))
8984 (float-time now))))
8985 ((= dcst ?c)
8986 (let ((end (save-excursion (outline-next-heading) (point))))
8987 (if (re-search-forward
8988 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8989 end t)
8990 (org-time-string-to-seconds (match-string 0))
8991 (float-time now))))
8992 ((= dcst ?s)
8993 (let ((end (save-excursion (outline-next-heading) (point))))
8994 (if (re-search-forward org-scheduled-time-regexp end t)
8995 (org-time-string-to-seconds (match-string 1))
8996 (float-time now))))
8997 ((= dcst ?d)
8998 (let ((end (save-excursion (outline-next-heading) (point))))
8999 (if (re-search-forward org-deadline-time-regexp end t)
9000 (org-time-string-to-seconds (match-string 1))
9001 (float-time now))))
9002 ((= dcst ?p)
9003 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9004 (string-to-char (match-string 2))
9005 org-default-priority))
9006 ((= dcst ?r)
9007 (or (org-entry-get nil property) ""))
9008 ((= dcst ?o)
9009 (when (looking-at org-complex-heading-regexp)
9010 (let* ((m (match-string 2))
9011 (s (if (member m org-done-keywords) '- '+)))
9012 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9013 ((= dcst ?f)
9014 (if getkey-func
9015 (progn
9016 (setq tmp (funcall getkey-func))
9017 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9018 tmp)
9019 (error "Invalid key function `%s'" getkey-func)))
9020 (t (error "Invalid sorting type `%c'" sorting-type))))
9022 (cond
9023 ((= dcst ?a) 'string<)
9024 ((= dcst ?f)
9025 (or compare-func
9026 (and interactive?
9027 (org-read-function
9028 (concat "Function for comparing keys "
9029 "(empty for default `sort-subr' predicate): ")
9030 'allow-empty))))
9031 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9032 (when restore-clock?
9033 (move-marker org-clock-marker
9034 (1+ (next-single-property-change
9035 start :org-clock-marker-backup)))
9036 (remove-text-properties (1- org-clock-marker) org-clock-marker
9037 '(:org-clock-marker-backup t)))))
9038 (run-hooks 'org-after-sorting-entries-or-items-hook)
9039 (message "Sorting entries...done")))
9041 ;;; The orgstruct minor mode
9043 ;; Define a minor mode which can be used in other modes in order to
9044 ;; integrate the Org mode structure editing commands.
9046 ;; This is really a hack, because the Org mode structure commands use
9047 ;; keys which normally belong to the major mode. Here is how it
9048 ;; works: The minor mode defines all the keys necessary to operate the
9049 ;; structure commands, but wraps the commands into a function which
9050 ;; tests if the cursor is currently at a headline or a plain list
9051 ;; item. If that is the case, the structure command is used,
9052 ;; temporarily setting many Org mode variables like regular
9053 ;; expressions for filling etc. However, when any of those keys is
9054 ;; used at a different location, function uses `key-binding' to look
9055 ;; up if the key has an associated command in another currently active
9056 ;; keymap (minor modes, major mode, global), and executes that
9057 ;; command. There might be problems if any of the keys is otherwise
9058 ;; used as a prefix key.
9060 (defcustom orgstruct-heading-prefix-regexp ""
9061 "Regexp that matches the custom prefix of Org headlines in
9062 orgstruct(++)-mode."
9063 :group 'org
9064 :version "26.1"
9065 :package-version '(Org . "8.3")
9066 :type 'regexp)
9067 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9069 (defcustom orgstruct-setup-hook nil
9070 "Hook run after orgstruct-mode-map is filled."
9071 :group 'org
9072 :version "24.4"
9073 :package-version '(Org . "8.0")
9074 :type 'hook)
9076 (defvar orgstruct-initialized nil)
9078 (defvar org-local-vars nil
9079 "List of local variables, for use by `orgstruct-mode'.")
9081 ;;;###autoload
9082 (define-minor-mode orgstruct-mode
9083 "Toggle the minor mode `orgstruct-mode'.
9084 This mode is for using Org mode structure commands in other
9085 modes. The following keys behave as if Org mode were active, if
9086 the cursor is on a headline, or on a plain list item (both as
9087 defined by Org mode)."
9088 nil " OrgStruct" (make-sparse-keymap)
9089 (funcall (if orgstruct-mode
9090 'add-to-invisibility-spec
9091 'remove-from-invisibility-spec)
9092 '(outline . t))
9093 (when orgstruct-mode
9094 (org-load-modules-maybe)
9095 (unless orgstruct-initialized
9096 (orgstruct-setup)
9097 (setq orgstruct-initialized t))))
9099 ;;;###autoload
9100 (defun turn-on-orgstruct ()
9101 "Unconditionally turn on `orgstruct-mode'."
9102 (orgstruct-mode 1))
9104 (defvar-local orgstruct-is-++ nil
9105 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9106 (defvar-local org-fb-vars nil)
9107 (defun orgstruct++-mode (&optional arg)
9108 "Toggle `orgstruct-mode', the enhanced version of it.
9109 In addition to setting orgstruct-mode, this also exports all
9110 indentation and autofilling variables from Org mode into the
9111 buffer. It will also recognize item context in multiline items."
9112 (interactive "P")
9113 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9114 (if (< arg 1)
9115 (progn (orgstruct-mode -1)
9116 (dolist (v org-fb-vars)
9117 (set (make-local-variable (car v))
9118 (if (eq (car-safe (cadr v)) 'quote)
9119 (cl-cadadr v)
9120 (nth 1 v)))))
9121 (orgstruct-mode 1)
9122 (setq org-fb-vars nil)
9123 (unless org-local-vars
9124 (setq org-local-vars (org-get-local-variables)))
9125 (let (var val)
9126 (dolist (x org-local-vars)
9127 (when (string-match
9128 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9129 \\|fill-prefix\\|indent-\\)"
9130 (symbol-name (car x)))
9131 (setq var (car x) val (nth 1 x))
9132 (push (list var `(quote ,(eval var))) org-fb-vars)
9133 (set (make-local-variable var)
9134 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9135 (setq-local orgstruct-is-++ t))))
9137 ;;;###autoload
9138 (defun turn-on-orgstruct++ ()
9139 "Unconditionally turn on `orgstruct++-mode'."
9140 (orgstruct++-mode 1))
9142 (defun orgstruct-error ()
9143 "Error when there is no default binding for a structure key."
9144 (interactive)
9145 (funcall (if (fboundp 'user-error)
9146 'user-error
9147 'error)
9148 "This key has no function outside structure elements"))
9150 (defun orgstruct-setup ()
9151 "Setup orgstruct keymap."
9152 (dolist (cell '((org-demote . t)
9153 (org-metaleft . t)
9154 (org-metaright . t)
9155 (org-promote . t)
9156 (org-shiftmetaleft . t)
9157 (org-shiftmetaright . t)
9158 org-backward-element
9159 org-backward-heading-same-level
9160 org-ctrl-c-ret
9161 org-ctrl-c-minus
9162 org-ctrl-c-star
9163 org-cycle
9164 org-force-cycle-archived
9165 org-forward-heading-same-level
9166 org-insert-heading
9167 org-insert-heading-respect-content
9168 org-kill-note-or-show-branches
9169 org-mark-subtree
9170 org-meta-return
9171 org-metadown
9172 org-metaup
9173 org-narrow-to-subtree
9174 org-promote-subtree
9175 org-reveal
9176 org-shiftdown
9177 org-shiftleft
9178 org-shiftmetadown
9179 org-shiftmetaup
9180 org-shiftright
9181 org-shifttab
9182 org-shifttab
9183 org-shiftup
9184 org-show-children
9185 org-show-subtree
9186 org-sort
9187 org-up-element
9188 outline-demote
9189 outline-next-visible-heading
9190 outline-previous-visible-heading
9191 outline-promote
9192 outline-up-heading))
9193 (let ((f (or (car-safe cell) cell))
9194 (disable-when-heading-prefix (cdr-safe cell)))
9195 (when (fboundp f)
9196 (let ((new-bindings))
9197 (dolist (binding (nconc (where-is-internal f org-mode-map)
9198 (where-is-internal f outline-mode-map)))
9199 (push binding new-bindings)
9200 ;; TODO use local-function-key-map
9201 (dolist (rep '(("<tab>" . "TAB")
9202 ("<return>" . "RET")
9203 ("<escape>" . "ESC")
9204 ("<delete>" . "DEL")))
9205 (setq binding (read-kbd-macro
9206 (let ((case-fold-search))
9207 (replace-regexp-in-string
9208 (regexp-quote (cdr rep))
9209 (car rep)
9210 (key-description binding)))))
9211 (cl-pushnew binding new-bindings :test 'equal)))
9212 (dolist (binding new-bindings)
9213 (let ((key (lookup-key orgstruct-mode-map binding)))
9214 (when (or (not key) (numberp key))
9215 (ignore-errors
9216 (org-defkey orgstruct-mode-map
9217 binding
9218 (orgstruct-make-binding
9219 f binding disable-when-heading-prefix))))))))))
9220 (run-hooks 'orgstruct-setup-hook))
9222 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9223 "Create a function for binding in the structure minor mode.
9224 FUN is the command to call inside a table. KEY is the key that
9225 should be checked in for a command to execute outside of tables.
9226 Non-nil `disable-when-heading-prefix' means to disable the command
9227 if `orgstruct-heading-prefix-regexp' is not empty."
9228 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9229 (let ((nname name)
9230 (i 0))
9231 (while (fboundp (intern nname))
9232 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9233 (setq name (intern nname)))
9234 (eval
9235 (let ((bindings '((org-heading-regexp
9236 (concat "^"
9237 orgstruct-heading-prefix-regexp
9238 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9239 (org-outline-regexp
9240 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9241 (org-outline-regexp-bol
9242 (concat "^" org-outline-regexp))
9243 (outline-regexp org-outline-regexp)
9244 (outline-heading-end-regexp "\n")
9245 (outline-level 'org-outline-level)
9246 (outline-heading-alist))))
9247 `(defun ,name (arg)
9248 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9249 "Outside of structure, run the binding of `"
9250 (key-description key) "'."
9251 (when disable-when-heading-prefix
9252 (concat
9253 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9254 "back to the default binding due to limitations of Org's implementation of\n"
9255 "`" (symbol-name fun) "'.")))
9256 (interactive "p")
9257 (let* ((disable
9258 ,(and disable-when-heading-prefix
9259 '(not (string= orgstruct-heading-prefix-regexp ""))))
9260 (fallback
9261 (or disable
9262 (not
9263 (let* ,bindings
9264 (org-context-p 'headline 'item
9265 ,(when (memq fun
9266 '(org-insert-heading
9267 org-insert-heading-respect-content
9268 org-meta-return))
9269 '(when orgstruct-is-++
9270 'item-body))))))))
9271 (if fallback
9272 (let* ((orgstruct-mode)
9273 (binding
9274 (let ((key ,key))
9275 (catch 'exit
9276 (dolist
9277 (rep
9278 '(nil
9279 ("<\\([^>]*\\)tab>" . "\\1TAB")
9280 ("<\\([^>]*\\)return>" . "\\1RET")
9281 ("<\\([^>]*\\)escape>" . "\\1ESC")
9282 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9283 nil)
9284 (when rep
9285 (setq key (read-kbd-macro
9286 (let ((case-fold-search))
9287 (replace-regexp-in-string
9288 (car rep)
9289 (cdr rep)
9290 (key-description key))))))
9291 (when (key-binding key)
9292 (throw 'exit (key-binding key))))))))
9293 (if (keymapp binding)
9294 (org-set-transient-map binding)
9295 (let ((func (or binding
9296 (unless disable
9297 'orgstruct-error))))
9298 (when func
9299 (call-interactively func)))))
9300 (org-run-like-in-org-mode
9301 (lambda ()
9302 (interactive)
9303 (let* ,bindings
9304 (call-interactively ',fun)))))))))
9305 name))
9307 (defun org-contextualize-keys (alist contexts)
9308 "Return valid elements in ALIST depending on CONTEXTS.
9310 `org-agenda-custom-commands' or `org-capture-templates' are the
9311 values used for ALIST, and `org-agenda-custom-commands-contexts'
9312 or `org-capture-templates-contexts' are the associated contexts
9313 definitions."
9314 (let ((contexts
9315 ;; normalize contexts
9316 (mapcar
9317 (lambda(c) (cond ((listp (cadr c))
9318 (list (car c) (car c) (nth 1 c)))
9319 ((string= "" (cadr c))
9320 (list (car c) (car c) (nth 2 c)))
9321 (t c)))
9322 contexts))
9323 (a alist) r s)
9324 ;; loop over all commands or templates
9325 (dolist (c a)
9326 (let (vrules repl)
9327 (cond
9328 ((not (assoc (car c) contexts))
9329 (push c r))
9330 ((and (assoc (car c) contexts)
9331 (setq vrules (org-contextualize-validate-key
9332 (car c) contexts)))
9333 (mapc (lambda (vr)
9334 (unless (equal (car vr) (cadr vr))
9335 (setq repl vr)))
9336 vrules)
9337 (if (not repl) (push c r)
9338 (push (cadr repl) s)
9339 (push
9340 (cons (car c)
9341 (cdr (or (assoc (cadr repl) alist)
9342 (error "Undefined key `%s' as contextual replacement for `%s'"
9343 (cadr repl) (car c)))))
9344 r))))))
9345 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9346 (delq
9348 (delete-dups
9349 (mapcar (lambda (x)
9350 (let ((tpl (car x)))
9351 (unless (delq
9353 (mapcar (lambda (y)
9354 (equal y tpl))
9356 x)))
9357 (reverse r))))))
9359 (defun org-contextualize-validate-key (key contexts)
9360 "Check CONTEXTS for agenda or capture KEY."
9361 (let (res)
9362 (dolist (r contexts)
9363 (dolist (rr (car (last r)))
9364 (when
9365 (and (equal key (car r))
9366 (if (functionp rr) (funcall rr)
9367 (or (and (eq (car rr) 'in-file)
9368 (buffer-file-name)
9369 (string-match (cdr rr) (buffer-file-name)))
9370 (and (eq (car rr) 'in-mode)
9371 (string-match (cdr rr) (symbol-name major-mode)))
9372 (and (eq (car rr) 'in-buffer)
9373 (string-match (cdr rr) (buffer-name)))
9374 (when (and (eq (car rr) 'not-in-file)
9375 (buffer-file-name))
9376 (not (string-match (cdr rr) (buffer-file-name))))
9377 (when (eq (car rr) 'not-in-mode)
9378 (not (string-match (cdr rr) (symbol-name major-mode))))
9379 (when (eq (car rr) 'not-in-buffer)
9380 (not (string-match (cdr rr) (buffer-name)))))))
9381 (push r res))))
9382 (delete-dups (delq nil res))))
9384 (defun org-context-p (&rest contexts)
9385 "Check if local context is any of CONTEXTS.
9386 Possible values in the list of contexts are `table', `headline', and `item'."
9387 (let ((pos (point)))
9388 (goto-char (point-at-bol))
9389 (prog1 (or (and (memq 'table contexts)
9390 (looking-at "[ \t]*|"))
9391 (and (memq 'headline contexts)
9392 (looking-at org-outline-regexp))
9393 (and (memq 'item contexts)
9394 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9395 (and (memq 'item-body contexts)
9396 (org-in-item-p)))
9397 (goto-char pos))))
9399 ;;;###autoload
9400 (defun org-run-like-in-org-mode (cmd)
9401 "Run a command, pretending that the current buffer is in Org mode.
9402 This will temporarily bind local variables that are typically bound in
9403 Org mode to the values they have in Org mode, and then interactively
9404 call CMD."
9405 (org-load-modules-maybe)
9406 (unless org-local-vars
9407 (setq org-local-vars (org-get-local-variables)))
9408 (let (binds)
9409 (dolist (var org-local-vars)
9410 (when (or (not (boundp (car var)))
9411 (eq (symbol-value (car var))
9412 (default-value (car var))))
9413 (push (list (car var) `(quote ,(cadr var))) binds)))
9414 (eval `(let ,binds
9415 (call-interactively (quote ,cmd))))))
9417 (defun org-get-category (&optional pos force-refresh)
9418 "Get the category applying to position POS."
9419 (save-match-data
9420 (when force-refresh (org-refresh-category-properties))
9421 (let ((pos (or pos (point))))
9422 (or (get-text-property pos 'org-category)
9423 (progn (org-refresh-category-properties)
9424 (get-text-property pos 'org-category))))))
9426 ;;; Refresh properties
9428 (defun org-refresh-properties (dprop tprop)
9429 "Refresh buffer text properties.
9430 DPROP is the drawer property and TPROP is either the
9431 corresponding text property to set, or an alist with each element
9432 being a text property (as a symbol) and a function to apply to
9433 the value of the drawer property."
9434 (let* ((case-fold-search t)
9435 (inhibit-read-only t)
9436 (inherit? (org-property-inherit-p dprop))
9437 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9438 (global (and inherit? (org--property-global-value dprop nil))))
9439 (org-with-silent-modifications
9440 (org-with-point-at 1
9441 ;; Set global values (e.g., values defined through
9442 ;; "#+PROPERTY:" keywords) to the whole buffer.
9443 (when global (put-text-property (point-min) (point-max) tprop global))
9444 ;; Set local values.
9445 (while (re-search-forward property-re nil t)
9446 (when (org-at-property-p)
9447 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9448 (outline-next-heading))))))
9450 (defun org-refresh-property (tprop p &optional inherit)
9451 "Refresh the buffer text property TPROP from the drawer property P.
9452 The refresh happens only for the current headline, or the whole
9453 sub-tree if optional argument INHERIT is non-nil."
9454 (unless (org-before-first-heading-p)
9455 (save-excursion
9456 (org-back-to-heading t)
9457 (let ((start (point))
9458 (end (save-excursion
9459 (if inherit (org-end-of-subtree t t)
9460 (or (outline-next-heading) (point-max))))))
9461 (if (symbolp tprop)
9462 ;; TPROP is a text property symbol.
9463 (put-text-property start end tprop p)
9464 ;; TPROP is an alist with (property . function) elements.
9465 (pcase-dolist (`(,prop . ,f) tprop)
9466 (put-text-property start end prop (funcall f p))))))))
9468 (defun org-refresh-category-properties ()
9469 "Refresh category text properties in the buffer."
9470 (let ((case-fold-search t)
9471 (inhibit-read-only t)
9472 (default-category
9473 (cond ((null org-category)
9474 (if buffer-file-name
9475 (file-name-sans-extension
9476 (file-name-nondirectory buffer-file-name))
9477 "???"))
9478 ((symbolp org-category) (symbol-name org-category))
9479 (t org-category))))
9480 (org-with-silent-modifications
9481 (org-with-wide-buffer
9482 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9483 ;; This is the default category for the buffer. If none is
9484 ;; found, fall-back to `org-category' or buffer file name.
9485 (put-text-property
9486 (point-min) (point-max)
9487 'org-category
9488 (catch 'buffer-category
9489 (goto-char (point-max))
9490 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9491 (let ((element (org-element-at-point)))
9492 (when (eq (org-element-type element) 'keyword)
9493 (throw 'buffer-category
9494 (org-element-property :value element)))))
9495 default-category))
9496 ;; Set sub-tree specific categories.
9497 (goto-char (point-min))
9498 (let ((regexp (org-re-property "CATEGORY")))
9499 (while (re-search-forward regexp nil t)
9500 (let ((value (match-string-no-properties 3)))
9501 (when (org-at-property-p)
9502 (put-text-property
9503 (save-excursion (org-back-to-heading t) (point))
9504 (save-excursion (org-end-of-subtree t t) (point))
9505 'org-category
9506 value)))))))))
9508 (defun org-refresh-stats-properties ()
9509 "Refresh stats text properties in the buffer."
9510 (org-with-silent-modifications
9511 (org-with-point-at 1
9512 (let ((regexp (concat org-outline-regexp-bol
9513 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9514 (while (re-search-forward regexp nil t)
9515 (let* ((numerator (string-to-number (match-string 1)))
9516 (denominator (and (match-end 2)
9517 (string-to-number (match-string 2))))
9518 (stats (cond ((not denominator) numerator) ;percent
9519 ((= denominator 0) 0)
9520 (t (/ (* numerator 100) denominator)))))
9521 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9522 'org-stats stats)))))))
9524 (defun org-refresh-effort-properties ()
9525 "Refresh effort properties"
9526 (org-refresh-properties
9527 org-effort-property
9528 '((effort . identity)
9529 (effort-minutes . org-duration-to-minutes))))
9531 ;;;; Link Stuff
9533 ;;; Link abbreviations
9535 (defun org-link-expand-abbrev (link)
9536 "Apply replacements as defined in `org-link-abbrev-alist'."
9537 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9538 (let* ((key (match-string 1 link))
9539 (as (or (assoc key org-link-abbrev-alist-local)
9540 (assoc key org-link-abbrev-alist)))
9541 (tag (and (match-end 2) (match-string 3 link)))
9542 rpl)
9543 (if (not as)
9544 link
9545 (setq rpl (cdr as))
9546 (cond
9547 ((symbolp rpl) (funcall rpl tag))
9548 ((string-match "%(\\([^)]+\\))" rpl)
9549 (replace-match
9550 (save-match-data
9551 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9552 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9553 ((string-match "%h" rpl)
9554 (replace-match (url-hexify-string (or tag "")) t t rpl))
9555 (t (concat rpl tag)))))
9556 link))
9558 ;;; Storing and inserting links
9560 (defvar org-insert-link-history nil
9561 "Minibuffer history for links inserted with `org-insert-link'.")
9563 (defvar org-stored-links nil
9564 "Contains the links stored with `org-store-link'.")
9566 (defvar org-store-link-plist nil
9567 "Plist with info about the most recently link created with `org-store-link'.")
9569 (defun org-store-link-functions ()
9570 "Return a list of functions that are called to create and store a link.
9571 The functions defined in the :store property of
9572 `org-link-parameters'.
9574 Each function will be called in turn until one returns a non-nil
9575 value. Each function should check if it is responsible for
9576 creating this link (for example by looking at the major mode).
9577 If not, it must exit and return nil. If yes, it should return
9578 a non-nil value after calling `org-store-link-props' with a list
9579 of properties and values. Special properties are:
9581 :type The link prefix, like \"http\". This must be given.
9582 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9583 This is obligatory as well.
9584 :description Optional default description for the second pair
9585 of brackets in an Org mode link. The user can still change
9586 this when inserting this link into an Org mode buffer.
9588 In addition to these, any additional properties can be specified
9589 and then used in capture templates."
9590 (cl-loop for link in org-link-parameters
9591 with store-func
9592 do (setq store-func (org-link-get-parameter (car link) :store))
9593 if store-func
9594 collect store-func))
9596 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9597 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9599 ;;;###autoload
9600 (defun org-store-link (arg)
9601 "Store an org-link to the current location.
9602 \\<org-mode-map>
9603 This link is added to `org-stored-links' and can later be inserted
9604 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9606 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9607 A single
9608 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9609 `org-gnus-prefer-web-links' for links to Usenet articles.
9611 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9612 skipping storing functions that are not
9613 part of Org core.
9615 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9616 prefix ARG forces storing a link for each line in the
9617 active region."
9618 (interactive "P")
9619 (org-load-modules-maybe)
9620 (if (and (equal arg '(64)) (org-region-active-p))
9621 (save-excursion
9622 (let ((end (region-end)))
9623 (goto-char (region-beginning))
9624 (set-mark (point))
9625 (while (< (point-at-eol) end)
9626 (move-end-of-line 1) (activate-mark)
9627 (let (current-prefix-arg)
9628 (call-interactively 'org-store-link))
9629 (move-beginning-of-line 2)
9630 (set-mark (point)))))
9631 (setq org-store-link-plist nil)
9632 (let (link cpltxt desc description search
9633 txt custom-id agenda-link sfuns sfunsn)
9634 (cond
9636 ;; Store a link using an external link type
9637 ((and (not (equal arg '(16)))
9638 (setq sfuns
9639 (delq
9640 nil (mapcar (lambda (f)
9641 (let (fs) (if (funcall f) (push f fs))))
9642 (org-store-link-functions)))
9643 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9644 (or (and (cdr sfuns)
9645 (funcall (intern
9646 (completing-read
9647 "Which function for creating the link? "
9648 sfunsn nil t (car sfunsn)))))
9649 (funcall (caar sfuns)))
9650 (setq link (plist-get org-store-link-plist :link)
9651 desc (or (plist-get org-store-link-plist
9652 :description)
9653 link))))
9655 ;; Store a link from a source code buffer.
9656 ((org-src-edit-buffer-p)
9657 (let ((coderef-format (org-src-coderef-format)))
9658 (cond ((save-excursion
9659 (beginning-of-line)
9660 (looking-at (org-src-coderef-regexp coderef-format)))
9661 (setq link (format "(%s)" (match-string-no-properties 3))))
9662 ((called-interactively-p 'any)
9663 (let ((label (read-string "Code line label: ")))
9664 (end-of-line)
9665 (setq link (format coderef-format label))
9666 (let ((gc (- 79 (length link))))
9667 (if (< (current-column) gc)
9668 (org-move-to-column gc t)
9669 (insert " ")))
9670 (insert link)
9671 (setq link (concat "(" label ")"))
9672 (setq desc nil)))
9673 (t (setq link nil)))))
9675 ;; We are in the agenda, link to referenced location
9676 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9677 (let ((m (or (get-text-property (point) 'org-hd-marker)
9678 (get-text-property (point) 'org-marker))))
9679 (when m
9680 (org-with-point-at m
9681 (setq agenda-link
9682 (if (called-interactively-p 'any)
9683 (call-interactively 'org-store-link)
9684 (org-store-link nil)))))))
9686 ((eq major-mode 'calendar-mode)
9687 (let ((cd (calendar-cursor-to-date)))
9688 (setq link
9689 (format-time-string
9690 (car org-time-stamp-formats)
9691 (apply 'encode-time
9692 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9693 nil nil nil))))
9694 (org-store-link-props :type "calendar" :date cd)))
9696 ((eq major-mode 'help-mode)
9697 (setq link (concat "help:" (save-excursion
9698 (goto-char (point-min))
9699 (looking-at "^[^ ]+")
9700 (match-string 0))))
9701 (org-store-link-props :type "help"))
9703 ((eq major-mode 'w3-mode)
9704 (setq cpltxt (if (and (buffer-name)
9705 (not (string-match "Untitled" (buffer-name))))
9706 (buffer-name)
9707 (url-view-url t))
9708 link (url-view-url t))
9709 (org-store-link-props :type "w3" :url (url-view-url t)))
9711 ((eq major-mode 'image-mode)
9712 (setq cpltxt (concat "file:"
9713 (abbreviate-file-name buffer-file-name))
9714 link cpltxt)
9715 (org-store-link-props :type "image" :file buffer-file-name))
9717 ;; In dired, store a link to the file of the current line
9718 ((derived-mode-p 'dired-mode)
9719 (let ((file (dired-get-filename nil t)))
9720 (setq file (if file
9721 (abbreviate-file-name
9722 (expand-file-name (dired-get-filename nil t)))
9723 ;; otherwise, no file so use current directory.
9724 default-directory))
9725 (setq cpltxt (concat "file:" file)
9726 link cpltxt)))
9728 ((setq search (run-hook-with-args-until-success
9729 'org-create-file-search-functions))
9730 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9731 "::" search))
9732 (setq cpltxt (or description link)))
9734 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9735 (org-with-limited-levels
9736 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9737 (cond
9738 ;; Store a link using the target at point
9739 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9740 (setq cpltxt
9741 (concat "file:"
9742 (abbreviate-file-name
9743 (buffer-file-name (buffer-base-buffer)))
9744 "::" (match-string 1))
9745 link cpltxt))
9746 ((and (featurep 'org-id)
9747 (or (eq org-id-link-to-org-use-id t)
9748 (and (called-interactively-p 'any)
9749 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9750 (and (eq org-id-link-to-org-use-id
9751 'create-if-interactive-and-no-custom-id)
9752 (not custom-id))))
9753 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9754 ;; Store a link using the ID at point
9755 (setq link (condition-case nil
9756 (prog1 (org-id-store-link)
9757 (setq desc (or (plist-get org-store-link-plist
9758 :description)
9759 "")))
9760 (error
9761 ;; Probably before first headline, link only to file
9762 (concat "file:"
9763 (abbreviate-file-name
9764 (buffer-file-name (buffer-base-buffer))))))))
9766 ;; Just link to current headline
9767 (setq cpltxt (concat "file:"
9768 (abbreviate-file-name
9769 (buffer-file-name (buffer-base-buffer)))))
9770 ;; Add a context search string
9771 (when (org-xor org-context-in-file-links
9772 (equal arg '(4)))
9773 (let* ((element (org-element-at-point))
9774 (name (org-element-property :name element)))
9775 (setq txt (cond
9776 ((org-at-heading-p) nil)
9777 (name)
9778 ((org-region-active-p)
9779 (buffer-substring (region-beginning) (region-end)))))
9780 (when (or (null txt) (string-match "\\S-" txt))
9781 (setq cpltxt
9782 (concat cpltxt "::"
9783 (condition-case nil
9784 (org-make-org-heading-search-string txt)
9785 (error "")))
9786 desc (or name
9787 (nth 4 (ignore-errors (org-heading-components)))
9788 "NONE")))))
9789 (when (string-match "::\\'" cpltxt)
9790 (setq cpltxt (substring cpltxt 0 -2)))
9791 (setq link cpltxt)))))
9793 ((buffer-file-name (buffer-base-buffer))
9794 ;; Just link to this file here.
9795 (setq cpltxt (concat "file:"
9796 (abbreviate-file-name
9797 (buffer-file-name (buffer-base-buffer)))))
9798 ;; Add a context string.
9799 (when (org-xor org-context-in-file-links
9800 (equal arg '(4)))
9801 (setq txt (if (org-region-active-p)
9802 (buffer-substring (region-beginning) (region-end))
9803 (buffer-substring (point-at-bol) (point-at-eol))))
9804 ;; Only use search option if there is some text.
9805 (when (string-match "\\S-" txt)
9806 (setq cpltxt
9807 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9808 desc "NONE")))
9809 (setq link cpltxt))
9811 ((called-interactively-p 'interactive)
9812 (user-error "No method for storing a link from this buffer"))
9814 (t (setq link nil)))
9816 ;; We're done setting link and desc, clean up
9817 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9818 (setq link (or link cpltxt)
9819 desc (or desc cpltxt))
9820 (cond ((not desc))
9821 ((equal desc "NONE") (setq desc nil))
9822 (t (setq desc
9823 (replace-regexp-in-string
9824 org-bracket-link-analytic-regexp
9825 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9826 desc))))
9827 ;; Return the link
9828 (if (not (and (or (called-interactively-p 'any)
9829 executing-kbd-macro)
9830 link))
9831 (or agenda-link (and link (org-make-link-string link desc)))
9832 (push (list link desc) org-stored-links)
9833 (message "Stored: %s" (or desc link))
9834 (when custom-id
9835 (setq link (concat "file:" (abbreviate-file-name
9836 (buffer-file-name)) "::#" custom-id))
9837 (push (list link desc) org-stored-links))
9838 (car org-stored-links)))))
9840 (defun org-store-link-props (&rest plist)
9841 "Store link properties, extract names, addresses and dates."
9842 (let ((x (plist-get plist :from)))
9843 (when x
9844 (let ((adr (mail-extract-address-components x)))
9845 (setq plist (plist-put plist :fromname (car adr)))
9846 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9847 (let ((x (plist-get plist :to)))
9848 (when x
9849 (let ((adr (mail-extract-address-components x)))
9850 (setq plist (plist-put plist :toname (car adr)))
9851 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9852 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9853 (when x
9854 (setq plist (plist-put plist :date-timestamp
9855 (format-time-string
9856 (org-time-stamp-format t) x)))
9857 (setq plist (plist-put plist :date-timestamp-inactive
9858 (format-time-string
9859 (org-time-stamp-format t t) x)))))
9860 (let ((from (plist-get plist :from))
9861 (to (plist-get plist :to)))
9862 (when (and from to org-from-is-user-regexp)
9863 (setq plist
9864 (plist-put plist :fromto
9865 (if (string-match org-from-is-user-regexp from)
9866 (concat "to %t")
9867 (concat "from %f"))))))
9868 (setq org-store-link-plist plist))
9870 (defun org-add-link-props (&rest plist)
9871 "Add these properties to the link property list."
9872 (let (key value)
9873 (while plist
9874 (setq key (pop plist) value (pop plist))
9875 (setq org-store-link-plist
9876 (plist-put org-store-link-plist key value)))))
9878 (defun org-email-link-description (&optional fmt)
9879 "Return the description part of an email link.
9880 This takes information from `org-store-link-plist' and formats it
9881 according to FMT (default from `org-email-link-description-format')."
9882 (setq fmt (or fmt org-email-link-description-format))
9883 (let* ((p org-store-link-plist)
9884 (to (plist-get p :toaddress))
9885 (from (plist-get p :fromaddress))
9886 (table
9887 (list
9888 (cons "%c" (plist-get p :fromto))
9889 (cons "%F" (plist-get p :from))
9890 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9891 (cons "%T" (plist-get p :to))
9892 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9893 (cons "%s" (plist-get p :subject))
9894 (cons "%d" (plist-get p :date))
9895 (cons "%m" (plist-get p :message-id)))))
9896 (when (string-match "%c" fmt)
9897 ;; Check if the user wrote this message
9898 (if (and org-from-is-user-regexp from to
9899 (save-match-data (string-match org-from-is-user-regexp from)))
9900 (setq fmt (replace-match "to %t" t t fmt))
9901 (setq fmt (replace-match "from %f" t t fmt))))
9902 (org-replace-escapes fmt table)))
9904 (defun org-make-org-heading-search-string (&optional string)
9905 "Make search string for the current headline or STRING."
9906 (let ((s (or string
9907 (and (derived-mode-p 'org-mode)
9908 (save-excursion
9909 (org-back-to-heading t)
9910 (org-element-property :raw-value (org-element-at-point))))))
9911 (lines org-context-in-file-links))
9912 (unless string (setq s (concat "*" s))) ;Add * for headlines
9913 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9914 (when (and string (integerp lines) (> lines 0))
9915 (let ((slines (org-split-string s "\n")))
9916 (when (< lines (length slines))
9917 (setq s (mapconcat
9918 'identity
9919 (reverse (nthcdr (- (length slines) lines)
9920 (reverse slines))) "\n")))))
9921 (mapconcat #'identity (split-string s) " ")))
9923 (defun org-make-link-string (link &optional description)
9924 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9925 (unless (org-string-nw-p link) (error "Empty link"))
9926 (let ((uri (cond ((string-match org-link-types-re link)
9927 (concat (match-string 1 link)
9928 (org-link-escape (substring link (match-end 1)))))
9929 ;; For readability, url-encode internal links only
9930 ;; when absolutely needed (i.e, when they contain
9931 ;; square brackets). File links however, are
9932 ;; encoded since, e.g., spaces are significant.
9933 ((or (file-name-absolute-p link)
9934 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9935 (org-link-escape link))
9936 (t link)))
9937 (description
9938 (and (org-string-nw-p description)
9939 ;; Remove brackets from description, as they are fatal.
9940 (replace-regexp-in-string
9941 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9942 (org-trim description)))))
9943 (format "[[%s]%s]"
9945 (if description (format "[%s]" description) ""))))
9947 (defconst org-link-escape-chars
9948 ;;%20 %5B %5D %25
9949 '(?\s ?\[ ?\] ?%)
9950 "List of characters that should be escaped in a link when stored to Org.
9951 This is the list that is used for internal purposes.")
9953 (defun org-link-escape (text &optional table merge)
9954 "Return percent escaped representation of TEXT.
9955 TEXT is a string with the text to escape.
9956 Optional argument TABLE is a list with characters that should be
9957 escaped. When nil, `org-link-escape-chars' is used.
9958 If optional argument MERGE is set, merge TABLE into
9959 `org-link-escape-chars'."
9960 (let ((characters-to-encode
9961 (cond ((null table) org-link-escape-chars)
9962 (merge (append org-link-escape-chars table))
9963 (t table))))
9964 (mapconcat
9965 (lambda (c)
9966 (if (or (memq c characters-to-encode)
9967 (and org-url-hexify-p (or (< c 32) (> c 126))))
9968 (mapconcat (lambda (e) (format "%%%.2X" e))
9969 (or (encode-coding-char c 'utf-8)
9970 (error "Unable to percent escape character: %c" c))
9972 (char-to-string c)))
9973 text "")))
9975 (defun org-link-unescape (str)
9976 "Unhex hexified Unicode parts in string STR.
9977 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9978 reciprocal of `org-link-escape', which see."
9979 (if (org-string-nw-p str)
9980 (replace-regexp-in-string
9981 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9982 str))
9984 (defun org-link-unescape-compound (hex)
9985 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9986 Note: this function also decodes single byte encodings like
9987 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9988 (save-match-data
9989 (let* ((bytes (cdr (split-string hex "%")))
9990 (ret "")
9991 (eat 0)
9992 (sum 0))
9993 (while bytes
9994 (let* ((val (string-to-number (pop bytes) 16))
9995 (shift-xor
9996 (if (= 0 eat)
9997 (cond
9998 ((>= val 252) (cons 6 252))
9999 ((>= val 248) (cons 5 248))
10000 ((>= val 240) (cons 4 240))
10001 ((>= val 224) (cons 3 224))
10002 ((>= val 192) (cons 2 192))
10003 (t (cons 0 0)))
10004 (cons 6 128))))
10005 (when (>= val 192) (setq eat (car shift-xor)))
10006 (setq val (logxor val (cdr shift-xor)))
10007 (setq sum (+ (lsh sum (car shift-xor)) val))
10008 (when (> eat 0) (setq eat (- eat 1)))
10009 (cond
10010 ((= 0 eat) ;multi byte
10011 (setq ret (concat ret (char-to-string sum)))
10012 (setq sum 0))
10013 ((not bytes) ; single byte(s)
10014 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10015 ret)))
10017 (defun org-link-unescape-single-byte-sequence (hex)
10018 "Unhexify hex-encoded single byte character sequences."
10019 (mapconcat (lambda (byte)
10020 (char-to-string (string-to-number byte 16)))
10021 (cdr (split-string hex "%")) ""))
10023 (defun org-fixup-message-id-for-http (s)
10024 "Replace special characters in a message id, so it can be used in an http query."
10025 (when (string-match "%" s)
10026 (setq s (mapconcat (lambda (c)
10027 (if (eq c ?%)
10028 "%25"
10029 (char-to-string c)))
10030 s "")))
10031 (while (string-match "<" s)
10032 (setq s (replace-match "%3C" t t s)))
10033 (while (string-match ">" s)
10034 (setq s (replace-match "%3E" t t s)))
10035 (while (string-match "@" s)
10036 (setq s (replace-match "%40" t t s)))
10039 (defun org-link-prettify (link)
10040 "Return a human-readable representation of LINK.
10041 The car of LINK must be a raw link.
10042 The cdr of LINK must be either a link description or nil."
10043 (let ((desc (or (cadr link) "<no description>")))
10044 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10045 "<" (car link) ">")))
10047 ;;;###autoload
10048 (defun org-insert-link-global ()
10049 "Insert a link like Org mode does.
10050 This command can be called in any mode to insert a link in Org syntax."
10051 (interactive)
10052 (org-load-modules-maybe)
10053 (org-run-like-in-org-mode 'org-insert-link))
10055 (defun org-insert-all-links (arg &optional pre post)
10056 "Insert all links in `org-stored-links'.
10057 When a universal prefix, do not delete the links from `org-stored-links'.
10058 When `ARG' is a number, insert the last N link(s).
10059 `PRE' and `POST' are optional arguments to define a string to
10060 prepend or to append."
10061 (interactive "P")
10062 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10063 (links (copy-sequence org-stored-links))
10064 (pr (or pre "- "))
10065 (po (or post "\n"))
10066 (cnt 1) l)
10067 (if (null org-stored-links)
10068 (message "No link to insert")
10069 (while (and (or (listp arg) (>= arg cnt))
10070 (setq l (if (listp arg)
10071 (pop links)
10072 (pop org-stored-links))))
10073 (setq cnt (1+ cnt))
10074 (insert pr)
10075 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10076 (insert po)))))
10078 (defun org-insert-last-stored-link (arg)
10079 "Insert the last link stored in `org-stored-links'."
10080 (interactive "p")
10081 (org-insert-all-links arg "" "\n"))
10083 (defun org-link-fontify-links-to-this-file ()
10084 "Fontify links to the current file in `org-stored-links'."
10085 (let ((f (buffer-file-name)) a b)
10086 (setq a (mapcar (lambda(l)
10087 (let ((ll (car l)))
10088 (when (and (string-match "^file:\\(.+\\)::" ll)
10089 (equal f (expand-file-name (match-string 1 ll))))
10090 ll)))
10091 org-stored-links))
10092 (when (featurep 'org-id)
10093 (setq b (mapcar (lambda(l)
10094 (let ((ll (car l)))
10095 (when (and (string-match "^id:\\(.+\\)$" ll)
10096 (equal f (expand-file-name
10097 (or (org-id-find-id-file
10098 (match-string 1 ll)) ""))))
10099 ll)))
10100 org-stored-links)))
10101 (mapcar (lambda(l)
10102 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10103 (delq nil (append a b)))))
10105 (defvar org--links-history nil)
10106 (defun org-insert-link (&optional complete-file link-location default-description)
10107 "Insert a link. At the prompt, enter the link.
10109 Completion can be used to insert any of the link protocol prefixes in use.
10111 The history can be used to select a link previously stored with
10112 `org-store-link'. When the empty string is entered (i.e. if you just
10113 press `RET' at the prompt), the link defaults to the most recently
10114 stored link. As `SPC' triggers completion in the minibuffer, you need to
10115 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10117 You will also be prompted for a description, and if one is given, it will
10118 be displayed in the buffer instead of the link.
10120 If there is already a link at point, this command will allow you to edit
10121 link and description parts.
10123 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10124 file name can be
10125 selected using completion. The path to the file will be relative to the
10126 current directory if the file is in the current directory or a subdirectory.
10127 Otherwise, the link will be the absolute path as completed in the minibuffer
10128 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10129 option `org-link-file-path-type'.
10131 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10132 absolute path even if the file is in
10133 the current directory or below.
10135 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10136 prefix negates `org-keep-stored-link-after-insertion'.
10138 If the LINK-LOCATION parameter is non-nil, this value will be used as
10139 the link location instead of reading one interactively.
10141 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10142 be used as the default description. Otherwise, if
10143 `org-make-link-description-function' is non-nil, this function
10144 will be called with the link target, and the result will be the
10145 default link description."
10146 (interactive "P")
10147 (let* ((wcf (current-window-configuration))
10148 (origbuf (current-buffer))
10149 (region (when (org-region-active-p)
10150 (buffer-substring (region-beginning) (region-end))))
10151 (remove (and region (list (region-beginning) (region-end))))
10152 (desc region)
10153 (link link-location)
10154 (abbrevs org-link-abbrev-alist-local)
10155 entry all-prefixes auto-desc)
10156 (cond
10157 (link-location) ; specified by arg, just use it.
10158 ((org-in-regexp org-bracket-link-regexp 1)
10159 ;; We do have a link at point, and we are going to edit it.
10160 (setq remove (list (match-beginning 0) (match-end 0)))
10161 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10162 (setq link (read-string "Link: "
10163 (org-link-unescape
10164 (match-string-no-properties 1)))))
10165 ((or (org-in-regexp org-angle-link-re)
10166 (org-in-regexp org-plain-link-re))
10167 ;; Convert to bracket link
10168 (setq remove (list (match-beginning 0) (match-end 0))
10169 link (read-string "Link: "
10170 (org-unbracket-string "<" ">" (match-string 0)))))
10171 ((member complete-file '((4) (16)))
10172 ;; Completing read for file names.
10173 (setq link (org-file-complete-link complete-file)))
10175 ;; Read link, with completion for stored links.
10176 (org-link-fontify-links-to-this-file)
10177 (org-switch-to-buffer-other-window "*Org Links*")
10178 (with-current-buffer "*Org Links*"
10179 (erase-buffer)
10180 (insert "Insert a link.
10181 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10182 (when org-stored-links
10183 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10184 (insert (mapconcat 'org-link-prettify
10185 (reverse org-stored-links) "\n")))
10186 (goto-char (point-min)))
10187 (let ((cw (selected-window)))
10188 (select-window (get-buffer-window "*Org Links*" 'visible))
10189 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10190 (unless (pos-visible-in-window-p (point-max))
10191 (org-fit-window-to-buffer))
10192 (and (window-live-p cw) (select-window cw)))
10193 (setq all-prefixes (append (mapcar 'car abbrevs)
10194 (mapcar 'car org-link-abbrev-alist)
10195 (org-link-types)))
10196 (unwind-protect
10197 ;; Fake a link history, containing the stored links.
10198 (let ((org--links-history
10199 (append (mapcar #'car org-stored-links)
10200 org-insert-link-history)))
10201 (setq link
10202 (org-completing-read
10203 "Link: "
10204 (append
10205 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10206 (mapcar #'car org-stored-links))
10207 nil nil nil
10208 'org--links-history
10209 (caar org-stored-links)))
10210 (unless (org-string-nw-p link) (user-error "No link selected"))
10211 (dolist (l org-stored-links)
10212 (when (equal link (cadr l))
10213 (setq link (car l))
10214 (setq auto-desc t)))
10215 (when (or (member link all-prefixes)
10216 (and (equal ":" (substring link -1))
10217 (member (substring link 0 -1) all-prefixes)
10218 (setq link (substring link 0 -1))))
10219 (setq link (with-current-buffer origbuf
10220 (org-link-try-special-completion link)))))
10221 (set-window-configuration wcf)
10222 (kill-buffer "*Org Links*"))
10223 (setq entry (assoc link org-stored-links))
10224 (or entry (push link org-insert-link-history))
10225 (setq desc (or desc (nth 1 entry)))))
10227 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10228 (not org-keep-stored-link-after-insertion))
10229 (setq org-stored-links (delq (assoc link org-stored-links)
10230 org-stored-links)))
10232 (when (and (string-match org-plain-link-re link)
10233 (not (string-match org-ts-regexp link)))
10234 ;; URL-like link, normalize the use of angular brackets.
10235 (setq link (org-unbracket-string "<" ">" link)))
10237 ;; Check if we are linking to the current file with a search
10238 ;; option If yes, simplify the link by using only the search
10239 ;; option.
10240 (when (and buffer-file-name
10241 (let ((case-fold-search nil))
10242 (string-match "\\`file:\\(.+?\\)::" link)))
10243 (let ((path (match-string-no-properties 1 link))
10244 (search (substring-no-properties link (match-end 0))))
10245 (save-match-data
10246 (when (equal (file-truename buffer-file-name) (file-truename path))
10247 ;; We are linking to this same file, with a search option
10248 (setq link search)))))
10250 ;; Check if we can/should use a relative path. If yes, simplify the link
10251 (let ((case-fold-search nil))
10252 (when (string-match "\\`\\(file\\|docview\\):" link)
10253 (let* ((type (match-string-no-properties 0 link))
10254 (path (substring-no-properties link (match-end 0)))
10255 (origpath path))
10256 (cond
10257 ((or (eq org-link-file-path-type 'absolute)
10258 (equal complete-file '(16)))
10259 (setq path (abbreviate-file-name (expand-file-name path))))
10260 ((eq org-link-file-path-type 'noabbrev)
10261 (setq path (expand-file-name path)))
10262 ((eq org-link-file-path-type 'relative)
10263 (setq path (file-relative-name path)))
10265 (save-match-data
10266 (if (string-match (concat "^" (regexp-quote
10267 (expand-file-name
10268 (file-name-as-directory
10269 default-directory))))
10270 (expand-file-name path))
10271 ;; We are linking a file with relative path name.
10272 (setq path (substring (expand-file-name path)
10273 (match-end 0)))
10274 (setq path (abbreviate-file-name (expand-file-name path)))))))
10275 (setq link (concat type path))
10276 (when (equal desc origpath)
10277 (setq desc path)))))
10279 (unless auto-desc
10280 (let ((initial-input
10281 (cond
10282 (default-description)
10283 ((not org-make-link-description-function) desc)
10284 (t (condition-case nil
10285 (funcall org-make-link-description-function link desc)
10286 (error
10287 (message "Can't get link description from `%s'"
10288 (symbol-name org-make-link-description-function))
10289 (sit-for 2)
10290 nil))))))
10291 (setq desc (read-string "Description: " initial-input))))
10293 (unless (string-match "\\S-" desc) (setq desc nil))
10294 (when remove (apply 'delete-region remove))
10295 (insert (org-make-link-string link desc))
10296 ;; Redisplay so as the new link has proper invisible characters.
10297 (sit-for 0)))
10299 (defun org-link-try-special-completion (type)
10300 "If there is completion support for link type TYPE, offer it."
10301 (let ((fun (org-link-get-parameter type :complete)))
10302 (if (functionp fun)
10303 (funcall fun)
10304 (read-string "Link (no completion support): " (concat type ":")))))
10306 (defun org-file-complete-link (&optional arg)
10307 "Create a file link using completion."
10308 (let ((file (read-file-name "File: "))
10309 (pwd (file-name-as-directory (expand-file-name ".")))
10310 (pwd1 (file-name-as-directory (abbreviate-file-name
10311 (expand-file-name ".")))))
10312 (cond ((equal arg '(16))
10313 (concat "file:"
10314 (abbreviate-file-name (expand-file-name file))))
10315 ((string-match
10316 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10317 (concat "file:" (match-string 1 file)))
10318 ((string-match
10319 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10320 (expand-file-name file))
10321 (concat "file:"
10322 (match-string 1 (expand-file-name file))))
10323 (t (concat "file:" file)))))
10325 (defun org-completing-read (&rest args)
10326 "Completing-read with SPACE being a normal character."
10327 (let ((enable-recursive-minibuffers t)
10328 (minibuffer-local-completion-map
10329 (copy-keymap minibuffer-local-completion-map)))
10330 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10331 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10332 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10333 'org-time-stamp-inactive)
10334 (apply #'completing-read args)))
10336 ;;; Opening/following a link
10338 (defvar org-link-search-failed nil)
10340 (defvar org-open-link-functions nil
10341 "Hook for functions finding a plain text link.
10342 These functions must take a single argument, the link content.
10343 They will be called for links that look like [[link text][description]]
10344 when LINK TEXT does not have a protocol like \"http:\" and does not look
10345 like a filename (e.g. \"./blue.png\").
10347 These functions will be called *before* Org attempts to resolve the
10348 link by doing text searches in the current buffer - so if you want a
10349 link \"[[target]]\" to still find \"<<target>>\", your function should
10350 handle this as a special case.
10352 When the function does handle the link, it must return a non-nil value.
10353 If it decides that it is not responsible for this link, it must return
10354 nil to indicate that that Org can continue with other options like
10355 exact and fuzzy text search.")
10357 (defun org-next-link (&optional search-backward)
10358 "Move forward to the next link.
10359 If the link is in hidden text, expose it."
10360 (interactive "P")
10361 (when (and org-link-search-failed (eq this-command last-command))
10362 (goto-char (point-min))
10363 (message "Link search wrapped back to beginning of buffer"))
10364 (setq org-link-search-failed nil)
10365 (let* ((pos (point))
10366 (ct (org-context))
10367 (a (assq :link ct))
10368 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10369 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10370 ((looking-at org-any-link-re)
10371 ;; Don't stay stuck at link without an org-link face
10372 (forward-char (if search-backward -1 1))))
10373 (if (funcall srch-fun org-any-link-re nil t)
10374 (progn
10375 (goto-char (match-beginning 0))
10376 (when (org-invisible-p) (org-show-context)))
10377 (goto-char pos)
10378 (setq org-link-search-failed t)
10379 (message "No further link found"))))
10381 (defun org-previous-link ()
10382 "Move backward to the previous link.
10383 If the link is in hidden text, expose it."
10384 (interactive)
10385 (funcall 'org-next-link t))
10387 (defun org-translate-link (s)
10388 "Translate a link string if a translation function has been defined."
10389 (with-temp-buffer
10390 (insert (org-trim s))
10391 (org-trim (org-element-interpret-data (org-element-context)))))
10393 (defun org-translate-link-from-planner (type path)
10394 "Translate a link from Emacs Planner syntax so that Org can follow it.
10395 This is still an experimental function, your mileage may vary."
10396 (cond
10397 ((member type '("http" "https" "news" "ftp"))
10398 ;; standard Internet links are the same.
10399 nil)
10400 ((and (equal type "irc") (string-match "^//" path))
10401 ;; Planner has two / at the beginning of an irc link, we have 1.
10402 ;; We should have zero, actually....
10403 (setq path (substring path 1)))
10404 ((and (equal type "lisp") (string-match "^/" path))
10405 ;; Planner has a slash, we do not.
10406 (setq type "elisp" path (substring path 1)))
10407 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10408 ;; A typical message link. Planner has the id after the final slash,
10409 ;; we separate it with a hash mark
10410 (setq path (concat (match-string 1 path) "#"
10411 (org-unbracket-string "<" ">" (match-string 2 path))))))
10412 (cons type path))
10414 (defun org-find-file-at-mouse (ev)
10415 "Open file link or URL at mouse."
10416 (interactive "e")
10417 (mouse-set-point ev)
10418 (org-open-at-point 'in-emacs))
10420 (defun org-open-at-mouse (ev)
10421 "Open file link or URL at mouse.
10422 See the docstring of `org-open-file' for details."
10423 (interactive "e")
10424 (mouse-set-point ev)
10425 (when (eq major-mode 'org-agenda-mode)
10426 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10427 (org-open-at-point))
10429 (defvar org-window-config-before-follow-link nil
10430 "The window configuration before following a link.
10431 This is saved in case the need arises to restore it.")
10433 ;;;###autoload
10434 (defun org-open-at-point-global ()
10435 "Follow a link or time-stamp like Org mode does.
10436 This command can be called in any mode to follow an external link
10437 or a time-stamp that has Org mode syntax. Its behavior is
10438 undefined when called on internal links (e.g., fuzzy links).
10439 Raise an error when there is nothing to follow. "
10440 (interactive)
10441 (cond ((org-in-regexp org-any-link-re)
10442 (org-open-link-from-string (match-string-no-properties 0)))
10443 ((or (org-in-regexp org-ts-regexp-both nil t)
10444 (org-in-regexp org-tsr-regexp-both nil t))
10445 (org-follow-timestamp-link))
10446 (t (user-error "No link found"))))
10448 ;;;###autoload
10449 (defun org-open-link-from-string (s &optional arg reference-buffer)
10450 "Open a link in the string S, as if it was in Org mode."
10451 (interactive "sLink: \nP")
10452 (let ((reference-buffer (or reference-buffer (current-buffer))))
10453 (with-temp-buffer
10454 (let ((org-inhibit-startup (not reference-buffer)))
10455 (org-mode)
10456 (insert s)
10457 (goto-char (point-min))
10458 (when reference-buffer
10459 (setq org-link-abbrev-alist-local
10460 (with-current-buffer reference-buffer
10461 org-link-abbrev-alist-local)))
10462 (org-open-at-point arg reference-buffer)))))
10464 (defvar org-open-at-point-functions nil
10465 "Hook that is run when following a link at point.
10467 Functions in this hook must return t if they identify and follow
10468 a link at point. If they don't find anything interesting at point,
10469 they must return nil.")
10471 (defvar org-link-search-inhibit-query nil)
10472 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10473 (defun org--open-doi-link (path)
10474 "Open a \"doi\" type link.
10475 PATH is a the path to search for, as a string."
10476 (browse-url (url-encode-url (concat org-doi-server-url path))))
10478 (defun org--open-elisp-link (path)
10479 "Open a \"elisp\" type link.
10480 PATH is the sexp to evaluate, as a string."
10481 (let ((cmd path))
10482 (if (or (and (org-string-nw-p
10483 org-confirm-elisp-link-not-regexp)
10484 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10485 (not org-confirm-elisp-link-function)
10486 (funcall org-confirm-elisp-link-function
10487 (format "Execute \"%s\" as elisp? "
10488 (org-add-props cmd nil 'face 'org-warning))))
10489 (message "%s => %s" cmd
10490 (if (eq (string-to-char cmd) ?\()
10491 (eval (read cmd))
10492 (call-interactively (read cmd))))
10493 (user-error "Abort"))))
10495 (defun org--open-help-link (path)
10496 "Open a \"help\" type link.
10497 PATH is a symbol name, as a string."
10498 (pcase (intern path)
10499 ((and (pred fboundp) variable) (describe-function variable))
10500 ((and (pred boundp) function) (describe-variable function))
10501 (name (user-error "Unknown function or variable: %s" name))))
10503 (defun org--open-shell-link (path)
10504 "Open a \"shell\" type link.
10505 PATH is the command to execute, as a string."
10506 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10507 (cmd path))
10508 (if (or (and (org-string-nw-p
10509 org-confirm-shell-link-not-regexp)
10510 (string-match
10511 org-confirm-shell-link-not-regexp cmd))
10512 (not org-confirm-shell-link-function)
10513 (funcall org-confirm-shell-link-function
10514 (format "Execute \"%s\" in shell? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (progn
10518 (message "Executing %s" cmd)
10519 (shell-command cmd buf)
10520 (when (featurep 'midnight)
10521 (setq clean-buffer-list-kill-buffer-names
10522 (cons (buffer-name buf)
10523 clean-buffer-list-kill-buffer-names))))
10524 (user-error "Abort"))))
10526 (defun org-open-at-point (&optional arg reference-buffer)
10527 "Open link, timestamp, footnote or tags at point.
10529 When point is on a link, follow it. Normally, files will be
10530 opened by an appropriate application. If the optional prefix
10531 argument ARG is non-nil, Emacs will visit the file. With
10532 a double prefix argument, try to open outside of Emacs, in the
10533 application the system uses for this file type.
10535 When point is on a timestamp, open the agenda at the day
10536 specified.
10538 When point is a footnote definition, move to the first reference
10539 found. If it is on a reference, move to the associated
10540 definition.
10542 When point is on a headline, display a list of every link in the
10543 entry, so it is possible to pick one, or all, of them. If point
10544 is on a tag, call `org-tags-view' instead.
10546 When optional argument REFERENCE-BUFFER is non-nil, it should
10547 specify a buffer from where the link search should happen. This
10548 is used internally by `org-open-link-from-string'.
10550 On top of syntactically correct links, this function will also
10551 try to open links and time-stamps in comments, example
10552 blocks... i.e., whenever point is on something looking like
10553 a timestamp or a link."
10554 (interactive "P")
10555 ;; On a code block, open block's results.
10556 (unless (call-interactively 'org-babel-open-src-block-result)
10557 (org-load-modules-maybe)
10558 (setq org-window-config-before-follow-link (current-window-configuration))
10559 (org-remove-occur-highlights nil nil t)
10560 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10561 (let* ((context
10562 ;; Only consider supported types, even if they are not
10563 ;; the closest one.
10564 (org-element-lineage
10565 (org-element-context)
10566 '(clock footnote-definition footnote-reference headline
10567 inlinetask link timestamp)
10569 (type (org-element-type context))
10570 (value (org-element-property :value context)))
10571 (cond
10572 ;; On a headline or an inlinetask, but not on a timestamp,
10573 ;; a link, a footnote reference.
10574 ((memq type '(headline inlinetask))
10575 (org-match-line org-complex-heading-regexp)
10576 (if (and (match-beginning 5)
10577 (>= (point) (match-beginning 5))
10578 (< (point) (match-end 5)))
10579 ;; On tags.
10580 (org-tags-view arg (substring (match-string 5) 0 -1))
10581 ;; Not on tags.
10582 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10583 (`(nil . ,_)
10584 (require 'org-attach)
10585 (org-attach-reveal 'if-exists))
10586 (`(,links . ,links-end)
10587 (dolist (link (if (stringp links) (list links) links))
10588 (search-forward link nil links-end)
10589 (goto-char (match-beginning 0))
10590 (org-open-at-point))))))
10591 ;; On a footnote reference or at definition's label.
10592 ((or (eq type 'footnote-reference)
10593 (and (eq type 'footnote-definition)
10594 (save-excursion
10595 ;; Do not validate action when point is on the
10596 ;; spaces right after the footnote label, in
10597 ;; order to be on par with behaviour on links.
10598 (skip-chars-forward " \t")
10599 (let ((begin
10600 (org-element-property :contents-begin context)))
10601 (if begin (< (point) begin)
10602 (= (org-element-property :post-affiliated context)
10603 (line-beginning-position)))))))
10604 (org-footnote-action))
10605 ;; No valid context. Ignore catch-all types like `headline'.
10606 ;; If point is on something looking like a link or
10607 ;; a time-stamp, try opening it. It may be useful in
10608 ;; comments, example blocks...
10609 ((memq type '(footnote-definition headline inlinetask nil))
10610 (call-interactively #'org-open-at-point-global))
10611 ;; On a clock line, make sure point is on the timestamp
10612 ;; before opening it.
10613 ((and (eq type 'clock)
10614 value
10615 (>= (point) (org-element-property :begin value))
10616 (<= (point) (org-element-property :end value)))
10617 (org-follow-timestamp-link))
10618 ;; Do nothing on white spaces after an object.
10619 ((>= (point)
10620 (save-excursion
10621 (goto-char (org-element-property :end context))
10622 (skip-chars-backward " \t")
10623 (point)))
10624 (user-error "No link found"))
10625 ((eq type 'timestamp) (org-follow-timestamp-link))
10626 ((eq type 'link)
10627 (let ((type (org-element-property :type context))
10628 (path (org-link-unescape (org-element-property :path context))))
10629 ;; Switch back to REFERENCE-BUFFER needed when called in
10630 ;; a temporary buffer through `org-open-link-from-string'.
10631 (with-current-buffer (or reference-buffer (current-buffer))
10632 (cond
10633 ((equal type "file")
10634 (if (string-match "[*?{]" (file-name-nondirectory path))
10635 (dired path)
10636 ;; Look into `org-link-parameters' in order to find
10637 ;; a DEDICATED-FUNCTION to open file. The function
10638 ;; will be applied on raw link instead of parsed
10639 ;; link due to the limitation in `org-add-link-type'
10640 ;; ("open" function called with a single argument).
10641 ;; If no such function is found, fallback to
10642 ;; `org-open-file'.
10643 (let* ((option (org-element-property :search-option context))
10644 (app (org-element-property :application context))
10645 (dedicated-function
10646 (org-link-get-parameter
10647 (if app (concat type "+" app) type)
10648 :follow)))
10649 (if dedicated-function
10650 (funcall dedicated-function
10651 (concat path
10652 (and option (concat "::" option))))
10653 (apply #'org-open-file
10654 path
10655 (cond (arg)
10656 ((equal app "emacs") 'emacs)
10657 ((equal app "sys") 'system))
10658 (cond ((not option) nil)
10659 ((string-match-p "\\`[0-9]+\\'" option)
10660 (list (string-to-number option)))
10661 (t (list nil
10662 (org-link-unescape option)))))))))
10663 ((functionp (org-link-get-parameter type :follow))
10664 (funcall (org-link-get-parameter type :follow) path))
10665 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10666 (unless (run-hook-with-args-until-success
10667 'org-open-link-functions path)
10668 (if (not arg) (org-mark-ring-push)
10669 (switch-to-buffer-other-window
10670 (org-get-buffer-for-internal-link (current-buffer))))
10671 (let ((destination
10672 (org-with-wide-buffer
10673 (if (equal type "radio")
10674 (org-search-radio-target
10675 (org-element-property :path context))
10676 (org-link-search
10677 (if (member type '("custom-id" "coderef"))
10678 (org-element-property :raw-link context)
10679 path)
10680 ;; Prevent fuzzy links from matching
10681 ;; themselves.
10682 (and (equal type "fuzzy")
10683 (+ 2 (org-element-property :begin context)))))
10684 (point))))
10685 (unless (and (<= (point-min) destination)
10686 (>= (point-max) destination))
10687 (widen))
10688 (goto-char destination))))
10689 (t (browse-url-at-point))))))
10690 (t (user-error "No link found")))))
10691 (run-hook-with-args 'org-follow-link-hook)))
10693 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10694 "Offer links in the current entry and return the selected link.
10695 If there is only one link, return it.
10696 If NTH is an integer, return the NTH link found.
10697 If ZERO is a string, check also this string for a link, and if
10698 there is one, return it."
10699 (with-current-buffer buffer
10700 (org-with-wide-buffer
10701 (goto-char marker)
10702 (let ((cnt ?0)
10703 have-zero end links link c)
10704 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10705 (push (match-string 0 zero) links)
10706 (setq cnt (1- cnt) have-zero t))
10707 (save-excursion
10708 (org-back-to-heading t)
10709 (setq end (save-excursion (outline-next-heading) (point)))
10710 (while (re-search-forward org-any-link-re end t)
10711 (push (match-string 0) links))
10712 (setq links (org-uniquify (reverse links))))
10713 (cond
10714 ((null links)
10715 (message "No links"))
10716 ((equal (length links) 1)
10717 (setq link (car links)))
10718 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10719 (setq link (nth (if have-zero nth (1- nth)) links)))
10720 (t ; we have to select a link
10721 (save-excursion
10722 (save-window-excursion
10723 (delete-other-windows)
10724 (with-output-to-temp-buffer "*Select Link*"
10725 (dolist (l links)
10726 (cond
10727 ((not (string-match org-bracket-link-regexp l))
10728 (princ (format "[%c] %s\n" (cl-incf cnt)
10729 (org-unbracket-string "<" ">" l))))
10730 ((match-end 3)
10731 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10732 (match-string 3 l) (match-string 1 l))))
10733 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10734 (match-string 1 l)))))))
10735 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10736 (message "Select link to open, RET to open all:")
10737 (setq c (read-char-exclusive))
10738 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10739 (when (equal c ?q) (user-error "Abort"))
10740 (if (equal c ?\C-m)
10741 (setq link links)
10742 (setq nth (- c ?0))
10743 (when have-zero (setq nth (1+ nth)))
10744 (unless (and (integerp nth) (>= (length links) nth))
10745 (user-error "Invalid link selection"))
10746 (setq link (nth (1- nth) links)))))
10747 (cons link end)))))
10749 ;; TODO: These functions are deprecated since `org-open-at-point'
10750 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10751 (defun org-open-file-with-system (path)
10752 "Open file at PATH using the system way of opening it."
10753 (org-open-file path 'system))
10754 (defun org-open-file-with-emacs (path)
10755 "Open file at PATH in Emacs."
10756 (org-open-file path 'emacs))
10759 ;;; File search
10761 (defvar org-create-file-search-functions nil
10762 "List of functions to construct the right search string for a file link.
10763 These functions are called in turn with point at the location to
10764 which the link should point.
10766 A function in the hook should first test if it would like to
10767 handle this file type, for example by checking the `major-mode'
10768 or the file extension. If it decides not to handle this file, it
10769 should just return nil to give other functions a chance. If it
10770 does handle the file, it must return the search string to be used
10771 when following the link. The search string will be part of the
10772 file link, given after a double colon, and `org-open-at-point'
10773 will automatically search for it. If special measures must be
10774 taken to make the search successful, another function should be
10775 added to the companion hook `org-execute-file-search-functions',
10776 which see.
10778 A function in this hook may also use `setq' to set the variable
10779 `description' to provide a suggestion for the descriptive text to
10780 be used for this link when it gets inserted into an Org buffer
10781 with \\[org-insert-link].")
10783 (defvar org-execute-file-search-functions nil
10784 "List of functions to execute a file search triggered by a link.
10786 Functions added to this hook must accept a single argument, the
10787 search string that was part of the file link, the part after the
10788 double colon. The function must first check if it would like to
10789 handle this search, for example by checking the `major-mode' or
10790 the file extension. If it decides not to handle this search, it
10791 should just return nil to give other functions a chance. If it
10792 does handle the search, it must return a non-nil value to keep
10793 other functions from trying.
10795 Each function can access the current prefix argument through the
10796 variable `current-prefix-arg'. Note that a single prefix is used
10797 to force opening a link in Emacs, so it may be good to only use a
10798 numeric or double prefix to guide the search function.
10800 In case this is needed, a function in this hook can also restore
10801 the window configuration before `org-open-at-point' was called using:
10803 (set-window-configuration org-window-config-before-follow-link)")
10805 (defun org-search-radio-target (target)
10806 "Search a radio target matching TARGET in current buffer.
10807 White spaces are not significant."
10808 (let ((re (format "<<<%s>>>"
10809 (mapconcat #'regexp-quote
10810 (split-string target)
10811 "[ \t]+\\(?:\n[ \t]*\\)?")))
10812 (origin (point)))
10813 (goto-char (point-min))
10814 (catch :radio-match
10815 (while (re-search-forward re nil t)
10816 (backward-char)
10817 (let ((object (org-element-context)))
10818 (when (eq (org-element-type object) 'radio-target)
10819 (goto-char (org-element-property :begin object))
10820 (org-show-context 'link-search)
10821 (throw :radio-match nil))))
10822 (goto-char origin)
10823 (user-error "No match for radio target: %s" target))))
10825 (defun org-link-search (s &optional avoid-pos stealth)
10826 "Search for a search string S.
10828 If S starts with \"#\", it triggers a custom ID search.
10830 If S is enclosed within parenthesis, it initiates a coderef
10831 search.
10833 If S is surrounded by forward slashes, it is interpreted as
10834 a regular expression. In Org mode files, this will create an
10835 `org-occur' sparse tree. In ordinary files, `occur' will be used
10836 to list matches. If the current buffer is in `dired-mode', grep
10837 will be used to search in all files.
10839 When AVOID-POS is given, ignore matches near that position.
10841 When optional argument STEALTH is non-nil, do not modify
10842 visibility around point, thus ignoring `org-show-context-detail'
10843 variable.
10845 Search is case-insensitive and ignores white spaces. Return type
10846 of matched result, which is either `dedicated' or `fuzzy'."
10847 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10848 (let* ((case-fold-search t)
10849 (origin (point))
10850 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10851 (starred (eq (string-to-char normalized) ?*))
10852 (words (split-string (if starred (substring s 1) s)))
10853 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10854 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10855 type)
10856 (cond
10857 ;; Check if there are any special search functions.
10858 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10859 ((eq (string-to-char s) ?#)
10860 ;; Look for a custom ID S if S starts with "#".
10861 (let* ((id (substring normalized 1))
10862 (match (org-find-property "CUSTOM_ID" id)))
10863 (if match (progn (goto-char match) (setf type 'dedicated))
10864 (error "No match for custom ID: %s" id))))
10865 ((string-match "\\`(\\(.*\\))\\'" normalized)
10866 ;; Look for coderef targets if S is enclosed within parenthesis.
10867 (let ((coderef (match-string-no-properties 1 normalized))
10868 (re (substring s-single-re 1 -1)))
10869 (goto-char (point-min))
10870 (catch :coderef-match
10871 (while (re-search-forward re nil t)
10872 (let ((element (org-element-at-point)))
10873 (when (and (memq (org-element-type element)
10874 '(example-block src-block))
10875 ;; Build proper regexp according to current
10876 ;; block's label format.
10877 (let ((label-fmt
10878 (regexp-quote
10879 (or (org-element-property :label-fmt element)
10880 org-coderef-label-format))))
10881 (save-excursion
10882 (beginning-of-line)
10883 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10884 (format label-fmt coderef))))))
10885 (setq type 'dedicated)
10886 (goto-char (match-beginning 1))
10887 (throw :coderef-match nil))))
10888 (goto-char origin)
10889 (error "No match for coderef: %s" coderef))))
10890 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10891 ;; Look for a regular expression.
10892 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10893 (match-string 1 s)))
10894 ;; From here, we handle fuzzy links.
10896 ;; Look for targets, only if not in a headline search.
10897 ((and (not starred)
10898 (let ((target (format "<<%s>>" s-multi-re)))
10899 (catch :target-match
10900 (goto-char (point-min))
10901 (while (re-search-forward target nil t)
10902 (backward-char)
10903 (let ((context (org-element-context)))
10904 (when (eq (org-element-type context) 'target)
10905 (setq type 'dedicated)
10906 (goto-char (org-element-property :begin context))
10907 (throw :target-match t))))
10908 nil))))
10909 ;; Look for elements named after S, only if not in a headline
10910 ;; search.
10911 ((and (not starred)
10912 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10913 (catch :name-match
10914 (goto-char (point-min))
10915 (while (re-search-forward name nil t)
10916 (let ((element (org-element-at-point)))
10917 (when (equal words
10918 (split-string
10919 (org-element-property :name element)))
10920 (setq type 'dedicated)
10921 (beginning-of-line)
10922 (throw :name-match t))))
10923 nil))))
10924 ;; Regular text search. Prefer headlines in Org mode buffers.
10925 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10926 ;; statistics cookies and tags.
10927 ((and (derived-mode-p 'org-mode)
10928 (let ((title-re
10929 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10930 org-outline-regexp-bol
10931 org-comment-string
10932 (mapconcat #'regexp-quote words ".+")))
10933 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10934 (comment-re (eval-when-compile
10935 (format "\\`%s[ \t]+" org-comment-string))))
10936 (goto-char (point-min))
10937 (catch :found
10938 (while (re-search-forward title-re nil t)
10939 (when (equal words
10940 (split-string
10941 (replace-regexp-in-string
10942 cookie-re ""
10943 (replace-regexp-in-string
10944 comment-re "" (org-get-heading t t t)))))
10945 (throw :found t)))
10946 nil)))
10947 (beginning-of-line)
10948 (setq type 'dedicated))
10949 ;; Offer to create non-existent headline depending on
10950 ;; `org-link-search-must-match-exact-headline'.
10951 ((and (derived-mode-p 'org-mode)
10952 (not org-link-search-inhibit-query)
10953 (eq org-link-search-must-match-exact-headline 'query-to-create)
10954 (yes-or-no-p "No match - create this as a new heading? "))
10955 (goto-char (point-max))
10956 (unless (bolp) (newline))
10957 (org-insert-heading nil t t)
10958 (insert s "\n")
10959 (beginning-of-line 0))
10960 ;; Only headlines are looked after. No need to process
10961 ;; further: throw an error.
10962 ((and (derived-mode-p 'org-mode)
10963 (or starred org-link-search-must-match-exact-headline))
10964 (goto-char origin)
10965 (error "No match for fuzzy expression: %s" normalized))
10966 ;; Regular text search.
10967 ((catch :fuzzy-match
10968 (goto-char (point-min))
10969 (while (re-search-forward s-multi-re nil t)
10970 ;; Skip match if it contains AVOID-POS or it is included in
10971 ;; a link with a description but outside the description.
10972 (unless (or (and avoid-pos
10973 (<= (match-beginning 0) avoid-pos)
10974 (> (match-end 0) avoid-pos))
10975 (and (save-match-data
10976 (org-in-regexp org-bracket-link-regexp))
10977 (match-beginning 3)
10978 (or (> (match-beginning 3) (point))
10979 (<= (match-end 3) (point)))
10980 (org-element-lineage
10981 (save-match-data (org-element-context))
10982 '(link) t)))
10983 (goto-char (match-beginning 0))
10984 (setq type 'fuzzy)
10985 (throw :fuzzy-match t)))
10986 nil))
10987 ;; All failed. Throw an error.
10988 (t (goto-char origin)
10989 (error "No match for fuzzy expression: %s" normalized)))
10990 ;; Disclose surroundings of match, if appropriate.
10991 (when (and (derived-mode-p 'org-mode) (not stealth))
10992 (org-show-context 'link-search))
10993 type))
10995 (defun org-get-buffer-for-internal-link (buffer)
10996 "Return a buffer to be used for displaying the link target of internal links."
10997 (cond
10998 ((not org-display-internal-link-with-indirect-buffer)
10999 buffer)
11000 ((string-suffix-p "(Clone)" (buffer-name buffer))
11001 (message "Buffer is already a clone, not making another one")
11002 ;; we also do not modify visibility in this case
11003 buffer)
11004 (t ; make a new indirect buffer for displaying the link
11005 (let* ((bn (buffer-name buffer))
11006 (ibn (concat bn "(Clone)"))
11007 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11008 (with-current-buffer ib (org-overview))
11009 ib))))
11011 (defun org-do-occur (regexp &optional cleanup)
11012 "Call the Emacs command `occur'.
11013 If CLEANUP is non-nil, remove the printout of the regular expression
11014 in the *Occur* buffer. This is useful if the regex is long and not useful
11015 to read."
11016 (occur regexp)
11017 (when cleanup
11018 (let ((cwin (selected-window)) win beg end)
11019 (when (setq win (get-buffer-window "*Occur*"))
11020 (select-window win))
11021 (goto-char (point-min))
11022 (when (re-search-forward "match[a-z]+" nil t)
11023 (setq beg (match-end 0))
11024 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11025 (setq end (1- (match-beginning 0)))))
11026 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11027 (goto-char (point-min))
11028 (select-window cwin))))
11030 ;;; The mark ring for links jumps
11032 (defvar org-mark-ring nil
11033 "Mark ring for positions before jumps in Org mode.")
11034 (defvar org-mark-ring-last-goto nil
11035 "Last position in the mark ring used to go back.")
11036 ;; Fill and close the ring
11037 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11038 (dotimes (_ org-mark-ring-length)
11039 (push (make-marker) org-mark-ring))
11040 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11041 org-mark-ring)
11043 (defun org-mark-ring-push (&optional pos buffer)
11044 "Put the current position or POS into the mark ring and rotate it."
11045 (interactive)
11046 (setq pos (or pos (point)))
11047 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11048 (move-marker (car org-mark-ring)
11049 (or pos (point))
11050 (or buffer (current-buffer)))
11051 (message "%s"
11052 (substitute-command-keys
11053 "Position saved to mark ring, go back with \
11054 `\\[org-mark-ring-goto]'.")))
11056 (defun org-mark-ring-goto (&optional n)
11057 "Jump to the previous position in the mark ring.
11058 With prefix arg N, jump back that many stored positions. When
11059 called several times in succession, walk through the entire ring.
11060 Org mode commands jumping to a different position in the current file,
11061 or to another Org file, automatically push the old position onto the ring."
11062 (interactive "p")
11063 (let (p m)
11064 (if (eq last-command this-command)
11065 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11066 (setq p org-mark-ring))
11067 (setq org-mark-ring-last-goto p)
11068 (setq m (car p))
11069 (pop-to-buffer-same-window (marker-buffer m))
11070 (goto-char m)
11071 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11073 (defun org-add-angle-brackets (s)
11074 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11075 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11078 ;;; Following specific links
11080 (defvar org-agenda-buffer-tmp-name)
11081 (defvar org-agenda-start-on-weekday)
11082 (defun org-follow-timestamp-link ()
11083 "Open an agenda view for the time-stamp date/range at point."
11084 (cond
11085 ((org-at-date-range-p t)
11086 (let ((org-agenda-start-on-weekday)
11087 (t1 (match-string 1))
11088 (t2 (match-string 2)) tt1 tt2)
11089 (setq tt1 (time-to-days (org-time-string-to-time t1))
11090 tt2 (time-to-days (org-time-string-to-time t2)))
11091 (let ((org-agenda-buffer-tmp-name
11092 (format "*Org Agenda(a:%s)"
11093 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11094 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11095 ((org-at-timestamp-p 'lax)
11096 (let ((org-agenda-buffer-tmp-name
11097 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11098 (org-agenda-list nil (time-to-days (org-time-string-to-time
11099 (substring (match-string 1) 0 10)))
11100 1)))
11101 (t (error "This should not happen"))))
11104 ;;; Following file links
11105 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11106 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11107 (declare-function mailcap-mime-info
11108 "mailcap" (string &optional request no-decode))
11109 (defvar org-wait nil)
11110 (defun org-open-file (path &optional in-emacs line search)
11111 "Open the file at PATH.
11112 First, this expands any special file name abbreviations. Then the
11113 configuration variable `org-file-apps' is checked if it contains an
11114 entry for this file type, and if yes, the corresponding command is launched.
11116 If no application is found, Emacs simply visits the file.
11118 With optional prefix argument IN-EMACS, Emacs will visit the file.
11119 With a double \\[universal-argument] \\[universal-argument] \
11120 prefix arg, Org tries to avoid opening in Emacs
11121 and to use an external application to visit the file.
11123 Optional LINE specifies a line to go to, optional SEARCH a string
11124 to search for. If LINE or SEARCH is given, the file will be
11125 opened in Emacs, unless an entry from org-file-apps that makes
11126 use of groups in a regexp matches.
11128 If you want to change the way frames are used when following a
11129 link, please customize `org-link-frame-setup'.
11131 If the file does not exist, an error is thrown."
11132 (let* ((file (if (equal path "")
11133 buffer-file-name
11134 (substitute-in-file-name (expand-file-name path))))
11135 (file-apps (append org-file-apps (org-default-apps)))
11136 (apps (cl-remove-if
11137 'org-file-apps-entry-match-against-dlink-p file-apps))
11138 (apps-dlink (cl-remove-if-not
11139 'org-file-apps-entry-match-against-dlink-p file-apps))
11140 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11141 (dirp (unless remp (file-directory-p file)))
11142 (file (if (and dirp org-open-directory-means-index-dot-org)
11143 (concat (file-name-as-directory file) "index.org")
11144 file))
11145 (a-m-a-p (assq 'auto-mode apps))
11146 (dfile (downcase file))
11147 ;; Reconstruct the original link from the PATH, LINE and
11148 ;; SEARCH args.
11149 (link (cond (line (concat file "::" (number-to-string line)))
11150 (search (concat file "::" search))
11151 (t file)))
11152 (dlink (downcase link))
11153 (ext
11154 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11155 (match-string 1 dfile)))
11156 (save-position-maybe
11157 (let ((old-buffer (current-buffer))
11158 (old-pos (point))
11159 (old-mode major-mode))
11160 (lambda ()
11161 (and (derived-mode-p 'org-mode)
11162 (eq old-mode 'org-mode)
11163 (or (not (eq old-buffer (current-buffer)))
11164 (not (eq old-pos (point))))
11165 (org-mark-ring-push old-pos old-buffer)))))
11166 cmd link-match-data)
11167 (cond
11168 ((member in-emacs '((16) system))
11169 (setq cmd (cdr (assq 'system apps))))
11170 (in-emacs (setq cmd 'emacs))
11172 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11173 (and dirp (cdr (assq 'directory apps)))
11174 ;; First, try matching against apps-dlink if we
11175 ;; get a match here, store the match data for
11176 ;; later.
11177 (let ((match (assoc-default dlink apps-dlink
11178 'string-match)))
11179 (if match
11180 (progn (setq link-match-data (match-data))
11181 match)
11182 (progn (setq in-emacs (or in-emacs line search))
11183 nil))) ; if we have no match in apps-dlink,
11184 ; always open the file in emacs if line or search
11185 ; is given (for backwards compatibility)
11186 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11187 'string-match)
11188 (cdr (assoc ext apps))
11189 (cdr (assq t apps))))))
11190 (when (eq cmd 'system)
11191 (setq cmd (cdr (assq 'system apps))))
11192 (when (eq cmd 'default)
11193 (setq cmd (cdr (assoc t apps))))
11194 (when (eq cmd 'mailcap)
11195 (require 'mailcap)
11196 (mailcap-parse-mailcaps)
11197 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11198 (command (mailcap-mime-info mime-type)))
11199 (if (stringp command)
11200 (setq cmd command)
11201 (setq cmd 'emacs))))
11202 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11203 (not (file-exists-p file))
11204 (not org-open-non-existing-files))
11205 (user-error "No such file: %s" file))
11206 (cond
11207 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11208 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11209 (while (string-match "['\"]%s['\"]" cmd)
11210 (setq cmd (replace-match "%s" t t cmd)))
11211 (setq cmd (replace-regexp-in-string
11212 "%s"
11213 (shell-quote-argument (convert-standard-filename file))
11215 nil t))
11217 ;; Replace "%1", "%2" etc. in command with group matches from regex
11218 (save-match-data
11219 (let ((match-index 1)
11220 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11221 (set-match-data link-match-data)
11222 (while (<= match-index number-of-groups)
11223 (let ((regex (concat "%" (number-to-string match-index)))
11224 (replace-with (match-string match-index dlink)))
11225 (while (string-match regex cmd)
11226 (setq cmd (replace-match replace-with t t cmd))))
11227 (setq match-index (+ match-index 1)))))
11229 (save-window-excursion
11230 (message "Running %s...done" cmd)
11231 (start-process-shell-command cmd nil cmd)
11232 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11233 ((or (stringp cmd)
11234 (eq cmd 'emacs))
11235 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11236 (widen)
11237 (cond (line (org-goto-line line)
11238 (when (derived-mode-p 'org-mode) (org-reveal)))
11239 (search (condition-case err
11240 (org-link-search search)
11241 ;; Save position before error-ing out so user
11242 ;; can easily move back to the original buffer.
11243 (error (funcall save-position-maybe)
11244 (error (nth 1 err)))))))
11245 ((functionp cmd)
11246 (save-match-data
11247 (set-match-data link-match-data)
11248 (condition-case nil
11249 (funcall cmd file link)
11250 ;; FIXME: Remove this check when most default installations
11251 ;; of Emacs have at least Org 9.0.
11252 ((debug wrong-number-of-arguments wrong-type-argument
11253 invalid-function)
11254 (user-error "Please see Org News for version 9.0 about \
11255 `org-file-apps'--Lisp error: %S" cmd)))))
11256 ((consp cmd)
11257 ;; FIXME: Remove this check when most default installations of
11258 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11259 ;; fall back to `org-link-frame-setup' for an old usage of
11260 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11261 (user-error "Please see Org News for version 9.0 about \
11262 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11263 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11264 (funcall save-position-maybe)))
11266 (defun org-file-apps-entry-match-against-dlink-p (entry)
11267 "This function returns non-nil if `entry' uses a regular
11268 expression which should be matched against the whole link by
11269 org-open-file.
11271 It assumes that is the case when the entry uses a regular
11272 expression which has at least one grouping construct and the
11273 action is either a lisp form or a command string containing
11274 `%1', i.e. using at least one subexpression match as a
11275 parameter."
11276 (let ((selector (car entry))
11277 (action (cdr entry)))
11278 (if (stringp selector)
11279 (and (> (regexp-opt-depth selector) 0)
11280 (or (and (stringp action)
11281 (string-match "%[0-9]" action))
11282 (consp action)))
11283 nil)))
11285 (defun org-default-apps ()
11286 "Return the default applications for this operating system."
11287 (cond
11288 ((eq system-type 'darwin)
11289 org-file-apps-defaults-macosx)
11290 ((eq system-type 'windows-nt)
11291 org-file-apps-defaults-windowsnt)
11292 (t org-file-apps-defaults-gnu)))
11294 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11295 "Convert extensions to regular expressions in the cars of LIST.
11296 Also, weed out any non-string entries, because the return value is used
11297 only for regexp matching.
11298 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11299 point to the symbol `emacs', indicating that the file should
11300 be opened in Emacs."
11301 (append
11302 (delq nil
11303 (mapcar (lambda (x)
11304 (unless (not (stringp (car x)))
11305 (if (string-match "\\W" (car x))
11307 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11308 list))
11309 (when add-auto-mode
11310 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11312 (defvar ange-ftp-name-format)
11313 (defun org-file-remote-p (file)
11314 "Test whether FILE specifies a location on a remote system.
11315 Return non-nil if the location is indeed remote.
11317 For example, the filename \"/user@host:/foo\" specifies a location
11318 on the system \"/user@host:\"."
11319 (cond ((fboundp 'file-remote-p)
11320 (file-remote-p file))
11321 ((fboundp 'tramp-handle-file-remote-p)
11322 (tramp-handle-file-remote-p file))
11323 ((and (boundp 'ange-ftp-name-format)
11324 (string-match (car ange-ftp-name-format) file))
11325 t)))
11328 ;;;; Refiling
11330 (defun org-get-org-file ()
11331 "Read a filename, with default directory `org-directory'."
11332 (let ((default (or org-default-notes-file remember-data-file)))
11333 (read-file-name (format "File name [%s]: " default)
11334 (file-name-as-directory org-directory)
11335 default)))
11337 (defun org-notes-order-reversed-p ()
11338 "Check if the current file should receive notes in reversed order."
11339 (cond
11340 ((not org-reverse-note-order) nil)
11341 ((eq t org-reverse-note-order) t)
11342 ((not (listp org-reverse-note-order)) nil)
11343 (t (catch 'exit
11344 (dolist (entry org-reverse-note-order)
11345 (when (string-match (car entry) buffer-file-name)
11346 (throw 'exit (cdr entry))))))))
11348 (defvar org-refile-target-table nil
11349 "The list of refile targets, created by `org-refile'.")
11351 (defvar org-agenda-new-buffers nil
11352 "Buffers created to visit agenda files.")
11354 (defvar org-refile-cache nil
11355 "Cache for refile targets.")
11357 (defvar org-refile-markers nil
11358 "All the markers used for caching refile locations.")
11360 (defun org-refile-marker (pos)
11361 "Get a new refile marker, but only if caching is in use."
11362 (if (not org-refile-use-cache)
11364 (let ((m (make-marker)))
11365 (move-marker m pos)
11366 (push m org-refile-markers)
11367 m)))
11369 (defun org-refile-cache-clear ()
11370 "Clear the refile cache and disable all the markers."
11371 (dolist (m org-refile-markers) (move-marker m nil))
11372 (setq org-refile-markers nil)
11373 (setq org-refile-cache nil)
11374 (message "Refile cache has been cleared"))
11376 (defun org-refile-cache-check-set (set)
11377 "Check if all the markers in the cache still have live buffers."
11378 (let (marker)
11379 (catch 'exit
11380 (while (and set (setq marker (nth 3 (pop set))))
11381 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11382 (when (and marker (null (marker-buffer marker)))
11383 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11384 (sit-for 3)
11385 (throw 'exit nil)))
11386 t)))
11388 (defun org-refile-cache-put (set &rest identifiers)
11389 "Push the refile targets SET into the cache, under IDENTIFIERS."
11390 (let* ((key (sha1 (prin1-to-string identifiers)))
11391 (entry (assoc key org-refile-cache)))
11392 (if entry
11393 (setcdr entry set)
11394 (push (cons key set) org-refile-cache))))
11396 (defun org-refile-cache-get (&rest identifiers)
11397 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11398 (cond
11399 ((not org-refile-cache) nil)
11400 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11402 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11403 org-refile-cache))))
11404 (and set (org-refile-cache-check-set set) set)))))
11406 (defvar org-outline-path-cache nil
11407 "Alist between buffer positions and outline paths.
11408 It value is an alist (POSITION . PATH) where POSITION is the
11409 buffer position at the beginning of an entry and PATH is a list
11410 of strings describing the outline path for that entry, in reverse
11411 order.")
11413 (defun org-refile-get-targets (&optional default-buffer)
11414 "Produce a table with refile targets."
11415 (let ((case-fold-search nil)
11416 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11417 (entries (or org-refile-targets '((nil . (:level . 1)))))
11418 targets tgs files desc descre)
11419 (message "Getting targets...")
11420 (with-current-buffer (or default-buffer (current-buffer))
11421 (dolist (entry entries)
11422 (setq files (car entry) desc (cdr entry))
11423 (cond
11424 ((null files) (setq files (list (current-buffer))))
11425 ((eq files 'org-agenda-files)
11426 (setq files (org-agenda-files 'unrestricted)))
11427 ((and (symbolp files) (fboundp files))
11428 (setq files (funcall files)))
11429 ((and (symbolp files) (boundp files))
11430 (setq files (symbol-value files))))
11431 (when (stringp files) (setq files (list files)))
11432 (cond
11433 ((eq (car desc) :tag)
11434 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11435 ((eq (car desc) :todo)
11436 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11437 ((eq (car desc) :regexp)
11438 (setq descre (cdr desc)))
11439 ((eq (car desc) :level)
11440 (setq descre (concat "^\\*\\{" (number-to-string
11441 (if org-odd-levels-only
11442 (1- (* 2 (cdr desc)))
11443 (cdr desc)))
11444 "\\}[ \t]")))
11445 ((eq (car desc) :maxlevel)
11446 (setq descre (concat "^\\*\\{1," (number-to-string
11447 (if org-odd-levels-only
11448 (1- (* 2 (cdr desc)))
11449 (cdr desc)))
11450 "\\}[ \t]")))
11451 (t (error "Bad refiling target description %s" desc)))
11452 (dolist (f files)
11453 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11455 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11456 (progn
11457 (when (bufferp f)
11458 (setq f (buffer-file-name (buffer-base-buffer f))))
11459 (setq f (and f (expand-file-name f)))
11460 (when (eq org-refile-use-outline-path 'file)
11461 (push (list (file-name-nondirectory f) f nil nil) tgs))
11462 (when (eq org-refile-use-outline-path 'buffer-name)
11463 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11464 (when (eq org-refile-use-outline-path 'full-file-path)
11465 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11466 (org-with-wide-buffer
11467 (goto-char (point-min))
11468 (setq org-outline-path-cache nil)
11469 (while (re-search-forward descre nil t)
11470 (beginning-of-line)
11471 (let ((case-fold-search nil))
11472 (looking-at org-complex-heading-regexp))
11473 (let ((begin (point))
11474 (heading (match-string-no-properties 4)))
11475 (unless (or (and
11476 org-refile-target-verify-function
11477 (not
11478 (funcall org-refile-target-verify-function)))
11479 (not heading))
11480 (let ((re (format org-complex-heading-regexp-format
11481 (regexp-quote heading)))
11482 (target
11483 (if (not org-refile-use-outline-path) heading
11484 (mapconcat
11485 #'identity
11486 (append
11487 (pcase org-refile-use-outline-path
11488 (`file (list (file-name-nondirectory
11489 (buffer-file-name
11490 (buffer-base-buffer)))))
11491 (`full-file-path
11492 (list (buffer-file-name
11493 (buffer-base-buffer))))
11494 (`buffer-name
11495 (list (buffer-name
11496 (buffer-base-buffer))))
11497 (_ nil))
11498 (mapcar (lambda (s) (replace-regexp-in-string
11499 "/" "\\/" s nil t))
11500 (org-get-outline-path t t)))
11501 "/"))))
11502 (push (list target f re (org-refile-marker (point)))
11503 tgs)))
11504 (when (= (point) begin)
11505 ;; Verification function has not moved point.
11506 (end-of-line)))))))
11507 (when org-refile-use-cache
11508 (org-refile-cache-put tgs (buffer-file-name) descre))
11509 (setq targets (append tgs targets))))))
11510 (message "Getting targets...done")
11511 (delete-dups (nreverse targets))))
11513 (defun org--get-outline-path-1 (&optional use-cache)
11514 "Return outline path to current headline.
11516 Outline path is a list of strings, in reverse order. When
11517 optional argument USE-CACHE is non-nil, make use of a cache. See
11518 `org-get-outline-path' for details.
11520 Assume buffer is widened and point is on a headline."
11521 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11522 (let ((p (point))
11523 (heading (let ((case-fold-search nil))
11524 (looking-at org-complex-heading-regexp)
11525 (if (not (match-end 4)) ""
11526 ;; Remove statistics cookies.
11527 (org-trim
11528 (org-link-display-format
11529 (replace-regexp-in-string
11530 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11531 (match-string-no-properties 4))))))))
11532 (if (org-up-heading-safe)
11533 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11534 (when use-cache
11535 (push (cons p path) org-outline-path-cache))
11536 path)
11537 ;; This is a new root node. Since we assume we are moving
11538 ;; forward, we can drop previous cache so as to limit number
11539 ;; of associations there.
11540 (let ((path (list heading)))
11541 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11542 path)))))
11544 (defun org-get-outline-path (&optional with-self use-cache)
11545 "Return the outline path to the current entry.
11547 An outline path is a list of ancestors for current headline, as
11548 a list of strings. Statistics cookies are removed and links are
11549 replaced with their description, if any, or their path otherwise.
11551 When optional argument WITH-SELF is non-nil, the path also
11552 includes the current headline.
11554 When optional argument USE-CACHE is non-nil, cache outline paths
11555 between calls to this function so as to avoid backtracking. This
11556 argument is useful when planning to find more than one outline
11557 path in the same document. In that case, there are two
11558 conditions to satisfy:
11559 - `org-outline-path-cache' is set to nil before starting the
11560 process;
11561 - outline paths are computed by increasing buffer positions."
11562 (org-with-wide-buffer
11563 (and (or (and with-self (org-back-to-heading t))
11564 (org-up-heading-safe))
11565 (reverse (org--get-outline-path-1 use-cache)))))
11567 (defun org-format-outline-path (path &optional width prefix separator)
11568 "Format the outline path PATH for display.
11569 WIDTH is the maximum number of characters that is available.
11570 PREFIX is a prefix to be included in the returned string,
11571 such as the file name.
11572 SEPARATOR is inserted between the different parts of the path,
11573 the default is \"/\"."
11574 (setq width (or width 79))
11575 (setq path (delq nil path))
11576 (unless (> width 0)
11577 (user-error "Argument `width' must be positive"))
11578 (setq separator (or separator "/"))
11579 (let* ((org-odd-levels-only nil)
11580 (fpath (concat
11581 prefix (and prefix path separator)
11582 (mapconcat
11583 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11584 (cl-loop for head in path
11585 for n from 0
11586 collect (org-add-props
11587 head nil 'face
11588 (nth (% n org-n-level-faces) org-level-faces)))
11589 separator))))
11590 (when (> (length fpath) width)
11591 (if (< width 7)
11592 ;; It's unlikely that `width' will be this small, but don't
11593 ;; waste characters by adding ".." if it is.
11594 (setq fpath (substring fpath 0 width))
11595 (setf (substring fpath (- width 2)) "..")))
11596 fpath))
11598 (defun org-display-outline-path (&optional file current separator just-return-string)
11599 "Display the current outline path in the echo area.
11601 If FILE is non-nil, prepend the output with the file name.
11602 If CURRENT is non-nil, append the current heading to the output.
11603 SEPARATOR is passed through to `org-format-outline-path'. It separates
11604 the different parts of the path and defaults to \"/\".
11605 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11606 (interactive "P")
11607 (let* (case-fold-search
11608 (bfn (buffer-file-name (buffer-base-buffer)))
11609 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11610 res)
11611 (when current (setq path (append path
11612 (save-excursion
11613 (org-back-to-heading t)
11614 (when (looking-at org-complex-heading-regexp)
11615 (list (match-string 4)))))))
11616 (setq res
11617 (org-format-outline-path
11618 path
11619 (1- (frame-width))
11620 (and file bfn (concat (file-name-nondirectory bfn) separator))
11621 separator))
11622 (if just-return-string
11623 (org-no-properties res)
11624 (org-unlogged-message "%s" res))))
11626 (defvar org-refile-history nil
11627 "History for refiling operations.")
11629 (defvar org-after-refile-insert-hook nil
11630 "Hook run after `org-refile' has inserted its stuff at the new location.
11631 Note that this is still *before* the stuff will be removed from
11632 the *old* location.")
11634 (defvar org-capture-last-stored-marker)
11635 (defvar org-refile-keep nil
11636 "Non-nil means `org-refile' will copy instead of refile.")
11638 (defun org-copy ()
11639 "Like `org-refile', but copy."
11640 (interactive)
11641 (let ((org-refile-keep t))
11642 (funcall 'org-refile nil nil nil "Copy")))
11644 (defun org-refile (&optional arg default-buffer rfloc msg)
11645 "Move the entry or entries at point to another heading.
11647 The list of target headings is compiled using the information in
11648 `org-refile-targets', which see.
11650 At the target location, the entry is filed as a subitem of the
11651 target heading. Depending on `org-reverse-note-order', the new
11652 subitem will either be the first or the last subitem.
11654 If there is an active region, all entries in that region will be
11655 refiled. However, the region must fulfill the requirement that
11656 the first heading sets the top-level of the moved text.
11658 With a `\\[universal-argument]' ARG, the command will only visit the target \
11659 location
11660 and not actually move anything.
11662 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11663 location where the last
11664 refiling operation has put the subtree.
11666 With a numeric prefix argument of `2', refile to the running clock.
11668 With a numeric prefix argument of `3', emulate `org-refile-keep'
11669 being set to t and copy to the target location, don't move it.
11670 Beware that keeping refiled entries may result in duplicated ID
11671 properties.
11673 RFLOC can be a refile location obtained in a different way.
11675 MSG is a string to replace \"Refile\" in the default prompt with
11676 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11678 See also `org-refile-use-outline-path'.
11680 If you are using target caching (see `org-refile-use-cache'), you
11681 have to clear the target cache in order to find new targets.
11682 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11683 prefix argument (`C-u C-u C-u C-c C-w')."
11684 (interactive "P")
11685 (if (member arg '(0 (64)))
11686 (org-refile-cache-clear)
11687 (let* ((actionmsg (cond (msg msg)
11688 ((equal arg 3) "Refile (and keep)")
11689 (t "Refile")))
11690 (regionp (org-region-active-p))
11691 (region-start (and regionp (region-beginning)))
11692 (region-end (and regionp (region-end)))
11693 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11694 pos it nbuf file level reversed)
11695 (setq last-command nil)
11696 (when regionp
11697 (goto-char region-start)
11698 (or (bolp) (goto-char (point-at-bol)))
11699 (setq region-start (point))
11700 (unless (or (org-kill-is-subtree-p
11701 (buffer-substring region-start region-end))
11702 (prog1 org-refile-active-region-within-subtree
11703 (let ((s (point-at-eol)))
11704 (org-toggle-heading)
11705 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11706 (user-error "The region is not a (sequence of) subtree(s)")))
11707 (if (equal arg '(16))
11708 (org-refile-goto-last-stored)
11709 (when (or
11710 (and (equal arg 2)
11711 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11712 (prog1
11713 (setq it (list (or org-clock-heading "running clock")
11714 (buffer-file-name
11715 (marker-buffer org-clock-hd-marker))
11717 (marker-position org-clock-hd-marker)))
11718 (setq arg nil)))
11719 (setq it
11720 (or rfloc
11721 (let (heading-text)
11722 (save-excursion
11723 (unless (and arg (listp arg))
11724 (org-back-to-heading t)
11725 (setq heading-text
11726 (replace-regexp-in-string
11727 org-bracket-link-regexp
11728 "\\3"
11729 (or (nth 4 (org-heading-components))
11730 ""))))
11731 (org-refile-get-location
11732 (cond ((and arg (listp arg)) "Goto")
11733 (regionp (concat actionmsg " region to"))
11734 (t (concat actionmsg " subtree \""
11735 heading-text "\" to")))
11736 default-buffer
11737 (and (not (equal '(4) arg))
11738 org-refile-allow-creating-parent-nodes)))))))
11739 (setq file (nth 1 it)
11740 pos (nth 3 it))
11741 (when (and (not arg)
11743 (equal (buffer-file-name) file)
11744 (if regionp
11745 (and (>= pos region-start)
11746 (<= pos region-end))
11747 (and (>= pos (point))
11748 (< pos (save-excursion
11749 (org-end-of-subtree t t))))))
11750 (error "Cannot refile to position inside the tree or region"))
11751 (setq nbuf (or (find-buffer-visiting file)
11752 (find-file-noselect file)))
11753 (if (and arg (not (equal arg 3)))
11754 (progn
11755 (pop-to-buffer-same-window nbuf)
11756 (goto-char (cond (pos)
11757 ((org-notes-order-reversed-p) (point-min))
11758 (t (point-max))))
11759 (org-show-context 'org-goto))
11760 (if regionp
11761 (progn
11762 (org-kill-new (buffer-substring region-start region-end))
11763 (org-save-markers-in-region region-start region-end))
11764 (org-copy-subtree 1 nil t))
11765 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11766 (find-file-noselect file)))
11767 (setq reversed (org-notes-order-reversed-p))
11768 (org-with-wide-buffer
11769 (if pos
11770 (progn
11771 (goto-char pos)
11772 (setq level (org-get-valid-level (funcall outline-level) 1))
11773 (goto-char
11774 (if reversed
11775 (or (outline-next-heading) (point-max))
11776 (or (save-excursion (org-get-next-sibling))
11777 (org-end-of-subtree t t)
11778 (point-max)))))
11779 (setq level 1)
11780 (if (not reversed)
11781 (goto-char (point-max))
11782 (goto-char (point-min))
11783 (or (outline-next-heading) (goto-char (point-max)))))
11784 (unless (bolp) (newline))
11785 (org-paste-subtree level nil nil t)
11786 (when org-log-refile
11787 (org-add-log-setup 'refile nil nil org-log-refile)
11788 (unless (eq org-log-refile 'note)
11789 (save-excursion (org-add-log-note))))
11790 (and org-auto-align-tags
11791 (let ((org-loop-over-headlines-in-active-region nil))
11792 (org-set-tags nil t)))
11793 (let ((bookmark-name (plist-get org-bookmark-names-plist
11794 :last-refile)))
11795 (when bookmark-name
11796 (with-demoted-errors
11797 (bookmark-set bookmark-name))))
11798 ;; If we are refiling for capture, make sure that the
11799 ;; last-capture pointers point here
11800 (when (bound-and-true-p org-capture-is-refiling)
11801 (let ((bookmark-name (plist-get org-bookmark-names-plist
11802 :last-capture-marker)))
11803 (when bookmark-name
11804 (with-demoted-errors
11805 (bookmark-set bookmark-name))))
11806 (move-marker org-capture-last-stored-marker (point)))
11807 (when (fboundp 'deactivate-mark) (deactivate-mark))
11808 (run-hooks 'org-after-refile-insert-hook)))
11809 (unless org-refile-keep
11810 (if regionp
11811 (delete-region (point) (+ (point) (- region-end region-start)))
11812 (delete-region
11813 (and (org-back-to-heading t) (point))
11814 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11815 (when (featurep 'org-inlinetask)
11816 (org-inlinetask-remove-END-maybe))
11817 (setq org-markers-to-move nil)
11818 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11820 (defun org-refile-goto-last-stored ()
11821 "Go to the location where the last refile was stored."
11822 (interactive)
11823 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11824 (message "This is the location of the last refile"))
11826 (defun org-refile--get-location (refloc tbl)
11827 "When user refile to REFLOC, find the associated target in TBL.
11828 Also check `org-refile-target-table'."
11829 (car (delq
11831 (mapcar
11832 (lambda (r) (or (assoc r tbl)
11833 (assoc r org-refile-target-table)))
11834 (list (replace-regexp-in-string "/$" "" refloc)
11835 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11837 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11838 "Prompt the user for a refile location, using PROMPT.
11839 PROMPT should not be suffixed with a colon and a space, because
11840 this function appends the default value from
11841 `org-refile-history' automatically, if that is not empty."
11842 (let ((org-refile-targets org-refile-targets)
11843 (org-refile-use-outline-path org-refile-use-outline-path))
11844 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11845 (unless org-refile-target-table
11846 (user-error "No refile targets"))
11847 (let* ((cbuf (current-buffer))
11848 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11849 (cfunc (if (and org-refile-use-outline-path
11850 org-outline-path-complete-in-steps)
11851 #'org-olpath-completing-read
11852 #'completing-read))
11853 (extra (if org-refile-use-outline-path "/" ""))
11854 (cbnex (concat (buffer-name) extra))
11855 (filename (and cfn (expand-file-name cfn)))
11856 (tbl (mapcar
11857 (lambda (x)
11858 (if (and (not (member org-refile-use-outline-path
11859 '(file full-file-path)))
11860 (not (equal filename (nth 1 x))))
11861 (cons (concat (car x) extra " ("
11862 (file-name-nondirectory (nth 1 x)) ")")
11863 (cdr x))
11864 (cons (concat (car x) extra) (cdr x))))
11865 org-refile-target-table))
11866 (completion-ignore-case t)
11867 cdef
11868 (prompt (concat prompt
11869 (or (and (car org-refile-history)
11870 (concat " (default " (car org-refile-history) ")"))
11871 (and (assoc cbnex tbl) (setq cdef cbnex)
11872 (concat " (default " cbnex ")"))) ": "))
11873 pa answ parent-target child parent old-hist)
11874 (setq old-hist org-refile-history)
11875 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11876 nil 'org-refile-history (or cdef (car org-refile-history))))
11877 (if (setq pa (org-refile--get-location answ tbl))
11878 (progn
11879 (org-refile-check-position pa)
11880 (when (or (not org-refile-history)
11881 (not (eq old-hist org-refile-history))
11882 (not (equal (car pa) (car org-refile-history))))
11883 (setq org-refile-history
11884 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11885 org-refile-history
11886 (cdr org-refile-history))))
11887 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11888 (pop org-refile-history)))
11890 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11891 (progn
11892 (setq parent (match-string 1 answ)
11893 child (match-string 2 answ))
11894 (setq parent-target (org-refile--get-location parent tbl))
11895 (when (and parent-target
11896 (or (eq new-nodes t)
11897 (and (eq new-nodes 'confirm)
11898 (y-or-n-p (format "Create new node \"%s\"? "
11899 child)))))
11900 (org-refile-new-child parent-target child)))
11901 (user-error "Invalid target location")))))
11903 (declare-function org-string-nw-p "org-macs" (s))
11904 (defun org-refile-check-position (refile-pointer)
11905 "Check if the refile pointer matches the headline to which it points."
11906 (let* ((file (nth 1 refile-pointer))
11907 (re (nth 2 refile-pointer))
11908 (pos (nth 3 refile-pointer))
11909 buffer)
11910 (if (and (not (markerp pos)) (not file))
11911 (user-error "Please indicate a target file in the refile path")
11912 (when (org-string-nw-p re)
11913 (setq buffer (if (markerp pos)
11914 (marker-buffer pos)
11915 (or (find-buffer-visiting file)
11916 (find-file-noselect file))))
11917 (with-current-buffer buffer
11918 (org-with-wide-buffer
11919 (goto-char pos)
11920 (beginning-of-line 1)
11921 (unless (looking-at-p re)
11922 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11924 (defun org-refile-new-child (parent-target child)
11925 "Use refile target PARENT-TARGET to add new CHILD below it."
11926 (unless parent-target
11927 (error "Cannot find parent for new node"))
11928 (let ((file (nth 1 parent-target))
11929 (pos (nth 3 parent-target))
11930 level)
11931 (with-current-buffer (or (find-buffer-visiting file)
11932 (find-file-noselect file))
11933 (org-with-wide-buffer
11934 (if pos
11935 (goto-char pos)
11936 (goto-char (point-max))
11937 (unless (bolp) (newline)))
11938 (when (looking-at org-outline-regexp)
11939 (setq level (funcall outline-level))
11940 (org-end-of-subtree t t))
11941 (org-back-over-empty-lines)
11942 (insert "\n" (make-string
11943 (if pos (org-get-valid-level level 1) 1) ?*)
11944 " " child "\n")
11945 (beginning-of-line 0)
11946 (list (concat (car parent-target) "/" child) file "" (point))))))
11948 (defun org-olpath-completing-read (prompt collection &rest args)
11949 "Read an outline path like a file name."
11950 (let ((thetable collection))
11951 (apply #'completing-read
11952 prompt
11953 (lambda (string predicate &optional flag)
11954 (cond
11955 ((eq flag nil) (try-completion string thetable))
11956 ((eq flag t)
11957 (let ((l (length string)))
11958 (mapcar (lambda (x)
11959 (let ((r (substring x l))
11960 (f (if (string-match " ([^)]*)$" x)
11961 (match-string 0 x)
11962 "")))
11963 (if (string-match "/" r)
11964 (concat string (substring r 0 (match-end 0)) f)
11965 x)))
11966 (all-completions string thetable predicate))))
11967 ;; Exact match?
11968 ((eq flag 'lambda) (assoc string thetable))))
11969 args)))
11971 ;;;; Dynamic blocks
11973 (defun org-find-dblock (name)
11974 "Find the first dynamic block with name NAME in the buffer.
11975 If not found, stay at current position and return nil."
11976 (let ((case-fold-search t) pos)
11977 (save-excursion
11978 (goto-char (point-min))
11979 (setq pos (and (re-search-forward
11980 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11981 (match-beginning 0))))
11982 (when pos (goto-char pos))
11983 pos))
11985 (defun org-create-dblock (plist)
11986 "Create a dynamic block section, with parameters taken from PLIST.
11987 PLIST must contain a :name entry which is used as the name of the block."
11988 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11989 (end-of-line 1)
11990 (newline))
11991 (let ((col (current-column))
11992 (name (plist-get plist :name)))
11993 (insert "#+BEGIN: " name)
11994 (while plist
11995 (if (eq (car plist) :name)
11996 (setq plist (cddr plist))
11997 (insert " " (prin1-to-string (pop plist)))))
11998 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11999 (beginning-of-line -2)))
12001 (defun org-prepare-dblock ()
12002 "Prepare dynamic block for refresh.
12003 This empties the block, puts the cursor at the insert position and returns
12004 the property list including an extra property :name with the block name."
12005 (unless (looking-at org-dblock-start-re)
12006 (user-error "Not at a dynamic block"))
12007 (let* ((begdel (1+ (match-end 0)))
12008 (name (org-no-properties (match-string 1)))
12009 (params (append (list :name name)
12010 (read (concat "(" (match-string 3) ")")))))
12011 (save-excursion
12012 (beginning-of-line 1)
12013 (skip-chars-forward " \t")
12014 (setq params (plist-put params :indentation-column (current-column))))
12015 (unless (re-search-forward org-dblock-end-re nil t)
12016 (error "Dynamic block not terminated"))
12017 (setq params
12018 (append params
12019 (list :content (buffer-substring
12020 begdel (match-beginning 0)))))
12021 (delete-region begdel (match-beginning 0))
12022 (goto-char begdel)
12023 (open-line 1)
12024 params))
12026 (defun org-map-dblocks (&optional command)
12027 "Apply COMMAND to all dynamic blocks in the current buffer.
12028 If COMMAND is not given, use `org-update-dblock'."
12029 (let ((cmd (or command 'org-update-dblock)))
12030 (save-excursion
12031 (goto-char (point-min))
12032 (while (re-search-forward org-dblock-start-re nil t)
12033 (goto-char (match-beginning 0))
12034 (save-excursion
12035 (condition-case nil
12036 (funcall cmd)
12037 (error (message "Error during update of dynamic block"))))
12038 (unless (re-search-forward org-dblock-end-re nil t)
12039 (error "Dynamic block not terminated"))))))
12041 (defun org-dblock-update (&optional arg)
12042 "User command for updating dynamic blocks.
12043 Update the dynamic block at point. With prefix ARG, update all dynamic
12044 blocks in the buffer."
12045 (interactive "P")
12046 (if arg
12047 (org-update-all-dblocks)
12048 (or (looking-at org-dblock-start-re)
12049 (org-beginning-of-dblock))
12050 (org-update-dblock)))
12052 (defun org-update-dblock ()
12053 "Update the dynamic block at point.
12054 This means to empty the block, parse for parameters and then call
12055 the correct writing function."
12056 (interactive)
12057 (save-excursion
12058 (let* ((win (selected-window))
12059 (pos (point))
12060 (line (org-current-line))
12061 (params (org-prepare-dblock))
12062 (name (plist-get params :name))
12063 (indent (plist-get params :indentation-column))
12064 (cmd (intern (concat "org-dblock-write:" name))))
12065 (message "Updating dynamic block `%s' at line %d..." name line)
12066 (funcall cmd params)
12067 (message "Updating dynamic block `%s' at line %d...done" name line)
12068 (goto-char pos)
12069 (when (and indent (> indent 0))
12070 (setq indent (make-string indent ?\ ))
12071 (save-excursion
12072 (select-window win)
12073 (org-beginning-of-dblock)
12074 (forward-line 1)
12075 (while (not (looking-at org-dblock-end-re))
12076 (insert indent)
12077 (beginning-of-line 2))
12078 (when (looking-at org-dblock-end-re)
12079 (and (looking-at "[ \t]+")
12080 (replace-match ""))
12081 (insert indent)))))))
12083 (defun org-beginning-of-dblock ()
12084 "Find the beginning of the dynamic block at point.
12085 Error if there is no such block at point."
12086 (let ((pos (point))
12087 beg)
12088 (end-of-line 1)
12089 (if (and (re-search-backward org-dblock-start-re nil t)
12090 (setq beg (match-beginning 0))
12091 (re-search-forward org-dblock-end-re nil t)
12092 (> (match-end 0) pos))
12093 (goto-char beg)
12094 (goto-char pos)
12095 (error "Not in a dynamic block"))))
12097 (defun org-update-all-dblocks ()
12098 "Update all dynamic blocks in the buffer.
12099 This function can be used in a hook."
12100 (interactive)
12101 (when (derived-mode-p 'org-mode)
12102 (org-map-dblocks 'org-update-dblock)))
12105 ;;;; Completion
12107 (declare-function org-export-backend-options "ox" (cl-x) t)
12108 (defun org-get-export-keywords ()
12109 "Return a list of all currently understood export keywords.
12110 Export keywords include options, block names, attributes and
12111 keywords relative to each registered export back-end."
12112 (let (keywords)
12113 (dolist (backend
12114 (bound-and-true-p org-export-registered-backends)
12115 (delq nil keywords))
12116 ;; Back-end name (for keywords, like #+LATEX:)
12117 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12118 (dolist (option-entry (org-export-backend-options backend))
12119 ;; Back-end options.
12120 (push (nth 1 option-entry) keywords)))))
12122 (defconst org-options-keywords
12123 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12124 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12125 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12126 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12127 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12129 (defcustom org-structure-template-alist
12130 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12131 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12132 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12133 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12134 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12135 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12136 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12137 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12138 ("L" "#+LaTeX: ")
12139 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12140 ("H" "#+HTML: ")
12141 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12142 ("A" "#+ASCII: ")
12143 ("i" "#+INDEX: ?")
12144 ("I" "#+INCLUDE: %file ?"))
12145 "Structure completion elements.
12146 This is a list of abbreviation keys and values. The value gets inserted
12147 if you type `<' followed by the key and then press the completion key,
12148 usually `TAB'. %file will be replaced by a file name after prompting
12149 for the file using completion. The cursor will be placed at the position
12150 of the `?' in the template.
12151 There are two templates for each key, the first uses the original Org syntax,
12152 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12153 the default when the /org-mtags.el/ module has been loaded. See also the
12154 variable `org-mtags-prefer-muse-templates'."
12155 :group 'org-completion
12156 :type '(repeat
12157 (list
12158 (string :tag "Key")
12159 (string :tag "Template")))
12160 :version "26.1"
12161 :package-version '(Org . "8.3"))
12163 (defun org-try-structure-completion ()
12164 "Try to complete a structure template before point.
12165 This looks for strings like \"<e\" on an otherwise empty line and
12166 expands them."
12167 (let ((l (buffer-substring (point-at-bol) (point)))
12169 (when (and (looking-at "[ \t]*$")
12170 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12171 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12172 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12173 (match-beginning 1)) a)
12174 t)))
12176 (defun org-complete-expand-structure-template (start cell)
12177 "Expand a structure template."
12178 (let ((rpl (nth 1 cell))
12179 (ind ""))
12180 (delete-region start (point))
12181 (when (string-match "\\`[ \t]*#\\+" rpl)
12182 (cond
12183 ((bolp))
12184 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12185 (setq ind (buffer-substring (point-at-bol) (point))))
12186 (t (newline))))
12187 (setq start (point))
12188 (when (string-match "%file" rpl)
12189 (setq rpl (replace-match
12190 (concat
12191 "\""
12192 (save-match-data
12193 (abbreviate-file-name (read-file-name "Include file: ")))
12194 "\"")
12195 t t rpl)))
12196 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12197 (concat "\n" ind)))
12198 (insert rpl)
12199 (when (re-search-backward "\\?" start t) (delete-char 1))))
12201 ;;;; TODO, DEADLINE, Comments
12203 (defun org-toggle-comment ()
12204 "Change the COMMENT state of an entry."
12205 (interactive)
12206 (save-excursion
12207 (org-back-to-heading)
12208 (let ((case-fold-search nil))
12209 (looking-at org-complex-heading-regexp))
12210 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12211 (skip-chars-forward " \t")
12212 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12213 (if (org-in-commented-heading-p t)
12214 (delete-region (point)
12215 (progn (search-forward " " (line-end-position) 'move)
12216 (skip-chars-forward " \t")
12217 (point)))
12218 (insert org-comment-string)
12219 (unless (eolp) (insert " ")))))
12221 (defvar org-last-todo-state-is-todo nil
12222 "This is non-nil when the last TODO state change led to a TODO state.
12223 If the last change removed the TODO tag or switched to DONE, then
12224 this is nil.")
12226 (defvar org-setting-tags nil) ; dynamically skipped
12228 (defvar org-todo-setup-filter-hook nil
12229 "Hook for functions that pre-filter todo specs.
12230 Each function takes a todo spec and returns either nil or the spec
12231 transformed into canonical form." )
12233 (defvar org-todo-get-default-hook nil
12234 "Hook for functions that get a default item for todo.
12235 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12236 nil or a string to be used for the todo mark." )
12238 (defvar org-agenda-headline-snapshot-before-repeat)
12240 (defun org-current-effective-time ()
12241 "Return current time adjusted for `org-extend-today-until' variable."
12242 (let* ((ct (org-current-time))
12243 (dct (decode-time ct))
12244 (ct1
12245 (cond
12246 (org-use-last-clock-out-time-as-effective-time
12247 (or (org-clock-get-last-clock-out-time) ct))
12248 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12249 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12250 (t ct))))
12251 ct1))
12253 (defun org-todo-yesterday (&optional arg)
12254 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12255 (interactive "P")
12256 (if (eq major-mode 'org-agenda-mode)
12257 (apply 'org-agenda-todo-yesterday arg)
12258 (let* ((org-use-effective-time t)
12259 (hour (nth 2 (decode-time (org-current-time))))
12260 (org-extend-today-until (1+ hour)))
12261 (org-todo arg))))
12263 (defvar org-block-entry-blocking ""
12264 "First entry preventing the TODO state change.")
12266 (defun org-cancel-repeater ()
12267 "Cancel a repeater by setting its numeric value to zero."
12268 (interactive)
12269 (save-excursion
12270 (org-back-to-heading t)
12271 (let ((bound1 (point))
12272 (bound0 (save-excursion (outline-next-heading) (point))))
12273 (when (and (re-search-forward
12274 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12275 org-deadline-time-regexp "\\)\\|\\("
12276 org-ts-regexp "\\)")
12277 bound0 t)
12278 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12279 bound1 t))
12280 (replace-match "0" t nil nil 1)))))
12282 (defvar org-state)
12283 (defvar org-blocked-by-checkboxes)
12284 (defun org-todo (&optional arg)
12285 "Change the TODO state of an item.
12287 The state of an item is given by a keyword at the start of the heading,
12288 like
12289 *** TODO Write paper
12290 *** DONE Call mom
12292 The different keywords are specified in the variable `org-todo-keywords'.
12293 By default the available states are \"TODO\" and \"DONE\". So, for this
12294 example: when the item starts with TODO, it is changed to DONE.
12295 When it starts with DONE, the DONE is removed. And when neither TODO nor
12296 DONE are present, add TODO at the beginning of the heading.
12298 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12299 state.
12300 With numeric prefix ARG, switch to that state.
12301 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12302 next set of TODO \
12303 keywords (nextset).
12304 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12305 prefix, circumvent any state blocking.
12306 With a numeric prefix arg of 0, inhibit note taking for the change.
12307 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12309 When called through ELisp, arg is also interpreted in the following way:
12310 `none' -> empty state
12311 \"\" -> switch to empty state
12312 `done' -> switch to DONE
12313 `nextset' -> switch to the next set of keywords
12314 `previousset' -> switch to the previous set of keywords
12315 \"WAITING\" -> switch to the specified keyword, but only if it
12316 really is a member of `org-todo-keywords'."
12317 (interactive "P")
12318 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12319 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12320 'region-start-level 'region))
12321 org-loop-over-headlines-in-active-region)
12322 (org-map-entries
12323 `(org-todo ,arg)
12324 org-loop-over-headlines-in-active-region
12325 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12326 (when (equal arg '(16)) (setq arg 'nextset))
12327 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12328 (let ((org-blocker-hook org-blocker-hook)
12329 commentp
12330 case-fold-search)
12331 (when (equal arg '(64))
12332 (setq arg nil org-blocker-hook nil))
12333 (when (and org-blocker-hook
12334 (or org-inhibit-blocking
12335 (org-entry-get nil "NOBLOCKING")))
12336 (setq org-blocker-hook nil))
12337 (save-excursion
12338 (catch 'exit
12339 (org-back-to-heading t)
12340 (when (org-in-commented-heading-p t)
12341 (org-toggle-comment)
12342 (setq commentp t))
12343 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12344 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12345 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12346 (let* ((match-data (match-data))
12347 (startpos (point-at-bol))
12348 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12349 (org-log-done org-log-done)
12350 (org-log-repeat org-log-repeat)
12351 (org-todo-log-states org-todo-log-states)
12352 (org-inhibit-logging
12353 (if (equal arg 0)
12354 (progn (setq arg nil) 'note) org-inhibit-logging))
12355 (this (match-string 1))
12356 (hl-pos (match-beginning 0))
12357 (head (org-get-todo-sequence-head this))
12358 (ass (assoc head org-todo-kwd-alist))
12359 (interpret (nth 1 ass))
12360 (done-word (nth 3 ass))
12361 (final-done-word (nth 4 ass))
12362 (org-last-state (or this ""))
12363 (completion-ignore-case t)
12364 (member (member this org-todo-keywords-1))
12365 (tail (cdr member))
12366 (org-state (cond
12367 ((and org-todo-key-trigger
12368 (or (and (equal arg '(4))
12369 (eq org-use-fast-todo-selection 'prefix))
12370 (and (not arg) org-use-fast-todo-selection
12371 (not (eq org-use-fast-todo-selection
12372 'prefix)))))
12373 ;; Use fast selection.
12374 (org-fast-todo-selection))
12375 ((and (equal arg '(4))
12376 (or (not org-use-fast-todo-selection)
12377 (not org-todo-key-trigger)))
12378 ;; Read a state with completion.
12379 (completing-read
12380 "State: " (mapcar #'list org-todo-keywords-1)
12381 nil t))
12382 ((eq arg 'right)
12383 (if this
12384 (if tail (car tail) nil)
12385 (car org-todo-keywords-1)))
12386 ((eq arg 'left)
12387 (unless (equal member org-todo-keywords-1)
12388 (if this
12389 (nth (- (length org-todo-keywords-1)
12390 (length tail) 2)
12391 org-todo-keywords-1)
12392 (org-last org-todo-keywords-1))))
12393 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12394 (setq arg nil))) ;hack to fall back to cycling
12395 (arg
12396 ;; User or caller requests a specific state.
12397 (cond
12398 ((equal arg "") nil)
12399 ((eq arg 'none) nil)
12400 ((eq arg 'done) (or done-word (car org-done-keywords)))
12401 ((eq arg 'nextset)
12402 (or (car (cdr (member head org-todo-heads)))
12403 (car org-todo-heads)))
12404 ((eq arg 'previousset)
12405 (let ((org-todo-heads (reverse org-todo-heads)))
12406 (or (car (cdr (member head org-todo-heads)))
12407 (car org-todo-heads))))
12408 ((car (member arg org-todo-keywords-1)))
12409 ((stringp arg)
12410 (user-error "State `%s' not valid in this file" arg))
12411 ((nth (1- (prefix-numeric-value arg))
12412 org-todo-keywords-1))))
12413 ((null member) (or head (car org-todo-keywords-1)))
12414 ((equal this final-done-word) nil) ;-> make empty
12415 ((null tail) nil) ;-> first entry
12416 ((memq interpret '(type priority))
12417 (if (eq this-command last-command)
12418 (car tail)
12419 (if (> (length tail) 0)
12420 (or done-word (car org-done-keywords))
12421 nil)))
12423 (car tail))))
12424 (org-state (or
12425 (run-hook-with-args-until-success
12426 'org-todo-get-default-hook org-state org-last-state)
12427 org-state))
12428 (next (if org-state (concat " " org-state " ") " "))
12429 (change-plist (list :type 'todo-state-change :from this :to org-state
12430 :position startpos))
12431 dolog now-done-p)
12432 (when org-blocker-hook
12433 (let (org-blocked-by-checkboxes block-reason)
12434 (setq org-last-todo-state-is-todo
12435 (not (member this org-done-keywords)))
12436 (unless (save-excursion
12437 (save-match-data
12438 (org-with-wide-buffer
12439 (run-hook-with-args-until-failure
12440 'org-blocker-hook change-plist))))
12441 (setq block-reason (if org-blocked-by-checkboxes
12442 "contained checkboxes"
12443 (format "\"%s\"" org-block-entry-blocking)))
12444 (if (called-interactively-p 'interactive)
12445 (user-error "TODO state change from %s to %s blocked (by %s)"
12446 this org-state block-reason)
12447 ;; Fail silently.
12448 (message "TODO state change from %s to %s blocked (by %s)"
12449 this org-state block-reason)
12450 (throw 'exit nil)))))
12451 (store-match-data match-data)
12452 (replace-match next t t)
12453 (cond ((equal this org-state)
12454 (message "TODO state was already %s" (org-trim next)))
12455 ((not (pos-visible-in-window-p hl-pos))
12456 (message "TODO state changed to %s" (org-trim next))))
12457 (unless head
12458 (setq head (org-get-todo-sequence-head org-state)
12459 ass (assoc head org-todo-kwd-alist)
12460 interpret (nth 1 ass)
12461 done-word (nth 3 ass)
12462 final-done-word (nth 4 ass)))
12463 (when (memq arg '(nextset previousset))
12464 (message "Keyword-Set %d/%d: %s"
12465 (- (length org-todo-sets) -1
12466 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12467 (length org-todo-sets)
12468 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12469 (setq org-last-todo-state-is-todo
12470 (not (member org-state org-done-keywords)))
12471 (setq now-done-p (and (member org-state org-done-keywords)
12472 (not (member this org-done-keywords))))
12473 (and logging (org-local-logging logging))
12474 (when (and (or org-todo-log-states org-log-done)
12475 (not (eq org-inhibit-logging t))
12476 (not (memq arg '(nextset previousset))))
12477 ;; We need to look at recording a time and note.
12478 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12479 (nth 2 (assoc this org-todo-log-states))))
12480 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12481 (setq dolog 'time))
12482 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12483 (and org-state
12484 (member org-state org-not-done-keywords)
12485 (not (member this org-not-done-keywords))))
12486 ;; This is now a todo state and was not one before
12487 ;; If there was a CLOSED time stamp, get rid of it.
12488 (org-add-planning-info nil nil 'closed))
12489 (when (and now-done-p org-log-done)
12490 ;; It is now done, and it was not done before.
12491 (org-add-planning-info 'closed (org-current-effective-time))
12492 (when (and (not dolog) (eq 'note org-log-done))
12493 (org-add-log-setup 'done org-state this 'note)))
12494 (when (and org-state dolog)
12495 ;; This is a non-nil state, and we need to log it.
12496 (org-add-log-setup 'state org-state this dolog)))
12497 ;; Fixup tag positioning.
12498 (org-todo-trigger-tag-changes org-state)
12499 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12500 (when org-provide-todo-statistics
12501 (org-update-parent-todo-statistics))
12502 (run-hooks 'org-after-todo-state-change-hook)
12503 (when (and arg (not (member org-state org-done-keywords)))
12504 (setq head (org-get-todo-sequence-head org-state)))
12505 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12506 ;; Do we need to trigger a repeat?
12507 (when now-done-p
12508 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12509 ;; This is for the agenda, take a snapshot of the headline.
12510 (save-match-data
12511 (setq org-agenda-headline-snapshot-before-repeat
12512 (org-get-heading))))
12513 (org-auto-repeat-maybe org-state))
12514 ;; Fixup cursor location if close to the keyword.
12515 (when (and (outline-on-heading-p)
12516 (not (bolp))
12517 (save-excursion (beginning-of-line 1)
12518 (looking-at org-todo-line-regexp))
12519 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12520 (goto-char (or (match-end 2) (match-end 1)))
12521 (and (looking-at " ") (just-one-space)))
12522 (when org-trigger-hook
12523 (save-excursion
12524 (run-hook-with-args 'org-trigger-hook change-plist)))
12525 (when commentp (org-toggle-comment))))))))
12527 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12528 "Block turning an entry into a TODO, using the hierarchy.
12529 This checks whether the current task should be blocked from state
12530 changes. Such blocking occurs when:
12532 1. The task has children which are not all in a completed state.
12534 2. A task has a parent with the property :ORDERED:, and there
12535 are siblings prior to the current task with incomplete
12536 status.
12538 3. The parent of the task is blocked because it has siblings that should
12539 be done first, or is child of a block grandparent TODO entry."
12541 (if (not org-enforce-todo-dependencies)
12542 t ; if locally turned off don't block
12543 (catch 'dont-block
12544 ;; If this is not a todo state change, or if this entry is already DONE,
12545 ;; do not block
12546 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12547 (member (plist-get change-plist :from)
12548 (cons 'done org-done-keywords))
12549 (member (plist-get change-plist :to)
12550 (cons 'todo org-not-done-keywords))
12551 (not (plist-get change-plist :to)))
12552 (throw 'dont-block t))
12553 ;; If this task has children, and any are undone, it's blocked
12554 (save-excursion
12555 (org-back-to-heading t)
12556 (let ((this-level (funcall outline-level)))
12557 (outline-next-heading)
12558 (let ((child-level (funcall outline-level)))
12559 (while (and (not (eobp))
12560 (> child-level this-level))
12561 ;; this todo has children, check whether they are all
12562 ;; completed
12563 (when (and (not (org-entry-is-done-p))
12564 (org-entry-is-todo-p))
12565 (setq org-block-entry-blocking (org-get-heading))
12566 (throw 'dont-block nil))
12567 (outline-next-heading)
12568 (setq child-level (funcall outline-level))))))
12569 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12570 ;; any previous siblings are undone, it's blocked
12571 (save-excursion
12572 (org-back-to-heading t)
12573 (let* ((pos (point))
12574 (parent-pos (and (org-up-heading-safe) (point)))
12575 (case-fold-search nil))
12576 (unless parent-pos (throw 'dont-block t)) ; no parent
12577 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12578 (forward-line 1)
12579 (re-search-forward org-not-done-heading-regexp pos t))
12580 (setq org-block-entry-blocking (match-string 0))
12581 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12582 ;; Search further up the hierarchy, to see if an ancestor is blocked
12583 (while t
12584 (goto-char parent-pos)
12585 (unless (looking-at org-not-done-heading-regexp)
12586 (throw 'dont-block t)) ; do not block, parent is not a TODO
12587 (setq pos (point))
12588 (setq parent-pos (and (org-up-heading-safe) (point)))
12589 (unless parent-pos (throw 'dont-block t)) ; no parent
12590 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12591 (forward-line 1)
12592 (re-search-forward org-not-done-heading-regexp pos t)
12593 (setq org-block-entry-blocking (org-get-heading)))
12594 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12596 (defcustom org-track-ordered-property-with-tag nil
12597 "Should the ORDERED property also be shown as a tag?
12598 The ORDERED property decides if an entry should require subtasks to be
12599 completed in sequence. Since a property is not very visible, setting
12600 this option means that toggling the ORDERED property with the command
12601 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12602 not relevant for the behavior, but it makes things more visible.
12604 Note that toggling the tag with tags commands will not change the property
12605 and therefore not influence behavior!
12607 This can be t, meaning the tag ORDERED should be used, It can also be a
12608 string to select a different tag for this task."
12609 :group 'org-todo
12610 :type '(choice
12611 (const :tag "No tracking" nil)
12612 (const :tag "Track with ORDERED tag" t)
12613 (string :tag "Use other tag")))
12615 (defun org-toggle-ordered-property ()
12616 "Toggle the ORDERED property of the current entry.
12617 For better visibility, you can track the value of this property with a tag.
12618 See variable `org-track-ordered-property-with-tag'."
12619 (interactive)
12620 (let* ((t1 org-track-ordered-property-with-tag)
12621 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12622 (save-excursion
12623 (org-back-to-heading)
12624 (if (org-entry-get nil "ORDERED")
12625 (progn
12626 (org-delete-property "ORDERED")
12627 (and tag (org-toggle-tag tag 'off))
12628 (message "Subtasks can be completed in arbitrary order"))
12629 (org-entry-put nil "ORDERED" "t")
12630 (and tag (org-toggle-tag tag 'on))
12631 (message "Subtasks must be completed in sequence")))))
12633 (defun org-block-todo-from-checkboxes (change-plist)
12634 "Block turning an entry into a TODO, using checkboxes.
12635 This checks whether the current task should be blocked from state
12636 changes because there are unchecked boxes in this entry."
12637 (if (not org-enforce-todo-checkbox-dependencies)
12638 t ; if locally turned off don't block
12639 (catch 'dont-block
12640 ;; If this is not a todo state change, or if this entry is already DONE,
12641 ;; do not block
12642 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12643 (member (plist-get change-plist :from)
12644 (cons 'done org-done-keywords))
12645 (member (plist-get change-plist :to)
12646 (cons 'todo org-not-done-keywords))
12647 (not (plist-get change-plist :to)))
12648 (throw 'dont-block t))
12649 ;; If this task has checkboxes that are not checked, it's blocked
12650 (save-excursion
12651 (org-back-to-heading t)
12652 (let ((beg (point)) end)
12653 (outline-next-heading)
12654 (setq end (point))
12655 (goto-char beg)
12656 (when (org-list-search-forward
12657 (concat (org-item-beginning-re)
12658 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12659 "\\[[- ]\\]")
12660 end t)
12661 (when (boundp 'org-blocked-by-checkboxes)
12662 (setq org-blocked-by-checkboxes t))
12663 (throw 'dont-block nil))))
12664 t))) ; do not block
12666 (defun org-entry-blocked-p ()
12667 "Non-nil if entry at point is blocked."
12668 (and (not (org-entry-get nil "NOBLOCKING"))
12669 (member (org-entry-get nil "TODO") org-not-done-keywords)
12670 (not (run-hook-with-args-until-failure
12671 'org-blocker-hook
12672 (list :type 'todo-state-change
12673 :position (point)
12674 :from 'todo
12675 :to 'done)))))
12677 (defun org-update-statistics-cookies (all)
12678 "Update the statistics cookie, either from TODO or from checkboxes.
12679 This should be called with the cursor in a line with a statistics
12680 cookie. When called with a \\[universal-argument] prefix, update
12681 all statistics cookies in the buffer."
12682 (interactive "P")
12683 (if all
12684 (progn
12685 (org-update-checkbox-count 'all)
12686 (org-map-entries 'org-update-parent-todo-statistics))
12687 (if (not (org-at-heading-p))
12688 (org-update-checkbox-count)
12689 (let ((pos (point-marker))
12690 end l1 l2)
12691 (ignore-errors (org-back-to-heading t))
12692 (if (not (org-at-heading-p))
12693 (org-update-checkbox-count)
12694 (setq l1 (org-outline-level))
12695 (setq end (save-excursion
12696 (outline-next-heading)
12697 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12698 (point)))
12699 (if (and (save-excursion
12700 (re-search-forward
12701 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12702 (not (save-excursion (re-search-forward
12703 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12704 (org-update-checkbox-count)
12705 (if (and l2 (> l2 l1))
12706 (progn
12707 (goto-char end)
12708 (org-update-parent-todo-statistics))
12709 (goto-char pos)
12710 (beginning-of-line 1)
12711 (while (re-search-forward
12712 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12713 (point-at-eol) t)
12714 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12715 (goto-char pos)
12716 (move-marker pos nil)))))
12718 (defvar org-entry-property-inherited-from) ;; defined below
12719 (defun org-update-parent-todo-statistics ()
12720 "Update any statistics cookie in the parent of the current headline.
12721 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12722 the entire subtree and this will travel up the hierarchy and update
12723 statistics everywhere."
12724 (let* ((prop (save-excursion (org-up-heading-safe)
12725 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12726 (recursive (or (not org-hierarchical-todo-statistics)
12727 (and prop (string-match "\\<recursive\\>" prop))))
12728 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12730 (first t)
12731 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12732 level ltoggle l1 new ndel
12733 (cnt-all 0) (cnt-done 0) is-percent kwd
12734 checkbox-beg cookie-present)
12735 (catch 'exit
12736 (save-excursion
12737 (beginning-of-line 1)
12738 (setq ltoggle (funcall outline-level))
12739 ;; Three situations are to consider:
12741 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12742 ;; to the top-level ancestor on the headline;
12744 ;; 2. If parent has "recursive" property, repeat up to the
12745 ;; headline setting that property, taking inheritance into
12746 ;; account;
12748 ;; 3. Else, move up to direct parent and proceed only once.
12749 (while (and (setq level (org-up-heading-safe))
12750 (or recursive first)
12751 (>= (point) lim))
12752 (setq first nil cookie-present nil)
12753 (unless (and level
12754 (not (string-match
12755 "\\<checkbox\\>"
12756 (downcase (or (org-entry-get nil "COOKIE_DATA")
12757 "")))))
12758 (throw 'exit nil))
12759 (while (re-search-forward box-re (point-at-eol) t)
12760 (setq cnt-all 0 cnt-done 0 cookie-present t)
12761 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12762 (save-match-data
12763 (unless (outline-next-heading) (throw 'exit nil))
12764 (while (and (looking-at org-complex-heading-regexp)
12765 (> (setq l1 (length (match-string 1))) level))
12766 (setq kwd (and (or recursive (= l1 ltoggle))
12767 (match-string 2)))
12768 (if (or (eq org-provide-todo-statistics 'all-headlines)
12769 (and (eq org-provide-todo-statistics t)
12770 (or (member kwd org-done-keywords)))
12771 (and (listp org-provide-todo-statistics)
12772 (stringp (car org-provide-todo-statistics))
12773 (or (member kwd org-provide-todo-statistics)
12774 (member kwd org-done-keywords)))
12775 (and (listp org-provide-todo-statistics)
12776 (listp (car org-provide-todo-statistics))
12777 (or (member kwd (car org-provide-todo-statistics))
12778 (and (member kwd org-done-keywords)
12779 (member kwd (cadr org-provide-todo-statistics))))))
12780 (setq cnt-all (1+ cnt-all))
12781 (and (eq org-provide-todo-statistics t)
12783 (setq cnt-all (1+ cnt-all))))
12784 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12785 (member kwd org-done-keywords))
12786 (and (listp org-provide-todo-statistics)
12787 (listp (car org-provide-todo-statistics))
12788 (member kwd org-done-keywords)
12789 (member kwd (cadr org-provide-todo-statistics)))
12790 (and (listp org-provide-todo-statistics)
12791 (stringp (car org-provide-todo-statistics))
12792 (member kwd org-done-keywords)))
12793 (setq cnt-done (1+ cnt-done)))
12794 (outline-next-heading)))
12795 (setq new
12796 (if is-percent
12797 (format "[%d%%]" (floor (* 100.0 cnt-done)
12798 (max 1 cnt-all)))
12799 (format "[%d/%d]" cnt-done cnt-all))
12800 ndel (- (match-end 0) checkbox-beg))
12801 (goto-char checkbox-beg)
12802 (insert new)
12803 (delete-region (point) (+ (point) ndel))
12804 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12805 (when cookie-present
12806 (run-hook-with-args 'org-after-todo-statistics-hook
12807 cnt-done (- cnt-all cnt-done))))))
12808 (run-hooks 'org-todo-statistics-hook)))
12810 (defvar org-after-todo-statistics-hook nil
12811 "Hook that is called after a TODO statistics cookie has been updated.
12812 Each function is called with two arguments: the number of not-done entries
12813 and the number of done entries.
12815 For example, the following function, when added to this hook, will switch
12816 an entry to DONE when all children are done, and back to TODO when new
12817 entries are set to a TODO status. Note that this hook is only called
12818 when there is a statistics cookie in the headline!
12820 (defun org-summary-todo (n-done n-not-done)
12821 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12822 (let (org-log-done org-log-states) ; turn off logging
12823 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12826 (defvar org-todo-statistics-hook nil
12827 "Hook that is run whenever Org thinks TODO statistics should be updated.
12828 This hook runs even if there is no statistics cookie present, in which case
12829 `org-after-todo-statistics-hook' would not run.")
12831 (defun org-todo-trigger-tag-changes (state)
12832 "Apply the changes defined in `org-todo-state-tags-triggers'."
12833 (let ((l org-todo-state-tags-triggers)
12834 changes)
12835 (when (or (not state) (equal state ""))
12836 (setq changes (append changes (cdr (assoc "" l)))))
12837 (when (and (stringp state) (> (length state) 0))
12838 (setq changes (append changes (cdr (assoc state l)))))
12839 (when (member state org-not-done-keywords)
12840 (setq changes (append changes (cdr (assq 'todo l)))))
12841 (when (member state org-done-keywords)
12842 (setq changes (append changes (cdr (assq 'done l)))))
12843 (dolist (c changes)
12844 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12846 (defun org-local-logging (value)
12847 "Get logging settings from a property VALUE."
12848 ;; Directly set the variables, they are already local.
12849 (setq org-log-done nil
12850 org-log-repeat nil
12851 org-todo-log-states nil)
12852 (dolist (w (split-string value))
12853 (let (a)
12854 (cond
12855 ((setq a (assoc w org-startup-options))
12856 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12857 (set (nth 1 a) (nth 2 a))))
12858 ((setq a (org-extract-log-state-settings w))
12859 (and (member (car a) org-todo-keywords-1)
12860 (push a org-todo-log-states)))))))
12862 (defun org-get-todo-sequence-head (kwd)
12863 "Return the head of the TODO sequence to which KWD belongs.
12864 If KWD is not set, check if there is a text property remembering the
12865 right sequence."
12866 (let (p)
12867 (cond
12868 ((not kwd)
12869 (or (get-text-property (point-at-bol) 'org-todo-head)
12870 (progn
12871 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12872 nil (point-at-eol)))
12873 (get-text-property p 'org-todo-head))))
12874 ((not (member kwd org-todo-keywords-1))
12875 (car org-todo-keywords-1))
12876 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12878 (defun org-fast-todo-selection ()
12879 "Fast TODO keyword selection with single keys.
12880 Returns the new TODO keyword, or nil if no state change should occur."
12881 (let* ((fulltable org-todo-key-alist)
12882 (done-keywords org-done-keywords) ;; needed for the faces.
12883 (maxlen (apply 'max (mapcar
12884 (lambda (x)
12885 (if (stringp (car x)) (string-width (car x)) 0))
12886 fulltable)))
12887 (expert nil)
12888 (fwidth (+ maxlen 3 1 3))
12889 (ncol (/ (- (window-width) 4) fwidth))
12890 tg cnt e c tbl
12891 groups ingroup)
12892 (save-excursion
12893 (save-window-excursion
12894 (if expert
12895 (set-buffer (get-buffer-create " *Org todo*"))
12896 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12897 (erase-buffer)
12898 (setq-local org-done-keywords done-keywords)
12899 (setq tbl fulltable cnt 0)
12900 (while (setq e (pop tbl))
12901 (cond
12902 ((equal e '(:startgroup))
12903 (push '() groups) (setq ingroup t)
12904 (unless (= cnt 0)
12905 (setq cnt 0)
12906 (insert "\n"))
12907 (insert "{ "))
12908 ((equal e '(:endgroup))
12909 (setq ingroup nil cnt 0)
12910 (insert "}\n"))
12911 ((equal e '(:newline))
12912 (unless (= cnt 0)
12913 (setq cnt 0)
12914 (insert "\n")
12915 (setq e (car tbl))
12916 (while (equal (car tbl) '(:newline))
12917 (insert "\n")
12918 (setq tbl (cdr tbl)))))
12920 (setq tg (car e) c (cdr e))
12921 (when ingroup (push tg (car groups)))
12922 (setq tg (org-add-props tg nil 'face
12923 (org-get-todo-face tg)))
12924 (when (and (= cnt 0) (not ingroup)) (insert " "))
12925 (insert "[" c "] " tg (make-string
12926 (- fwidth 4 (length tg)) ?\ ))
12927 (when (= (setq cnt (1+ cnt)) ncol)
12928 (insert "\n")
12929 (when ingroup (insert " "))
12930 (setq cnt 0)))))
12931 (insert "\n")
12932 (goto-char (point-min))
12933 (unless expert (org-fit-window-to-buffer))
12934 (message "[a-z..]:Set [SPC]:clear")
12935 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12936 (cond
12937 ((or (= c ?\C-g)
12938 (and (= c ?q) (not (rassoc c fulltable))))
12939 (setq quit-flag t))
12940 ((= c ?\ ) nil)
12941 ((setq e (rassoc c fulltable) tg (car e))
12943 (t (setq quit-flag t)))))))
12945 (defun org-entry-is-todo-p ()
12946 (member (org-get-todo-state) org-not-done-keywords))
12948 (defun org-entry-is-done-p ()
12949 (member (org-get-todo-state) org-done-keywords))
12951 (defun org-get-todo-state ()
12952 "Return the TODO keyword of the current subtree."
12953 (save-excursion
12954 (org-back-to-heading t)
12955 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12956 (match-end 2)
12957 (match-string 2))))
12959 (defun org-at-date-range-p (&optional inactive-ok)
12960 "Non-nil if point is inside a date range.
12962 When optional argument INACTIVE-OK is non-nil, also consider
12963 inactive time ranges.
12965 When this function returns a non-nil value, match data is set
12966 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12967 on INACTIVE-OK."
12968 (interactive)
12969 (save-excursion
12970 (catch 'exit
12971 (let ((pos (point)))
12972 (skip-chars-backward "^[<\r\n")
12973 (skip-chars-backward "<[")
12974 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12975 (>= (match-end 0) pos)
12976 (throw 'exit t))
12977 (skip-chars-backward "^<[\r\n")
12978 (skip-chars-backward "<[")
12979 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12980 (>= (match-end 0) pos)
12981 (throw 'exit t)))
12982 nil)))
12984 (defun org-get-repeat (&optional timestamp)
12985 "Check if there is a time-stamp with repeater in this entry.
12987 Return the repeater, as a string, or nil. Also return nil when
12988 this function is called before first heading.
12990 When optional argument TIMESTAMP is a string, extract the
12991 repeater from there instead."
12992 (save-match-data
12993 (cond (timestamp
12994 (and (string-match org-repeat-re timestamp)
12995 (match-string-no-properties 1 timestamp)))
12996 ((org-before-first-heading-p) nil)
12998 (save-excursion
12999 (org-back-to-heading t)
13000 (let ((end (org-entry-end-position)))
13001 (catch :repeat
13002 (while (re-search-forward org-repeat-re end t)
13003 (when (save-match-data (org-at-timestamp-p 'agenda))
13004 (throw :repeat (match-string-no-properties 1)))))))))))
13006 (defvar org-last-changed-timestamp)
13007 (defvar org-last-inserted-timestamp)
13008 (defvar org-log-post-message)
13009 (defvar org-log-note-purpose)
13010 (defvar org-log-note-how nil)
13011 (defvar org-log-note-extra)
13012 (defun org-auto-repeat-maybe (done-word)
13013 "Check if the current headline contains a repeated time-stamp.
13015 If yes, set TODO state back to what it was and change the base date
13016 of repeating deadline/scheduled time stamps to new date.
13018 This function is run automatically after each state change to a DONE state."
13019 (let* ((repeat (org-get-repeat))
13020 (aa (assoc org-last-state org-todo-kwd-alist))
13021 (interpret (nth 1 aa))
13022 (head (nth 2 aa))
13023 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13024 (msg "Entry repeats: ")
13025 (org-log-done nil)
13026 (org-todo-log-states nil)
13027 (end (copy-marker (org-entry-end-position))))
13028 (unwind-protect
13029 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13030 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13031 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13032 org-todo-repeat-to-state)))
13033 (org-todo (cond
13034 ((and to-state (member to-state org-todo-keywords-1))
13035 to-state)
13036 ((eq interpret 'type) org-last-state)
13037 (head)
13038 (t 'none))))
13039 (org-back-to-heading t)
13040 (org-add-planning-info nil nil 'closed)
13041 ;; When `org-log-repeat' is non-nil or entry contains
13042 ;; a clock, set LAST_REPEAT property.
13043 (when (or org-log-repeat
13044 (catch :clock
13045 (save-excursion
13046 (while (re-search-forward org-clock-line-re end t)
13047 (when (org-at-clock-log-p) (throw :clock t))))))
13048 (org-entry-put nil "LAST_REPEAT" (format-time-string
13049 (org-time-stamp-format t t)
13050 (current-time))))
13051 (when org-log-repeat
13052 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13053 (memq 'org-add-log-note post-command-hook))
13054 ;; We are already setup for some record.
13055 (when (eq org-log-repeat 'note)
13056 ;; Make sure we take a note, not only a time stamp.
13057 (setq org-log-note-how 'note))
13058 ;; Set up for taking a record.
13059 (org-add-log-setup 'state
13060 (or done-word (car org-done-keywords))
13061 org-last-state
13062 org-log-repeat)))
13063 (let ((planning-re (regexp-opt
13064 (list org-scheduled-string org-deadline-string))))
13065 (while (re-search-forward org-ts-regexp end t)
13066 (let* ((ts (match-string 0))
13067 (planning? (org-at-planning-p))
13068 (type (if (not planning?) "Plain:"
13069 (save-excursion
13070 (re-search-backward
13071 planning-re (line-beginning-position) t)
13072 (match-string 0)))))
13073 (cond
13074 ;; Ignore fake time-stamps (e.g., within comments).
13075 ((not (org-at-timestamp-p 'agenda)))
13076 ;; Time-stamps without a repeater are usually
13077 ;; skipped. However, a SCHEDULED time-stamp without
13078 ;; one is removed, as they are no longer relevant.
13079 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13080 ts))
13081 (when (equal type org-scheduled-string)
13082 (org-remove-timestamp-with-keyword type)))
13084 (let ((n (string-to-number (match-string 2 ts)))
13085 (what (match-string 3 ts)))
13086 (when (equal what "w") (setq n (* n 7) what "d"))
13087 (when (and (equal what "h")
13088 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13089 ts)))
13090 (user-error
13091 "Cannot repeat in Repeat in %d hour(s) because no hour \
13092 has been set"
13094 ;; Preparation, see if we need to modify the start
13095 ;; date for the change.
13096 (when (match-end 1)
13097 (let ((time (save-match-data
13098 (org-time-string-to-time ts))))
13099 (cond
13100 ((equal (match-string 1 ts) ".")
13101 ;; Shift starting date to today
13102 (org-timestamp-change
13103 (- (org-today) (time-to-days time))
13104 'day))
13105 ((equal (match-string 1 ts) "+")
13106 (let ((nshiftmax 10)
13107 (nshift 0))
13108 (while (or (= nshift 0)
13109 (not (time-less-p (current-time) time)))
13110 (when (= (cl-incf nshift) nshiftmax)
13111 (or (y-or-n-p
13112 (format "%d repeater intervals were not \
13113 enough to shift date past today. Continue? "
13114 nshift))
13115 (user-error "Abort")))
13116 (org-timestamp-change n (cdr (assoc what whata)))
13117 (org-in-regexp org-ts-regexp3)
13118 (setq ts (match-string 1))
13119 (setq time
13120 (save-match-data
13121 (org-time-string-to-time ts)))))
13122 (org-timestamp-change (- n) (cdr (assoc what whata)))
13123 ;; Rematch, so that we have everything in place
13124 ;; for the real shift.
13125 (org-in-regexp org-ts-regexp3)
13126 (setq ts (match-string 1))
13127 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13128 ts)))))
13129 (save-excursion
13130 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13131 (setq msg
13132 (concat
13133 msg type " " org-last-changed-timestamp " "))))))))
13134 (setq org-log-post-message msg)
13135 (message "%s" msg))
13136 (set-marker end nil))))
13138 (defun org-show-todo-tree (arg)
13139 "Make a compact tree which shows all headlines marked with TODO.
13140 The tree will show the lines where the regexp matches, and all higher
13141 headlines above the match.
13142 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13143 With a numeric prefix N, construct a sparse tree for the Nth element
13144 of `org-todo-keywords-1'."
13145 (interactive "P")
13146 (let ((case-fold-search nil)
13147 (kwd-re
13148 (cond ((null arg) org-not-done-regexp)
13149 ((equal arg '(4))
13150 (let ((kwd
13151 (completing-read "Keyword (or KWD1|KWD2|...): "
13152 (mapcar #'list org-todo-keywords-1))))
13153 (concat "\\("
13154 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13155 "\\)\\>")))
13156 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13157 (regexp-quote (nth (1- (prefix-numeric-value arg))
13158 org-todo-keywords-1)))
13159 (t (user-error "Invalid prefix argument: %s" arg)))))
13160 (message "%d TODO entries found"
13161 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13163 (defun org--deadline-or-schedule (arg type time)
13164 "Insert DEADLINE or SCHEDULE information in current entry.
13165 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13166 `org-schedule' for information about ARG and TIME arguments."
13167 (let* ((deadline? (eq type 'deadline))
13168 (keyword (if deadline? org-deadline-string org-scheduled-string))
13169 (log (if deadline? org-log-redeadline org-log-reschedule))
13170 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13171 (old-date-time (and old-date (org-time-string-to-time old-date)))
13172 ;; Save repeater cookie from either TIME or current scheduled
13173 ;; time stamp. We are going to insert it back at the end of
13174 ;; the process.
13175 (repeater (or (and (org-string-nw-p time)
13176 ;; We use `org-repeat-re' because we need
13177 ;; to tell the difference between a real
13178 ;; repeater and a time delta, e.g. "+2d".
13179 (string-match org-repeat-re time)
13180 (match-string 1 time))
13181 (and (org-string-nw-p old-date)
13182 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13183 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13184 old-date)
13185 (match-string 1 old-date)))))
13186 (pcase arg
13187 (`(4)
13188 (when (and old-date log)
13189 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13190 nil old-date log))
13191 (org-remove-timestamp-with-keyword keyword)
13192 (message (if deadline? "Item no longer has a deadline."
13193 "Item is no longer scheduled.")))
13194 (`(16)
13195 (save-excursion
13196 (org-back-to-heading t)
13197 (let ((regexp (if deadline? org-deadline-time-regexp
13198 org-scheduled-time-regexp)))
13199 (if (not (re-search-forward regexp (line-end-position 2) t))
13200 (user-error (if deadline? "No deadline information to update"
13201 "No scheduled information to update"))
13202 (let* ((rpl0 (match-string 1))
13203 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13204 (msg (if deadline? "Warn starting from" "Delay until")))
13205 (replace-match
13206 (concat keyword
13207 " <" rpl
13208 (format " -%dd"
13209 (abs (- (time-to-days
13210 (save-match-data
13211 (org-read-date
13212 nil t nil msg old-date-time)))
13213 (time-to-days old-date-time))))
13214 ">") t t))))))
13216 (org-add-planning-info type time 'closed)
13217 (when (and old-date
13219 (not (equal old-date org-last-inserted-timestamp)))
13220 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13221 org-last-inserted-timestamp
13222 old-date
13223 log))
13224 (when repeater
13225 (save-excursion
13226 (org-back-to-heading t)
13227 (when (re-search-forward
13228 (concat keyword " " org-last-inserted-timestamp)
13229 (line-end-position 2)
13231 (goto-char (1- (match-end 0)))
13232 (insert " " repeater)
13233 (setq org-last-inserted-timestamp
13234 (concat (substring org-last-inserted-timestamp 0 -1)
13235 " " repeater
13236 (substring org-last-inserted-timestamp -1))))))
13237 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13238 org-last-inserted-timestamp)))))
13240 (defun org-deadline (arg &optional time)
13241 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13242 With one universal prefix argument, remove any deadline from the item.
13243 With two universal prefix arguments, prompt for a warning delay.
13244 With argument TIME, set the deadline at the corresponding date. TIME
13245 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13246 (interactive "P")
13247 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13248 (org-map-entries
13249 (lambda () (org--deadline-or-schedule arg 'deadline time))
13251 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13252 'region-start-level
13253 'region)
13254 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13255 (org--deadline-or-schedule arg 'deadline time)))
13257 (defun org-schedule (arg &optional time)
13258 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13259 With one universal prefix argument, remove any scheduling date from the item.
13260 With two universal prefix arguments, prompt for a delay cookie.
13261 With argument TIME, scheduled at the corresponding date. TIME can
13262 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13263 (interactive "P")
13264 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13265 (org-map-entries
13266 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13268 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13269 'region-start-level
13270 'region)
13271 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13272 (org--deadline-or-schedule arg 'scheduled time)))
13274 (defun org-get-scheduled-time (pom &optional inherit)
13275 "Get the scheduled time as a time tuple, of a format suitable
13276 for calling org-schedule with, or if there is no scheduling,
13277 returns nil."
13278 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13279 (when time
13280 (apply 'encode-time (org-parse-time-string time)))))
13282 (defun org-get-deadline-time (pom &optional inherit)
13283 "Get the deadline as a time tuple, of a format suitable for
13284 calling org-deadline with, or if there is no scheduling, returns
13285 nil."
13286 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13287 (when time
13288 (apply 'encode-time (org-parse-time-string time)))))
13290 (defun org-remove-timestamp-with-keyword (keyword)
13291 "Remove all time stamps with KEYWORD in the current entry."
13292 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13293 beg)
13294 (save-excursion
13295 (org-back-to-heading t)
13296 (setq beg (point))
13297 (outline-next-heading)
13298 (while (re-search-backward re beg t)
13299 (replace-match "")
13300 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13301 (equal (char-before) ?\ ))
13302 (backward-delete-char 1)
13303 (when (string-match "^[ \t]*$" (buffer-substring
13304 (point-at-bol) (point-at-eol)))
13305 (delete-region (point-at-bol)
13306 (min (point-max) (1+ (point-at-eol))))))))))
13308 (defvar org-time-was-given) ; dynamically scoped parameter
13309 (defvar org-end-time-was-given) ; dynamically scoped parameter
13311 (defun org-at-planning-p ()
13312 "Non-nil when point is on a planning info line."
13313 ;; This is as accurate and faster than `org-element-at-point' since
13314 ;; planning info location is fixed in the section.
13315 (org-with-wide-buffer
13316 (beginning-of-line)
13317 (and (looking-at-p org-planning-line-re)
13318 (eq (point)
13319 (ignore-errors
13320 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13321 (org-back-to-heading t)
13322 (org-with-limited-levels (org-back-to-heading t)))
13323 (line-beginning-position 2))))))
13325 (defun org-add-planning-info (what &optional time &rest remove)
13326 "Insert new timestamp with keyword in the planning line.
13327 WHAT indicates what kind of time stamp to add. It is a symbol
13328 among `closed', `deadline', `scheduled' and nil. TIME indicates
13329 the time to use. If none is given, the user is prompted for
13330 a date. REMOVE indicates what kind of entries to remove. An old
13331 WHAT entry will also be removed."
13332 (let (org-time-was-given org-end-time-was-given default-time default-input)
13333 (catch 'exit
13334 (when (and (memq what '(scheduled deadline))
13335 (or (not time)
13336 (and (stringp time)
13337 (string-match "^[-+]+[0-9]" time))))
13338 ;; Try to get a default date/time from existing timestamp
13339 (save-excursion
13340 (org-back-to-heading t)
13341 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13342 (when (re-search-forward (if (eq what 'scheduled)
13343 org-scheduled-time-regexp
13344 org-deadline-time-regexp)
13345 end t)
13346 (setq ts (match-string 1)
13347 default-time (apply 'encode-time (org-parse-time-string ts))
13348 default-input (and ts (org-get-compact-tod ts)))))))
13349 (when what
13350 (setq time
13351 (if (stringp time)
13352 ;; This is a string (relative or absolute), set
13353 ;; proper date.
13354 (apply #'encode-time
13355 (org-read-date-analyze
13356 time default-time (decode-time default-time)))
13357 ;; If necessary, get the time from the user
13358 (or time (org-read-date nil 'to-time nil nil
13359 default-time default-input)))))
13361 (org-with-wide-buffer
13362 (org-back-to-heading t)
13363 (forward-line)
13364 (unless (bolp) (insert "\n"))
13365 (cond ((looking-at-p org-planning-line-re)
13366 ;; Move to current indentation.
13367 (skip-chars-forward " \t")
13368 ;; Check if we have to remove something.
13369 (dolist (type (if what (cons what remove) remove))
13370 (save-excursion
13371 (when (re-search-forward
13372 (cl-case type
13373 (closed org-closed-time-regexp)
13374 (deadline org-deadline-time-regexp)
13375 (scheduled org-scheduled-time-regexp)
13376 (otherwise
13377 (error "Invalid planning type: %s" type)))
13378 (line-end-position) t)
13379 ;; Delete until next keyword or end of line.
13380 (delete-region
13381 (match-beginning 0)
13382 (if (re-search-forward org-keyword-time-not-clock-regexp
13383 (line-end-position)
13385 (match-beginning 0)
13386 (line-end-position))))))
13387 ;; If there is nothing more to add and no more keyword
13388 ;; is left, remove the line completely.
13389 (if (and (looking-at-p "[ \t]*$") (not what))
13390 (delete-region (line-beginning-position)
13391 (line-beginning-position 2))
13392 ;; If we removed last keyword, do not leave trailing
13393 ;; white space at the end of line.
13394 (let ((p (point)))
13395 (save-excursion
13396 (end-of-line)
13397 (unless (= (skip-chars-backward " \t" p) 0)
13398 (delete-region (point) (line-end-position)))))))
13399 ((not what) (throw 'exit nil)) ; Nothing to do.
13400 (t (insert-before-markers "\n")
13401 (backward-char 1)
13402 (when org-adapt-indentation
13403 (indent-to-column (1+ (org-outline-level))))))
13404 (when what
13405 ;; Insert planning keyword.
13406 (insert (cl-case what
13407 (closed org-closed-string)
13408 (deadline org-deadline-string)
13409 (scheduled org-scheduled-string)
13410 (otherwise (error "Invalid planning type: %s" what)))
13411 " ")
13412 ;; Insert associated timestamp.
13413 (let ((ts (org-insert-time-stamp
13414 time
13415 (or org-time-was-given
13416 (and (eq what 'closed) org-log-done-with-time))
13417 (eq what 'closed)
13418 nil nil (list org-end-time-was-given))))
13419 (unless (eolp) (insert " "))
13420 ts))))))
13422 (defvar org-log-note-marker (make-marker)
13423 "Marker pointing at the entry where the note is to be inserted.")
13424 (defvar org-log-note-purpose nil)
13425 (defvar org-log-note-state nil)
13426 (defvar org-log-note-previous-state nil)
13427 (defvar org-log-note-extra nil)
13428 (defvar org-log-note-window-configuration nil)
13429 (defvar org-log-note-return-to (make-marker))
13430 (defvar org-log-note-effective-time nil
13431 "Remembered current time so that dynamically scoped
13432 `org-extend-today-until' affects timestamps in state change log")
13434 (defvar org-log-post-message nil
13435 "Message to be displayed after a log note has been stored.
13436 The auto-repeater uses this.")
13438 (defun org-add-note ()
13439 "Add a note to the current entry.
13440 This is done in the same way as adding a state change note."
13441 (interactive)
13442 (org-add-log-setup 'note))
13444 (defun org-log-beginning (&optional create)
13445 "Return expected start of log notes in current entry.
13446 When optional argument CREATE is non-nil, the function creates
13447 a drawer to store notes, if necessary. Returned position ignores
13448 narrowing."
13449 (org-with-wide-buffer
13450 (let ((drawer (org-log-into-drawer)))
13451 (cond
13452 (drawer
13453 (org-end-of-meta-data)
13454 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13455 (end (if (org-at-heading-p) (point)
13456 (save-excursion (outline-next-heading) (point))))
13457 (case-fold-search t))
13458 (catch 'exit
13459 ;; Try to find existing drawer.
13460 (while (re-search-forward regexp end t)
13461 (let ((element (org-element-at-point)))
13462 (when (eq (org-element-type element) 'drawer)
13463 (let ((cend (org-element-property :contents-end element)))
13464 (when (and (not org-log-states-order-reversed) cend)
13465 (goto-char cend)))
13466 (throw 'exit nil))))
13467 ;; No drawer found. Create one, if permitted.
13468 (when create
13469 (unless (bolp) (insert "\n"))
13470 (let ((beg (point)))
13471 (insert ":" drawer ":\n:END:\n")
13472 (org-indent-region beg (point)))
13473 (end-of-line -1)))))
13475 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13476 (skip-chars-forward " \t\n")
13477 (beginning-of-line)
13478 (unless org-log-states-order-reversed
13479 (org-skip-over-state-notes)
13480 (skip-chars-backward " \t\n")
13481 (forward-line)))))
13482 (if (bolp) (point) (line-beginning-position 2))))
13484 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13485 "Set up the post command hook to take a note.
13486 If this is about to TODO state change, the new state is expected in STATE.
13487 HOW is an indicator what kind of note should be created.
13488 EXTRA is additional text that will be inserted into the notes buffer."
13489 (move-marker org-log-note-marker (point))
13490 (setq org-log-note-purpose purpose
13491 org-log-note-state state
13492 org-log-note-previous-state prev-state
13493 org-log-note-how how
13494 org-log-note-extra extra
13495 org-log-note-effective-time (org-current-effective-time))
13496 (add-hook 'post-command-hook 'org-add-log-note 'append))
13498 (defun org-skip-over-state-notes ()
13499 "Skip past the list of State notes in an entry."
13500 (when (ignore-errors (goto-char (org-in-item-p)))
13501 (let* ((struct (org-list-struct))
13502 (prevs (org-list-prevs-alist struct))
13503 (regexp
13504 (concat "[ \t]*- +"
13505 (replace-regexp-in-string
13506 " +" " +"
13507 (org-replace-escapes
13508 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13509 `(("%d" . ,org-ts-regexp-inactive)
13510 ("%D" . ,org-ts-regexp)
13511 ("%s" . "\"\\S-+\"")
13512 ("%S" . "\"\\S-+\"")
13513 ("%t" . ,org-ts-regexp-inactive)
13514 ("%T" . ,org-ts-regexp)
13515 ("%u" . ".*?")
13516 ("%U" . ".*?")))))))
13517 (while (looking-at-p regexp)
13518 (goto-char (or (org-list-get-next-item (point) struct prevs)
13519 (org-list-get-item-end (point) struct)))))))
13521 (defun org-add-log-note (&optional _purpose)
13522 "Pop up a window for taking a note, and add this note later."
13523 (remove-hook 'post-command-hook 'org-add-log-note)
13524 (setq org-log-note-window-configuration (current-window-configuration))
13525 (delete-other-windows)
13526 (move-marker org-log-note-return-to (point))
13527 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13528 (goto-char org-log-note-marker)
13529 (org-switch-to-buffer-other-window "*Org Note*")
13530 (erase-buffer)
13531 (if (memq org-log-note-how '(time state))
13532 (org-store-log-note)
13533 (let ((org-inhibit-startup t)) (org-mode))
13534 (insert (format "# Insert note for %s.
13535 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13536 (cond
13537 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13538 ((eq org-log-note-purpose 'done) "closed todo item")
13539 ((eq org-log-note-purpose 'state)
13540 (format "state change from \"%s\" to \"%s\""
13541 (or org-log-note-previous-state "")
13542 (or org-log-note-state "")))
13543 ((eq org-log-note-purpose 'reschedule)
13544 "rescheduling")
13545 ((eq org-log-note-purpose 'delschedule)
13546 "no longer scheduled")
13547 ((eq org-log-note-purpose 'redeadline)
13548 "changing deadline")
13549 ((eq org-log-note-purpose 'deldeadline)
13550 "removing deadline")
13551 ((eq org-log-note-purpose 'refile)
13552 "refiling")
13553 ((eq org-log-note-purpose 'note)
13554 "this entry")
13555 (t (error "This should not happen")))))
13556 (when org-log-note-extra (insert org-log-note-extra))
13557 (setq-local org-finish-function 'org-store-log-note)
13558 (run-hooks 'org-log-buffer-setup-hook)))
13560 (defvar org-note-abort nil) ; dynamically scoped
13561 (defun org-store-log-note ()
13562 "Finish taking a log note, and insert it to where it belongs."
13563 (let ((txt (prog1 (buffer-string)
13564 (kill-buffer)))
13565 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13566 lines)
13567 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13568 (setq txt (replace-match "" t t txt)))
13569 (when (string-match "\\s-+\\'" txt)
13570 (setq txt (replace-match "" t t txt)))
13571 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13572 (when (org-string-nw-p note)
13573 (setq note
13574 (org-replace-escapes
13575 note
13576 (list (cons "%u" (user-login-name))
13577 (cons "%U" user-full-name)
13578 (cons "%t" (format-time-string
13579 (org-time-stamp-format 'long 'inactive)
13580 org-log-note-effective-time))
13581 (cons "%T" (format-time-string
13582 (org-time-stamp-format 'long nil)
13583 org-log-note-effective-time))
13584 (cons "%d" (format-time-string
13585 (org-time-stamp-format nil 'inactive)
13586 org-log-note-effective-time))
13587 (cons "%D" (format-time-string
13588 (org-time-stamp-format nil nil)
13589 org-log-note-effective-time))
13590 (cons "%s" (cond
13591 ((not org-log-note-state) "")
13592 ((string-match-p org-ts-regexp
13593 org-log-note-state)
13594 (format "\"[%s]\""
13595 (substring org-log-note-state 1 -1)))
13596 (t (format "\"%s\"" org-log-note-state))))
13597 (cons "%S"
13598 (cond
13599 ((not org-log-note-previous-state) "")
13600 ((string-match-p org-ts-regexp
13601 org-log-note-previous-state)
13602 (format "\"[%s]\""
13603 (substring
13604 org-log-note-previous-state 1 -1)))
13605 (t (format "\"%s\""
13606 org-log-note-previous-state)))))))
13607 (when lines (setq note (concat note " \\\\")))
13608 (push note lines))
13609 (when (and lines (not org-note-abort))
13610 (with-current-buffer (marker-buffer org-log-note-marker)
13611 (org-with-wide-buffer
13612 ;; Find location for the new note.
13613 (goto-char org-log-note-marker)
13614 (set-marker org-log-note-marker nil)
13615 ;; Note associated to a clock is to be located right after
13616 ;; the clock. Do not move point.
13617 (unless (eq org-log-note-purpose 'clock-out)
13618 (goto-char (org-log-beginning t)))
13619 ;; Make sure point is at the beginning of an empty line.
13620 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13621 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13622 ;; In an existing list, add a new item at the top level.
13623 ;; Otherwise, indent line like a regular one.
13624 (let ((itemp (org-in-item-p)))
13625 (if itemp
13626 (indent-line-to
13627 (let ((struct (save-excursion
13628 (goto-char itemp) (org-list-struct))))
13629 (org-list-get-ind (org-list-get-top-point struct) struct)))
13630 (org-indent-line)))
13631 (insert (org-list-bullet-string "-") (pop lines))
13632 (let ((ind (org-list-item-body-column (line-beginning-position))))
13633 (dolist (line lines)
13634 (insert "\n")
13635 (indent-line-to ind)
13636 (insert line)))
13637 (message "Note stored")
13638 (org-back-to-heading t)
13639 (org-cycle-hide-drawers 'children))
13640 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13641 ;; from within `org-add-log-note' because `buffer-undo-list'
13642 ;; is then modified outside of `org-with-remote-undo'.
13643 (when (eq this-command 'org-agenda-todo)
13644 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13645 ;; Don't add undo information when called from `org-agenda-todo'.
13646 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13647 (set-window-configuration org-log-note-window-configuration)
13648 (with-current-buffer (marker-buffer org-log-note-return-to)
13649 (goto-char org-log-note-return-to))
13650 (move-marker org-log-note-return-to nil)
13651 (when org-log-post-message (message "%s" org-log-post-message))))
13653 (defun org-remove-empty-drawer-at (pos)
13654 "Remove an empty drawer at position POS.
13655 POS may also be a marker."
13656 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13657 (org-with-wide-buffer
13658 (goto-char pos)
13659 (let ((drawer (org-element-at-point)))
13660 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13661 (not (org-element-property :contents-begin drawer)))
13662 (delete-region (org-element-property :begin drawer)
13663 (progn (goto-char (org-element-property :end drawer))
13664 (skip-chars-backward " \r\t\n")
13665 (forward-line)
13666 (point))))))))
13668 (defvar org-ts-type nil)
13669 (defun org-sparse-tree (&optional arg type)
13670 "Create a sparse tree, prompt for the details.
13671 This command can create sparse trees. You first need to select the type
13672 of match used to create the tree:
13674 t Show all TODO entries.
13675 T Show entries with a specific TODO keyword.
13676 m Show entries selected by a tags/property match.
13677 p Enter a property name and its value (both with completion on existing
13678 names/values) and show entries with that property.
13679 r Show entries matching a regular expression (`/' can be used as well).
13680 b Show deadlines and scheduled items before a date.
13681 a Show deadlines and scheduled items after a date.
13682 d Show deadlines due within `org-deadline-warning-days'.
13683 D Show deadlines and scheduled items between a date range."
13684 (interactive "P")
13685 (setq type (or type org-sparse-tree-default-date-type))
13686 (setq org-ts-type type)
13687 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13688 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13689 \[c]ycle through date types: %s"
13690 (cl-case type
13691 (all "all timestamps")
13692 (scheduled "only scheduled")
13693 (deadline "only deadline")
13694 (active "only active timestamps")
13695 (inactive "only inactive timestamps")
13696 (closed "with a closed time-stamp")
13697 (otherwise "scheduled/deadline")))
13698 (let ((answer (read-char-exclusive)))
13699 (cl-case answer
13701 (org-sparse-tree
13703 (cadr
13704 (memq type '(nil all scheduled deadline active inactive closed)))))
13705 (?d (call-interactively 'org-check-deadlines))
13706 (?b (call-interactively 'org-check-before-date))
13707 (?a (call-interactively 'org-check-after-date))
13708 (?D (call-interactively 'org-check-dates-range))
13709 (?t (call-interactively 'org-show-todo-tree))
13710 (?T (org-show-todo-tree '(4)))
13711 (?m (call-interactively 'org-match-sparse-tree))
13712 ((?p ?P)
13713 (let* ((kwd (completing-read
13714 "Property: " (mapcar #'list (org-buffer-property-keys))))
13715 (value (completing-read
13716 "Value: " (mapcar #'list (org-property-values kwd)))))
13717 (unless (string-match "\\`{.*}\\'" value)
13718 (setq value (concat "\"" value "\"")))
13719 (org-match-sparse-tree arg (concat kwd "=" value))))
13720 ((?r ?R ?/) (call-interactively 'org-occur))
13721 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13723 (defvar-local org-occur-highlights nil
13724 "List of overlays used for occur matches.")
13725 (defvar-local org-occur-parameters nil
13726 "Parameters of the active org-occur calls.
13727 This is a list, each call to org-occur pushes as cons cell,
13728 containing the regular expression and the callback, onto the list.
13729 The list can contain several entries if `org-occur' has been called
13730 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13731 will only contain one set of parameters. When the highlights are
13732 removed (for example with `C-c C-c', or with the next edit (depending
13733 on `org-remove-highlights-with-change'), this variable is emptied
13734 as well.")
13736 (defun org-occur (regexp &optional keep-previous callback)
13737 "Make a compact tree which shows all matches of REGEXP.
13739 The tree will show the lines where the regexp matches, and any other context
13740 defined in `org-show-context-detail', which see.
13742 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13743 done by a previous call to `org-occur' will be kept, to allow stacking of
13744 calls to this command.
13746 Optional argument CALLBACK can be a function of no argument. In this case,
13747 it is called with point at the end of the match, match data being set
13748 accordingly. Current match is shown only if the return value is non-nil.
13749 The function must neither move point nor alter narrowing."
13750 (interactive "sRegexp: \nP")
13751 (when (equal regexp "")
13752 (user-error "Regexp cannot be empty"))
13753 (unless keep-previous
13754 (org-remove-occur-highlights nil nil t))
13755 (push (cons regexp callback) org-occur-parameters)
13756 (let ((cnt 0))
13757 (save-excursion
13758 (goto-char (point-min))
13759 (when (or (not keep-previous) ; do not want to keep
13760 (not org-occur-highlights)) ; no previous matches
13761 ;; hide everything
13762 (org-overview))
13763 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13764 (isearch-no-upper-case-p regexp t)
13765 org-occur-case-fold-search)))
13766 (while (re-search-forward regexp nil t)
13767 (when (or (not callback)
13768 (save-match-data (funcall callback)))
13769 (setq cnt (1+ cnt))
13770 (when org-highlight-sparse-tree-matches
13771 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13772 (org-show-context 'occur-tree)))))
13773 (when org-remove-highlights-with-change
13774 (add-hook 'before-change-functions 'org-remove-occur-highlights
13775 nil 'local))
13776 (unless org-sparse-tree-open-archived-trees
13777 (org-hide-archived-subtrees (point-min) (point-max)))
13778 (run-hooks 'org-occur-hook)
13779 (when (called-interactively-p 'interactive)
13780 (message "%d match(es) for regexp %s" cnt regexp))
13781 cnt))
13783 (defun org-occur-next-match (&optional n _reset)
13784 "Function for `next-error-function' to find sparse tree matches.
13785 N is the number of matches to move, when negative move backwards.
13786 This function always goes back to the starting point when no
13787 match is found."
13788 (let* ((limit (if (< n 0) (point-min) (point-max)))
13789 (search-func (if (< n 0)
13790 'previous-single-char-property-change
13791 'next-single-char-property-change))
13792 (n (abs n))
13793 (pos (point))
13795 (catch 'exit
13796 (while (setq p1 (funcall search-func (point) 'org-type))
13797 (when (equal p1 limit)
13798 (goto-char pos)
13799 (user-error "No more matches"))
13800 (when (equal (get-char-property p1 'org-type) 'org-occur)
13801 (setq n (1- n))
13802 (when (= n 0)
13803 (goto-char p1)
13804 (throw 'exit (point))))
13805 (goto-char p1))
13806 (goto-char p1)
13807 (user-error "No more matches"))))
13809 (defun org-show-context (&optional key)
13810 "Make sure point and context are visible.
13811 Optional argument KEY, when non-nil, is a symbol. See
13812 `org-show-context-detail' for allowed values and how much is to
13813 be shown."
13814 (org-show-set-visibility
13815 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13816 ((cdr (assq key org-show-context-detail)))
13817 (t (cdr (assq 'default org-show-context-detail))))))
13819 (defun org-show-set-visibility (detail)
13820 "Set visibility around point according to DETAIL.
13821 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13822 `tree', `canonical' or t. See `org-show-context-detail' for more
13823 information."
13824 ;; Show current heading and possibly its entry, following headline
13825 ;; or all children.
13826 (if (and (org-at-heading-p) (not (eq detail 'local)))
13827 (org-flag-heading nil)
13828 (org-show-entry)
13829 ;; If point is hidden within a drawer or a block, make sure to
13830 ;; expose it.
13831 (dolist (o (overlays-at (point)))
13832 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13833 (delete-overlay o)))
13834 (unless (org-before-first-heading-p)
13835 (org-with-limited-levels
13836 (cl-case detail
13837 ((tree canonical t) (org-show-children))
13838 ((nil minimal ancestors))
13839 (t (save-excursion
13840 (outline-next-heading)
13841 (org-flag-heading nil)))))))
13842 ;; Show all siblings.
13843 (when (eq detail 'lineage) (org-show-siblings))
13844 ;; Show ancestors, possibly with their children.
13845 (when (memq detail '(ancestors lineage tree canonical t))
13846 (save-excursion
13847 (while (org-up-heading-safe)
13848 (org-flag-heading nil)
13849 (when (memq detail '(canonical t)) (org-show-entry))
13850 (when (memq detail '(tree canonical t)) (org-show-children))))))
13852 (defvar org-reveal-start-hook nil
13853 "Hook run before revealing a location.")
13855 (defun org-reveal (&optional siblings)
13856 "Show current entry, hierarchy above it, and the following headline.
13858 This can be used to show a consistent set of context around
13859 locations exposed with `org-show-context'.
13861 With optional argument SIBLINGS, on each level of the hierarchy all
13862 siblings are shown. This repairs the tree structure to what it would
13863 look like when opened with hierarchical calls to `org-cycle'.
13865 With a \\[universal-argument] \\[universal-argument] prefix, \
13866 go to the parent and show the entire tree."
13867 (interactive "P")
13868 (run-hooks 'org-reveal-start-hook)
13869 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13870 ((equal siblings '(16))
13871 (save-excursion
13872 (when (org-up-heading-safe)
13873 (org-show-subtree)
13874 (run-hook-with-args 'org-cycle-hook 'subtree))))
13875 (t (org-show-set-visibility 'lineage))))
13877 (defun org-highlight-new-match (beg end)
13878 "Highlight from BEG to END and mark the highlight is an occur headline."
13879 (let ((ov (make-overlay beg end)))
13880 (overlay-put ov 'face 'secondary-selection)
13881 (overlay-put ov 'org-type 'org-occur)
13882 (push ov org-occur-highlights)))
13884 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13885 "Remove the occur highlights from the buffer.
13886 BEG and END are ignored. If NOREMOVE is nil, remove this function
13887 from the `before-change-functions' in the current buffer."
13888 (interactive)
13889 (unless org-inhibit-highlight-removal
13890 (mapc #'delete-overlay org-occur-highlights)
13891 (setq org-occur-highlights nil)
13892 (setq org-occur-parameters nil)
13893 (unless noremove
13894 (remove-hook 'before-change-functions
13895 'org-remove-occur-highlights 'local))))
13897 ;;;; Priorities
13899 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13900 "Regular expression matching the priority indicator.")
13902 (defvar org-remove-priority-next-time nil)
13904 (defun org-priority-up ()
13905 "Increase the priority of the current item."
13906 (interactive)
13907 (org-priority 'up))
13909 (defun org-priority-down ()
13910 "Decrease the priority of the current item."
13911 (interactive)
13912 (org-priority 'down))
13914 (defun org-priority (&optional action _show)
13915 "Change the priority of an item.
13916 ACTION can be `set', `up', `down', or a character."
13917 (interactive "P")
13918 (if (equal action '(4))
13919 (org-show-priority)
13920 (unless org-enable-priority-commands
13921 (user-error "Priority commands are disabled"))
13922 (setq action (or action 'set))
13923 (let (current new news have remove)
13924 (save-excursion
13925 (org-back-to-heading t)
13926 (when (looking-at org-priority-regexp)
13927 (setq current (string-to-char (match-string 2))
13928 have t))
13929 (cond
13930 ((eq action 'remove)
13931 (setq remove t new ?\ ))
13932 ((or (eq action 'set)
13933 (integerp action))
13934 (if (not (eq action 'set))
13935 (setq new action)
13936 (message "Priority %c-%c, SPC to remove: "
13937 org-highest-priority org-lowest-priority)
13938 (save-match-data
13939 (setq new (read-char-exclusive))))
13940 (when (and (= (upcase org-highest-priority) org-highest-priority)
13941 (= (upcase org-lowest-priority) org-lowest-priority))
13942 (setq new (upcase new)))
13943 (cond ((equal new ?\ ) (setq remove t))
13944 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13945 (user-error "Priority must be between `%c' and `%c'"
13946 org-highest-priority org-lowest-priority))))
13947 ((eq action 'up)
13948 (setq new (if have
13949 (1- current) ; normal cycling
13950 ;; last priority was empty
13951 (if (eq last-command this-command)
13952 org-lowest-priority ; wrap around empty to lowest
13953 ;; default
13954 (if org-priority-start-cycle-with-default
13955 org-default-priority
13956 (1- org-default-priority))))))
13957 ((eq action 'down)
13958 (setq new (if have
13959 (1+ current) ; normal cycling
13960 ;; last priority was empty
13961 (if (eq last-command this-command)
13962 org-highest-priority ; wrap around empty to highest
13963 ;; default
13964 (if org-priority-start-cycle-with-default
13965 org-default-priority
13966 (1+ org-default-priority))))))
13967 (t (user-error "Invalid action")))
13968 (when (or (< (upcase new) org-highest-priority)
13969 (> (upcase new) org-lowest-priority))
13970 (if (and (memq action '(up down))
13971 (not have) (not (eq last-command this-command)))
13972 ;; `new' is from default priority
13973 (error
13974 "The default can not be set, see `org-default-priority' why")
13975 ;; normal cycling: `new' is beyond highest/lowest priority
13976 ;; and is wrapped around to the empty priority
13977 (setq remove t)))
13978 (setq news (format "%c" new))
13979 (if have
13980 (if remove
13981 (replace-match "" t t nil 1)
13982 (replace-match news t t nil 2))
13983 (if remove
13984 (user-error "No priority cookie found in line")
13985 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13986 (if (match-end 2)
13987 (progn
13988 (goto-char (match-end 2))
13989 (insert " [#" news "]"))
13990 (goto-char (match-beginning 3))
13991 (insert "[#" news "] "))))
13992 (org-set-tags nil 'align))
13993 (if remove
13994 (message "Priority removed")
13995 (message "Priority of current item set to %s" news)))))
13997 (defun org-show-priority ()
13998 "Show the priority of the current item.
13999 This priority is composed of the main priority given with the [#A] cookies,
14000 and by additional input from the age of a schedules or deadline entry."
14001 (interactive)
14002 (let ((pri (if (eq major-mode 'org-agenda-mode)
14003 (org-get-at-bol 'priority)
14004 (save-excursion
14005 (save-match-data
14006 (beginning-of-line)
14007 (and (looking-at org-heading-regexp)
14008 (org-get-priority (match-string 0))))))))
14009 (message "Priority is %d" (if pri pri -1000))))
14011 (defun org-get-priority (s)
14012 "Find priority cookie and return priority."
14013 (save-match-data
14014 (if (functionp org-get-priority-function)
14015 (funcall org-get-priority-function)
14016 (if (not (string-match org-priority-regexp s))
14017 (* 1000 (- org-lowest-priority org-default-priority))
14018 (* 1000 (- org-lowest-priority
14019 (string-to-char (match-string 2 s))))))))
14021 ;;;; Tags
14023 (defvar org-agenda-archives-mode)
14024 (defvar org-map-continue-from nil
14025 "Position from where mapping should continue.
14026 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14028 (defvar org-scanner-tags nil
14029 "The current tag list while the tags scanner is running.")
14031 (defvar org-trust-scanner-tags nil
14032 "Should `org-get-tags-at' use the tags for the scanner.
14033 This is for internal dynamical scoping only.
14034 When this is non-nil, the function `org-get-tags-at' will return the value
14035 of `org-scanner-tags' instead of building the list by itself. This
14036 can lead to large speed-ups when the tags scanner is used in a file with
14037 many entries, and when the list of tags is retrieved, for example to
14038 obtain a list of properties. Building the tags list for each entry in such
14039 a file becomes an N^2 operation - but with this variable set, it scales
14040 as N.")
14042 (defvar org--matcher-tags-todo-only nil)
14044 (defun org-scan-tags (action matcher todo-only &optional start-level)
14045 "Scan headline tags with inheritance and produce output ACTION.
14047 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14048 or `agenda' to produce an entry list for an agenda view. It can also be
14049 a Lisp form or a function that should be called at each matched headline, in
14050 this case the return value is a list of all return values from these calls.
14052 MATCHER is a function accepting three arguments, returning
14053 a non-nil value whenever a given set of tags qualifies a headline
14054 for inclusion. See `org-make-tags-matcher' for more information.
14055 As a special case, it can also be set to t (respectively nil) in
14056 order to match all (respectively none) headline.
14058 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14059 included in the output.
14061 START-LEVEL can be a string with asterisks, reducing the scope to
14062 headlines matching this string."
14063 (require 'org-agenda)
14064 (let* ((re (concat "^"
14065 (if start-level
14066 ;; Get the correct level to match
14067 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14068 org-outline-regexp)
14069 " *\\(\\<\\("
14070 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14071 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14072 (props (list 'face 'default
14073 'done-face 'org-agenda-done
14074 'undone-face 'default
14075 'mouse-face 'highlight
14076 'org-not-done-regexp org-not-done-regexp
14077 'org-todo-regexp org-todo-regexp
14078 'org-complex-heading-regexp org-complex-heading-regexp
14079 'help-echo
14080 (format "mouse-2 or RET jump to org file %s"
14081 (abbreviate-file-name
14082 (or (buffer-file-name (buffer-base-buffer))
14083 (buffer-name (buffer-base-buffer)))))))
14084 (org-map-continue-from nil)
14085 lspos tags tags-list
14086 (tags-alist (list (cons 0 org-file-tags)))
14087 (llast 0) rtn rtn1 level category i txt
14088 todo marker entry priority
14089 ts-date ts-date-type ts-date-pair)
14090 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14091 (setq action (list 'lambda nil action)))
14092 (save-excursion
14093 (goto-char (point-min))
14094 (when (eq action 'sparse-tree)
14095 (org-overview)
14096 (org-remove-occur-highlights))
14097 (while (let (case-fold-search)
14098 (re-search-forward re nil t))
14099 (setq org-map-continue-from nil)
14100 (catch :skip
14101 (setq todo
14102 ;; TODO: is the 1-2 difference a bug?
14103 (when (match-end 1) (match-string-no-properties 2))
14104 tags (when (match-end 4) (match-string-no-properties 4)))
14105 (goto-char (setq lspos (match-beginning 0)))
14106 (setq level (org-reduced-level (org-outline-level))
14107 category (org-get-category))
14108 (when (eq action 'agenda)
14109 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14110 ts-date (car ts-date-pair)
14111 ts-date-type (cdr ts-date-pair)))
14112 (setq i llast llast level)
14113 ;; remove tag lists from same and sublevels
14114 (while (>= i level)
14115 (when (setq entry (assoc i tags-alist))
14116 (setq tags-alist (delete entry tags-alist)))
14117 (setq i (1- i)))
14118 ;; add the next tags
14119 (when tags
14120 (setq tags (org-split-string tags ":")
14121 tags-alist
14122 (cons (cons level tags) tags-alist)))
14123 ;; compile tags for current headline
14124 (setq tags-list
14125 (if org-use-tag-inheritance
14126 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14127 tags)
14128 org-scanner-tags tags-list)
14129 (when org-use-tag-inheritance
14130 (setcdr (car tags-alist)
14131 (mapcar (lambda (x)
14132 (setq x (copy-sequence x))
14133 (org-add-prop-inherited x))
14134 (cdar tags-alist))))
14135 (when (and tags org-use-tag-inheritance
14136 (or (not (eq t org-use-tag-inheritance))
14137 org-tags-exclude-from-inheritance))
14138 ;; Selective inheritance, remove uninherited ones.
14139 (setcdr (car tags-alist)
14140 (org-remove-uninherited-tags (cdar tags-alist))))
14141 (when (and
14143 ;; eval matcher only when the todo condition is OK
14144 (and (or (not todo-only) (member todo org-todo-keywords-1))
14145 (if (functionp matcher)
14146 (let ((case-fold-search t) (org-trust-scanner-tags t))
14147 (funcall matcher todo tags-list level))
14148 matcher))
14150 ;; Call the skipper, but return t if it does not
14151 ;; skip, so that the `and' form continues evaluating.
14152 (progn
14153 (unless (eq action 'sparse-tree) (org-agenda-skip))
14156 ;; Check if timestamps are deselecting this entry
14157 (or (not todo-only)
14158 (and (member todo org-todo-keywords-1)
14159 (or (not org-agenda-tags-todo-honor-ignore-options)
14160 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14162 ;; select this headline
14163 (cond
14164 ((eq action 'sparse-tree)
14165 (and org-highlight-sparse-tree-matches
14166 (org-get-heading) (match-end 0)
14167 (org-highlight-new-match
14168 (match-beginning 1) (match-end 1)))
14169 (org-show-context 'tags-tree))
14170 ((eq action 'agenda)
14171 (setq txt (org-agenda-format-item
14173 (concat
14174 (if (eq org-tags-match-list-sublevels 'indented)
14175 (make-string (1- level) ?.) "")
14176 (org-get-heading))
14177 (make-string level ?\s)
14178 category
14179 tags-list)
14180 priority (org-get-priority txt))
14181 (goto-char lspos)
14182 (setq marker (org-agenda-new-marker))
14183 (org-add-props txt props
14184 'org-marker marker 'org-hd-marker marker 'org-category category
14185 'todo-state todo
14186 'ts-date ts-date
14187 'priority priority
14188 'type (concat "tagsmatch" ts-date-type))
14189 (push txt rtn))
14190 ((functionp action)
14191 (setq org-map-continue-from nil)
14192 (save-excursion
14193 (setq rtn1 (funcall action))
14194 (push rtn1 rtn)))
14195 (t (user-error "Invalid action")))
14197 ;; if we are to skip sublevels, jump to end of subtree
14198 (unless org-tags-match-list-sublevels
14199 (org-end-of-subtree t)
14200 (backward-char 1))))
14201 ;; Get the correct position from where to continue
14202 (if org-map-continue-from
14203 (goto-char org-map-continue-from)
14204 (and (= (point) lspos) (end-of-line 1)))))
14205 (when (and (eq action 'sparse-tree)
14206 (not org-sparse-tree-open-archived-trees))
14207 (org-hide-archived-subtrees (point-min) (point-max)))
14208 (nreverse rtn)))
14210 (defun org-remove-uninherited-tags (tags)
14211 "Remove all tags that are not inherited from the list TAGS."
14212 (cond
14213 ((eq org-use-tag-inheritance t)
14214 (if org-tags-exclude-from-inheritance
14215 (org-delete-all org-tags-exclude-from-inheritance tags)
14216 tags))
14217 ((not org-use-tag-inheritance) nil)
14218 ((stringp org-use-tag-inheritance)
14219 (delq nil (mapcar
14220 (lambda (x)
14221 (if (and (string-match org-use-tag-inheritance x)
14222 (not (member x org-tags-exclude-from-inheritance)))
14223 x nil))
14224 tags)))
14225 ((listp org-use-tag-inheritance)
14226 (delq nil (mapcar
14227 (lambda (x)
14228 (if (member x org-use-tag-inheritance) x nil))
14229 tags)))))
14231 (defun org-match-sparse-tree (&optional todo-only match)
14232 "Create a sparse tree according to tags string MATCH.
14234 MATCH is a string with match syntax. It can contain a selection
14235 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14236 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14237 those. See the manual for details.
14239 If optional argument TODO-ONLY is non-nil, only select lines that
14240 are also TODO tasks."
14241 (interactive "P")
14242 (org-agenda-prepare-buffers (list (current-buffer)))
14243 (let ((org--matcher-tags-todo-only todo-only))
14244 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14245 org--matcher-tags-todo-only)))
14247 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14249 (defvar org-cached-props nil)
14250 (defun org-cached-entry-get (pom property)
14251 (if (or (eq t org-use-property-inheritance)
14252 (and (stringp org-use-property-inheritance)
14253 (let ((case-fold-search t))
14254 (string-match-p org-use-property-inheritance property)))
14255 (and (listp org-use-property-inheritance)
14256 (member-ignore-case property org-use-property-inheritance)))
14257 ;; Caching is not possible, check it directly.
14258 (org-entry-get pom property 'inherit)
14259 ;; Get all properties, so we can do complicated checks easily.
14260 (cdr (assoc-string property
14261 (or org-cached-props
14262 (setq org-cached-props (org-entry-properties pom)))
14263 t))))
14265 (defun org-global-tags-completion-table (&optional files)
14266 "Return the list of all tags in all agenda buffer/files.
14267 Optional FILES argument is a list of files which can be used
14268 instead of the agenda files."
14269 (save-excursion
14270 (org-uniquify
14271 (delq nil
14272 (apply #'append
14273 (mapcar
14274 (lambda (file)
14275 (set-buffer (find-file-noselect file))
14276 (mapcar (lambda (x)
14277 (and (stringp (car-safe x))
14278 (list (car-safe x))))
14279 (or org-current-tag-alist (org-get-buffer-tags))))
14280 (if (car-safe files) files
14281 (org-agenda-files))))))))
14283 (defun org-make-tags-matcher (match)
14284 "Create the TAGS/TODO matcher form for the selection string MATCH.
14286 Returns a cons of the selection string MATCH and a function
14287 implementing the matcher.
14289 The matcher is to be called at an Org entry, with point on the
14290 headline, and returns non-nil if the entry matches the selection
14291 string MATCH. It must be called with three arguments: the TODO
14292 keyword at the entry (or nil if none), the list of all tags at
14293 the entry including inherited ones and the reduced level of the
14294 headline. Additionally, the category of the entry, if any, must
14295 be specified as the text property `org-category' on the headline.
14297 This function sets the variable `org--matcher-tags-todo-only' to
14298 a non-nil value if the matcher restricts matching to TODO
14299 entries, otherwise it is not touched.
14301 See also `org-scan-tags'."
14302 (unless match
14303 ;; Get a new match request, with completion against the global
14304 ;; tags table and the local tags in current buffer.
14305 (let ((org-last-tags-completion-table
14306 (org-uniquify
14307 (delq nil (append (org-get-buffer-tags)
14308 (org-global-tags-completion-table))))))
14309 (setq match
14310 (completing-read
14311 "Match: "
14312 'org-tags-completion-function nil nil nil 'org-tags-history))))
14314 (let ((match0 match)
14315 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14316 (start 0)
14317 tagsmatch todomatch tagsmatcher todomatcher)
14319 ;; Expand group tags.
14320 (setq match (org-tags-expand match))
14322 ;; Check if there is a TODO part of this match, which would be the
14323 ;; part after a "/". To make sure that this slash is not part of
14324 ;; a property value to be matched against, we also check that
14325 ;; there is no / after that slash. First, find the last slash.
14326 (let ((s 0))
14327 (while (string-match "/+" match s)
14328 (setq start (match-beginning 0))
14329 (setq s (match-end 0))))
14330 (if (and (string-match "/+" match start)
14331 (not (string-match-p "\"" match start)))
14332 ;; Match contains also a TODO-matching request.
14333 (progn
14334 (setq tagsmatch (substring match 0 (match-beginning 0)))
14335 (setq todomatch (substring match (match-end 0)))
14336 (when (string-prefix-p "!" todomatch)
14337 (setq org--matcher-tags-todo-only t)
14338 (setq todomatch (substring todomatch 1)))
14339 (when (string-match "\\`\\s-*\\'" todomatch)
14340 (setq todomatch nil)))
14341 ;; Only matching tags.
14342 (setq tagsmatch match)
14343 (setq todomatch nil))
14345 ;; Make the tags matcher.
14346 (when (org-string-nw-p tagsmatch)
14347 (let ((orlist nil)
14348 (orterms (org-split-string tagsmatch "|"))
14349 term)
14350 (while (setq term (pop orterms))
14351 (while (and (equal (substring term -1) "\\") orterms)
14352 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14353 (while (string-match re term)
14354 (let* ((rest (substring term (match-end 0)))
14355 (minus (and (match-end 1)
14356 (equal (match-string 1 term) "-")))
14357 (tag (save-match-data
14358 (replace-regexp-in-string
14359 "\\\\-" "-" (match-string 2 term))))
14360 (regexp (eq (string-to-char tag) ?{))
14361 (levelp (match-end 4))
14362 (propp (match-end 5))
14364 (cond
14365 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14366 (levelp
14367 `(,(org-op-to-function (match-string 3 term))
14368 level
14369 ,(string-to-number (match-string 4 term))))
14370 (propp
14371 (let* ((gv (pcase (upcase (match-string 5 term))
14372 ("CATEGORY"
14373 '(get-text-property (point) 'org-category))
14374 ("TODO" 'todo)
14375 (p `(org-cached-entry-get nil ,p))))
14376 (pv (match-string 7 term))
14377 (regexp (eq (string-to-char pv) ?{))
14378 (strp (eq (string-to-char pv) ?\"))
14379 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14380 (po (org-op-to-function (match-string 6 term)
14381 (if timep 'time strp))))
14382 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14383 (when timep (setq pv (org-matcher-time pv)))
14384 (cond ((and regexp (eq po 'org<>))
14385 `(not (string-match ,pv (or ,gv ""))))
14386 (regexp `(string-match ,pv (or ,gv "")))
14387 (strp `(,po (or ,gv "") ,pv))
14389 `(,po
14390 (string-to-number (or ,gv ""))
14391 ,(string-to-number pv))))))
14392 (t `(member ,tag tags-list)))))
14393 (push (if minus `(not ,mm) mm) tagsmatcher)
14394 (setq term rest)))
14395 (push `(and ,@tagsmatcher) orlist)
14396 (setq tagsmatcher nil))
14397 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14399 ;; Make the TODO matcher.
14400 (when (org-string-nw-p todomatch)
14401 (let ((orlist nil))
14402 (dolist (term (org-split-string todomatch "|"))
14403 (while (string-match re term)
14404 (let* ((minus (and (match-end 1)
14405 (equal (match-string 1 term) "-")))
14406 (kwd (match-string 2 term))
14407 (regexp (eq (string-to-char kwd) ?{))
14408 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14409 `(equal todo ,kwd))))
14410 (push (if minus `(not ,mm) mm) todomatcher))
14411 (setq term (substring term (match-end 0))))
14412 (push (if (> (length todomatcher) 1)
14413 (cons 'and todomatcher)
14414 (car todomatcher))
14415 orlist)
14416 (setq todomatcher nil))
14417 (setq todomatcher (cons 'or orlist))))
14419 ;; Return the string and function of the matcher. If no
14420 ;; tags-specific or todo-specific matcher exists, match
14421 ;; everything.
14422 (let ((matcher (if (and tagsmatcher todomatcher)
14423 `(and ,tagsmatcher ,todomatcher)
14424 (or tagsmatcher todomatcher t))))
14425 (when org--matcher-tags-todo-only
14426 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14427 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14429 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14430 "Expand group tags in MATCH.
14432 This replaces every group tag in MATCH with a regexp tag search.
14433 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14434 will be replaced like this:
14436 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14437 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14438 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14440 Replacing by a regexp preserves the structure of the match.
14441 E.g., this expansion
14443 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14445 will match anything tagged with \"Lab\" and \"Home\", or tagged
14446 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14448 A group tag in MATCH can contain regular expressions of its own.
14449 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14450 will be replaced like this:
14452 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14454 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14455 assumed to be a single group tag, and the function will return
14456 the list of tags in this group.
14458 When DOWNCASE is non-nil, expand downcased TAGS."
14459 (if org-group-tags
14460 (let* ((case-fold-search t)
14461 (stable org-mode-syntax-table)
14462 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14463 (taggroups (if downcased
14464 (mapcar (lambda (tg) (mapcar #'downcase tg))
14465 taggroups)
14466 taggroups))
14467 (taggroups-keys (mapcar #'car taggroups))
14468 (return-match (if downcased (downcase match) match))
14469 (count 0)
14470 (work-already-expanded tags-already-expanded)
14471 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14472 ;; @ and _ are allowed as word-components in tags.
14473 (modify-syntax-entry ?@ "w" stable)
14474 (modify-syntax-entry ?_ "w" stable)
14475 ;; Temporarily replace regexp-expressions in the match-expression.
14476 (while (string-match "{.+?}" return-match)
14477 (cl-incf count)
14478 (push (match-string 0 return-match) regexps-in-match)
14479 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14480 (while (and taggroups-keys
14481 (with-syntax-table stable
14482 (string-match
14483 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14484 (regexp-opt taggroups-keys) "\\>\\)")
14485 return-match)))
14486 (let* ((dir (match-string 1 return-match))
14487 (tag (match-string 2 return-match))
14488 (tag (if downcased (downcase tag) tag)))
14489 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14490 (member tag work-already-expanded))
14491 (setq tags-in-group (assoc tag taggroups))
14492 (push tag work-already-expanded)
14493 ;; Recursively expand each tag in the group, if the tag hasn't
14494 ;; already been expanded. Restore the match-data after all recursive calls.
14495 (save-match-data
14496 (let (tags-expanded)
14497 (dolist (x (cdr tags-in-group))
14498 (if (and (member x taggroups-keys)
14499 (not (member x work-already-expanded)))
14500 (setq tags-expanded
14501 (delete-dups
14502 (append
14503 (org-tags-expand x t downcased
14504 work-already-expanded)
14505 tags-expanded)))
14506 (setq tags-expanded
14507 (append (list x) tags-expanded)))
14508 (setq work-already-expanded
14509 (delete-dups
14510 (append tags-expanded
14511 work-already-expanded))))
14512 (setq tags-in-group
14513 (delete-dups (cons (car tags-in-group)
14514 tags-expanded)))))
14515 ;; Filter tag-regexps from tags.
14516 (setq regexp-in-group-escaped
14517 (delq nil (mapcar (lambda (x)
14518 (if (stringp x)
14519 (and (equal "{" (substring x 0 1))
14520 (equal "}" (substring x -1))
14523 tags-in-group))
14524 regexp-in-group
14525 (mapcar (lambda (x)
14526 (substring x 1 -1))
14527 regexp-in-group-escaped)
14528 tags-in-group
14529 (delq nil (mapcar (lambda (x)
14530 (if (stringp x)
14531 (and (not (equal "{" (substring x 0 1)))
14532 (not (equal "}" (substring x -1)))
14535 tags-in-group)))
14536 ;; If single-as-list, do no more in the while-loop.
14537 (if (not single-as-list)
14538 (progn
14539 (when regexp-in-group
14540 (setq regexp-in-group
14541 (concat "\\|"
14542 (mapconcat 'identity regexp-in-group
14543 "\\|"))))
14544 (setq tags-in-group
14545 (concat dir
14546 "{\\<"
14547 (regexp-opt tags-in-group)
14548 "\\>"
14549 regexp-in-group
14550 "}"))
14551 (when (stringp tags-in-group)
14552 (org-add-props tags-in-group '(grouptag t)))
14553 (setq return-match
14554 (replace-match tags-in-group t t return-match)))
14555 (setq tags-in-group
14556 (append regexp-in-group-escaped tags-in-group))))
14557 (setq taggroups-keys (delete tag taggroups-keys))))
14558 ;; Add the regular expressions back into the match-expression again.
14559 (while regexps-in-match
14560 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14561 (pop regexps-in-match)
14562 return-match t t))
14563 (cl-decf count))
14564 (if single-as-list
14565 (if tags-in-group tags-in-group (list return-match))
14566 return-match))
14567 (if single-as-list
14568 (list (if downcased (downcase match) match))
14569 match)))
14571 (defun org-op-to-function (op &optional stringp)
14572 "Turn an operator into the appropriate function."
14573 (setq op
14574 (cond
14575 ((equal op "<" ) '(< string< org-time<))
14576 ((equal op ">" ) '(> org-string> org-time>))
14577 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14578 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14579 ((member op '("=" "==")) '(= string= org-time=))
14580 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14581 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14583 (defun org<> (a b) (not (= a b)))
14584 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14585 (defun org-string>= (a b) (not (string< a b)))
14586 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14587 (defun org-string<> (a b) (not (string= a b)))
14588 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14589 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14590 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14591 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14592 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14593 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14594 (defun org-2ft (s)
14595 "Convert S to a floating point time.
14596 If S is already a number, just return it. If it is a string, parse
14597 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14598 (cond
14599 ((numberp s) s)
14600 ((stringp s)
14601 (condition-case nil
14602 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14603 (error 0.)))
14604 (t 0.)))
14606 (defun org-time-today ()
14607 "Time in seconds today at 0:00.
14608 Returns the float number of seconds since the beginning of the
14609 epoch to the beginning of today (00:00)."
14610 (float-time (apply 'encode-time
14611 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14613 (defun org-matcher-time (s)
14614 "Interpret a time comparison value."
14615 (save-match-data
14616 (cond
14617 ((string= s "<now>") (float-time))
14618 ((string= s "<today>") (org-time-today))
14619 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14620 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14621 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14622 (+ (org-time-today)
14623 (* (string-to-number (match-string 1 s))
14624 (cdr (assoc (match-string 2 s)
14625 '(("d" . 86400.0) ("w" . 604800.0)
14626 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14627 (t (org-2ft s)))))
14629 (defun org-match-any-p (re list)
14630 "Does re match any element of list?"
14631 (setq list (mapcar (lambda (x) (string-match re x)) list))
14632 (delq nil list))
14634 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14635 (defvar org-tags-overlay (make-overlay 1 1))
14636 (delete-overlay org-tags-overlay)
14638 (defun org-get-local-tags-at (&optional pos)
14639 "Get a list of tags defined in the current headline."
14640 (org-get-tags-at pos 'local))
14642 (defun org-get-local-tags ()
14643 "Get a list of tags defined in the current headline."
14644 (org-get-tags-at nil 'local))
14646 (defun org-get-tags-at (&optional pos local)
14647 "Get a list of all headline tags applicable at POS.
14648 POS defaults to point. If tags are inherited, the list contains
14649 the targets in the same sequence as the headlines appear, i.e.
14650 the tags of the current headline come last.
14651 When LOCAL is non-nil, only return tags from the current headline,
14652 ignore inherited ones."
14653 (interactive)
14654 (if (and org-trust-scanner-tags
14655 (or (not pos) (equal pos (point)))
14656 (not local))
14657 org-scanner-tags
14658 (let (tags ltags lastpos parent)
14659 (save-excursion
14660 (save-restriction
14661 (widen)
14662 (goto-char (or pos (point)))
14663 (save-match-data
14664 (catch 'done
14665 (condition-case nil
14666 (progn
14667 (org-back-to-heading t)
14668 (while (not (equal lastpos (point)))
14669 (setq lastpos (point))
14670 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14671 (setq ltags (org-split-string
14672 (match-string-no-properties 1) ":"))
14673 (when parent
14674 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14675 (setq tags (append
14676 (if parent
14677 (org-remove-uninherited-tags ltags)
14678 ltags)
14679 tags)))
14680 (or org-use-tag-inheritance (throw 'done t))
14681 (when local (throw 'done t))
14682 (or (org-up-heading-safe) (error nil))
14683 (setq parent t)))
14684 (error nil)))))
14685 (if local
14686 tags
14687 (reverse (delete-dups
14688 (reverse (append
14689 (org-remove-uninherited-tags
14690 org-file-tags)
14691 tags)))))))))
14693 (defun org-add-prop-inherited (s)
14694 (add-text-properties 0 (length s) '(inherited t) s)
14697 (defun org-toggle-tag (tag &optional onoff)
14698 "Toggle the tag TAG for the current line.
14699 If ONOFF is `on' or `off', don't toggle but set to this state."
14700 (save-excursion
14701 (org-back-to-heading t)
14702 (let ((current
14703 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14704 (line-end-position) t)
14705 (let ((tags (match-string 1)))
14706 ;; Clear current tags.
14707 (replace-match "")
14708 ;; Reverse the tags list so any new tag is appended to
14709 ;; the current list of tags.
14710 (nreverse (org-split-string tags ":")))))
14711 res)
14712 (pcase onoff
14713 (`off (setq current (delete tag current)))
14714 ((or `on (guard (not (member tag current))))
14715 (setq res t)
14716 (cl-pushnew tag current :test #'equal))
14717 (_ (setq current (delete tag current))))
14718 (end-of-line)
14719 (if current
14720 (progn
14721 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14722 (org-set-tags nil t))
14723 (delete-horizontal-space))
14724 (run-hooks 'org-after-tags-change-hook)
14725 res)))
14727 (defun org--align-tags-here (to-col)
14728 "Align tags on the current headline to TO-COL.
14729 Assume point is on a headline."
14730 (let ((pos (point)))
14731 (beginning-of-line)
14732 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14733 (>= pos (match-beginning 2)))
14734 ;; No tags or point within tags: do not align.
14735 (goto-char pos)
14736 (goto-char (match-beginning 1))
14737 (let ((shift (max (- (if (>= to-col 0) to-col
14738 (- (abs to-col) (string-width (match-string 2))))
14739 (current-column))
14740 1)))
14741 (replace-match (make-string shift ?\s) nil nil nil 1)
14742 ;; Preserve initial position, if possible. In any case, stop
14743 ;; before tags.
14744 (when (< pos (point)) (goto-char pos))))))
14746 (defun org-set-tags-command (&optional arg just-align)
14747 "Call the set-tags command for the current entry."
14748 (interactive "P")
14749 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14750 (org-set-tags arg just-align)
14751 (save-excursion
14752 (unless (and (org-region-active-p)
14753 org-loop-over-headlines-in-active-region)
14754 (org-back-to-heading t))
14755 (org-set-tags arg just-align))))
14757 (defun org-set-tags-to (data)
14758 "Set the tags of the current entry to DATA, replacing the current tags.
14759 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14760 If DATA is nil or the empty string, any tags will be removed."
14761 (interactive "sTags: ")
14762 (setq data
14763 (cond
14764 ((eq data nil) "")
14765 ((equal data "") "")
14766 ((stringp data)
14767 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14768 ":"))
14769 ((listp data)
14770 (concat ":" (mapconcat 'identity data ":") ":"))))
14771 (when data
14772 (save-excursion
14773 (org-back-to-heading t)
14774 (when (let ((case-fold-search nil))
14775 (looking-at org-complex-heading-regexp))
14776 (if (match-end 5)
14777 (progn
14778 (goto-char (match-beginning 5))
14779 (insert data)
14780 (delete-region (point) (point-at-eol))
14781 (org-set-tags nil 'align))
14782 (goto-char (point-at-eol))
14783 (insert " " data)
14784 (org-set-tags nil 'align)))
14785 (beginning-of-line 1)
14786 (when (looking-at ".*?\\([ \t]+\\)$")
14787 (delete-region (match-beginning 1) (match-end 1))))))
14789 (defun org-align-all-tags ()
14790 "Align the tags in all headings."
14791 (interactive)
14792 (save-excursion
14793 (or (ignore-errors (org-back-to-heading t))
14794 (outline-next-heading))
14795 (if (org-at-heading-p)
14796 (org-set-tags t)
14797 (message "No headings"))))
14799 (defvar org-indent-indentation-per-level)
14800 (defun org-set-tags (&optional arg just-align)
14801 "Set the tags for the current headline.
14802 With prefix ARG, realign all tags in headings in the current buffer.
14803 When JUST-ALIGN is non-nil, only align tags."
14804 (interactive "P")
14805 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14806 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14807 'region-start-level
14808 'region))
14809 org-loop-over-headlines-in-active-region)
14810 (org-map-entries
14811 ;; We don't use ARG and JUST-ALIGN here because these args
14812 ;; are not useful when looping over headlines.
14813 #'org-set-tags
14814 org-loop-over-headlines-in-active-region
14816 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14817 (let ((org-setting-tags t))
14818 (if arg
14819 (save-excursion
14820 (goto-char (point-min))
14821 (while (re-search-forward org-outline-regexp-bol nil t)
14822 (org-set-tags nil t)
14823 (end-of-line))
14824 (message "All tags realigned to column %d" org-tags-column))
14825 (let* ((current (org-get-tags-string))
14826 (tags
14827 (if just-align current
14828 ;; Get a new set of tags from the user.
14829 (save-excursion
14830 (let* ((seen)
14831 (table
14832 (setq
14833 org-last-tags-completion-table
14834 ;; Uniquify tags in alists, yet preserve
14835 ;; structure (i.e., keywords).
14836 (delq nil
14837 (mapcar
14838 (lambda (pair)
14839 (let ((head (car pair)))
14840 (cond ((symbolp head) pair)
14841 ((member head seen) nil)
14842 (t (push head seen)
14843 pair))))
14844 (append
14845 (or org-current-tag-alist
14846 (org-get-buffer-tags))
14847 (and
14848 org-complete-tags-always-offer-all-agenda-tags
14849 (org-global-tags-completion-table
14850 (org-agenda-files))))))))
14851 (current-tags (org-split-string current ":"))
14852 (inherited-tags
14853 (nreverse (nthcdr (length current-tags)
14854 (nreverse (org-get-tags-at))))))
14855 (replace-regexp-in-string
14856 "\\([-+&]+\\|,\\)"
14858 (if (or (eq t org-use-fast-tag-selection)
14859 (and org-use-fast-tag-selection
14860 (delq nil (mapcar #'cdr table))))
14861 (org-fast-tag-selection
14862 current-tags inherited-tags table
14863 (and org-fast-tag-selection-include-todo
14864 org-todo-key-alist))
14865 (let ((org-add-colon-after-tag-completion
14866 (< 1 (length table))))
14867 (org-trim
14868 (completing-read
14869 "Tags: "
14870 #'org-tags-completion-function
14871 nil nil current 'org-tags-history))))))))))
14873 (when org-tags-sort-function
14874 (setq tags
14875 (mapconcat
14876 #'identity
14877 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14878 org-tags-sort-function)
14879 ":")))
14881 (if (or (string= ":" tags)
14882 (string= "::" tags))
14883 (setq tags ""))
14884 (if (not (org-string-nw-p tags)) (setq tags "")
14885 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14886 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14888 ;; Insert new tags at the correct column.
14889 (unless (equal current tags)
14890 (save-excursion
14891 (beginning-of-line)
14892 (let ((case-fold-search nil))
14893 (looking-at org-complex-heading-regexp))
14894 ;; Remove current tags, if any.
14895 (when (match-end 5) (replace-match "" nil nil nil 5))
14896 ;; Insert new tags, if any. Otherwise, remove trailing
14897 ;; white spaces.
14898 (end-of-line)
14899 (if (not (equal tags ""))
14900 ;; When text is being inserted on an invisible
14901 ;; region boundary, it can be inadvertently sucked
14902 ;; into invisibility.
14903 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14904 (skip-chars-backward " \t")
14905 (delete-region (point) (line-end-position)))))
14906 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14907 ;; is on.
14908 (unless (equal tags "")
14909 (let* ((level (save-excursion
14910 (beginning-of-line)
14911 (skip-chars-forward "\\*")))
14912 (offset (if (bound-and-true-p org-indent-mode)
14913 (* (1- org-indent-indentation-per-level)
14914 (1- level))
14916 (tags-column
14917 (+ org-tags-column
14918 (if (> org-tags-column 0) (- offset) offset))))
14919 (org--align-tags-here tags-column))))
14920 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14922 (defun org-change-tag-in-region (beg end tag off)
14923 "Add or remove TAG for each entry in the region.
14924 This works in the agenda, and also in an Org buffer."
14925 (interactive
14926 (list (region-beginning) (region-end)
14927 (let ((org-last-tags-completion-table
14928 (if (derived-mode-p 'org-mode)
14929 (org-uniquify
14930 (delq nil (append (org-get-buffer-tags)
14931 (org-global-tags-completion-table))))
14932 (org-global-tags-completion-table))))
14933 (completing-read
14934 "Tag: " 'org-tags-completion-function nil nil nil
14935 'org-tags-history))
14936 (progn
14937 (message "[s]et or [r]emove? ")
14938 (equal (read-char-exclusive) ?r))))
14939 (when (fboundp 'deactivate-mark) (deactivate-mark))
14940 (let ((agendap (equal major-mode 'org-agenda-mode))
14941 l1 l2 m buf pos newhead (cnt 0))
14942 (goto-char end)
14943 (setq l2 (1- (org-current-line)))
14944 (goto-char beg)
14945 (setq l1 (org-current-line))
14946 (cl-loop for l from l1 to l2 do
14947 (org-goto-line l)
14948 (setq m (get-text-property (point) 'org-hd-marker))
14949 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14950 (and agendap m))
14951 (setq buf (if agendap (marker-buffer m) (current-buffer))
14952 pos (if agendap m (point)))
14953 (with-current-buffer buf
14954 (save-excursion
14955 (save-restriction
14956 (goto-char pos)
14957 (setq cnt (1+ cnt))
14958 (org-toggle-tag tag (if off 'off 'on))
14959 (setq newhead (org-get-heading)))))
14960 (and agendap (org-agenda-change-all-lines newhead m))))
14961 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14963 (defun org-tags-completion-function (string _predicate &optional flag)
14964 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14965 (confirm (lambda (x) (stringp (car x)))))
14966 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14967 (setq s1 (match-string 1 string)
14968 s2 (match-string 2 string))
14969 (setq s1 "" s2 string))
14970 (cond
14971 ((eq flag nil)
14972 ;; try completion
14973 (setq rtn (try-completion s2 ctable confirm))
14974 (when (stringp rtn)
14975 (setq rtn
14976 (concat s1 s2 (substring rtn (length s2))
14977 (if (and org-add-colon-after-tag-completion
14978 (assoc rtn ctable))
14979 ":" ""))))
14980 rtn)
14981 ((eq flag t)
14982 ;; all-completions
14983 (all-completions s2 ctable confirm))
14984 ((eq flag 'lambda)
14985 ;; exact match?
14986 (assoc s2 ctable)))))
14988 (defun org-fast-tag-insert (kwd tags face &optional end)
14989 "Insert KDW, and the TAGS, the latter with face FACE.
14990 Also insert END."
14991 (insert (format "%-12s" (concat kwd ":"))
14992 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14993 (or end "")))
14995 (defun org-fast-tag-show-exit (flag)
14996 (save-excursion
14997 (org-goto-line 3)
14998 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14999 (replace-match ""))
15000 (when flag
15001 (end-of-line 1)
15002 (org-move-to-column (- (window-width) 19) t)
15003 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15005 (defun org-set-current-tags-overlay (current prefix)
15006 "Add an overlay to CURRENT tag with PREFIX."
15007 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15008 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15009 (org-overlay-display org-tags-overlay (concat prefix s))))
15011 (defvar org-last-tag-selection-key nil)
15012 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15013 "Fast tag selection with single keys.
15014 CURRENT is the current list of tags in the headline, INHERITED is the
15015 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15016 possibly with grouping information. TODO-TABLE is a similar table with
15017 TODO keywords, should these have keys assigned to them.
15018 If the keys are nil, a-z are automatically assigned.
15019 Returns the new tags string, or nil to not change the current settings."
15020 (let* ((fulltable (append table todo-table))
15021 (maxlen (apply 'max (mapcar
15022 (lambda (x)
15023 (if (stringp (car x)) (string-width (car x)) 0))
15024 fulltable)))
15025 (buf (current-buffer))
15026 (expert (eq org-fast-tag-selection-single-key 'expert))
15027 (buffer-tags nil)
15028 (fwidth (+ maxlen 3 1 3))
15029 (ncol (/ (- (window-width) 4) fwidth))
15030 (i-face 'org-done)
15031 (c-face 'org-todo)
15032 tg cnt e c char c1 c2 ntable tbl rtn
15033 ov-start ov-end ov-prefix
15034 (exit-after-next org-fast-tag-selection-single-key)
15035 (done-keywords org-done-keywords)
15036 groups ingroup intaggroup)
15037 (save-excursion
15038 (beginning-of-line 1)
15039 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15040 (setq ov-start (match-beginning 1)
15041 ov-end (match-end 1)
15042 ov-prefix "")
15043 (setq ov-start (1- (point-at-eol))
15044 ov-end (1+ ov-start))
15045 (skip-chars-forward "^\n\r")
15046 (setq ov-prefix
15047 (concat
15048 (buffer-substring (1- (point)) (point))
15049 (if (> (current-column) org-tags-column)
15051 (make-string (- org-tags-column (current-column)) ?\ ))))))
15052 (move-overlay org-tags-overlay ov-start ov-end)
15053 (save-window-excursion
15054 (if expert
15055 (set-buffer (get-buffer-create " *Org tags*"))
15056 (delete-other-windows)
15057 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15058 (org-switch-to-buffer-other-window " *Org tags*"))
15059 (erase-buffer)
15060 (setq-local org-done-keywords done-keywords)
15061 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15062 (org-fast-tag-insert "Current" current c-face "\n\n")
15063 (org-fast-tag-show-exit exit-after-next)
15064 (org-set-current-tags-overlay current ov-prefix)
15065 (setq tbl fulltable char ?a cnt 0)
15066 (while (setq e (pop tbl))
15067 (cond
15068 ((eq (car e) :startgroup)
15069 (push '() groups) (setq ingroup t)
15070 (unless (zerop cnt)
15071 (setq cnt 0)
15072 (insert "\n"))
15073 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15074 ((eq (car e) :endgroup)
15075 (setq ingroup nil cnt 0)
15076 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15077 ((eq (car e) :startgrouptag)
15078 (setq intaggroup t)
15079 (unless (zerop cnt)
15080 (setq cnt 0)
15081 (insert "\n"))
15082 (insert "[ "))
15083 ((eq (car e) :endgrouptag)
15084 (setq intaggroup nil cnt 0)
15085 (insert "]\n"))
15086 ((equal e '(:newline))
15087 (unless (zerop cnt)
15088 (setq cnt 0)
15089 (insert "\n")
15090 (setq e (car tbl))
15091 (while (equal (car tbl) '(:newline))
15092 (insert "\n")
15093 (setq tbl (cdr tbl)))))
15094 ((equal e '(:grouptags)) (insert " : "))
15096 (setq tg (copy-sequence (car e)) c2 nil)
15097 (if (cdr e)
15098 (setq c (cdr e))
15099 ;; automatically assign a character.
15100 (setq c1 (string-to-char
15101 (downcase (substring
15102 tg (if (= (string-to-char tg) ?@) 1 0)))))
15103 (if (or (rassoc c1 ntable) (rassoc c1 table))
15104 (while (or (rassoc char ntable) (rassoc char table))
15105 (setq char (1+ char)))
15106 (setq c2 c1))
15107 (setq c (or c2 char)))
15108 (when ingroup (push tg (car groups)))
15109 (setq tg (org-add-props tg nil 'face
15110 (cond
15111 ((not (assoc tg table))
15112 (org-get-todo-face tg))
15113 ((member tg current) c-face)
15114 ((member tg inherited) i-face))))
15115 (when (equal (caar tbl) :grouptags)
15116 (org-add-props tg nil 'face 'org-tag-group))
15117 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15118 (insert "[" c "] " tg (make-string
15119 (- fwidth 4 (length tg)) ?\ ))
15120 (push (cons tg c) ntable)
15121 (when (= (cl-incf cnt) ncol)
15122 (insert "\n")
15123 (when (or ingroup intaggroup) (insert " "))
15124 (setq cnt 0)))))
15125 (setq ntable (nreverse ntable))
15126 (insert "\n")
15127 (goto-char (point-min))
15128 (unless expert (org-fit-window-to-buffer))
15129 (setq rtn
15130 (catch 'exit
15131 (while t
15132 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15133 (if (not groups) "no " "")
15134 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15135 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15136 (setq org-last-tag-selection-key c)
15137 (cond
15138 ((= c ?\r) (throw 'exit t))
15139 ((= c ?!)
15140 (setq groups (not groups))
15141 (goto-char (point-min))
15142 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15143 ((= c ?\C-c)
15144 (if (not expert)
15145 (org-fast-tag-show-exit
15146 (setq exit-after-next (not exit-after-next)))
15147 (setq expert nil)
15148 (delete-other-windows)
15149 (set-window-buffer (split-window-vertically) " *Org tags*")
15150 (org-switch-to-buffer-other-window " *Org tags*")
15151 (org-fit-window-to-buffer)))
15152 ((or (= c ?\C-g)
15153 (and (= c ?q) (not (rassoc c ntable))))
15154 (delete-overlay org-tags-overlay)
15155 (setq quit-flag t))
15156 ((= c ?\ )
15157 (setq current nil)
15158 (when exit-after-next (setq exit-after-next 'now)))
15159 ((= c ?\t)
15160 (condition-case nil
15161 (setq tg (completing-read
15162 "Tag: "
15163 (or buffer-tags
15164 (with-current-buffer buf
15165 (setq buffer-tags
15166 (org-get-buffer-tags))))))
15167 (quit (setq tg "")))
15168 (when (string-match "\\S-" tg)
15169 (cl-pushnew (list tg) buffer-tags :test #'equal)
15170 (if (member tg current)
15171 (setq current (delete tg current))
15172 (push tg current)))
15173 (when exit-after-next (setq exit-after-next 'now)))
15174 ((setq e (rassoc c todo-table) tg (car e))
15175 (with-current-buffer buf
15176 (save-excursion (org-todo tg)))
15177 (when exit-after-next (setq exit-after-next 'now)))
15178 ((setq e (rassoc c ntable) tg (car e))
15179 (if (member tg current)
15180 (setq current (delete tg current))
15181 (cl-loop for g in groups do
15182 (when (member tg g)
15183 (dolist (x g) (setq current (delete x current)))))
15184 (push tg current))
15185 (when exit-after-next (setq exit-after-next 'now))))
15187 ;; Create a sorted list
15188 (setq current
15189 (sort current
15190 (lambda (a b)
15191 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15192 (when (eq exit-after-next 'now) (throw 'exit t))
15193 (goto-char (point-min))
15194 (beginning-of-line 2)
15195 (delete-region (point) (point-at-eol))
15196 (org-fast-tag-insert "Current" current c-face)
15197 (org-set-current-tags-overlay current ov-prefix)
15198 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15199 (setq tg (match-string 1))
15200 (add-text-properties
15201 (match-beginning 1) (match-end 1)
15202 (list 'face
15203 (cond
15204 ((member tg current) c-face)
15205 ((member tg inherited) i-face)
15206 (t (get-text-property (match-beginning 1) 'face))))))
15207 (goto-char (point-min)))))
15208 (delete-overlay org-tags-overlay)
15209 (if rtn
15210 (mapconcat 'identity current ":")
15211 nil))))
15213 (defun org-get-tags-string ()
15214 "Get the TAGS string in the current headline."
15215 (unless (org-at-heading-p t)
15216 (user-error "Not on a heading"))
15217 (save-excursion
15218 (beginning-of-line 1)
15219 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15220 (match-string-no-properties 1)
15221 "")))
15223 (defun org-get-tags ()
15224 "Get the list of tags specified in the current headline."
15225 (org-split-string (org-get-tags-string) ":"))
15227 (defun org-get-buffer-tags ()
15228 "Get a table of all tags used in the buffer, for completion."
15229 (org-with-wide-buffer
15230 (goto-char (point-min))
15231 (let ((tag-re (concat org-outline-regexp-bol
15232 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15233 tags)
15234 (while (re-search-forward tag-re nil t)
15235 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15236 (push tag tags)))
15237 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15239 ;;;; The mapping API
15241 (defvar org-agenda-skip-comment-trees)
15242 (defvar org-agenda-skip-function)
15243 (defun org-map-entries (func &optional match scope &rest skip)
15244 "Call FUNC at each headline selected by MATCH in SCOPE.
15246 FUNC is a function or a lisp form. The function will be called without
15247 arguments, with the cursor positioned at the beginning of the headline.
15248 The return values of all calls to the function will be collected and
15249 returned as a list.
15251 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15252 does not need to preserve point. After evaluation, the cursor will be
15253 moved to the end of the line (presumably of the headline of the
15254 processed entry) and search continues from there. Under some
15255 circumstances, this may not produce the wanted results. For example,
15256 if you have removed (e.g. archived) the current (sub)tree it could
15257 mean that the next entry will be skipped entirely. In such cases, you
15258 can specify the position from where search should continue by making
15259 FUNC set the variable `org-map-continue-from' to the desired buffer
15260 position.
15262 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15263 Only headlines that are matched by this query will be considered during
15264 the iteration. When MATCH is nil or t, all headlines will be
15265 visited by the iteration.
15267 SCOPE determines the scope of this command. It can be any of:
15269 nil The current buffer, respecting the restriction if any
15270 tree The subtree started with the entry at point
15271 region The entries within the active region, if any
15272 region-start-level
15273 The entries within the active region, but only those at
15274 the same level than the first one.
15275 file The current buffer, without restriction
15276 file-with-archives
15277 The current buffer, and any archives associated with it
15278 agenda All agenda files
15279 agenda-with-archives
15280 All agenda files with any archive files associated with them
15281 \(file1 file2 ...)
15282 If this is a list, all files in the list will be scanned
15284 The remaining args are treated as settings for the skipping facilities of
15285 the scanner. The following items can be given here:
15287 archive skip trees with the archive tag
15288 comment skip trees with the COMMENT keyword
15289 function or Emacs Lisp form:
15290 will be used as value for `org-agenda-skip-function', so
15291 whenever the function returns a position, FUNC will not be
15292 called for that entry and search will continue from the
15293 position returned
15295 If your function needs to retrieve the tags including inherited tags
15296 at the *current* entry, you can use the value of the variable
15297 `org-scanner-tags' which will be much faster than getting the value
15298 with `org-get-tags-at'. If your function gets properties with
15299 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15300 to t around the call to `org-entry-properties' to get the same speedup.
15301 Note that if your function moves around to retrieve tags and properties at
15302 a *different* entry, you cannot use these techniques."
15303 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15304 (not (org-region-active-p)))
15305 (let* ((org-agenda-archives-mode nil) ; just to make sure
15306 (org-agenda-skip-archived-trees (memq 'archive skip))
15307 (org-agenda-skip-comment-trees (memq 'comment skip))
15308 (org-agenda-skip-function
15309 (car (org-delete-all '(comment archive) skip)))
15310 (org-tags-match-list-sublevels t)
15311 (start-level (eq scope 'region-start-level))
15312 matcher res
15313 org-todo-keywords-for-agenda
15314 org-done-keywords-for-agenda
15315 org-todo-keyword-alist-for-agenda
15316 org-tag-alist-for-agenda
15317 org--matcher-tags-todo-only)
15319 (cond
15320 ((eq match t) (setq matcher t))
15321 ((eq match nil) (setq matcher t))
15322 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15324 (save-excursion
15325 (save-restriction
15326 (cond ((eq scope 'tree)
15327 (org-back-to-heading t)
15328 (org-narrow-to-subtree)
15329 (setq scope nil))
15330 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15331 (org-region-active-p))
15332 ;; If needed, set start-level to a string like "2"
15333 (when start-level
15334 (save-excursion
15335 (goto-char (region-beginning))
15336 (unless (org-at-heading-p) (outline-next-heading))
15337 (setq start-level (org-current-level))))
15338 (narrow-to-region (region-beginning)
15339 (save-excursion
15340 (goto-char (region-end))
15341 (unless (and (bolp) (org-at-heading-p))
15342 (outline-next-heading))
15343 (point)))
15344 (setq scope nil)))
15346 (if (not scope)
15347 (progn
15348 (org-agenda-prepare-buffers
15349 (and buffer-file-name (list buffer-file-name)))
15350 (setq res
15351 (org-scan-tags
15352 func matcher org--matcher-tags-todo-only start-level)))
15353 ;; Get the right scope
15354 (cond
15355 ((and scope (listp scope) (symbolp (car scope)))
15356 (setq scope (eval scope)))
15357 ((eq scope 'agenda)
15358 (setq scope (org-agenda-files t)))
15359 ((eq scope 'agenda-with-archives)
15360 (setq scope (org-agenda-files t))
15361 (setq scope (org-add-archive-files scope)))
15362 ((eq scope 'file)
15363 (setq scope (and buffer-file-name (list buffer-file-name))))
15364 ((eq scope 'file-with-archives)
15365 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15366 (org-agenda-prepare-buffers scope)
15367 (dolist (file scope)
15368 (with-current-buffer (org-find-base-buffer-visiting file)
15369 (org-with-wide-buffer
15370 (goto-char (point-min))
15371 (setq res
15372 (append
15374 (org-scan-tags
15375 func matcher org--matcher-tags-todo-only)))))))))
15376 res)))
15378 ;;; Properties API
15380 (defconst org-special-properties
15381 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15382 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15383 "The special properties valid in Org mode.
15384 These are properties that are not defined in the property drawer,
15385 but in some other way.")
15387 (defconst org-default-properties
15388 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15389 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15390 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15391 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15392 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15393 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15394 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15395 "Some properties that are used by Org mode for various purposes.
15396 Being in this list makes sure that they are offered for completion.")
15398 (defun org--valid-property-p (property)
15399 "Non nil when string PROPERTY is a valid property name."
15400 (not
15401 (or (equal property "")
15402 (string-match-p "\\s-" property))))
15404 (defun org--update-property-plist (key val props)
15405 "Associate KEY to VAL in alist PROPS.
15406 Modifications are made by side-effect. Return new alist."
15407 (let* ((appending (string= (substring key -1) "+"))
15408 (key (if appending (substring key 0 -1) key))
15409 (old (assoc-string key props t)))
15410 (if (not old) (cons (cons key val) props)
15411 (setcdr old (if appending (concat (cdr old) " " val) val))
15412 props)))
15414 (defun org-get-property-block (&optional beg force)
15415 "Return the (beg . end) range of the body of the property drawer.
15416 BEG is the beginning of the current subtree, or of the part
15417 before the first headline. If it is not given, it will be found.
15418 If the drawer does not exist, create it if FORCE is non-nil, or
15419 return nil."
15420 (org-with-wide-buffer
15421 (when beg (goto-char beg))
15422 (unless (org-before-first-heading-p)
15423 (let ((beg (cond (beg)
15424 ((or (not (featurep 'org-inlinetask))
15425 (org-inlinetask-in-task-p))
15426 (org-back-to-heading t))
15427 (t (org-with-limited-levels (org-back-to-heading t))))))
15428 (forward-line)
15429 (when (looking-at-p org-planning-line-re) (forward-line))
15430 (cond ((looking-at org-property-drawer-re)
15431 (forward-line)
15432 (cons (point) (progn (goto-char (match-end 0))
15433 (line-beginning-position))))
15434 (force
15435 (goto-char beg)
15436 (org-insert-property-drawer)
15437 (let ((pos (save-excursion (search-forward ":END:")
15438 (line-beginning-position))))
15439 (cons pos pos))))))))
15441 (defun org-at-property-p ()
15442 "Non-nil when point is inside a property drawer.
15443 See `org-property-re' for match data, if applicable."
15444 (save-excursion
15445 (beginning-of-line)
15446 (and (looking-at org-property-re)
15447 (let ((property-drawer (save-match-data (org-get-property-block))))
15448 (and property-drawer
15449 (>= (point) (car property-drawer))
15450 (< (point) (cdr property-drawer)))))))
15452 (defun org-property-action ()
15453 "Do an action on properties."
15454 (interactive)
15455 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15456 (let ((c (read-char-exclusive)))
15457 (cl-case c
15458 (?s (call-interactively #'org-set-property))
15459 (?d (call-interactively #'org-delete-property))
15460 (?D (call-interactively #'org-delete-property-globally))
15461 (?c (call-interactively #'org-compute-property-at-point))
15462 (otherwise (user-error "No such property action %c" c)))))
15464 (defun org-inc-effort ()
15465 "Increment the value of the effort property in the current entry."
15466 (interactive)
15467 (org-set-effort nil t))
15469 (defvar org-clock-effort) ; Defined in org-clock.el.
15470 (defvar org-clock-current-task) ; Defined in org-clock.el.
15471 (defun org-set-effort (&optional value increment)
15472 "Set the effort property of the current entry.
15473 With numerical prefix arg, use the nth allowed value, 0 stands for the
15474 10th allowed value.
15476 When INCREMENT is non-nil, set the property to the next allowed value."
15477 (interactive "P")
15478 (when (equal value 0) (setq value 10))
15479 (let* ((completion-ignore-case t)
15480 (prop org-effort-property)
15481 (cur (org-entry-get nil prop))
15482 (allowed (org-property-get-allowed-values nil prop 'table))
15483 (existing (mapcar 'list (org-property-values prop)))
15484 (heading (nth 4 (org-heading-components)))
15486 (val (cond
15487 ((stringp value) value)
15488 ((and allowed (integerp value))
15489 (or (car (nth (1- value) allowed))
15490 (car (org-last allowed))))
15491 ((and allowed increment)
15492 (or (cl-caadr (member (list cur) allowed))
15493 (user-error "Allowed effort values are not set")))
15494 (allowed
15495 (message "Select 1-9,0, [RET%s]: %s"
15496 (if cur (concat "=" cur) "")
15497 (mapconcat 'car allowed " "))
15498 (setq rpl (read-char-exclusive))
15499 (if (equal rpl ?\r)
15501 (setq rpl (- rpl ?0))
15502 (when (equal rpl 0) (setq rpl 10))
15503 (if (and (> rpl 0) (<= rpl (length allowed)))
15504 (car (nth (1- rpl) allowed))
15505 (org-completing-read "Effort: " allowed nil))))
15507 (org-completing-read
15508 (concat "Effort" (and cur (string-match "\\S-" cur)
15509 (concat " [" cur "]"))
15510 ": ")
15511 existing nil nil "" nil cur)))))
15512 (unless (equal (org-entry-get nil prop) val)
15513 (org-entry-put nil prop val))
15514 (org-refresh-property
15515 '((effort . identity)
15516 (effort-minutes . org-duration-to-minutes))
15517 val)
15518 (when (equal heading (bound-and-true-p org-clock-current-task))
15519 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15520 (org-clock-update-mode-line))
15521 (message "%s is now %s" prop val)))
15523 (defun org-entry-properties (&optional pom which)
15524 "Get all properties of the current entry.
15526 When POM is a buffer position, get all properties from the entry
15527 there instead.
15529 This includes the TODO keyword, the tags, time strings for
15530 deadline, scheduled, and clocking, and any additional properties
15531 defined in the entry.
15533 If WHICH is nil or `all', get all properties. If WHICH is
15534 `special' or `standard', only get that subclass. If WHICH is
15535 a string, only get that property.
15537 Return value is an alist. Keys are properties, as upcased
15538 strings."
15539 (org-with-point-at pom
15540 (when (and (derived-mode-p 'org-mode)
15541 (ignore-errors (org-back-to-heading t)))
15542 (catch 'exit
15543 (let* ((beg (point))
15544 (specific (and (stringp which) (upcase which)))
15545 (which (cond ((not specific) which)
15546 ((member specific org-special-properties) 'special)
15547 (t 'standard)))
15548 props)
15549 ;; Get the special properties, like TODO and TAGS.
15550 (when (memq which '(nil all special))
15551 (when (or (not specific) (string= specific "CLOCKSUM"))
15552 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15553 (when clocksum
15554 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15555 props)))
15556 (when specific (throw 'exit props)))
15557 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15558 (let ((clocksumt (get-text-property (point)
15559 :org-clock-minutes-today)))
15560 (when clocksumt
15561 (push (cons "CLOCKSUM_T"
15562 (org-duration-from-minutes clocksumt))
15563 props)))
15564 (when specific (throw 'exit props)))
15565 (when (or (not specific) (string= specific "ITEM"))
15566 (let ((case-fold-search nil))
15567 (when (looking-at org-complex-heading-regexp)
15568 (push (cons "ITEM"
15569 (let ((title (match-string-no-properties 4)))
15570 (if (org-string-nw-p title)
15571 (org-remove-tabs title)
15572 "")))
15573 props)))
15574 (when specific (throw 'exit props)))
15575 (when (or (not specific) (string= specific "TODO"))
15576 (let ((case-fold-search nil))
15577 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15578 (push (cons "TODO" (match-string-no-properties 2)) props)))
15579 (when specific (throw 'exit props)))
15580 (when (or (not specific) (string= specific "PRIORITY"))
15581 (push (cons "PRIORITY"
15582 (if (looking-at org-priority-regexp)
15583 (match-string-no-properties 2)
15584 (char-to-string org-default-priority)))
15585 props)
15586 (when specific (throw 'exit props)))
15587 (when (or (not specific) (string= specific "FILE"))
15588 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15589 props)
15590 (when specific (throw 'exit props)))
15591 (when (or (not specific) (string= specific "TAGS"))
15592 (let ((value (org-string-nw-p (org-get-tags-string))))
15593 (when value (push (cons "TAGS" value) props)))
15594 (when specific (throw 'exit props)))
15595 (when (or (not specific) (string= specific "ALLTAGS"))
15596 (let ((value (org-get-tags-at)))
15597 (when value
15598 (push (cons "ALLTAGS"
15599 (format ":%s:" (mapconcat #'identity value ":")))
15600 props)))
15601 (when specific (throw 'exit props)))
15602 (when (or (not specific) (string= specific "BLOCKED"))
15603 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15604 (when specific (throw 'exit props)))
15605 (when (or (not specific)
15606 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15607 (forward-line)
15608 (when (looking-at-p org-planning-line-re)
15609 (end-of-line)
15610 (let ((bol (line-beginning-position))
15611 ;; Backward compatibility: time keywords used to
15612 ;; be configurable (before 8.3). Make sure we
15613 ;; get the correct keyword.
15614 (key-assoc `(("CLOSED" . ,org-closed-string)
15615 ("DEADLINE" . ,org-deadline-string)
15616 ("SCHEDULED" . ,org-scheduled-string))))
15617 (dolist (pair (if specific (list (assoc specific key-assoc))
15618 key-assoc))
15619 (save-excursion
15620 (when (search-backward (cdr pair) bol t)
15621 (goto-char (match-end 0))
15622 (skip-chars-forward " \t")
15623 (and (looking-at org-ts-regexp-both)
15624 (push (cons (car pair)
15625 (match-string-no-properties 0))
15626 props)))))))
15627 (when specific (throw 'exit props)))
15628 (when (or (not specific)
15629 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15630 (let ((find-ts
15631 (lambda (end ts)
15632 ;; Fix next time-stamp before END. TS is the
15633 ;; list of time-stamps found so far.
15634 (let ((ts ts)
15635 (regexp (cond
15636 ((string= specific "TIMESTAMP")
15637 org-ts-regexp)
15638 ((string= specific "TIMESTAMP_IA")
15639 org-ts-regexp-inactive)
15640 ((assoc "TIMESTAMP_IA" ts)
15641 org-ts-regexp)
15642 ((assoc "TIMESTAMP" ts)
15643 org-ts-regexp-inactive)
15644 (t org-ts-regexp-both))))
15645 (catch 'next
15646 (while (re-search-forward regexp end t)
15647 (backward-char)
15648 (let ((object (org-element-context)))
15649 ;; Accept to match timestamps in node
15650 ;; properties, too.
15651 (when (memq (org-element-type object)
15652 '(node-property timestamp))
15653 (let ((type
15654 (org-element-property :type object)))
15655 (cond
15656 ((and (memq type '(active active-range))
15657 (not (equal specific "TIMESTAMP_IA")))
15658 (unless (assoc "TIMESTAMP" ts)
15659 (push (cons "TIMESTAMP"
15660 (org-element-property
15661 :raw-value object))
15663 (when specific (throw 'exit ts))))
15664 ((and (memq type '(inactive inactive-range))
15665 (not (string= specific "TIMESTAMP")))
15666 (unless (assoc "TIMESTAMP_IA" ts)
15667 (push (cons "TIMESTAMP_IA"
15668 (org-element-property
15669 :raw-value object))
15671 (when specific (throw 'exit ts))))))
15672 ;; Both timestamp types are found,
15673 ;; move to next part.
15674 (when (= (length ts) 2) (throw 'next ts)))))
15675 ts)))))
15676 (goto-char beg)
15677 ;; First look for timestamps within headline.
15678 (let ((ts (funcall find-ts (line-end-position) nil)))
15679 (if (= (length ts) 2) (setq props (nconc ts props))
15680 ;; Then find timestamps in the section, skipping
15681 ;; planning line.
15682 (let ((end (save-excursion (outline-next-heading))))
15683 (forward-line)
15684 (when (looking-at-p org-planning-line-re) (forward-line))
15685 (setq props (nconc (funcall find-ts end ts) props))))))))
15686 ;; Get the standard properties, like :PROP:.
15687 (when (memq which '(nil all standard))
15688 ;; If we are looking after a specific property, delegate
15689 ;; to `org-entry-get', which is faster. However, make an
15690 ;; exception for "CATEGORY", since it can be also set
15691 ;; through keywords (i.e. #+CATEGORY).
15692 (if (and specific (not (equal specific "CATEGORY")))
15693 (let ((value (org-entry-get beg specific nil t)))
15694 (throw 'exit (and value (list (cons specific value)))))
15695 (let ((range (org-get-property-block beg)))
15696 (when range
15697 (let ((end (cdr range)) seen-base)
15698 (goto-char (car range))
15699 ;; Unlike to `org--update-property-plist', we
15700 ;; handle the case where base values is found
15701 ;; after its extension. We also forbid standard
15702 ;; properties to be named as special properties.
15703 (while (re-search-forward org-property-re end t)
15704 (let* ((key (upcase (match-string-no-properties 2)))
15705 (extendp (string-match-p "\\+\\'" key))
15706 (key-base (if extendp (substring key 0 -1) key))
15707 (value (match-string-no-properties 3)))
15708 (cond
15709 ((member-ignore-case key-base org-special-properties))
15710 (extendp
15711 (setq props
15712 (org--update-property-plist key value props)))
15713 ((member key seen-base))
15714 (t (push key seen-base)
15715 (let ((p (assoc-string key props t)))
15716 (if p (setcdr p (concat value " " (cdr p)))
15717 (push (cons key value) props))))))))))))
15718 (unless (assoc "CATEGORY" props)
15719 (push (cons "CATEGORY" (org-get-category beg)) props)
15720 (when (string= specific "CATEGORY") (throw 'exit props)))
15721 ;; Return value.
15722 props)))))
15724 (defun org--property-local-values (property literal-nil)
15725 "Return value for PROPERTY in current entry.
15726 Value is a list whose car is the base value for PROPERTY and cdr
15727 a list of accumulated values. Return nil if neither is found in
15728 the entry. Also return nil when PROPERTY is set to \"nil\",
15729 unless LITERAL-NIL is non-nil."
15730 (let ((range (org-get-property-block)))
15731 (when range
15732 (goto-char (car range))
15733 (let* ((case-fold-search t)
15734 (end (cdr range))
15735 (value
15736 ;; Base value.
15737 (save-excursion
15738 (let ((v (and (re-search-forward
15739 (org-re-property property nil t) end t)
15740 (match-string-no-properties 3))))
15741 (list (if literal-nil v (org-not-nil v)))))))
15742 ;; Find additional values.
15743 (let* ((property+ (org-re-property (concat property "+") nil t)))
15744 (while (re-search-forward property+ end t)
15745 (push (match-string-no-properties 3) value)))
15746 ;; Return final values.
15747 (and (not (equal value '(nil))) (nreverse value))))))
15749 (defun org--property-global-value (property literal-nil)
15750 "Return value for PROPERTY in current buffer.
15751 Return value is a string. Return nil if property is not set
15752 globally. Also return nil when PROPERTY is set to \"nil\",
15753 unless LITERAL-NIL is non-nil."
15754 (let ((global
15755 (cdr (or (assoc-string property org-file-properties t)
15756 (assoc-string property org-global-properties t)
15757 (assoc-string property org-global-properties-fixed t)))))
15758 (if literal-nil global (org-not-nil global))))
15760 (defun org-entry-get (pom property &optional inherit literal-nil)
15761 "Get value of PROPERTY for entry or content at point-or-marker POM.
15763 If INHERIT is non-nil and the entry does not have the property,
15764 then also check higher levels of the hierarchy. If INHERIT is
15765 the symbol `selective', use inheritance only if the setting in
15766 `org-use-property-inheritance' selects PROPERTY for inheritance.
15768 If the property is present but empty, the return value is the
15769 empty string. If the property is not present at all, nil is
15770 returned. In any other case, return the value as a string.
15771 Search is case-insensitive.
15773 If LITERAL-NIL is set, return the string value \"nil\" as
15774 a string, do not interpret it as the list atom nil. This is used
15775 for inheritance when a \"nil\" value can supersede a non-nil
15776 value higher up the hierarchy."
15777 (org-with-point-at pom
15778 (cond
15779 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15780 ;; We need a special property. Use `org-entry-properties' to
15781 ;; retrieve it, but specify the wanted property.
15782 (cdr (assoc-string property (org-entry-properties nil property))))
15783 ((and inherit
15784 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15785 (org-entry-get-with-inheritance property literal-nil))
15787 (let* ((local (org--property-local-values property literal-nil))
15788 (value (and local (mapconcat #'identity (delq nil local) " "))))
15789 (if literal-nil value (org-not-nil value)))))))
15791 (defun org-property-or-variable-value (var &optional inherit)
15792 "Check if there is a property fixing the value of VAR.
15793 If yes, return this value. If not, return the current value of the variable."
15794 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15795 (if (and prop (stringp prop) (string-match "\\S-" prop))
15796 (read prop)
15797 (symbol-value var))))
15799 (defun org-entry-delete (pom property)
15800 "Delete PROPERTY from entry at point-or-marker POM.
15801 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15802 non-nil when a property was removed."
15803 (org-with-point-at pom
15804 (pcase (org-get-property-block)
15805 (`(,begin . ,origin)
15806 (let* ((end (copy-marker origin))
15807 (re (org-re-property
15808 (concat (regexp-quote property) "\\+?") t t)))
15809 (goto-char begin)
15810 (while (re-search-forward re end t)
15811 (delete-region (match-beginning 0) (line-beginning-position 2)))
15812 ;; If drawer is empty, remove it altogether.
15813 (when (= begin end)
15814 (delete-region (line-beginning-position 0)
15815 (line-beginning-position 2)))
15816 ;; Return non-nil if some property was removed.
15817 (prog1 (/= end origin) (set-marker end nil))))
15818 (_ nil))))
15820 ;; Multi-values properties are properties that contain multiple values
15821 ;; These values are assumed to be single words, separated by whitespace.
15822 (defun org-entry-add-to-multivalued-property (pom property value)
15823 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15824 (let* ((old (org-entry-get pom property))
15825 (values (and old (split-string old))))
15826 (setq value (org-entry-protect-space value))
15827 (unless (member value values)
15828 (setq values (append values (list value)))
15829 (org-entry-put pom property (mapconcat #'identity values " ")))))
15831 (defun org-entry-remove-from-multivalued-property (pom property value)
15832 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15833 (let* ((old (org-entry-get pom property))
15834 (values (and old (split-string old))))
15835 (setq value (org-entry-protect-space value))
15836 (when (member value values)
15837 (setq values (delete value values))
15838 (org-entry-put pom property (mapconcat #'identity values " ")))))
15840 (defun org-entry-member-in-multivalued-property (pom property value)
15841 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15842 (let* ((old (org-entry-get pom property))
15843 (values (and old (split-string old))))
15844 (setq value (org-entry-protect-space value))
15845 (member value values)))
15847 (defun org-entry-get-multivalued-property (pom property)
15848 "Return a list of values in a multivalued property."
15849 (let* ((value (org-entry-get pom property))
15850 (values (and value (split-string value))))
15851 (mapcar #'org-entry-restore-space values)))
15853 (defun org-entry-put-multivalued-property (pom property &rest values)
15854 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15855 VALUES should be a list of strings. Spaces will be protected."
15856 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15857 (let* ((value (org-entry-get pom property))
15858 (values (and value (split-string value))))
15859 (mapcar #'org-entry-restore-space values)))
15861 (defun org-entry-protect-space (s)
15862 "Protect spaces and newline in string S."
15863 (while (string-match " " s)
15864 (setq s (replace-match "%20" t t s)))
15865 (while (string-match "\n" s)
15866 (setq s (replace-match "%0A" t t s)))
15869 (defun org-entry-restore-space (s)
15870 "Restore spaces and newline in string S."
15871 (while (string-match "%20" s)
15872 (setq s (replace-match " " t t s)))
15873 (while (string-match "%0A" s)
15874 (setq s (replace-match "\n" t t s)))
15877 (defvar org-entry-property-inherited-from (make-marker)
15878 "Marker pointing to the entry from where a property was inherited.
15879 Each call to `org-entry-get-with-inheritance' will set this marker to the
15880 location of the entry where the inheritance search matched. If there was
15881 no match, the marker will point nowhere.
15882 Note that also `org-entry-get' calls this function, if the INHERIT flag
15883 is set.")
15885 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15886 "Get PROPERTY of entry or content at point, search higher levels if needed.
15887 The search will stop at the first ancestor which has the property defined.
15888 If the value found is \"nil\", return nil to show that the property
15889 should be considered as undefined (this is the meaning of nil here).
15890 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15891 (move-marker org-entry-property-inherited-from nil)
15892 (org-with-wide-buffer
15893 (let (value)
15894 (catch 'exit
15895 (while t
15896 (let ((v (org--property-local-values property literal-nil)))
15897 (when v
15898 (setq value
15899 (concat (mapconcat #'identity (delq nil v) " ")
15900 (and value " ")
15901 value)))
15902 (cond
15903 ((car v)
15904 (org-back-to-heading t)
15905 (move-marker org-entry-property-inherited-from (point))
15906 (throw 'exit nil))
15907 ((org-up-heading-safe))
15909 (let ((global (org--property-global-value property literal-nil)))
15910 (cond ((not global))
15911 (value (setq value (concat global " " value)))
15912 (t (setq value global))))
15913 (throw 'exit nil))))))
15914 (if literal-nil value (org-not-nil value)))))
15916 (defvar org-property-changed-functions nil
15917 "Hook called when the value of a property has changed.
15918 Each hook function should accept two arguments, the name of the property
15919 and the new value.")
15921 (defun org-entry-put (pom property value)
15922 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15924 If the value is nil, it is converted to the empty string. If it
15925 is not a string, an error is raised. Also raise an error on
15926 invalid property names.
15928 PROPERTY can be any regular property (see
15929 `org-special-properties'). It can also be \"TODO\",
15930 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15932 For the last two properties, VALUE may have any of the special
15933 values \"earlier\" and \"later\". The function then increases or
15934 decreases scheduled or deadline date by one day."
15935 (cond ((null value) (setq value ""))
15936 ((not (stringp value)) (error "Properties values should be strings"))
15937 ((not (org--valid-property-p property))
15938 (user-error "Invalid property name: \"%s\"" property)))
15939 (org-with-point-at pom
15940 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15941 (org-back-to-heading t)
15942 (org-with-limited-levels (org-back-to-heading t)))
15943 (let ((beg (point)))
15944 (cond
15945 ((equal property "TODO")
15946 (cond ((not (org-string-nw-p value)) (setq value 'none))
15947 ((not (member value org-todo-keywords-1))
15948 (user-error "\"%s\" is not a valid TODO state" value)))
15949 (org-todo value)
15950 (org-set-tags nil 'align))
15951 ((equal property "PRIORITY")
15952 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15953 (org-set-tags nil 'align))
15954 ((equal property "SCHEDULED")
15955 (forward-line)
15956 (if (and (looking-at-p org-planning-line-re)
15957 (re-search-forward
15958 org-scheduled-time-regexp (line-end-position) t))
15959 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15960 ((string= value "later") (org-timestamp-change 1 'day))
15961 ((string= value "") (org-schedule '(4)))
15962 (t (org-schedule nil value)))
15963 (if (member value '("earlier" "later" ""))
15964 (call-interactively #'org-schedule)
15965 (org-schedule nil value))))
15966 ((equal property "DEADLINE")
15967 (forward-line)
15968 (if (and (looking-at-p org-planning-line-re)
15969 (re-search-forward
15970 org-deadline-time-regexp (line-end-position) t))
15971 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15972 ((string= value "later") (org-timestamp-change 1 'day))
15973 ((string= value "") (org-deadline '(4)))
15974 (t (org-deadline nil value)))
15975 (if (member value '("earlier" "later" ""))
15976 (call-interactively #'org-deadline)
15977 (org-deadline nil value))))
15978 ((member property org-special-properties)
15979 (error "The %s property cannot be set with `org-entry-put'" property))
15981 (let* ((range (org-get-property-block beg 'force))
15982 (end (cdr range))
15983 (case-fold-search t))
15984 (goto-char (car range))
15985 (if (re-search-forward (org-re-property property nil t) end t)
15986 (progn (delete-region (match-beginning 0) (match-end 0))
15987 (goto-char (match-beginning 0)))
15988 (goto-char end)
15989 (insert "\n")
15990 (backward-char))
15991 (insert ":" property ":")
15992 (when value (insert " " value))
15993 (org-indent-line)))))
15994 (run-hook-with-args 'org-property-changed-functions property value)))
15996 (defun org-buffer-property-keys (&optional specials defaults columns)
15997 "Get all property keys in the current buffer.
15999 When SPECIALS is non-nil, also list the special properties that
16000 reflect things like tags and TODO state.
16002 When DEFAULTS is non-nil, also include properties that has
16003 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16004 DESCRIPTION, LOCATION, and LOGGING and others.
16006 When COLUMNS in non-nil, also include property names given in
16007 COLUMN formats in the current buffer."
16008 (let ((case-fold-search t)
16009 (props (append
16010 (and specials org-special-properties)
16011 (and defaults (cons org-effort-property org-default-properties))
16012 nil)))
16013 (org-with-wide-buffer
16014 (goto-char (point-min))
16015 (while (re-search-forward org-property-start-re nil t)
16016 (catch :skip
16017 (let ((range (org-get-property-block)))
16018 (unless range (throw :skip nil))
16019 (goto-char (car range))
16020 (let ((begin (car range))
16021 (end (cdr range)))
16022 ;; Make sure that found property block is not located
16023 ;; before current point, as it would generate an infloop.
16024 ;; It can happen, for example, in the following
16025 ;; situation:
16027 ;; * Headline
16028 ;; :PROPERTIES:
16029 ;; ...
16030 ;; :END:
16031 ;; *************** Inlinetask
16032 ;; #+BEGIN_EXAMPLE
16033 ;; :PROPERTIES:
16034 ;; #+END_EXAMPLE
16036 (if (< begin (point)) (throw :skip nil) (goto-char begin))
16037 (while (< (point) end)
16038 (let ((p (progn (looking-at org-property-re)
16039 (match-string-no-properties 2))))
16040 ;; Only add true property name, not extension symbol.
16041 (push (if (not (string-match-p "\\+\\'" p)) p
16042 (substring p 0 -1))
16043 props))
16044 (forward-line))))
16045 (outline-next-heading)))
16046 (when columns
16047 (goto-char (point-min))
16048 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16049 (let ((element (org-element-at-point)))
16050 (when (memq (org-element-type element) '(keyword node-property))
16051 (let ((value (org-element-property :value element))
16052 (start 0))
16053 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
16054 \\(?:{[^}]+}\\)?"
16055 value start)
16056 (setq start (match-end 0))
16057 (let ((p (match-string-no-properties 1 value)))
16058 (unless (member-ignore-case p org-special-properties)
16059 (push p props))))))))))
16060 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16062 (defun org-property-values (key)
16063 "List all non-nil values of property KEY in current buffer."
16064 (org-with-wide-buffer
16065 (goto-char (point-min))
16066 (let ((case-fold-search t)
16067 (re (org-re-property key))
16068 values)
16069 (while (re-search-forward re nil t)
16070 (push (org-entry-get (point) key) values))
16071 (delete-dups values))))
16073 (defun org-insert-property-drawer ()
16074 "Insert a property drawer into the current entry."
16075 (org-with-wide-buffer
16076 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16077 (org-back-to-heading t)
16078 (org-with-limited-levels (org-back-to-heading t)))
16079 (forward-line)
16080 (when (looking-at-p org-planning-line-re) (forward-line))
16081 (unless (looking-at-p org-property-drawer-re)
16082 ;; Make sure we start editing a line from current entry, not from
16083 ;; next one. It prevents extending text properties or overlays
16084 ;; belonging to the latter.
16085 (when (bolp) (backward-char))
16086 (let ((begin (1+ (point)))
16087 (inhibit-read-only t))
16088 (insert "\n:PROPERTIES:\n:END:")
16089 (when (eobp) (insert "\n"))
16090 (org-indent-region begin (point))))))
16092 (defun org-insert-drawer (&optional arg drawer)
16093 "Insert a drawer at point.
16095 When optional argument ARG is non-nil, insert a property drawer.
16097 Optional argument DRAWER, when non-nil, is a string representing
16098 drawer's name. Otherwise, the user is prompted for a name.
16100 If a region is active, insert the drawer around that region
16101 instead.
16103 Point is left between drawer's boundaries."
16104 (interactive "P")
16105 (let* ((drawer (if arg "PROPERTIES"
16106 (or drawer (read-from-minibuffer "Drawer: ")))))
16107 (cond
16108 ;; With C-u, fall back on `org-insert-property-drawer'
16109 (arg (org-insert-property-drawer))
16110 ;; Check validity of suggested drawer's name.
16111 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16112 (user-error "Invalid drawer name"))
16113 ;; With an active region, insert a drawer at point.
16114 ((not (org-region-active-p))
16115 (progn
16116 (unless (bolp) (insert "\n"))
16117 (insert (format ":%s:\n\n:END:\n" drawer))
16118 (forward-line -2)))
16119 ;; Otherwise, insert the drawer at point
16121 (let ((rbeg (region-beginning))
16122 (rend (copy-marker (region-end))))
16123 (unwind-protect
16124 (progn
16125 (goto-char rbeg)
16126 (beginning-of-line)
16127 (when (save-excursion
16128 (re-search-forward org-outline-regexp-bol rend t))
16129 (user-error "Drawers cannot contain headlines"))
16130 ;; Position point at the beginning of the first
16131 ;; non-blank line in region. Insert drawer's opening
16132 ;; there, then indent it.
16133 (org-skip-whitespace)
16134 (beginning-of-line)
16135 (insert ":" drawer ":\n")
16136 (forward-line -1)
16137 (indent-for-tab-command)
16138 ;; Move point to the beginning of the first blank line
16139 ;; after the last non-blank line in region. Insert
16140 ;; drawer's closing, then indent it.
16141 (goto-char rend)
16142 (skip-chars-backward " \r\t\n")
16143 (insert "\n:END:")
16144 (deactivate-mark t)
16145 (indent-for-tab-command)
16146 (unless (eolp) (insert "\n")))
16147 ;; Clear marker, whatever the outcome of insertion is.
16148 (set-marker rend nil)))))))
16150 (defvar org-property-set-functions-alist nil
16151 "Property set function alist.
16152 Each entry should have the following format:
16154 (PROPERTY . READ-FUNCTION)
16156 The read function will be called with the same argument as
16157 `org-completing-read'.")
16159 (defun org-set-property-function (property)
16160 "Get the function that should be used to set PROPERTY.
16161 This is computed according to `org-property-set-functions-alist'."
16162 (or (cdr (assoc property org-property-set-functions-alist))
16163 'org-completing-read))
16165 (defun org-read-property-value (property)
16166 "Read PROPERTY value from user."
16167 (let* ((completion-ignore-case t)
16168 (allowed (org-property-get-allowed-values nil property 'table))
16169 (cur (org-entry-get nil property))
16170 (prompt (concat property " value"
16171 (if (and cur (string-match "\\S-" cur))
16172 (concat " [" cur "]") "") ": "))
16173 (set-function (org-set-property-function property))
16174 (val (if allowed
16175 (funcall set-function prompt allowed nil
16176 (not (get-text-property 0 'org-unrestricted
16177 (caar allowed))))
16178 (funcall set-function prompt
16179 (mapcar 'list (org-property-values property))
16180 nil nil "" nil cur))))
16181 (org-trim val)))
16183 (defvar org-last-set-property nil)
16184 (defvar org-last-set-property-value nil)
16185 (defun org-read-property-name ()
16186 "Read a property name."
16187 (let ((completion-ignore-case t)
16188 (default-prop (or (and (org-at-property-p)
16189 (match-string-no-properties 2))
16190 org-last-set-property)))
16191 (org-completing-read
16192 (concat "Property"
16193 (if default-prop (concat " [" default-prop "]") "")
16194 ": ")
16195 (mapcar #'list (org-buffer-property-keys nil t t))
16196 nil nil nil nil default-prop)))
16198 (defun org-set-property-and-value (use-last)
16199 "Allow to set [PROPERTY]: [value] direction from prompt.
16200 When use-default, don't even ask, just use the last
16201 \"[PROPERTY]: [value]\" string from the history."
16202 (interactive "P")
16203 (let* ((completion-ignore-case t)
16204 (pv (or (and use-last org-last-set-property-value)
16205 (org-completing-read
16206 "Enter a \"[Property]: [value]\" pair: "
16207 nil nil nil nil nil
16208 org-last-set-property-value)))
16209 prop val)
16210 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16211 (setq prop (match-string 1 pv)
16212 val (match-string 2 pv))
16213 (org-set-property prop val))))
16215 (defun org-set-property (property value)
16216 "In the current entry, set PROPERTY to VALUE.
16218 When called interactively, this will prompt for a property name, offering
16219 completion on existing and default properties. And then it will prompt
16220 for a value, offering completion either on allowed values (via an inherited
16221 xxx_ALL property) or on existing values in other instances of this property
16222 in the current file.
16224 Throw an error when trying to set a property with an invalid name."
16225 (interactive (list nil nil))
16226 (let ((property (or property (org-read-property-name))))
16227 ;; `org-entry-put' also makes the following check, but this one
16228 ;; avoids polluting `org-last-set-property' and
16229 ;; `org-last-set-property-value' needlessly.
16230 (unless (org--valid-property-p property)
16231 (user-error "Invalid property name: \"%s\"" property))
16232 (let ((value (or value (org-read-property-value property)))
16233 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16234 (setq org-last-set-property property)
16235 (setq org-last-set-property-value (concat property ": " value))
16236 ;; Possibly postprocess the inserted value:
16237 (when fn (setq value (funcall fn value)))
16238 (unless (equal (org-entry-get nil property) value)
16239 (org-entry-put nil property value)))))
16241 (defun org-find-property (property &optional value)
16242 "Find first entry in buffer that sets PROPERTY.
16244 When optional argument VALUE is non-nil, only consider an entry
16245 if it contains PROPERTY set to this value. If PROPERTY should be
16246 explicitly set to nil, use string \"nil\" for VALUE.
16248 Return position where the entry begins, or nil if there is no
16249 such entry. If narrowing is in effect, only search the visible
16250 part of the buffer."
16251 (save-excursion
16252 (goto-char (point-min))
16253 (let ((case-fold-search t)
16254 (re (org-re-property property nil (not value) value)))
16255 (catch 'exit
16256 (while (re-search-forward re nil t)
16257 (when (if value (org-at-property-p)
16258 (org-entry-get (point) property nil t))
16259 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16261 (defun org-delete-property (property)
16262 "In the current entry, delete PROPERTY."
16263 (interactive
16264 (let* ((completion-ignore-case t)
16265 (cat (org-entry-get (point) "CATEGORY"))
16266 (props0 (org-entry-properties nil 'standard))
16267 (props (if cat props0
16268 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16269 (prop (if (< 1 (length props))
16270 (completing-read "Property: " props nil t)
16271 (caar props))))
16272 (list prop)))
16273 (if (not property)
16274 (message "No property to delete in this entry")
16275 (org-entry-delete nil property)
16276 (message "Property \"%s\" deleted" property)))
16278 (defun org-delete-property-globally (property)
16279 "Remove PROPERTY globally, from all entries.
16280 This function ignores narrowing, if any."
16281 (interactive
16282 (let* ((completion-ignore-case t)
16283 (prop (completing-read
16284 "Globally remove property: "
16285 (mapcar #'list (org-buffer-property-keys)))))
16286 (list prop)))
16287 (org-with-wide-buffer
16288 (goto-char (point-min))
16289 (let ((count 0)
16290 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16291 (while (re-search-forward re nil t)
16292 (when (org-entry-delete (point) property) (cl-incf count)))
16293 (message "Property \"%s\" removed from %d entries" property count))))
16295 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16297 (defun org-compute-property-at-point ()
16298 "Compute the property at point.
16299 This looks for an enclosing column format, extracts the operator and
16300 then applies it to the property in the column format's scope."
16301 (interactive)
16302 (unless (org-at-property-p)
16303 (user-error "Not at a property"))
16304 (let ((prop (match-string-no-properties 2)))
16305 (org-columns-get-format-and-top-level)
16306 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16307 (user-error "No operator defined for property %s" prop))
16308 (org-columns-compute prop)))
16310 (defvar org-property-allowed-value-functions nil
16311 "Hook for functions supplying allowed values for a specific property.
16312 The functions must take a single argument, the name of the property, and
16313 return a flat list of allowed values. If \":ETC\" is one of
16314 the values, this means that these values are intended as defaults for
16315 completion, but that other values should be allowed too.
16316 The functions must return nil if they are not responsible for this
16317 property.")
16319 (defun org-property-get-allowed-values (pom property &optional table)
16320 "Get allowed values for the property PROPERTY.
16321 When TABLE is non-nil, return an alist that can directly be used for
16322 completion."
16323 (let (vals)
16324 (cond
16325 ((equal property "TODO")
16326 (setq vals (org-with-point-at pom
16327 (append org-todo-keywords-1 '("")))))
16328 ((equal property "PRIORITY")
16329 (let ((n org-lowest-priority))
16330 (while (>= n org-highest-priority)
16331 (push (char-to-string n) vals)
16332 (setq n (1- n)))))
16333 ((equal property "CATEGORY"))
16334 ((member property org-special-properties))
16335 ((setq vals (run-hook-with-args-until-success
16336 'org-property-allowed-value-functions property)))
16338 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16339 (when (and vals (string-match "\\S-" vals))
16340 (setq vals (car (read-from-string (concat "(" vals ")"))))
16341 (setq vals (mapcar (lambda (x)
16342 (cond ((stringp x) x)
16343 ((numberp x) (number-to-string x))
16344 ((symbolp x) (symbol-name x))
16345 (t "???")))
16346 vals)))))
16347 (when (member ":ETC" vals)
16348 (setq vals (remove ":ETC" vals))
16349 (org-add-props (car vals) '(org-unrestricted t)))
16350 (if table (mapcar 'list vals) vals)))
16352 (defun org-property-previous-allowed-value (&optional _previous)
16353 "Switch to the next allowed value for this property."
16354 (interactive)
16355 (org-property-next-allowed-value t))
16357 (defun org-property-next-allowed-value (&optional previous)
16358 "Switch to the next allowed value for this property."
16359 (interactive)
16360 (unless (org-at-property-p)
16361 (user-error "Not at a property"))
16362 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16363 (key (match-string 2))
16364 (value (match-string 3))
16365 (allowed (or (org-property-get-allowed-values (point) key)
16366 (and (member value '("[ ]" "[-]" "[X]"))
16367 '("[ ]" "[X]"))))
16368 (heading (save-match-data (nth 4 (org-heading-components))))
16369 nval)
16370 (unless allowed
16371 (user-error "Allowed values for this property have not been defined"))
16372 (when previous (setq allowed (reverse allowed)))
16373 (when (member value allowed)
16374 (setq nval (car (cdr (member value allowed)))))
16375 (setq nval (or nval (car allowed)))
16376 (when (equal nval value)
16377 (user-error "Only one allowed value for this property"))
16378 (org-at-property-p)
16379 (replace-match (concat " :" key ": " nval) t t)
16380 (org-indent-line)
16381 (beginning-of-line 1)
16382 (skip-chars-forward " \t")
16383 (when (equal prop org-effort-property)
16384 (org-refresh-property
16385 '((effort . identity)
16386 (effort-minutes . org-duration-to-minutes))
16387 nval)
16388 (when (string= org-clock-current-task heading)
16389 (setq org-clock-effort nval)
16390 (org-clock-update-mode-line)))
16391 (run-hook-with-args 'org-property-changed-functions key nval)))
16393 (defun org-find-olp (path &optional this-buffer)
16394 "Return a marker pointing to the entry at outline path OLP.
16395 If anything goes wrong, throw an error.
16396 You can wrap this call to catch the error like this:
16398 (condition-case msg
16399 (org-mobile-locate-entry (match-string 4))
16400 (error (nth 1 msg)))
16402 The return value will then be either a string with the error message,
16403 or a marker if everything is OK.
16405 If THIS-BUFFER is set, the outline path does not contain a file,
16406 only headings."
16407 (let* ((file (if this-buffer buffer-file-name (pop path)))
16408 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16409 (level 1)
16410 (lmin 1)
16411 (lmax 1)
16412 end found flevel)
16413 (unless buffer (error "File not found :%s" file))
16414 (with-current-buffer buffer
16415 (unless (derived-mode-p 'org-mode)
16416 (error "Buffer %s needs to be in Org mode" buffer))
16417 (org-with-wide-buffer
16418 (goto-char (point-min))
16419 (dolist (heading path)
16420 (let ((re (format org-complex-heading-regexp-format
16421 (regexp-quote heading)))
16422 (cnt 0))
16423 (while (re-search-forward re end t)
16424 (setq level (- (match-end 1) (match-beginning 1)))
16425 (when (and (>= level lmin) (<= level lmax))
16426 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16427 (when (= cnt 0)
16428 (error "Heading not found on level %d: %s" lmax heading))
16429 (when (> cnt 1)
16430 (error "Heading not unique on level %d: %s" lmax heading))
16431 (goto-char found)
16432 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16433 (setq end (save-excursion (org-end-of-subtree t t)))))
16434 (when (org-at-heading-p)
16435 (point-marker))))))
16437 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16438 "Find node HEADING in BUFFER.
16439 Return a marker to the heading if it was found, or nil if not.
16440 If POS-ONLY is set, return just the position instead of a marker.
16442 The heading text must match exact, but it may have a TODO keyword,
16443 a priority cookie and tags in the standard locations."
16444 (with-current-buffer (or buffer (current-buffer))
16445 (org-with-wide-buffer
16446 (goto-char (point-min))
16447 (let (case-fold-search)
16448 (when (re-search-forward
16449 (format org-complex-heading-regexp-format
16450 (regexp-quote heading)) nil t)
16451 (if pos-only
16452 (match-beginning 0)
16453 (move-marker (make-marker) (match-beginning 0))))))))
16455 (defun org-find-exact-heading-in-directory (heading &optional dir)
16456 "Find Org node headline HEADING in all .org files in directory DIR.
16457 When the target headline is found, return a marker to this location."
16458 (let ((files (directory-files (or dir default-directory)
16459 t "\\`[^.#].*\\.org\\'"))
16460 visiting m buffer)
16461 (catch 'found
16462 (dolist (file files)
16463 (message "trying %s" file)
16464 (setq visiting (org-find-base-buffer-visiting file))
16465 (setq buffer (or visiting (find-file-noselect file)))
16466 (setq m (org-find-exact-headline-in-buffer
16467 heading buffer))
16468 (when (and (not m) (not visiting)) (kill-buffer buffer))
16469 (and m (throw 'found m))))))
16471 (defun org-find-entry-with-id (ident)
16472 "Locate the entry that contains the ID property with exact value IDENT.
16473 IDENT can be a string, a symbol or a number, this function will search for
16474 the string representation of it.
16475 Return the position where this entry starts, or nil if there is no such entry."
16476 (interactive "sID: ")
16477 (let ((id (cond
16478 ((stringp ident) ident)
16479 ((symbolp ident) (symbol-name ident))
16480 ((numberp ident) (number-to-string ident))
16481 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16482 (org-with-wide-buffer (org-find-property "ID" id))))
16484 ;;;; Timestamps
16486 (defvar org-last-changed-timestamp nil)
16487 (defvar org-last-inserted-timestamp nil
16488 "The last time stamp inserted with `org-insert-time-stamp'.")
16490 (defun org-time-stamp (arg &optional inactive)
16491 "Prompt for a date/time and insert a time stamp.
16493 If the user specifies a time like HH:MM or if this command is
16494 called with at least one prefix argument, the time stamp contains
16495 the date and the time. Otherwise, only the date is included.
16497 All parts of a date not specified by the user are filled in from
16498 the timestamp at point, if any, or the current date/time
16499 otherwise.
16501 If there is already a timestamp at the cursor, it is replaced.
16503 With two universal prefix arguments, insert an active timestamp
16504 with the current time without prompting the user.
16506 When called from lisp, the timestamp is inactive if INACTIVE is
16507 non-nil."
16508 (interactive "P")
16509 (let* ((ts (cond
16510 ((org-at-date-range-p t)
16511 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16512 ((org-at-timestamp-p 'lax) (match-string 0))))
16513 ;; Default time is either the timestamp at point or today.
16514 ;; When entering a range, only the range start is considered.
16515 (default-time (if (not ts) (current-time)
16516 (apply #'encode-time (org-parse-time-string ts))))
16517 (default-input (and ts (org-get-compact-tod ts)))
16518 (repeater (and ts
16519 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16520 (match-string 0 ts)))
16521 org-time-was-given
16522 org-end-time-was-given
16523 (time
16524 (and (if (equal arg '(16)) (current-time)
16525 ;; Preserve `this-command' and `last-command'.
16526 (let ((this-command this-command)
16527 (last-command last-command))
16528 (org-read-date
16529 arg 'totime nil nil default-time default-input
16530 inactive))))))
16531 (cond
16532 ((and ts
16533 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16534 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16535 (insert "--")
16536 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16538 ;; Make sure we're on a timestamp. When in the middle of a date
16539 ;; range, move arbitrarily to range end.
16540 (unless (org-at-timestamp-p 'lax)
16541 (skip-chars-forward "-")
16542 (org-at-timestamp-p 'lax))
16543 (replace-match "")
16544 (setq org-last-changed-timestamp
16545 (org-insert-time-stamp
16546 time (or org-time-was-given arg)
16547 inactive nil nil (list org-end-time-was-given)))
16548 (when repeater
16549 (backward-char)
16550 (insert " " repeater)
16551 (setq org-last-changed-timestamp
16552 (concat (substring org-last-inserted-timestamp 0 -1)
16553 " " repeater ">")))
16554 (message "Timestamp updated"))
16555 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16556 (t (org-insert-time-stamp
16557 time (or org-time-was-given arg) inactive nil nil
16558 (list org-end-time-was-given))))))
16560 ;; FIXME: can we use this for something else, like computing time differences?
16561 (defun org-get-compact-tod (s)
16562 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16563 (let* ((t1 (match-string 1 s))
16564 (h1 (string-to-number (match-string 2 s)))
16565 (m1 (string-to-number (match-string 3 s)))
16566 (t2 (and (match-end 4) (match-string 5 s)))
16567 (h2 (and t2 (string-to-number (match-string 6 s))))
16568 (m2 (and t2 (string-to-number (match-string 7 s))))
16569 dh dm)
16570 (if (not t2)
16572 (setq dh (- h2 h1) dm (- m2 m1))
16573 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16574 (concat t1 "+" (number-to-string dh)
16575 (and (/= 0 dm) (format ":%02d" dm)))))))
16577 (defun org-time-stamp-inactive (&optional arg)
16578 "Insert an inactive time stamp.
16579 An inactive time stamp is enclosed in square brackets instead of angle
16580 brackets. It is inactive in the sense that it does not trigger agenda entries,
16581 does not link to the calendar and cannot be changed with the S-cursor keys.
16582 So these are more for recording a certain time/date."
16583 (interactive "P")
16584 (org-time-stamp arg 'inactive))
16586 (defvar org-date-ovl (make-overlay 1 1))
16587 (overlay-put org-date-ovl 'face 'org-date-selected)
16588 (delete-overlay org-date-ovl)
16590 (defvar org-ans1) ; dynamically scoped parameter
16591 (defvar org-ans2) ; dynamically scoped parameter
16593 (defvar org-plain-time-of-day-regexp) ; defined below
16595 (defvar org-overriding-default-time nil) ; dynamically scoped
16596 (defvar org-read-date-overlay nil)
16597 (defvar org-dcst nil) ; dynamically scoped
16598 (defvar org-read-date-history nil)
16599 (defvar org-read-date-final-answer nil)
16600 (defvar org-read-date-analyze-futurep nil)
16601 (defvar org-read-date-analyze-forced-year nil)
16602 (defvar org-read-date-inactive)
16604 (defvar org-read-date-minibuffer-local-map
16605 (let* ((map (make-sparse-keymap)))
16606 (set-keymap-parent map minibuffer-local-map)
16607 (org-defkey map (kbd ".")
16608 (lambda () (interactive)
16609 ;; Are we at the beginning of the prompt?
16610 (if (looking-back "^[^:]+: "
16611 (let ((inhibit-field-text-motion t))
16612 (line-beginning-position)))
16613 (org-eval-in-calendar '(calendar-goto-today))
16614 (insert "."))))
16615 (org-defkey map (kbd "C-.")
16616 (lambda () (interactive)
16617 (org-eval-in-calendar '(calendar-goto-today))))
16618 (org-defkey map [(meta shift left)]
16619 (lambda () (interactive)
16620 (org-eval-in-calendar '(calendar-backward-month 1))))
16621 (org-defkey map [(meta shift right)]
16622 (lambda () (interactive)
16623 (org-eval-in-calendar '(calendar-forward-month 1))))
16624 (org-defkey map [(meta shift up)]
16625 (lambda () (interactive)
16626 (org-eval-in-calendar '(calendar-backward-year 1))))
16627 (org-defkey map [(meta shift down)]
16628 (lambda () (interactive)
16629 (org-eval-in-calendar '(calendar-forward-year 1))))
16630 (org-defkey map [?\e (shift left)]
16631 (lambda () (interactive)
16632 (org-eval-in-calendar '(calendar-backward-month 1))))
16633 (org-defkey map [?\e (shift right)]
16634 (lambda () (interactive)
16635 (org-eval-in-calendar '(calendar-forward-month 1))))
16636 (org-defkey map [?\e (shift up)]
16637 (lambda () (interactive)
16638 (org-eval-in-calendar '(calendar-backward-year 1))))
16639 (org-defkey map [?\e (shift down)]
16640 (lambda () (interactive)
16641 (org-eval-in-calendar '(calendar-forward-year 1))))
16642 (org-defkey map [(shift up)]
16643 (lambda () (interactive)
16644 (org-eval-in-calendar '(calendar-backward-week 1))))
16645 (org-defkey map [(shift down)]
16646 (lambda () (interactive)
16647 (org-eval-in-calendar '(calendar-forward-week 1))))
16648 (org-defkey map [(shift left)]
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-backward-day 1))))
16651 (org-defkey map [(shift right)]
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-forward-day 1))))
16654 (org-defkey map "!"
16655 (lambda () (interactive)
16656 (org-eval-in-calendar '(diary-view-entries))
16657 (message "")))
16658 (org-defkey map ">"
16659 (lambda () (interactive)
16660 (org-eval-in-calendar '(calendar-scroll-left 1))))
16661 (org-defkey map "<"
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(calendar-scroll-right 1))))
16664 (org-defkey map "\C-v"
16665 (lambda () (interactive)
16666 (org-eval-in-calendar
16667 '(calendar-scroll-left-three-months 1))))
16668 (org-defkey map "\M-v"
16669 (lambda () (interactive)
16670 (org-eval-in-calendar
16671 '(calendar-scroll-right-three-months 1))))
16672 map)
16673 "Keymap for minibuffer commands when using `org-read-date'.")
16675 (defvar org-def)
16676 (defvar org-defdecode)
16677 (defvar org-with-time)
16679 (defvar calendar-setup) ; Dynamically scoped.
16680 (defun org-read-date (&optional with-time to-time from-string prompt
16681 default-time default-input inactive)
16682 "Read a date, possibly a time, and make things smooth for the user.
16683 The prompt will suggest to enter an ISO date, but you can also enter anything
16684 which will at least partially be understood by `parse-time-string'.
16685 Unrecognized parts of the date will default to the current day, month, year,
16686 hour and minute. If this command is called to replace a timestamp at point,
16687 or to enter the second timestamp of a range, the default time is taken
16688 from the existing stamp. Furthermore, the command prefers the future,
16689 so if you are giving a date where the year is not given, and the day-month
16690 combination is already past in the current year, it will assume you
16691 mean next year. For details, see the manual. A few examples:
16693 3-2-5 --> 2003-02-05
16694 feb 15 --> currentyear-02-15
16695 2/15 --> currentyear-02-15
16696 sep 12 9 --> 2009-09-12
16697 12:45 --> today 12:45
16698 22 sept 0:34 --> currentyear-09-22 0:34
16699 12 --> currentyear-currentmonth-12
16700 Fri --> nearest Friday after today
16701 -Tue --> last Tuesday
16702 etc.
16704 Furthermore you can specify a relative date by giving, as the *first* thing
16705 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16706 change in days weeks, months, years.
16707 With a single plus or minus, the date is relative to today. With a double
16708 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16709 +4d --> four days from today
16710 +4 --> same as above
16711 +2w --> two weeks from today
16712 ++5 --> five days from default date
16714 The function understands only English month and weekday abbreviations.
16716 While prompting, a calendar is popped up - you can also select the
16717 date with the mouse (button 1). The calendar shows a period of three
16718 months. To scroll it to other months, use the keys `>' and `<'.
16719 If you don't like the calendar, turn it off with
16720 (setq org-read-date-popup-calendar nil)
16722 With optional argument TO-TIME, the date will immediately be converted
16723 to an internal time.
16724 With an optional argument WITH-TIME, the prompt will suggest to
16725 also insert a time. Note that when WITH-TIME is not set, you can
16726 still enter a time, and this function will inform the calling routine
16727 about this change. The calling routine may then choose to change the
16728 format used to insert the time stamp into the buffer to include the time.
16729 With optional argument FROM-STRING, read from this string instead from
16730 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16731 the time/date that is used for everything that is not specified by the
16732 user."
16733 (require 'parse-time)
16734 (let* ((org-with-time with-time)
16735 (org-time-stamp-rounding-minutes
16736 (if (equal org-with-time '(16))
16737 '(0 0)
16738 org-time-stamp-rounding-minutes))
16739 (org-dcst org-display-custom-times)
16740 (ct (org-current-time))
16741 (org-def (or org-overriding-default-time default-time ct))
16742 (org-defdecode (decode-time org-def))
16743 (cur-frame (selected-frame))
16744 (mouse-autoselect-window nil) ; Don't let the mouse jump
16745 (calendar-setup
16746 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16747 (calendar-move-hook nil)
16748 (calendar-view-diary-initially-flag nil)
16749 (calendar-view-holidays-initially-flag nil)
16750 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16751 ;; Rationalize `org-def' and `org-defdecode', if required.
16752 (when (< (nth 2 org-defdecode) org-extend-today-until)
16753 (setf (nth 2 org-defdecode) -1)
16754 (setf (nth 1 org-defdecode) 59)
16755 (setq org-def (apply #'encode-time org-defdecode))
16756 (setq org-defdecode (decode-time org-def)))
16757 (let* ((timestr (format-time-string
16758 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16759 org-def))
16760 (prompt (concat (if prompt (concat prompt " ") "")
16761 (format "Date+time [%s]: " timestr))))
16762 (cond
16763 (from-string (setq ans from-string))
16764 (org-read-date-popup-calendar
16765 (save-excursion
16766 (save-window-excursion
16767 (calendar)
16768 (when (eq calendar-setup 'calendar-only)
16769 (setq cal-frame
16770 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16771 (select-frame cal-frame))
16772 (org-eval-in-calendar '(setq cursor-type nil) t)
16773 (unwind-protect
16774 (progn
16775 (calendar-forward-day (- (time-to-days org-def)
16776 (calendar-absolute-from-gregorian
16777 (calendar-current-date))))
16778 (org-eval-in-calendar nil t)
16779 (let* ((old-map (current-local-map))
16780 (map (copy-keymap calendar-mode-map))
16781 (minibuffer-local-map
16782 (copy-keymap org-read-date-minibuffer-local-map)))
16783 (org-defkey map (kbd "RET") 'org-calendar-select)
16784 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16785 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16786 (unwind-protect
16787 (progn
16788 (use-local-map map)
16789 (setq org-read-date-inactive inactive)
16790 (add-hook 'post-command-hook 'org-read-date-display)
16791 (setq org-ans0
16792 (read-string prompt
16793 default-input
16794 'org-read-date-history
16795 nil))
16796 ;; org-ans0: from prompt
16797 ;; org-ans1: from mouse click
16798 ;; org-ans2: from calendar motion
16799 (setq ans
16800 (concat org-ans0 " " (or org-ans1 org-ans2))))
16801 (remove-hook 'post-command-hook 'org-read-date-display)
16802 (use-local-map old-map)
16803 (when org-read-date-overlay
16804 (delete-overlay org-read-date-overlay)
16805 (setq org-read-date-overlay nil)))))
16806 (bury-buffer "*Calendar*")
16807 (when cal-frame
16808 (delete-frame cal-frame)
16809 (select-frame-set-input-focus cur-frame))))))
16811 (t ; Naked prompt only
16812 (unwind-protect
16813 (setq ans (read-string prompt default-input
16814 'org-read-date-history timestr))
16815 (when org-read-date-overlay
16816 (delete-overlay org-read-date-overlay)
16817 (setq org-read-date-overlay nil))))))
16819 (setq final (org-read-date-analyze ans org-def org-defdecode))
16821 (when org-read-date-analyze-forced-year
16822 (message "Year was forced into %s"
16823 (if org-read-date-force-compatible-dates
16824 "compatible range (1970-2037)"
16825 "range representable on this machine"))
16826 (ding))
16828 ;; One round trip to get rid of 34th of August and stuff like that....
16829 (setq final (decode-time (apply 'encode-time final)))
16831 (setq org-read-date-final-answer ans)
16833 (if to-time
16834 (apply 'encode-time final)
16835 (if (and (boundp 'org-time-was-given) org-time-was-given)
16836 (format "%04d-%02d-%02d %02d:%02d"
16837 (nth 5 final) (nth 4 final) (nth 3 final)
16838 (nth 2 final) (nth 1 final))
16839 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16841 (defun org-read-date-display ()
16842 "Display the current date prompt interpretation in the minibuffer."
16843 (when org-read-date-display-live
16844 (when org-read-date-overlay
16845 (delete-overlay org-read-date-overlay))
16846 (when (minibufferp (current-buffer))
16847 (save-excursion
16848 (end-of-line 1)
16849 (while (not (equal (buffer-substring
16850 (max (point-min) (- (point) 4)) (point))
16851 " "))
16852 (insert " ")))
16853 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16854 " " (or org-ans1 org-ans2)))
16855 (org-end-time-was-given nil)
16856 (f (org-read-date-analyze ans org-def org-defdecode))
16857 (fmts (if org-dcst
16858 org-time-stamp-custom-formats
16859 org-time-stamp-formats))
16860 (fmt (if (or org-with-time
16861 (and (boundp 'org-time-was-given) org-time-was-given))
16862 (cdr fmts)
16863 (car fmts)))
16864 (txt (format-time-string fmt (apply 'encode-time f)))
16865 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16866 (txt (concat "=> " txt)))
16867 (when (and org-end-time-was-given
16868 (string-match org-plain-time-of-day-regexp txt))
16869 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16870 org-end-time-was-given
16871 (substring txt (match-end 0)))))
16872 (when org-read-date-analyze-futurep
16873 (setq txt (concat txt " (=>F)")))
16874 (setq org-read-date-overlay
16875 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16876 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16878 (defun org-read-date-analyze (ans def defdecode)
16879 "Analyze the combined answer of the date prompt."
16880 ;; FIXME: cleanup and comment
16881 ;; Pass `current-time' result to `decode-time' (instead of calling
16882 ;; without arguments) so that only `current-time' has to be
16883 ;; overridden in tests.
16884 (let ((org-def def)
16885 (org-defdecode defdecode)
16886 (nowdecode (decode-time (current-time)))
16887 delta deltan deltaw deltadef year month day
16888 hour minute second wday pm h2 m2 tl wday1
16889 iso-year iso-weekday iso-week iso-date futurep kill-year)
16890 (setq org-read-date-analyze-futurep nil
16891 org-read-date-analyze-forced-year nil)
16892 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16893 (setq ans "+0"))
16895 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16896 (setq ans (replace-match "" t t ans)
16897 deltan (car delta)
16898 deltaw (nth 1 delta)
16899 deltadef (nth 2 delta)))
16901 ;; Check if there is an iso week date in there. If yes, store the
16902 ;; info and postpone interpreting it until the rest of the parsing
16903 ;; is done.
16904 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16905 (setq iso-year (when (match-end 1)
16906 (org-small-year-to-year
16907 (string-to-number (match-string 1 ans))))
16908 iso-weekday (when (match-end 3)
16909 (string-to-number (match-string 3 ans)))
16910 iso-week (string-to-number (match-string 2 ans)))
16911 (setq ans (replace-match "" t t ans)))
16913 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16914 (when (string-match
16915 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16916 (setq year (if (match-end 2)
16917 (string-to-number (match-string 2 ans))
16918 (progn (setq kill-year t)
16919 (string-to-number (format-time-string "%Y"))))
16920 month (string-to-number (match-string 3 ans))
16921 day (string-to-number (match-string 4 ans)))
16922 (setq year (org-small-year-to-year year))
16923 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16924 t nil ans)))
16926 ;; Help matching dotted european dates
16927 (when (string-match
16928 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16929 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16930 (setq kill-year t)
16931 (string-to-number (format-time-string "%Y")))
16932 day (string-to-number (match-string 1 ans))
16933 month (string-to-number (match-string 2 ans))
16934 ans (replace-match (format "%04d-%02d-%02d" year month day)
16935 t nil ans)))
16937 ;; Help matching american dates, like 5/30 or 5/30/7
16938 (when (string-match
16939 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16940 (setq year (if (match-end 4)
16941 (string-to-number (match-string 4 ans))
16942 (progn (setq kill-year t)
16943 (string-to-number (format-time-string "%Y"))))
16944 month (string-to-number (match-string 1 ans))
16945 day (string-to-number (match-string 2 ans)))
16946 (setq year (org-small-year-to-year year))
16947 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16948 t nil ans)))
16949 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16950 ;; If there is a time with am/pm, and *no* time without it, we convert
16951 ;; so that matching will be successful.
16952 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16953 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16954 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16955 (setq hour (string-to-number (match-string 1 ans))
16956 minute (if (match-end 3)
16957 (string-to-number (match-string 3 ans))
16959 pm (equal ?p
16960 (string-to-char (downcase (match-string 4 ans)))))
16961 (if (and (= hour 12) (not pm))
16962 (setq hour 0)
16963 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16964 (setq ans (replace-match (format "%02d:%02d" hour minute)
16965 t t ans))))
16967 ;; Check if a time range is given as a duration
16968 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16969 (setq hour (string-to-number (match-string 1 ans))
16970 h2 (+ hour (string-to-number (match-string 3 ans)))
16971 minute (string-to-number (match-string 2 ans))
16972 m2 (+ minute (if (match-end 5) (string-to-number
16973 (match-string 5 ans))0)))
16974 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16975 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16976 t t ans)))
16978 ;; Check if there is a time range
16979 (when (boundp 'org-end-time-was-given)
16980 (setq org-time-was-given nil)
16981 (when (and (string-match org-plain-time-of-day-regexp ans)
16982 (match-end 8))
16983 (setq org-end-time-was-given (match-string 8 ans))
16984 (setq ans (concat (substring ans 0 (match-beginning 7))
16985 (substring ans (match-end 7))))))
16987 (setq tl (parse-time-string ans)
16988 day (or (nth 3 tl) (nth 3 org-defdecode))
16989 month
16990 (cond ((nth 4 tl))
16991 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16992 ;; Day was specified. Make sure DAY+MONTH
16993 ;; combination happens in the future.
16994 ((nth 3 tl)
16995 (setq futurep t)
16996 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16997 (nth 4 nowdecode)))
16998 (t (nth 4 org-defdecode)))
16999 year
17000 (cond ((and (not kill-year) (nth 5 tl)))
17001 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17002 ;; Month was guessed in the future and is at least
17003 ;; equal to NOWDECODE's. Fix year accordingly.
17004 (futurep
17005 (if (or (> month (nth 4 nowdecode))
17006 (>= day (nth 3 nowdecode)))
17007 (nth 5 nowdecode)
17008 (1+ (nth 5 nowdecode))))
17009 ;; Month was specified. Make sure MONTH+YEAR
17010 ;; combination happens in the future.
17011 ((nth 4 tl)
17012 (setq futurep t)
17013 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17014 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17015 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17016 (t (nth 5 nowdecode))))
17017 (t (nth 5 org-defdecode)))
17018 hour (or (nth 2 tl) (nth 2 org-defdecode))
17019 minute (or (nth 1 tl) (nth 1 org-defdecode))
17020 second (or (nth 0 tl) 0)
17021 wday (nth 6 tl))
17023 (when (and (eq org-read-date-prefer-future 'time)
17024 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17025 (equal day (nth 3 nowdecode))
17026 (equal month (nth 4 nowdecode))
17027 (equal year (nth 5 nowdecode))
17028 (nth 2 tl)
17029 (or (< (nth 2 tl) (nth 2 nowdecode))
17030 (and (= (nth 2 tl) (nth 2 nowdecode))
17031 (nth 1 tl)
17032 (< (nth 1 tl) (nth 1 nowdecode)))))
17033 (setq day (1+ day)
17034 futurep t))
17036 ;; Special date definitions below
17037 (cond
17038 (iso-week
17039 ;; There was an iso week
17040 (require 'cal-iso)
17041 (setq futurep nil)
17042 (setq year (or iso-year year)
17043 day (or iso-weekday wday 1)
17044 wday nil ; to make sure that the trigger below does not match
17045 iso-date (calendar-gregorian-from-absolute
17046 (calendar-iso-to-absolute
17047 (list iso-week day year))))
17048 ; FIXME: Should we also push ISO weeks into the future?
17049 ; (when (and org-read-date-prefer-future
17050 ; (not iso-year)
17051 ; (< (calendar-absolute-from-gregorian iso-date)
17052 ; (time-to-days (current-time))))
17053 ; (setq year (1+ year)
17054 ; iso-date (calendar-gregorian-from-absolute
17055 ; (calendar-iso-to-absolute
17056 ; (list iso-week day year)))))
17057 (setq month (car iso-date)
17058 year (nth 2 iso-date)
17059 day (nth 1 iso-date)))
17060 (deltan
17061 (setq futurep nil)
17062 (unless deltadef
17063 ;; Pass `current-time' result to `decode-time' (instead of
17064 ;; calling without arguments) so that only `current-time' has
17065 ;; to be overridden in tests.
17066 (let ((now (decode-time (current-time))))
17067 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17068 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17069 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17070 ((equal deltaw "m") (setq month (+ month deltan)))
17071 ((equal deltaw "y") (setq year (+ year deltan)))))
17072 ((and wday (not (nth 3 tl)))
17073 ;; Weekday was given, but no day, so pick that day in the week
17074 ;; on or after the derived date.
17075 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17076 (unless (equal wday wday1)
17077 (setq day (+ day (% (- wday wday1 -7) 7))))))
17078 (when (and (boundp 'org-time-was-given)
17079 (nth 2 tl))
17080 (setq org-time-was-given t))
17081 (when (< year 100) (setq year (+ 2000 year)))
17082 ;; Check of the date is representable
17083 (if org-read-date-force-compatible-dates
17084 (progn
17085 (when (< year 1970)
17086 (setq year 1970 org-read-date-analyze-forced-year t))
17087 (when (> year 2037)
17088 (setq year 2037 org-read-date-analyze-forced-year t)))
17089 (condition-case nil
17090 (ignore (encode-time second minute hour day month year))
17091 (error
17092 (setq year (nth 5 org-defdecode))
17093 (setq org-read-date-analyze-forced-year t))))
17094 (setq org-read-date-analyze-futurep futurep)
17095 (list second minute hour day month year)))
17097 (defvar parse-time-weekdays)
17098 (defun org-read-date-get-relative (s today default)
17099 "Check string S for special relative date string.
17100 TODAY and DEFAULT are internal times, for today and for a default.
17101 Return shift list (N what def-flag)
17102 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17103 N is the number of WHATs to shift.
17104 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17105 the DEFAULT date rather than TODAY."
17106 (require 'parse-time)
17107 (when (and
17108 (string-match
17109 (concat
17110 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17111 "\\([0-9]+\\)?"
17112 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17113 "\\([ \t]\\|$\\)") s)
17114 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17115 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17116 (string-to-char (substring (match-string 1 s) -1))
17117 ?+))
17118 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17119 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17120 (what (if (match-end 3) (match-string 3 s) "d"))
17121 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17122 (date (if rel default today))
17123 (wday (nth 6 (decode-time date)))
17124 delta)
17125 (if wday1
17126 (progn
17127 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17128 (when (= delta 0) (setq delta 7))
17129 (when (= dir ?-)
17130 (setq delta (- delta 7))
17131 (when (= delta 0) (setq delta -7)))
17132 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17133 (list delta "d" rel))
17134 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17136 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17137 "Turn a user-specified date into the internal representation.
17138 The internal representation needed by the calendar is (month day year).
17139 This is a wrapper to handle the brain-dead convention in calendar that
17140 user function argument order change dependent on argument order."
17141 (pcase calendar-date-style
17142 (`american (list arg1 arg2 arg3))
17143 (`european (list arg2 arg1 arg3))
17144 (`iso (list arg2 arg3 arg1))))
17146 (defun org-eval-in-calendar (form &optional keepdate)
17147 "Eval FORM in the calendar window and return to current window.
17148 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17149 (let ((sf (selected-frame))
17150 (sw (selected-window)))
17151 (select-window (get-buffer-window "*Calendar*" t))
17152 (eval form)
17153 (when (and (not keepdate) (calendar-cursor-to-date))
17154 (let* ((date (calendar-cursor-to-date))
17155 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17156 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17157 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17158 (select-window sw)
17159 (select-frame-set-input-focus sf)))
17161 (defun org-calendar-select ()
17162 "Return to `org-read-date' with the date currently selected.
17163 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17164 (interactive)
17165 (when (calendar-cursor-to-date)
17166 (let* ((date (calendar-cursor-to-date))
17167 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17168 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17169 (when (active-minibuffer-window) (exit-minibuffer))))
17171 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17172 "Insert a date stamp for the date given by the internal TIME.
17173 See `format-time-string' for the format of TIME.
17174 WITH-HM means use the stamp format that includes the time of the day.
17175 INACTIVE means use square brackets instead of angular ones, so that the
17176 stamp will not contribute to the agenda.
17177 PRE and POST are optional strings to be inserted before and after the
17178 stamp.
17179 The command returns the inserted time stamp."
17180 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17181 stamp)
17182 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17183 (insert-before-markers (or pre ""))
17184 (when (listp extra)
17185 (setq extra (car extra))
17186 (if (and (stringp extra)
17187 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17188 (setq extra (format "-%02d:%02d"
17189 (string-to-number (match-string 1 extra))
17190 (string-to-number (match-string 2 extra))))
17191 (setq extra nil)))
17192 (when extra
17193 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17194 (insert-before-markers (setq stamp (format-time-string fmt time)))
17195 (insert-before-markers (or post ""))
17196 (setq org-last-inserted-timestamp stamp)))
17198 (defun org-toggle-time-stamp-overlays ()
17199 "Toggle the use of custom time stamp formats."
17200 (interactive)
17201 (setq org-display-custom-times (not org-display-custom-times))
17202 (unless org-display-custom-times
17203 (let ((p (point-min)) (bmp (buffer-modified-p)))
17204 (while (setq p (next-single-property-change p 'display))
17205 (when (and (get-text-property p 'display)
17206 (eq (get-text-property p 'face) 'org-date))
17207 (remove-text-properties
17208 p (setq p (next-single-property-change p 'display))
17209 '(display t))))
17210 (set-buffer-modified-p bmp)))
17211 (org-restart-font-lock)
17212 (setq org-table-may-need-update t)
17213 (if org-display-custom-times
17214 (message "Time stamps are overlaid with custom format")
17215 (message "Time stamp overlays removed")))
17217 (defun org-display-custom-time (beg end)
17218 "Overlay modified time stamp format over timestamp between BEG and END."
17219 (let* ((ts (buffer-substring beg end))
17220 t1 with-hm tf time str (off 0))
17221 (save-match-data
17222 (setq t1 (org-parse-time-string ts t))
17223 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17224 (setq off (- (match-end 0) (match-beginning 0)))))
17225 (setq end (- end off))
17226 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17227 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17228 time (org-fix-decoded-time t1)
17229 str (org-add-props
17230 (format-time-string
17231 (substring tf 1 -1) (apply 'encode-time time))
17232 nil 'mouse-face 'highlight))
17233 (put-text-property beg end 'display str)))
17235 (defun org-fix-decoded-time (time)
17236 "Set 0 instead of nil for the first 6 elements of time.
17237 Don't touch the rest."
17238 (let ((n 0))
17239 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17241 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17242 "Difference between TIMESTAMP-STRING and now in days.
17243 If SECONDS is non-nil, return the difference in seconds."
17244 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17245 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17246 (funcall fdiff (current-time)))))
17248 (defun org-deadline-close-p (timestamp-string &optional ndays)
17249 "Is the time in TIMESTAMP-STRING close to the current date?"
17250 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17251 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17252 (not (org-entry-is-done-p))))
17254 (defun org-get-wdays (ts &optional delay zero-delay)
17255 "Get the deadline lead time appropriate for timestring TS.
17256 When DELAY is non-nil, get the delay time for scheduled items
17257 instead of the deadline lead time. When ZERO-DELAY is non-nil
17258 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17259 don't try to find the delay cookie in the scheduled timestamp."
17260 (let ((tv (if delay org-scheduled-delay-days
17261 org-deadline-warning-days)))
17262 (cond
17263 ((or (and delay (< tv 0))
17264 (and delay zero-delay (<= tv 0))
17265 (and (not delay) (<= tv 0)))
17266 ;; Enforce this value no matter what
17267 (- tv))
17268 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17269 ;; lead time is specified.
17270 (floor (* (string-to-number (match-string 1 ts))
17271 (cdr (assoc (match-string 2 ts)
17272 '(("d" . 1) ("w" . 7)
17273 ("m" . 30.4) ("y" . 365.25)
17274 ("h" . 0.041667)))))))
17275 ;; go for the default.
17276 (t tv))))
17278 (defun org-calendar-select-mouse (ev)
17279 "Return to `org-read-date' with the date currently selected.
17280 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17281 (interactive "e")
17282 (mouse-set-point ev)
17283 (when (calendar-cursor-to-date)
17284 (let* ((date (calendar-cursor-to-date))
17285 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17286 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17287 (when (active-minibuffer-window) (exit-minibuffer))))
17289 (defun org-check-deadlines (ndays)
17290 "Check if there are any deadlines due or past due.
17291 A deadline is considered due if it happens within `org-deadline-warning-days'
17292 days from today's date. If the deadline appears in an entry marked DONE,
17293 it is not shown. A numeric prefix argument NDAYS can be used to test that
17294 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17295 are shown."
17296 (interactive "P")
17297 (let* ((org-warn-days
17298 (cond
17299 ((equal ndays '(4)) 100000)
17300 (ndays (prefix-numeric-value ndays))
17301 (t (abs org-deadline-warning-days))))
17302 (case-fold-search nil)
17303 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17304 (callback
17305 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17306 (message "%d deadlines past-due or due within %d days"
17307 (org-occur regexp nil callback)
17308 org-warn-days)))
17310 (defsubst org-re-timestamp (type)
17311 "Return a regexp for timestamp TYPE.
17312 Allowed values for TYPE are:
17314 all: all timestamps
17315 active: only active timestamps (<...>)
17316 inactive: only inactive timestamps ([...])
17317 scheduled: only scheduled timestamps
17318 deadline: only deadline timestamps
17319 closed: only closed time-stamps
17321 When TYPE is nil, fall back on returning a regexp that matches
17322 both scheduled and deadline timestamps."
17323 (cl-case type
17324 (all org-ts-regexp-both)
17325 (active org-ts-regexp)
17326 (inactive org-ts-regexp-inactive)
17327 (scheduled org-scheduled-time-regexp)
17328 (deadline org-deadline-time-regexp)
17329 (closed org-closed-time-regexp)
17330 (otherwise
17331 (concat "\\<"
17332 (regexp-opt (list org-deadline-string org-scheduled-string))
17333 " *<\\([^>]+\\)>"))))
17335 (defun org-check-before-date (d)
17336 "Check if there are deadlines or scheduled entries before date D."
17337 (interactive (list (org-read-date)))
17338 (let* ((case-fold-search nil)
17339 (regexp (org-re-timestamp org-ts-type))
17340 (ts-type org-ts-type)
17341 (callback
17342 (lambda ()
17343 (let ((match (match-string 1)))
17344 (and (if (memq ts-type '(active inactive all))
17345 (eq (org-element-type (save-excursion
17346 (backward-char)
17347 (org-element-context)))
17348 'timestamp)
17349 (org-at-planning-p))
17350 (time-less-p
17351 (org-time-string-to-time match t)
17352 (org-time-string-to-time d t)))))))
17353 (message "%d entries before %s"
17354 (org-occur regexp nil callback)
17355 d)))
17357 (defun org-check-after-date (d)
17358 "Check if there are deadlines or scheduled entries after date D."
17359 (interactive (list (org-read-date)))
17360 (let* ((case-fold-search nil)
17361 (regexp (org-re-timestamp org-ts-type))
17362 (ts-type org-ts-type)
17363 (callback
17364 (lambda ()
17365 (let ((match (match-string 1)))
17366 (and (if (memq ts-type '(active inactive all))
17367 (eq (org-element-type (save-excursion
17368 (backward-char)
17369 (org-element-context)))
17370 'timestamp)
17371 (org-at-planning-p))
17372 (not (time-less-p
17373 (org-time-string-to-time match t)
17374 (org-time-string-to-time d t))))))))
17375 (message "%d entries after %s"
17376 (org-occur regexp nil callback)
17377 d)))
17379 (defun org-check-dates-range (start-date end-date)
17380 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17381 (interactive (list (org-read-date nil nil nil "Range starts")
17382 (org-read-date nil nil nil "Range end")))
17383 (let ((case-fold-search nil)
17384 (regexp (org-re-timestamp org-ts-type))
17385 (callback
17386 (let ((type org-ts-type))
17387 (lambda ()
17388 (let ((match (match-string 1)))
17389 (and
17390 (if (memq type '(active inactive all))
17391 (eq (org-element-type (save-excursion
17392 (backward-char)
17393 (org-element-context)))
17394 'timestamp)
17395 (org-at-planning-p))
17396 (not (time-less-p
17397 (org-time-string-to-time match t)
17398 (org-time-string-to-time start-date t)))
17399 (time-less-p
17400 (org-time-string-to-time match t)
17401 (org-time-string-to-time end-date t))))))))
17402 (message "%d entries between %s and %s"
17403 (org-occur regexp nil callback) start-date end-date)))
17405 (defun org-evaluate-time-range (&optional to-buffer)
17406 "Evaluate a time range by computing the difference between start and end.
17407 Normally the result is just printed in the echo area, but with prefix arg
17408 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17409 If the time range is actually in a table, the result is inserted into the
17410 next column.
17411 For time difference computation, a year is assumed to be exactly 365
17412 days in order to avoid rounding problems."
17413 (interactive "P")
17415 (org-clock-update-time-maybe)
17416 (save-excursion
17417 (unless (org-at-date-range-p t)
17418 (goto-char (point-at-bol))
17419 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17420 (unless (org-at-date-range-p t)
17421 (user-error "Not at a time-stamp range, and none found in current line")))
17422 (let* ((ts1 (match-string 1))
17423 (ts2 (match-string 2))
17424 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17425 (match-end (match-end 0))
17426 (time1 (org-time-string-to-time ts1))
17427 (time2 (org-time-string-to-time ts2))
17428 (t1 (float-time time1))
17429 (t2 (float-time time2))
17430 (diff (abs (- t2 t1)))
17431 (negative (< (- t2 t1) 0))
17432 ;; (ys (floor (* 365 24 60 60)))
17433 (ds (* 24 60 60))
17434 (hs (* 60 60))
17435 (fy "%dy %dd %02d:%02d")
17436 (fy1 "%dy %dd")
17437 (fd "%dd %02d:%02d")
17438 (fd1 "%dd")
17439 (fh "%02d:%02d")
17440 y d h m align)
17441 (if havetime
17442 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17444 d (floor (/ diff ds)) diff (mod diff ds)
17445 h (floor (/ diff hs)) diff (mod diff hs)
17446 m (floor (/ diff 60)))
17447 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17449 d (floor (+ (/ diff ds) 0.5))
17450 h 0 m 0))
17451 (if (not to-buffer)
17452 (message "%s" (org-make-tdiff-string y d h m))
17453 (if (org-at-table-p)
17454 (progn
17455 (goto-char match-end)
17456 (setq align t)
17457 (and (looking-at " *|") (goto-char (match-end 0))))
17458 (goto-char match-end))
17459 (when (looking-at
17460 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17461 (replace-match ""))
17462 (when negative (insert " -"))
17463 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17464 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17465 (insert " " (format fh h m))))
17466 (when align (org-table-align))
17467 (message "Time difference inserted")))))
17469 (defun org-make-tdiff-string (y d h m)
17470 (let ((fmt "")
17471 (l nil))
17472 (when (> y 0)
17473 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17474 (push y l))
17475 (when (> d 0)
17476 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17477 (push d l))
17478 (when (> h 0)
17479 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17480 (push h l))
17481 (when (> m 0)
17482 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17483 (push m l))
17484 (apply 'format fmt (nreverse l))))
17486 (defun org-time-string-to-time (s &optional zone)
17487 "Convert timestamp string S into internal time.
17488 The optional ZONE is omitted or nil for Emacs local time, t for
17489 Universal Time, ‘wall’ for system wall clock time, or a string as
17490 in the TZ environment variable."
17491 (apply #'encode-time (org-parse-time-string s nil zone)))
17493 (defun org-time-string-to-seconds (s &optional zone)
17494 "Convert a timestamp string S into a number of seconds.
17495 The optional ZONE is omitted or nil for Emacs local time, t for
17496 Universal Time, ‘wall’ for system wall clock time, or a string as
17497 in the TZ environment variable."
17498 (float-time (org-time-string-to-time s zone)))
17500 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17502 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17503 "Convert time stamp S to an absolute day number.
17505 If DAYNR in non-nil, and there is a specifier for a cyclic time
17506 stamp, get the closest date to DAYNR. If PREFER is
17507 `past' (respectively `future') return a date past (respectively
17508 after) or equal to DAYNR.
17510 POS is the location of time stamp S, as a buffer position in
17511 BUFFER.
17513 Diary sexp timestamps are matched against DAYNR, when non-nil.
17514 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17515 signaled."
17516 (cond
17517 ((string-match "\\`%%\\((.*)\\)" s)
17518 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17519 ;; only able to match individual dates. If it fails, raise an
17520 ;; error.
17521 (if (and daynr
17522 (org-diary-sexp-entry
17523 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17524 daynr
17525 (signal 'org-diary-sexp-no-match (list s))))
17526 (daynr (org-closest-date s daynr prefer))
17527 (t (time-to-days
17528 (condition-case errdata
17529 (apply #'encode-time (org-parse-time-string s))
17530 (error (error "Bad timestamp `%s'%s\nError was: %s"
17532 (if (not (and buffer pos)) ""
17533 (format-message " at %d in buffer `%s'" pos buffer))
17534 (cdr errdata))))))))
17536 (defun org-days-to-iso-week (days)
17537 "Return the iso week number."
17538 (require 'cal-iso)
17539 (car (calendar-iso-from-absolute days)))
17541 (defun org-small-year-to-year (year)
17542 "Convert 2-digit years into 4-digit years.
17543 YEAR is expanded into one of the 30 next years, if possible, or
17544 into a past one. Any year larger than 99 is returned unchanged."
17545 (if (>= year 100) year
17546 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17547 (century (/ current 100))
17548 (offset (- year (% current 100))))
17549 (cond ((> offset 30) (+ (* (1- century) 100) year))
17550 ((> offset -70) (+ (* century 100) year))
17551 (t (+ (* (1+ century) 100) year))))))
17553 (defun org-time-from-absolute (d)
17554 "Return the time corresponding to date D.
17555 D may be an absolute day number, or a calendar-type list (month day year)."
17556 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17557 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17559 (defvar org-agenda-current-date)
17560 (defun org-calendar-holiday ()
17561 "List of holidays, for Diary display in Org mode."
17562 (require 'holidays)
17563 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17564 (and hl (mapconcat #'identity hl "; "))))
17566 (defun org-diary-sexp-entry (sexp entry d)
17567 "Process a SEXP diary ENTRY for date D."
17568 (require 'diary-lib)
17569 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17570 ;; dynamically.
17571 (let* ((sexp `(let ((entry ,entry)
17572 (date ',d))
17573 ,(car (read-from-string sexp))))
17574 (result (if calendar-debug-sexp (eval sexp)
17575 (condition-case nil
17576 (eval sexp)
17577 (error
17578 (beep)
17579 (message "Bad sexp at line %d in %s: %s"
17580 (org-current-line)
17581 (buffer-file-name) sexp)
17582 (sleep-for 2))))))
17583 (cond ((stringp result) (split-string result "; "))
17584 ((and (consp result)
17585 (not (consp (cdr result)))
17586 (stringp (cdr result))) (cdr result))
17587 ((and (consp result)
17588 (stringp (car result))) result)
17589 (result entry))))
17591 (defun org-diary-to-ical-string (frombuf)
17592 "Get iCalendar entries from diary entries in buffer FROMBUF.
17593 This uses the icalendar.el library."
17594 (let* ((tmpdir temporary-file-directory)
17595 (tmpfile (make-temp-name
17596 (expand-file-name "orgics" tmpdir)))
17597 buf rtn b e)
17598 (with-current-buffer frombuf
17599 (icalendar-export-region (point-min) (point-max) tmpfile)
17600 (setq buf (find-buffer-visiting tmpfile))
17601 (set-buffer buf)
17602 (goto-char (point-min))
17603 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17604 (setq b (match-beginning 0)))
17605 (goto-char (point-max))
17606 (when (re-search-backward "^END:VEVENT" nil t)
17607 (setq e (match-end 0)))
17608 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17609 (kill-buffer buf)
17610 (delete-file tmpfile)
17611 rtn))
17613 (defun org-closest-date (start current prefer)
17614 "Return closest date to CURRENT starting from START.
17616 CURRENT and START are both time stamps.
17618 When PREFER is `past', return a date that is either CURRENT or
17619 past. When PREFER is `future', return a date that is either
17620 CURRENT or future.
17622 Only time stamps with a repeater are modified. Any other time
17623 stamp stay unchanged. In any case, return value is an absolute
17624 day number."
17625 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17626 ;; No repeater. Do not shift time stamp.
17627 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17628 (let ((value (string-to-number (match-string 1 start)))
17629 (type (match-string 2 start)))
17630 (if (= 0 value)
17631 ;; Repeater with a 0-value is considered as void.
17632 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17633 (let* ((base (org-date-to-gregorian start))
17634 (target (org-date-to-gregorian current))
17635 (sday (calendar-absolute-from-gregorian base))
17636 (cday (calendar-absolute-from-gregorian target))
17637 n1 n2)
17638 ;; If START is already past CURRENT, just return START.
17639 (if (<= cday sday) sday
17640 ;; Compute closest date before (N1) and closest date past
17641 ;; (N2) CURRENT.
17642 (pcase type
17643 ("h"
17644 (let ((missing-hours
17645 (mod (+ (- (* 24 (- cday sday))
17646 (nth 2 (org-parse-time-string start)))
17647 org-extend-today-until)
17648 value)))
17649 (setf n1 (if (= missing-hours 0) cday
17650 (- cday (1+ (/ missing-hours 24)))))
17651 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17652 ((or "d" "w")
17653 (let ((value (if (equal type "w") (* 7 value) value)))
17654 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17655 (setf n2 (+ n1 value))))
17656 ("m"
17657 (let* ((add-months
17658 (lambda (d n)
17659 ;; Add N months to gregorian date D, i.e.,
17660 ;; a list (MONTH DAY YEAR). Return a valid
17661 ;; gregorian date.
17662 (let ((m (+ (nth 0 d) n)))
17663 (list (mod m 12)
17664 (nth 1 d)
17665 (+ (/ m 12) (nth 2 d))))))
17666 (months ; Complete months to TARGET.
17667 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17668 (- (nth 0 target) (nth 0 base))
17669 ;; If START's day is greater than
17670 ;; TARGET's, remove incomplete month.
17671 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17672 value)
17673 value))
17674 (before (funcall add-months base months)))
17675 (setf n1 (calendar-absolute-from-gregorian before))
17676 (setf n2
17677 (calendar-absolute-from-gregorian
17678 (funcall add-months before value)))))
17680 (let* ((d (nth 1 base))
17681 (m (nth 0 base))
17682 (y (nth 2 base))
17683 (years ; Complete years to TARGET.
17684 (* (/ (- (nth 2 target)
17686 ;; If START's month and day are
17687 ;; greater than TARGET's, remove
17688 ;; incomplete year.
17689 (if (or (> (nth 0 target) m)
17690 (and (= (nth 0 target) m)
17691 (> (nth 1 target) d)))
17694 value)
17695 value))
17696 (before (list m d (+ y years))))
17697 (setf n1 (calendar-absolute-from-gregorian before))
17698 (setf n2 (calendar-absolute-from-gregorian
17699 (list m d (+ (nth 2 before) value)))))))
17700 ;; Handle PREFER parameter, if any.
17701 (cond
17702 ((eq prefer 'past) (if (= cday n2) n2 n1))
17703 ((eq prefer 'future) (if (= cday n1) n1 n2))
17704 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17706 (defun org-date-to-gregorian (d)
17707 "Turn any specification of date D into a Gregorian date for the calendar."
17708 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17709 ((and (listp d) (= (length d) 3)) d)
17710 ((stringp d)
17711 (let ((d (org-parse-time-string d)))
17712 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17713 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17715 (defun org-parse-time-string (s &optional nodefault zone)
17716 "Parse the standard Org time string.
17718 This should be a lot faster than the normal `parse-time-string'.
17720 If time is not given, defaults to 0:00. However, with optional
17721 NODEFAULT, hour and minute fields will be nil if not given.
17723 The optional ZONE is omitted or nil for Emacs local time, t for
17724 Universal Time, ‘wall’ for system wall clock time, or a string as
17725 in the TZ environment variable."
17726 (cond ((string-match org-ts-regexp0 s)
17727 (list 0
17728 (when (or (match-beginning 8) (not nodefault))
17729 (string-to-number (or (match-string 8 s) "0")))
17730 (when (or (match-beginning 7) (not nodefault))
17731 (string-to-number (or (match-string 7 s) "0")))
17732 (string-to-number (match-string 4 s))
17733 (string-to-number (match-string 3 s))
17734 (string-to-number (match-string 2 s))
17735 nil nil zone))
17736 ((string-match "^<[^>]+>$" s)
17737 ;; FIXME: `decode-time' needs to be called with ZONE as its
17738 ;; second argument. However, this requires at least Emacs
17739 ;; 25.1. We can do it when we switch to this version as our
17740 ;; minimal requirement.
17741 (decode-time (seconds-to-time (org-matcher-time s))))
17742 (t (error "Not a standard Org time string: %s" s))))
17744 (defun org-timestamp-up (&optional arg)
17745 "Increase the date item at the cursor by one.
17746 If the cursor is on the year, change the year. If it is on the month,
17747 the day or the time, change that.
17748 With prefix ARG, change by that many units."
17749 (interactive "p")
17750 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17752 (defun org-timestamp-down (&optional arg)
17753 "Decrease the date item at the cursor by one.
17754 If the cursor is on the year, change the year. If it is on the month,
17755 the day or the time, change that.
17756 With prefix ARG, change by that many units."
17757 (interactive "p")
17758 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17760 (defun org-timestamp-up-day (&optional arg)
17761 "Increase the date in the time stamp by one day.
17762 With prefix ARG, change that many days."
17763 (interactive "p")
17764 (if (and (not (org-at-timestamp-p 'lax))
17765 (org-at-heading-p))
17766 (org-todo 'up)
17767 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17769 (defun org-timestamp-down-day (&optional arg)
17770 "Decrease the date in the time stamp by one day.
17771 With prefix ARG, change that many days."
17772 (interactive "p")
17773 (if (and (not (org-at-timestamp-p 'lax))
17774 (org-at-heading-p))
17775 (org-todo 'down)
17776 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17778 (defun org-at-timestamp-p (&optional extended)
17779 "Non-nil if point is inside a timestamp.
17781 By default, the function only consider syntactically valid active
17782 timestamps. However, the caller may have a broader definition
17783 for timestamps. As a consequence, optional argument EXTENDED can
17784 be set to the following values
17786 `inactive'
17788 Include also syntactically valid inactive timestamps.
17790 `agenda'
17792 Include timestamps allowed in Agenda, i.e., those in
17793 properties drawers, planning lines and clock lines.
17795 `lax'
17797 Ignore context. The function matches any part of the
17798 document looking like a timestamp. This includes comments,
17799 example blocks...
17801 For backward-compatibility with Org 9.0, every other non-nil
17802 value is equivalent to `inactive'.
17804 When at a timestamp, return the position of the point as a symbol
17805 among `bracket', `after', `year', `month', `hour', `minute',
17806 `day' or a number of character from the last know part of the
17807 time stamp.
17809 When matching, the match groups are the following:
17810 group 1: year
17811 group 2: month
17812 group 3: day number
17813 group 4: day name
17814 group 5: hours, if any
17815 group 6: minutes, if any"
17816 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17817 (pos (point))
17818 (match?
17819 (let ((boundaries (org-in-regexp regexp)))
17820 (save-match-data
17821 (cond ((null boundaries) nil)
17822 ((eq extended 'lax) t)
17824 (or (and (eq extended 'agenda)
17825 (or (org-at-planning-p)
17826 (org-at-property-p)
17827 (and (bound-and-true-p
17828 org-agenda-include-inactive-timestamps)
17829 (org-at-clock-log-p))))
17830 (eq 'timestamp
17831 (save-excursion
17832 (when (= pos (cdr boundaries)) (forward-char -1))
17833 (org-element-type (org-element-context)))))))))))
17834 (cond
17835 ((not match?) nil)
17836 ((= pos (match-beginning 0)) 'bracket)
17837 ;; Distinguish location right before the closing bracket from
17838 ;; right after it.
17839 ((= pos (1- (match-end 0))) 'bracket)
17840 ((= pos (match-end 0)) 'after)
17841 ((org-pos-in-match-range pos 2) 'year)
17842 ((org-pos-in-match-range pos 3) 'month)
17843 ((org-pos-in-match-range pos 7) 'hour)
17844 ((org-pos-in-match-range pos 8) 'minute)
17845 ((or (org-pos-in-match-range pos 4)
17846 (org-pos-in-match-range pos 5)) 'day)
17847 ((and (> pos (or (match-end 8) (match-end 5)))
17848 (< pos (match-end 0)))
17849 (- pos (or (match-end 8) (match-end 5))))
17850 (t 'day))))
17852 (defun org-toggle-timestamp-type ()
17853 "Toggle the type (<active> or [inactive]) of a time stamp."
17854 (interactive)
17855 (when (org-at-timestamp-p 'lax)
17856 (let ((beg (match-beginning 0)) (end (match-end 0))
17857 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17858 (save-excursion
17859 (goto-char beg)
17860 (while (re-search-forward "[][<>]" end t)
17861 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17862 t t)))
17863 (message "Timestamp is now %sactive"
17864 (if (equal (char-after beg) ?<) "" "in")))))
17866 (defun org-at-clock-log-p ()
17867 "Non-nil if point is on a clock log line."
17868 (and (org-match-line org-clock-line-re)
17869 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17871 (defvar org-clock-history) ; defined in org-clock.el
17872 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17873 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17874 "Change the date in the time stamp at point.
17875 The date will be changed by N times WHAT. WHAT can be `day', `month',
17876 `year', `minute', `second'. If WHAT is not given, the cursor position
17877 in the timestamp determines what will be changed.
17878 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17879 (let ((origin (point))
17880 (timestamp? (org-at-timestamp-p 'lax))
17881 origin-cat
17882 with-hm inactive
17883 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17884 extra rem
17885 ts time time0 fixnext clrgx)
17886 (unless timestamp? (user-error "Not at a timestamp"))
17887 (if (and (not what) (eq timestamp? 'bracket))
17888 (org-toggle-timestamp-type)
17889 ;; Point isn't on brackets. Remember the part of the time-stamp
17890 ;; the point was in. Indeed, size of time-stamps may change,
17891 ;; but point must be kept in the same category nonetheless.
17892 (setq origin-cat timestamp?)
17893 (when (and (not what) (not (eq timestamp? 'day))
17894 org-display-custom-times
17895 (get-text-property (point) 'display)
17896 (not (get-text-property (1- (point)) 'display)))
17897 (setq timestamp? 'day))
17898 (setq timestamp? (or what timestamp?)
17899 inactive (= (char-after (match-beginning 0)) ?\[)
17900 ts (match-string 0))
17901 (replace-match "")
17902 (when (string-match
17903 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17905 (setq extra (match-string 1 ts))
17906 (when suppress-tmp-delay
17907 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17908 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17909 (setq with-hm t))
17910 (setq time0 (org-parse-time-string ts))
17911 (when (and updown
17912 (eq timestamp? 'minute)
17913 (not current-prefix-arg))
17914 ;; This looks like s-up and s-down. Change by one rounding step.
17915 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17916 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17917 (setcar (cdr time0) (+ (nth 1 time0)
17918 (if (> n 0) (- rem) (- dm rem))))))
17919 (setq time
17920 (apply #'encode-time
17921 (or (car time0) 0)
17922 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17923 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17924 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17925 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17926 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17927 (nthcdr 6 time0)))
17928 (when (and (memq timestamp? '(hour minute))
17929 extra
17930 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17931 (setq extra (org-modify-ts-extra
17932 extra
17933 (if (eq timestamp? 'hour) 2 5)
17934 n dm)))
17935 (when (integerp timestamp?)
17936 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17937 (when (eq what 'calendar)
17938 (let ((cal-date (org-get-date-from-calendar)))
17939 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17940 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17941 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17942 (setcar time0 (or (car time0) 0))
17943 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17944 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17945 (setq time (apply 'encode-time time0))))
17946 ;; Insert the new time-stamp, and ensure point stays in the same
17947 ;; category as before (i.e. not after the last position in that
17948 ;; category).
17949 (let ((pos (point)))
17950 ;; Stay before inserted string. `save-excursion' is of no use.
17951 (setq org-last-changed-timestamp
17952 (org-insert-time-stamp time with-hm inactive nil nil extra))
17953 (goto-char pos))
17954 (save-match-data
17955 (looking-at org-ts-regexp3)
17956 (goto-char
17957 (pcase origin-cat
17958 ;; `day' category ends before `hour' if any, or at the end
17959 ;; of the day name.
17960 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17961 (`hour (min (match-end 7) origin))
17962 (`minute (min (1- (match-end 8)) origin))
17963 ((pred integerp) (min (1- (match-end 0)) origin))
17964 ;; Point was right after the time-stamp. However, the
17965 ;; time-stamp length might have changed, so refer to
17966 ;; (match-end 0) instead.
17967 (`after (match-end 0))
17968 ;; `year' and `month' have both fixed size: point couldn't
17969 ;; have moved into another part.
17970 (_ origin))))
17971 ;; Update clock if on a CLOCK line.
17972 (org-clock-update-time-maybe)
17973 ;; Maybe adjust the closest clock in `org-clock-history'
17974 (when org-clock-adjust-closest
17975 (if (not (and (org-at-clock-log-p)
17976 (< 1 (length (delq nil (mapcar 'marker-position
17977 org-clock-history))))))
17978 (message "No clock to adjust")
17979 (cond ((save-excursion ; fix previous clock?
17980 (re-search-backward org-ts-regexp0 nil t)
17981 (looking-back (concat org-clock-string " \\[")
17982 (line-beginning-position)))
17983 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17984 ((save-excursion ; fix next clock?
17985 (re-search-backward org-ts-regexp0 nil t)
17986 (looking-at (concat org-ts-regexp0 "\\] =>")))
17987 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17988 (save-window-excursion
17989 ;; Find closest clock to point, adjust the previous/next one in history
17990 (let* ((p (save-excursion (org-back-to-heading t)))
17991 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17992 (clfixnth
17993 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17994 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17995 (if (not clfixpos)
17996 (message "No clock to adjust")
17997 (save-excursion
17998 (org-goto-marker-or-bmk clfixpos)
17999 (org-show-subtree)
18000 (when (re-search-forward clrgx nil t)
18001 (goto-char (match-beginning 1))
18002 (let (org-clock-adjust-closest)
18003 (org-timestamp-change n timestamp? updown))
18004 (message "Clock adjusted in %s for heading: %s"
18005 (file-name-nondirectory (buffer-file-name))
18006 (org-get-heading t t)))))))))
18007 ;; Try to recenter the calendar window, if any.
18008 (when (and org-calendar-follow-timestamp-change
18009 (get-buffer-window "*Calendar*" t)
18010 (memq timestamp? '(day month year)))
18011 (org-recenter-calendar (time-to-days time))))))
18013 (defun org-modify-ts-extra (s pos n dm)
18014 "Change the different parts of the lead-time and repeat fields in timestamp."
18015 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18016 ng h m new rem)
18017 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18018 (cond
18019 ((or (org-pos-in-match-range pos 2)
18020 (org-pos-in-match-range pos 3))
18021 (setq m (string-to-number (match-string 3 s))
18022 h (string-to-number (match-string 2 s)))
18023 (if (org-pos-in-match-range pos 2)
18024 (setq h (+ h n))
18025 (setq n (* dm (with-no-warnings (signum n))))
18026 (unless (= 0 (setq rem (% m dm)))
18027 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18028 (setq m (+ m n)))
18029 (when (< m 0) (setq m (+ m 60) h (1- h)))
18030 (when (> m 59) (setq m (- m 60) h (1+ h)))
18031 (setq h (mod h 24))
18032 (setq ng 1 new (format "-%02d:%02d" h m)))
18033 ((org-pos-in-match-range pos 6)
18034 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18035 ((org-pos-in-match-range pos 5)
18036 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18038 ((org-pos-in-match-range pos 9)
18039 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18040 ((org-pos-in-match-range pos 8)
18041 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18043 (when ng
18044 (setq s (concat
18045 (substring s 0 (match-beginning ng))
18047 (substring s (match-end ng))))))
18050 (defun org-recenter-calendar (d)
18051 "If the calendar is visible, recenter it to date D."
18052 (let ((cwin (get-buffer-window "*Calendar*" t)))
18053 (when cwin
18054 (let ((calendar-move-hook nil))
18055 (with-selected-window cwin
18056 (calendar-goto-date
18057 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18059 (defun org-goto-calendar (&optional arg)
18060 "Go to the Emacs calendar at the current date.
18061 If there is a time stamp in the current line, go to that date.
18062 A prefix ARG can be used to force the current date."
18063 (interactive "P")
18064 (let ((calendar-move-hook nil)
18065 (calendar-view-holidays-initially-flag nil)
18066 (calendar-view-diary-initially-flag nil)
18067 diff)
18068 (when (or (org-at-timestamp-p 'lax)
18069 (org-match-line (concat ".*" org-ts-regexp)))
18070 (let ((d1 (time-to-days (current-time)))
18071 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18072 (setq diff (- d2 d1))))
18073 (calendar)
18074 (calendar-goto-today)
18075 (when (and diff (not arg)) (calendar-forward-day diff))))
18077 (defun org-get-date-from-calendar ()
18078 "Return a list (month day year) of date at point in calendar."
18079 (with-current-buffer "*Calendar*"
18080 (save-match-data
18081 (calendar-cursor-to-date))))
18083 (defun org-date-from-calendar ()
18084 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18085 If there is already a time stamp at the cursor position, update it."
18086 (interactive)
18087 (if (org-at-timestamp-p 'lax)
18088 (org-timestamp-change 0 'calendar)
18089 (let ((cal-date (org-get-date-from-calendar)))
18090 (org-insert-time-stamp
18091 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18093 (defcustom org-effort-durations
18094 `(("min" . 1)
18095 ("h" . 60)
18096 ("d" . ,(* 60 8))
18097 ("w" . ,(* 60 8 5))
18098 ("m" . ,(* 60 8 5 4))
18099 ("y" . ,(* 60 8 5 40)))
18100 "Conversion factor to minutes for an effort modifier.
18102 Each entry has the form (MODIFIER . MINUTES).
18104 In an effort string, a number followed by MODIFIER is multiplied
18105 by the specified number of MINUTES to obtain an effort in
18106 minutes.
18108 For example, if the value of this variable is ((\"hours\" . 60)), then an
18109 effort string \"2hours\" is equivalent to 120 minutes."
18110 :group 'org-agenda
18111 :version "26.1"
18112 :package-version '(Org . "8.3")
18113 :type '(alist :key-type (string :tag "Modifier")
18114 :value-type (number :tag "Minutes")))
18116 (defcustom org-image-actual-width t
18117 "Should we use the actual width of images when inlining them?
18119 When set to t, always use the image width.
18121 When set to a number, use imagemagick (when available) to set
18122 the image's width to this value.
18124 When set to a number in a list, try to get the width from any
18125 #+ATTR.* keyword if it matches a width specification like
18127 #+ATTR_HTML: :width 300px
18129 and fall back on that number if none is found.
18131 When set to nil, try to get the width from an #+ATTR.* keyword
18132 and fall back on the original width if none is found.
18134 This requires Emacs >= 24.1, build with imagemagick support."
18135 :group 'org-appearance
18136 :version "24.4"
18137 :package-version '(Org . "8.0")
18138 :type '(choice
18139 (const :tag "Use the image width" t)
18140 (integer :tag "Use a number of pixels")
18141 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18142 (const :tag "Use #+ATTR* or don't resize" nil)))
18144 (defcustom org-agenda-inhibit-startup nil
18145 "Inhibit startup when preparing agenda buffers.
18146 When this variable is t, the initialization of the Org agenda
18147 buffers is inhibited: e.g. the visibility state is not set, the
18148 tables are not re-aligned, etc."
18149 :type 'boolean
18150 :version "24.3"
18151 :group 'org-agenda)
18153 (defcustom org-agenda-ignore-properties nil
18154 "Avoid updating text properties when building the agenda.
18155 Properties are used to prepare buffers for effort estimates,
18156 appointments, statistics and subtree-local categories.
18157 If you don't use these in the agenda, you can add them to this
18158 list and agenda building will be a bit faster.
18159 The value is a list, with zero or more of the symbols `effort', `appt',
18160 `stats' or `category'."
18161 :type '(set :greedy t
18162 (const effort)
18163 (const appt)
18164 (const stats)
18165 (const category))
18166 :version "26.1"
18167 :package-version '(Org . "8.3")
18168 :group 'org-agenda)
18170 ;;;; Files
18172 (defun org-save-all-org-buffers ()
18173 "Save all Org buffers without user confirmation."
18174 (interactive)
18175 (message "Saving all Org buffers...")
18176 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18177 (when (featurep 'org-id) (org-id-locations-save))
18178 (message "Saving all Org buffers... done"))
18180 (defun org-revert-all-org-buffers ()
18181 "Revert all Org buffers.
18182 Prompt for confirmation when there are unsaved changes.
18183 Be sure you know what you are doing before letting this function
18184 overwrite your changes.
18186 This function is useful in a setup where one tracks org files
18187 with a version control system, to revert on one machine after pulling
18188 changes from another. I believe the procedure must be like this:
18190 1. M-x org-save-all-org-buffers
18191 2. Pull changes from the other machine, resolve conflicts
18192 3. M-x org-revert-all-org-buffers"
18193 (interactive)
18194 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18195 (user-error "Abort"))
18196 (save-excursion
18197 (save-window-excursion
18198 (dolist (b (buffer-list))
18199 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18200 (with-current-buffer b buffer-file-name))
18201 (pop-to-buffer-same-window b)
18202 (revert-buffer t 'no-confirm)))
18203 (when (and (featurep 'org-id) org-id-track-globally)
18204 (org-id-locations-load)))))
18206 ;;;; Agenda files
18208 ;;;###autoload
18209 (defun org-switchb (&optional arg)
18210 "Switch between Org buffers.
18212 With `\\[universal-argument]' prefix, restrict available buffers to files.
18214 With `\\[universal-argument] \\[universal-argument]' \
18215 prefix, restrict available buffers to agenda files."
18216 (interactive "P")
18217 (let ((blist (org-buffer-list
18218 (cond ((equal arg '(4)) 'files)
18219 ((equal arg '(16)) 'agenda)))))
18220 (pop-to-buffer-same-window
18221 (completing-read "Org buffer: "
18222 (mapcar #'list (mapcar #'buffer-name blist))
18223 nil t))))
18225 (defun org-buffer-list (&optional predicate exclude-tmp)
18226 "Return a list of Org buffers.
18227 PREDICATE can be `export', `files' or `agenda'.
18229 export restrict the list to Export buffers.
18230 files restrict the list to buffers visiting Org files.
18231 agenda restrict the list to buffers visiting agenda files.
18233 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18234 (let* ((bfn nil)
18235 (agenda-files (and (eq predicate 'agenda)
18236 (mapcar 'file-truename (org-agenda-files t))))
18237 (filter
18238 (cond
18239 ((eq predicate 'files)
18240 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18241 ((eq predicate 'export)
18242 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18243 ((eq predicate 'agenda)
18244 (lambda (b)
18245 (with-current-buffer b
18246 (and (derived-mode-p 'org-mode)
18247 (setq bfn (buffer-file-name b))
18248 (member (file-truename bfn) agenda-files)))))
18249 (t (lambda (b) (with-current-buffer b
18250 (or (derived-mode-p 'org-mode)
18251 (string-match "\\*Org .*Export"
18252 (buffer-name b)))))))))
18253 (delq nil
18254 (mapcar
18255 (lambda(b)
18256 (if (and (funcall filter b)
18257 (or (not exclude-tmp)
18258 (not (string-match "tmp" (buffer-name b)))))
18260 nil))
18261 (buffer-list)))))
18263 (defun org-agenda-files (&optional unrestricted archives)
18264 "Get the list of agenda files.
18265 Optional UNRESTRICTED means return the full list even if a restriction
18266 is currently in place.
18267 When ARCHIVES is t, include all archive files that are really being
18268 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18269 `org-agenda-archives-mode' is t."
18270 (let ((files
18271 (cond
18272 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18273 ((stringp org-agenda-files) (org-read-agenda-file-list))
18274 ((listp org-agenda-files) org-agenda-files)
18275 (t (error "Invalid value of `org-agenda-files'")))))
18276 (setq files (apply 'append
18277 (mapcar (lambda (f)
18278 (if (file-directory-p f)
18279 (directory-files
18280 f t org-agenda-file-regexp)
18281 (list f)))
18282 files)))
18283 (when org-agenda-skip-unavailable-files
18284 (setq files (delq nil
18285 (mapcar (function
18286 (lambda (file)
18287 (and (file-readable-p file) file)))
18288 files))))
18289 (when (or (eq archives t)
18290 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18291 (setq files (org-add-archive-files files)))
18292 files))
18294 (defun org-agenda-file-p (&optional file)
18295 "Return non-nil, if FILE is an agenda file.
18296 If FILE is omitted, use the file associated with the current
18297 buffer."
18298 (let ((fname (or file (buffer-file-name))))
18299 (and fname
18300 (member (file-truename fname)
18301 (mapcar #'file-truename (org-agenda-files t))))))
18303 (defun org-edit-agenda-file-list ()
18304 "Edit the list of agenda files.
18305 Depending on setup, this either uses customize to edit the variable
18306 `org-agenda-files', or it visits the file that is holding the list. In the
18307 latter case, the buffer is set up in a way that saving it automatically kills
18308 the buffer and restores the previous window configuration."
18309 (interactive)
18310 (if (stringp org-agenda-files)
18311 (let ((cw (current-window-configuration)))
18312 (find-file org-agenda-files)
18313 (setq-local org-window-configuration cw)
18314 (add-hook 'after-save-hook
18315 (lambda ()
18316 (set-window-configuration
18317 (prog1 org-window-configuration
18318 (kill-buffer (current-buffer))))
18319 (org-install-agenda-files-menu)
18320 (message "New agenda file list installed"))
18321 nil 'local)
18322 (message "%s" (substitute-command-keys
18323 "Edit list and finish with \\[save-buffer]")))
18324 (customize-variable 'org-agenda-files)))
18326 (defun org-store-new-agenda-file-list (list)
18327 "Set new value for the agenda file list and save it correctly."
18328 (if (stringp org-agenda-files)
18329 (let ((fe (org-read-agenda-file-list t)) b u)
18330 (while (setq b (find-buffer-visiting org-agenda-files))
18331 (kill-buffer b))
18332 (with-temp-file org-agenda-files
18333 (insert
18334 (mapconcat
18335 (lambda (f) ;; Keep un-expanded entries.
18336 (if (setq u (assoc f fe))
18337 (cdr u)
18339 list "\n")
18340 "\n")))
18341 (let ((org-mode-hook nil) (org-inhibit-startup t)
18342 (org-insert-mode-line-in-empty-file nil))
18343 (setq org-agenda-files list)
18344 (customize-save-variable 'org-agenda-files org-agenda-files))))
18346 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18347 "Read the list of agenda files from a file.
18348 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18349 filenames, used by `org-store-new-agenda-file-list' to write back
18350 un-expanded file names."
18351 (when (file-directory-p org-agenda-files)
18352 (error "`org-agenda-files' cannot be a single directory"))
18353 (when (stringp org-agenda-files)
18354 (with-temp-buffer
18355 (insert-file-contents org-agenda-files)
18356 (mapcar
18357 (lambda (f)
18358 (let ((e (expand-file-name (substitute-in-file-name f)
18359 org-directory)))
18360 (if pair-with-expansion
18361 (cons e f)
18362 e)))
18363 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18365 ;;;###autoload
18366 (defun org-cycle-agenda-files ()
18367 "Cycle through the files in `org-agenda-files'.
18368 If the current buffer visits an agenda file, find the next one in the list.
18369 If the current buffer does not, find the first agenda file."
18370 (interactive)
18371 (let* ((fs (or (org-agenda-files t)
18372 (user-error "No agenda files")))
18373 (files (copy-sequence fs))
18374 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18375 file)
18376 (when tcf
18377 (while (and (setq file (pop files))
18378 (not (equal (file-truename file) tcf)))))
18379 (find-file (car (or files fs)))
18380 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18382 (defun org-agenda-file-to-front (&optional to-end)
18383 "Move/add the current file to the top of the agenda file list.
18384 If the file is not present in the list, it is added to the front. If it is
18385 present, it is moved there. With optional argument TO-END, add/move to the
18386 end of the list."
18387 (interactive "P")
18388 (let ((org-agenda-skip-unavailable-files nil)
18389 (file-alist (mapcar (lambda (x)
18390 (cons (file-truename x) x))
18391 (org-agenda-files t)))
18392 (ctf (file-truename
18393 (or buffer-file-name
18394 (user-error "Please save the current buffer to a file"))))
18395 x had)
18396 (setq x (assoc ctf file-alist) had x)
18398 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18399 (if to-end
18400 (setq file-alist (append (delq x file-alist) (list x)))
18401 (setq file-alist (cons x (delq x file-alist))))
18402 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18403 (org-install-agenda-files-menu)
18404 (message "File %s to %s of agenda file list"
18405 (if had "moved" "added") (if to-end "end" "front"))))
18407 (defun org-remove-file (&optional file)
18408 "Remove current file from the list of files in variable `org-agenda-files'.
18409 These are the files which are being checked for agenda entries.
18410 Optional argument FILE means use this file instead of the current."
18411 (interactive)
18412 (let* ((org-agenda-skip-unavailable-files nil)
18413 (file (or file buffer-file-name
18414 (user-error "Current buffer does not visit a file")))
18415 (true-file (file-truename file))
18416 (afile (abbreviate-file-name file))
18417 (files (delq nil (mapcar
18418 (lambda (x)
18419 (unless (equal true-file
18420 (file-truename x))
18422 (org-agenda-files t)))))
18423 (if (not (= (length files) (length (org-agenda-files t))))
18424 (progn
18425 (org-store-new-agenda-file-list files)
18426 (org-install-agenda-files-menu)
18427 (message "Removed from Org Agenda list: %s" afile))
18428 (message "File was not in list: %s (not removed)" afile))))
18430 (defun org-file-menu-entry (file)
18431 (vector file (list 'find-file file) t))
18433 (defun org-check-agenda-file (file)
18434 "Make sure FILE exists. If not, ask user what to do."
18435 (unless (file-exists-p file)
18436 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18437 (abbreviate-file-name file))
18438 (let ((r (downcase (read-char-exclusive))))
18439 (cond
18440 ((equal r ?r)
18441 (org-remove-file file)
18442 (throw 'nextfile t))
18443 (t (user-error "Abort"))))))
18445 (defun org-get-agenda-file-buffer (file)
18446 "Get an agenda buffer visiting FILE.
18447 If the buffer needs to be created, add it to the list of buffers
18448 which might be released later."
18449 (let ((buf (org-find-base-buffer-visiting file)))
18450 (if buf
18451 buf ; just return it
18452 ;; Make a new buffer and remember it
18453 (setq buf (find-file-noselect file))
18454 (when buf (push buf org-agenda-new-buffers))
18455 buf)))
18457 (defun org-release-buffers (blist)
18458 "Release all buffers in list, asking the user for confirmation when needed.
18459 When a buffer is unmodified, it is just killed. When modified, it is saved
18460 \(if the user agrees) and then killed."
18461 (let (file)
18462 (dolist (buf blist)
18463 (setq file (buffer-file-name buf))
18464 (when (and (buffer-modified-p buf)
18465 file
18466 (y-or-n-p (format "Save file %s? " file)))
18467 (with-current-buffer buf (save-buffer)))
18468 (kill-buffer buf))))
18470 (defun org-agenda-prepare-buffers (files)
18471 "Create buffers for all agenda files, protect archived trees and comments."
18472 (interactive)
18473 (let ((pa '(:org-archived t))
18474 (pc '(:org-comment t))
18475 (pall '(:org-archived t :org-comment t))
18476 (inhibit-read-only t)
18477 (org-inhibit-startup org-agenda-inhibit-startup)
18478 (rea (concat ":" org-archive-tag ":"))
18479 re pos)
18480 (setq org-tag-alist-for-agenda nil
18481 org-tag-groups-alist-for-agenda nil)
18482 (save-excursion
18483 (save-restriction
18484 (dolist (file files)
18485 (catch 'nextfile
18486 (if (bufferp file)
18487 (set-buffer file)
18488 (org-check-agenda-file file)
18489 (set-buffer (org-get-agenda-file-buffer file)))
18490 (widen)
18491 (org-set-regexps-and-options 'tags-only)
18492 (setq pos (point))
18493 (or (memq 'category org-agenda-ignore-properties)
18494 (org-refresh-category-properties))
18495 (or (memq 'stats org-agenda-ignore-properties)
18496 (org-refresh-stats-properties))
18497 (or (memq 'effort org-agenda-ignore-properties)
18498 (org-refresh-effort-properties))
18499 (or (memq 'appt org-agenda-ignore-properties)
18500 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18501 (setq org-todo-keywords-for-agenda
18502 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18503 (setq org-done-keywords-for-agenda
18504 (append org-done-keywords-for-agenda org-done-keywords))
18505 (setq org-todo-keyword-alist-for-agenda
18506 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18507 (setq org-tag-alist-for-agenda
18508 (org-uniquify
18509 (append org-tag-alist-for-agenda
18510 org-current-tag-alist)))
18511 ;; Merge current file's tag groups into global
18512 ;; `org-tag-groups-alist-for-agenda'.
18513 (when org-group-tags
18514 (dolist (alist org-tag-groups-alist)
18515 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18516 (if old
18517 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18518 (push alist org-tag-groups-alist-for-agenda)))))
18519 (org-with-silent-modifications
18520 (save-excursion
18521 (remove-text-properties (point-min) (point-max) pall)
18522 (when org-agenda-skip-archived-trees
18523 (goto-char (point-min))
18524 (while (re-search-forward rea nil t)
18525 (when (org-at-heading-p t)
18526 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18527 (goto-char (point-min))
18528 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18529 (while (re-search-forward re nil t)
18530 (when (save-match-data (org-in-commented-heading-p t))
18531 (add-text-properties
18532 (match-beginning 0) (org-end-of-subtree t) pc)))))
18533 (goto-char pos)))))
18534 (setq org-todo-keywords-for-agenda
18535 (org-uniquify org-todo-keywords-for-agenda))
18536 (setq org-todo-keyword-alist-for-agenda
18537 (org-uniquify org-todo-keyword-alist-for-agenda))))
18540 ;;;; CDLaTeX minor mode
18542 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18543 "Keymap for the minor `org-cdlatex-mode'.")
18545 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18546 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18547 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18548 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18549 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18551 (defvar org-cdlatex-texmathp-advice-is-done nil
18552 "Flag remembering if we have applied the advice to texmathp already.")
18554 (define-minor-mode org-cdlatex-mode
18555 "Toggle the minor `org-cdlatex-mode'.
18556 This mode supports entering LaTeX environment and math in LaTeX fragments
18557 in Org mode.
18558 \\{org-cdlatex-mode-map}"
18559 nil " OCDL" nil
18560 (when org-cdlatex-mode
18561 (require 'cdlatex)
18562 (run-hooks 'cdlatex-mode-hook)
18563 (cdlatex-compute-tables))
18564 (unless org-cdlatex-texmathp-advice-is-done
18565 (setq org-cdlatex-texmathp-advice-is-done t)
18566 (defadvice texmathp (around org-math-always-on activate)
18567 "Always return t in Org buffers.
18568 This is because we want to insert math symbols without dollars even outside
18569 the LaTeX math segments. If Org mode thinks that point is actually inside
18570 an embedded LaTeX fragment, let `texmathp' do its job.
18571 `\\[org-cdlatex-mode-map]'"
18572 (interactive)
18573 (let (p)
18574 (cond
18575 ((not (derived-mode-p 'org-mode)) ad-do-it)
18576 ((eq this-command 'cdlatex-math-symbol)
18577 (setq ad-return-value t
18578 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18580 (let ((p (org-inside-LaTeX-fragment-p)))
18581 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18582 (setq ad-return-value t
18583 texmathp-why '("Org mode embedded math" . 0))
18584 (when p ad-do-it)))))))))
18586 (defun turn-on-org-cdlatex ()
18587 "Unconditionally turn on `org-cdlatex-mode'."
18588 (org-cdlatex-mode 1))
18590 (defun org-try-cdlatex-tab ()
18591 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18592 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18593 - inside a LaTeX fragment, or
18594 - after the first word in a line, where an abbreviation expansion could
18595 insert a LaTeX environment."
18596 (when org-cdlatex-mode
18597 (cond
18598 ;; Before any word on the line: No expansion possible.
18599 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18600 ;; Just after first word on the line: Expand it. Make sure it
18601 ;; cannot happen on headlines, though.
18602 ((save-excursion
18603 (skip-chars-backward "a-zA-Z0-9*")
18604 (skip-chars-backward " \t")
18605 (and (bolp) (not (org-at-heading-p))))
18606 (cdlatex-tab) t)
18607 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18609 (defun org-cdlatex-underscore-caret (&optional _arg)
18610 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18611 Revert to the normal definition outside of these fragments."
18612 (interactive "P")
18613 (if (org-inside-LaTeX-fragment-p)
18614 (call-interactively 'cdlatex-sub-superscript)
18615 (let (org-cdlatex-mode)
18616 (call-interactively (key-binding (vector last-input-event))))))
18618 (defun org-cdlatex-math-modify (&optional _arg)
18619 "Execute `cdlatex-math-modify' in LaTeX fragments.
18620 Revert to the normal definition outside of these fragments."
18621 (interactive "P")
18622 (if (org-inside-LaTeX-fragment-p)
18623 (call-interactively 'cdlatex-math-modify)
18624 (let (org-cdlatex-mode)
18625 (call-interactively (key-binding (vector last-input-event))))))
18627 (defun org-cdlatex-environment-indent (&optional environment item)
18628 "Execute `cdlatex-environment' and indent the inserted environment.
18630 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18632 The inserted environment is indented to current indentation
18633 unless point is at the beginning of the line, in which the
18634 environment remains unintended."
18635 (interactive)
18636 ;; cdlatex-environment always return nil. Therefore, capture output
18637 ;; first and determine if an environment was selected.
18638 (let* ((beg (point-marker))
18639 (end (copy-marker (point) t))
18640 (inserted (progn
18641 (ignore-errors (cdlatex-environment environment item))
18642 (< beg end)))
18643 ;; Figure out how many lines to move forward after the
18644 ;; environment has been inserted.
18645 (lines (when inserted
18646 (save-excursion
18647 (- (cl-loop while (< beg (point))
18648 with x = 0
18649 do (forward-line -1)
18650 (cl-incf x)
18651 finally return x)
18652 (if (progn (goto-char beg)
18653 (and (progn (skip-chars-forward " \t") (eolp))
18654 (progn (skip-chars-backward " \t") (bolp))))
18655 1 0)))))
18656 (env (org-trim (delete-and-extract-region beg end))))
18657 (when inserted
18658 ;; Get indentation of next line unless at column 0.
18659 (let ((ind (if (bolp) 0
18660 (save-excursion
18661 (org-return-indent)
18662 (prog1 (org-get-indentation)
18663 (when (progn (skip-chars-forward " \t") (eolp))
18664 (delete-region beg (point)))))))
18665 (bol (progn (skip-chars-backward " \t") (bolp))))
18666 ;; Insert a newline before environment unless at column zero
18667 ;; to "escape" the current line. Insert a newline if
18668 ;; something is one the same line as \end{ENVIRONMENT}.
18669 (insert
18670 (concat (unless bol "\n") env
18671 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18672 (unless (zerop ind)
18673 (save-excursion
18674 (goto-char beg)
18675 (while (< (point) end)
18676 (unless (eolp) (indent-line-to ind))
18677 (forward-line))))
18678 (goto-char beg)
18679 (forward-line lines)
18680 (indent-line-to ind)))
18681 (set-marker beg nil)
18682 (set-marker end nil)))
18685 ;;;; LaTeX fragments
18687 (defun org-inside-LaTeX-fragment-p ()
18688 "Test if point is inside a LaTeX fragment.
18689 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18690 sequence appearing also before point.
18691 Even though the matchers for math are configurable, this function assumes
18692 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18693 delimiters are skipped when they have been removed by customization.
18694 The return value is nil, or a cons cell with the delimiter and the
18695 position of this delimiter.
18697 This function does a reasonably good job, but can locally be fooled by
18698 for example currency specifications. For example it will assume being in
18699 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18700 fragments that are properly closed, but during editing, we have to live
18701 with the uncertainty caused by missing closing delimiters. This function
18702 looks only before point, not after."
18703 (catch 'exit
18704 (let ((pos (point))
18705 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18706 (lim (save-excursion (org-backward-paragraph) (point)))
18707 dd-on str (start 0) m re)
18708 (goto-char pos)
18709 (when dodollar
18710 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18711 re (nth 1 (assoc "$" org-latex-regexps)))
18712 (while (string-match re str start)
18713 (cond
18714 ((= (match-end 0) (length str))
18715 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18716 ((= (match-end 0) (- (length str) 5))
18717 (throw 'exit nil))
18718 (t (setq start (match-end 0))))))
18719 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18720 (goto-char pos)
18721 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18722 (and (match-beginning 2) (throw 'exit nil))
18723 ;; count $$
18724 (while (re-search-backward "\\$\\$" lim t)
18725 (setq dd-on (not dd-on)))
18726 (goto-char pos)
18727 (when dd-on (cons "$$" m))))))
18729 (defun org-inside-latex-macro-p ()
18730 "Is point inside a LaTeX macro or its arguments?"
18731 (save-match-data
18732 (org-in-regexp
18733 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18735 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18736 "Build an overlay between BEG and END using IMAGE file.
18737 Argument IMAGETYPE is the extension of the displayed image,
18738 as a string. It defaults to \"png\"."
18739 (let ((ov (make-overlay beg end))
18740 (imagetype (or (intern imagetype) 'png)))
18741 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18742 (overlay-put ov 'evaporate t)
18743 (overlay-put ov
18744 'modification-hooks
18745 (list (lambda (o _flag _beg _end &optional _l)
18746 (delete-overlay o))))
18747 (overlay-put ov
18748 'display
18749 (list 'image :type imagetype :file image :ascent 'center))))
18751 (defun org--list-latex-overlays (&optional beg end)
18752 "List all Org LaTeX overlays in current buffer.
18753 Limit to overlays between BEG and END when those are provided."
18754 (cl-remove-if-not
18755 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18756 (overlays-in (or beg (point-min)) (or end (point-max)))))
18758 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18759 "Remove all overlays with LaTeX fragment images in current buffer.
18760 When optional arguments BEG and END are non-nil, remove all
18761 overlays between them instead. Return a non-nil value when some
18762 overlays were removed, nil otherwise."
18763 (let ((overlays (org--list-latex-overlays beg end)))
18764 (mapc #'delete-overlay overlays)
18765 overlays))
18767 (defun org-toggle-latex-fragment (&optional arg)
18768 "Preview the LaTeX fragment at point, or all locally or globally.
18770 If the cursor is on a LaTeX fragment, create the image and overlay
18771 it over the source code, if there is none. Remove it otherwise.
18772 If there is no fragment at point, display all fragments in the
18773 current section.
18775 With prefix ARG, preview or clear image for all fragments in the
18776 current subtree or in the whole buffer when used before the first
18777 headline. With a prefix ARG `\\[universal-argument] \
18778 \\[universal-argument]' preview or clear images
18779 for all fragments in the buffer."
18780 (interactive "P")
18781 (when (display-graphic-p)
18782 (catch 'exit
18783 (save-excursion
18784 (let (beg end msg)
18785 (cond
18786 ((or (equal arg '(16))
18787 (and (equal arg '(4))
18788 (org-with-limited-levels (org-before-first-heading-p))))
18789 (if (org-remove-latex-fragment-image-overlays)
18790 (progn (message "LaTeX fragments images removed from buffer")
18791 (throw 'exit nil))
18792 (setq msg "Creating images for buffer...")))
18793 ((equal arg '(4))
18794 (org-with-limited-levels (org-back-to-heading t))
18795 (setq beg (point))
18796 (setq end (progn (org-end-of-subtree t) (point)))
18797 (if (org-remove-latex-fragment-image-overlays beg end)
18798 (progn
18799 (message "LaTeX fragment images removed from subtree")
18800 (throw 'exit nil))
18801 (setq msg "Creating images for subtree...")))
18802 ((let ((datum (org-element-context)))
18803 (when (memq (org-element-type datum)
18804 '(latex-environment latex-fragment))
18805 (setq beg (org-element-property :begin datum))
18806 (setq end (org-element-property :end datum))
18807 (if (org-remove-latex-fragment-image-overlays beg end)
18808 (progn (message "LaTeX fragment image removed")
18809 (throw 'exit nil))
18810 (setq msg "Creating image...")))))
18812 (org-with-limited-levels
18813 (setq beg (if (org-at-heading-p) (line-beginning-position)
18814 (outline-previous-heading)
18815 (point)))
18816 (setq end (progn (outline-next-heading) (point)))
18817 (if (org-remove-latex-fragment-image-overlays beg end)
18818 (progn
18819 (message "LaTeX fragment images removed from section")
18820 (throw 'exit nil))
18821 (setq msg "Creating images for section...")))))
18822 (let ((file (buffer-file-name (buffer-base-buffer))))
18823 (org-format-latex
18824 (concat org-preview-latex-image-directory "org-ltximg")
18825 beg end
18826 ;; Emacs cannot overlay images from remote hosts. Create
18827 ;; it in `temporary-file-directory' instead.
18828 (if (or (not file) (file-remote-p file))
18829 temporary-file-directory
18830 default-directory)
18831 'overlays msg 'forbuffer org-preview-latex-default-process))
18832 (message (concat msg "done")))))))
18834 (defun org-format-latex
18835 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18836 "Replace LaTeX fragments with links to an image.
18838 The function takes care of creating the replacement image.
18840 Only consider fragments between BEG and END when those are
18841 provided.
18843 When optional argument OVERLAYS is non-nil, display the image on
18844 top of the fragment instead of replacing it.
18846 PROCESSING-TYPE is the conversion method to use, as a symbol.
18848 Some of the options can be changed using the variable
18849 `org-format-latex-options', which see."
18850 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18851 (unless (eq processing-type 'verbatim)
18852 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18853 (cnt 0)
18854 checkdir-flag)
18855 (goto-char (or beg (point-min)))
18856 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18857 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18858 (overlay-recenter (or end (point-max))))
18859 (while (re-search-forward math-regexp end t)
18860 (unless (and overlays
18861 (eq (get-char-property (point) 'org-overlay-type)
18862 'org-latex-overlay))
18863 (let* ((context (org-element-context))
18864 (type (org-element-type context)))
18865 (when (memq type '(latex-environment latex-fragment))
18866 (let ((block-type (eq type 'latex-environment))
18867 (value (org-element-property :value context))
18868 (beg (org-element-property :begin context))
18869 (end (save-excursion
18870 (goto-char (org-element-property :end context))
18871 (skip-chars-backward " \r\t\n")
18872 (point))))
18873 (cond
18874 ((eq processing-type 'mathjax)
18875 ;; Prepare for MathJax processing.
18876 (if (not (string-match "\\`\\$\\$?" value))
18877 (goto-char end)
18878 (delete-region beg end)
18879 (if (string= (match-string 0 value) "$$")
18880 (insert "\\[" (substring value 2 -2) "\\]")
18881 (insert "\\(" (substring value 1 -1) "\\)"))))
18882 ((assq processing-type org-preview-latex-process-alist)
18883 ;; Process to an image.
18884 (cl-incf cnt)
18885 (goto-char beg)
18886 (let* ((processing-info
18887 (cdr (assq processing-type org-preview-latex-process-alist)))
18888 (face (face-at-point))
18889 ;; Get the colors from the face at point.
18891 (let ((color (plist-get org-format-latex-options
18892 :foreground)))
18893 (if (and forbuffer (eq color 'auto))
18894 (face-attribute face :foreground nil 'default)
18895 color)))
18897 (let ((color (plist-get org-format-latex-options
18898 :background)))
18899 (if (and forbuffer (eq color 'auto))
18900 (face-attribute face :background nil 'default)
18901 color)))
18902 (hash (sha1 (prin1-to-string
18903 (list org-format-latex-header
18904 org-latex-default-packages-alist
18905 org-latex-packages-alist
18906 org-format-latex-options
18907 forbuffer value fg bg))))
18908 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18909 (absprefix (expand-file-name prefix dir))
18910 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18911 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18912 (sep (and block-type "\n\n"))
18913 (link (concat sep "[[file:" linkfile "]]" sep))
18914 (options
18915 (org-combine-plists
18916 org-format-latex-options
18917 `(:foreground ,fg :background ,bg))))
18918 (when msg (message msg cnt))
18919 (unless checkdir-flag ; Ensure the directory exists.
18920 (setq checkdir-flag t)
18921 (let ((todir (file-name-directory absprefix)))
18922 (unless (file-directory-p todir)
18923 (make-directory todir t))))
18924 (unless (file-exists-p movefile)
18925 (org-create-formula-image
18926 value movefile options forbuffer processing-type))
18927 (if overlays
18928 (progn
18929 (dolist (o (overlays-in beg end))
18930 (when (eq (overlay-get o 'org-overlay-type)
18931 'org-latex-overlay)
18932 (delete-overlay o)))
18933 (org--format-latex-make-overlay beg end movefile imagetype)
18934 (goto-char end))
18935 (delete-region beg end)
18936 (insert
18937 (org-add-props link
18938 (list 'org-latex-src
18939 (replace-regexp-in-string "\"" "" value)
18940 'org-latex-src-embed-type
18941 (if block-type 'paragraph 'character)))))))
18942 ((eq processing-type 'mathml)
18943 ;; Process to MathML.
18944 (unless (org-format-latex-mathml-available-p)
18945 (user-error "LaTeX to MathML converter not configured"))
18946 (cl-incf cnt)
18947 (when msg (message msg cnt))
18948 (goto-char beg)
18949 (delete-region beg end)
18950 (insert (org-format-latex-as-mathml
18951 value block-type prefix dir)))
18953 (error "Unknown conversion process %s for LaTeX fragments"
18954 processing-type)))))))))))
18956 (defun org-create-math-formula (latex-frag &optional mathml-file)
18957 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18958 Use `org-latex-to-mathml-convert-command'. If the conversion is
18959 sucessful, return the portion between \"<math...> </math>\"
18960 elements otherwise return nil. When MATHML-FILE is specified,
18961 write the results in to that file. When invoked as an
18962 interactive command, prompt for LATEX-FRAG, with initial value
18963 set to the current active region and echo the results for user
18964 inspection."
18965 (interactive (list (let ((frag (when (org-region-active-p)
18966 (buffer-substring-no-properties
18967 (region-beginning) (region-end)))))
18968 (read-string "LaTeX Fragment: " frag nil frag))))
18969 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18970 (let* ((tmp-in-file
18971 (let ((file (file-relative-name
18972 (make-temp-name (expand-file-name "ltxmathml-in")))))
18973 (write-region latex-frag nil file)
18974 file))
18975 (tmp-out-file (file-relative-name
18976 (make-temp-name (expand-file-name "ltxmathml-out"))))
18977 (cmd (format-spec
18978 org-latex-to-mathml-convert-command
18979 `((?j . ,(and org-latex-to-mathml-jar-file
18980 (shell-quote-argument
18981 (expand-file-name
18982 org-latex-to-mathml-jar-file))))
18983 (?I . ,(shell-quote-argument tmp-in-file))
18984 (?i . ,latex-frag)
18985 (?o . ,(shell-quote-argument tmp-out-file)))))
18986 mathml shell-command-output)
18987 (when (called-interactively-p 'any)
18988 (unless (org-format-latex-mathml-available-p)
18989 (user-error "LaTeX to MathML converter not configured")))
18990 (message "Running %s" cmd)
18991 (setq shell-command-output (shell-command-to-string cmd))
18992 (setq mathml
18993 (when (file-readable-p tmp-out-file)
18994 (with-current-buffer (find-file-noselect tmp-out-file t)
18995 (goto-char (point-min))
18996 (when (re-search-forward
18997 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18998 (regexp-quote
18999 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19000 nil t)
19001 (prog1 (match-string 0) (kill-buffer))))))
19002 (cond
19003 (mathml
19004 (setq mathml
19005 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19006 (when mathml-file
19007 (write-region mathml nil mathml-file))
19008 (when (called-interactively-p 'any)
19009 (message mathml)))
19010 ((message "LaTeX to MathML conversion failed")
19011 (message shell-command-output)))
19012 (delete-file tmp-in-file)
19013 (when (file-exists-p tmp-out-file)
19014 (delete-file tmp-out-file))
19015 mathml))
19017 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19018 prefix &optional dir)
19019 "Use `org-create-math-formula' but check local cache first."
19020 (let* ((absprefix (expand-file-name prefix dir))
19021 (print-length nil) (print-level nil)
19022 (formula-id (concat
19023 "formula-"
19024 (sha1
19025 (prin1-to-string
19026 (list latex-frag
19027 org-latex-to-mathml-convert-command)))))
19028 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19029 (formula-cache-dir (file-name-directory formula-cache)))
19031 (unless (file-directory-p formula-cache-dir)
19032 (make-directory formula-cache-dir t))
19034 (unless (file-exists-p formula-cache)
19035 (org-create-math-formula latex-frag formula-cache))
19037 (if (file-exists-p formula-cache)
19038 ;; Successful conversion. Return the link to MathML file.
19039 (org-add-props
19040 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19041 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19042 'org-latex-src-embed-type (if latex-frag-type
19043 'paragraph 'character)))
19044 ;; Failed conversion. Return the LaTeX fragment verbatim
19045 latex-frag)))
19047 (defun org--get-display-dpi ()
19048 "Get the DPI of the display.
19049 The function assumes that the display has the same pixel width in
19050 the horizontal and vertical directions."
19051 (if (display-graphic-p)
19052 (round (/ (display-pixel-height)
19053 (/ (display-mm-height) 25.4)))
19054 (error "Attempt to calculate the dpi of a non-graphic display")))
19056 (defun org-create-formula-image
19057 (string tofile options buffer &optional processing-type)
19058 "Create an image from LaTeX source using external processes.
19060 The LaTeX STRING is saved to a temporary LaTeX file, then
19061 converted to an image file by process PROCESSING-TYPE defined in
19062 `org-preview-latex-process-alist'. A nil value defaults to
19063 `org-preview-latex-default-process'.
19065 The generated image file is eventually moved to TOFILE.
19067 The OPTIONS argument controls the size, foreground color and
19068 background color of the generated image.
19070 When BUFFER non-nil, this function is used for LaTeX previewing.
19071 Otherwise, it is used to deal with LaTeX snippets showed in
19072 a HTML file."
19073 (let* ((processing-type (or processing-type
19074 org-preview-latex-default-process))
19075 (processing-info
19076 (cdr (assq processing-type org-preview-latex-process-alist)))
19077 (programs (plist-get processing-info :programs))
19078 (error-message (or (plist-get processing-info :message) ""))
19079 (use-xcolor (plist-get processing-info :use-xcolor))
19080 (image-input-type (plist-get processing-info :image-input-type))
19081 (image-output-type (plist-get processing-info :image-output-type))
19082 (post-clean (or (plist-get processing-info :post-clean)
19083 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19084 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19085 (latex-header
19086 (or (plist-get processing-info :latex-header)
19087 (org-latex-make-preamble
19088 (org-export-get-environment (org-export-get-backend 'latex))
19089 org-format-latex-header
19090 'snippet)))
19091 (latex-compiler (plist-get processing-info :latex-compiler))
19092 (image-converter (plist-get processing-info :image-converter))
19093 (tmpdir temporary-file-directory)
19094 (texfilebase (make-temp-name
19095 (expand-file-name "orgtex" tmpdir)))
19096 (texfile (concat texfilebase ".tex"))
19097 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19098 '(1.0 . 1.0)))
19099 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19100 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19101 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19102 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19103 "Black"))
19104 (bg (or (plist-get options (if buffer :background :html-background))
19105 "Transparent"))
19106 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19107 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19108 (dolist (program programs)
19109 (org-check-external-command program error-message))
19110 (if use-xcolor
19111 (progn (if (eq fg 'default)
19112 (setq fg (org-latex-color :foreground))
19113 (setq fg (org-latex-color-format fg)))
19114 (if (eq bg 'default)
19115 (setq bg (org-latex-color :background))
19116 (setq bg (org-latex-color-format
19117 (if (string= bg "Transparent") "white" bg))))
19118 (with-temp-file texfile
19119 (insert latex-header)
19120 (insert "\n\\begin{document}\n"
19121 "\\definecolor{fg}{rgb}{" fg "}\n"
19122 "\\definecolor{bg}{rgb}{" bg "}\n"
19123 "\n\\pagecolor{bg}\n"
19124 "\n{\\color{fg}\n"
19125 string
19126 "\n}\n"
19127 "\n\\end{document}\n")))
19128 (if (eq fg 'default)
19129 (setq fg (org-dvipng-color :foreground))
19130 (unless (string= fg "Transparent")
19131 (setq fg (org-dvipng-color-format fg))))
19132 (if (eq bg 'default)
19133 (setq bg (org-dvipng-color :background))
19134 (unless (string= bg "Transparent")
19135 (setq bg (org-dvipng-color-format bg))))
19136 (with-temp-file texfile
19137 (insert latex-header)
19138 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19140 (let* ((err-msg (format "Please adjust `%s' part of \
19141 `org-preview-latex-process-alist'."
19142 processing-type))
19143 (image-input-file
19144 (org-compile-file
19145 texfile latex-compiler image-input-type err-msg log-buf))
19146 (image-output-file
19147 (org-compile-file
19148 image-input-file image-converter image-output-type err-msg log-buf
19149 `((?F . ,(shell-quote-argument fg))
19150 (?B . ,(shell-quote-argument bg))
19151 (?D . ,(shell-quote-argument (format "%s" dpi)))
19152 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19153 (copy-file image-output-file tofile 'replace)
19154 (dolist (e post-clean)
19155 (when (file-exists-p (concat texfilebase e))
19156 (delete-file (concat texfilebase e))))
19157 image-output-file)))
19159 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19160 "Fill a LaTeX header template TPL.
19161 In the template, the following place holders will be recognized:
19163 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19164 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19165 [PACKAGES] \\usepackage statements for PKG
19166 [NO-PACKAGES] do not include PKG
19167 [EXTRA] the string EXTRA
19168 [NO-EXTRA] do not include EXTRA
19170 For backward compatibility, if both the positive and the negative place
19171 holder is missing, the positive one (without the \"NO-\") will be
19172 assumed to be present at the end of the template.
19173 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19174 EXTRA is a string.
19175 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19176 (let (rpl (end ""))
19177 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19178 (setq rpl (if (or (match-end 1) (not def-pkg))
19179 "" (org-latex-packages-to-string def-pkg snippets-p t))
19180 tpl (replace-match rpl t t tpl))
19181 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19183 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19184 (setq rpl (if (or (match-end 1) (not pkg))
19185 "" (org-latex-packages-to-string pkg snippets-p t))
19186 tpl (replace-match rpl t t tpl))
19187 (when pkg (setq end
19188 (concat end "\n"
19189 (org-latex-packages-to-string pkg snippets-p)))))
19191 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19192 (setq rpl (if (or (match-end 1) (not extra))
19193 "" (concat extra "\n"))
19194 tpl (replace-match rpl t t tpl))
19195 (when (and extra (string-match "\\S-" extra))
19196 (setq end (concat end "\n" extra))))
19198 (if (string-match "\\S-" end)
19199 (concat tpl "\n" end)
19200 tpl)))
19202 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19203 "Turn an alist of packages into a string with the \\usepackage macros."
19204 (setq pkg (mapconcat (lambda(p)
19205 (cond
19206 ((stringp p) p)
19207 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19208 (format "%% Package %s omitted" (cadr p)))
19209 ((equal "" (car p))
19210 (format "\\usepackage{%s}" (cadr p)))
19212 (format "\\usepackage[%s]{%s}"
19213 (car p) (cadr p)))))
19215 "\n"))
19216 (if newline (concat pkg "\n") pkg))
19218 (defun org-dvipng-color (attr)
19219 "Return a RGB color specification for dvipng."
19220 (org-dvipng-color-format (face-attribute 'default attr nil)))
19222 (defun org-dvipng-color-format (color-name)
19223 "Convert COLOR-NAME to a RGB color value for dvipng."
19224 (apply #'format "rgb %s %s %s"
19225 (mapcar 'org-normalize-color
19226 (color-values color-name))))
19228 (defun org-latex-color (attr)
19229 "Return a RGB color for the LaTeX color package."
19230 (org-latex-color-format (face-attribute 'default attr nil)))
19232 (defun org-latex-color-format (color-name)
19233 "Convert COLOR-NAME to a RGB color value."
19234 (apply #'format "%s,%s,%s"
19235 (mapcar 'org-normalize-color
19236 (color-values color-name))))
19238 (defun org-normalize-color (value)
19239 "Return string to be used as color value for an RGB component."
19240 (format "%g" (/ value 65535.0)))
19244 ;; Image display
19246 (defvar-local org-inline-image-overlays nil)
19248 (defun org-toggle-inline-images (&optional include-linked)
19249 "Toggle the display of inline images.
19250 INCLUDE-LINKED is passed to `org-display-inline-images'."
19251 (interactive "P")
19252 (if org-inline-image-overlays
19253 (progn
19254 (org-remove-inline-images)
19255 (when (called-interactively-p 'interactive)
19256 (message "Inline image display turned off")))
19257 (org-display-inline-images include-linked)
19258 (when (called-interactively-p 'interactive)
19259 (message (if org-inline-image-overlays
19260 (format "%d images displayed inline"
19261 (length org-inline-image-overlays))
19262 "No images to display inline")))))
19264 (defun org-redisplay-inline-images ()
19265 "Refresh the display of inline images."
19266 (interactive)
19267 (if (not org-inline-image-overlays)
19268 (org-toggle-inline-images)
19269 (org-toggle-inline-images)
19270 (org-toggle-inline-images)))
19272 (defun org-display-inline-images (&optional include-linked refresh beg end)
19273 "Display inline images.
19275 An inline image is a link which follows either of these
19276 conventions:
19278 1. Its path is a file with an extension matching return value
19279 from `image-file-name-regexp' and it has no contents.
19281 2. Its description consists in a single link of the previous
19282 type.
19284 When optional argument INCLUDE-LINKED is non-nil, also links with
19285 a text description part will be inlined. This can be nice for
19286 a quick look at those images, but it does not reflect what
19287 exported files will look like.
19289 When optional argument REFRESH is non-nil, refresh existing
19290 images between BEG and END. This will create new image displays
19291 only if necessary. BEG and END default to the buffer
19292 boundaries."
19293 (interactive "P")
19294 (when (display-graphic-p)
19295 (unless refresh
19296 (org-remove-inline-images)
19297 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19298 (org-with-wide-buffer
19299 (goto-char (or beg (point-min)))
19300 (let* ((case-fold-search t)
19301 (file-extension-re (image-file-name-regexp))
19302 (link-abbrevs (mapcar #'car
19303 (append org-link-abbrev-alist-local
19304 org-link-abbrev-alist)))
19305 ;; Check absolute, relative file names and explicit
19306 ;; "file:" links. Also check link abbreviations since
19307 ;; some might expand to "file" links.
19308 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19309 (and link-abbrevs
19310 (format "\\|\\(?:%s:\\)"
19311 (regexp-opt link-abbrevs))))))
19312 (while (re-search-forward file-types-re end t)
19313 (let ((link (save-match-data (org-element-context))))
19314 ;; Check if we're at an inline image, i.e., an image file
19315 ;; link without a description (unless INCLUDE-LINKED is
19316 ;; non-nil).
19317 (when (and (equal "file" (org-element-property :type link))
19318 (or include-linked
19319 (null (org-element-contents link)))
19320 (string-match-p file-extension-re
19321 (org-element-property :path link)))
19322 (let ((file (expand-file-name
19323 (org-link-unescape
19324 (org-element-property :path link)))))
19325 (when (file-exists-p file)
19326 (let ((width
19327 ;; Apply `org-image-actual-width' specifications.
19328 (cond
19329 ((not (image-type-available-p 'imagemagick)) nil)
19330 ((eq org-image-actual-width t) nil)
19331 ((listp org-image-actual-width)
19333 ;; First try to find a width among
19334 ;; attributes associated to the paragraph
19335 ;; containing link.
19336 (let ((paragraph
19337 (let ((e link))
19338 (while (and (setq e (org-element-property
19339 :parent e))
19340 (not (eq (org-element-type e)
19341 'paragraph))))
19342 e)))
19343 (when paragraph
19344 (save-excursion
19345 (goto-char (org-element-property :begin paragraph))
19346 (when
19347 (re-search-forward
19348 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19349 (org-element-property
19350 :post-affiliated paragraph)
19352 (string-to-number (match-string 1))))))
19353 ;; Otherwise, fall-back to provided number.
19354 (car org-image-actual-width)))
19355 ((numberp org-image-actual-width)
19356 org-image-actual-width)))
19357 (old (get-char-property-and-overlay
19358 (org-element-property :begin link)
19359 'org-image-overlay)))
19360 (if (and (car-safe old) refresh)
19361 (image-refresh (overlay-get (cdr old) 'display))
19362 (let ((image (create-image file
19363 (and width 'imagemagick)
19365 :width width)))
19366 (when image
19367 (let ((ov (make-overlay
19368 (org-element-property :begin link)
19369 (progn
19370 (goto-char
19371 (org-element-property :end link))
19372 (skip-chars-backward " \t")
19373 (point)))))
19374 (overlay-put ov 'display image)
19375 (overlay-put ov 'face 'default)
19376 (overlay-put ov 'org-image-overlay t)
19377 (overlay-put
19378 ov 'modification-hooks
19379 (list 'org-display-inline-remove-overlay))
19380 (push ov org-inline-image-overlays)))))))))))))))
19382 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19383 "Remove inline-display overlay if a corresponding region is modified."
19384 (let ((inhibit-modification-hooks t))
19385 (when (and ov after)
19386 (delete ov org-inline-image-overlays)
19387 (delete-overlay ov))))
19389 (defun org-remove-inline-images ()
19390 "Remove inline display of images."
19391 (interactive)
19392 (mapc #'delete-overlay org-inline-image-overlays)
19393 (setq org-inline-image-overlays nil))
19395 ;;;; Key bindings
19397 (defun org-remap (map &rest commands)
19398 "In MAP, remap the functions given in COMMANDS.
19399 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19400 (let (new old)
19401 (while commands
19402 (setq old (pop commands) new (pop commands))
19403 (org-defkey map (vector 'remap old) new))))
19405 ;; Outline functions from `outline-mode-prefix-map'
19406 ;; that can be remapped in Org:
19407 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19408 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19409 (define-key org-mode-map [remap outline-forward-same-level]
19410 'org-forward-heading-same-level)
19411 (define-key org-mode-map [remap outline-backward-same-level]
19412 'org-backward-heading-same-level)
19413 (define-key org-mode-map [remap outline-show-branches]
19414 'org-kill-note-or-show-branches)
19415 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19416 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19417 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19418 (define-key org-mode-map [remap outline-next-visible-heading]
19419 'org-next-visible-heading)
19420 (define-key org-mode-map [remap outline-previous-visible-heading]
19421 'org-previous-visible-heading)
19422 (define-key org-mode-map [remap show-children] 'org-show-children)
19424 ;; Outline functions from `outline-mode-prefix-map' that can not
19425 ;; be remapped in Org:
19427 ;; - the column "key binding" shows whether the Outline function is still
19428 ;; available in Org mode on the same key that it has been bound to in
19429 ;; Outline mode:
19430 ;; - "overridden": key used for a different functionality in Org mode
19431 ;; - else: key still bound to the same Outline function in Org mode
19433 ;; | Outline function | key binding | Org replacement |
19434 ;; |------------------------------------+-------------+--------------------------|
19435 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19436 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19437 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19438 ;; | `show-entry' | overridden | no replacement |
19439 ;; | `show-branches' | `C-c C-k' | still same function |
19440 ;; | `show-subtree' | overridden | visibility cycling |
19441 ;; | `show-all' | overridden | no replacement |
19442 ;; | `hide-subtree' | overridden | visibility cycling |
19443 ;; | `hide-body' | overridden | no replacement |
19444 ;; | `hide-entry' | overridden | visibility cycling |
19445 ;; | `hide-leaves' | overridden | no replacement |
19446 ;; | `hide-sublevels' | overridden | no replacement |
19447 ;; | `hide-other' | overridden | no replacement |
19449 ;; Make `C-c C-x' a prefix key
19450 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19452 ;; TAB key with modifiers
19453 (org-defkey org-mode-map "\C-i" 'org-cycle)
19454 (org-defkey org-mode-map [(tab)] 'org-cycle)
19455 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19456 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19458 ;; The following line is necessary under Suse GNU/Linux
19459 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19460 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19461 (define-key org-mode-map [backtab] 'org-shifttab)
19463 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19464 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19465 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19467 ;; Cursor keys with modifiers
19468 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19469 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19470 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19471 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19473 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19474 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19475 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19476 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19477 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19478 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19480 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19481 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19482 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19483 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19485 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19486 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19487 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19488 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19490 ;; Babel keys
19491 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19492 (dolist (pair org-babel-key-bindings)
19493 (define-key org-babel-map (car pair) (cdr pair)))
19495 ;;; Extra keys for tty access.
19496 ;; We only set them when really needed because otherwise the
19497 ;; menus don't show the simple keys
19499 (when (or org-use-extra-keys (not window-system))
19500 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19501 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19502 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19503 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19504 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19505 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19506 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19507 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19508 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19509 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19510 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19511 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19512 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19513 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19514 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19515 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19516 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19517 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19518 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19519 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19520 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19521 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19522 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19523 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19524 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19525 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19526 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19527 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19529 ;; All the other keys
19530 (org-remap org-mode-map
19531 'self-insert-command 'org-self-insert-command
19532 'delete-char 'org-delete-char
19533 'delete-backward-char 'org-delete-backward-char)
19534 (org-defkey org-mode-map "|" 'org-force-self-insert)
19536 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19537 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19538 (if (boundp 'narrow-map)
19539 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19540 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19541 (if (boundp 'narrow-map)
19542 (org-defkey narrow-map "b" 'org-narrow-to-block)
19543 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19544 (if (boundp 'narrow-map)
19545 (org-defkey narrow-map "e" 'org-narrow-to-element)
19546 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19547 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19548 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19549 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19550 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19551 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19552 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19553 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19554 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19555 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19556 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19557 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19558 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19559 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19560 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19561 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19562 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19563 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19564 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19565 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19566 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19567 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19568 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19569 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19570 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19571 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19572 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19573 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19574 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19575 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19576 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19577 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19578 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19579 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19580 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19581 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19582 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19583 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19584 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19585 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19586 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19587 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19588 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19589 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19590 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19591 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19592 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19593 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19594 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19595 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19596 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19597 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19598 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19599 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19600 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19601 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19602 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19603 (org-defkey org-mode-map "\C-c^" 'org-sort)
19604 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19605 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19606 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19607 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19608 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19609 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19610 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19611 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19612 (org-defkey org-mode-map "\C-m" 'org-return)
19613 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19614 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19615 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19616 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19617 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19618 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19619 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19620 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19621 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19622 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19623 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19624 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19625 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19626 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19627 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19628 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19629 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19630 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19631 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19632 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19633 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19634 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19635 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19636 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19637 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19639 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19640 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19641 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19643 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19644 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19645 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19646 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19647 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19648 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19649 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19650 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19651 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19652 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19653 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19654 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19655 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19656 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19657 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19658 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19659 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19660 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19661 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19662 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19663 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19664 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19666 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19667 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19668 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19669 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19670 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19672 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19674 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19676 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19677 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19679 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19682 (defconst org-speed-commands-default
19684 ("Outline Navigation")
19685 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19686 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19687 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19688 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19689 ("F" . org-next-block)
19690 ("B" . org-previous-block)
19691 ("u" . (org-speed-move-safe 'outline-up-heading))
19692 ("j" . org-goto)
19693 ("g" . (org-refile t))
19694 ("Outline Visibility")
19695 ("c" . org-cycle)
19696 ("C" . org-shifttab)
19697 (" " . org-display-outline-path)
19698 ("s" . org-narrow-to-subtree)
19699 ("=" . org-columns)
19700 ("Outline Structure Editing")
19701 ("U" . org-metaup)
19702 ("D" . org-metadown)
19703 ("r" . org-metaright)
19704 ("l" . org-metaleft)
19705 ("R" . org-shiftmetaright)
19706 ("L" . org-shiftmetaleft)
19707 ("i" . (progn (forward-char 1) (call-interactively
19708 'org-insert-heading-respect-content)))
19709 ("^" . org-sort)
19710 ("w" . org-refile)
19711 ("a" . org-archive-subtree-default-with-confirmation)
19712 ("@" . org-mark-subtree)
19713 ("#" . org-toggle-comment)
19714 ("Clock Commands")
19715 ("I" . org-clock-in)
19716 ("O" . org-clock-out)
19717 ("Meta Data Editing")
19718 ("t" . org-todo)
19719 ("," . (org-priority))
19720 ("0" . (org-priority ?\ ))
19721 ("1" . (org-priority ?A))
19722 ("2" . (org-priority ?B))
19723 ("3" . (org-priority ?C))
19724 (":" . org-set-tags-command)
19725 ("e" . org-set-effort)
19726 ("E" . org-inc-effort)
19727 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19728 (org-entry-put (point) "APPT_WARNTIME" m)))
19729 ("Agenda Views etc")
19730 ("v" . org-agenda)
19731 ("/" . org-sparse-tree)
19732 ("Misc")
19733 ("o" . org-open-at-point)
19734 ("?" . org-speed-command-help)
19735 ("<" . (org-agenda-set-restriction-lock 'subtree))
19736 (">" . (org-agenda-remove-restriction-lock))
19738 "The default speed commands.")
19740 (defun org-print-speed-command (e)
19741 (if (> (length (car e)) 1)
19742 (progn
19743 (princ "\n")
19744 (princ (car e))
19745 (princ "\n")
19746 (princ (make-string (length (car e)) ?-))
19747 (princ "\n"))
19748 (princ (car e))
19749 (princ " ")
19750 (if (symbolp (cdr e))
19751 (princ (symbol-name (cdr e)))
19752 (prin1 (cdr e)))
19753 (princ "\n")))
19755 (defun org-speed-command-help ()
19756 "Show the available speed commands."
19757 (interactive)
19758 (if (not org-use-speed-commands)
19759 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19760 (with-output-to-temp-buffer "*Help*"
19761 (princ "User-defined Speed commands\n===========================\n")
19762 (mapc #'org-print-speed-command org-speed-commands-user)
19763 (princ "\n")
19764 (princ "Built-in Speed commands\n=======================\n")
19765 (mapc #'org-print-speed-command org-speed-commands-default))
19766 (with-current-buffer "*Help*"
19767 (setq truncate-lines t))))
19769 (defun org-speed-move-safe (cmd)
19770 "Execute CMD, but make sure that the cursor always ends up in a headline.
19771 If not, return to the original position and throw an error."
19772 (interactive)
19773 (let ((pos (point)))
19774 (call-interactively cmd)
19775 (unless (and (bolp) (org-at-heading-p))
19776 (goto-char pos)
19777 (error "Boundary reached while executing %s" cmd))))
19779 (defvar org-self-insert-command-undo-counter 0)
19781 (defvar org-table-auto-blank-field) ; defined in org-table.el
19782 (defvar org-speed-command nil)
19784 (defun org-speed-command-activate (keys)
19785 "Hook for activating single-letter speed commands.
19786 `org-speed-commands-default' specifies a minimal command set.
19787 Use `org-speed-commands-user' for further customization."
19788 (when (or (and (bolp) (looking-at org-outline-regexp))
19789 (and (functionp org-use-speed-commands)
19790 (funcall org-use-speed-commands)))
19791 (cdr (assoc keys (append org-speed-commands-user
19792 org-speed-commands-default)))))
19794 (defun org-babel-speed-command-activate (keys)
19795 "Hook for activating single-letter code block commands."
19796 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19797 (cdr (assoc keys org-babel-key-bindings))))
19799 (defcustom org-speed-command-hook
19800 '(org-speed-command-activate org-babel-speed-command-activate)
19801 "Hook for activating speed commands at strategic locations.
19802 Hook functions are called in sequence until a valid handler is
19803 found.
19805 Each hook takes a single argument, a user-pressed command key
19806 which is also a `self-insert-command' from the global map.
19808 Within the hook, examine the cursor position and the command key
19809 and return nil or a valid handler as appropriate. Handler could
19810 be one of an interactive command, a function, or a form.
19812 Set `org-use-speed-commands' to non-nil value to enable this
19813 hook. The default setting is `org-speed-command-activate'."
19814 :group 'org-structure
19815 :version "24.1"
19816 :type 'hook)
19818 (defun org-self-insert-command (N)
19819 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19820 If the cursor is in a table looking at whitespace, the whitespace is
19821 overwritten, and the table is not marked as requiring realignment."
19822 (interactive "p")
19823 (org-check-before-invisible-edit 'insert)
19824 (cond
19825 ((and org-use-speed-commands
19826 (let ((kv (this-command-keys-vector)))
19827 (setq org-speed-command
19828 (run-hook-with-args-until-success
19829 'org-speed-command-hook
19830 (make-string 1 (aref kv (1- (length kv))))))))
19831 (cond
19832 ((commandp org-speed-command)
19833 (setq this-command org-speed-command)
19834 (call-interactively org-speed-command))
19835 ((functionp org-speed-command)
19836 (funcall org-speed-command))
19837 ((and org-speed-command (listp org-speed-command))
19838 (eval org-speed-command))
19839 (t (let (org-use-speed-commands)
19840 (call-interactively 'org-self-insert-command)))))
19841 ((and
19842 (org-at-table-p)
19843 (eq N 1)
19844 (not (org-region-active-p))
19845 (progn
19846 ;; Check if we blank the field, and if that triggers align.
19847 (and (featurep 'org-table) org-table-auto-blank-field
19848 (memq last-command
19849 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19850 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19851 ;; Got extra space, this field does not determine
19852 ;; column width.
19853 (let (org-table-may-need-update) (org-table-blank-field))
19854 ;; No extra space, this field may determine column
19855 ;; width.
19856 (org-table-blank-field)))
19858 (looking-at "[^|\n]* \\( \\)|"))
19859 ;; There is room for insertion without re-aligning the table.
19860 (delete-region (match-beginning 1) (match-end 1))
19861 (self-insert-command N))
19863 (setq org-table-may-need-update t)
19864 (self-insert-command N)
19865 (org-fix-tags-on-the-fly)
19866 (when org-self-insert-cluster-for-undo
19867 (if (not (eq last-command 'org-self-insert-command))
19868 (setq org-self-insert-command-undo-counter 1)
19869 (if (>= org-self-insert-command-undo-counter 20)
19870 (setq org-self-insert-command-undo-counter 1)
19871 (and (> org-self-insert-command-undo-counter 0)
19872 buffer-undo-list (listp buffer-undo-list)
19873 (not (cadr buffer-undo-list)) ; remove nil entry
19874 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19875 (setq org-self-insert-command-undo-counter
19876 (1+ org-self-insert-command-undo-counter))))))))
19878 (defun org-check-before-invisible-edit (kind)
19879 "Check is editing if kind KIND would be dangerous with invisible text around.
19880 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19881 ;; First, try to get out of here as quickly as possible, to reduce overhead
19882 (when (and org-catch-invisible-edits
19883 (or (not (boundp 'visible-mode)) (not visible-mode))
19884 (or (get-char-property (point) 'invisible)
19885 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19886 ;; OK, we need to take a closer look. Do not consider
19887 ;; invisibility obtained through text properties (e.g., link
19888 ;; fontification), as it cannot be toggled.
19889 (let* ((invisible-at-point
19890 (pcase (get-char-property-and-overlay (point) 'invisible)
19891 (`(,_ . ,(and (pred overlayp) o)) o)))
19892 ;; Assume that point cannot land in the middle of an
19893 ;; overlay, or between two overlays.
19894 (invisible-before-point
19895 (and (not invisible-at-point)
19896 (not (bobp))
19897 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19898 (`(,_ . ,(and (pred overlayp) o)) o))))
19899 (border-and-ok-direction
19901 ;; Check if we are acting predictably before invisible
19902 ;; text.
19903 (and invisible-at-point
19904 (memq kind '(insert delete-backward)))
19905 ;; Check if we are acting predictably after invisible text
19906 ;; This works not well, and I have turned it off. It seems
19907 ;; better to always show and stop after invisible text.
19908 ;; (and (not invisible-at-point) invisible-before-point
19909 ;; (memq kind '(insert delete)))
19911 (when (or invisible-at-point invisible-before-point)
19912 (when (eq org-catch-invisible-edits 'error)
19913 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19914 (if (and org-custom-properties-overlays
19915 (y-or-n-p "Display invisible properties in this buffer? "))
19916 (org-toggle-custom-properties-visibility)
19917 ;; Make the area visible
19918 (save-excursion
19919 (when invisible-before-point
19920 (goto-char
19921 (previous-single-char-property-change (point) 'invisible)))
19922 ;; Remove whatever overlay is currently making yet-to-be
19923 ;; edited text invisible. Also remove nested invisibility
19924 ;; related overlays.
19925 (delete-overlay (or invisible-at-point invisible-before-point))
19926 (let ((origin (if invisible-at-point (point) (1- (point)))))
19927 (while (pcase (get-char-property-and-overlay origin 'invisible)
19928 (`(,_ . ,(and (pred overlayp) o))
19929 (delete-overlay o)
19930 t)))))
19931 (cond
19932 ((eq org-catch-invisible-edits 'show)
19933 ;; That's it, we do the edit after showing
19934 (message
19935 "Unfolding invisible region around point before editing")
19936 (sit-for 1))
19937 ((and (eq org-catch-invisible-edits 'smart)
19938 border-and-ok-direction)
19939 (message "Unfolding invisible region around point before editing"))
19941 ;; Don't do the edit, make the user repeat it in full visibility
19942 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19944 (defun org-fix-tags-on-the-fly ()
19945 "Align tags in headline at point.
19946 Unlike to `org-set-tags', it ignores region and sorting."
19947 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19948 (org-at-heading-p))
19949 (let ((org-ignore-region t)
19950 (org-tags-sort-function nil))
19951 (org-set-tags nil t))))
19953 (defun org-delete-backward-char (N)
19954 "Like `delete-backward-char', insert whitespace at field end in tables.
19955 When deleting backwards, in tables this function will insert whitespace in
19956 front of the next \"|\" separator, to keep the table aligned. The table will
19957 still be marked for re-alignment if the field did fill the entire column,
19958 because, in this case the deletion might narrow the column."
19959 (interactive "p")
19960 (save-match-data
19961 (org-check-before-invisible-edit 'delete-backward)
19962 (if (and (org-at-table-p)
19963 (eq N 1)
19964 (not (org-region-active-p))
19965 (string-match "|" (buffer-substring (point-at-bol) (point)))
19966 (looking-at ".*?|"))
19967 (let ((pos (point))
19968 (noalign (looking-at "[^|\n\r]* |"))
19969 (c org-table-may-need-update))
19970 (backward-delete-char N)
19971 (unless overwrite-mode
19972 (skip-chars-forward "^|")
19973 (insert " ")
19974 (goto-char (1- pos)))
19975 ;; noalign: if there were two spaces at the end, this field
19976 ;; does not determine the width of the column.
19977 (when noalign (setq org-table-may-need-update c)))
19978 (backward-delete-char N)
19979 (org-fix-tags-on-the-fly))))
19981 (defun org-delete-char (N)
19982 "Like `delete-char', but insert whitespace at field end in tables.
19983 When deleting characters, in tables this function will insert whitespace in
19984 front of the next \"|\" separator, to keep the table aligned. The table will
19985 still be marked for re-alignment if the field did fill the entire column,
19986 because, in this case the deletion might narrow the column."
19987 (interactive "p")
19988 (save-match-data
19989 (org-check-before-invisible-edit 'delete)
19990 (if (and (org-at-table-p)
19991 (not (bolp))
19992 (not (= (char-after) ?|))
19993 (eq N 1))
19994 (if (looking-at ".*?|")
19995 (let ((pos (point))
19996 (noalign (looking-at "[^|\n\r]* |"))
19997 (c org-table-may-need-update))
19998 (replace-match
19999 (concat (substring (match-string 0) 1 -1) " |") nil t)
20000 (goto-char pos)
20001 ;; noalign: if there were two spaces at the end, this field
20002 ;; does not determine the width of the column.
20003 (when noalign (setq org-table-may-need-update c)))
20004 (delete-char N))
20005 (delete-char N)
20006 (org-fix-tags-on-the-fly))))
20008 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20009 (put 'org-self-insert-command 'delete-selection
20010 (lambda ()
20011 (not (run-hook-with-args-until-success
20012 'self-insert-uses-region-functions))))
20013 (put 'orgtbl-self-insert-command 'delete-selection
20014 (lambda ()
20015 (not (run-hook-with-args-until-success
20016 'self-insert-uses-region-functions))))
20017 (put 'org-delete-char 'delete-selection 'supersede)
20018 (put 'org-delete-backward-char 'delete-selection 'supersede)
20019 (put 'org-yank 'delete-selection 'yank)
20021 ;; Make `flyspell-mode' delay after some commands
20022 (put 'org-self-insert-command 'flyspell-delayed t)
20023 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20024 (put 'org-delete-char 'flyspell-delayed t)
20025 (put 'org-delete-backward-char 'flyspell-delayed t)
20027 ;; Make pabbrev-mode expand after Org mode commands
20028 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20029 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20031 (defun org-transpose-words ()
20032 "Transpose words for Org.
20033 This uses the `org-mode-transpose-word-syntax-table' syntax
20034 table, which interprets characters in `org-emphasis-alist' as
20035 word constituents."
20036 (interactive)
20037 (with-syntax-table org-mode-transpose-word-syntax-table
20038 (call-interactively 'transpose-words)))
20039 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20041 (defvar org-ctrl-c-ctrl-c-hook nil
20042 "Hook for functions attaching themselves to `C-c C-c'.
20044 This can be used to add additional functionality to the C-c C-c
20045 key which executes context-dependent commands. This hook is run
20046 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20047 run after the last test.
20049 Each function will be called with no arguments. The function
20050 must check if the context is appropriate for it to act. If yes,
20051 it should do its thing and then return a non-nil value. If the
20052 context is wrong, just do nothing and return nil.")
20054 (defvar org-ctrl-c-ctrl-c-final-hook nil
20055 "Hook for functions attaching themselves to `C-c C-c'.
20057 This can be used to add additional functionality to the C-c C-c
20058 key which executes context-dependent commands. This hook is run
20059 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20060 before the first test.
20062 Each function will be called with no arguments. The function
20063 must check if the context is appropriate for it to act. If yes,
20064 it should do its thing and then return a non-nil value. If the
20065 context is wrong, just do nothing and return nil.")
20067 (defvar org-tab-first-hook nil
20068 "Hook for functions to attach themselves to TAB.
20069 See `org-ctrl-c-ctrl-c-hook' for more information.
20070 This hook runs as the first action when TAB is pressed, even before
20071 `org-cycle' messes around with the `outline-regexp' to cater for
20072 inline tasks and plain list item folding.
20073 If any function in this hook returns t, any other actions that
20074 would have been caused by TAB (such as table field motion or visibility
20075 cycling) will not occur.")
20077 (defvar org-tab-after-check-for-table-hook nil
20078 "Hook for functions to attach themselves to TAB.
20079 See `org-ctrl-c-ctrl-c-hook' for more information.
20080 This hook runs after it has been established that the cursor is not in a
20081 table, but before checking if the cursor is in a headline or if global cycling
20082 should be done.
20083 If any function in this hook returns t, not other actions like visibility
20084 cycling will be done.")
20086 (defvar org-tab-after-check-for-cycling-hook nil
20087 "Hook for functions to attach themselves to TAB.
20088 See `org-ctrl-c-ctrl-c-hook' for more information.
20089 This hook runs after it has been established that not table field motion and
20090 not visibility should be done because of current context. This is probably
20091 the place where a package like yasnippets can hook in.")
20093 (defvar org-tab-before-tab-emulation-hook nil
20094 "Hook for functions to attach themselves to TAB.
20095 See `org-ctrl-c-ctrl-c-hook' for more information.
20096 This hook runs after every other options for TAB have been exhausted, but
20097 before indentation and \t insertion takes place.")
20099 (defvar org-metaleft-hook nil
20100 "Hook for functions attaching themselves to `M-left'.
20101 See `org-ctrl-c-ctrl-c-hook' for more information.")
20102 (defvar org-metaright-hook nil
20103 "Hook for functions attaching themselves to `M-right'.
20104 See `org-ctrl-c-ctrl-c-hook' for more information.")
20105 (defvar org-metaup-hook nil
20106 "Hook for functions attaching themselves to `M-up'.
20107 See `org-ctrl-c-ctrl-c-hook' for more information.")
20108 (defvar org-metadown-hook nil
20109 "Hook for functions attaching themselves to `M-down'.
20110 See `org-ctrl-c-ctrl-c-hook' for more information.")
20111 (defvar org-shiftmetaleft-hook nil
20112 "Hook for functions attaching themselves to `M-S-left'.
20113 See `org-ctrl-c-ctrl-c-hook' for more information.")
20114 (defvar org-shiftmetaright-hook nil
20115 "Hook for functions attaching themselves to `M-S-right'.
20116 See `org-ctrl-c-ctrl-c-hook' for more information.")
20117 (defvar org-shiftmetaup-hook nil
20118 "Hook for functions attaching themselves to `M-S-up'.
20119 See `org-ctrl-c-ctrl-c-hook' for more information.")
20120 (defvar org-shiftmetadown-hook nil
20121 "Hook for functions attaching themselves to `M-S-down'.
20122 See `org-ctrl-c-ctrl-c-hook' for more information.")
20123 (defvar org-metareturn-hook nil
20124 "Hook for functions attaching themselves to `M-RET'.
20125 See `org-ctrl-c-ctrl-c-hook' for more information.")
20126 (defvar org-shiftup-hook nil
20127 "Hook for functions attaching themselves to `S-up'.
20128 See `org-ctrl-c-ctrl-c-hook' for more information.")
20129 (defvar org-shiftup-final-hook nil
20130 "Hook for functions attaching themselves to `S-up'.
20131 This one runs after all other options except shift-select have been excluded.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-shiftdown-hook nil
20134 "Hook for functions attaching themselves to `S-down'.
20135 See `org-ctrl-c-ctrl-c-hook' for more information.")
20136 (defvar org-shiftdown-final-hook nil
20137 "Hook for functions attaching themselves to `S-down'.
20138 This one runs after all other options except shift-select have been excluded.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftleft-hook nil
20141 "Hook for functions attaching themselves to `S-left'.
20142 See `org-ctrl-c-ctrl-c-hook' for more information.")
20143 (defvar org-shiftleft-final-hook nil
20144 "Hook for functions attaching themselves to `S-left'.
20145 This one runs after all other options except shift-select have been excluded.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.")
20147 (defvar org-shiftright-hook nil
20148 "Hook for functions attaching themselves to `S-right'.
20149 See `org-ctrl-c-ctrl-c-hook' for more information.")
20150 (defvar org-shiftright-final-hook nil
20151 "Hook for functions attaching themselves to `S-right'.
20152 This one runs after all other options except shift-select have been excluded.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defun org-modifier-cursor-error ()
20156 "Throw an error, a modified cursor command was applied in wrong context."
20157 (user-error "This command is active in special context like tables, headlines or items"))
20159 (defun org-shiftselect-error ()
20160 "Throw an error because Shift-Cursor command was applied in wrong context."
20161 (if (and (boundp 'shift-select-mode) shift-select-mode)
20162 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20163 (user-error "This command works only in special context like headlines or timestamps")))
20165 (defun org-call-for-shift-select (cmd)
20166 (let ((this-command-keys-shift-translated t))
20167 (call-interactively cmd)))
20169 (defun org-shifttab (&optional arg)
20170 "Global visibility cycling or move to previous table field.
20171 Call `org-table-previous-field' within a table.
20172 When ARG is nil, cycle globally through visibility states.
20173 When ARG is a numeric prefix, show contents of this level."
20174 (interactive "P")
20175 (cond
20176 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20177 ((integerp arg)
20178 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20179 (message "Content view to level: %d" arg)
20180 (org-content (prefix-numeric-value arg2))
20181 (org-cycle-show-empty-lines t)
20182 (setq org-cycle-global-status 'overview)))
20183 (t (call-interactively 'org-global-cycle))))
20185 (defun org-shiftmetaleft ()
20186 "Promote subtree or delete table column.
20187 Calls `org-promote-subtree', `org-outdent-item-tree', or
20188 `org-table-delete-column', depending on context. See the
20189 individual commands for more information."
20190 (interactive)
20191 (cond
20192 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20193 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20194 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20195 ((if (not (org-region-active-p)) (org-at-item-p)
20196 (save-excursion (goto-char (region-beginning))
20197 (org-at-item-p)))
20198 (call-interactively 'org-outdent-item-tree))
20199 (t (org-modifier-cursor-error))))
20201 (defun org-shiftmetaright ()
20202 "Demote subtree or insert table column.
20203 Calls `org-demote-subtree', `org-indent-item-tree', or
20204 `org-table-insert-column', depending on context. See the
20205 individual commands for more information."
20206 (interactive)
20207 (cond
20208 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20209 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20210 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20211 ((if (not (org-region-active-p)) (org-at-item-p)
20212 (save-excursion (goto-char (region-beginning))
20213 (org-at-item-p)))
20214 (call-interactively 'org-indent-item-tree))
20215 (t (org-modifier-cursor-error))))
20217 (defun org-shiftmetaup (&optional _arg)
20218 "Drag the line at point up.
20219 In a table, kill the current row.
20220 On a clock timestamp, update the value of the timestamp like `S-<up>'
20221 but also adjust the previous clocked item in the clock history.
20222 Everywhere else, drag the line at point up."
20223 (interactive "P")
20224 (cond
20225 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20226 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20227 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20228 (call-interactively 'org-timestamp-up)))
20229 (t (call-interactively 'org-drag-line-backward))))
20231 (defun org-shiftmetadown (&optional _arg)
20232 "Drag the line at point down.
20233 In a table, insert an empty row at the current line.
20234 On a clock timestamp, update the value of the timestamp like `S-<down>'
20235 but also adjust the previous clocked item in the clock history.
20236 Everywhere else, drag the line at point down."
20237 (interactive "P")
20238 (cond
20239 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20240 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20241 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20242 (call-interactively 'org-timestamp-down)))
20243 (t (call-interactively 'org-drag-line-forward))))
20245 (defsubst org-hidden-tree-error ()
20246 (user-error
20247 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20249 (defun org-metaleft (&optional _arg)
20250 "Promote heading, list item at point or move table column left.
20252 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20253 depending on context. With no specific context, calls the Emacs
20254 default `backward-word'. See the individual commands for more
20255 information.
20257 This function runs the hook `org-metaleft-hook' as a first step,
20258 and returns at first non-nil value."
20259 (interactive "P")
20260 (cond
20261 ((run-hook-with-args-until-success 'org-metaleft-hook))
20262 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20263 ((org-with-limited-levels
20264 (or (org-at-heading-p)
20265 (and (org-region-active-p)
20266 (save-excursion
20267 (goto-char (region-beginning))
20268 (org-at-heading-p)))))
20269 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20270 (call-interactively 'org-do-promote))
20271 ;; At an inline task.
20272 ((org-at-heading-p)
20273 (call-interactively 'org-inlinetask-promote))
20274 ((or (org-at-item-p)
20275 (and (org-region-active-p)
20276 (save-excursion
20277 (goto-char (region-beginning))
20278 (org-at-item-p))))
20279 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20280 (call-interactively 'org-outdent-item))
20281 (t (call-interactively 'backward-word))))
20283 (defun org-metaright (&optional _arg)
20284 "Demote heading, list item at point or move table column right.
20286 In front of a drawer or a block keyword, indent it correctly.
20288 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20289 `org-indent-drawer' or `org-indent-block' depending on context.
20290 With no specific context, calls the Emacs default `forward-word'.
20291 See the individual commands for more information.
20293 This function runs the hook `org-metaright-hook' as a first step,
20294 and returns at first non-nil value."
20295 (interactive "P")
20296 (cond
20297 ((run-hook-with-args-until-success 'org-metaright-hook))
20298 ((org-at-table-p) (call-interactively 'org-table-move-column))
20299 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20300 ((org-at-block-p) (call-interactively 'org-indent-block))
20301 ((org-with-limited-levels
20302 (or (org-at-heading-p)
20303 (and (org-region-active-p)
20304 (save-excursion
20305 (goto-char (region-beginning))
20306 (org-at-heading-p)))))
20307 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20308 (call-interactively 'org-do-demote))
20309 ;; At an inline task.
20310 ((org-at-heading-p)
20311 (call-interactively 'org-inlinetask-demote))
20312 ((or (org-at-item-p)
20313 (and (org-region-active-p)
20314 (save-excursion
20315 (goto-char (region-beginning))
20316 (org-at-item-p))))
20317 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20318 (call-interactively 'org-indent-item))
20319 (t (call-interactively 'forward-word))))
20321 (defun org-check-for-hidden (what)
20322 "Check if there are hidden headlines/items in the current visual line.
20323 WHAT can be either `headlines' or `items'. If the current line is
20324 an outline or item heading and it has a folded subtree below it,
20325 this function returns t, nil otherwise."
20326 (let ((re (cond
20327 ((eq what 'headlines) org-outline-regexp-bol)
20328 ((eq what 'items) (org-item-beginning-re))
20329 (t (error "This should not happen"))))
20330 beg end)
20331 (save-excursion
20332 (catch 'exit
20333 (unless (org-region-active-p)
20334 (setq beg (point-at-bol))
20335 (beginning-of-line 2)
20336 (while (and (not (eobp)) ;; this is like `next-line'
20337 (get-char-property (1- (point)) 'invisible))
20338 (beginning-of-line 2))
20339 (setq end (point))
20340 (goto-char beg)
20341 (goto-char (point-at-eol))
20342 (setq end (max end (point)))
20343 (while (re-search-forward re end t)
20344 (when (get-char-property (match-beginning 0) 'invisible)
20345 (throw 'exit t))))
20346 nil))))
20348 (defun org-metaup (&optional _arg)
20349 "Move subtree up or move table row up.
20350 Calls `org-move-subtree-up' or `org-table-move-row' or
20351 `org-move-item-up', depending on context. See the individual commands
20352 for more information."
20353 (interactive "P")
20354 (cond
20355 ((run-hook-with-args-until-success 'org-metaup-hook))
20356 ((org-region-active-p)
20357 (let* ((a (min (region-beginning) (region-end)))
20358 (b (1- (max (region-beginning) (region-end))))
20359 (c (save-excursion (goto-char a)
20360 (move-beginning-of-line 0)))
20361 (d (save-excursion (goto-char a)
20362 (move-end-of-line 0) (point))))
20363 (transpose-regions a b c d)
20364 (goto-char c)))
20365 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20366 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20367 ((org-at-item-p) (call-interactively 'org-move-item-up))
20368 (t (org-drag-element-backward))))
20370 (defun org-metadown (&optional _arg)
20371 "Move subtree down or move table row down.
20372 Calls `org-move-subtree-down' or `org-table-move-row' or
20373 `org-move-item-down', depending on context. See the individual
20374 commands for more information."
20375 (interactive "P")
20376 (cond
20377 ((run-hook-with-args-until-success 'org-metadown-hook))
20378 ((org-region-active-p)
20379 (let* ((a (min (region-beginning) (region-end)))
20380 (b (max (region-beginning) (region-end)))
20381 (c (save-excursion (goto-char b)
20382 (move-beginning-of-line 1)))
20383 (d (save-excursion (goto-char b)
20384 (move-end-of-line 1) (1+ (point)))))
20385 (transpose-regions a b c d)
20386 (goto-char d)))
20387 ((org-at-table-p) (call-interactively 'org-table-move-row))
20388 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20389 ((org-at-item-p) (call-interactively 'org-move-item-down))
20390 (t (org-drag-element-forward))))
20392 (defun org-shiftup (&optional arg)
20393 "Increase item in timestamp or increase priority of current headline.
20394 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20395 depending on context. See the individual commands for more information."
20396 (interactive "P")
20397 (cond
20398 ((run-hook-with-args-until-success 'org-shiftup-hook))
20399 ((and org-support-shift-select (org-region-active-p))
20400 (org-call-for-shift-select 'previous-line))
20401 ((org-at-timestamp-p 'lax)
20402 (call-interactively (if org-edit-timestamp-down-means-later
20403 'org-timestamp-down 'org-timestamp-up)))
20404 ((and (not (eq org-support-shift-select 'always))
20405 org-enable-priority-commands
20406 (org-at-heading-p))
20407 (call-interactively 'org-priority-up))
20408 ((and (not org-support-shift-select) (org-at-item-p))
20409 (call-interactively 'org-previous-item))
20410 ((org-clocktable-try-shift 'up arg))
20411 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20412 (org-support-shift-select
20413 (org-call-for-shift-select 'previous-line))
20414 (t (org-shiftselect-error))))
20416 (defun org-shiftdown (&optional arg)
20417 "Decrease item in timestamp or decrease priority of current headline.
20418 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20419 depending on context. See the individual commands for more information."
20420 (interactive "P")
20421 (cond
20422 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20423 ((and org-support-shift-select (org-region-active-p))
20424 (org-call-for-shift-select 'next-line))
20425 ((org-at-timestamp-p 'lax)
20426 (call-interactively (if org-edit-timestamp-down-means-later
20427 'org-timestamp-up 'org-timestamp-down)))
20428 ((and (not (eq org-support-shift-select 'always))
20429 org-enable-priority-commands
20430 (org-at-heading-p))
20431 (call-interactively 'org-priority-down))
20432 ((and (not org-support-shift-select) (org-at-item-p))
20433 (call-interactively 'org-next-item))
20434 ((org-clocktable-try-shift 'down arg))
20435 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20436 (org-support-shift-select
20437 (org-call-for-shift-select 'next-line))
20438 (t (org-shiftselect-error))))
20440 (defun org-shiftright (&optional arg)
20441 "Cycle the thing at point or in the current line, depending on context.
20442 Depending on context, this does one of the following:
20444 - switch a timestamp at point one day into the future
20445 - on a headline, switch to the next TODO keyword.
20446 - on an item, switch entire list to the next bullet type
20447 - on a property line, switch to the next allowed value
20448 - on a clocktable definition line, move time block into the future"
20449 (interactive "P")
20450 (cond
20451 ((run-hook-with-args-until-success 'org-shiftright-hook))
20452 ((and org-support-shift-select (org-region-active-p))
20453 (org-call-for-shift-select 'forward-char))
20454 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20455 ((and (not (eq org-support-shift-select 'always))
20456 (org-at-heading-p))
20457 (let ((org-inhibit-logging
20458 (not org-treat-S-cursor-todo-selection-as-state-change))
20459 (org-inhibit-blocking
20460 (not org-treat-S-cursor-todo-selection-as-state-change)))
20461 (org-call-with-arg 'org-todo 'right)))
20462 ((or (and org-support-shift-select
20463 (not (eq org-support-shift-select 'always))
20464 (org-at-item-bullet-p))
20465 (and (not org-support-shift-select) (org-at-item-p)))
20466 (org-call-with-arg 'org-cycle-list-bullet nil))
20467 ((and (not (eq org-support-shift-select 'always))
20468 (org-at-property-p))
20469 (call-interactively 'org-property-next-allowed-value))
20470 ((org-clocktable-try-shift 'right arg))
20471 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20472 (org-support-shift-select
20473 (org-call-for-shift-select 'forward-char))
20474 (t (org-shiftselect-error))))
20476 (defun org-shiftleft (&optional arg)
20477 "Cycle the thing at point or in the current line, depending on context.
20478 Depending on context, this does one of the following:
20480 - switch a timestamp at point one day into the past
20481 - on a headline, switch to the previous TODO keyword.
20482 - on an item, switch entire list to the previous bullet type
20483 - on a property line, switch to the previous allowed value
20484 - on a clocktable definition line, move time block into the past"
20485 (interactive "P")
20486 (cond
20487 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20488 ((and org-support-shift-select (org-region-active-p))
20489 (org-call-for-shift-select 'backward-char))
20490 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20491 ((and (not (eq org-support-shift-select 'always))
20492 (org-at-heading-p))
20493 (let ((org-inhibit-logging
20494 (not org-treat-S-cursor-todo-selection-as-state-change))
20495 (org-inhibit-blocking
20496 (not org-treat-S-cursor-todo-selection-as-state-change)))
20497 (org-call-with-arg 'org-todo 'left)))
20498 ((or (and org-support-shift-select
20499 (not (eq org-support-shift-select 'always))
20500 (org-at-item-bullet-p))
20501 (and (not org-support-shift-select) (org-at-item-p)))
20502 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20503 ((and (not (eq org-support-shift-select 'always))
20504 (org-at-property-p))
20505 (call-interactively 'org-property-previous-allowed-value))
20506 ((org-clocktable-try-shift 'left arg))
20507 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20508 (org-support-shift-select
20509 (org-call-for-shift-select 'backward-char))
20510 (t (org-shiftselect-error))))
20512 (defun org-shiftcontrolright ()
20513 "Switch to next TODO set."
20514 (interactive)
20515 (cond
20516 ((and org-support-shift-select (org-region-active-p))
20517 (org-call-for-shift-select 'forward-word))
20518 ((and (not (eq org-support-shift-select 'always))
20519 (org-at-heading-p))
20520 (org-call-with-arg 'org-todo 'nextset))
20521 (org-support-shift-select
20522 (org-call-for-shift-select 'forward-word))
20523 (t (org-shiftselect-error))))
20525 (defun org-shiftcontrolleft ()
20526 "Switch to previous TODO set."
20527 (interactive)
20528 (cond
20529 ((and org-support-shift-select (org-region-active-p))
20530 (org-call-for-shift-select 'backward-word))
20531 ((and (not (eq org-support-shift-select 'always))
20532 (org-at-heading-p))
20533 (org-call-with-arg 'org-todo 'previousset))
20534 (org-support-shift-select
20535 (org-call-for-shift-select 'backward-word))
20536 (t (org-shiftselect-error))))
20538 (defun org-shiftcontrolup (&optional n)
20539 "Change timestamps synchronously up in CLOCK log lines.
20540 Optional argument N tells to change by that many units."
20541 (interactive "P")
20542 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20543 (let (org-support-shift-select)
20544 (org-clock-timestamps-up n))
20545 (user-error "Not at a clock log")))
20547 (defun org-shiftcontroldown (&optional n)
20548 "Change timestamps synchronously down in CLOCK log lines.
20549 Optional argument N tells to change by that many units."
20550 (interactive "P")
20551 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20552 (let (org-support-shift-select)
20553 (org-clock-timestamps-down n))
20554 (user-error "Not at a clock log")))
20556 (defun org-increase-number-at-point (&optional inc)
20557 "Increment the number at point.
20558 With an optional prefix numeric argument INC, increment using
20559 this numeric value."
20560 (interactive "p")
20561 (if (not (number-at-point))
20562 (user-error "Not on a number")
20563 (unless inc (setq inc 1))
20564 (let ((pos (point))
20565 (beg (skip-chars-backward "-+^/*0-9eE."))
20566 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20567 (setq nap (buffer-substring-no-properties
20568 (+ pos beg) (+ pos beg end)))
20569 (delete-region (+ pos beg) (+ pos beg end))
20570 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20571 (when (org-at-table-p)
20572 (org-table-align)
20573 (org-table-end-of-field 1))))
20575 (defun org-decrease-number-at-point (&optional inc)
20576 "Decrement the number at point.
20577 With an optional prefix numeric argument INC, decrement using
20578 this numeric value."
20579 (interactive "p")
20580 (org-increase-number-at-point (- (or inc 1))))
20582 (defun org-ctrl-c-ret ()
20583 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20584 (interactive)
20585 (cond
20586 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20587 (t (call-interactively 'org-insert-heading))))
20589 (defun org-find-visible ()
20590 (let ((s (point)))
20591 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20592 (get-char-property s 'invisible)))
20594 (defun org-find-invisible ()
20595 (let ((s (point)))
20596 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20597 (not (get-char-property s 'invisible))))
20600 (defun org-copy-visible (beg end)
20601 "Copy the visible parts of the region."
20602 (interactive "r")
20603 (let ((result ""))
20604 (while (/= beg end)
20605 (when (get-char-property beg 'invisible)
20606 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20607 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20608 (setq result (concat result (buffer-substring beg next)))
20609 (setq beg next)))
20610 (kill-new result)))
20612 (defun org-copy-special ()
20613 "Copy region in table or copy current subtree.
20614 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20615 context. See the individual commands for more information."
20616 (interactive)
20617 (call-interactively
20618 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20620 (defun org-cut-special ()
20621 "Cut region in table or cut current subtree.
20622 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20623 context. See the individual commands for more information."
20624 (interactive)
20625 (call-interactively
20626 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20628 (defun org-paste-special (arg)
20629 "Paste rectangular region into table, or past subtree relative to level.
20630 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20631 See the individual commands for more information."
20632 (interactive "P")
20633 (if (org-at-table-p)
20634 (org-table-paste-rectangle)
20635 (org-paste-subtree arg)))
20637 (defun org-edit-special (&optional arg)
20638 "Call a special editor for the element at point.
20639 When at a table, call the formula editor with `org-table-edit-formulas'.
20640 When in a source code block, call `org-edit-src-code'.
20641 When in a fixed-width region, call `org-edit-fixed-width-region'.
20642 When in an export block, call `org-edit-export-block'.
20643 When in a LaTeX environment, call `org-edit-latex-environment'.
20644 When at an #+INCLUDE keyword, visit the included file.
20645 When at a footnote reference, call `org-edit-footnote-reference'
20646 On a link, call `ffap' to visit the link at point.
20647 Otherwise, return a user error."
20648 (interactive "P")
20649 (let ((element (org-element-at-point)))
20650 (barf-if-buffer-read-only)
20651 (pcase (org-element-type element)
20652 (`src-block
20653 (if (not arg) (org-edit-src-code)
20654 (let* ((info (org-babel-get-src-block-info))
20655 (lang (nth 0 info))
20656 (params (nth 2 info))
20657 (session (cdr (assq :session params))))
20658 (if (not session) (org-edit-src-code)
20659 ;; At a src-block with a session and function called with
20660 ;; an ARG: switch to the buffer related to the inferior
20661 ;; process.
20662 (switch-to-buffer
20663 (funcall (intern (concat "org-babel-prep-session:" lang))
20664 session params))))))
20665 (`keyword
20666 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20667 (org-open-link-from-string
20668 (format "[[%s]]"
20669 (expand-file-name
20670 (let ((value (org-element-property :value element)))
20671 (cond ((org-file-url-p value)
20672 (user-error "The file is specified as a URL, cannot be edited"))
20673 ((not (org-string-nw-p value))
20674 (user-error "No file to edit"))
20675 ((string-match "\\`\"\\(.*?\\)\"" value)
20676 (match-string 1 value))
20677 ((string-match "\\`[^ \t\"]\\S-*" value)
20678 (match-string 0 value))
20679 (t (user-error "No valid file specified")))))))
20680 (user-error "No special environment to edit here")))
20681 (`table
20682 (if (eq (org-element-property :type element) 'table.el)
20683 (org-edit-table.el)
20684 (call-interactively 'org-table-edit-formulas)))
20685 ;; Only Org tables contain `table-row' type elements.
20686 (`table-row (call-interactively 'org-table-edit-formulas))
20687 (`example-block (org-edit-src-code))
20688 (`export-block (org-edit-export-block))
20689 (`fixed-width (org-edit-fixed-width-region))
20690 (`latex-environment (org-edit-latex-environment))
20692 ;; No notable element at point. Though, we may be at a link or
20693 ;; a footnote reference, which are objects. Thus, scan deeper.
20694 (let ((context (org-element-context element)))
20695 (pcase (org-element-type context)
20696 (`footnote-reference (org-edit-footnote-reference))
20697 (`inline-src-block (org-edit-inline-src-code))
20698 (`link (call-interactively #'ffap))
20699 (_ (user-error "No special environment to edit here"))))))))
20701 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20702 (defun org-ctrl-c-ctrl-c (&optional arg)
20703 "Set tags in headline, or update according to changed information at point.
20705 This command does many different things, depending on context:
20707 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20708 this is what we do.
20710 - If the cursor is on a statistics cookie, update it.
20712 - If the cursor is in a headline, prompt for tags and insert them
20713 into the current line, aligned to `org-tags-column'. When called
20714 with prefix arg, realign all tags in the current buffer.
20716 - If the cursor is in one of the special #+KEYWORD lines, this
20717 triggers scanning the buffer for these lines and updating the
20718 information.
20720 - If the cursor is inside a table, realign the table. This command
20721 works even if the automatic table editor has been turned off.
20723 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20724 the entire table.
20726 - If the cursor is at a footnote reference or definition, jump to
20727 the corresponding definition or references, respectively.
20729 - If the cursor is a the beginning of a dynamic block, update it.
20731 - If the current buffer is a capture buffer, close note and file it.
20733 - If the cursor is on a <<<target>>>, update radio targets and
20734 corresponding links in this buffer.
20736 - If the cursor is on a numbered item in a plain list, renumber the
20737 ordered list.
20739 - If the cursor is on a checkbox, toggle it.
20741 - If the cursor is on a code block, evaluate it. The variable
20742 `org-confirm-babel-evaluate' can be used to control prompting
20743 before code block evaluation, by default every code block
20744 evaluation requires confirmation. Code block evaluation can be
20745 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20746 (interactive "P")
20747 (cond
20748 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20749 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20750 (org-remove-occur-highlights)
20751 (message "Temporary highlights/overlays removed from current buffer"))
20752 ((and (local-variable-p 'org-finish-function)
20753 (fboundp org-finish-function))
20754 (funcall org-finish-function))
20755 ((org-babel-hash-at-point))
20756 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20758 (let* ((context
20759 (org-element-lineage
20760 (org-element-context)
20761 ;; Limit to supported contexts.
20762 '(babel-call clock dynamic-block footnote-definition
20763 footnote-reference inline-babel-call inline-src-block
20764 inlinetask item keyword node-property paragraph
20765 plain-list planning property-drawer radio-target
20766 src-block statistics-cookie table table-cell table-row
20767 timestamp)
20769 (type (org-element-type context)))
20770 ;; For convenience: at the first line of a paragraph on the same
20771 ;; line as an item, apply function on that item instead.
20772 (when (eq type 'paragraph)
20773 (let ((parent (org-element-property :parent context)))
20774 (when (and (eq (org-element-type parent) 'item)
20775 (= (line-beginning-position)
20776 (org-element-property :begin parent)))
20777 (setq context parent)
20778 (setq type 'item))))
20779 ;; Act according to type of element or object at point.
20781 ;; Do nothing on a blank line, except if it is contained in
20782 ;; a src block. Hence, we first check if point is in such
20783 ;; a block and then if it is at a blank line.
20784 (pcase type
20785 ((or `inline-src-block `src-block)
20786 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20787 (org-babel-eval-wipe-error-buffer)
20788 (org-babel-execute-src-block
20789 current-prefix-arg (org-babel-get-src-block-info nil context))))
20790 ((guard (org-match-line "[ \t]*$"))
20791 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20792 (user-error
20793 (substitute-command-keys
20794 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20795 ((or `babel-call `inline-babel-call)
20796 (let ((info (org-babel-lob-get-info context)))
20797 (when info (org-babel-execute-src-block nil info))))
20798 (`clock (org-clock-update-time-maybe))
20799 (`dynamic-block
20800 (save-excursion
20801 (goto-char (org-element-property :post-affiliated context))
20802 (org-update-dblock)))
20803 (`footnote-definition
20804 (goto-char (org-element-property :post-affiliated context))
20805 (call-interactively 'org-footnote-action))
20806 (`footnote-reference (call-interactively #'org-footnote-action))
20807 ((or `headline `inlinetask)
20808 (save-excursion (goto-char (org-element-property :begin context))
20809 (call-interactively #'org-set-tags)))
20810 (`item
20811 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20812 ;; unconditionally, whereas `C-u' will toggle its presence.
20813 ;; Without a universal argument, if the item has a checkbox,
20814 ;; toggle it. Otherwise repair the list.
20815 (let* ((box (org-element-property :checkbox context))
20816 (struct (org-element-property :structure context))
20817 (old-struct (copy-tree struct))
20818 (parents (org-list-parents-alist struct))
20819 (prevs (org-list-prevs-alist struct))
20820 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20821 (org-list-set-checkbox
20822 (org-element-property :begin context) struct
20823 (cond ((equal arg '(16)) "[-]")
20824 ((and (not box) (equal arg '(4))) "[ ]")
20825 ((or (not box) (equal arg '(4))) nil)
20826 ((eq box 'on) "[ ]")
20827 (t "[X]")))
20828 ;; Mimic `org-list-write-struct' but with grabbing a return
20829 ;; value from `org-list-struct-fix-box'.
20830 (org-list-struct-fix-ind struct parents 2)
20831 (org-list-struct-fix-item-end struct)
20832 (org-list-struct-fix-bul struct prevs)
20833 (org-list-struct-fix-ind struct parents)
20834 (let ((block-item
20835 (org-list-struct-fix-box struct parents prevs orderedp)))
20836 (if (and box (equal struct old-struct))
20837 (if (equal arg '(16))
20838 (message "Checkboxes already reset")
20839 (user-error "Cannot toggle this checkbox: %s"
20840 (if (eq box 'on)
20841 "all subitems checked"
20842 "unchecked subitems")))
20843 (org-list-struct-apply-struct struct old-struct)
20844 (org-update-checkbox-count-maybe))
20845 (when block-item
20846 (message "Checkboxes were removed due to empty box at line %d"
20847 (org-current-line block-item))))))
20848 (`keyword
20849 (let ((org-inhibit-startup-visibility-stuff t)
20850 (org-startup-align-all-tables nil))
20851 (when (boundp 'org-table-coordinate-overlays)
20852 (mapc #'delete-overlay org-table-coordinate-overlays)
20853 (setq org-table-coordinate-overlays nil))
20854 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20855 (message "Local setup has been refreshed"))
20856 (`plain-list
20857 ;; At a plain list, with a double C-u argument, set
20858 ;; checkboxes of each item to "[-]", whereas a single one
20859 ;; will toggle their presence according to the state of the
20860 ;; first item in the list. Without an argument, repair the
20861 ;; list.
20862 (let* ((begin (org-element-property :contents-begin context))
20863 (beginm (move-marker (make-marker) begin))
20864 (struct (org-element-property :structure context))
20865 (old-struct (copy-tree struct))
20866 (first-box (save-excursion
20867 (goto-char begin)
20868 (looking-at org-list-full-item-re)
20869 (match-string-no-properties 3)))
20870 (new-box (cond ((equal arg '(16)) "[-]")
20871 ((equal arg '(4)) (unless first-box "[ ]"))
20872 ((equal first-box "[X]") "[ ]")
20873 (t "[X]"))))
20874 (cond
20875 (arg
20876 (dolist (pos
20877 (org-list-get-all-items
20878 begin struct (org-list-prevs-alist struct)))
20879 (org-list-set-checkbox pos struct new-box)))
20880 ((and first-box (eq (point) begin))
20881 ;; For convenience, when point is at bol on the first
20882 ;; item of the list and no argument is provided, simply
20883 ;; toggle checkbox of that item, if any.
20884 (org-list-set-checkbox begin struct new-box)))
20885 (org-list-write-struct
20886 struct (org-list-parents-alist struct) old-struct)
20887 (org-update-checkbox-count-maybe)
20888 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20889 ((or `property-drawer `node-property)
20890 (call-interactively #'org-property-action))
20891 (`radio-target
20892 (call-interactively #'org-update-radio-target-regexp))
20893 (`statistics-cookie
20894 (call-interactively #'org-update-statistics-cookies))
20895 ((or `table `table-cell `table-row)
20896 ;; At a table, recalculate every field and align it. Also
20897 ;; send the table if necessary. If the table has
20898 ;; a `table.el' type, just give up. At a table row or cell,
20899 ;; maybe recalculate line but always align table.
20900 (if (eq (org-element-property :type context) 'table.el)
20901 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20902 Use `\\[org-edit-special]' to edit table.el tables"))
20903 (if (or (eq type 'table)
20904 ;; Check if point is at a TBLFM line.
20905 (and (eq type 'table-row)
20906 (= (point) (org-element-property :end context))))
20907 (save-excursion
20908 (if (org-at-TBLFM-p)
20909 (progn (require 'org-table)
20910 (org-table-calc-current-TBLFM))
20911 (goto-char (org-element-property :contents-begin context))
20912 (org-call-with-arg 'org-table-recalculate (or arg t))
20913 (orgtbl-send-table 'maybe)))
20914 (org-table-maybe-eval-formula)
20915 (cond (arg (call-interactively #'org-table-recalculate))
20916 ((org-table-maybe-recalculate-line))
20917 (t (org-table-align))))))
20918 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20919 (org-timestamp-change 0 'day))
20920 ((and `nil (guard (org-at-heading-p)))
20921 ;; When point is on an unsupported object type, we can miss
20922 ;; the fact that it also is at a heading. Handle it here.
20923 (call-interactively #'org-set-tags))
20924 ((guard
20925 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20927 (user-error
20928 (substitute-command-keys
20929 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20931 (defun org-mode-restart ()
20932 (interactive)
20933 (let ((indent-status (bound-and-true-p org-indent-mode)))
20934 (funcall major-mode)
20935 (hack-local-variables)
20936 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20937 (org-indent-mode -1))
20938 (org-reset-file-cache))
20939 (message "%s restarted" major-mode))
20941 (defun org-kill-note-or-show-branches ()
20942 "Abort storing current note, or call `outline-show-branches'."
20943 (interactive)
20944 (if (not org-finish-function)
20945 (progn
20946 (outline-hide-subtree)
20947 (call-interactively 'outline-show-branches))
20948 (let ((org-note-abort t))
20949 (funcall org-finish-function))))
20951 (defun org-delete-indentation (&optional arg)
20952 "Join current line to previous and fix whitespace at join.
20954 If previous line is a headline add to headline title. Otherwise
20955 the function calls `delete-indentation'.
20957 With a non-nil optional argument, join it to the following one."
20958 (interactive "*P")
20959 (if (save-excursion
20960 (beginning-of-line (if arg 1 0))
20961 (let ((case-fold-search nil))
20962 (looking-at org-complex-heading-regexp)))
20963 ;; At headline.
20964 (let ((tags-column (when (match-beginning 5)
20965 (save-excursion (goto-char (match-beginning 5))
20966 (current-column))))
20967 (string (concat " " (progn (when arg (forward-line 1))
20968 (org-trim (delete-and-extract-region
20969 (line-beginning-position)
20970 (line-end-position)))))))
20971 (unless (bobp) (delete-region (point) (1- (point))))
20972 (goto-char (or (match-end 4)
20973 (match-beginning 5)
20974 (match-end 0)))
20975 (skip-chars-backward " \t")
20976 (save-excursion (insert string))
20977 ;; Adjust alignment of tags.
20978 (cond
20979 ((not tags-column)) ;no tags
20980 (org-auto-align-tags (org-set-tags nil t))
20981 (t (org--align-tags-here tags-column)))) ;preserve tags column
20982 (delete-indentation arg)))
20984 (defun org-open-line (n)
20985 "Insert a new row in tables, call `open-line' elsewhere.
20986 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20987 As a special case, when a document starts with a table, allow to
20988 call `open-line' on the very first character."
20989 (interactive "*p")
20990 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20991 (org-table-insert-row)
20992 (open-line n)))
20994 (defun org-return (&optional indent)
20995 "Goto next table row or insert a newline.
20997 Calls `org-table-next-row' or `newline', depending on context.
20999 When optional INDENT argument is non-nil, call
21000 `newline-and-indent' instead of `newline'.
21002 When `org-return-follows-link' is non-nil and point is on
21003 a timestamp or a link, call `org-open-at-point'. However, it
21004 will not happen if point is in a table or on a \"dead\"
21005 object (e.g., within a comment). In these case, you need to use
21006 `org-open-at-point' directly."
21007 (interactive)
21008 (let ((context (if org-return-follows-link (org-element-context)
21009 (org-element-at-point))))
21010 (cond
21011 ;; In a table, call `org-table-next-row'.
21012 ((or (and (eq (org-element-type context) 'table)
21013 (>= (point) (org-element-property :contents-begin context))
21014 (< (point) (org-element-property :contents-end context)))
21015 (org-element-lineage context '(table-row table-cell) t))
21016 (org-table-justify-field-maybe)
21017 (call-interactively #'org-table-next-row))
21018 ;; On a link or a timestamp, call `org-open-at-point' if
21019 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21020 ;; locations, e.g., in a comment, as `org-open-at-point'.
21021 ((and org-return-follows-link
21022 (or (org-in-regexp org-ts-regexp-both nil t)
21023 (org-in-regexp org-tsr-regexp-both nil t)
21024 (org-in-regexp org-any-link-re nil t)))
21025 (call-interactively #'org-open-at-point))
21026 ;; Insert newline in heading, but preserve tags.
21027 ((and (not (bolp))
21028 (save-excursion (beginning-of-line)
21029 (let ((case-fold-search nil))
21030 (looking-at org-complex-heading-regexp))))
21031 ;; At headline. Split line. However, if point is on keyword,
21032 ;; priority cookie or tags, do not break any of them: add
21033 ;; a newline after the headline instead.
21034 (let ((tags-column (and (match-beginning 5)
21035 (save-excursion (goto-char (match-beginning 5))
21036 (current-column))))
21037 (string
21038 (when (and (match-end 4) (org-point-in-group (point) 4))
21039 (delete-and-extract-region (point) (match-end 4)))))
21040 ;; Adjust tag alignment.
21041 (cond
21042 ((not (and tags-column string)))
21043 (org-auto-align-tags (org-set-tags nil t))
21044 (t (org--align-tags-here tags-column))) ;preserve tags column
21045 (end-of-line)
21046 (org-show-entry)
21047 (if indent (newline-and-indent) (newline))
21048 (when string (save-excursion (insert (org-trim string))))))
21049 ;; In a list, make sure indenting keeps trailing text within.
21050 ((and indent
21051 (not (eolp))
21052 (org-element-lineage context '(item)))
21053 (let ((trailing-data
21054 (delete-and-extract-region (point) (line-end-position))))
21055 (newline-and-indent)
21056 (save-excursion (insert trailing-data))))
21057 (t (if indent (newline-and-indent) (newline))))))
21059 (defun org-return-indent ()
21060 "Goto next table row or insert a newline and indent.
21061 Calls `org-table-next-row' or `newline-and-indent', depending on
21062 context. See the individual commands for more information."
21063 (interactive)
21064 (org-return t))
21066 (defun org-ctrl-c-tab (&optional _arg)
21067 "Toggle columns width in a table, or show children.
21068 Call `org-table-toggle-column-width' if point is in a table.
21069 Otherwise, call `org-show-children'."
21070 (interactive "p")
21071 (call-interactively
21072 (if (org-at-table-p) #'org-table-toggle-column-width
21073 #'org-show-children)))
21075 (defun org-ctrl-c-star ()
21076 "Compute table, or change heading status of lines.
21077 Calls `org-table-recalculate' or `org-toggle-heading',
21078 depending on context."
21079 (interactive)
21080 (cond
21081 ((org-at-table-p)
21082 (call-interactively 'org-table-recalculate))
21084 ;; Convert all lines in region to list items
21085 (call-interactively 'org-toggle-heading))))
21087 (defun org-ctrl-c-minus ()
21088 "Insert separator line in table or modify bullet status of line.
21089 Also turns a plain line or a region of lines into list items.
21090 Calls `org-table-insert-hline', `org-toggle-item', or
21091 `org-cycle-list-bullet', depending on context."
21092 (interactive)
21093 (cond
21094 ((org-at-table-p)
21095 (call-interactively 'org-table-insert-hline))
21096 ((org-region-active-p)
21097 (call-interactively 'org-toggle-item))
21098 ((org-in-item-p)
21099 (call-interactively 'org-cycle-list-bullet))
21101 (call-interactively 'org-toggle-item))))
21103 (defun org-toggle-heading (&optional nstars)
21104 "Convert headings to normal text, or items or text to headings.
21105 If there is no active region, only convert the current line.
21107 With a `\\[universal-argument]' prefix, convert the whole list at
21108 point into heading.
21110 In a region:
21112 - If the first non blank line is a headline, remove the stars
21113 from all headlines in the region.
21115 - If it is a normal line, turn each and every normal line (i.e.,
21116 not an heading or an item) in the region into headings. If you
21117 want to convert only the first line of this region, use one
21118 universal prefix argument.
21120 - If it is a plain list item, turn all plain list items into headings.
21122 When converting a line into a heading, the number of stars is chosen
21123 such that the lines become children of the current entry. However,
21124 when a numeric prefix argument is given, its value determines the
21125 number of stars to add."
21126 (interactive "P")
21127 (let ((skip-blanks
21128 (function
21129 ;; Return beginning of first non-blank line, starting from
21130 ;; line at POS.
21131 (lambda (pos)
21132 (save-excursion
21133 (goto-char pos)
21134 (while (org-at-comment-p) (forward-line))
21135 (skip-chars-forward " \r\t\n")
21136 (point-at-bol)))))
21137 beg end toggled)
21138 ;; Determine boundaries of changes. If a universal prefix has
21139 ;; been given, put the list in a region. If region ends at a bol,
21140 ;; do not consider the last line to be in the region.
21142 (when (and current-prefix-arg (org-at-item-p))
21143 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21144 (org-mark-element))
21146 (if (org-region-active-p)
21147 (setq beg (funcall skip-blanks (region-beginning))
21148 end (copy-marker (save-excursion
21149 (goto-char (region-end))
21150 (if (bolp) (point) (point-at-eol)))))
21151 (setq beg (funcall skip-blanks (point-at-bol))
21152 end (copy-marker (point-at-eol))))
21153 ;; Ensure inline tasks don't count as headings.
21154 (org-with-limited-levels
21155 (save-excursion
21156 (goto-char beg)
21157 (cond
21158 ;; Case 1. Started at an heading: de-star headings.
21159 ((org-at-heading-p)
21160 (while (< (point) end)
21161 (when (org-at-heading-p t)
21162 (looking-at org-outline-regexp) (replace-match "")
21163 (setq toggled t))
21164 (forward-line)))
21165 ;; Case 2. Started at an item: change items into headlines.
21166 ;; One star will be added by `org-list-to-subtree'.
21167 ((org-at-item-p)
21168 (while (< (point) end)
21169 (when (org-at-item-p)
21170 ;; Pay attention to cases when region ends before list.
21171 (let* ((struct (org-list-struct))
21172 (list-end
21173 (min (org-list-get-bottom-point struct) (1+ end))))
21174 (save-restriction
21175 (narrow-to-region (point) list-end)
21176 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21177 (setq toggled t))
21178 (forward-line)))
21179 ;; Case 3. Started at normal text: make every line an heading,
21180 ;; skipping headlines and items.
21181 (t (let* ((stars
21182 (make-string
21183 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21184 (add-stars
21185 (cond (nstars "") ; stars from prefix only
21186 ((equal stars "") "*") ; before first heading
21187 (org-odd-levels-only "**") ; inside heading, odd
21188 (t "*"))) ; inside heading, oddeven
21189 (rpl (concat stars add-stars " "))
21190 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21191 (while (< (point) (if (equal nstars '(4)) lend end))
21192 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21193 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21194 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21195 (forward-line)))))))
21196 (unless toggled (message "Cannot toggle heading from here"))))
21198 (defun org-meta-return (&optional arg)
21199 "Insert a new heading or wrap a region in a table.
21200 Calls `org-insert-heading', `org-insert-item' or
21201 `org-table-wrap-region', depending on context. When called with
21202 an argument, unconditionally call `org-insert-heading'."
21203 (interactive "P")
21204 (org-check-before-invisible-edit 'insert)
21205 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21206 (call-interactively (cond (arg #'org-insert-heading)
21207 ((org-at-table-p) #'org-table-wrap-region)
21208 ((org-in-item-p) #'org-insert-item)
21209 (t #'org-insert-heading)))))
21211 ;;; Menu entries
21213 (defsubst org-in-subtree-not-table-p ()
21214 "Are we in a subtree and not in a table?"
21215 (and (not (org-before-first-heading-p))
21216 (not (org-at-table-p))))
21218 ;; Define the Org mode menus
21219 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21220 '("Tbl"
21221 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21222 ["Next Field" org-cycle (org-at-table-p)]
21223 ["Previous Field" org-shifttab (org-at-table-p)]
21224 ["Next Row" org-return (org-at-table-p)]
21225 "--"
21226 ["Blank Field" org-table-blank-field (org-at-table-p)]
21227 ["Edit Field" org-table-edit-field (org-at-table-p)]
21228 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21229 "--"
21230 ("Column"
21231 ["Move Column Left" org-metaleft (org-at-table-p)]
21232 ["Move Column Right" org-metaright (org-at-table-p)]
21233 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21234 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21235 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21236 ("Row"
21237 ["Move Row Up" org-metaup (org-at-table-p)]
21238 ["Move Row Down" org-metadown (org-at-table-p)]
21239 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21240 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21241 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21242 "--"
21243 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21244 ("Rectangle"
21245 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21246 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21247 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21248 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21249 "--"
21250 ("Calculate"
21251 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21252 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21253 ["Edit Formulas" org-edit-special (org-at-table-p)]
21254 "--"
21255 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21256 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21257 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21258 "--"
21259 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21260 "--"
21261 ["Sum Column/Rectangle" org-table-sum
21262 (or (org-at-table-p) (org-region-active-p))]
21263 ["Which Column?" org-table-current-column (org-at-table-p)])
21264 ["Debug Formulas"
21265 org-table-toggle-formula-debugger
21266 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21267 ["Show Col/Row Numbers"
21268 org-table-toggle-coordinate-overlays
21269 :style toggle
21270 :selected (bound-and-true-p org-table-overlay-coordinates)]
21271 "--"
21272 ["Create" org-table-create (not (org-at-table-p))]
21273 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21274 ["Import from File" org-table-import (not (org-at-table-p))]
21275 ["Export to File" org-table-export (org-at-table-p)]
21276 "--"
21277 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21278 "--"
21279 ("Plot"
21280 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21281 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21283 (easy-menu-define org-org-menu org-mode-map "Org menu"
21284 '("Org"
21285 ("Show/Hide"
21286 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21287 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21288 ["Sparse Tree..." org-sparse-tree t]
21289 ["Reveal Context" org-reveal t]
21290 ["Show All" outline-show-all t]
21291 "--"
21292 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21293 "--"
21294 ["New Heading" org-insert-heading t]
21295 ("Navigate Headings"
21296 ["Up" outline-up-heading t]
21297 ["Next" outline-next-visible-heading t]
21298 ["Previous" outline-previous-visible-heading t]
21299 ["Next Same Level" outline-forward-same-level t]
21300 ["Previous Same Level" outline-backward-same-level t]
21301 "--"
21302 ["Jump" org-goto t])
21303 ("Edit Structure"
21304 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21305 "--"
21306 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21307 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21308 "--"
21309 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21310 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21311 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21312 "--"
21313 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21314 "--"
21315 ["Copy visible text" org-copy-visible t]
21316 "--"
21317 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21318 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21319 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21320 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21321 "--"
21322 ["Sort Region/Children" org-sort t]
21323 "--"
21324 ["Convert to odd levels" org-convert-to-odd-levels t]
21325 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21326 ("Editing"
21327 ["Emphasis..." org-emphasize t]
21328 ["Edit Source Example" org-edit-special t]
21329 "--"
21330 ["Footnote new/jump" org-footnote-action t]
21331 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21332 ("Archive"
21333 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21334 "--"
21335 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21336 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21337 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21339 "--"
21340 ("Hyperlinks"
21341 ["Store Link (Global)" org-store-link t]
21342 ["Find existing link to here" org-occur-link-in-agenda-files t]
21343 ["Insert Link" org-insert-link t]
21344 ["Follow Link" org-open-at-point t]
21345 "--"
21346 ["Next link" org-next-link t]
21347 ["Previous link" org-previous-link t]
21348 "--"
21349 ["Descriptive Links"
21350 org-toggle-link-display
21351 :style radio
21352 :selected org-descriptive-links
21354 ["Literal Links"
21355 org-toggle-link-display
21356 :style radio
21357 :selected (not org-descriptive-links)])
21358 "--"
21359 ("TODO Lists"
21360 ["TODO/DONE/-" org-todo t]
21361 ("Select keyword"
21362 ["Next keyword" org-shiftright (org-at-heading-p)]
21363 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21364 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21365 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21366 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21367 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21368 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21369 "--"
21370 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21371 :selected org-enforce-todo-dependencies :style toggle :active t]
21372 "Settings for tree at point"
21373 ["Do Children sequentially" org-toggle-ordered-property :style radio
21374 :selected (org-entry-get nil "ORDERED")
21375 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21376 ["Do Children parallel" org-toggle-ordered-property :style radio
21377 :selected (not (org-entry-get nil "ORDERED"))
21378 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21379 "--"
21380 ["Set Priority" org-priority t]
21381 ["Priority Up" org-shiftup t]
21382 ["Priority Down" org-shiftdown t]
21383 "--"
21384 ["Get news from all feeds" org-feed-update-all t]
21385 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21386 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21387 ("TAGS and Properties"
21388 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21389 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21390 "--"
21391 ["Set property" org-set-property (not (org-before-first-heading-p))]
21392 ["Column view of properties" org-columns t]
21393 ["Insert Column View DBlock" org-columns-insert-dblock t])
21394 ("Dates and Scheduling"
21395 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21396 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21397 ("Change Date"
21398 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21399 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21400 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21401 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21402 ["Compute Time Range" org-evaluate-time-range t]
21403 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21404 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21405 "--"
21406 ["Custom time format" org-toggle-time-stamp-overlays
21407 :style radio :selected org-display-custom-times]
21408 "--"
21409 ["Goto Calendar" org-goto-calendar t]
21410 ["Date from Calendar" org-date-from-calendar t]
21411 "--"
21412 ["Start/Restart Timer" org-timer-start t]
21413 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21414 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21415 ["Insert Timer String" org-timer t]
21416 ["Insert Timer Item" org-timer-item t])
21417 ("Logging work"
21418 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21419 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21420 ["Clock out" org-clock-out t]
21421 ["Clock cancel" org-clock-cancel t]
21422 "--"
21423 ["Mark as default task" org-clock-mark-default-task t]
21424 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21425 ["Goto running clock" org-clock-goto t]
21426 "--"
21427 ["Display times" org-clock-display t]
21428 ["Create clock table" org-clock-report t]
21429 "--"
21430 ["Record DONE time"
21431 (progn (setq org-log-done (not org-log-done))
21432 (message "Switching to %s will %s record a timestamp"
21433 (car org-done-keywords)
21434 (if org-log-done "automatically" "not")))
21435 :style toggle :selected org-log-done])
21436 "--"
21437 ["Agenda Command..." org-agenda t]
21438 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21439 ("File List for Agenda")
21440 ("Special views current file"
21441 ["TODO Tree" org-show-todo-tree t]
21442 ["Check Deadlines" org-check-deadlines t]
21443 ["Tags/Property tree" org-match-sparse-tree t])
21444 "--"
21445 ["Export/Publish..." org-export-dispatch t]
21446 ("LaTeX"
21447 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21448 :selected org-cdlatex-mode]
21449 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21450 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21451 ["Modify math symbol" org-cdlatex-math-modify
21452 (org-inside-LaTeX-fragment-p)]
21453 ["Insert citation" org-reftex-citation t])
21454 "--"
21455 ("MobileOrg"
21456 ["Push Files and Views" org-mobile-push t]
21457 ["Get Captured and Flagged" org-mobile-pull t]
21458 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21459 "--"
21460 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21461 "--"
21462 ("Documentation"
21463 ["Show Version" org-version t]
21464 ["Info Documentation" org-info t])
21465 ("Customize"
21466 ["Browse Org Group" org-customize t]
21467 "--"
21468 ["Expand This Menu" org-create-customize-menu
21469 (fboundp 'customize-menu-create)])
21470 ["Send bug report" org-submit-bug-report t]
21471 "--"
21472 ("Refresh/Reload"
21473 ["Refresh setup current buffer" org-mode-restart t]
21474 ["Reload Org (after update)" org-reload t]
21475 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21478 (defun org-info (&optional node)
21479 "Read documentation for Org in the info system.
21480 With optional NODE, go directly to that node."
21481 (interactive)
21482 (info (format "(org)%s" (or node ""))))
21484 ;;;###autoload
21485 (defun org-submit-bug-report ()
21486 "Submit a bug report on Org via mail.
21488 Don't hesitate to report any problems or inaccurate documentation.
21490 If you don't have setup sending mail from (X)Emacs, please copy the
21491 output buffer into your mail program, as it gives us important
21492 information about your Org version and configuration."
21493 (interactive)
21494 (require 'reporter)
21495 (defvar reporter-prompt-for-summary-p)
21496 (org-load-modules-maybe)
21497 (org-require-autoloaded-modules)
21498 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21499 (reporter-submit-bug-report
21500 "emacs-orgmode@gnu.org"
21501 (org-version nil 'full)
21502 (let (list)
21503 (save-window-excursion
21504 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21505 (delete-other-windows)
21506 (erase-buffer)
21507 (insert "You are about to submit a bug report to the Org mailing list.
21509 We would like to add your full Org and Outline configuration to the
21510 bug report. This greatly simplifies the work of the maintainer and
21511 other experts on the mailing list.
21513 HOWEVER, some variables you have customized may contain private
21514 information. The names of customers, colleagues, or friends, might
21515 appear in the form of file names, tags, todo states, or search strings.
21516 If you answer yes to the prompt, you might want to check and remove
21517 such private information before sending the email.")
21518 (add-text-properties (point-min) (point-max) '(face org-warning))
21519 (when (yes-or-no-p "Include your Org configuration ")
21520 (mapatoms
21521 (lambda (v)
21522 (and (boundp v)
21523 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21524 (or (and (symbol-value v)
21525 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21526 (and
21527 (get v 'custom-type) (get v 'standard-value)
21528 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21529 (push v list)))))
21530 (kill-buffer (get-buffer "*Warn about privacy*"))
21531 list))
21532 nil nil
21533 "Remember to cover the basics, that is, what you expected to happen and
21534 what in fact did happen. You don't know how to make a good report? See
21536 http://orgmode.org/manual/Feedback.html#Feedback
21538 Your bug report will be posted to the Org mailing list.
21539 ------------------------------------------------------------------------")
21540 (save-excursion
21541 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21542 (replace-match "\\1Bug: \\3 [\\2]")))))
21545 (defun org-install-agenda-files-menu ()
21546 (let ((bl (buffer-list)))
21547 (save-excursion
21548 (while bl
21549 (set-buffer (pop bl))
21550 (when (derived-mode-p 'org-mode) (setq bl nil)))
21551 (when (derived-mode-p 'org-mode)
21552 (easy-menu-change
21553 '("Org") "File List for Agenda"
21554 (append
21555 (list
21556 ["Edit File List" (org-edit-agenda-file-list) t]
21557 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21558 ["Remove Current File from List" org-remove-file t]
21559 ["Cycle through agenda files" org-cycle-agenda-files t]
21560 ["Occur in all agenda files" org-occur-in-agenda-files t]
21561 "--")
21562 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21564 ;;;; Documentation
21566 (defun org-require-autoloaded-modules ()
21567 (interactive)
21568 (mapc #'require
21569 '(org-agenda org-archive org-attach org-clock org-colview org-id
21570 org-table org-timer)))
21572 ;;;###autoload
21573 (defun org-reload (&optional uncompiled)
21574 "Reload all org lisp files.
21575 With prefix arg UNCOMPILED, load the uncompiled versions."
21576 (interactive "P")
21577 (require 'loadhist)
21578 (let* ((org-dir (org-find-library-dir "org"))
21579 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21580 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21581 (remove-re (format "\\`%s\\'"
21582 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21583 (feats (delete-dups
21584 (mapcar 'file-name-sans-extension
21585 (mapcar 'file-name-nondirectory
21586 (delq nil
21587 (mapcar 'feature-file
21588 features))))))
21589 (lfeat (append
21590 (sort
21591 (setq feats
21592 (delq nil (mapcar
21593 (lambda (f)
21594 (if (and (string-match feature-re f)
21595 (not (string-match remove-re f)))
21596 f nil))
21597 feats)))
21598 'string-lessp)
21599 (list "org-version" "org")))
21600 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21601 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21602 load-uncore load-misses)
21603 (setq load-misses
21604 (delq 't
21605 (mapcar (lambda (f)
21606 (or (org-load-noerror-mustsuffix (concat org-dir f))
21607 (and (string= org-dir contrib-dir)
21608 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21609 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21610 (add-to-list 'load-uncore f 'append)
21613 lfeat)))
21614 (when load-uncore
21615 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21616 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21617 (if load-misses
21618 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21619 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21620 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21622 ;;;###autoload
21623 (defun org-customize ()
21624 "Call the customize function with org as argument."
21625 (interactive)
21626 (org-load-modules-maybe)
21627 (org-require-autoloaded-modules)
21628 (customize-browse 'org))
21630 (defun org-create-customize-menu ()
21631 "Create a full customization menu for Org mode, insert it into the menu."
21632 (interactive)
21633 (org-load-modules-maybe)
21634 (org-require-autoloaded-modules)
21635 (if (fboundp 'customize-menu-create)
21636 (progn
21637 (easy-menu-change
21638 '("Org") "Customize"
21639 `(["Browse Org group" org-customize t]
21640 "--"
21641 ,(customize-menu-create 'org)
21642 ["Set" Custom-set t]
21643 ["Save" Custom-save t]
21644 ["Reset to Current" Custom-reset-current t]
21645 ["Reset to Saved" Custom-reset-saved t]
21646 ["Reset to Standard Settings" Custom-reset-standard t]))
21647 (message "\"Org\"-menu now contains full customization menu"))
21648 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21650 ;;;; Miscellaneous stuff
21652 ;;; Generally useful functions
21654 (defun org-get-at-eol (property n)
21655 "Get text property PROPERTY at the end of line less N characters."
21656 (get-text-property (- (point-at-eol) n) property))
21658 (defun org-find-text-property-in-string (prop s)
21659 "Return the first non-nil value of property PROP in string S."
21660 (or (get-text-property 0 prop s)
21661 (get-text-property (or (next-single-property-change 0 prop s) 0)
21662 prop s)))
21664 (defun org-display-warning (message)
21665 "Display the given MESSAGE as a warning."
21666 (display-warning 'org message :warning))
21668 (defun org-eval (form)
21669 "Eval FORM and return result."
21670 (condition-case error
21671 (eval form)
21672 (error (format "%%![Error: %s]" error))))
21674 (defun org-in-clocktable-p ()
21675 "Check if the cursor is in a clocktable."
21676 (let ((pos (point)) start)
21677 (save-excursion
21678 (end-of-line 1)
21679 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21680 (setq start (match-beginning 0))
21681 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21682 (>= (match-end 0) pos)
21683 start))))
21685 (defun org-in-verbatim-emphasis ()
21686 (save-match-data
21687 (and (org-in-regexp org-verbatim-re 2)
21688 (>= (point) (match-beginning 3))
21689 (<= (point) (match-end 4)))))
21691 (defun org-overlay-display (ovl text &optional face evap)
21692 "Make overlay OVL display TEXT with face FACE."
21693 (overlay-put ovl 'display text)
21694 (if face (overlay-put ovl 'face face))
21695 (if evap (overlay-put ovl 'evaporate t)))
21697 (defun org-overlay-before-string (ovl text &optional face evap)
21698 "Make overlay OVL display TEXT with face FACE."
21699 (if face (org-add-props text nil 'face face))
21700 (overlay-put ovl 'before-string text)
21701 (if evap (overlay-put ovl 'evaporate t)))
21703 (defun org-find-overlays (prop &optional pos delete)
21704 "Find all overlays specifying PROP at POS or point.
21705 If DELETE is non-nil, delete all those overlays."
21706 (let (found)
21707 (dolist (ov (overlays-at (or pos (point))) found)
21708 (cond ((not (overlay-get ov prop)))
21709 (delete (delete-overlay ov))
21710 (t (push ov found))))))
21712 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21713 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21714 (if (and marker (marker-buffer marker)
21715 (buffer-live-p (marker-buffer marker)))
21716 (progn
21717 (pop-to-buffer-same-window (marker-buffer marker))
21718 (when (or (> marker (point-max)) (< marker (point-min)))
21719 (widen))
21720 (goto-char marker)
21721 (org-show-context 'org-goto))
21722 (if bookmark
21723 (bookmark-jump bookmark)
21724 (error "Cannot find location"))))
21726 (defun org-quote-csv-field (s)
21727 "Quote field for inclusion in CSV material."
21728 (if (string-match "[\",]" s)
21729 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21732 (defun org-force-self-insert (N)
21733 "Needed to enforce self-insert under remapping."
21734 (interactive "p")
21735 (self-insert-command N))
21737 (defun org-shorten-string (s maxlength)
21738 "Shorten string S so that it is no longer than MAXLENGTH characters.
21739 If the string is shorter or has length MAXLENGTH, just return the
21740 original string. If it is longer, the functions finds a space in the
21741 string, breaks this string off at that locations and adds three dots
21742 as ellipsis. Including the ellipsis, the string will not be longer
21743 than MAXLENGTH. If finding a good breaking point in the string does
21744 not work, the string is just chopped off in the middle of a word
21745 if necessary."
21746 (if (<= (length s) maxlength)
21748 (let* ((n (max (- maxlength 4) 1))
21749 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21750 (if (string-match re s)
21751 (concat (match-string 1 s) "...")
21752 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21754 (defun org-get-indentation (&optional line)
21755 "Get the indentation of the current line, interpreting tabs.
21756 When LINE is given, assume it represents a line and compute its indentation."
21757 (if line
21758 (when (string-match "^ *" (org-remove-tabs line))
21759 (match-end 0))
21760 (save-excursion
21761 (beginning-of-line 1)
21762 (skip-chars-forward " \t")
21763 (current-column))))
21765 (defun org-get-string-indentation (s)
21766 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21767 (let ((n -1) (i 0) (w tab-width) c)
21768 (catch 'exit
21769 (while (< (setq n (1+ n)) (length s))
21770 (setq c (aref s n))
21771 (cond ((= c ?\ ) (setq i (1+ i)))
21772 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21773 (t (throw 'exit t)))))
21776 (defun org-remove-tabs (s &optional width)
21777 "Replace tabulators in S with spaces.
21778 Assumes that s is a single line, starting in column 0."
21779 (setq width (or width tab-width))
21780 (while (string-match "\t" s)
21781 (setq s (replace-match
21782 (make-string
21783 (- (* width (/ (+ (match-beginning 0) width) width))
21784 (match-beginning 0)) ?\ )
21785 t t s)))
21788 (defun org-fix-indentation (line ind)
21789 "Fix indentation in LINE.
21790 IND is a cons cell with target and minimum indentation.
21791 If the current indentation in LINE is smaller than the minimum,
21792 leave it alone. If it is larger than ind, set it to the target."
21793 (let* ((l (org-remove-tabs line))
21794 (i (org-get-indentation l))
21795 (i1 (car ind)) (i2 (cdr ind)))
21796 (when (>= i i2) (setq l (substring line i2)))
21797 (if (> i1 0)
21798 (concat (make-string i1 ?\ ) l)
21799 l)))
21801 (defun org-remove-indentation (code &optional n)
21802 "Remove maximum common indentation in string CODE and return it.
21803 N may optionally be the number of columns to remove. Return CODE
21804 as-is if removal failed."
21805 (with-temp-buffer
21806 (insert code)
21807 (if (org-do-remove-indentation n) (buffer-string) code)))
21809 (defun org-do-remove-indentation (&optional n)
21810 "Remove the maximum common indentation from the buffer.
21811 When optional argument N is a positive integer, remove exactly
21812 that much characters from indentation, if possible. Return nil
21813 if it fails."
21814 (catch :exit
21815 (goto-char (point-min))
21816 ;; Find maximum common indentation, if not specified.
21817 (let ((n (or n
21818 (let ((min-ind (point-max)))
21819 (save-excursion
21820 (while (re-search-forward "^[ \t]*\\S-" nil t)
21821 (let ((ind (1- (current-column))))
21822 (if (zerop ind) (throw :exit nil)
21823 (setq min-ind (min min-ind ind))))))
21824 min-ind))))
21825 (if (zerop n) (throw :exit nil)
21826 ;; Remove exactly N indentation, but give up if not possible.
21827 (while (not (eobp))
21828 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21829 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21830 ((< ind n) (throw :exit nil))
21831 (t (indent-line-to (- ind n))))
21832 (forward-line)))
21833 ;; Signal success.
21834 t))))
21836 (defun org-fill-template (template alist)
21837 "Find each %key of ALIST in TEMPLATE and replace it."
21838 (let ((case-fold-search nil))
21839 (dolist (entry (sort (copy-sequence alist)
21840 (lambda (a b) (< (length (car a)) (length (car b))))))
21841 (setq template
21842 (replace-regexp-in-string
21843 (concat "%" (regexp-quote (car entry)))
21844 (or (cdr entry) "") template t t)))
21845 template))
21847 (defun org-base-buffer (buffer)
21848 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21849 (if (not buffer)
21850 buffer
21851 (or (buffer-base-buffer buffer)
21852 buffer)))
21854 (defun org-wrap (string &optional width lines)
21855 "Wrap string to either a number of lines, or a width in characters.
21856 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21857 that costs. If there is a word longer than WIDTH, the text is actually
21858 wrapped to the length of that word.
21859 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21860 many lines, whatever width that takes.
21861 The return value is a list of lines, without newlines at the end."
21862 (let* ((words (split-string string))
21863 (maxword (apply 'max (mapcar 'org-string-width words)))
21864 w ll)
21865 (cond (width
21866 (org-do-wrap words (max maxword width)))
21867 (lines
21868 (setq w maxword)
21869 (setq ll (org-do-wrap words maxword))
21870 (if (<= (length ll) lines)
21872 (setq ll words)
21873 (while (> (length ll) lines)
21874 (setq w (1+ w))
21875 (setq ll (org-do-wrap words w)))
21876 ll))
21877 (t (error "Cannot wrap this")))))
21879 (defun org-do-wrap (words width)
21880 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21881 (let (lines line)
21882 (while words
21883 (setq line (pop words))
21884 (while (and words (< (+ (length line) (length (car words))) width))
21885 (setq line (concat line " " (pop words))))
21886 (setq lines (push line lines)))
21887 (nreverse lines)))
21889 (defun org-quote-vert (s)
21890 "Replace \"|\" with \"\\vert\"."
21891 (while (string-match "|" s)
21892 (setq s (replace-match "\\vert" t t s)))
21895 (defun org-uuidgen-p (s)
21896 "Is S an ID created by UUIDGEN?"
21897 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21899 (defun org-in-src-block-p (&optional inside)
21900 "Whether point is in a code source block.
21901 When INSIDE is non-nil, don't consider we are within a src block
21902 when point is at #+BEGIN_SRC or #+END_SRC."
21903 (let ((case-fold-search t))
21904 (or (and (eq (get-char-property (point) 'src-block) t))
21905 (and (not inside)
21906 (save-match-data
21907 (save-excursion
21908 (beginning-of-line)
21909 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21911 (defun org-context ()
21912 "Return a list of contexts of the current cursor position.
21913 If several contexts apply, all are returned.
21914 Each context entry is a list with a symbol naming the context, and
21915 two positions indicating start and end of the context. Possible
21916 contexts are:
21918 :headline anywhere in a headline
21919 :headline-stars on the leading stars in a headline
21920 :todo-keyword on a TODO keyword (including DONE) in a headline
21921 :tags on the TAGS in a headline
21922 :priority on the priority cookie in a headline
21923 :item on the first line of a plain list item
21924 :item-bullet on the bullet/number of a plain list item
21925 :checkbox on the checkbox in a plain list item
21926 :table in an Org table
21927 :table-special on a special filed in a table
21928 :table-table in a table.el table
21929 :clocktable in a clocktable
21930 :src-block in a source block
21931 :link on a hyperlink
21932 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21933 :target on a <<target>>
21934 :radio-target on a <<<radio-target>>>
21935 :latex-fragment on a LaTeX fragment
21936 :latex-preview on a LaTeX fragment with overlaid preview image
21938 This function expects the position to be visible because it uses font-lock
21939 faces as a help to recognize the following contexts: :table-special, :link,
21940 and :keyword."
21941 (let* ((f (get-text-property (point) 'face))
21942 (faces (if (listp f) f (list f)))
21943 (case-fold-search t)
21944 (p (point)) clist o)
21945 ;; First the large context
21946 (cond
21947 ((org-at-heading-p t)
21948 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21949 (when (progn
21950 (beginning-of-line 1)
21951 (looking-at org-todo-line-tags-regexp))
21952 (push (org-point-in-group p 1 :headline-stars) clist)
21953 (push (org-point-in-group p 2 :todo-keyword) clist)
21954 (push (org-point-in-group p 4 :tags) clist))
21955 (goto-char p)
21956 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21957 (when (looking-at "\\[#[A-Z0-9]\\]")
21958 (push (org-point-in-group p 0 :priority) clist)))
21960 ((org-at-item-p)
21961 (push (org-point-in-group p 2 :item-bullet) clist)
21962 (push (list :item (point-at-bol)
21963 (save-excursion (org-end-of-item) (point)))
21964 clist)
21965 (and (org-at-item-checkbox-p)
21966 (push (org-point-in-group p 0 :checkbox) clist)))
21968 ((org-at-table-p)
21969 (push (list :table (org-table-begin) (org-table-end)) clist)
21970 (when (memq 'org-formula faces)
21971 (push (list :table-special
21972 (previous-single-property-change p 'face)
21973 (next-single-property-change p 'face)) clist)))
21974 ((org-at-table-p 'any)
21975 (push (list :table-table) clist)))
21976 (goto-char p)
21978 (let ((case-fold-search t))
21979 ;; New the "medium" contexts: clocktables, source blocks
21980 (cond ((org-in-clocktable-p)
21981 (push (list :clocktable
21982 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21983 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21984 (match-beginning 1))
21985 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21986 (match-end 0))) clist))
21987 ((org-in-src-block-p)
21988 (push (list :src-block
21989 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21990 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21991 (match-beginning 1))
21992 (and (search-forward "#+END_SRC" nil t)
21993 (match-beginning 0))) clist))))
21994 (goto-char p)
21996 ;; Now the small context
21997 (cond
21998 ((org-at-timestamp-p)
21999 (push (org-point-in-group p 0 :timestamp) clist))
22000 ((memq 'org-link faces)
22001 (push (list :link
22002 (previous-single-property-change p 'face)
22003 (next-single-property-change p 'face)) clist))
22004 ((memq 'org-special-keyword faces)
22005 (push (list :keyword
22006 (previous-single-property-change p 'face)
22007 (next-single-property-change p 'face)) clist))
22008 ((org-at-target-p)
22009 (push (org-point-in-group p 0 :target) clist)
22010 (goto-char (1- (match-beginning 0)))
22011 (when (looking-at org-radio-target-regexp)
22012 (push (org-point-in-group p 0 :radio-target) clist))
22013 (goto-char p))
22014 ((setq o (cl-some
22015 (lambda (o)
22016 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22018 (overlays-at (point))))
22019 (push (list :latex-fragment
22020 (overlay-start o) (overlay-end o)) clist)
22021 (push (list :latex-preview
22022 (overlay-start o) (overlay-end o)) clist))
22023 ((org-inside-LaTeX-fragment-p)
22024 ;; FIXME: positions wrong.
22025 (push (list :latex-fragment (point) (point)) clist)))
22027 (setq clist (nreverse (delq nil clist)))
22028 clist))
22030 (defun org-in-regexp (regexp &optional nlines visually)
22031 "Check if point is inside a match of REGEXP.
22033 Normally only the current line is checked, but you can include
22034 NLINES extra lines around point into the search. If VISUALLY is
22035 set, require that the cursor is not after the match but really
22036 on, so that the block visually is on the match.
22038 Return nil or a cons cell (BEG . END) where BEG and END are,
22039 respectively, the positions at the beginning and the end of the
22040 match."
22041 (catch :exit
22042 (let ((pos (point))
22043 (eol (line-end-position (if nlines (1+ nlines) 1))))
22044 (save-excursion
22045 (beginning-of-line (- 1 (or nlines 0)))
22046 (while (and (re-search-forward regexp eol t)
22047 (<= (match-beginning 0) pos))
22048 (let ((end (match-end 0)))
22049 (when (or (> end pos) (and (= end pos) (not visually)))
22050 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22052 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22053 "Non-nil when point is between matches of START-RE and END-RE.
22055 Also return a non-nil value when point is on one of the matches.
22057 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22058 buffer positions. Default values are the positions of headlines
22059 surrounding the point.
22061 The functions returns a cons cell whose car (resp. cdr) is the
22062 position before START-RE (resp. after END-RE)."
22063 (save-match-data
22064 (let ((pos (point))
22065 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22066 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22067 beg end)
22068 (save-excursion
22069 ;; Point is on a block when on START-RE or if START-RE can be
22070 ;; found before it...
22071 (and (or (org-in-regexp start-re)
22072 (re-search-backward start-re limit-up t))
22073 (setq beg (match-beginning 0))
22074 ;; ... and END-RE after it...
22075 (goto-char (match-end 0))
22076 (re-search-forward end-re limit-down t)
22077 (> (setq end (match-end 0)) pos)
22078 ;; ... without another START-RE in-between.
22079 (goto-char (match-beginning 0))
22080 (not (re-search-backward start-re (1+ beg) t))
22081 ;; Return value.
22082 (cons beg end))))))
22084 (defun org-in-block-p (names)
22085 "Non-nil when point belongs to a block whose name belongs to NAMES.
22087 NAMES is a list of strings containing names of blocks.
22089 Return first block name matched, or nil. Beware that in case of
22090 nested blocks, the returned name may not belong to the closest
22091 block from point."
22092 (save-match-data
22093 (catch 'exit
22094 (let ((case-fold-search t)
22095 (lim-up (save-excursion (outline-previous-heading)))
22096 (lim-down (save-excursion (outline-next-heading))))
22097 (dolist (name names)
22098 (let ((n (regexp-quote name)))
22099 (when (org-between-regexps-p
22100 (concat "^[ \t]*#\\+begin_" n)
22101 (concat "^[ \t]*#\\+end_" n)
22102 lim-up lim-down)
22103 (throw 'exit n)))))
22104 nil)))
22106 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22107 "Call `multi-occur' with buffers for all agenda files."
22108 (interactive "sOrg-files matching: ")
22109 (let* ((files (org-agenda-files))
22110 (tnames (mapcar #'file-truename files))
22111 (extra org-agenda-text-search-extra-files))
22112 (when (eq (car extra) 'agenda-archives)
22113 (setq extra (cdr extra))
22114 (setq files (org-add-archive-files files)))
22115 (dolist (f extra)
22116 (unless (member (file-truename f) tnames)
22117 (unless (member f files) (setq files (append files (list f))))
22118 (setq tnames (append tnames (list (file-truename f))))))
22119 (multi-occur
22120 (mapcar (lambda (x)
22121 (with-current-buffer
22122 ;; FIXME: Why not just (find-file-noselect x)?
22123 ;; Is it to avoid the "revert buffer" prompt?
22124 (or (get-file-buffer x) (find-file-noselect x))
22125 (widen)
22126 (current-buffer)))
22127 files)
22128 regexp)))
22130 (add-hook 'occur-mode-find-occurrence-hook
22131 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22133 (defun org-occur-link-in-agenda-files ()
22134 "Create a link and search for it in the agendas.
22135 The link is not stored in `org-stored-links', it is just created
22136 for the search purpose."
22137 (interactive)
22138 (let ((link (condition-case nil
22139 (org-store-link nil)
22140 (error "Unable to create a link to here"))))
22141 (org-occur-in-agenda-files (regexp-quote link))))
22143 (defun org-reverse-string (string)
22144 "Return the reverse of STRING."
22145 (apply 'string (reverse (string-to-list string))))
22147 ;; defsubst org-uniquify must be defined before first use
22149 (defun org-uniquify-alist (alist)
22150 "Merge elements of ALIST with the same key.
22152 For example, in this alist:
22154 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22155 => \\='((a 1 3) (b 2))
22157 merge (a 1) and (a 3) into (a 1 3).
22159 The function returns the new ALIST."
22160 (let (rtn)
22161 (dolist (e alist rtn)
22162 (let (n)
22163 (if (not (assoc (car e) rtn))
22164 (push e rtn)
22165 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22166 (setq rtn (assq-delete-all (car e) rtn))
22167 (push n rtn))))))
22169 (defun org-delete-all (elts list)
22170 "Remove all elements in ELTS from LIST.
22171 Comparison is done with `equal'. It is a destructive operation
22172 that may remove elements by altering the list structure."
22173 (while elts
22174 (setq list (delete (pop elts) list)))
22175 list)
22177 (defun org-back-over-empty-lines ()
22178 "Move backwards over whitespace, to the beginning of the first empty line.
22179 Returns the number of empty lines passed."
22180 (let ((pos (point)))
22181 (if (cdr (assq 'heading org-blank-before-new-entry))
22182 (skip-chars-backward " \t\n\r")
22183 (unless (eobp)
22184 (forward-line -1)))
22185 (beginning-of-line 2)
22186 (goto-char (min (point) pos))
22187 (count-lines (point) pos)))
22189 (defun org-skip-whitespace ()
22190 (skip-chars-forward " \t\n\r"))
22192 (defun org-point-in-group (point group &optional context)
22193 "Check if POINT is in match-group GROUP.
22194 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22195 match. If the match group does not exist or point is not inside it,
22196 return nil."
22197 (and (match-beginning group)
22198 (>= point (match-beginning group))
22199 (<= point (match-end group))
22200 (if context
22201 (list context (match-beginning group) (match-end group))
22202 t)))
22204 (defun org-switch-to-buffer-other-window (&rest args)
22205 "Switch to buffer in a second window on the current frame.
22206 In particular, do not allow pop-up frames.
22207 Returns the newly created buffer."
22208 (org-no-popups
22209 (apply 'switch-to-buffer-other-window args)))
22211 (defun org-combine-plists (&rest plists)
22212 "Create a single property list from all plists in PLISTS.
22213 The process starts by copying the first list, and then setting properties
22214 from the other lists. Settings in the last list are the most significant
22215 ones and overrule settings in the other lists."
22216 (let ((rtn (copy-sequence (pop plists)))
22217 p v ls)
22218 (while plists
22219 (setq ls (pop plists))
22220 (while ls
22221 (setq p (pop ls) v (pop ls))
22222 (setq rtn (plist-put rtn p v))))
22223 rtn))
22225 (defun org-replace-escapes (string table)
22226 "Replace %-escapes in STRING with values in TABLE.
22227 TABLE is an association list with keys like \"%a\" and string values.
22228 The sequences in STRING may contain normal field width and padding information,
22229 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22230 so values can contain further %-escapes if they are define later in TABLE."
22231 (let ((tbl (copy-alist table))
22232 (case-fold-search nil)
22233 (pchg 0)
22234 re rpl)
22235 (dolist (e tbl)
22236 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22237 (when (and (cdr e) (string-match re (cdr e)))
22238 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22239 (safe "SREF"))
22240 (add-text-properties 0 3 (list 'sref sref) safe)
22241 (setcdr e (replace-match safe t t (cdr e)))))
22242 (while (string-match re string)
22243 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22244 (cdr e)))
22245 (setq string (replace-match rpl t t string))))
22246 (while (setq pchg (next-property-change pchg string))
22247 (let ((sref (get-text-property pchg 'sref string)))
22248 (when (and sref (string-match "SREF" string pchg))
22249 (setq string (replace-match sref t t string)))))
22250 string))
22252 (defun org-find-base-buffer-visiting (file)
22253 "Like `find-buffer-visiting' but always return the base buffer and
22254 not an indirect buffer."
22255 (let ((buf (or (get-file-buffer file)
22256 (find-buffer-visiting file))))
22257 (if buf
22258 (or (buffer-base-buffer buf) buf)
22259 nil)))
22261 ;;; TODO: Only called once, from ox-odt which should probably use
22262 ;;; org-export-inline-image-p or something.
22263 (defun org-file-image-p (file)
22264 "Return non-nil if FILE is an image."
22265 (save-match-data
22266 (string-match (image-file-name-regexp) file)))
22268 (defun org-get-cursor-date (&optional with-time)
22269 "Return the date at cursor in as a time.
22270 This works in the calendar and in the agenda, anywhere else it just
22271 returns the current time.
22272 If WITH-TIME is non-nil, returns the time of the event at point (in
22273 the agenda) or the current time of the day."
22274 (let (date day defd tp hod mod)
22275 (when with-time
22276 (setq tp (get-text-property (point) 'time))
22277 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22278 (setq hod (string-to-number (match-string 1 tp))
22279 mod (string-to-number (match-string 2 tp))))
22280 (or tp (let ((now (decode-time)))
22281 (setq hod (nth 2 now)
22282 mod (nth 1 now)))))
22283 (cond
22284 ((eq major-mode 'calendar-mode)
22285 (setq date (calendar-cursor-to-date)
22286 defd (encode-time 0 (or mod 0) (or hod 0)
22287 (nth 1 date) (nth 0 date) (nth 2 date))))
22288 ((eq major-mode 'org-agenda-mode)
22289 (setq day (get-text-property (point) 'day))
22290 (when day
22291 (setq date (calendar-gregorian-from-absolute day)
22292 defd (encode-time 0 (or mod 0) (or hod 0)
22293 (nth 1 date) (nth 0 date) (nth 2 date))))))
22294 (or defd (current-time))))
22296 (defun org-mark-subtree (&optional up)
22297 "Mark the current subtree.
22298 This puts point at the start of the current subtree, and mark at
22299 the end. If a numeric prefix UP is given, move up into the
22300 hierarchy of headlines by UP levels before marking the subtree."
22301 (interactive "P")
22302 (org-with-limited-levels
22303 (cond ((org-at-heading-p) (beginning-of-line))
22304 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22305 (t (outline-previous-visible-heading 1))))
22306 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22307 (if (called-interactively-p 'any)
22308 (call-interactively 'org-mark-element)
22309 (org-mark-element)))
22311 (defun org-file-newer-than-p (file time)
22312 "Non-nil if FILE is newer than TIME.
22313 FILE is a filename, as a string, TIME is a list of integers, as
22314 returned by, e.g., `current-time'."
22315 (and (file-exists-p file)
22316 ;; Only compare times up to whole seconds as some file-systems
22317 ;; (e.g. HFS+) do not retain any finer granularity. As
22318 ;; a consequence, make sure we return non-nil when the two
22319 ;; times are equal.
22320 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22321 (cl-subseq time 0 2)))))
22323 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22324 "Compile a SOURCE file using PROCESS.
22326 PROCESS is either a function or a list of shell commands, as
22327 strings. EXT is a file extension, without the leading dot, as
22328 a string. It is used to check if the process actually succeeded.
22330 PROCESS must create a file with the same base name and directory
22331 as SOURCE, but ending with EXT. The function then returns its
22332 filename. Otherwise, it raises an error. The error message can
22333 then be refined by providing string ERR-MSG, which is appended to
22334 the standard message.
22336 If PROCESS is a function, it is called with a single argument:
22337 the SOURCE file.
22339 If it is a list of commands, each of them is called using
22340 `shell-command'. By default, in each command, %b, %f, %F, %o and
22341 %O are replaced with, respectively, SOURCE base name, name, full
22342 name, directory and absolute output file name. It is possible,
22343 however, to use more place-holders by specifying them in optional
22344 argument SPEC, as an alist following the pattern
22346 (CHARACTER . REPLACEMENT-STRING).
22348 When PROCESS is a list of commands, optional argument LOG-BUF can
22349 be set to a buffer or a buffer name. `shell-command' then uses
22350 it for output."
22351 (let* ((base-name (file-name-base source))
22352 (full-name (file-truename source))
22353 (out-dir (or (file-name-directory source) "./"))
22354 (output (expand-file-name (concat base-name "." ext) out-dir))
22355 (time (current-time))
22356 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22357 (save-window-excursion
22358 (pcase process
22359 ((pred functionp) (funcall process (shell-quote-argument source)))
22360 ((pred consp)
22361 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22362 (spec (append spec
22363 `((?b . ,(shell-quote-argument base-name))
22364 (?f . ,(shell-quote-argument source))
22365 (?F . ,(shell-quote-argument full-name))
22366 (?o . ,(shell-quote-argument out-dir))
22367 (?O . ,(shell-quote-argument output))))))
22368 (dolist (command process)
22369 (shell-command (format-spec command spec) log-buf))
22370 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22371 (_ (error "No valid command to process %S%s" source err-msg))))
22372 ;; Check for process failure. Output file is expected to be
22373 ;; located in the same directory as SOURCE.
22374 (unless (org-file-newer-than-p output time)
22375 (error (format "File %S wasn't produced%s" output err-msg)))
22376 output))
22378 ;;; Indentation
22380 (defvar org-element-greater-elements)
22381 (defun org--get-expected-indentation (element contentsp)
22382 "Expected indentation column for current line, according to ELEMENT.
22383 ELEMENT is an element containing point. CONTENTSP is non-nil
22384 when indentation is to be computed according to contents of
22385 ELEMENT."
22386 (let ((type (org-element-type element))
22387 (start (org-element-property :begin element))
22388 (post-affiliated (org-element-property :post-affiliated element)))
22389 (org-with-wide-buffer
22390 (cond
22391 (contentsp
22392 (cl-case type
22393 ((diary-sexp footnote-definition) 0)
22394 ((headline inlinetask nil)
22395 (if (not org-adapt-indentation) 0
22396 (let ((level (org-current-level)))
22397 (if level (1+ level) 0))))
22398 ((item plain-list) (org-list-item-body-column post-affiliated))
22400 (goto-char start)
22401 (org-get-indentation))))
22402 ((memq type '(headline inlinetask nil))
22403 (if (org-match-line "[ \t]*$")
22404 (org--get-expected-indentation element t)
22406 ((memq type '(diary-sexp footnote-definition)) 0)
22407 ;; First paragraph of a footnote definition or an item.
22408 ;; Indent like parent.
22409 ((< (line-beginning-position) start)
22410 (org--get-expected-indentation
22411 (org-element-property :parent element) t))
22412 ;; At first line: indent according to previous sibling, if any,
22413 ;; ignoring footnote definitions and inline tasks, or parent's
22414 ;; contents.
22415 ((= (line-beginning-position) start)
22416 (catch 'exit
22417 (while t
22418 (if (= (point-min) start) (throw 'exit 0)
22419 (goto-char (1- start))
22420 (let* ((previous (org-element-at-point))
22421 (parent previous))
22422 (while (and parent (<= (org-element-property :end parent) start))
22423 (setq previous parent
22424 parent (org-element-property :parent parent)))
22425 (cond
22426 ((not previous) (throw 'exit 0))
22427 ((> (org-element-property :end previous) start)
22428 (throw 'exit (org--get-expected-indentation previous t)))
22429 ((memq (org-element-type previous)
22430 '(footnote-definition inlinetask))
22431 (setq start (org-element-property :begin previous)))
22432 (t (goto-char (org-element-property :begin previous))
22433 (throw 'exit
22434 (if (bolp) (org-get-indentation)
22435 ;; At first paragraph in an item or
22436 ;; a footnote definition.
22437 (org--get-expected-indentation
22438 (org-element-property :parent previous) t))))))))))
22439 ;; Otherwise, move to the first non-blank line above.
22441 (beginning-of-line)
22442 (let ((pos (point)))
22443 (skip-chars-backward " \r\t\n")
22444 (cond
22445 ;; Two blank lines end a footnote definition or a plain
22446 ;; list. When we indent an empty line after them, the
22447 ;; containing list or footnote definition is over, so it
22448 ;; qualifies as a previous sibling. Therefore, we indent
22449 ;; like its first line.
22450 ((and (memq type '(footnote-definition plain-list))
22451 (> (count-lines (point) pos) 2))
22452 (goto-char start)
22453 (org-get-indentation))
22454 ;; Line above is the first one of a paragraph at the
22455 ;; beginning of an item or a footnote definition. Indent
22456 ;; like parent.
22457 ((< (line-beginning-position) start)
22458 (org--get-expected-indentation
22459 (org-element-property :parent element) t))
22460 ;; Line above is the beginning of an element, i.e., point
22461 ;; was originally on the blank lines between element's start
22462 ;; and contents.
22463 ((= (line-beginning-position) post-affiliated)
22464 (org--get-expected-indentation element t))
22465 ;; POS is after contents in a greater element. Indent like
22466 ;; the beginning of the element.
22467 ((and (memq type org-element-greater-elements)
22468 (let ((cend (org-element-property :contents-end element)))
22469 (and cend (<= cend pos))))
22470 ;; As a special case, if point is at the end of a footnote
22471 ;; definition or an item, indent like the very last element
22472 ;; within. If that last element is an item, indent like
22473 ;; its contents.
22474 (if (memq type '(footnote-definition item plain-list))
22475 (let ((last (org-element-at-point)))
22476 (goto-char pos)
22477 (org--get-expected-indentation
22478 last (eq (org-element-type last) 'item)))
22479 (goto-char start)
22480 (org-get-indentation)))
22481 ;; In any other case, indent like the current line.
22482 (t (org-get-indentation)))))))))
22484 (defun org--align-node-property ()
22485 "Align node property at point.
22486 Alignment is done according to `org-property-format', which see."
22487 (when (save-excursion
22488 (beginning-of-line)
22489 (looking-at org-property-re))
22490 (replace-match
22491 (concat (match-string 4)
22492 (org-trim
22493 (format org-property-format (match-string 1) (match-string 3))))
22494 t t)))
22496 (defun org-indent-line ()
22497 "Indent line depending on context.
22499 Indentation is done according to the following rules:
22501 - Footnote definitions, diary sexps, headlines and inline tasks
22502 have to start at column 0.
22504 - On the very first line of an element, consider, in order, the
22505 next rules until one matches:
22507 1. If there's a sibling element before, ignoring footnote
22508 definitions and inline tasks, indent like its first line.
22510 2. If element has a parent, indent like its contents. More
22511 precisely, if parent is an item, indent after the
22512 description part, if any, or the bullet (see
22513 `org-list-description-max-indent'). Else, indent like
22514 parent's first line.
22516 3. Otherwise, indent relatively to current level, if
22517 `org-adapt-indentation' is non-nil, or to left margin.
22519 - On a blank line at the end of an element, indent according to
22520 the type of the element. More precisely
22522 1. If element is a plain list, an item, or a footnote
22523 definition, indent like the very last element within.
22525 2. If element is a paragraph, indent like its last non blank
22526 line.
22528 3. Otherwise, indent like its very first line.
22530 - In the code part of a source block, use language major mode
22531 to indent current line if `org-src-tab-acts-natively' is
22532 non-nil. If it is nil, do nothing.
22534 - Otherwise, indent like the first non-blank line above.
22536 The function doesn't indent an item as it could break the whole
22537 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22538 `\\[org-shiftmetaright]'.
22540 Also align node properties according to `org-property-format'."
22541 (interactive)
22542 (cond
22543 (orgstruct-is-++
22544 (let ((indent-line-function
22545 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22546 (indent-according-to-mode)))
22547 ((org-at-heading-p) 'noindent)
22549 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22550 (type (org-element-type element)))
22551 (cond ((and (memq type '(plain-list item))
22552 (= (line-beginning-position)
22553 (org-element-property :post-affiliated element)))
22554 'noindent)
22555 ((and (eq type 'latex-environment)
22556 (>= (point) (org-element-property :post-affiliated element))
22557 (< (point) (org-with-wide-buffer
22558 (goto-char (org-element-property :end element))
22559 (skip-chars-backward " \r\t\n")
22560 (line-beginning-position 2))))
22561 'noindent)
22562 ((and (eq type 'src-block)
22563 org-src-tab-acts-natively
22564 (> (line-beginning-position)
22565 (org-element-property :post-affiliated element))
22566 (< (line-beginning-position)
22567 (org-with-wide-buffer
22568 (goto-char (org-element-property :end element))
22569 (skip-chars-backward " \r\t\n")
22570 (line-beginning-position))))
22571 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22573 (let ((column (org--get-expected-indentation element nil)))
22574 ;; Preserve current column.
22575 (if (<= (current-column) (current-indentation))
22576 (indent-line-to column)
22577 (save-excursion (indent-line-to column))))
22578 ;; Align node property. Also preserve current column.
22579 (when (eq type 'node-property)
22580 (let ((column (current-column)))
22581 (org--align-node-property)
22582 (org-move-to-column column)))))))))
22584 (defun org-indent-region (start end)
22585 "Indent each non-blank line in the region.
22586 Called from a program, START and END specify the region to
22587 indent. The function will not indent contents of example blocks,
22588 verse blocks and export blocks as leading white spaces are
22589 assumed to be significant there."
22590 (interactive "r")
22591 (save-excursion
22592 (goto-char start)
22593 (skip-chars-forward " \r\t\n")
22594 (unless (eobp) (beginning-of-line))
22595 (let ((indent-to
22596 (lambda (ind pos)
22597 ;; Set IND as indentation for all lines between point and
22598 ;; POS. Blank lines are ignored. Leave point after POS
22599 ;; once done.
22600 (let ((limit (copy-marker pos)))
22601 (while (< (point) limit)
22602 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22603 (forward-line))
22604 (set-marker limit nil))))
22605 (end (copy-marker end)))
22606 (while (< (point) end)
22607 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22608 (let* ((element (org-element-at-point))
22609 (type (org-element-type element))
22610 (element-end (copy-marker (org-element-property :end element)))
22611 (ind (org--get-expected-indentation element nil)))
22612 (cond
22613 ;; Element indented as a single block. Example blocks
22614 ;; preserving indentation are a special case since the
22615 ;; "contents" must not be indented whereas the block
22616 ;; boundaries can.
22617 ((or (memq type '(export-block latex-environment))
22618 (and (eq type 'example-block)
22619 (not
22620 (or org-src-preserve-indentation
22621 (org-element-property :preserve-indent element)))))
22622 (let ((offset (- ind (org-get-indentation))))
22623 (unless (zerop offset)
22624 (indent-rigidly (org-element-property :begin element)
22625 (org-element-property :end element)
22626 offset)))
22627 (goto-char element-end))
22628 ;; Elements indented line wise. Be sure to exclude
22629 ;; example blocks (preserving indentation) and source
22630 ;; blocks from this category as they are treated
22631 ;; specially later.
22632 ((or (memq type '(paragraph table table-row))
22633 (not (or (org-element-property :contents-begin element)
22634 (memq type '(example-block src-block)))))
22635 (when (eq type 'node-property)
22636 (org--align-node-property)
22637 (beginning-of-line))
22638 (funcall indent-to ind (min element-end end)))
22639 ;; Elements consisting of three parts: before the
22640 ;; contents, the contents, and after the contents. The
22641 ;; contents are treated specially, according to the
22642 ;; element type, or not indented at all. Other parts are
22643 ;; indented as a single block.
22645 (let* ((post (copy-marker
22646 (org-element-property :post-affiliated element)))
22647 (cbeg
22648 (copy-marker
22649 (cond
22650 ((not (org-element-property :contents-begin element))
22651 ;; Fake contents for source blocks.
22652 (org-with-wide-buffer
22653 (goto-char post)
22654 (line-beginning-position 2)))
22655 ((memq type '(footnote-definition item plain-list))
22656 ;; Contents in these elements could start on
22657 ;; the same line as the beginning of the
22658 ;; element. Make sure we start indenting
22659 ;; from the second line.
22660 (org-with-wide-buffer
22661 (goto-char post)
22662 (end-of-line)
22663 (skip-chars-forward " \r\t\n")
22664 (if (eobp) (point) (line-beginning-position))))
22665 (t (org-element-property :contents-begin element)))))
22666 (cend (copy-marker
22667 (or (org-element-property :contents-end element)
22668 ;; Fake contents for source blocks.
22669 (org-with-wide-buffer
22670 (goto-char element-end)
22671 (skip-chars-backward " \r\t\n")
22672 (line-beginning-position)))
22673 t)))
22674 ;; Do not change items indentation individually as it
22675 ;; might break the list as a whole. On the other
22676 ;; hand, when at a plain list, indent it as a whole.
22677 (cond ((eq type 'plain-list)
22678 (let ((offset (- ind (org-get-indentation))))
22679 (unless (zerop offset)
22680 (indent-rigidly (org-element-property :begin element)
22681 (org-element-property :end element)
22682 offset))
22683 (goto-char cbeg)))
22684 ((eq type 'item) (goto-char cbeg))
22685 (t (funcall indent-to ind (min cbeg end))))
22686 (when (< (point) end)
22687 (cl-case type
22688 ((example-block verse-block))
22689 (src-block
22690 ;; In a source block, indent source code
22691 ;; according to language major mode, but only if
22692 ;; `org-src-tab-acts-natively' is non-nil.
22693 (when (and (< (point) end) org-src-tab-acts-natively)
22694 (ignore-errors
22695 (org-babel-do-in-edit-buffer
22696 (indent-region (point-min) (point-max))))))
22697 (t (org-indent-region (point) (min cend end))))
22698 (goto-char (min cend end))
22699 (when (< (point) end)
22700 (funcall indent-to ind (min element-end end))))
22701 (set-marker post nil)
22702 (set-marker cbeg nil)
22703 (set-marker cend nil))))
22704 (set-marker element-end nil))))
22705 (set-marker end nil))))
22707 (defun org-indent-drawer ()
22708 "Indent the drawer at point."
22709 (interactive)
22710 (unless (save-excursion
22711 (beginning-of-line)
22712 (looking-at-p org-drawer-regexp))
22713 (user-error "Not at a drawer"))
22714 (let ((element (org-element-at-point)))
22715 (unless (memq (org-element-type element) '(drawer property-drawer))
22716 (user-error "Not at a drawer"))
22717 (org-with-wide-buffer
22718 (org-indent-region (org-element-property :begin element)
22719 (org-element-property :end element))))
22720 (message "Drawer at point indented"))
22722 (defun org-indent-block ()
22723 "Indent the block at point."
22724 (interactive)
22725 (unless (save-excursion
22726 (beginning-of-line)
22727 (let ((case-fold-search t))
22728 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22729 (user-error "Not at a block"))
22730 (let ((element (org-element-at-point)))
22731 (unless (memq (org-element-type element)
22732 '(comment-block center-block dynamic-block example-block
22733 export-block quote-block special-block
22734 src-block verse-block))
22735 (user-error "Not at a block"))
22736 (org-with-wide-buffer
22737 (org-indent-region (org-element-property :begin element)
22738 (org-element-property :end element))))
22739 (message "Block at point indented"))
22742 ;;; Filling
22744 ;; We use our own fill-paragraph and auto-fill functions.
22746 ;; `org-fill-paragraph' relies on adaptive filling and context
22747 ;; checking. Appropriate `fill-prefix' is computed with
22748 ;; `org-adaptive-fill-function'.
22750 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22751 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22752 ;; `org-adaptive-fill-function' value. Internally,
22753 ;; `org-comment-line-break-function' breaks the line.
22755 ;; `org-setup-filling' installs filling and auto-filling related
22756 ;; variables during `org-mode' initialization.
22758 (defvar org-element-paragraph-separate) ; org-element.el
22759 (defun org-setup-filling ()
22760 (require 'org-element)
22761 ;; Prevent auto-fill from inserting unwanted new items.
22762 (when (boundp 'fill-nobreak-predicate)
22763 (setq-local
22764 fill-nobreak-predicate
22765 (org-uniquify
22766 (append fill-nobreak-predicate
22767 '(org-fill-line-break-nobreak-p
22768 org-fill-n-macro-as-item-nobreak-p
22769 org-fill-paragraph-with-timestamp-nobreak-p)))))
22770 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22771 (setq-local paragraph-start paragraph-ending)
22772 (setq-local paragraph-separate paragraph-ending))
22773 (setq-local fill-paragraph-function 'org-fill-paragraph)
22774 (setq-local auto-fill-inhibit-regexp nil)
22775 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22776 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22777 (setq-local comment-line-break-function 'org-comment-line-break-function))
22779 (defun org-fill-line-break-nobreak-p ()
22780 "Non-nil when a new line at point would create an Org line break."
22781 (save-excursion
22782 (skip-chars-backward "[ \t]")
22783 (skip-chars-backward "\\\\")
22784 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22786 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22787 "Non-nil when a new line at point would split a timestamp."
22788 (and (org-at-timestamp-p 'lax)
22789 (not (looking-at org-ts-regexp-both))))
22791 (defun org-fill-n-macro-as-item-nobreak-p ()
22792 "Non-nil when a new line at point would create a new list."
22793 ;; During export, a "n" macro followed by a dot or a closing
22794 ;; parenthesis can end up being parsed as a new list item.
22795 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22797 (declare-function message-in-body-p "message" ())
22798 (defvar orgtbl-line-start-regexp) ; From org-table.el
22799 (defun org-adaptive-fill-function ()
22800 "Compute a fill prefix for the current line.
22801 Return fill prefix, as a string, or nil if current line isn't
22802 meant to be filled. For convenience, if `adaptive-fill-regexp'
22803 matches in paragraphs or comments, use it."
22804 (catch 'exit
22805 (when (derived-mode-p 'message-mode)
22806 (save-excursion
22807 (beginning-of-line)
22808 (cond ((not (message-in-body-p)) (throw 'exit nil))
22809 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22810 ((looking-at message-cite-prefix-regexp)
22811 (throw 'exit (match-string-no-properties 0)))
22812 ((looking-at org-outline-regexp)
22813 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22814 (org-with-wide-buffer
22815 (unless (org-at-heading-p)
22816 (let* ((p (line-beginning-position))
22817 (element (save-excursion
22818 (beginning-of-line)
22819 (org-element-at-point)))
22820 (type (org-element-type element))
22821 (post-affiliated (org-element-property :post-affiliated element)))
22822 (unless (< p post-affiliated)
22823 (cl-case type
22824 (comment
22825 (save-excursion
22826 (beginning-of-line)
22827 (looking-at "[ \t]*")
22828 (concat (match-string 0) "# ")))
22829 (footnote-definition "")
22830 ((item plain-list)
22831 (make-string (org-list-item-body-column post-affiliated) ?\s))
22832 (paragraph
22833 ;; Fill prefix is usually the same as the current line,
22834 ;; unless the paragraph is at the beginning of an item.
22835 (let ((parent (org-element-property :parent element)))
22836 (save-excursion
22837 (beginning-of-line)
22838 (cond ((eq (org-element-type parent) 'item)
22839 (make-string (org-list-item-body-column
22840 (org-element-property :begin parent))
22841 ?\s))
22842 ((and adaptive-fill-regexp
22843 ;; Locally disable
22844 ;; `adaptive-fill-function' to let
22845 ;; `fill-context-prefix' handle
22846 ;; `adaptive-fill-regexp' variable.
22847 (let (adaptive-fill-function)
22848 (fill-context-prefix
22849 post-affiliated
22850 (org-element-property :end element)))))
22851 ((looking-at "[ \t]+") (match-string 0))
22852 (t "")))))
22853 (comment-block
22854 ;; Only fill contents if P is within block boundaries.
22855 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22856 (forward-line)
22857 (point)))
22858 (cend (save-excursion
22859 (goto-char (org-element-property :end element))
22860 (skip-chars-backward " \r\t\n")
22861 (line-beginning-position))))
22862 (when (and (>= p cbeg) (< p cend))
22863 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22864 (match-string 0)
22865 "")))))))))))
22867 (declare-function message-goto-body "message" ())
22868 (defvar message-cite-prefix-regexp) ; From message.el
22870 (defun org-fill-element (&optional justify)
22871 "Fill element at point, when applicable.
22873 This function only applies to comment blocks, comments, example
22874 blocks and paragraphs. Also, as a special case, re-align table
22875 when point is at one.
22877 If JUSTIFY is non-nil (interactively, with prefix argument),
22878 justify as well. If `sentence-end-double-space' is non-nil, then
22879 period followed by one space does not end a sentence, so don't
22880 break a line there. The variable `fill-column' controls the
22881 width for filling.
22883 For convenience, when point is at a plain list, an item or
22884 a footnote definition, try to fill the first paragraph within."
22885 (with-syntax-table org-mode-transpose-word-syntax-table
22886 ;; Move to end of line in order to get the first paragraph within
22887 ;; a plain list or a footnote definition.
22888 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22889 ;; First check if point is in a blank line at the beginning of
22890 ;; the buffer. In that case, ignore filling.
22891 (cl-case (org-element-type element)
22892 ;; Use major mode filling function is src blocks.
22893 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22894 ;; Align Org tables, leave table.el tables as-is.
22895 (table-row (org-table-align) t)
22896 (table
22897 (when (eq (org-element-property :type element) 'org)
22898 (save-excursion
22899 (goto-char (org-element-property :post-affiliated element))
22900 (org-table-align)))
22902 (paragraph
22903 ;; Paragraphs may contain `line-break' type objects.
22904 (let ((beg (max (point-min)
22905 (org-element-property :contents-begin element)))
22906 (end (min (point-max)
22907 (org-element-property :contents-end element))))
22908 ;; Do nothing if point is at an affiliated keyword.
22909 (if (< (line-end-position) beg) t
22910 (when (derived-mode-p 'message-mode)
22911 ;; In `message-mode', do not fill following citation
22912 ;; in current paragraph nor text before message body.
22913 (let ((body-start (save-excursion (message-goto-body))))
22914 (when body-start (setq beg (max body-start beg))))
22915 (when (save-excursion
22916 (re-search-forward
22917 (concat "^" message-cite-prefix-regexp) end t))
22918 (setq end (match-beginning 0))))
22919 ;; Fill paragraph, taking line breaks into account.
22920 (save-excursion
22921 (goto-char beg)
22922 (let ((cuts (list beg)))
22923 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22924 (when (eq 'line-break
22925 (org-element-type
22926 (save-excursion (backward-char)
22927 (org-element-context))))
22928 (push (point) cuts)))
22929 (dolist (c (delq end cuts))
22930 (fill-region-as-paragraph c end justify)
22931 (setq end c))))
22932 t)))
22933 ;; Contents of `comment-block' type elements should be
22934 ;; filled as plain text, but only if point is within block
22935 ;; markers.
22936 (comment-block
22937 (let* ((case-fold-search t)
22938 (beg (save-excursion
22939 (goto-char (org-element-property :begin element))
22940 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22941 (forward-line)
22942 (point)))
22943 (end (save-excursion
22944 (goto-char (org-element-property :end element))
22945 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22946 (line-beginning-position))))
22947 (if (or (< (point) beg) (> (point) end)) t
22948 (fill-region-as-paragraph
22949 (save-excursion (end-of-line)
22950 (re-search-backward "^[ \t]*$" beg 'move)
22951 (line-beginning-position))
22952 (save-excursion (beginning-of-line)
22953 (re-search-forward "^[ \t]*$" end 'move)
22954 (line-beginning-position))
22955 justify))))
22956 ;; Fill comments.
22957 (comment
22958 (let ((begin (org-element-property :post-affiliated element))
22959 (end (org-element-property :end element)))
22960 (when (and (>= (point) begin) (<= (point) end))
22961 (let ((begin (save-excursion
22962 (end-of-line)
22963 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22964 (progn (forward-line) (point))
22965 begin)))
22966 (end (save-excursion
22967 (end-of-line)
22968 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22969 (1- (line-beginning-position))
22970 (skip-chars-backward " \r\t\n")
22971 (line-end-position)))))
22972 ;; Do not fill comments when at a blank line.
22973 (when (> end begin)
22974 (let ((fill-prefix
22975 (save-excursion
22976 (beginning-of-line)
22977 (looking-at "[ \t]*#")
22978 (let ((comment-prefix (match-string 0)))
22979 (goto-char (match-end 0))
22980 (if (looking-at adaptive-fill-regexp)
22981 (concat comment-prefix (match-string 0))
22982 (concat comment-prefix " "))))))
22983 (save-excursion
22984 (fill-region-as-paragraph begin end justify))))))
22986 ;; Ignore every other element.
22987 (otherwise t)))))
22989 (defun org-fill-paragraph (&optional justify region)
22990 "Fill element at point, when applicable.
22992 This function only applies to comment blocks, comments, example
22993 blocks and paragraphs. Also, as a special case, re-align table
22994 when point is at one.
22996 For convenience, when point is at a plain list, an item or
22997 a footnote definition, try to fill the first paragraph within.
22999 If JUSTIFY is non-nil (interactively, with prefix argument),
23000 justify as well. If `sentence-end-double-space' is non-nil, then
23001 period followed by one space does not end a sentence, so don't
23002 break a line there. The variable `fill-column' controls the
23003 width for filling.
23005 The REGION argument is non-nil if called interactively; in that
23006 case, if Transient Mark mode is enabled and the mark is active,
23007 fill each of the elements in the active region, instead of just
23008 filling the current element."
23009 (interactive (progn
23010 (barf-if-buffer-read-only)
23011 (list (if current-prefix-arg 'full) t)))
23012 (cond
23013 ((and (derived-mode-p 'message-mode)
23014 (or (not (message-in-body-p))
23015 (save-excursion (move-beginning-of-line 1)
23016 (looking-at message-cite-prefix-regexp))))
23017 ;; First ensure filling is correct in message-mode.
23018 (let ((fill-paragraph-function
23019 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23020 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23021 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23022 (paragraph-separate
23023 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23024 (fill-paragraph nil)))
23025 ((and region transient-mark-mode mark-active
23026 (not (eq (region-beginning) (region-end))))
23027 (let ((origin (point-marker))
23028 (start (region-beginning)))
23029 (unwind-protect
23030 (progn
23031 (goto-char (region-end))
23032 (while (> (point) start)
23033 (org-backward-paragraph)
23034 (org-fill-element justify)))
23035 (goto-char origin)
23036 (set-marker origin nil))))
23037 (t (org-fill-element justify))))
23038 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23040 (defun org-auto-fill-function ()
23041 "Auto-fill function."
23042 ;; Check if auto-filling is meaningful.
23043 (let ((fc (current-fill-column)))
23044 (when (and fc (> (current-column) fc))
23045 (let* ((fill-prefix (org-adaptive-fill-function))
23046 ;; Enforce empty fill prefix, if required. Otherwise, it
23047 ;; will be computed again.
23048 (adaptive-fill-mode (not (equal fill-prefix ""))))
23049 (when fill-prefix (do-auto-fill))))))
23051 (defun org-comment-line-break-function (&optional soft)
23052 "Break line at point and indent, continuing comment if within one.
23053 The inserted newline is marked hard if variable
23054 `use-hard-newlines' is true, unless optional argument SOFT is
23055 non-nil."
23056 (if soft (insert-and-inherit ?\n) (newline 1))
23057 (save-excursion (forward-char -1) (delete-horizontal-space))
23058 (delete-horizontal-space)
23059 (indent-to-left-margin)
23060 (insert-before-markers-and-inherit fill-prefix))
23063 ;;; Fixed Width Areas
23065 (defun org-toggle-fixed-width ()
23066 "Toggle fixed-width markup.
23068 Add or remove fixed-width markup on current line, whenever it
23069 makes sense. Return an error otherwise.
23071 If a region is active and if it contains only fixed-width areas
23072 or blank lines, remove all fixed-width markup in it. If the
23073 region contains anything else, convert all non-fixed-width lines
23074 to fixed-width ones.
23076 Blank lines at the end of the region are ignored unless the
23077 region only contains such lines."
23078 (interactive)
23079 (if (not (org-region-active-p))
23080 ;; No region:
23082 ;; Remove fixed width marker only in a fixed-with element.
23084 ;; Add fixed width maker in paragraphs, in blank lines after
23085 ;; elements or at the beginning of a headline or an inlinetask,
23086 ;; and before any one-line elements (e.g., a clock).
23087 (progn
23088 (beginning-of-line)
23089 (let* ((element (org-element-at-point))
23090 (type (org-element-type element)))
23091 (cond
23092 ((and (eq type 'fixed-width)
23093 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23094 (replace-match
23095 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23096 ((and (memq type '(babel-call clock comment diary-sexp headline
23097 horizontal-rule keyword paragraph
23098 planning))
23099 (<= (org-element-property :post-affiliated element) (point)))
23100 (skip-chars-forward " \t")
23101 (insert ": "))
23102 ((and (looking-at-p "[ \t]*$")
23103 (or (eq type 'inlinetask)
23104 (save-excursion
23105 (skip-chars-forward " \r\t\n")
23106 (<= (org-element-property :end element) (point)))))
23107 (delete-region (point) (line-end-position))
23108 (org-indent-line)
23109 (insert ": "))
23110 (t (user-error "Cannot insert a fixed-width line here")))))
23111 ;; Region active.
23112 (let* ((begin (save-excursion
23113 (goto-char (region-beginning))
23114 (line-beginning-position)))
23115 (end (copy-marker
23116 (save-excursion
23117 (goto-char (region-end))
23118 (unless (eolp) (beginning-of-line))
23119 (if (save-excursion (re-search-backward "\\S-" begin t))
23120 (progn (skip-chars-backward " \r\t\n") (point))
23121 (point)))))
23122 (all-fixed-width-p
23123 (catch 'not-all-p
23124 (save-excursion
23125 (goto-char begin)
23126 (skip-chars-forward " \r\t\n")
23127 (when (eobp) (throw 'not-all-p nil))
23128 (while (< (point) end)
23129 (let ((element (org-element-at-point)))
23130 (if (eq (org-element-type element) 'fixed-width)
23131 (goto-char (org-element-property :end element))
23132 (throw 'not-all-p nil))))
23133 t))))
23134 (if all-fixed-width-p
23135 (save-excursion
23136 (goto-char begin)
23137 (while (< (point) end)
23138 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23139 (replace-match
23140 "" nil nil nil
23141 (if (= (line-end-position) (match-end 0)) 0 1)))
23142 (forward-line)))
23143 (let ((min-ind (point-max)))
23144 ;; Find minimum indentation across all lines.
23145 (save-excursion
23146 (goto-char begin)
23147 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23148 (setq min-ind 0)
23149 (catch 'zerop
23150 (while (< (point) end)
23151 (unless (looking-at-p "[ \t]*$")
23152 (let ((ind (org-get-indentation)))
23153 (setq min-ind (min min-ind ind))
23154 (when (zerop ind) (throw 'zerop t))))
23155 (forward-line)))))
23156 ;; Loop over all lines and add fixed-width markup everywhere
23157 ;; but in fixed-width lines.
23158 (save-excursion
23159 (goto-char begin)
23160 (while (< (point) end)
23161 (cond
23162 ((org-at-heading-p)
23163 (insert ": ")
23164 (forward-line)
23165 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23166 (insert ":")
23167 (forward-line)))
23168 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23169 (let* ((element (org-element-at-point))
23170 (element-end (org-element-property :end element)))
23171 (if (eq (org-element-type element) 'fixed-width)
23172 (progn (goto-char element-end)
23173 (skip-chars-backward " \r\t\n")
23174 (forward-line))
23175 (let ((limit (min end element-end)))
23176 (while (< (point) limit)
23177 (org-move-to-column min-ind t)
23178 (insert ": ")
23179 (forward-line))))))
23181 (org-move-to-column min-ind t)
23182 (insert ": ")
23183 (forward-line)))))))
23184 (set-marker end nil))))
23187 ;;; Comments
23189 ;; Org comments syntax is quite complex. It requires the entire line
23190 ;; to be just a comment. Also, even with the right syntax at the
23191 ;; beginning of line, some elements (e.g., verse-block or
23192 ;; example-block) don't accept comments. Usual Emacs comment commands
23193 ;; cannot cope with those requirements. Therefore, Org replaces them.
23195 ;; Org still relies on `comment-dwim', but cannot trust
23196 ;; `comment-only-p'. So, `comment-region-function' and
23197 ;; `uncomment-region-function' both point
23198 ;; to`org-comment-or-uncomment-region'. Eventually,
23199 ;; `org-insert-comment' takes care of insertion of comments at the
23200 ;; beginning of line.
23202 ;; `org-setup-comments-handling' install comments related variables
23203 ;; during `org-mode' initialization.
23205 (defun org-setup-comments-handling ()
23206 (interactive)
23207 (setq-local comment-use-syntax nil)
23208 (setq-local comment-start "# ")
23209 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23210 (setq-local comment-insert-comment-function 'org-insert-comment)
23211 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23212 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23214 (defun org-insert-comment ()
23215 "Insert an empty comment above current line.
23216 If the line is empty, insert comment at its beginning. When
23217 point is within a source block, comment according to the related
23218 major mode."
23219 (if (let ((element (org-element-at-point)))
23220 (and (eq (org-element-type element) 'src-block)
23221 (< (save-excursion
23222 (goto-char (org-element-property :post-affiliated element))
23223 (line-end-position))
23224 (point))
23225 (> (save-excursion
23226 (goto-char (org-element-property :end element))
23227 (skip-chars-backward " \r\t\n")
23228 (line-beginning-position))
23229 (point))))
23230 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23231 (beginning-of-line)
23232 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23233 (open-line 1))
23234 (org-indent-line)
23235 (insert "# ")))
23237 (defvar comment-empty-lines) ; From newcomment.el.
23238 (defun org-comment-or-uncomment-region (beg end &rest _)
23239 "Comment or uncomment each non-blank line in the region.
23240 Uncomment each non-blank line between BEG and END if it only
23241 contains commented lines. Otherwise, comment them. If region is
23242 strictly within a source block, use appropriate comment syntax."
23243 (if (let ((element (org-element-at-point)))
23244 (and (eq (org-element-type element) 'src-block)
23245 (< (save-excursion
23246 (goto-char (org-element-property :post-affiliated element))
23247 (line-end-position))
23248 beg)
23249 (>= (save-excursion
23250 (goto-char (org-element-property :end element))
23251 (skip-chars-backward " \r\t\n")
23252 (line-beginning-position))
23253 end)))
23254 ;; Translate region boundaries for the Org buffer to the source
23255 ;; buffer.
23256 (let ((offset (- end beg)))
23257 (save-excursion
23258 (goto-char beg)
23259 (org-babel-do-in-edit-buffer
23260 (comment-or-uncomment-region (point) (+ offset (point))))))
23261 (save-restriction
23262 ;; Restrict region
23263 (narrow-to-region (save-excursion (goto-char beg)
23264 (skip-chars-forward " \r\t\n" end)
23265 (line-beginning-position))
23266 (save-excursion (goto-char end)
23267 (skip-chars-backward " \r\t\n" beg)
23268 (line-end-position)))
23269 (let ((uncommentp
23270 ;; UNCOMMENTP is non-nil when every non blank line between
23271 ;; BEG and END is a comment.
23272 (save-excursion
23273 (goto-char (point-min))
23274 (while (and (not (eobp))
23275 (let ((element (org-element-at-point)))
23276 (and (eq (org-element-type element) 'comment)
23277 (goto-char (min (point-max)
23278 (org-element-property
23279 :end element)))))))
23280 (eobp))))
23281 (if uncommentp
23282 ;; Only blank lines and comments in region: uncomment it.
23283 (save-excursion
23284 (goto-char (point-min))
23285 (while (not (eobp))
23286 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23287 (replace-match "" nil nil nil 1))
23288 (forward-line)))
23289 ;; Comment each line in region.
23290 (let ((min-indent (point-max)))
23291 ;; First find the minimum indentation across all lines.
23292 (save-excursion
23293 (goto-char (point-min))
23294 (while (and (not (eobp)) (not (zerop min-indent)))
23295 (unless (looking-at "[ \t]*$")
23296 (setq min-indent (min min-indent (current-indentation))))
23297 (forward-line)))
23298 ;; Then loop over all lines.
23299 (save-excursion
23300 (goto-char (point-min))
23301 (while (not (eobp))
23302 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23303 ;; Don't get fooled by invisible text (e.g. link path)
23304 ;; when moving to column MIN-INDENT.
23305 (let ((buffer-invisibility-spec nil))
23306 (org-move-to-column min-indent t))
23307 (insert comment-start))
23308 (forward-line)))))))))
23310 (defun org-comment-dwim (_arg)
23311 "Call `comment-dwim' within a source edit buffer if needed."
23312 (interactive "*P")
23313 (if (org-in-src-block-p)
23314 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23315 (call-interactively 'comment-dwim)))
23318 ;;; Timestamps API
23320 ;; This section contains tools to operate on timestamp objects, as
23321 ;; returned by, e.g. `org-element-context'.
23323 (defun org-timestamp--to-internal-time (timestamp &optional end)
23324 "Encode TIMESTAMP object into Emacs internal time.
23325 Use end of date range or time range when END is non-nil."
23326 (apply #'encode-time
23327 (cons 0
23328 (mapcar
23329 (lambda (prop) (or (org-element-property prop timestamp) 0))
23330 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23331 '(:minute-start :hour-start :day-start :month-start
23332 :year-start))))))
23334 (defun org-timestamp-has-time-p (timestamp)
23335 "Non-nil when TIMESTAMP has a time specified."
23336 (org-element-property :hour-start timestamp))
23338 (defun org-timestamp-format (timestamp format &optional end utc)
23339 "Format a TIMESTAMP object into a string.
23341 FORMAT is a format specifier to be passed to
23342 `format-time-string'.
23344 When optional argument END is non-nil, use end of date-range or
23345 time-range, if possible.
23347 When optional argument UTC is non-nil, time will be expressed as
23348 Universal Time."
23349 (format-time-string
23350 format (org-timestamp--to-internal-time timestamp end)
23351 (and utc t)))
23353 (defun org-timestamp-split-range (timestamp &optional end)
23354 "Extract a TIMESTAMP object from a date or time range.
23356 END, when non-nil, means extract the end of the range.
23357 Otherwise, extract its start.
23359 Return a new timestamp object."
23360 (let ((type (org-element-property :type timestamp)))
23361 (if (memq type '(active inactive diary)) timestamp
23362 (let ((split-ts (org-element-copy timestamp)))
23363 ;; Set new type.
23364 (org-element-put-property
23365 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23366 ;; Copy start properties over end properties if END is
23367 ;; non-nil. Otherwise, copy end properties over `start' ones.
23368 (let ((p-alist '((:minute-start . :minute-end)
23369 (:hour-start . :hour-end)
23370 (:day-start . :day-end)
23371 (:month-start . :month-end)
23372 (:year-start . :year-end))))
23373 (dolist (p-cell p-alist)
23374 (org-element-put-property
23375 split-ts
23376 (funcall (if end #'car #'cdr) p-cell)
23377 (org-element-property
23378 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23379 ;; Eventually refresh `:raw-value'.
23380 (org-element-put-property split-ts :raw-value nil)
23381 (org-element-put-property
23382 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23384 (defun org-timestamp-translate (timestamp &optional boundary)
23385 "Translate TIMESTAMP object to custom format.
23387 Format string is defined in `org-time-stamp-custom-formats',
23388 which see.
23390 When optional argument BOUNDARY is non-nil, it is either the
23391 symbol `start' or `end'. In this case, only translate the
23392 starting or ending part of TIMESTAMP if it is a date or time
23393 range. Otherwise, translate both parts.
23395 Return timestamp as-is if `org-display-custom-times' is nil or if
23396 it has a `diary' type."
23397 (let ((type (org-element-property :type timestamp)))
23398 (if (or (not org-display-custom-times) (eq type 'diary))
23399 (org-element-interpret-data timestamp)
23400 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23401 org-time-stamp-custom-formats)))
23402 (if (and (not boundary) (memq type '(active-range inactive-range)))
23403 (concat (org-timestamp-format timestamp fmt)
23404 "--"
23405 (org-timestamp-format timestamp fmt t))
23406 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23410 ;;; Other stuff.
23412 (defvar reftex-docstruct-symbol)
23413 (defvar org--rds)
23415 (defun org-reftex-citation ()
23416 "Use reftex-citation to insert a citation into the buffer.
23417 This looks for a line like
23419 #+BIBLIOGRAPHY: foo plain option:-d
23421 and derives from it that foo.bib is the bibliography file relevant
23422 for this document. It then installs the necessary environment for RefTeX
23423 to work in this buffer and calls `reftex-citation' to insert a citation
23424 into the buffer.
23426 Export of such citations to both LaTeX and HTML is handled by the contributed
23427 package ox-bibtex by Taru Karttunen."
23428 (interactive)
23429 (let ((reftex-docstruct-symbol 'org--rds)
23430 org--rds bib)
23431 (org-with-wide-buffer
23432 (let ((case-fold-search t)
23433 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23434 (if (not (save-excursion
23435 (or (re-search-forward re nil t)
23436 (re-search-backward re nil t))))
23437 (user-error "No bibliography defined in file")
23438 (setq bib (concat (match-string 1) ".bib")
23439 org--rds (list (list 'bib bib))))))
23440 (call-interactively 'reftex-citation)))
23442 ;;;; Functions extending outline functionality
23444 (defun org-beginning-of-line (&optional n)
23445 "Go to the beginning of the current visible line.
23447 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23448 tags on the first attempt, and only move to after the tags when
23449 the cursor is already beyond the end of the headline.
23451 With argument N not nil or 1, move forward N - 1 lines first."
23452 (interactive "^p")
23453 (let ((origin (point))
23454 (special (pcase org-special-ctrl-a/e
23455 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23456 deactivate-mark)
23457 ;; First move to a visible line.
23458 (if (bound-and-true-p visual-line-mode)
23459 (beginning-of-visual-line n)
23460 (move-beginning-of-line n)
23461 ;; `move-beginning-of-line' may leave point after invisible
23462 ;; characters if line starts with such of these (e.g., with
23463 ;; a link at column 0). Really move to the beginning of the
23464 ;; current visible line.
23465 (beginning-of-line))
23466 (cond
23467 ;; No special behavior. Point is already at the beginning of
23468 ;; a line, logical or visual.
23469 ((not special))
23470 ;; `beginning-of-visual-line' left point before logical beginning
23471 ;; of line: point is at the beginning of a visual line. Bail
23472 ;; out.
23473 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23474 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23475 ;; At a headline, special position is before the title, but
23476 ;; after any TODO keyword or priority cookie.
23477 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23478 (line-end-position)))
23479 (bol (point)))
23480 (if (eq special 'reversed)
23481 (when (and (= origin bol) (eq last-command this-command))
23482 (goto-char refpos))
23483 (when (or (> origin refpos) (= origin bol))
23484 (goto-char refpos)))))
23485 ((and (looking-at org-list-full-item-re)
23486 (memq (org-element-type (save-match-data (org-element-at-point)))
23487 '(item plain-list)))
23488 ;; Set special position at first white space character after
23489 ;; bullet, and check-box, if any.
23490 (let ((after-bullet
23491 (let ((box (match-end 3)))
23492 (cond ((not box) (match-end 1))
23493 ((eq (char-after box) ?\s) (1+ box))
23494 (t box)))))
23495 (if (eq special 'reversed)
23496 (when (and (= (point) origin) (eq last-command this-command))
23497 (goto-char after-bullet))
23498 (when (or (> origin after-bullet) (= (point) origin))
23499 (goto-char after-bullet)))))
23500 ;; No special context. Point is already at beginning of line.
23501 (t nil))))
23503 (defun org-end-of-line (&optional n)
23504 "Go to the end of the line, but before ellipsis, if any.
23506 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23507 tags on the first attempt, and only move to after the tags when
23508 the cursor is already beyond the end of the headline.
23510 With argument N not nil or 1, move forward N - 1 lines first."
23511 (interactive "^p")
23512 (let ((origin (point))
23513 (special (pcase org-special-ctrl-a/e
23514 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23515 deactivate-mark)
23516 ;; First move to a visible line.
23517 (if (bound-and-true-p visual-line-mode)
23518 (beginning-of-visual-line n)
23519 (move-beginning-of-line n))
23520 (cond
23521 ;; At a headline, with tags.
23522 ((and special
23523 (save-excursion
23524 (beginning-of-line)
23525 (let ((case-fold-search nil))
23526 (looking-at org-complex-heading-regexp)))
23527 (match-end 5))
23528 (let ((tags (save-excursion
23529 (goto-char (match-beginning 5))
23530 (skip-chars-backward " \t")
23531 (point)))
23532 (visual-end (and (bound-and-true-p visual-line-mode)
23533 (save-excursion
23534 (end-of-visual-line)
23535 (point)))))
23536 ;; If `end-of-visual-line' brings us before end of line or
23537 ;; even tags, i.e., the headline spans over multiple visual
23538 ;; lines, move there.
23539 (cond ((and visual-end
23540 (< visual-end tags)
23541 (<= origin visual-end))
23542 (goto-char visual-end))
23543 ((eq special 'reversed)
23544 (if (and (= origin (line-end-position))
23545 (eq this-command last-command))
23546 (goto-char tags)
23547 (end-of-line)))
23549 (if (or (< origin tags) (= origin (line-end-position)))
23550 (goto-char tags)
23551 (end-of-line))))))
23552 ((bound-and-true-p visual-line-mode)
23553 (let ((bol (line-beginning-position)))
23554 (end-of-visual-line)
23555 ;; If `end-of-visual-line' gets us past the ellipsis at the
23556 ;; end of a line, backtrack and use `end-of-line' instead.
23557 (when (/= bol (line-beginning-position))
23558 (goto-char bol)
23559 (end-of-line))))
23560 (t (end-of-line)))))
23562 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23563 (define-key org-mode-map "\C-e" 'org-end-of-line)
23565 (defun org-backward-sentence (&optional _arg)
23566 "Go to beginning of sentence, or beginning of table field.
23567 This will call `backward-sentence' or `org-table-beginning-of-field',
23568 depending on context."
23569 (interactive)
23570 (let* ((element (org-element-at-point))
23571 (contents-begin (org-element-property :contents-begin element))
23572 (table (org-element-lineage element '(table) t)))
23573 (if (and table
23574 (> (point) contents-begin)
23575 (<= (point) (org-element-property :contents-end table)))
23576 (call-interactively #'org-table-beginning-of-field)
23577 (save-restriction
23578 (when (and contents-begin
23579 (< (point-min) contents-begin)
23580 (> (point) contents-begin))
23581 (narrow-to-region contents-begin
23582 (org-element-property :contents-end element)))
23583 (call-interactively #'backward-sentence)))))
23585 (defun org-forward-sentence (&optional _arg)
23586 "Go to end of sentence, or end of table field.
23587 This will call `forward-sentence' or `org-table-end-of-field',
23588 depending on context."
23589 (interactive)
23590 (if (and (org-at-heading-p)
23591 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23592 (save-restriction
23593 (narrow-to-region (line-beginning-position) (line-end-position))
23594 (call-interactively #'forward-sentence))
23595 (let* ((element (org-element-at-point))
23596 (contents-end (org-element-property :contents-end element))
23597 (table (org-element-lineage element '(table) t)))
23598 (if (and table
23599 (>= (point) (org-element-property :contents-begin table))
23600 (< (point) contents-end))
23601 (call-interactively #'org-table-end-of-field)
23602 (save-restriction
23603 (when (and contents-end
23604 (> (point-max) contents-end)
23605 ;; Skip blank lines between elements.
23606 (< (org-element-property :end element)
23607 (save-excursion (goto-char contents-end)
23608 (skip-chars-forward " \r\t\n"))))
23609 (narrow-to-region (org-element-property :contents-begin element)
23610 contents-end))
23611 ;; End of heading is considered as the end of a sentence.
23612 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23613 (call-interactively #'forward-sentence)))))))
23615 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23616 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23618 (defun org-kill-line (&optional _arg)
23619 "Kill line, to tags or end of line."
23620 (interactive)
23621 (cond
23622 ((or (not org-special-ctrl-k)
23623 (bolp)
23624 (not (org-at-heading-p)))
23625 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23626 org-ctrl-k-protect-subtree
23627 (or (eq org-ctrl-k-protect-subtree 'error)
23628 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23629 (user-error "C-k aborted as it would kill a hidden subtree"))
23630 (call-interactively
23631 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23632 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23633 (kill-region (point) (match-beginning 1))
23634 (org-set-tags nil t))
23635 (t (kill-region (point) (point-at-eol)))))
23637 (define-key org-mode-map "\C-k" 'org-kill-line)
23639 (defun org-yank (&optional arg)
23640 "Yank. If the kill is a subtree, treat it specially.
23641 This command will look at the current kill and check if is a single
23642 subtree, or a series of subtrees[1]. If it passes the test, and if the
23643 cursor is at the beginning of a line or after the stars of a currently
23644 empty headline, then the yank is handled specially. How exactly depends
23645 on the value of the following variables.
23647 `org-yank-folded-subtrees'
23648 By default, this variable is non-nil, which results in
23649 subtree(s) being folded after insertion, except if doing so
23650 would swallow text after the yanked text.
23652 `org-yank-adjusted-subtrees'
23653 When non-nil (the default value is nil), the subtree will be
23654 promoted or demoted in order to fit into the local outline tree
23655 structure, which means that the level will be adjusted so that it
23656 becomes the smaller one of the two *visible* surrounding headings.
23658 Any prefix to this command will cause `yank' to be called directly with
23659 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23660 will just
23661 plainly yank the text as it is.
23663 \[1] The test checks if the first non-white line is a heading
23664 and if there are no other headings with fewer stars."
23665 (interactive "P")
23666 (org-yank-generic 'yank arg))
23668 (defun org-yank-generic (command arg)
23669 "Perform some yank-like command.
23671 This function implements the behavior described in the `org-yank'
23672 documentation. However, it has been generalized to work for any
23673 interactive command with similar behavior."
23675 ;; pretend to be command COMMAND
23676 (setq this-command command)
23678 (if arg
23679 (call-interactively command)
23681 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23682 (and (org-kill-is-subtree-p)
23683 (or (bolp)
23684 (and (looking-at "[ \t]*$")
23685 (string-match
23686 "\\`\\*+\\'"
23687 (buffer-substring (point-at-bol) (point)))))))
23688 swallowp)
23689 (cond
23690 ((and subtreep org-yank-folded-subtrees)
23691 (let ((beg (point))
23692 end)
23693 (if (and subtreep org-yank-adjusted-subtrees)
23694 (org-paste-subtree nil nil 'for-yank)
23695 (call-interactively command))
23697 (setq end (point))
23698 (goto-char beg)
23699 (when (and (bolp) subtreep
23700 (not (setq swallowp
23701 (org-yank-folding-would-swallow-text beg end))))
23702 (org-with-limited-levels
23703 (or (looking-at org-outline-regexp)
23704 (re-search-forward org-outline-regexp-bol end t))
23705 (while (and (< (point) end) (looking-at org-outline-regexp))
23706 (outline-hide-subtree)
23707 (org-cycle-show-empty-lines 'folded)
23708 (condition-case nil
23709 (outline-forward-same-level 1)
23710 (error (goto-char end))))))
23711 (when swallowp
23712 (message
23713 "Inserted text not folded because that would swallow text"))
23715 (goto-char end)
23716 (skip-chars-forward " \t\n\r")
23717 (beginning-of-line 1)
23718 (push-mark beg 'nomsg)))
23719 ((and subtreep org-yank-adjusted-subtrees)
23720 (let ((beg (point-at-bol)))
23721 (org-paste-subtree nil nil 'for-yank)
23722 (push-mark beg 'nomsg)))
23724 (call-interactively command))))))
23726 (defun org-yank-folding-would-swallow-text (beg end)
23727 "Would hide-subtree at BEG swallow any text after END?"
23728 (let (level)
23729 (org-with-limited-levels
23730 (save-excursion
23731 (goto-char beg)
23732 (when (or (looking-at org-outline-regexp)
23733 (re-search-forward org-outline-regexp-bol end t))
23734 (setq level (org-outline-level)))
23735 (goto-char end)
23736 (skip-chars-forward " \t\r\n\v\f")
23737 (not (or (eobp)
23738 (and (bolp) (looking-at-p org-outline-regexp)
23739 (<= (org-outline-level) level))))))))
23741 (define-key org-mode-map "\C-y" 'org-yank)
23743 (defun org-truely-invisible-p ()
23744 "Check if point is at a character currently not visible.
23745 This version does not only check the character property, but also
23746 `visible-mode'."
23747 (unless (bound-and-true-p visible-mode)
23748 (org-invisible-p)))
23750 (defun org-invisible-p2 ()
23751 "Check if point is at a character currently not visible.
23753 If the point is at EOL (and not at the beginning of a buffer too),
23754 move it back by one char before doing this check."
23755 (save-excursion
23756 (when (and (eolp) (not (bobp)))
23757 (backward-char 1))
23758 (org-invisible-p)))
23760 (defun org-back-to-heading (&optional invisible-ok)
23761 "Call `outline-back-to-heading', but provide a better error message."
23762 (condition-case nil
23763 (outline-back-to-heading invisible-ok)
23764 (error (error "Before first headline at position %d in buffer %s"
23765 (point) (current-buffer)))))
23767 (defun org-before-first-heading-p ()
23768 "Before first heading?"
23769 (save-excursion
23770 (end-of-line)
23771 (null (re-search-backward org-outline-regexp-bol nil t))))
23773 (defun org-at-heading-p (&optional ignored)
23774 (outline-on-heading-p t))
23776 (defun org-in-commented-heading-p (&optional no-inheritance)
23777 "Non-nil if point is under a commented heading.
23778 This function also checks ancestors of the current headline,
23779 unless optional argument NO-INHERITANCE is non-nil."
23780 (cond
23781 ((org-before-first-heading-p) nil)
23782 ((let ((headline (nth 4 (org-heading-components))))
23783 (and headline
23784 (let ((case-fold-search nil))
23785 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23786 headline)))))
23787 (no-inheritance nil)
23789 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23791 (defun org-at-comment-p nil
23792 "Is cursor in a commented line?"
23793 (save-excursion
23794 (save-match-data
23795 (beginning-of-line)
23796 (looking-at "^[ \t]*# "))))
23798 (defun org-at-drawer-p nil
23799 "Is cursor at a drawer keyword?"
23800 (save-excursion
23801 (move-beginning-of-line 1)
23802 (looking-at org-drawer-regexp)))
23804 (defun org-at-block-p nil
23805 "Is cursor at a block keyword?"
23806 (save-excursion
23807 (move-beginning-of-line 1)
23808 (looking-at org-block-regexp)))
23810 (defun org-point-at-end-of-empty-headline ()
23811 "If point is at the end of an empty headline, return t, else nil.
23812 If the heading only contains a TODO keyword, it is still still considered
23813 empty."
23814 (let ((case-fold-search nil))
23815 (and (looking-at "[ \t]*$")
23816 org-todo-line-regexp
23817 (save-excursion
23818 (beginning-of-line)
23819 (looking-at org-todo-line-regexp)
23820 (string= (match-string 3) "")))))
23822 (defun org-at-heading-or-item-p ()
23823 (or (org-at-heading-p) (org-at-item-p)))
23825 (defun org-at-target-p ()
23826 (or (org-in-regexp org-radio-target-regexp)
23827 (org-in-regexp org-target-regexp)))
23828 ;; Compatibility alias with Org versions < 7.8.03
23829 (defalias 'org-on-target-p 'org-at-target-p)
23831 (defun org-up-heading-all (arg)
23832 "Move to the heading line of which the present line is a subheading.
23833 This function considers both visible and invisible heading lines.
23834 With argument, move up ARG levels."
23835 (outline-up-heading arg t))
23837 (defun org-up-heading-safe ()
23838 "Move to the heading line of which the present line is a subheading.
23839 This version will not throw an error. It will return the level of the
23840 headline found, or nil if no higher level is found.
23842 Also, this function will be a lot faster than `outline-up-heading',
23843 because it relies on stars being the outline starters. This can really
23844 make a significant difference in outlines with very many siblings."
23845 (when (ignore-errors (org-back-to-heading t))
23846 (let ((level-up (1- (funcall outline-level))))
23847 (and (> level-up 0)
23848 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23849 (funcall outline-level)))))
23851 (defun org-first-sibling-p ()
23852 "Is this heading the first child of its parents?"
23853 (interactive)
23854 (let ((re org-outline-regexp-bol)
23855 level l)
23856 (unless (org-at-heading-p t)
23857 (user-error "Not at a heading"))
23858 (setq level (funcall outline-level))
23859 (save-excursion
23860 (if (not (re-search-backward re nil t))
23862 (setq l (funcall outline-level))
23863 (< l level)))))
23865 (defun org-goto-sibling (&optional previous)
23866 "Goto the next sibling, even if it is invisible.
23867 When PREVIOUS is set, go to the previous sibling instead. Returns t
23868 when a sibling was found. When none is found, return nil and don't
23869 move point."
23870 (let ((fun (if previous 're-search-backward 're-search-forward))
23871 (pos (point))
23872 (re org-outline-regexp-bol)
23873 level l)
23874 (when (ignore-errors (org-back-to-heading t))
23875 (setq level (funcall outline-level))
23876 (catch 'exit
23877 (or previous (forward-char 1))
23878 (while (funcall fun re nil t)
23879 (setq l (funcall outline-level))
23880 (when (< l level) (goto-char pos) (throw 'exit nil))
23881 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23882 (goto-char pos)
23883 nil))))
23885 (defun org-show-siblings ()
23886 "Show all siblings of the current headline."
23887 (save-excursion
23888 (while (org-goto-sibling) (org-flag-heading nil)))
23889 (save-excursion
23890 (while (org-goto-sibling 'previous)
23891 (org-flag-heading nil))))
23893 (defun org-goto-first-child ()
23894 "Goto the first child, even if it is invisible.
23895 Return t when a child was found. Otherwise don't move point and
23896 return nil."
23897 (let (level (pos (point)) (re org-outline-regexp-bol))
23898 (when (ignore-errors (org-back-to-heading t))
23899 (setq level (outline-level))
23900 (forward-char 1)
23901 (if (and (re-search-forward re nil t) (> (outline-level) level))
23902 (progn (goto-char (match-beginning 0)) t)
23903 (goto-char pos) nil))))
23905 (defun org-show-hidden-entry ()
23906 "Show an entry where even the heading is hidden."
23907 (save-excursion
23908 (org-show-entry)))
23910 (defun org-flag-heading (flag &optional entry)
23911 "Flag the current heading. FLAG non-nil means make invisible.
23912 When ENTRY is non-nil, show the entire entry."
23913 (save-excursion
23914 (org-back-to-heading t)
23915 ;; Check if we should show the entire entry
23916 (if entry
23917 (progn
23918 (org-show-entry)
23919 (save-excursion
23920 (and (outline-next-heading)
23921 (org-flag-heading nil))))
23922 (outline-flag-region (max (point-min) (1- (point)))
23923 (save-excursion (outline-end-of-heading) (point))
23924 flag))))
23926 (defun org-get-next-sibling ()
23927 "Move to next heading of the same level, and return point.
23928 If there is no such heading, return nil.
23929 This is like outline-next-sibling, but invisible headings are ok."
23930 (let ((level (funcall outline-level)))
23931 (outline-next-heading)
23932 (while (and (not (eobp)) (> (funcall outline-level) level))
23933 (outline-next-heading))
23934 (unless (or (eobp) (< (funcall outline-level) level))
23935 (point))))
23937 (defun org-get-last-sibling ()
23938 "Move to previous heading of the same level, and return point.
23939 If there is no such heading, return nil."
23940 (let ((opoint (point))
23941 (level (funcall outline-level)))
23942 (outline-previous-heading)
23943 (when (and (/= (point) opoint) (outline-on-heading-p t))
23944 (while (and (> (funcall outline-level) level)
23945 (not (bobp)))
23946 (outline-previous-heading))
23947 (unless (< (funcall outline-level) level)
23948 (point)))))
23950 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23951 "Goto to the end of a subtree."
23952 ;; This contains an exact copy of the original function, but it uses
23953 ;; `org-back-to-heading', to make it work also in invisible
23954 ;; trees. And is uses an invisible-ok argument.
23955 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23956 ;; Furthermore, when used inside Org, finding the end of a large subtree
23957 ;; with many children and grandchildren etc, this can be much faster
23958 ;; than the outline version.
23959 (org-back-to-heading invisible-ok)
23960 (let ((first t)
23961 (level (funcall outline-level)))
23962 (if (and (derived-mode-p 'org-mode) (< level 1000))
23963 ;; A true heading (not a plain list item), in Org
23964 ;; This means we can easily find the end by looking
23965 ;; only for the right number of stars. Using a regexp to do
23966 ;; this is so much faster than using a Lisp loop.
23967 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23968 (forward-char 1)
23969 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23970 ;; something else, do it the slow way
23971 (while (and (not (eobp))
23972 (or first (> (funcall outline-level) level)))
23973 (setq first nil)
23974 (outline-next-heading)))
23975 (unless to-heading
23976 (when (memq (preceding-char) '(?\n ?\^M))
23977 ;; Go to end of line before heading
23978 (forward-char -1)
23979 (when (memq (preceding-char) '(?\n ?\^M))
23980 ;; leave blank line before heading
23981 (forward-char -1)))))
23982 (point))
23984 (defun org-end-of-meta-data (&optional full)
23985 "Skip planning line and properties drawer in current entry.
23986 When optional argument FULL is non-nil, also skip empty lines,
23987 clocking lines and regular drawers at the beginning of the
23988 entry."
23989 (org-back-to-heading t)
23990 (forward-line)
23991 (when (looking-at-p org-planning-line-re) (forward-line))
23992 (when (looking-at org-property-drawer-re)
23993 (goto-char (match-end 0))
23994 (forward-line))
23995 (when (and full (not (org-at-heading-p)))
23996 (catch 'exit
23997 (let ((end (save-excursion (outline-next-heading) (point)))
23998 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23999 (while (not (eobp))
24000 (cond ((looking-at-p org-drawer-regexp)
24001 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24002 (forward-line)
24003 (throw 'exit t)))
24004 ((looking-at-p re) (forward-line))
24005 (t (throw 'exit t))))))))
24007 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24008 "Move forward to the ARG'th subheading at same level as this one.
24009 Stop at the first and last subheadings of a superior heading.
24010 Normally this only looks at visible headings, but when INVISIBLE-OK is
24011 non-nil it will also look at invisible ones."
24012 (interactive "p")
24013 (let ((backward? (and arg (< arg 0))))
24014 (if (org-before-first-heading-p)
24015 (if backward? (goto-char (point-min)) (outline-next-heading))
24016 (org-back-to-heading invisible-ok)
24017 (unless backward? (end-of-line)) ;do not match current headline
24018 (let ((level (- (match-end 0) (match-beginning 0) 1))
24019 (f (if backward? #'re-search-backward #'re-search-forward))
24020 (count (if arg (abs arg) 1))
24021 (result (point)))
24022 (while (and (> count 0)
24023 (funcall f org-outline-regexp-bol nil 'move))
24024 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24025 (cond ((< l level) (setq count 0))
24026 ((and (= l level)
24027 (or invisible-ok
24028 (not (org-invisible-p
24029 (line-beginning-position)))))
24030 (cl-decf count)
24031 (when (= l level) (setq result (point)))))))
24032 (goto-char result))
24033 (beginning-of-line))))
24035 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24036 "Move backward to the ARG'th subheading at same level as this one.
24037 Stop at the first and last subheadings of a superior heading."
24038 (interactive "p")
24039 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24041 (defun org-next-visible-heading (arg)
24042 "Move to the next visible heading.
24044 This function wraps `outline-next-visible-heading' with
24045 `org-with-limited-levels' in order to skip over inline tasks and
24046 respect customization of `org-odd-levels-only'."
24047 (interactive "p")
24048 (org-with-limited-levels
24049 (outline-next-visible-heading arg)))
24051 (defun org-previous-visible-heading (arg)
24052 "Move to the previous visible heading.
24054 This function wraps `outline-previous-visible-heading' with
24055 `org-with-limited-levels' in order to skip over inline tasks and
24056 respect customization of `org-odd-levels-only'."
24057 (interactive "p")
24058 (org-with-limited-levels
24059 (outline-previous-visible-heading arg)))
24061 (defun org-next-block (arg &optional backward block-regexp)
24062 "Jump to the next block.
24064 With a prefix argument ARG, jump forward ARG many blocks.
24066 When BACKWARD is non-nil, jump to the previous block.
24068 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24069 Match data is set according to this regexp when the function
24070 returns.
24072 Return point at beginning of the opening line of found block.
24073 Throw an error if no block is found."
24074 (interactive "p")
24075 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24076 (case-fold-search t)
24077 (search-fn (if backward #'re-search-backward #'re-search-forward))
24078 (count (or arg 1))
24079 (origin (point))
24080 last-element)
24081 (if backward (beginning-of-line) (end-of-line))
24082 (while (and (> count 0) (funcall search-fn re nil t))
24083 (let ((element (save-excursion
24084 (goto-char (match-beginning 0))
24085 (save-match-data (org-element-at-point)))))
24086 (when (and (memq (org-element-type element)
24087 '(center-block comment-block dynamic-block
24088 example-block export-block quote-block
24089 special-block src-block verse-block))
24090 (<= (match-beginning 0)
24091 (org-element-property :post-affiliated element)))
24092 (setq last-element element)
24093 (cl-decf count))))
24094 (if (= count 0)
24095 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24096 (save-match-data (org-show-context)))
24097 (goto-char origin)
24098 (user-error "No %s code blocks" (if backward "previous" "further")))))
24100 (defun org-previous-block (arg &optional block-regexp)
24101 "Jump to the previous block.
24102 With a prefix argument ARG, jump backward ARG many source blocks.
24103 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24104 (interactive "p")
24105 (org-next-block arg t block-regexp))
24107 (defun org-forward-paragraph ()
24108 "Move forward to beginning of next paragraph or equivalent.
24110 The function moves point to the beginning of the next visible
24111 structural element, which can be a paragraph, a table, a list
24112 item, etc. It also provides some special moves for convenience:
24114 - On an affiliated keyword, jump to the beginning of the
24115 relative element.
24116 - On an item or a footnote definition, move to the second
24117 element inside, if any.
24118 - On a table or a property drawer, jump after it.
24119 - On a verse or source block, stop after blank lines."
24120 (interactive)
24121 (unless (eobp)
24122 (let* ((deactivate-mark nil)
24123 (element (org-element-at-point))
24124 (type (org-element-type element))
24125 (post-affiliated (org-element-property :post-affiliated element))
24126 (contents-begin (org-element-property :contents-begin element))
24127 (contents-end (org-element-property :contents-end element))
24128 (end (let ((end (org-element-property :end element)) (parent element))
24129 (while (and (setq parent (org-element-property :parent parent))
24130 (= (org-element-property :contents-end parent) end))
24131 (setq end (org-element-property :end parent)))
24132 end)))
24133 (cond ((not element)
24134 (skip-chars-forward " \r\t\n")
24135 (or (eobp) (beginning-of-line)))
24136 ;; On affiliated keywords, move to element's beginning.
24137 ((< (point) post-affiliated)
24138 (goto-char post-affiliated))
24139 ;; At a table row, move to the end of the table. Similarly,
24140 ;; at a node property, move to the end of the property
24141 ;; drawer.
24142 ((memq type '(node-property table-row))
24143 (goto-char (org-element-property
24144 :end (org-element-property :parent element))))
24145 ((memq type '(property-drawer table)) (goto-char end))
24146 ;; Consider blank lines as separators in verse and source
24147 ;; blocks to ease editing.
24148 ((memq type '(src-block verse-block))
24149 (when (eq type 'src-block)
24150 (setq contents-end
24151 (save-excursion (goto-char end)
24152 (skip-chars-backward " \r\t\n")
24153 (line-beginning-position))))
24154 (beginning-of-line)
24155 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24156 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24157 (goto-char end)
24158 (skip-chars-forward " \r\t\n")
24159 (if (= (point) contents-end) (goto-char end)
24160 (beginning-of-line))))
24161 ;; With no contents, just skip element.
24162 ((not contents-begin) (goto-char end))
24163 ;; If contents are invisible, skip the element altogether.
24164 ((org-invisible-p (line-end-position))
24165 (cl-case type
24166 (headline
24167 (org-with-limited-levels (outline-next-visible-heading 1)))
24168 ;; At a plain list, make sure we move to the next item
24169 ;; instead of skipping the whole list.
24170 (plain-list (forward-char)
24171 (org-forward-paragraph))
24172 (otherwise (goto-char end))))
24173 ((>= (point) contents-end) (goto-char end))
24174 ((>= (point) contents-begin)
24175 ;; This can only happen on paragraphs and plain lists.
24176 (cl-case type
24177 (paragraph (goto-char end))
24178 ;; At a plain list, try to move to second element in
24179 ;; first item, if possible.
24180 (plain-list (end-of-line)
24181 (org-forward-paragraph))))
24182 ;; When contents start on the middle of a line (e.g. in
24183 ;; items and footnote definitions), try to reach first
24184 ;; element starting after current line.
24185 ((> (line-end-position) contents-begin)
24186 (end-of-line)
24187 (org-forward-paragraph))
24188 (t (goto-char contents-begin))))))
24190 (defun org-backward-paragraph ()
24191 "Move backward to start of previous paragraph or equivalent.
24193 The function moves point to the beginning of the current
24194 structural element, which can be a paragraph, a table, a list
24195 item, etc., or to the beginning of the previous visible one if
24196 point is already there. It also provides some special moves for
24197 convenience:
24199 - On an affiliated keyword, jump to the first one.
24200 - On a table or a property drawer, move to its beginning.
24201 - On comment, example, export, src and verse blocks, stop
24202 before blank lines."
24203 (interactive)
24204 (unless (bobp)
24205 (let* ((deactivate-mark nil)
24206 (element (org-element-at-point))
24207 (type (org-element-type element))
24208 (contents-end (org-element-property :contents-end element))
24209 (post-affiliated (org-element-property :post-affiliated element))
24210 (begin (org-element-property :begin element))
24211 (special? ;blocks handled specially
24212 (memq type '(comment-block example-block export-block src-block
24213 verse-block)))
24214 (contents-begin
24215 (if special?
24216 ;; These types have no proper contents. Fake line
24217 ;; below the block opening line as contents beginning.
24218 (save-excursion (goto-char begin) (line-beginning-position 2))
24219 (org-element-property :contents-begin element))))
24220 (cond
24221 ((not element) (goto-char (point-min)))
24222 ((= (point) begin)
24223 (backward-char)
24224 (org-backward-paragraph))
24225 ((<= (point) post-affiliated) (goto-char begin))
24226 ;; Special behavior: on a table or a property drawer, move to
24227 ;; its beginning.
24228 ((memq type '(node-property table-row))
24229 (goto-char (org-element-property
24230 :post-affiliated (org-element-property :parent element))))
24231 (special?
24232 (if (<= (point) contents-begin) (goto-char post-affiliated)
24233 ;; Inside a verse block, see blank lines as paragraph
24234 ;; separators.
24235 (let ((origin (point)))
24236 (skip-chars-backward " \r\t\n" contents-begin)
24237 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24238 (skip-chars-forward " \r\t\n" origin)
24239 (if (= (point) origin) (goto-char contents-begin)
24240 (beginning-of-line))))))
24241 ((eq type 'paragraph) (goto-char contents-begin)
24242 ;; When at first paragraph in an item or a footnote definition,
24243 ;; move directly to beginning of line.
24244 (let ((parent-contents
24245 (org-element-property
24246 :contents-begin (org-element-property :parent element))))
24247 (when (and parent-contents (= parent-contents contents-begin))
24248 (beginning-of-line))))
24249 ;; At the end of a greater element, move to the beginning of
24250 ;; the last element within.
24251 ((and contents-end (>= (point) contents-end))
24252 (goto-char (1- contents-end))
24253 (org-backward-paragraph))
24254 (t (goto-char (or post-affiliated begin))))
24255 ;; Ensure we never leave point invisible.
24256 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24258 (defun org-forward-element ()
24259 "Move forward by one element.
24260 Move to the next element at the same level, when possible."
24261 (interactive)
24262 (cond ((eobp) (user-error "Cannot move further down"))
24263 ((org-with-limited-levels (org-at-heading-p))
24264 (let ((origin (point)))
24265 (goto-char (org-end-of-subtree nil t))
24266 (unless (org-with-limited-levels (org-at-heading-p))
24267 (goto-char origin)
24268 (user-error "Cannot move further down"))))
24270 (let* ((elem (org-element-at-point))
24271 (end (org-element-property :end elem))
24272 (parent (org-element-property :parent elem)))
24273 (cond ((and parent (= (org-element-property :contents-end parent) end))
24274 (goto-char (org-element-property :end parent)))
24275 ((integer-or-marker-p end) (goto-char end))
24276 (t (message "No element at point")))))))
24278 (defun org-backward-element ()
24279 "Move backward by one element.
24280 Move to the previous element at the same level, when possible."
24281 (interactive)
24282 (cond ((bobp) (user-error "Cannot move further up"))
24283 ((org-with-limited-levels (org-at-heading-p))
24284 ;; At a headline, move to the previous one, if any, or stay
24285 ;; here.
24286 (let ((origin (point)))
24287 (org-with-limited-levels (org-backward-heading-same-level 1))
24288 ;; When current headline has no sibling above, move to its
24289 ;; parent.
24290 (when (= (point) origin)
24291 (or (org-with-limited-levels (org-up-heading-safe))
24292 (progn (goto-char origin)
24293 (user-error "Cannot move further up"))))))
24295 (let* ((elem (org-element-at-point))
24296 (beg (org-element-property :begin elem)))
24297 (cond
24298 ;; Move to beginning of current element if point isn't
24299 ;; there already.
24300 ((null beg) (message "No element at point"))
24301 ((/= (point) beg) (goto-char beg))
24302 (t (goto-char beg)
24303 (skip-chars-backward " \r\t\n")
24304 (unless (bobp)
24305 (let ((prev (org-element-at-point)))
24306 (goto-char (org-element-property :begin prev))
24307 (while (and (setq prev (org-element-property :parent prev))
24308 (<= (org-element-property :end prev) beg))
24309 (goto-char (org-element-property :begin prev)))))))))))
24311 (defun org-up-element ()
24312 "Move to upper element."
24313 (interactive)
24314 (if (org-with-limited-levels (org-at-heading-p))
24315 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24316 (let* ((elem (org-element-at-point))
24317 (parent (org-element-property :parent elem)))
24318 (if parent (goto-char (org-element-property :begin parent))
24319 (if (org-with-limited-levels (org-before-first-heading-p))
24320 (user-error "No surrounding element")
24321 (org-with-limited-levels (org-back-to-heading)))))))
24323 (defun org-down-element ()
24324 "Move to inner element."
24325 (interactive)
24326 (let ((element (org-element-at-point)))
24327 (cond
24328 ((memq (org-element-type element) '(plain-list table))
24329 (goto-char (org-element-property :contents-begin element))
24330 (forward-char))
24331 ((memq (org-element-type element) org-element-greater-elements)
24332 ;; If contents are hidden, first disclose them.
24333 (when (org-invisible-p (line-end-position)) (org-cycle))
24334 (goto-char (or (org-element-property :contents-begin element)
24335 (user-error "No content for this element"))))
24336 (t (user-error "No inner element")))))
24338 (defun org-drag-element-backward ()
24339 "Move backward element at point."
24340 (interactive)
24341 (let ((elem (or (org-element-at-point)
24342 (user-error "No element at point"))))
24343 (if (eq (org-element-type elem) 'headline)
24344 ;; Preserve point when moving a whole tree, even if point was
24345 ;; on blank lines below the headline.
24346 (let ((offset (skip-chars-backward " \t\n")))
24347 (unwind-protect (org-move-subtree-up)
24348 (forward-char (- offset))))
24349 (let ((prev-elem
24350 (save-excursion
24351 (goto-char (org-element-property :begin elem))
24352 (skip-chars-backward " \r\t\n")
24353 (unless (bobp)
24354 (let* ((beg (org-element-property :begin elem))
24355 (prev (org-element-at-point))
24356 (up prev))
24357 (while (and (setq up (org-element-property :parent up))
24358 (<= (org-element-property :end up) beg))
24359 (setq prev up))
24360 prev)))))
24361 ;; Error out if no previous element or previous element is
24362 ;; a parent of the current one.
24363 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24364 (user-error "Cannot drag element backward")
24365 (let ((pos (point)))
24366 (org-element-swap-A-B prev-elem elem)
24367 (goto-char (+ (org-element-property :begin prev-elem)
24368 (- pos (org-element-property :begin elem))))))))))
24370 (defun org-drag-element-forward ()
24371 "Move forward element at point."
24372 (interactive)
24373 (let* ((pos (point))
24374 (elem (or (org-element-at-point)
24375 (user-error "No element at point"))))
24376 (when (= (point-max) (org-element-property :end elem))
24377 (user-error "Cannot drag element forward"))
24378 (goto-char (org-element-property :end elem))
24379 (let ((next-elem (org-element-at-point)))
24380 (when (or (org-element-nested-p elem next-elem)
24381 (and (eq (org-element-type next-elem) 'headline)
24382 (not (eq (org-element-type elem) 'headline))))
24383 (goto-char pos)
24384 (user-error "Cannot drag element forward"))
24385 ;; Compute new position of point: it's shifted by NEXT-ELEM
24386 ;; body's length (without final blanks) and by the length of
24387 ;; blanks between ELEM and NEXT-ELEM.
24388 (let ((size-next (- (save-excursion
24389 (goto-char (org-element-property :end next-elem))
24390 (skip-chars-backward " \r\t\n")
24391 (forward-line)
24392 ;; Small correction if buffer doesn't end
24393 ;; with a newline character.
24394 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24395 (org-element-property :begin next-elem)))
24396 (size-blank (- (org-element-property :end elem)
24397 (save-excursion
24398 (goto-char (org-element-property :end elem))
24399 (skip-chars-backward " \r\t\n")
24400 (forward-line)
24401 (point)))))
24402 (org-element-swap-A-B elem next-elem)
24403 (goto-char (+ pos size-next size-blank))))))
24405 (defun org-drag-line-forward (arg)
24406 "Drag the line at point ARG lines forward."
24407 (interactive "p")
24408 (dotimes (_ (abs arg))
24409 (let ((c (current-column)))
24410 (if (< 0 arg)
24411 (progn
24412 (beginning-of-line 2)
24413 (transpose-lines 1)
24414 (beginning-of-line 0))
24415 (transpose-lines 1)
24416 (beginning-of-line -1))
24417 (org-move-to-column c))))
24419 (defun org-drag-line-backward (arg)
24420 "Drag the line at point ARG lines backward."
24421 (interactive "p")
24422 (org-drag-line-forward (- arg)))
24424 (defun org-mark-element ()
24425 "Put point at beginning of this element, mark at end.
24427 Interactively, if this command is repeated or (in Transient Mark
24428 mode) if the mark is active, it marks the next element after the
24429 ones already marked."
24430 (interactive)
24431 (let (deactivate-mark)
24432 (if (and (called-interactively-p 'any)
24433 (or (and (eq last-command this-command) (mark t))
24434 (and transient-mark-mode mark-active)))
24435 (set-mark
24436 (save-excursion
24437 (goto-char (mark))
24438 (goto-char (org-element-property :end (org-element-at-point)))))
24439 (let ((element (org-element-at-point)))
24440 (end-of-line)
24441 (push-mark (org-element-property :end element) t t)
24442 (goto-char (org-element-property :begin element))))))
24444 (defun org-narrow-to-element ()
24445 "Narrow buffer to current element."
24446 (interactive)
24447 (let ((elem (org-element-at-point)))
24448 (cond
24449 ((eq (car elem) 'headline)
24450 (narrow-to-region
24451 (org-element-property :begin elem)
24452 (org-element-property :end elem)))
24453 ((memq (car elem) org-element-greater-elements)
24454 (narrow-to-region
24455 (org-element-property :contents-begin elem)
24456 (org-element-property :contents-end elem)))
24458 (narrow-to-region
24459 (org-element-property :begin elem)
24460 (org-element-property :end elem))))))
24462 (defun org-transpose-element ()
24463 "Transpose current and previous elements, keeping blank lines between.
24464 Point is moved after both elements."
24465 (interactive)
24466 (org-skip-whitespace)
24467 (let ((end (org-element-property :end (org-element-at-point))))
24468 (org-drag-element-backward)
24469 (goto-char end)))
24471 (defun org-unindent-buffer ()
24472 "Un-indent the visible part of the buffer.
24473 Relative indentation (between items, inside blocks, etc.) isn't
24474 modified."
24475 (interactive)
24476 (unless (eq major-mode 'org-mode)
24477 (user-error "Cannot un-indent a buffer not in Org mode"))
24478 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24479 (unindent-tree
24480 (lambda (contents)
24481 (dolist (element (reverse contents))
24482 (if (memq (org-element-type element) '(headline section))
24483 (funcall unindent-tree (org-element-contents element))
24484 (save-excursion
24485 (save-restriction
24486 (narrow-to-region
24487 (org-element-property :begin element)
24488 (org-element-property :end element))
24489 (org-do-remove-indentation))))))))
24490 (funcall unindent-tree (org-element-contents parse-tree))))
24492 (defun org-show-children (&optional level)
24493 "Show all direct subheadings of this heading.
24494 Prefix arg LEVEL is how many levels below the current level
24495 should be shown. Default is enough to cause the following
24496 heading to appear."
24497 (interactive "p")
24498 ;; If `orgstruct-mode' is active, use the slower version.
24499 (if orgstruct-mode (call-interactively #'outline-show-children)
24500 (save-excursion
24501 (org-back-to-heading t)
24502 (let* ((current-level (funcall outline-level))
24503 (max-level (org-get-valid-level
24504 current-level
24505 (if level (prefix-numeric-value level) 1)))
24506 (end (save-excursion (org-end-of-subtree t t)))
24507 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24508 (past-first-child nil)
24509 ;; Make sure to skip inlinetasks.
24510 (re (format regexp-fmt
24511 current-level
24512 (cond
24513 ((not (featurep 'org-inlinetask)) "")
24514 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24516 (t (1- org-inlinetask-min-level))))))
24517 ;; Display parent heading.
24518 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24519 (forward-line)
24520 ;; Display children. First child may be deeper than expected
24521 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24522 ;; MAX-LEVEL accordingly.
24523 (while (re-search-forward re end t)
24524 (unless past-first-child
24525 (setq re (format regexp-fmt
24526 current-level
24527 (max (funcall outline-level) max-level)))
24528 (setq past-first-child t))
24529 (outline-flag-region
24530 (line-end-position 0) (line-end-position) nil))))))
24532 (defun org-show-subtree ()
24533 "Show everything after this heading at deeper levels."
24534 (interactive)
24535 (outline-flag-region
24536 (point)
24537 (save-excursion
24538 (org-end-of-subtree t t))
24539 nil))
24541 (defun org-show-entry ()
24542 "Show the body directly following this heading.
24543 Show the heading too, if it is currently invisible."
24544 (interactive)
24545 (save-excursion
24546 (ignore-errors
24547 (org-back-to-heading t)
24548 (outline-flag-region
24549 (max (point-min) (1- (point)))
24550 (save-excursion
24551 (if (re-search-forward
24552 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24553 (match-beginning 1)
24554 (point-max)))
24555 nil)
24556 (org-cycle-hide-drawers 'children))))
24558 (defun org-make-options-regexp (kwds &optional extra)
24559 "Make a regular expression for keyword lines.
24560 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24561 when non-nil, is a regexp matching keywords names."
24562 (concat "^[ \t]*#\\+\\("
24563 (regexp-opt kwds)
24564 (and extra (concat (and kwds "\\|") extra))
24565 "\\):[ \t]*\\(.*\\)"))
24567 ;;;; Integration with and fixes for other packages
24569 ;;; Imenu support
24571 (defvar-local org-imenu-markers nil
24572 "All markers currently used by Imenu.")
24574 (defun org-imenu-new-marker (&optional pos)
24575 "Return a new marker for use by Imenu, and remember the marker."
24576 (let ((m (make-marker)))
24577 (move-marker m (or pos (point)))
24578 (push m org-imenu-markers)
24581 (defun org-imenu-get-tree ()
24582 "Produce the index for Imenu."
24583 (dolist (x org-imenu-markers) (move-marker x nil))
24584 (setq org-imenu-markers nil)
24585 (let* ((case-fold-search nil)
24586 (n org-imenu-depth)
24587 (re (concat "^" (org-get-limited-outline-regexp)))
24588 (subs (make-vector (1+ n) nil))
24589 (last-level 0)
24590 m level head0 head)
24591 (org-with-wide-buffer
24592 (goto-char (point-max))
24593 (while (re-search-backward re nil t)
24594 (setq level (org-reduced-level (funcall outline-level)))
24595 (when (and (<= level n)
24596 (looking-at org-complex-heading-regexp)
24597 (setq head0 (match-string-no-properties 4)))
24598 (setq head (org-link-display-format head0)
24599 m (org-imenu-new-marker))
24600 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24601 (if (>= level last-level)
24602 (push (cons head m) (aref subs level))
24603 (push (cons head (aref subs (1+ level))) (aref subs level))
24604 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24605 (setq last-level level))))
24606 (aref subs 1)))
24608 (eval-after-load "imenu"
24609 '(progn
24610 (add-hook 'imenu-after-jump-hook
24611 (lambda ()
24612 (when (derived-mode-p 'org-mode)
24613 (org-show-context 'org-goto))))))
24615 (defun org-link-display-format (s)
24616 "Replace links in string S with their description.
24617 If there is no description, use the link target."
24618 (save-match-data
24619 (replace-regexp-in-string
24620 org-bracket-link-analytic-regexp
24621 (lambda (m)
24622 (if (match-end 5) (match-string 5 m)
24623 (concat (match-string 1 m) (match-string 3 m))))
24624 s nil t)))
24626 (defun org-toggle-link-display ()
24627 "Toggle the literal or descriptive display of links."
24628 (interactive)
24629 (if org-descriptive-links
24630 (progn (org-remove-from-invisibility-spec '(org-link))
24631 (org-restart-font-lock)
24632 (setq org-descriptive-links nil))
24633 (progn (add-to-invisibility-spec '(org-link))
24634 (org-restart-font-lock)
24635 (setq org-descriptive-links t))))
24637 ;; Speedbar support
24639 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24640 "Overlay marking the agenda restriction line in speedbar.")
24641 (overlay-put org-speedbar-restriction-lock-overlay
24642 'face 'org-agenda-restriction-lock)
24643 (overlay-put org-speedbar-restriction-lock-overlay
24644 'help-echo "Agendas are currently limited to this item.")
24645 (delete-overlay org-speedbar-restriction-lock-overlay)
24647 (defun org-speedbar-set-agenda-restriction ()
24648 "Restrict future agenda commands to the location at point in speedbar.
24649 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24650 (interactive)
24651 (require 'org-agenda)
24652 (let (p m tp np dir txt)
24653 (cond
24654 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24655 'org-imenu t))
24656 (setq m (get-text-property p 'org-imenu-marker))
24657 (with-current-buffer (marker-buffer m)
24658 (goto-char m)
24659 (org-agenda-set-restriction-lock 'subtree)))
24660 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24661 'speedbar-function 'speedbar-find-file))
24662 (setq tp (previous-single-property-change
24663 (1+ p) 'speedbar-function)
24664 np (next-single-property-change
24665 tp 'speedbar-function)
24666 dir (speedbar-line-directory)
24667 txt (buffer-substring-no-properties (or tp (point-min))
24668 (or np (point-max))))
24669 (with-current-buffer (find-file-noselect
24670 (let ((default-directory dir))
24671 (expand-file-name txt)))
24672 (unless (derived-mode-p 'org-mode)
24673 (user-error "Cannot restrict to non-Org mode file"))
24674 (org-agenda-set-restriction-lock 'file)))
24675 (t (user-error "Don't know how to restrict Org mode agenda")))
24676 (move-overlay org-speedbar-restriction-lock-overlay
24677 (point-at-bol) (point-at-eol))
24678 (setq current-prefix-arg nil)
24679 (org-agenda-maybe-redo)))
24681 (defvar speedbar-file-key-map)
24682 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24683 (eval-after-load "speedbar"
24684 '(progn
24685 (speedbar-add-supported-extension ".org")
24686 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24687 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24688 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24689 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24690 (add-hook 'speedbar-visiting-tag-hook
24691 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24693 ;;; Fixes and Hacks for problems with other packages
24695 (defun org--flyspell-object-check-p (element)
24696 "Non-nil when Flyspell can check object at point.
24697 ELEMENT is the element at point."
24698 (let ((object (save-excursion
24699 (when (looking-at-p "\\>") (backward-char))
24700 (org-element-context element))))
24701 (cl-case (org-element-type object)
24702 ;; Prevent checks in links due to keybinding conflict with
24703 ;; Flyspell.
24704 ((code entity export-snippet inline-babel-call
24705 inline-src-block line-break latex-fragment link macro
24706 statistics-cookie target timestamp verbatim)
24707 nil)
24708 (footnote-reference
24709 ;; Only in inline footnotes, within the definition.
24710 (and (eq (org-element-property :type object) 'inline)
24711 (< (save-excursion
24712 (goto-char (org-element-property :begin object))
24713 (search-forward ":" nil t 2))
24714 (point))))
24715 (otherwise t))))
24717 (defun org-mode-flyspell-verify ()
24718 "Function used for `flyspell-generic-check-word-predicate'."
24719 (if (org-at-heading-p)
24720 ;; At a headline or an inlinetask, check title only. This is
24721 ;; faster than relying on `org-element-at-point'.
24722 (and (save-excursion (beginning-of-line)
24723 (and (let ((case-fold-search t))
24724 (not (looking-at-p "\\*+ END[ \t]*$")))
24725 (let ((case-fold-search nil))
24726 (looking-at org-complex-heading-regexp))))
24727 (match-beginning 4)
24728 (>= (point) (match-beginning 4))
24729 (or (not (match-beginning 5))
24730 (< (point) (match-beginning 5))))
24731 (let* ((element (org-element-at-point))
24732 (post-affiliated (org-element-property :post-affiliated element)))
24733 (cond
24734 ;; Ignore checks in all affiliated keywords but captions.
24735 ((< (point) post-affiliated)
24736 (and (save-excursion
24737 (beginning-of-line)
24738 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24739 (> (point) (match-end 0))
24740 (org--flyspell-object-check-p element)))
24741 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24742 ((let ((log (org-log-into-drawer)))
24743 (and log
24744 (let ((drawer (org-element-lineage element '(drawer))))
24745 (and drawer
24746 (eq (compare-strings
24747 log nil nil
24748 (org-element-property :drawer-name drawer) nil nil t)
24749 t)))))
24750 nil)
24752 (cl-case (org-element-type element)
24753 ((comment quote-section) t)
24754 (comment-block
24755 ;; Allow checks between block markers, not on them.
24756 (and (> (line-beginning-position) post-affiliated)
24757 (save-excursion
24758 (end-of-line)
24759 (skip-chars-forward " \r\t\n")
24760 (< (point) (org-element-property :end element)))))
24761 ;; Arbitrary list of keywords where checks are meaningful.
24762 ;; Make sure point is on the value part of the element.
24763 (keyword
24764 (and (member (org-element-property :key element)
24765 '("DESCRIPTION" "TITLE"))
24766 (save-excursion
24767 (search-backward ":" (line-beginning-position) t))))
24768 ;; Check is globally allowed in paragraphs verse blocks and
24769 ;; table rows (after affiliated keywords) but some objects
24770 ;; must not be affected.
24771 ((paragraph table-row verse-block)
24772 (let ((cbeg (org-element-property :contents-begin element))
24773 (cend (org-element-property :contents-end element)))
24774 (and cbeg (>= (point) cbeg) (< (point) cend)
24775 (org--flyspell-object-check-p element))))))))))
24776 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24778 (defun org-remove-flyspell-overlays-in (beg end)
24779 "Remove flyspell overlays in region."
24780 (and (bound-and-true-p flyspell-mode)
24781 (fboundp 'flyspell-delete-region-overlays)
24782 (flyspell-delete-region-overlays beg end)))
24784 (defvar flyspell-delayed-commands)
24785 (eval-after-load "flyspell"
24786 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24788 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24789 (eval-after-load "bookmark"
24790 '(if (boundp 'bookmark-after-jump-hook)
24791 ;; We can use the hook
24792 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24793 ;; Hook not available, use advice
24794 (defadvice bookmark-jump (after org-make-visible activate)
24795 "Make the position visible."
24796 (org-bookmark-jump-unhide))))
24798 ;; Make sure saveplace shows the location if it was hidden
24799 (eval-after-load "saveplace"
24800 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24801 "Make the position visible."
24802 (org-bookmark-jump-unhide)))
24804 ;; Make sure ecb shows the location if it was hidden
24805 (eval-after-load "ecb"
24806 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24807 "Make hierarchy visible when jumping into location from ECB tree buffer."
24808 (when (derived-mode-p 'org-mode)
24809 (org-show-context))))
24811 (defun org-bookmark-jump-unhide ()
24812 "Unhide the current position, to show the bookmark location."
24813 (and (derived-mode-p 'org-mode)
24814 (or (org-invisible-p)
24815 (save-excursion (goto-char (max (point-min) (1- (point))))
24816 (org-invisible-p)))
24817 (org-show-context 'bookmark-jump)))
24819 (defun org-mark-jump-unhide ()
24820 "Make the point visible with `org-show-context' after jumping to the mark."
24821 (when (and (derived-mode-p 'org-mode)
24822 (org-invisible-p))
24823 (org-show-context 'mark-goto)))
24825 (eval-after-load "simple"
24826 '(defadvice pop-to-mark-command (after org-make-visible activate)
24827 "Make the point visible with `org-show-context'."
24828 (org-mark-jump-unhide)))
24830 (eval-after-load "simple"
24831 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24832 "Make the point visible with `org-show-context'."
24833 (org-mark-jump-unhide)))
24835 (eval-after-load "simple"
24836 '(defadvice pop-global-mark (after org-make-visible activate)
24837 "Make the point visible with `org-show-context'."
24838 (org-mark-jump-unhide)))
24840 ;; Make session.el ignore our circular variable
24841 (defvar session-globals-exclude)
24842 (eval-after-load "session"
24843 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24845 ;;;; Finish up
24847 (provide 'org)
24849 (run-hooks 'org-load-hook)
24851 ;;; org.el ends here