Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blobde4c7a3817a62b93c868f2017c7d01a09b02bc54
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 <http://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-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
159 (declare-function org-table-cut-region "org-table" (beg end))
160 (declare-function org-table-edit-field "org-table" (arg))
161 (declare-function org-table-end "org-table" (&optional table-type))
162 (declare-function org-table-end-of-field "org-table" (&optional n))
163 (declare-function org-table-insert-row "org-table" (&optional arg))
164 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
165 (declare-function org-table-maybe-eval-formula "org-table" ())
166 (declare-function org-table-maybe-recalculate-line "org-table" ())
167 (declare-function org-table-next-row "org-table" ())
168 (declare-function org-table-paste-rectangle "org-table" ())
169 (declare-function org-table-recalculate "org-table" (&optional all noalign))
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
174 (declare-function org-export-get-backend "ox" (name))
175 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
176 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
178 (defsubst org-uniquify (list)
179 "Non-destructively remove duplicate elements from LIST."
180 (let ((res (copy-sequence list))) (delete-dups res)))
182 (defsubst org-get-at-bol (property)
183 "Get text property PROPERTY at the beginning of line."
184 (get-text-property (point-at-bol) property))
186 (defsubst org-trim (s &optional keep-lead)
187 "Remove whitespace at the beginning and the end of string S.
188 When optional argument KEEP-LEAD is non-nil, removing blank lines
189 at the beginning of the string does not affect leading indentation."
190 (replace-regexp-in-string
191 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
192 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
194 ;; load languages based on value of `org-babel-load-languages'
195 (defvar org-babel-load-languages)
197 ;;;###autoload
198 (defun org-babel-do-load-languages (sym value)
199 "Load the languages defined in `org-babel-load-languages'."
200 (set-default sym value)
201 (dolist (pair org-babel-load-languages)
202 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
203 (if active
204 (require (intern (concat "ob-" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-execute:" lang)))
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-expand-body:" lang)))))))
210 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
211 ;;;###autoload
212 (defun org-babel-load-file (file &optional compile)
213 "Load Emacs Lisp source code blocks in the Org FILE.
214 This function exports the source code using `org-babel-tangle'
215 and then loads the resulting file using `load-file'. With prefix
216 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
217 file to byte-code before it is loaded."
218 (interactive "fFile to load: \nP")
219 (let* ((age (lambda (file)
220 (float-time
221 (time-subtract (current-time)
222 (nth 5 (or (file-attributes (file-truename file))
223 (file-attributes file)))))))
224 (base-name (file-name-sans-extension file))
225 (exported-file (concat base-name ".el")))
226 ;; tangle if the Org file is newer than the elisp file
227 (unless (and (file-exists-p exported-file)
228 (> (funcall age file) (funcall age exported-file)))
229 ;; Tangle-file traversal returns reversed list of tangled files
230 ;; and we want to evaluate the first target.
231 (setq exported-file
232 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
233 (message "%s %s"
234 (if compile
235 (progn (byte-compile-file exported-file 'load)
236 "Compiled and loaded")
237 (progn (load-file exported-file) "Loaded"))
238 exported-file)))
240 (defcustom org-babel-load-languages '((emacs-lisp . t))
241 "Languages which can be evaluated in Org buffers.
242 This list can be used to load support for any of the languages
243 below, note that each language will depend on a different set of
244 system executables and/or Emacs modes. When a language is
245 \"loaded\", then code blocks in that language can be evaluated
246 with `org-babel-execute-src-block' bound by default to C-c
247 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
248 be set to remove code block evaluation from the C-c C-c
249 keybinding. By default only Emacs Lisp (which has no
250 requirements) is loaded."
251 :group 'org-babel
252 :set 'org-babel-do-load-languages
253 :version "24.1"
254 :type '(alist :tag "Babel Languages"
255 :key-type
256 (choice
257 (const :tag "Awk" awk)
258 (const :tag "C" C)
259 (const :tag "R" R)
260 (const :tag "Asymptote" asymptote)
261 (const :tag "Calc" calc)
262 (const :tag "Clojure" clojure)
263 (const :tag "CSS" css)
264 (const :tag "Ditaa" ditaa)
265 (const :tag "Dot" dot)
266 (const :tag "Emacs Lisp" emacs-lisp)
267 (const :tag "Forth" forth)
268 (const :tag "Fortran" fortran)
269 (const :tag "Gnuplot" gnuplot)
270 (const :tag "Haskell" haskell)
271 (const :tag "IO" io)
272 (const :tag "J" J)
273 (const :tag "Java" java)
274 (const :tag "Javascript" js)
275 (const :tag "LaTeX" latex)
276 (const :tag "Ledger" ledger)
277 (const :tag "Lilypond" lilypond)
278 (const :tag "Lisp" lisp)
279 (const :tag "Makefile" makefile)
280 (const :tag "Maxima" maxima)
281 (const :tag "Matlab" matlab)
282 (const :tag "Mscgen" mscgen)
283 (const :tag "Ocaml" ocaml)
284 (const :tag "Octave" octave)
285 (const :tag "Org" org)
286 (const :tag "Perl" perl)
287 (const :tag "Pico Lisp" picolisp)
288 (const :tag "PlantUML" plantuml)
289 (const :tag "Python" python)
290 (const :tag "Ruby" ruby)
291 (const :tag "Sass" sass)
292 (const :tag "Scala" scala)
293 (const :tag "Scheme" scheme)
294 (const :tag "Screen" screen)
295 (const :tag "Shell Script" shell)
296 (const :tag "Shen" shen)
297 (const :tag "Sql" sql)
298 (const :tag "Sqlite" sqlite)
299 (const :tag "Stan" stan)
300 (const :tag "ebnf2ps" ebnf2ps))
301 :value-type (boolean :tag "Activate" :value t)))
303 ;;;; Customization variables
304 (defcustom org-clone-delete-id nil
305 "Remove ID property of clones of a subtree.
306 When non-nil, clones of a subtree don't inherit the ID property.
307 Otherwise they inherit the ID property with a new unique
308 identifier."
309 :type 'boolean
310 :version "24.1"
311 :group 'org-id)
313 ;;; Version
314 (org-check-version)
316 ;;;###autoload
317 (defun org-version (&optional here full message)
318 "Show the Org version.
319 Interactively, or when MESSAGE is non-nil, show it in echo area.
320 With prefix argument, or when HERE is non-nil, insert it at point.
321 In non-interactive uses, a reduced version string is output unless
322 FULL is given."
323 (interactive (list current-prefix-arg t (not current-prefix-arg)))
324 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
325 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
326 (load-suffixes (list ".el"))
327 (org-install-dir
328 (ignore-errors (org-find-library-dir "org-loaddefs"))))
329 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
330 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
331 (let* ((load-suffixes save-load-suffixes)
332 (release (org-release))
333 (git-version (org-git-version))
334 (version (format "Org mode version %s (%s @ %s)"
335 release
336 git-version
337 (if org-install-dir
338 (if (string= org-dir org-install-dir)
339 org-install-dir
340 (concat "mixed installation! "
341 org-install-dir
342 " and "
343 org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version release)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1)))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 \\<org-mode-map>
379 A deadline is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-deadline]'.")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 \\<org-mode-map>
386 A schedule is this string, followed by a time stamp. It must be
387 a word, terminated by a colon. You can insert a schedule keyword
388 and a timestamp with `\\[org-schedule]'.")
390 (defconst org-ds-keyword-length
391 (+ 2
392 (apply #'max
393 (mapcar #'length
394 (list org-deadline-string org-scheduled-string
395 org-clock-string org-closed-string))))
396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
398 (defconst org-planning-line-re
399 (concat "^[ \t]*"
400 (regexp-opt
401 (list org-closed-string org-deadline-string org-scheduled-string)
403 "Matches a line with planning info.
404 Matched keyword is in group 1.")
406 (defconst org-clock-line-re
407 (concat "^[ \t]*" org-clock-string)
408 "Matches a line with clock info.")
410 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
411 "Matches the DEADLINE keyword.")
413 (defconst org-deadline-time-regexp
414 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
415 "Matches the DEADLINE keyword together with a time stamp.")
417 (defconst org-deadline-time-hour-regexp
418 (concat "\\<" org-deadline-string
419 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
420 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
422 (defconst org-deadline-line-regexp
423 (concat "\\<\\(" org-deadline-string "\\).*")
424 "Matches the DEADLINE keyword and the rest of the line.")
426 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
427 "Matches the SCHEDULED keyword.")
429 (defconst org-scheduled-time-regexp
430 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
431 "Matches the SCHEDULED keyword together with a time stamp.")
433 (defconst org-scheduled-time-hour-regexp
434 (concat "\\<" org-scheduled-string
435 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
436 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
438 (defconst org-closed-time-regexp
439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
440 "Matches the CLOSED keyword together with a time stamp.")
442 (defconst org-keyword-time-regexp
443 (concat "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string
446 org-clock-string)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 4 keywords, together with the time stamp.")
451 (defconst org-keyword-time-not-clock-regexp
452 (concat
453 "\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string) t)
456 " *[[<]\\([^]>]+\\)[]>]")
457 "Matches any of the 3 keywords, together with the time stamp.")
459 (defconst org-maybe-keyword-time-regexp
460 (concat "\\(\\<"
461 (regexp-opt
462 (list org-scheduled-string org-deadline-string org-closed-string
463 org-clock-string)
465 "\\)?"
466 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "\\|"
468 "<%%([^\r\n>]*>\\)")
469 "Matches a timestamp, possibly preceded by a keyword.")
471 (defconst org-all-time-keywords
472 (mapcar (lambda (w) (substring w 0 -1))
473 (list org-scheduled-string org-deadline-string
474 org-clock-string org-closed-string))
475 "List of time keywords.")
477 ;;;; Drawer
479 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
480 "Matches first or last line of a hidden block.
481 Group 1 contains drawer's name or \"END\".")
483 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
484 "Regular expression matching the first line of a property drawer.")
486 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a property drawer.")
489 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
490 "Regular expression matching the first line of a clock drawer.")
492 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
493 "Regular expression matching the last line of a clock drawer.")
495 (defconst org-property-drawer-re
496 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
497 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
498 "[ \t]*:END:[ \t]*$")
499 "Matches an entire property drawer.")
501 (defconst org-clock-drawer-re
502 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
503 org-clock-drawer-end-re "\\)\n?")
504 "Matches an entire clock drawer.")
506 ;;;; Headline
508 (defconst org-heading-keyword-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline with some keyword.
511 This regexp will match the headline of any node which has the
512 exact keyword that is put into the format. The keyword isn't in
513 any group by default, but the stars and the body are.")
515 (defconst org-heading-keyword-maybe-regexp-format
516 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
517 "Printf format for a regexp matching a headline, possibly with some keyword.
518 This regexp can match any headline with the specified keyword, or
519 without a keyword. The keyword isn't in any group by default,
520 but the stars and the body are.")
522 (defconst org-archive-tag "ARCHIVE"
523 "The tag that marks a subtree as archived.
524 An archived subtree does not open during visibility cycling, and does
525 not contribute to the agenda listings.")
527 (defconst org-comment-string "COMMENT"
528 "Entries starting with this keyword will never be exported.
529 \\<org-mode-map>
530 An entry can be toggled between COMMENT and normal with
531 `\\[org-toggle-comment]'.")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (dolist (ext org-modules)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 (setq org-modules-loaded t)))
666 (defun org-set-modules (var value)
667 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
668 (set var value)
669 (when (featurep 'org)
670 (org-load-modules-maybe 'force)
671 (org-element-cache-reset 'all)))
673 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
674 "Modules that should always be loaded together with org.el.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 You can also use this system to load external packages (i.e. neither Org
681 core modules, nor modules from the CONTRIB directory). Just add symbols
682 to the end of the list. If the package is called org-xyz.el, then you need
683 to add the symbol `xyz', and the package must have a call to:
685 (provide \\='org-xyz)
687 For export specific modules, see also `org-export-backends'."
688 :group 'org
689 :set 'org-set-modules
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type
693 '(set :greedy t
694 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
695 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
696 (const :tag " crypt: Encryption of subtrees" org-crypt)
697 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
698 (const :tag " docview: Links to doc-view buffers" org-docview)
699 (const :tag " eww: Store link to url of eww" org-eww)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defgroup org-startup nil
921 "Options concerning startup of Org mode."
922 :tag "Org Startup"
923 :group 'org)
925 (defcustom org-startup-folded t
926 "Non-nil means entering Org mode will switch to OVERVIEW.
928 This can also be configured on a per-file basis by adding one of
929 the following lines anywhere in the buffer:
931 #+STARTUP: fold (or `overview', this is equivalent)
932 #+STARTUP: nofold (or `showall', this is equivalent)
933 #+STARTUP: content
934 #+STARTUP: showeverything
936 Set `org-agenda-inhibit-startup' to a non-nil value if you want
937 to ignore this option when Org opens agenda files for the first
938 time."
939 :group 'org-startup
940 :type '(choice
941 (const :tag "nofold: show all" nil)
942 (const :tag "fold: overview" t)
943 (const :tag "content: all headlines" content)
944 (const :tag "show everything, even drawers" showeverything)))
946 (defcustom org-startup-truncated t
947 "Non-nil means entering Org mode will set `truncate-lines'.
948 This is useful since some lines containing links can be very long and
949 uninteresting. Also tables look terrible when wrapped.
951 The variable `org-startup-truncated' allows to configure
952 truncation for Org mode different to the other modes that use the
953 variable `truncate-lines' and as a shortcut instead of putting
954 the variable `truncate-lines' into the `org-mode-hook'. If one
955 wants to configure truncation for Org mode not statically but
956 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
957 the variable `truncate-lines' has to be used because in such a
958 case it is too late to set the variable `org-startup-truncated'."
959 :group 'org-startup
960 :type 'boolean)
962 (defcustom org-startup-indented nil
963 "Non-nil means turn on `org-indent-mode' on startup.
964 This can also be configured on a per-file basis by adding one of
965 the following lines anywhere in the buffer:
967 #+STARTUP: indent
968 #+STARTUP: noindent"
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Not" nil)
972 (const :tag "Globally (slow on startup in large files)" t)))
974 (defcustom org-use-sub-superscripts t
975 "Non-nil means interpret \"_\" and \"^\" for display.
977 If you want to control how Org exports those characters, see
978 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
979 used to be an alias for `org-export-with-sub-superscripts' in
980 Org <8.0, it is not anymore.
982 When this option is turned on, you can use TeX-like syntax for
983 sub- and superscripts within the buffer. Several characters after
984 \"_\" or \"^\" will be considered as a single item - so grouping
985 with {} is normally not needed. For example, the following things
986 will be parsed as single sub- or superscripts:
988 10^24 or 10^tau several digits will be considered 1 item.
989 10^-12 or 10^-tau a leading sign with digits or a word
990 x^2-y^3 will be read as x^2 - y^3, because items are
991 terminated by almost any nonword/nondigit char.
992 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
994 Still, ambiguity is possible. So when in doubt, use {} to enclose
995 the sub/superscript. If you set this variable to the symbol `{}',
996 the braces are *required* in order to trigger interpretations as
997 sub/superscript. This can be helpful in documents that need \"_\"
998 frequently in plain text."
999 :group 'org-startup
1000 :version "24.4"
1001 :package-version '(Org . "8.0")
1002 :type '(choice
1003 (const :tag "Always interpret" t)
1004 (const :tag "Only with braces" {})
1005 (const :tag "Never interpret" nil)))
1007 (defcustom org-startup-with-beamer-mode nil
1008 "Non-nil means turn on `org-beamer-mode' on startup.
1009 This can also be configured on a per-file basis by adding one of
1010 the following lines anywhere in the buffer:
1012 #+STARTUP: beamer"
1013 :group 'org-startup
1014 :version "24.1"
1015 :type 'boolean)
1017 (defcustom org-startup-align-all-tables nil
1018 "Non-nil means align all tables when visiting a file.
1019 This is useful when the column width in tables is forced with <N> cookies
1020 in table fields. Such tables will look correct only after the first re-align.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: align
1024 #+STARTUP: noalign"
1025 :group 'org-startup
1026 :type 'boolean)
1028 (defcustom org-startup-with-inline-images nil
1029 "Non-nil means show inline images when loading a new Org file.
1030 This can also be configured on a per-file basis by adding one of
1031 the following lines anywhere in the buffer:
1032 #+STARTUP: inlineimages
1033 #+STARTUP: noinlineimages"
1034 :group 'org-startup
1035 :version "24.1"
1036 :type 'boolean)
1038 (defcustom org-startup-with-latex-preview nil
1039 "Non-nil means preview LaTeX fragments when loading a new Org file.
1041 This can also be configured on a per-file basis by adding one of
1042 the following lines anywhere in the buffer:
1043 #+STARTUP: latexpreview
1044 #+STARTUP: nolatexpreview"
1045 :group 'org-startup
1046 :version "24.4"
1047 :package-version '(Org . "8.0")
1048 :type 'boolean)
1050 (defcustom org-insert-mode-line-in-empty-file nil
1051 "Non-nil means insert the first line setting Org mode in empty files.
1052 When the function `org-mode' is called interactively in an empty file, this
1053 normally means that the file name does not automatically trigger Org mode.
1054 To ensure that the file will always be in Org mode in the future, a
1055 line enforcing Org mode will be inserted into the buffer, if this option
1056 has been set."
1057 :group 'org-startup
1058 :type 'boolean)
1060 (defcustom org-replace-disputed-keys nil
1061 "Non-nil means use alternative key bindings for some keys.
1062 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1063 These keys are also used by other packages like shift-selection-mode'
1064 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1065 If you want to use Org mode together with one of these other modes,
1066 or more generally if you would like to move some Org mode commands to
1067 other keys, set this variable and configure the keys with the variable
1068 `org-disputed-keys'.
1070 This option is only relevant at load-time of Org mode, and must be set
1071 *before* org.el is loaded. Changing it requires a restart of Emacs to
1072 become effective."
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-use-extra-keys nil
1077 "Non-nil means use extra key sequence definitions for certain commands.
1078 This happens automatically if `window-system' is nil. This
1079 variable lets you do the same manually. You must set it before
1080 loading Org."
1081 :group 'org-startup
1082 :type 'boolean)
1084 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1086 (defcustom org-disputed-keys
1087 '(([(shift up)] . [(meta p)])
1088 ([(shift down)] . [(meta n)])
1089 ([(shift left)] . [(meta -)])
1090 ([(shift right)] . [(meta +)])
1091 ([(control shift right)] . [(meta shift +)])
1092 ([(control shift left)] . [(meta shift -)]))
1093 "Keys for which Org mode and other modes compete.
1094 This is an alist, cars are the default keys, second element specifies
1095 the alternative to use when `org-replace-disputed-keys' is t.
1097 Keys can be specified in any syntax supported by `define-key'.
1098 The value of this option takes effect only at Org mode startup,
1099 therefore you'll have to restart Emacs to apply it after changing."
1100 :group 'org-startup
1101 :type 'alist)
1103 (defun org-key (key)
1104 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1105 Or return the original if not disputed."
1106 (when org-replace-disputed-keys
1107 (let* ((nkey (key-description key))
1108 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1109 org-disputed-keys)))
1110 (setq key (if x (cdr x) key))))
1111 key)
1113 (defun org-defkey (keymap key def)
1114 "Define a key, possibly translated, as returned by `org-key'."
1115 (define-key keymap (org-key key) def))
1117 (defcustom org-ellipsis nil
1118 "The ellipsis to use in the Org mode outline.
1120 When nil, just use the standard three dots.
1121 When a string, use that string instead.
1123 The change affects only Org mode (which will then use its own display table).
1124 Changing this requires executing `\\[org-mode]' in a buffer to become
1125 effective."
1126 :group 'org-startup
1127 :type '(choice (const :tag "Default" nil)
1128 (string :tag "String" :value "...#"))
1129 :safe #'string-or-null-p)
1131 (defvar org-display-table nil
1132 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1134 (defgroup org-keywords nil
1135 "Keywords in Org mode."
1136 :tag "Org Keywords"
1137 :group 'org)
1139 (defcustom org-closed-keep-when-no-todo nil
1140 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1141 :group 'org-todo
1142 :group 'org-keywords
1143 :version "24.4"
1144 :package-version '(Org . "8.0")
1145 :type 'boolean)
1147 (defgroup org-structure nil
1148 "Options concerning the general structure of Org files."
1149 :tag "Org Structure"
1150 :group 'org)
1152 (defgroup org-reveal-location nil
1153 "Options about how to make context of a location visible."
1154 :tag "Org Reveal Location"
1155 :group 'org-structure)
1157 (defcustom org-show-context-detail '((agenda . local)
1158 (bookmark-jump . lineage)
1159 (isearch . lineage)
1160 (default . ancestors))
1161 "Alist between context and visibility span when revealing a location.
1163 \\<org-mode-map>Some actions may move point into invisible
1164 locations. As a consequence, Org always expose a neighborhood
1165 around point. How much is shown depends on the initial action,
1166 or context. Valid contexts are
1168 agenda when exposing an entry from the agenda
1169 org-goto when using the command `org-goto' (`\\[org-goto]')
1170 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1171 tags-tree when constructing a sparse tree based on tags matches
1172 link-search when exposing search matches associated with a link
1173 mark-goto when exposing the jump goal of a mark
1174 bookmark-jump when exposing a bookmark location
1175 isearch when exiting from an incremental search
1176 default default for all contexts not set explicitly
1178 Allowed visibility spans are
1180 minimal show current headline; if point is not on headline,
1181 also show entry
1183 local show current headline, entry and next headline
1185 ancestors show current headline and its direct ancestors; if
1186 point is not on headline, also show entry
1188 lineage show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and first child
1192 tree show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and all children
1196 canonical show current headline, its direct ancestors along with
1197 their entries and children; if point is not located on
1198 the headline, also show current entry and all children
1200 As special cases, a nil or t value means show all contexts in
1201 `minimal' or `canonical' view, respectively.
1203 Some views can make displayed information very compact, but also
1204 make it harder to edit the location of the match. In such
1205 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1206 more context."
1207 :group 'org-reveal-location
1208 :version "26.1"
1209 :package-version '(Org . "9.0")
1210 :type '(choice
1211 (const :tag "Canonical" t)
1212 (const :tag "Minimal" nil)
1213 (repeat :greedy t :tag "Individual contexts"
1214 (cons
1215 (choice :tag "Context"
1216 (const agenda)
1217 (const org-goto)
1218 (const occur-tree)
1219 (const tags-tree)
1220 (const link-search)
1221 (const mark-goto)
1222 (const bookmark-jump)
1223 (const isearch)
1224 (const default))
1225 (choice :tag "Detail level"
1226 (const minimal)
1227 (const local)
1228 (const ancestors)
1229 (const lineage)
1230 (const tree)
1231 (const canonical))))))
1233 (defcustom org-indirect-buffer-display 'other-window
1234 "How should indirect tree buffers be displayed?
1236 This applies to indirect buffers created with the commands
1237 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1239 Valid values are:
1240 current-window Display in the current window
1241 other-window Just display in another window.
1242 dedicated-frame Create one new frame, and re-use it each time.
1243 new-frame Make a new frame each time. Note that in this case
1244 previously-made indirect buffers are kept, and you need to
1245 kill these buffers yourself."
1246 :group 'org-structure
1247 :group 'org-agenda-windows
1248 :type '(choice
1249 (const :tag "In current window" current-window)
1250 (const :tag "In current frame, other window" other-window)
1251 (const :tag "Each time a new frame" new-frame)
1252 (const :tag "One dedicated frame" dedicated-frame)))
1254 (defcustom org-use-speed-commands nil
1255 "Non-nil means activate single letter commands at beginning of a headline.
1256 This may also be a function to test for appropriate locations where speed
1257 commands should be active.
1259 For example, to activate speed commands when the point is on any
1260 star at the beginning of the headline, you can do this:
1262 (setq org-use-speed-commands
1263 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1264 :group 'org-structure
1265 :type '(choice
1266 (const :tag "Never" nil)
1267 (const :tag "At beginning of headline stars" t)
1268 (function)))
1270 (defcustom org-speed-commands-user nil
1271 "Alist of additional speed commands.
1272 This list will be checked before `org-speed-commands-default'
1273 when the variable `org-use-speed-commands' is non-nil
1274 and when the cursor is at the beginning of a headline.
1275 The car if each entry is a string with a single letter, which must
1276 be assigned to `self-insert-command' in the global map.
1277 The cdr is either a command to be called interactively, a function
1278 to be called, or a form to be evaluated.
1279 An entry that is just a list with a single string will be interpreted
1280 as a descriptive headline that will be added when listing the speed
1281 commands in the Help buffer using the `?' speed command."
1282 :group 'org-structure
1283 :type '(repeat :value ("k" . ignore)
1284 (choice :value ("k" . ignore)
1285 (list :tag "Descriptive Headline" (string :tag "Headline"))
1286 (cons :tag "Letter and Command"
1287 (string :tag "Command letter")
1288 (choice
1289 (function)
1290 (sexp))))))
1292 (defcustom org-bookmark-names-plist
1293 '(:last-capture "org-capture-last-stored"
1294 :last-refile "org-refile-last-stored"
1295 :last-capture-marker "org-capture-last-stored-marker")
1296 "Names for bookmarks automatically set by some Org commands.
1297 This can provide strings as names for a number of bookmarks Org sets
1298 automatically. The following keys are currently implemented:
1299 :last-capture
1300 :last-capture-marker
1301 :last-refile
1302 When a key does not show up in the property list, the corresponding bookmark
1303 is not set."
1304 :group 'org-structure
1305 :type 'plist)
1307 (defgroup org-cycle nil
1308 "Options concerning visibility cycling in Org mode."
1309 :tag "Org Cycle"
1310 :group 'org-structure)
1312 (defcustom org-cycle-skip-children-state-if-no-children t
1313 "Non-nil means skip CHILDREN state in entries that don't have any."
1314 :group 'org-cycle
1315 :type 'boolean)
1317 (defcustom org-cycle-max-level nil
1318 "Maximum level which should still be subject to visibility cycling.
1319 Levels higher than this will, for cycling, be treated as text, not a headline.
1320 When `org-odd-levels-only' is set, a value of N in this variable actually
1321 means 2N-1 stars as the limiting headline.
1322 When nil, cycle all levels.
1323 Note that the limiting level of cycling is also influenced by
1324 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1325 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1326 than its value."
1327 :group 'org-cycle
1328 :type '(choice
1329 (const :tag "No limit" nil)
1330 (integer :tag "Maximum level")))
1332 (defcustom org-hide-block-startup nil
1333 "Non-nil means entering Org mode will fold all blocks.
1334 This can also be set in on a per-file basis with
1336 #+STARTUP: hideblocks
1337 #+STARTUP: showblocks"
1338 :group 'org-startup
1339 :group 'org-cycle
1340 :type 'boolean)
1342 (defcustom org-cycle-global-at-bob nil
1343 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1345 This makes it possible to do global cycling without having to use `S-TAB'
1346 or `\\[universal-argument] TAB'. For this special case to work, the first \
1347 line of the buffer
1348 must not be a headline -- it may be empty or some other text.
1350 When used in this way, `org-cycle-hook' is disabled temporarily to make
1351 sure the cursor stays at the beginning of the buffer.
1353 When this option is nil, don't do anything special at the beginning of
1354 the buffer."
1355 :group 'org-cycle
1356 :type 'boolean)
1358 (defcustom org-cycle-level-after-item/entry-creation t
1359 "Non-nil means cycle entry level or item indentation in new empty entries.
1361 When the cursor is at the end of an empty headline, i.e., with only stars
1362 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1363 and then all possible ancestor states, before returning to the original state.
1364 This makes data entry extremely fast: M-RET to create a new headline,
1365 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1367 When the cursor is at the end of an empty plain list item, one TAB will
1368 make it a subitem, two or more tabs will back up to make this an item
1369 higher up in the item hierarchy."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-emulate-tab t
1374 "Where should `org-cycle' emulate TAB.
1375 nil Never
1376 white Only in completely white lines
1377 whitestart Only at the beginning of lines, before the first non-white char
1378 t Everywhere except in headlines
1379 exc-hl-bol Everywhere except at the start of a headline
1380 If TAB is used in a place where it does not emulate TAB, the current subtree
1381 visibility is cycled."
1382 :group 'org-cycle
1383 :type '(choice (const :tag "Never" nil)
1384 (const :tag "Only in completely white lines" white)
1385 (const :tag "Before first char in a line" whitestart)
1386 (const :tag "Everywhere except in headlines" t)
1387 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1389 (defcustom org-cycle-separator-lines 2
1390 "Number of empty lines needed to keep an empty line between collapsed trees.
1391 If you leave an empty line between the end of a subtree and the following
1392 headline, this empty line is hidden when the subtree is folded.
1393 Org mode will leave (exactly) one empty line visible if the number of
1394 empty lines is equal or larger to the number given in this variable.
1395 So the default 2 means at least 2 empty lines after the end of a subtree
1396 are needed to produce free space between a collapsed subtree and the
1397 following headline.
1399 If the number is negative, and the number of empty lines is at least -N,
1400 all empty lines are shown.
1402 Special case: when 0, never leave empty lines in collapsed view."
1403 :group 'org-cycle
1404 :type 'integer)
1405 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1407 (defcustom org-pre-cycle-hook nil
1408 "Hook that is run before visibility cycling is happening.
1409 The function(s) in this hook must accept a single argument which indicates
1410 the new state that will be set right after running this hook. The
1411 argument is a symbol. Before a global state change, it can have the values
1412 `overview', `content', or `all'. Before a local state change, it can have
1413 the values `folded', `children', or `subtree'."
1414 :group 'org-cycle
1415 :type 'hook)
1417 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1418 org-cycle-hide-drawers
1419 org-cycle-show-empty-lines
1420 org-optimize-window-after-visibility-change)
1421 "Hook that is run after `org-cycle' has changed the buffer visibility.
1422 The function(s) in this hook must accept a single argument which indicates
1423 the new state that was set by the most recent `org-cycle' command. The
1424 argument is a symbol. After a global state change, it can have the values
1425 `overview', `contents', or `all'. After a local state change, it can have
1426 the values `folded', `children', or `subtree'."
1427 :group 'org-cycle
1428 :type 'hook
1429 :version "26.1"
1430 :package-version '(Org . "8.3"))
1432 (defgroup org-edit-structure nil
1433 "Options concerning structure editing in Org mode."
1434 :tag "Org Edit Structure"
1435 :group 'org-structure)
1437 (defcustom org-odd-levels-only nil
1438 "Non-nil means skip even levels and only use odd levels for the outline.
1439 This has the effect that two stars are being added/taken away in
1440 promotion/demotion commands. It also influences how levels are
1441 handled by the exporters.
1442 Changing it requires restart of `font-lock-mode' to become effective
1443 for fontification also in regions already fontified.
1444 You may also set this on a per-file basis by adding one of the following
1445 lines to the buffer:
1447 #+STARTUP: odd
1448 #+STARTUP: oddeven"
1449 :group 'org-edit-structure
1450 :group 'org-appearance
1451 :type 'boolean)
1453 (defcustom org-adapt-indentation t
1454 "Non-nil means adapt indentation to outline node level.
1456 When this variable is set, Org assumes that you write outlines by
1457 indenting text in each node to align with the headline (after the
1458 stars). The following issues are influenced by this variable:
1460 - The indentation is increased by one space in a demotion
1461 command, and decreased by one in a promotion command. However,
1462 in the latter case, if shifting some line in the entry body
1463 would alter document structure (e.g., insert a new headline),
1464 indentation is not changed at all.
1466 - Property drawers and planning information is inserted indented
1467 when this variable is set. When nil, they will not be indented.
1469 - TAB indents a line relative to current level. The lines below
1470 a headline will be indented when this variable is set.
1472 Note that this is all about true indentation, by adding and
1473 removing space characters. See also `org-indent.el' which does
1474 level-dependent indentation in a virtual way, i.e. at display
1475 time in Emacs."
1476 :group 'org-edit-structure
1477 :type 'boolean)
1479 (defcustom org-special-ctrl-a/e nil
1480 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1482 When t, `C-a' will bring back the cursor to the beginning of the
1483 headline text, i.e. after the stars and after a possible TODO
1484 keyword. In an item, this will be the position after bullet and
1485 check-box, if any. When the cursor is already at that position,
1486 another `C-a' will bring it to the beginning of the line.
1488 `C-e' will jump to the end of the headline, ignoring the presence
1489 of tags in the headline. A second `C-e' will then jump to the
1490 true end of the line, after any tags. This also means that, when
1491 this variable is non-nil, `C-e' also will never jump beyond the
1492 end of the heading of a folded section, i.e. not after the
1493 ellipses.
1495 When set to the symbol `reversed', the first `C-a' or `C-e' works
1496 normally, going to the true line boundary first. Only a directly
1497 following, identical keypress will bring the cursor to the
1498 special positions.
1500 This may also be a cons cell where the behavior for `C-a' and
1501 `C-e' is set separately."
1502 :group 'org-edit-structure
1503 :type '(choice
1504 (const :tag "off" nil)
1505 (const :tag "on: after stars/bullet and before tags first" t)
1506 (const :tag "reversed: true line boundary first" reversed)
1507 (cons :tag "Set C-a and C-e separately"
1508 (choice :tag "Special C-a"
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet first" t)
1511 (const :tag "reversed: before stars/bullet first" reversed))
1512 (choice :tag "Special C-e"
1513 (const :tag "off" nil)
1514 (const :tag "on: before tags first" t)
1515 (const :tag "reversed: after tags first" reversed)))))
1516 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1518 (defcustom org-special-ctrl-k nil
1519 "Non-nil means `C-k' will behave specially in headlines.
1520 When nil, `C-k' will call the default `kill-line' command.
1521 When t, the following will happen while the cursor is in the headline:
1523 - When the cursor is at the beginning of a headline, kill the entire
1524 line and possible the folded subtree below the line.
1525 - When in the middle of the headline text, kill the headline up to the tags.
1526 - When after the headline text, kill the tags."
1527 :group 'org-edit-structure
1528 :type 'boolean)
1530 (defcustom org-ctrl-k-protect-subtree nil
1531 "Non-nil means, do not delete a hidden subtree with C-k.
1532 When set to the symbol `error', simply throw an error when C-k is
1533 used to kill (part-of) a headline that has hidden text behind it.
1534 Any other non-nil value will result in a query to the user, if it is
1535 OK to kill that hidden subtree. When nil, kill without remorse."
1536 :group 'org-edit-structure
1537 :version "24.1"
1538 :type '(choice
1539 (const :tag "Do not protect hidden subtrees" nil)
1540 (const :tag "Protect hidden subtrees with a security query" t)
1541 (const :tag "Never kill a hidden subtree with C-k" error)))
1543 (defcustom org-special-ctrl-o t
1544 "Non-nil means, make `C-o' insert a row in tables."
1545 :group 'org-edit-structure
1546 :type 'boolean)
1548 (defcustom org-catch-invisible-edits nil
1549 "Check if in invisible region before inserting or deleting a character.
1550 Valid values are:
1552 nil Do not check, so just do invisible edits.
1553 error Throw an error and do nothing.
1554 show Make point visible, and do the requested edit.
1555 show-and-error Make point visible, then throw an error and abort the edit.
1556 smart Make point visible, and do insertion/deletion if it is
1557 adjacent to visible text and the change feels predictable.
1558 Never delete a previously invisible character or add in the
1559 middle or right after an invisible region. Basically, this
1560 allows insertion and backward-delete right before ellipses.
1561 FIXME: maybe in this case we should not even show?"
1562 :group 'org-edit-structure
1563 :version "24.1"
1564 :type '(choice
1565 (const :tag "Do not check" nil)
1566 (const :tag "Throw error when trying to edit" error)
1567 (const :tag "Unhide, but do not do the edit" show-and-error)
1568 (const :tag "Show invisible part and do the edit" show)
1569 (const :tag "Be smart and do the right thing" smart)))
1571 (defcustom org-yank-folded-subtrees t
1572 "Non-nil means when yanking subtrees, fold them.
1573 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1574 it starts with a heading and all other headings in it are either children
1575 or siblings, then fold all the subtrees. However, do this only if no
1576 text after the yank would be swallowed into a folded tree by this action."
1577 :group 'org-edit-structure
1578 :type 'boolean)
1580 (defcustom org-yank-adjusted-subtrees nil
1581 "Non-nil means when yanking subtrees, adjust the level.
1582 With this setting, `org-paste-subtree' is used to insert the subtree, see
1583 this function for details."
1584 :group 'org-edit-structure
1585 :type 'boolean)
1587 (defcustom org-M-RET-may-split-line '((default . t))
1588 "Non-nil means M-RET will split the line at the cursor position.
1589 When nil, it will go to the end of the line before making a
1590 new line.
1591 You may also set this option in a different way for different
1592 contexts. Valid contexts are:
1594 headline when creating a new headline
1595 item when creating a new item
1596 table in a table field
1597 default the value to be used for all contexts not explicitly
1598 customized"
1599 :group 'org-structure
1600 :group 'org-table
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Never" nil)
1604 (repeat :greedy t :tag "Individual contexts"
1605 (cons
1606 (choice :tag "Context"
1607 (const headline)
1608 (const item)
1609 (const table)
1610 (const default))
1611 (boolean)))))
1614 (defcustom org-insert-heading-respect-content nil
1615 "Non-nil means insert new headings after the current subtree.
1616 \\<org-mode-map>
1617 When nil, the new heading is created directly after the current line.
1618 The commands `\\[org-insert-heading-respect-content]' and \
1619 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1620 for the duration of the command."
1621 :group 'org-structure
1622 :type 'boolean)
1624 (defcustom org-blank-before-new-entry '((heading . auto)
1625 (plain-list-item . auto))
1626 "Should `org-insert-heading' leave a blank line before new heading/item?
1627 The value is an alist, with `heading' and `plain-list-item' as CAR,
1628 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1629 which case Org will look at the surrounding headings/items and try to
1630 make an intelligent decision whether to insert a blank line or not."
1631 :group 'org-edit-structure
1632 :type '(list
1633 (cons (const heading)
1634 (choice (const :tag "Never" nil)
1635 (const :tag "Always" t)
1636 (const :tag "Auto" auto)))
1637 (cons (const plain-list-item)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))))
1642 (defcustom org-insert-heading-hook nil
1643 "Hook being run after inserting a new heading."
1644 :group 'org-edit-structure
1645 :type 'hook)
1647 (defcustom org-enable-fixed-width-editor t
1648 "Non-nil means lines starting with \":\" are treated as fixed-width.
1649 This currently only means they are never auto-wrapped.
1650 When nil, such lines will be treated like ordinary lines."
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defcustom org-goto-auto-isearch t
1655 "Non-nil means typing characters in `org-goto' starts incremental search.
1656 When nil, you can use these keybindings to navigate the buffer:
1658 q Quit the org-goto interface
1659 n Go to the next visible heading
1660 p Go to the previous visible heading
1661 f Go one heading forward on same level
1662 b Go one heading backward on same level
1663 u Go one heading up"
1664 :group 'org-edit-structure
1665 :type 'boolean)
1667 (defgroup org-sparse-trees nil
1668 "Options concerning sparse trees in Org mode."
1669 :tag "Org Sparse Trees"
1670 :group 'org-structure)
1672 (defcustom org-highlight-sparse-tree-matches t
1673 "Non-nil means highlight all matches that define a sparse tree.
1674 The highlights will automatically disappear the next time the buffer is
1675 changed by an edit command."
1676 :group 'org-sparse-trees
1677 :type 'boolean)
1679 (defcustom org-remove-highlights-with-change t
1680 "Non-nil means any change to the buffer will remove temporary highlights.
1681 \\<org-mode-map>\
1682 Such highlights are created by `org-occur' and `org-clock-display'.
1683 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1684 to get rid of the highlights.
1685 The highlights created by `org-toggle-latex-fragment' always need
1686 `\\[org-toggle-latex-fragment]' to be removed."
1687 :group 'org-sparse-trees
1688 :group 'org-time
1689 :type 'boolean)
1691 (defcustom org-occur-case-fold-search t
1692 "Non-nil means `org-occur' should be case-insensitive.
1693 If set to `smart' the search will be case-insensitive only if it
1694 doesn't specify any upper case character."
1695 :group 'org-sparse-trees
1696 :version "26.1"
1697 :type '(choice
1698 (const :tag "Case-sensitive" nil)
1699 (const :tag "Case-insensitive" t)
1700 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1702 (defcustom org-occur-hook '(org-first-headline-recenter)
1703 "Hook that is run after `org-occur' has constructed a sparse tree.
1704 This can be used to recenter the window to show as much of the structure
1705 as possible."
1706 :group 'org-sparse-trees
1707 :type 'hook)
1709 (defgroup org-imenu-and-speedbar nil
1710 "Options concerning imenu and speedbar in Org mode."
1711 :tag "Org Imenu and Speedbar"
1712 :group 'org-structure)
1714 (defcustom org-imenu-depth 2
1715 "The maximum level for Imenu access to Org headlines.
1716 This also applied for speedbar access."
1717 :group 'org-imenu-and-speedbar
1718 :type 'integer)
1720 (defgroup org-table nil
1721 "Options concerning tables in Org mode."
1722 :tag "Org Table"
1723 :group 'org)
1725 (defcustom org-enable-table-editor 'optimized
1726 "Non-nil means lines starting with \"|\" are handled by the table editor.
1727 When nil, such lines will be treated like ordinary lines.
1729 When equal to the symbol `optimized', the table editor will be optimized to
1730 do the following:
1731 - Automatic overwrite mode in front of whitespace in table fields.
1732 This makes the structure of the table stay in tact as long as the edited
1733 field does not exceed the column width.
1734 - Minimize the number of realigns. Normally, the table is aligned each time
1735 TAB or RET are pressed to move to another field. With optimization this
1736 happens only if changes to a field might have changed the column width.
1737 Optimization requires replacing the functions `self-insert-command',
1738 `delete-char', and `backward-delete-char' in Org buffers, with a
1739 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1740 good at guessing when a re-align will be necessary, but you can always
1741 force one with `\\[org-ctrl-c-ctrl-c]'.
1743 If you would like to use the optimized version in Org mode, but the
1744 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1746 This variable can be used to turn on and off the table editor during a session,
1747 but in order to toggle optimization, a restart is required.
1749 See also the variable `org-table-auto-blank-field'."
1750 :group 'org-table
1751 :type '(choice
1752 (const :tag "off" nil)
1753 (const :tag "on" t)
1754 (const :tag "on, optimized" optimized)))
1756 (defcustom org-self-insert-cluster-for-undo nil
1757 "Non-nil means cluster self-insert commands for undo when possible.
1758 If this is set, then, like in the Emacs command loop, 20 consecutive
1759 characters will be undone together.
1760 This is configurable, because there is some impact on typing performance."
1761 :group 'org-table
1762 :type 'boolean)
1764 (defcustom org-table-tab-recognizes-table.el t
1765 "Non-nil means TAB will automatically notice a table.el table.
1766 When it sees such a table, it moves point into it and - if necessary -
1767 calls `table-recognize-table'."
1768 :group 'org-table-editing
1769 :type 'boolean)
1771 (defgroup org-link nil
1772 "Options concerning links in Org mode."
1773 :tag "Org Link"
1774 :group 'org)
1776 (defvar-local org-link-abbrev-alist-local nil
1777 "Buffer-local version of `org-link-abbrev-alist', which see.
1778 The value of this is taken from the #+LINK lines.")
1780 (defcustom org-link-parameters
1781 '(("doi" :follow org--open-doi-link)
1782 ("elisp" :follow org--open-elisp-link)
1783 ("file" :complete org-file-complete-link)
1784 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1785 ("help" :follow org--open-help-link)
1786 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1787 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1788 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1789 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1790 ("shell" :follow org--open-shell-link))
1791 "An alist of properties that defines all the links in Org mode.
1792 The key in each association is a string of the link type.
1793 Subsequent optional elements make up a p-list of link properties.
1795 :follow - A function that takes the link path as an argument.
1797 :export - A function that takes the link path, description and
1798 export-backend as arguments.
1800 :store - A function responsible for storing the link. See the
1801 function `org-store-link-functions'.
1803 :complete - A function that inserts a link with completion. The
1804 function takes one optional prefix arg.
1806 :face - A face for the link, or a function that returns a face.
1807 The function takes one argument which is the link path. The
1808 default face is `org-link'.
1810 :mouse-face - The mouse-face. The default is `highlight'.
1812 :display - `full' will not fold the link in descriptive
1813 display. Default is `org-link'.
1815 :help-echo - A string or function that takes (window object position)
1816 as arguments and returns a string.
1818 :keymap - A keymap that is active on the link. The default is
1819 `org-mouse-map'.
1821 :htmlize-link - A function for the htmlize-link. Defaults
1822 to (list :uri \"type:path\")
1824 :activate-func - A function to run at the end of font-lock
1825 activation. The function must accept (link-start link-end path bracketp)
1826 as arguments."
1827 :group 'org-link
1828 :type '(alist :tag "Link display parameters"
1829 :value-type plist)
1830 :version "26.1"
1831 :package-version '(Org . "9.1"))
1833 (defun org-link-get-parameter (type key)
1834 "Get TYPE link property for KEY.
1835 TYPE is a string and KEY is a plist keyword."
1836 (plist-get
1837 (cdr (assoc type org-link-parameters))
1838 key))
1840 (defun org-link-set-parameters (type &rest parameters)
1841 "Set link TYPE properties to PARAMETERS.
1842 PARAMETERS should be :key val pairs."
1843 (let ((data (assoc type org-link-parameters)))
1844 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1845 (push (cons type parameters) org-link-parameters)
1846 (org-make-link-regexps)
1847 (org-element-update-syntax))))
1849 (defun org-link-types ()
1850 "Return a list of known link types."
1851 (mapcar #'car org-link-parameters))
1853 (defcustom org-link-abbrev-alist nil
1854 "Alist of link abbreviations.
1855 The car of each element is a string, to be replaced at the start of a link.
1856 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1857 links in Org buffers can have an optional tag after a double colon, e.g.,
1859 [[linkkey:tag][description]]
1861 The `linkkey' must be a single word, starting with a letter, followed
1862 by letters, numbers, `-' or `_'.
1864 If REPLACE is a string, the tag will simply be appended to create the link.
1865 If the string contains \"%s\", the tag will be inserted there. If the string
1866 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1867 at that point (see the function `url-hexify-string'). If the string contains
1868 the specifier \"%(my-function)\", then the custom function `my-function' will
1869 be invoked: this function takes the tag as its only argument and must return
1870 a string.
1872 REPLACE may also be a function that will be called with the tag as the
1873 only argument to create the link, which should be returned as a string.
1875 See the manual for examples."
1876 :group 'org-link
1877 :type '(repeat
1878 (cons
1879 (string :tag "Protocol")
1880 (choice
1881 (string :tag "Format")
1882 (function)))))
1884 (defcustom org-descriptive-links t
1885 "Non-nil means Org will display descriptive links.
1886 E.g. [[http://orgmode.org][Org website]] will be displayed as
1887 \"Org Website\", hiding the link itself and just displaying its
1888 description. When set to nil, Org will display the full links
1889 literally.
1891 You can interactively set the value of this variable by calling
1892 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1893 :group 'org-link
1894 :type 'boolean)
1896 (defcustom org-link-file-path-type 'adaptive
1897 "How the path name in file links should be stored.
1898 Valid values are:
1900 relative Relative to the current directory, i.e. the directory of the file
1901 into which the link is being inserted.
1902 absolute Absolute path, if possible with ~ for home directory.
1903 noabbrev Absolute path, no abbreviation of home directory.
1904 adaptive Use relative path for files in the current directory and sub-
1905 directories of it. For other files, use an absolute path."
1906 :group 'org-link
1907 :type '(choice
1908 (const relative)
1909 (const absolute)
1910 (const noabbrev)
1911 (const adaptive)))
1913 (defvaralias 'org-activate-links 'org-highlight-links)
1914 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1915 "Types of links that should be highlighted in Org files.
1917 This is a list of symbols, each one of them leading to the
1918 highlighting of a certain link type.
1920 You can still open links that are not highlighted.
1922 In principle, it does not hurt to turn on highlighting for all
1923 link types. There may be a small gain when turning off unused
1924 link types. The types are:
1926 bracket The recommended [[link][description]] or [[link]] links with hiding.
1927 angle Links in angular brackets that may contain whitespace like
1928 <bbdb:Carsten Dominik>.
1929 plain Plain links in normal text, no whitespace, like http://google.com.
1930 radio Text that is matched by a radio target, see manual for details.
1931 tag Tag settings in a headline (link to tag search).
1932 date Time stamps (link to calendar).
1933 footnote Footnote labels.
1935 If you set this variable during an Emacs session, use `org-mode-restart'
1936 in the Org buffer so that the change takes effect."
1937 :group 'org-link
1938 :group 'org-appearance
1939 :type '(set :greedy t
1940 (const :tag "Double bracket links" bracket)
1941 (const :tag "Angular bracket links" angle)
1942 (const :tag "Plain text links" plain)
1943 (const :tag "Radio target matches" radio)
1944 (const :tag "Tags" tag)
1945 (const :tag "Timestamps" date)
1946 (const :tag "Footnotes" footnote)))
1948 (defcustom org-make-link-description-function nil
1949 "Function to use for generating link descriptions from links.
1950 When nil, the link location will be used. This function must take
1951 two parameters: the first one is the link, the second one is the
1952 description generated by `org-insert-link'. The function should
1953 return the description to use."
1954 :group 'org-link
1955 :type '(choice (const nil) (function)))
1957 (defgroup org-link-store nil
1958 "Options concerning storing links in Org mode."
1959 :tag "Org Store Link"
1960 :group 'org-link)
1962 (defcustom org-url-hexify-p t
1963 "When non-nil, hexify URL when creating a link."
1964 :type 'boolean
1965 :version "24.3"
1966 :group 'org-link-store)
1968 (defcustom org-email-link-description-format "Email %c: %.30s"
1969 "Format of the description part of a link to an email or usenet message.
1970 The following %-escapes will be replaced by corresponding information:
1972 %F full \"From\" field
1973 %f name, taken from \"From\" field, address if no name
1974 %T full \"To\" field
1975 %t first name in \"To\" field, address if no name
1976 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1977 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1978 %s subject
1979 %d date
1980 %m message-id.
1982 You may use normal field width specification between the % and the letter.
1983 This is for example useful to limit the length of the subject.
1985 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1986 :group 'org-link-store
1987 :type 'string)
1989 (defcustom org-from-is-user-regexp
1990 (let (r1 r2)
1991 (when (and user-mail-address (not (string= user-mail-address "")))
1992 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1993 (when (and user-full-name (not (string= user-full-name "")))
1994 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1995 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1996 "Regexp matched against the \"From:\" header of an email or usenet message.
1997 It should match if the message is from the user him/herself."
1998 :group 'org-link-store
1999 :type 'regexp)
2001 (defcustom org-context-in-file-links t
2002 "Non-nil means file links from `org-store-link' contain context.
2003 \\<org-mode-map>
2004 A search string will be added to the file name with :: as separator
2005 and used to find the context when the link is activated by the command
2006 `org-open-at-point'. When this option is t, the entire active region
2007 will be placed in the search string of the file link. If set to a
2008 positive integer, only the first n lines of context will be stored.
2010 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2011 \\[org-store-link]')
2012 negates this setting for the duration of the command."
2013 :group 'org-link-store
2014 :type '(choice boolean integer))
2016 (defcustom org-keep-stored-link-after-insertion nil
2017 "Non-nil means keep link in list for entire session.
2018 \\<org-mode-map>
2019 The command `org-store-link' adds a link pointing to the current
2020 location to an internal list. These links accumulate during a session.
2021 The command `org-insert-link' can be used to insert links into any
2022 Org file (offering completion for all stored links).
2024 When this option is nil, every link which has been inserted once using
2025 `\\[org-insert-link]' will be removed from the list, to make completing the \
2026 unused
2027 links more efficient."
2028 :group 'org-link-store
2029 :type 'boolean)
2031 (defgroup org-link-follow nil
2032 "Options concerning following links in Org mode."
2033 :tag "Org Follow Link"
2034 :group 'org-link)
2036 (defcustom org-link-translation-function nil
2037 "Function to translate links with different syntax to Org syntax.
2038 This can be used to translate links created for example by the Planner
2039 or emacs-wiki packages to Org syntax.
2040 The function must accept two parameters, a TYPE containing the link
2041 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2042 which is everything after the link protocol. It should return a cons
2043 with possibly modified values of type and path.
2044 Org contains a function for this, so if you set this variable to
2045 `org-translate-link-from-planner', you should be able follow many
2046 links created by planner."
2047 :group 'org-link-follow
2048 :type '(choice (const nil) (function)))
2050 (defcustom org-follow-link-hook nil
2051 "Hook that is run after a link has been followed."
2052 :group 'org-link-follow
2053 :type 'hook)
2055 (defcustom org-tab-follows-link nil
2056 "Non-nil means on links TAB will follow the link.
2057 Needs to be set before org.el is loaded.
2058 This really should not be used, it does not make sense, and the
2059 implementation is bad."
2060 :group 'org-link-follow
2061 :type 'boolean)
2063 (defcustom org-return-follows-link nil
2064 "Non-nil means on links RET will follow the link.
2065 In tables, the special behavior of RET has precedence."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-mouse-1-follows-link
2070 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2071 "Non-nil means mouse-1 on a link will follow the link.
2072 A longer mouse click will still set point. Needs to be set
2073 before org.el is loaded."
2074 :group 'org-link-follow
2075 :version "24.4"
2076 :package-version '(Org . "8.3")
2077 :type '(choice
2078 (const :tag "A double click follows the link" double)
2079 (const :tag "Unconditionally follow the link with mouse-1" t)
2080 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2082 (defcustom org-mark-ring-length 4
2083 "Number of different positions to be recorded in the ring.
2084 Changing this requires a restart of Emacs to work correctly."
2085 :group 'org-link-follow
2086 :type 'integer)
2088 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2089 "Non-nil means internal fuzzy links can only match headlines.
2091 When nil, the a fuzzy link may point to a target or a named
2092 construct in the document. When set to the special value
2093 `query-to-create', offer to create a new headline when none
2094 matched.
2096 Spaces and statistics cookies are ignored during heading searches."
2097 :group 'org-link-follow
2098 :version "24.1"
2099 :type '(choice
2100 (const :tag "Use fuzzy text search" nil)
2101 (const :tag "Match only exact headline" t)
2102 (const :tag "Match exact headline or query to create it"
2103 query-to-create))
2104 :safe #'symbolp)
2106 (defcustom org-link-frame-setup
2107 '((vm . vm-visit-folder-other-frame)
2108 (vm-imap . vm-visit-imap-folder-other-frame)
2109 (gnus . org-gnus-no-new-news)
2110 (file . find-file-other-window)
2111 (wl . wl-other-frame))
2112 "Setup the frame configuration for following links.
2113 When following a link with Emacs, it may often be useful to display
2114 this link in another window or frame. This variable can be used to
2115 set this up for the different types of links.
2116 For VM, use any of
2117 `vm-visit-folder'
2118 `vm-visit-folder-other-window'
2119 `vm-visit-folder-other-frame'
2120 For Gnus, use any of
2121 `gnus'
2122 `gnus-other-frame'
2123 `org-gnus-no-new-news'
2124 For FILE, use any of
2125 `find-file'
2126 `find-file-other-window'
2127 `find-file-other-frame'
2128 For Wanderlust use any of
2129 `wl'
2130 `wl-other-frame'
2131 For the calendar, use the variable `calendar-setup'.
2132 For BBDB, it is currently only possible to display the matches in
2133 another window."
2134 :group 'org-link-follow
2135 :type '(list
2136 (cons (const vm)
2137 (choice
2138 (const vm-visit-folder)
2139 (const vm-visit-folder-other-window)
2140 (const vm-visit-folder-other-frame)))
2141 (cons (const vm-imap)
2142 (choice
2143 (const vm-visit-imap-folder)
2144 (const vm-visit-imap-folder-other-window)
2145 (const vm-visit-imap-folder-other-frame)))
2146 (cons (const gnus)
2147 (choice
2148 (const gnus)
2149 (const gnus-other-frame)
2150 (const org-gnus-no-new-news)))
2151 (cons (const file)
2152 (choice
2153 (const find-file)
2154 (const find-file-other-window)
2155 (const find-file-other-frame)))
2156 (cons (const wl)
2157 (choice
2158 (const wl)
2159 (const wl-other-frame)))))
2161 (defcustom org-display-internal-link-with-indirect-buffer nil
2162 "Non-nil means use indirect buffer to display infile links.
2163 Activating internal links (from one location in a file to another location
2164 in the same file) normally just jumps to the location. When the link is
2165 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2166 is displayed in
2167 another window. When this option is set, the other window actually displays
2168 an indirect buffer clone of the current buffer, to avoid any visibility
2169 changes to the current buffer."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-open-non-existing-files nil
2174 "Non-nil means `org-open-file' will open non-existing files.
2175 When nil, an error will be generated.
2176 This variable applies only to external applications because they
2177 might choke on non-existing files. If the link is to a file that
2178 will be opened in Emacs, the variable is ignored."
2179 :group 'org-link-follow
2180 :type 'boolean)
2182 (defcustom org-open-directory-means-index-dot-org nil
2183 "Non-nil means a link to a directory really means to index.org.
2184 When nil, following a directory link will run dired or open a finder/explorer
2185 window on that directory."
2186 :group 'org-link-follow
2187 :type 'boolean)
2189 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2190 "Non-nil means ask for confirmation before executing shell links.
2191 Shell links can be dangerous: just think about a link
2193 [[shell:rm -rf ~/*][Google Search]]
2195 This link would show up in your Org document as \"Google Search\",
2196 but really it would remove your entire home directory.
2197 Therefore we advise against setting this variable to nil.
2198 Just change it to `y-or-n-p' if you want to confirm with a
2199 single keystroke rather than having to type \"yes\"."
2200 :group 'org-link-follow
2201 :type '(choice
2202 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2203 (const :tag "with y-or-n (faster)" y-or-n-p)
2204 (const :tag "no confirmation (dangerous)" nil)))
2205 (put 'org-confirm-shell-link-function
2206 'safe-local-variable
2207 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2209 (defcustom org-confirm-shell-link-not-regexp ""
2210 "A regexp to skip confirmation for shell links."
2211 :group 'org-link-follow
2212 :version "24.1"
2213 :type 'regexp)
2215 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2216 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2217 Elisp links can be dangerous: just think about a link
2219 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2221 This link would show up in your Org document as \"Google Search\",
2222 but really it would remove your entire home directory.
2223 Therefore we advise against setting this variable to nil.
2224 Just change it to `y-or-n-p' if you want to confirm with a
2225 single keystroke rather than having to type \"yes\"."
2226 :group 'org-link-follow
2227 :type '(choice
2228 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2229 (const :tag "with y-or-n (faster)" y-or-n-p)
2230 (const :tag "no confirmation (dangerous)" nil)))
2231 (put 'org-confirm-shell-link-function
2232 'safe-local-variable
2233 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2235 (defcustom org-confirm-elisp-link-not-regexp ""
2236 "A regexp to skip confirmation for Elisp links."
2237 :group 'org-link-follow
2238 :version "24.1"
2239 :type 'regexp)
2241 (defconst org-file-apps-defaults-gnu
2242 '((remote . emacs)
2243 (system . mailcap)
2244 (t . mailcap))
2245 "Default file applications on a UNIX or GNU/Linux system.
2246 See `org-file-apps'.")
2248 (defconst org-file-apps-defaults-macosx
2249 '((remote . emacs)
2250 (system . "open %s")
2251 ("ps.gz" . "gv %s")
2252 ("eps.gz" . "gv %s")
2253 ("dvi" . "xdvi %s")
2254 ("fig" . "xfig %s")
2255 (t . "open %s"))
2256 "Default file applications on a macOS system.
2257 The system \"open\" is known as a default, but we use X11 applications
2258 for some files for which the OS does not have a good default.
2259 See `org-file-apps'.")
2261 (defconst org-file-apps-defaults-windowsnt
2262 (list '(remote . emacs)
2263 (cons 'system (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file))))
2265 (cons t (lambda (file _path)
2266 (with-no-warnings (w32-shell-execute "open" file)))))
2267 "Default file applications on a Windows NT system.
2268 The system \"open\" is used for most files.
2269 See `org-file-apps'.")
2271 (defcustom org-file-apps
2272 '((auto-mode . emacs)
2273 ("\\.mm\\'" . default)
2274 ("\\.x?html?\\'" . default)
2275 ("\\.pdf\\'" . default))
2276 "External applications for opening `file:path' items in a document.
2277 \\<org-mode-map>\
2279 Org mode uses system defaults for different file types, but
2280 you can use this variable to set the application for a given file
2281 extension. The entries in this list are cons cells where the car identifies
2282 files and the cdr the corresponding command.
2284 Possible values for the file identifier are:
2286 \"string\" A string as a file identifier can be interpreted in different
2287 ways, depending on its contents:
2289 - Alphanumeric characters only:
2290 Match links with this file extension.
2291 Example: (\"pdf\" . \"evince %s\")
2292 to open PDFs with evince.
2294 - Regular expression: Match links where the
2295 filename matches the regexp. If you want to
2296 use groups here, use shy groups.
2298 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2299 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2300 to open *.html and *.xhtml with firefox.
2302 - Regular expression which contains (non-shy) groups:
2303 Match links where the whole link, including \"::\", and
2304 anything after that, matches the regexp.
2305 In a custom command string, %1, %2, etc. are replaced with
2306 the parts of the link that were matched by the groups.
2307 For backwards compatibility, if a command string is given
2308 that does not use any of the group matches, this case is
2309 handled identically to the second one (i.e. match against
2310 file name only).
2311 In a custom function, you can access the group matches with
2312 (match-string n link).
2314 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2315 \"evince -p %1 %s\")
2316 to open [[file:document.pdf::5]] with evince at page 5.
2318 `directory' Matches a directory
2319 `remote' Matches a remote file, accessible through tramp or efs.
2320 Remote files most likely should be visited through Emacs
2321 because external applications cannot handle such paths.
2322 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2323 so all files Emacs knows how to handle. Using this with
2324 command `emacs' will open most files in Emacs. Beware that this
2325 will also open html files inside Emacs, unless you add
2326 (\"html\" . default) to the list as well.
2327 `system' The system command to open files, like `open' on Windows
2328 and macOS, and mailcap under GNU/Linux. This is the command
2329 that will be selected if you call `org-open-at-point' with a
2330 double prefix argument (`\\[universal-argument] \
2331 \\[universal-argument] \\[org-open-at-point]').
2332 t Default for files not matched by any of the other options.
2334 Possible values for the command are:
2336 `emacs' The file will be visited by the current Emacs process.
2337 `default' Use the default application for this file type, which is the
2338 association for t in the list, most likely in the system-specific
2339 part. This can be used to overrule an unwanted setting in the
2340 system-specific variable.
2341 `system' Use the system command for opening files, like \"open\".
2342 This command is specified by the entry whose car is `system'.
2343 Most likely, the system-specific version of this variable
2344 does define this command, but you can overrule/replace it
2345 here.
2346 `mailcap' Use command specified in the mailcaps.
2347 string A command to be executed by a shell; %s will be replaced
2348 by the path to the file.
2349 function A Lisp function, which will be called with two arguments:
2350 the file path and the original link string, without the
2351 \"file:\" prefix.
2353 For more examples, see the system specific constants
2354 `org-file-apps-defaults-macosx'
2355 `org-file-apps-defaults-windowsnt'
2356 `org-file-apps-defaults-gnu'."
2357 :group 'org-link-follow
2358 :type '(repeat
2359 (cons (choice :value ""
2360 (string :tag "Extension")
2361 (const :tag "System command to open files" system)
2362 (const :tag "Default for unrecognized files" t)
2363 (const :tag "Remote file" remote)
2364 (const :tag "Links to a directory" directory)
2365 (const :tag "Any files that have Emacs modes"
2366 auto-mode))
2367 (choice :value ""
2368 (const :tag "Visit with Emacs" emacs)
2369 (const :tag "Use default" default)
2370 (const :tag "Use the system command" system)
2371 (string :tag "Command")
2372 (function :tag "Function")))))
2374 (defcustom org-doi-server-url "http://dx.doi.org/"
2375 "The URL of the DOI server."
2376 :type 'string
2377 :version "24.3"
2378 :group 'org-link-follow)
2380 (defgroup org-refile nil
2381 "Options concerning refiling entries in Org mode."
2382 :tag "Org Refile"
2383 :group 'org)
2385 (defcustom org-directory "~/org"
2386 "Directory with Org files.
2387 This is just a default location to look for Org files. There is no need
2388 at all to put your files into this directory. It is used in the
2389 following situations:
2391 1. When a capture template specifies a target file that is not an
2392 absolute path. The path will then be interpreted relative to
2393 `org-directory'
2394 2. When the value of variable `org-agenda-files' is a single file, any
2395 relative paths in this file will be taken as relative to
2396 `org-directory'."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'directory)
2401 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2402 "Default target for storing notes.
2403 Used as a fall back file for org-capture.el, for templates that
2404 do not specify a target file."
2405 :group 'org-refile
2406 :group 'org-capture
2407 :type 'file)
2409 (defcustom org-goto-interface 'outline
2410 "The default interface to be used for `org-goto'.
2411 Allowed values are:
2412 outline The interface shows an outline of the relevant file
2413 and the correct heading is found by moving through
2414 the outline or by searching with incremental search.
2415 outline-path-completion Headlines in the current buffer are offered via
2416 completion. This is the interface also used by
2417 the refile command."
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Outline" outline)
2421 (const :tag "Outline-path-completion" outline-path-completion)))
2423 (defcustom org-goto-max-level 5
2424 "Maximum target level when running `org-goto' with refile interface."
2425 :group 'org-refile
2426 :type 'integer)
2428 (defcustom org-reverse-note-order nil
2429 "Non-nil means store new notes at the beginning of a file or entry.
2430 When nil, new notes will be filed to the end of a file or entry.
2431 This can also be a list with cons cells of regular expressions that
2432 are matched against file names, and values."
2433 :group 'org-capture
2434 :group 'org-refile
2435 :type '(choice
2436 (const :tag "Reverse always" t)
2437 (const :tag "Reverse never" nil)
2438 (repeat :tag "By file name regexp"
2439 (cons regexp boolean))))
2441 (defcustom org-log-refile nil
2442 "Information to record when a task is refiled.
2444 Possible values are:
2446 nil Don't add anything
2447 time Add a time stamp to the task
2448 note Prompt for a note and add it with template `org-log-note-headings'
2450 This option can also be set with on a per-file-basis with
2452 #+STARTUP: nologrefile
2453 #+STARTUP: logrefile
2454 #+STARTUP: lognoterefile
2456 You can have local logging settings for a subtree by setting the LOGGING
2457 property to one or more of these keywords.
2459 When bulk-refiling from the agenda, the value `note' is forbidden and
2460 will temporarily be changed to `time'."
2461 :group 'org-refile
2462 :group 'org-progress
2463 :version "24.1"
2464 :type '(choice
2465 (const :tag "No logging" nil)
2466 (const :tag "Record timestamp" time)
2467 (const :tag "Record timestamp with note." note)))
2469 (defcustom org-refile-targets nil
2470 "Targets for refiling entries with `\\[org-refile]'.
2471 This is a list of cons cells. Each cell contains:
2472 - a specification of the files to be considered, either a list of files,
2473 or a symbol whose function or variable value will be used to retrieve
2474 a file name or a list of file names. If you use `org-agenda-files' for
2475 that, all agenda files will be scanned for targets. Nil means consider
2476 headings in the current buffer.
2477 - A specification of how to find candidate refile targets. This may be
2478 any of:
2479 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2480 This tag has to be present in all target headlines, inheritance will
2481 not be considered.
2482 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2483 todo keyword.
2484 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2485 headlines that are refiling targets.
2486 - a cons cell (:level . N). Any headline of level N is considered a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2489 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2490 Note that, when `org-odd-levels-only' is set, level corresponds to
2491 order in hierarchy, not to the number of stars.
2493 Each element of this list generates a set of possible targets.
2494 The union of these sets is presented (with completion) to
2495 the user by `org-refile'.
2497 You can set the variable `org-refile-target-verify-function' to a function
2498 to verify each headline found by the simple criteria above.
2500 When this variable is nil, all top-level headlines in the current buffer
2501 are used, equivalent to the value `((nil . (:level . 1))'."
2502 :group 'org-refile
2503 :type '(repeat
2504 (cons
2505 (choice :value org-agenda-files
2506 (const :tag "All agenda files" org-agenda-files)
2507 (const :tag "Current buffer" nil)
2508 (function) (variable) (file))
2509 (choice :tag "Identify target headline by"
2510 (cons :tag "Specific tag" (const :value :tag) (string))
2511 (cons :tag "TODO keyword" (const :value :todo) (string))
2512 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2513 (cons :tag "Level number" (const :value :level) (integer))
2514 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2516 (defcustom org-refile-target-verify-function nil
2517 "Function to verify if the headline at point should be a refile target.
2518 The function will be called without arguments, with point at the
2519 beginning of the headline. It should return t and leave point
2520 where it is if the headline is a valid target for refiling.
2522 If the target should not be selected, the function must return nil.
2523 In addition to this, it may move point to a place from where the search
2524 should be continued. For example, the function may decide that the entire
2525 subtree of the current entry should be excluded and move point to the end
2526 of the subtree."
2527 :group 'org-refile
2528 :type '(choice
2529 (const nil)
2530 (function)))
2532 (defcustom org-refile-use-cache nil
2533 "Non-nil means cache refile targets to speed up the process.
2534 \\<org-mode-map>\
2535 The cache for a particular file will be updated automatically when
2536 the buffer has been killed, or when any of the marker used for flagging
2537 refile targets no longer points at a live buffer.
2538 If you have added new entries to a buffer that might themselves be targets,
2539 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2540 if you find that easier, \
2541 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2542 \\[org-refile]'."
2543 :group 'org-refile
2544 :version "24.1"
2545 :type 'boolean)
2547 (defcustom org-refile-use-outline-path nil
2548 "Non-nil means provide refile targets as paths.
2549 So a level 3 headline will be available as level1/level2/level3.
2551 When the value is `file', also include the file name (without directory)
2552 into the path. In this case, you can also stop the completion after
2553 the file name, to get entries inserted as top level in the file.
2555 When `full-file-path', include the full file path."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Not" nil)
2559 (const :tag "Yes" t)
2560 (const :tag "Start with file name" file)
2561 (const :tag "Start with full file path" full-file-path)))
2563 (defcustom org-outline-path-complete-in-steps t
2564 "Non-nil means complete the outline path in hierarchical steps.
2565 When Org uses the refile interface to select an outline path (see
2566 `org-refile-use-outline-path'), the completion of the path can be
2567 done in a single go, or it can be done in steps down the headline
2568 hierarchy. Going in steps is probably the best if you do not use
2569 a special completion package like `ido' or `icicles'. However,
2570 when using these packages, going in one step can be very fast,
2571 while still showing the whole path to the entry."
2572 :group 'org-refile
2573 :type 'boolean)
2575 (defcustom org-refile-allow-creating-parent-nodes nil
2576 "Non-nil means allow the creation of new nodes as refile targets.
2577 New nodes are then created by adding \"/new node name\" to the completion
2578 of an existing node. When the value of this variable is `confirm',
2579 new node creation must be confirmed by the user (recommended).
2580 When nil, the completion must match an existing entry.
2582 Note that, if the new heading is not seen by the criteria
2583 listed in `org-refile-targets', multiple instances of the same
2584 heading would be created by trying again to file under the new
2585 heading."
2586 :group 'org-refile
2587 :type '(choice
2588 (const :tag "Never" nil)
2589 (const :tag "Always" t)
2590 (const :tag "Prompt for confirmation" confirm)))
2592 (defcustom org-refile-active-region-within-subtree nil
2593 "Non-nil means also refile active region within a subtree.
2595 By default `org-refile' doesn't allow refiling regions if they
2596 don't contain a set of subtrees, but it might be convenient to
2597 do so sometimes: in that case, the first line of the region is
2598 converted to a headline before refiling."
2599 :group 'org-refile
2600 :version "24.1"
2601 :type 'boolean)
2603 (defgroup org-todo nil
2604 "Options concerning TODO items in Org mode."
2605 :tag "Org TODO"
2606 :group 'org)
2608 (defgroup org-progress nil
2609 "Options concerning Progress logging in Org mode."
2610 :tag "Org Progress"
2611 :group 'org-time)
2613 (defvar org-todo-interpretation-widgets
2614 '((:tag "Sequence (cycling hits every state)" sequence)
2615 (:tag "Type (cycling directly to DONE)" type))
2616 "The available interpretation symbols for customizing `org-todo-keywords'.
2617 Interested libraries should add to this list.")
2619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2620 "List of TODO entry keyword sequences and their interpretation.
2621 \\<org-mode-map>This is a list of sequences.
2623 Each sequence starts with a symbol, either `sequence' or `type',
2624 indicating if the keywords should be interpreted as a sequence of
2625 action steps, or as different types of TODO items. The first
2626 keywords are states requiring action - these states will select a headline
2627 for inclusion into the global TODO list Org produces. If one of the
2628 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2629 signify that no further action is necessary. If \"|\" is not found,
2630 the last keyword is treated as the only DONE state of the sequence.
2632 The command `\\[org-todo]' cycles an entry through these states, and one
2633 additional state where no keyword is present. For details about this
2634 cycling, see the manual.
2636 TODO keywords and interpretation can also be set on a per-file basis with
2637 the special #+SEQ_TODO and #+TYP_TODO lines.
2639 Each keyword can optionally specify a character for fast state selection
2640 \(in combination with the variable `org-use-fast-todo-selection')
2641 and specifiers for state change logging, using the same syntax that
2642 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2643 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2644 indicates to record a time stamp each time this state is selected.
2646 Each keyword may also specify if a timestamp or a note should be
2647 recorded when entering or leaving the state, by adding additional
2648 characters in the parenthesis after the keyword. This looks like this:
2649 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2650 record only the time of the state change. With X and Y being either
2651 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2652 Y when leaving the state if and only if the *target* state does not
2653 define X. You may omit any of the fast-selection key or X or /Y,
2654 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2656 For backward compatibility, this variable may also be just a list
2657 of keywords. In this case the interpretation (sequence or type) will be
2658 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice
2662 (repeat :tag "Old syntax, just keywords"
2663 (string :tag "Keyword"))
2664 (repeat :tag "New syntax"
2665 (cons
2666 (choice
2667 :tag "Interpretation"
2668 ;;Quick and dirty way to see
2669 ;;`org-todo-interpretations'. This takes the
2670 ;;place of item arguments
2671 :convert-widget
2672 (lambda (widget)
2673 (widget-put widget
2674 :args (mapcar
2675 (lambda (x)
2676 (widget-convert
2677 (cons 'const x)))
2678 org-todo-interpretation-widgets))
2679 widget))
2680 (repeat
2681 (string :tag "Keyword"))))))
2683 (defvar-local org-todo-keywords-1 nil
2684 "All TODO and DONE keywords active in a buffer.")
2685 (defvar org-todo-keywords-for-agenda nil)
2686 (defvar org-done-keywords-for-agenda nil)
2687 (defvar org-todo-keyword-alist-for-agenda nil)
2688 (defvar org-tag-alist-for-agenda nil
2689 "Alist of all tags from all agenda files.")
2690 (defvar org-tag-groups-alist-for-agenda nil
2691 "Alist of all groups tags from all current agenda files.")
2692 (defvar-local org-tag-groups-alist nil)
2693 (defvar org-agenda-contributing-files nil)
2694 (defvar-local org-current-tag-alist nil
2695 "Alist of all tag groups in current buffer.
2696 This variable takes into consideration `org-tag-alist',
2697 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2698 (defvar-local org-not-done-keywords nil)
2699 (defvar-local org-done-keywords nil)
2700 (defvar-local org-todo-heads nil)
2701 (defvar-local org-todo-sets nil)
2702 (defvar-local org-todo-log-states nil)
2703 (defvar-local org-todo-kwd-alist nil)
2704 (defvar-local org-todo-key-alist nil)
2705 (defvar-local org-todo-key-trigger nil)
2707 (defcustom org-todo-interpretation 'sequence
2708 "Controls how TODO keywords are interpreted.
2709 This variable is in principle obsolete and is only used for
2710 backward compatibility, if the interpretation of todo keywords is
2711 not given already in `org-todo-keywords'. See that variable for
2712 more information."
2713 :group 'org-todo
2714 :group 'org-keywords
2715 :type '(choice (const sequence)
2716 (const type)))
2718 (defcustom org-use-fast-todo-selection t
2719 "\\<org-mode-map>\
2720 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2721 This variable describes if and under what circumstances the cycling
2722 mechanism for TODO keywords will be replaced by a single-key, direct
2723 selection scheme.
2725 When nil, fast selection is never used.
2727 When the symbol `prefix', it will be used when `org-todo' is called
2728 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2729 in an Org buffer, and
2730 `\\[universal-argument] t' in an agenda buffer.
2732 When t, fast selection is used by default. In this case, the prefix
2733 argument forces cycling instead.
2735 In all cases, the special interface is only used if access keys have
2736 actually been assigned by the user, i.e. if keywords in the configuration
2737 are followed by a letter in parenthesis, like TODO(t)."
2738 :group 'org-todo
2739 :type '(choice
2740 (const :tag "Never" nil)
2741 (const :tag "By default" t)
2742 (const :tag "Only with C-u C-c C-t" prefix)))
2744 (defcustom org-provide-todo-statistics t
2745 "Non-nil means update todo statistics after insert and toggle.
2746 ALL-HEADLINES means update todo statistics by including headlines
2747 with no TODO keyword as well, counting them as not done.
2748 A list of TODO keywords means the same, but skip keywords that are
2749 not in this list.
2750 When set to a list of two lists, the first list contains keywords
2751 to consider as TODO keywords, the second list contains keywords
2752 to consider as DONE keywords.
2754 When this is set, todo statistics is updated in the parent of the
2755 current entry each time a todo state is changed."
2756 :group 'org-todo
2757 :type '(choice
2758 (const :tag "Yes, only for TODO entries" t)
2759 (const :tag "Yes, including all entries" all-headlines)
2760 (repeat :tag "Yes, for TODOs in this list"
2761 (string :tag "TODO keyword"))
2762 (list :tag "Yes, for TODOs and DONEs in these lists"
2763 (repeat (string :tag "TODO keyword"))
2764 (repeat (string :tag "DONE keyword")))
2765 (other :tag "No TODO statistics" nil)))
2767 (defcustom org-hierarchical-todo-statistics t
2768 "Non-nil means TODO statistics covers just direct children.
2769 When nil, all entries in the subtree are considered.
2770 This has only an effect if `org-provide-todo-statistics' is set.
2771 To set this to nil for only a single subtree, use a COOKIE_DATA
2772 property and include the word \"recursive\" into the value."
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-after-todo-state-change-hook nil
2777 "Hook which is run after the state of a TODO item was changed.
2778 The new state (a string with a TODO keyword, or nil) is available in the
2779 Lisp variable `org-state'."
2780 :group 'org-todo
2781 :type 'hook)
2783 (defvar org-blocker-hook nil
2784 "Hook for functions that are allowed to block a state change.
2786 Functions in this hook should not modify the buffer.
2787 Each function gets as its single argument a property list,
2788 see `org-trigger-hook' for more information about this list.
2790 If any of the functions in this hook returns nil, the state change
2791 is blocked.")
2793 (defvar org-trigger-hook nil
2794 "Hook for functions that are triggered by a state change.
2796 Each function gets as its single argument a property list with at
2797 least the following elements:
2799 (:type type-of-change :position pos-at-entry-start
2800 :from old-state :to new-state)
2802 Depending on the type, more properties may be present.
2804 This mechanism is currently implemented for:
2806 TODO state changes
2807 ------------------
2808 :type todo-state-change
2809 :from previous state (keyword as a string), or nil, or a symbol
2810 `todo' or `done', to indicate the general type of state.
2811 :to new state, like in :from")
2813 (defcustom org-enforce-todo-dependencies nil
2814 "Non-nil means undone TODO entries will block switching the parent to DONE.
2815 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2816 be blocked if any prior sibling is not yet done.
2817 Finally, if the parent is blocked because of ordered siblings of its own,
2818 the child will also be blocked."
2819 :set (lambda (var val)
2820 (set var val)
2821 (if val
2822 (add-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)
2824 (remove-hook 'org-blocker-hook
2825 'org-block-todo-from-children-or-siblings-or-parent)))
2826 :group 'org-todo
2827 :type 'boolean)
2829 (defcustom org-enforce-todo-checkbox-dependencies nil
2830 "Non-nil means unchecked boxes will block switching the parent to DONE.
2831 When this is nil, checkboxes have no influence on switching TODO states.
2832 When non-nil, you first need to check off all check boxes before the TODO
2833 entry can be switched to DONE.
2834 This variable needs to be set before org.el is loaded, and you need to
2835 restart Emacs after a change to make the change effective. The only way
2836 to change is while Emacs is running is through the customize interface."
2837 :set (lambda (var val)
2838 (set var val)
2839 (if val
2840 (add-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)
2842 (remove-hook 'org-blocker-hook
2843 'org-block-todo-from-checkboxes)))
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-treat-insert-todo-heading-as-state-change nil
2848 "Non-nil means inserting a TODO heading is treated as state change.
2849 So when the command `\\[org-insert-todo-heading]' is used, state change
2850 logging will apply if appropriate. When nil, the new TODO item will
2851 be inserted directly, and no logging will take place."
2852 :group 'org-todo
2853 :type 'boolean)
2855 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2856 "Non-nil means switching TODO states with S-cursor counts as state change.
2857 This is the default behavior. However, setting this to nil allows a
2858 convenient way to select a TODO state and bypass any logging associated
2859 with that."
2860 :group 'org-todo
2861 :type 'boolean)
2863 (defcustom org-todo-state-tags-triggers nil
2864 "Tag changes that should be triggered by TODO state changes.
2865 This is a list. Each entry is
2867 (state-change (tag . flag) .......)
2869 State-change can be a string with a state, and empty string to indicate the
2870 state that has no TODO keyword, or it can be one of the symbols `todo'
2871 or `done', meaning any not-done or done state, respectively."
2872 :group 'org-todo
2873 :group 'org-tags
2874 :type '(repeat
2875 (cons (choice :tag "When changing to"
2876 (const :tag "Not-done state" todo)
2877 (const :tag "Done state" done)
2878 (string :tag "State"))
2879 (repeat
2880 (cons :tag "Tag action"
2881 (string :tag "Tag")
2882 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2884 (defcustom org-log-done nil
2885 "Information to record when a task moves to the DONE state.
2887 Possible values are:
2889 nil Don't add anything, just change the keyword
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologdone
2896 #+STARTUP: logdone
2897 #+STARTUP: lognotedone
2899 You can have local logging settings for a subtree by setting the LOGGING
2900 property to one or more of these keywords."
2901 :group 'org-todo
2902 :group 'org-progress
2903 :type '(choice
2904 (const :tag "No logging" nil)
2905 (const :tag "Record CLOSED timestamp" time)
2906 (const :tag "Record CLOSED timestamp with note." note)))
2908 ;; Normalize old uses of org-log-done.
2909 (cond
2910 ((eq org-log-done t) (setq org-log-done 'time))
2911 ((and (listp org-log-done) (memq 'done org-log-done))
2912 (setq org-log-done 'note)))
2914 (defcustom org-log-reschedule nil
2915 "Information to record when the scheduling 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: nologreschedule
2926 #+STARTUP: logreschedule
2927 #+STARTUP: lognotereschedule"
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "No logging" nil)
2932 (const :tag "Record timestamp" time)
2933 (const :tag "Record timestamp with note." note)))
2935 (defcustom org-log-redeadline nil
2936 "Information to record when the deadline date of a tasks is modified.
2938 Possible values are:
2940 nil Don't add anything, just change the date
2941 time Add a time stamp to the task
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologredeadline
2947 #+STARTUP: logredeadline
2948 #+STARTUP: lognoteredeadline
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "No logging" nil)
2956 (const :tag "Record timestamp" time)
2957 (const :tag "Record timestamp with note." note)))
2959 (defcustom org-log-note-clock-out nil
2960 "Non-nil means record a note when clocking out of an item.
2961 This can also be configured on a per-file basis by adding one of
2962 the following lines anywhere in the buffer:
2964 #+STARTUP: lognoteclock-out
2965 #+STARTUP: nolognoteclock-out"
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-done-with-time t
2971 "Non-nil means the CLOSED time stamp will contain date and time.
2972 When nil, only the date will be recorded."
2973 :group 'org-progress
2974 :type 'boolean)
2976 (defcustom org-log-note-headings
2977 '((done . "CLOSING NOTE %t")
2978 (state . "State %-12s from %-12S %t")
2979 (note . "Note taken on %t")
2980 (reschedule . "Rescheduled from %S on %t")
2981 (delschedule . "Not scheduled, was %S on %t")
2982 (redeadline . "New deadline from %S on %t")
2983 (deldeadline . "Removed deadline, was %S on %t")
2984 (refile . "Refiled on %t")
2985 (clock-out . ""))
2986 "Headings for notes added to entries.
2988 The value is an alist, with the car being a symbol indicating the
2989 note context, and the cdr is the heading to be used. The heading
2990 may also be the empty string. The following placeholders can be
2991 used:
2993 %t a time stamp.
2994 %T an active time stamp instead the default inactive one
2995 %d a short-format time stamp.
2996 %D an active short-format time stamp.
2997 %s the new TODO state or time stamp (inactive), in double quotes.
2998 %S the old TODO state or time stamp (inactive), in double quotes.
2999 %u the user name.
3000 %U full user name.
3002 In fact, it is not a good idea to change the `state' entry,
3003 because Agenda Log mode depends on the format of these entries."
3004 :group 'org-todo
3005 :group 'org-progress
3006 :type '(list :greedy t
3007 (cons (const :tag "Heading when closing an item" done) string)
3008 (cons (const :tag
3009 "Heading when changing todo state (todo sequence only)"
3010 state) string)
3011 (cons (const :tag "Heading when just taking a note" note) string)
3012 (cons (const :tag "Heading when rescheduling" reschedule) string)
3013 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3014 (cons (const :tag "Heading when changing deadline" redeadline) string)
3015 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3016 (cons (const :tag "Heading when refiling" refile) string)
3017 (cons (const :tag "Heading when clocking out" clock-out) string)))
3019 (unless (assq 'note org-log-note-headings)
3020 (push '(note . "%t") org-log-note-headings))
3022 (defcustom org-log-into-drawer nil
3023 "Non-nil means insert state change notes and time stamps into a drawer.
3024 When nil, state changes notes will be inserted after the headline and
3025 any scheduling and clock lines, but not inside a drawer.
3027 The value of this variable should be the name of the drawer to use.
3028 LOGBOOK is proposed as the default drawer for this purpose, you can
3029 also set this to a string to define the drawer of your choice.
3031 A value of t is also allowed, representing \"LOGBOOK\".
3033 A value of t or nil can also be set with on a per-file-basis with
3035 #+STARTUP: logdrawer
3036 #+STARTUP: nologdrawer
3038 If this variable is set, `org-log-state-notes-insert-after-drawers'
3039 will be ignored.
3041 You can set the property LOG_INTO_DRAWER to overrule this setting for
3042 a subtree.
3044 Do not check directly this variable in a Lisp program. Call
3045 function `org-log-into-drawer' instead."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type '(choice
3049 (const :tag "Not into a drawer" nil)
3050 (const :tag "LOGBOOK" t)
3051 (string :tag "Other")))
3053 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3055 (defun org-log-into-drawer ()
3056 "Name of the log drawer, as a string, or nil.
3057 This is the value of `org-log-into-drawer'. However, if the
3058 current entry has or inherits a LOG_INTO_DRAWER property, it will
3059 be used instead of the default value."
3060 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3061 (cond ((equal p "nil") nil)
3062 ((equal p "t") "LOGBOOK")
3063 ((stringp p) p)
3064 (p "LOGBOOK")
3065 ((stringp org-log-into-drawer) org-log-into-drawer)
3066 (org-log-into-drawer "LOGBOOK"))))
3068 (defcustom org-log-state-notes-insert-after-drawers nil
3069 "Non-nil means insert state change notes after any drawers in entry.
3070 Only the drawers that *immediately* follow the headline and the
3071 deadline/scheduled line are skipped.
3072 When nil, insert notes right after the heading and perhaps the line
3073 with deadline/scheduling if present.
3075 This variable will have no effect if `org-log-into-drawer' is
3076 set."
3077 :group 'org-todo
3078 :group 'org-progress
3079 :type 'boolean)
3081 (defcustom org-log-states-order-reversed t
3082 "Non-nil means the latest state note will be directly after heading.
3083 When nil, the state change notes will be ordered according to time.
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: logstatesreversed
3088 #+STARTUP: nologstatesreversed"
3089 :group 'org-todo
3090 :group 'org-progress
3091 :type 'boolean)
3093 (defcustom org-todo-repeat-to-state nil
3094 "The TODO state to which a repeater should return the repeating task.
3095 By default this is the first task in a TODO sequence, or the previous state
3096 in a TODO_TYP set. But you can specify another task here.
3097 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3098 :group 'org-todo
3099 :version "24.1"
3100 :type '(choice (const :tag "Head of sequence" nil)
3101 (string :tag "Specific state")))
3103 (defcustom org-log-repeat 'time
3104 "Non-nil means record moving through the DONE state when triggering repeat.
3105 An auto-repeating task is immediately switched back to TODO when
3106 marked DONE. If you are not logging state changes (by adding \"@\"
3107 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3108 record a closing note, there will be no record of the task moving
3109 through DONE. This variable forces taking a note anyway.
3111 nil Don't force a record
3112 time Record a time stamp
3113 note Prompt for a note and add it with template `org-log-note-headings'
3115 This option can also be set with on a per-file-basis with
3117 #+STARTUP: nologrepeat
3118 #+STARTUP: logrepeat
3119 #+STARTUP: lognoterepeat
3121 You can have local logging settings for a subtree by setting the LOGGING
3122 property to one or more of these keywords."
3123 :group 'org-todo
3124 :group 'org-progress
3125 :type '(choice
3126 (const :tag "Don't force a record" nil)
3127 (const :tag "Force recording the DONE state" time)
3128 (const :tag "Force recording a note with the DONE state" note)))
3131 (defgroup org-priorities nil
3132 "Priorities in Org mode."
3133 :tag "Org Priorities"
3134 :group 'org-todo)
3136 (defcustom org-enable-priority-commands t
3137 "Non-nil means priority commands are active.
3138 When nil, these commands will be disabled, so that you never accidentally
3139 set a priority."
3140 :group 'org-priorities
3141 :type 'boolean)
3143 (defcustom org-highest-priority ?A
3144 "The highest priority of TODO items. A character like ?A, ?B etc.
3145 Must have a smaller ASCII number than `org-lowest-priority'."
3146 :group 'org-priorities
3147 :type 'character)
3149 (defcustom org-lowest-priority ?C
3150 "The lowest priority of TODO items. A character like ?A, ?B etc.
3151 Must have a larger ASCII number than `org-highest-priority'."
3152 :group 'org-priorities
3153 :type 'character)
3155 (defcustom org-default-priority ?B
3156 "The default priority of TODO items.
3157 This is the priority an item gets if no explicit priority is given.
3158 When starting to cycle on an empty priority the first step in the cycle
3159 depends on `org-priority-start-cycle-with-default'. The resulting first
3160 step priority must not exceed the range from `org-highest-priority' to
3161 `org-lowest-priority' which means that `org-default-priority' has to be
3162 in this range exclusive or inclusive the range boundaries. Else the
3163 first step refuses to set the default and the second will fall back
3164 to (depending on the command used) the highest or lowest priority."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-priority-start-cycle-with-default t
3169 "Non-nil means start with default priority when starting to cycle.
3170 When this is nil, the first step in the cycle will be (depending on the
3171 command used) one higher or lower than the default priority.
3172 See also `org-default-priority'."
3173 :group 'org-priorities
3174 :type 'boolean)
3176 (defcustom org-get-priority-function nil
3177 "Function to extract the priority from a string.
3178 The string is normally the headline. If this is nil Org computes the
3179 priority from the priority cookie like [#A] in the headline. It returns
3180 an integer, increasing by 1000 for each priority level.
3181 The user can set a different function here, which should take a string
3182 as an argument and return the numeric priority."
3183 :group 'org-priorities
3184 :version "24.1"
3185 :type '(choice
3186 (const nil)
3187 (function)))
3189 (defgroup org-time nil
3190 "Options concerning time stamps and deadlines in Org mode."
3191 :tag "Org Time"
3192 :group 'org)
3194 (defcustom org-time-stamp-rounding-minutes '(0 5)
3195 "Number of minutes to round time stamps to.
3196 \\<org-mode-map>\
3197 These are two values, the first applies when first creating a time stamp.
3198 The second applies when changing it with the commands `S-up' and `S-down'.
3199 When changing the time stamp, this means that it will change in steps
3200 of N minutes, as given by the second value.
3202 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3203 numbers should be factors of 60, so for example 5, 10, 15.
3205 When this is larger than 1, you can still force an exact time stamp by using
3206 a double prefix argument to a time stamp command like \
3207 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3208 and by using a prefix arg to `S-up/down' to specify the exact number
3209 of minutes to shift."
3210 :group 'org-time
3211 :get (lambda (var) ; Make sure both elements are there
3212 (if (integerp (default-value var))
3213 (list (default-value var) 5)
3214 (default-value var)))
3215 :type '(list
3216 (integer :tag "when inserting times")
3217 (integer :tag "when modifying times")))
3219 ;; Normalize old customizations of this variable.
3220 (when (integerp org-time-stamp-rounding-minutes)
3221 (setq org-time-stamp-rounding-minutes
3222 (list org-time-stamp-rounding-minutes
3223 org-time-stamp-rounding-minutes)))
3225 (defcustom org-display-custom-times nil
3226 "Non-nil means overlay custom formats over all time stamps.
3227 The formats are defined through the variable `org-time-stamp-custom-formats'.
3228 To turn this on on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: customtime"
3230 :group 'org-time
3231 :set 'set-default
3232 :type 'sexp)
3233 (make-variable-buffer-local 'org-display-custom-times)
3235 (defcustom org-time-stamp-custom-formats
3236 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3237 "Custom formats for time stamps. See `format-time-string' for the syntax.
3238 These are overlaid over the default ISO format if the variable
3239 `org-display-custom-times' is set. Time like %H:%M should be at the
3240 end of the second format. The custom formats are also honored by export
3241 commands, if custom time display is turned on at the time of export."
3242 :group 'org-time
3243 :type 'sexp)
3245 (defun org-time-stamp-format (&optional long inactive)
3246 "Get the right format for a time string."
3247 (let ((f (if long (cdr org-time-stamp-formats)
3248 (car org-time-stamp-formats))))
3249 (if inactive
3250 (concat "[" (substring f 1 -1) "]")
3251 f)))
3253 (defcustom org-deadline-warning-days 14
3254 "Number of days before expiration during which a deadline becomes active.
3255 This variable governs the display in sparse trees and in the agenda.
3256 When 0 or negative, it means use this number (the absolute value of it)
3257 even if a deadline has a different individual lead time specified.
3259 Custom commands can set this variable in the options section."
3260 :group 'org-time
3261 :group 'org-agenda-daily/weekly
3262 :type 'integer)
3264 (defcustom org-scheduled-delay-days 0
3265 "Number of days before a scheduled item becomes active.
3266 This variable governs the display in sparse trees and in the agenda.
3267 The default value (i.e. 0) means: don't delay scheduled item.
3268 When negative, it means use this number (the absolute value of it)
3269 even if a scheduled item has a different individual delay time
3270 specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :version "24.4"
3276 :package-version '(Org . "8.0")
3277 :type 'integer)
3279 (defcustom org-read-date-prefer-future t
3280 "Non-nil means assume future for incomplete date input from user.
3281 This affects the following situations:
3282 1. The user gives a month but not a year.
3283 For example, if it is April and you enter \"feb 2\", this will be read
3284 as Feb 2, *next* year. \"May 5\", however, will be this year.
3285 2. The user gives a day, but no month.
3286 For example, if today is the 15th, and you enter \"3\", Org will read
3287 this as the third of *next* month. However, if you enter \"17\",
3288 it will be considered as *this* month.
3290 If you set this variable to the symbol `time', then also the following
3291 will work:
3293 3. If the user gives a time.
3294 If the time is before now, it will be interpreted as tomorrow.
3296 Currently none of this works for ISO week specifications.
3298 When this option is nil, the current day, month and year will always be
3299 used as defaults.
3301 See also `org-agenda-jump-prefer-future'."
3302 :group 'org-time
3303 :type '(choice
3304 (const :tag "Never" nil)
3305 (const :tag "Check month and day" t)
3306 (const :tag "Check month, day, and time" time)))
3308 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3309 "Should the agenda jump command prefer the future for incomplete dates?
3310 The default is to do the same as configured in `org-read-date-prefer-future'.
3311 But you can also set a deviating value here.
3312 This may t or nil, or the symbol `org-read-date-prefer-future'."
3313 :group 'org-agenda
3314 :group 'org-time
3315 :version "24.1"
3316 :type '(choice
3317 (const :tag "Use org-read-date-prefer-future"
3318 org-read-date-prefer-future)
3319 (const :tag "Never" nil)
3320 (const :tag "Always" t)))
3322 (defcustom org-read-date-force-compatible-dates t
3323 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3325 Depending on the system Emacs is running on, certain dates cannot
3326 be represented with the type used internally to represent time.
3327 Dates between 1970-1-1 and 2038-1-1 can always be represented
3328 correctly. Some systems allow for earlier dates, some for later,
3329 some for both. One way to find out it to insert any date into an
3330 Org buffer, putting the cursor on the year and hitting S-up and
3331 S-down to test the range.
3333 When this variable is set to t, the date/time prompt will not let
3334 you specify dates outside the 1970-2037 range, so it is certain that
3335 these dates will work in whatever version of Emacs you are
3336 running, and also that you can move a file from one Emacs implementation
3337 to another. WHenever Org is forcing the year for you, it will display
3338 a message and beep.
3340 When this variable is nil, Org will check if the date is
3341 representable in the specific Emacs implementation you are using.
3342 If not, it will force a year, usually the current year, and beep
3343 to remind you. Currently this setting is not recommended because
3344 the likelihood that you will open your Org files in an Emacs that
3345 has limited date range is not negligible.
3347 A workaround for this problem is to use diary sexp dates for time
3348 stamps outside of this range."
3349 :group 'org-time
3350 :version "24.1"
3351 :type 'boolean)
3353 (defcustom org-read-date-display-live t
3354 "Non-nil means display current interpretation of date prompt live.
3355 This display will be in an overlay, in the minibuffer."
3356 :group 'org-time
3357 :type 'boolean)
3359 (defcustom org-read-date-popup-calendar t
3360 "Non-nil means pop up a calendar when prompting for a date.
3361 In the calendar, the date can be selected with mouse-1. However, the
3362 minibuffer will also be active, and you can simply enter the date as well.
3363 When nil, only the minibuffer will be available."
3364 :group 'org-time
3365 :type 'boolean)
3366 (defvaralias 'org-popup-calendar-for-date-prompt
3367 'org-read-date-popup-calendar)
3369 (defcustom org-extend-today-until 0
3370 "The hour when your day really ends. Must be an integer.
3371 This has influence for the following applications:
3372 - When switching the agenda to \"today\". It it is still earlier than
3373 the time given here, the day recognized as TODAY is actually yesterday.
3374 - When a date is read from the user and it is still before the time given
3375 here, the current date and time will be assumed to be yesterday, 23:59.
3376 Also, timestamps inserted in capture templates follow this rule.
3378 IMPORTANT: This is a feature whose implementation is and likely will
3379 remain incomplete. Really, it is only here because past midnight seems to
3380 be the favorite working time of John Wiegley :-)"
3381 :group 'org-time
3382 :type 'integer)
3384 (defcustom org-use-effective-time nil
3385 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3386 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3387 \"effective time\" of any timestamps between midnight and 8am will be
3388 23:59 of the previous day."
3389 :group 'org-time
3390 :version "24.1"
3391 :type 'boolean)
3393 (defcustom org-use-last-clock-out-time-as-effective-time nil
3394 "When non-nil, use the last clock out time for `org-todo'.
3395 Note that this option has precedence over the combined use of
3396 `org-use-effective-time' and `org-extend-today-until'."
3397 :group 'org-time
3398 :version "24.4"
3399 :package-version '(Org . "8.0")
3400 :type 'boolean)
3402 (defcustom org-edit-timestamp-down-means-later nil
3403 "Non-nil means S-down will increase the time in a time stamp.
3404 When nil, S-up will increase."
3405 :group 'org-time
3406 :type 'boolean)
3408 (defcustom org-calendar-follow-timestamp-change t
3409 "Non-nil means make the calendar window follow timestamp changes.
3410 When a timestamp is modified and the calendar window is visible, it will be
3411 moved to the new date."
3412 :group 'org-time
3413 :type 'boolean)
3415 (defgroup org-tags nil
3416 "Options concerning tags in Org mode."
3417 :tag "Org Tags"
3418 :group 'org)
3420 (defcustom org-tag-alist nil
3421 "Default tags available in Org files.
3423 The value of this variable is an alist. Associations either:
3425 (TAG)
3426 (TAG . SELECT)
3427 (SPECIAL)
3429 where TAG is a tag as a string, SELECT is character, used to
3430 select that tag through the fast tag selection interface, and
3431 SPECIAL is one of the following keywords: `:startgroup',
3432 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3433 `:newline'. These keywords are used to define a hierarchy of
3434 tags. See manual for details.
3436 When this variable is nil, Org mode bases tag input on what is
3437 already in the buffer. The value can be overridden locally by
3438 using a TAGS keyword, e.g.,
3440 #+TAGS: tag1 tag2
3442 See also `org-tag-persistent-alist' to sidestep this behavior."
3443 :group 'org-tags
3444 :type '(repeat
3445 (choice
3446 (cons (string :tag "Tag name")
3447 (character :tag "Access char"))
3448 (const :tag "Start radio group" (:startgroup))
3449 (const :tag "Start tag group, non distinct" (:startgrouptag))
3450 (const :tag "Group tags delimiter" (:grouptags))
3451 (const :tag "End radio group" (:endgroup))
3452 (const :tag "End tag group, non distinct" (:endgrouptag))
3453 (const :tag "New line" (:newline)))))
3455 (defcustom org-tag-persistent-alist nil
3456 "Tags always available in Org files.
3458 The value of this variable is an alist. Associations either:
3460 (TAG)
3461 (TAG . SELECT)
3462 (SPECIAL)
3464 where TAG is a tag as a string, SELECT is a character, used to
3465 select that tag through the fast tag selection interface, and
3466 SPECIAL is one of the following keywords: `:startgroup',
3467 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3468 `:newline'. These keywords are used to define a hierarchy of
3469 tags. See manual for details.
3471 Unlike to `org-tag-alist', tags defined in this variable do not
3472 depend on a local TAGS keyword. Instead, to disable these tags
3473 on a per-file basis, insert anywhere in the file:
3475 #+STARTUP: noptag"
3476 :group 'org-tags
3477 :type '(repeat
3478 (choice
3479 (cons (string :tag "Tag name")
3480 (character :tag "Access char"))
3481 (const :tag "Start radio group" (:startgroup))
3482 (const :tag "Start tag group, non distinct" (:startgrouptag))
3483 (const :tag "Group tags delimiter" (:grouptags))
3484 (const :tag "End radio group" (:endgroup))
3485 (const :tag "End tag group, non distinct" (:endgrouptag))
3486 (const :tag "New line" (:newline)))))
3488 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3489 "If non-nil, always offer completion for all tags of all agenda files.
3490 Instead of customizing this variable directly, you might want to
3491 set it locally for capture buffers, because there no list of
3492 tags in that file can be created dynamically (there are none).
3494 (add-hook \\='org-capture-mode-hook
3495 (lambda ()
3496 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3497 :group 'org-tags
3498 :version "24.1"
3499 :type 'boolean)
3501 (defvar org-file-tags nil
3502 "List of tags that can be inherited by all entries in the file.
3503 The tags will be inherited if the variable `org-use-tag-inheritance'
3504 says they should be.
3505 This variable is populated from #+FILETAGS lines.")
3507 (defcustom org-use-fast-tag-selection 'auto
3508 "Non-nil means use fast tag selection scheme.
3509 This is a special interface to select and deselect tags with single keys.
3510 When nil, fast selection is never used.
3511 When the symbol `auto', fast selection is used if and only if selection
3512 characters for tags have been configured, either through the variable
3513 `org-tag-alist' or through a #+TAGS line in the buffer.
3514 When t, fast selection is always used and selection keys are assigned
3515 automatically if necessary."
3516 :group 'org-tags
3517 :type '(choice
3518 (const :tag "Always" t)
3519 (const :tag "Never" nil)
3520 (const :tag "When selection characters are configured" auto)))
3522 (defcustom org-fast-tag-selection-single-key nil
3523 "Non-nil means fast tag selection exits after first change.
3524 When nil, you have to press RET to exit it.
3525 During fast tag selection, you can toggle this flag with `C-c'.
3526 This variable can also have the value `expert'. In this case, the window
3527 displaying the tags menu is not even shown, until you press C-c again."
3528 :group 'org-tags
3529 :type '(choice
3530 (const :tag "No" nil)
3531 (const :tag "Yes" t)
3532 (const :tag "Expert" expert)))
3534 (defvar org-fast-tag-selection-include-todo nil
3535 "Non-nil means fast tags selection interface will also offer TODO states.
3536 This is an undocumented feature, you should not rely on it.")
3538 (defcustom org-tags-column -77
3539 "The column to which tags should be indented in a headline.
3540 If this number is positive, it specifies the column. If it is negative,
3541 it means that the tags should be flushright to that column. For example,
3542 -80 works well for a normal 80 character screen.
3543 When 0, place tags directly after headline text, with only one space in
3544 between."
3545 :group 'org-tags
3546 :type 'integer)
3548 (defcustom org-auto-align-tags t
3549 "Non-nil keeps tags aligned when modifying headlines.
3550 Some operations (i.e. demoting) change the length of a headline and
3551 therefore shift the tags around. With this option turned on, after
3552 each such operation the tags are again aligned to `org-tags-column'."
3553 :group 'org-tags
3554 :type 'boolean)
3556 (defcustom org-use-tag-inheritance t
3557 "Non-nil means tags in levels apply also for sublevels.
3558 When nil, only the tags directly given in a specific line apply there.
3559 This may also be a list of tags that should be inherited, or a regexp that
3560 matches tags that should be inherited. Additional control is possible
3561 with the variable `org-tags-exclude-from-inheritance' which gives an
3562 explicit list of tags to be excluded from inheritance, even if the value of
3563 `org-use-tag-inheritance' would select it for inheritance.
3565 If this option is t, a match early-on in a tree can lead to a large
3566 number of matches in the subtree when constructing the agenda or creating
3567 a sparse tree. If you only want to see the first match in a tree during
3568 a search, check out the variable `org-tags-match-list-sublevels'."
3569 :group 'org-tags
3570 :type '(choice
3571 (const :tag "Not" nil)
3572 (const :tag "Always" t)
3573 (repeat :tag "Specific tags" (string :tag "Tag"))
3574 (regexp :tag "Tags matched by regexp")))
3576 (defcustom org-tags-exclude-from-inheritance nil
3577 "List of tags that should never be inherited.
3578 This is a way to exclude a few tags from inheritance. For way to do
3579 the opposite, to actively allow inheritance for selected tags,
3580 see the variable `org-use-tag-inheritance'."
3581 :group 'org-tags
3582 :type '(repeat (string :tag "Tag")))
3584 (defun org-tag-inherit-p (tag)
3585 "Check if TAG is one that should be inherited."
3586 (cond
3587 ((member tag org-tags-exclude-from-inheritance) nil)
3588 ((eq org-use-tag-inheritance t) t)
3589 ((not org-use-tag-inheritance) nil)
3590 ((stringp org-use-tag-inheritance)
3591 (string-match org-use-tag-inheritance tag))
3592 ((listp org-use-tag-inheritance)
3593 (member tag org-use-tag-inheritance))
3594 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3596 (defcustom org-tags-match-list-sublevels t
3597 "Non-nil means list also sublevels of headlines matching a search.
3598 This variable applies to tags/property searches, and also to stuck
3599 projects because this search is based on a tags match as well.
3601 When set to the symbol `indented', sublevels are indented with
3602 leading dots.
3604 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3605 the sublevels of a headline matching a tag search often also match
3606 the same search. Listing all of them can create very long lists.
3607 Setting this variable to nil causes subtrees of a match to be skipped.
3609 This variable is semi-obsolete and probably should always be true. It
3610 is better to limit inheritance to certain tags using the variables
3611 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3612 :group 'org-tags
3613 :type '(choice
3614 (const :tag "No, don't list them" nil)
3615 (const :tag "Yes, do list them" t)
3616 (const :tag "List them, indented with leading dots" indented)))
3618 (defcustom org-tags-sort-function nil
3619 "When set, tags are sorted using this function as a comparator."
3620 :group 'org-tags
3621 :type '(choice
3622 (const :tag "No sorting" nil)
3623 (const :tag "Alphabetical" string<)
3624 (const :tag "Reverse alphabetical" string>)
3625 (function :tag "Custom function" nil)))
3627 (defvar org-tags-history nil
3628 "History of minibuffer reads for tags.")
3629 (defvar org-last-tags-completion-table nil
3630 "The last used completion table for tags.")
3631 (defvar org-after-tags-change-hook nil
3632 "Hook that is run after the tags in a line have changed.")
3634 (defgroup org-properties nil
3635 "Options concerning properties in Org mode."
3636 :tag "Org Properties"
3637 :group 'org)
3639 (defcustom org-property-format "%-10s %s"
3640 "How property key/value pairs should be formatted by `indent-line'.
3641 When `indent-line' hits a property definition, it will format the line
3642 according to this format, mainly to make sure that the values are
3643 lined-up with respect to each other."
3644 :group 'org-properties
3645 :type 'string)
3647 (defcustom org-properties-postprocess-alist nil
3648 "Alist of properties and functions to adjust inserted values.
3649 Elements of this alist must be of the form
3651 ([string] [function])
3653 where [string] must be a property name and [function] must be a
3654 lambda expression: this lambda expression must take one argument,
3655 the value to adjust, and return the new value as a string.
3657 For example, this element will allow the property \"Remaining\"
3658 to be updated wrt the relation between the \"Effort\" property
3659 and the clock summary:
3661 ((\"Remaining\" (lambda(value)
3662 (let ((clocksum (org-clock-sum-current-item))
3663 (effort (org-duration-to-minutes
3664 (org-entry-get (point) \"Effort\"))))
3665 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3666 :group 'org-properties
3667 :version "24.1"
3668 :type '(alist :key-type (string :tag "Property")
3669 :value-type (function :tag "Function")))
3671 (defcustom org-use-property-inheritance nil
3672 "Non-nil means properties apply also for sublevels.
3674 This setting is chiefly used during property searches. Turning it on can
3675 cause significant overhead when doing a search, which is why it is not
3676 on by default.
3678 When nil, only the properties directly given in the current entry count.
3679 When t, every property is inherited. The value may also be a list of
3680 properties that should have inheritance, or a regular expression matching
3681 properties that should be inherited.
3683 However, note that some special properties use inheritance under special
3684 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3685 and the properties ending in \"_ALL\" when they are used as descriptor
3686 for valid values of a property.
3688 Note for programmers:
3689 When querying an entry with `org-entry-get', you can control if inheritance
3690 should be used. By default, `org-entry-get' looks only at the local
3691 properties. You can request inheritance by setting the inherit argument
3692 to t (to force inheritance) or to `selective' (to respect the setting
3693 in this variable)."
3694 :group 'org-properties
3695 :type '(choice
3696 (const :tag "Not" nil)
3697 (const :tag "Always" t)
3698 (repeat :tag "Specific properties" (string :tag "Property"))
3699 (regexp :tag "Properties matched by regexp")))
3701 (defun org-property-inherit-p (property)
3702 "Return a non-nil value if PROPERTY should be inherited."
3703 (cond
3704 ((eq org-use-property-inheritance t) t)
3705 ((not org-use-property-inheritance) nil)
3706 ((stringp org-use-property-inheritance)
3707 (string-match org-use-property-inheritance property))
3708 ((listp org-use-property-inheritance)
3709 (member-ignore-case property org-use-property-inheritance))
3710 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3712 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3713 "The default column format, if no other format has been defined.
3714 This variable can be set on the per-file basis by inserting a line
3716 #+COLUMNS: %25ITEM ....."
3717 :group 'org-properties
3718 :type 'string)
3720 (defcustom org-columns-ellipses ".."
3721 "The ellipses to be used when a field in column view is truncated.
3722 When this is the empty string, as many characters as possible are shown,
3723 but then there will be no visual indication that the field has been truncated.
3724 When this is a string of length N, the last N characters of a truncated
3725 field are replaced by this string. If the column is narrower than the
3726 ellipses string, only part of the ellipses string will be shown."
3727 :group 'org-properties
3728 :type 'string)
3730 (defconst org-global-properties-fixed
3731 '(("VISIBILITY_ALL" . "folded children content all")
3732 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3733 "List of property/value pairs that can be inherited by any entry.
3735 These are fixed values, for the preset properties. The user variable
3736 that can be used to add to this list is `org-global-properties'.
3738 The entries in this list are cons cells where the car is a property
3739 name and cdr is a string with the value. If the value represents
3740 multiple items like an \"_ALL\" property, separate the items by
3741 spaces.")
3743 (defcustom org-global-properties nil
3744 "List of property/value pairs that can be inherited by any entry.
3746 This list will be combined with the constant `org-global-properties-fixed'.
3748 The entries in this list are cons cells where the car is a property
3749 name and cdr is a string with the value.
3751 You can set buffer-local values for the same purpose in the variable
3752 `org-file-properties' this by adding lines like
3754 #+PROPERTY: NAME VALUE"
3755 :group 'org-properties
3756 :type '(repeat
3757 (cons (string :tag "Property")
3758 (string :tag "Value"))))
3760 (defvar-local org-file-properties nil
3761 "List of property/value pairs that can be inherited by any entry.
3762 Valid for the current buffer.
3763 This variable is populated from #+PROPERTY lines.")
3765 (defgroup org-agenda nil
3766 "Options concerning agenda views in Org mode."
3767 :tag "Org Agenda"
3768 :group 'org)
3770 (defvar-local org-category nil
3771 "Variable used by org files to set a category for agenda display.
3772 Such files should use a file variable to set it, for example
3774 # -*- mode: org; org-category: \"ELisp\"
3776 or contain a special line
3778 #+CATEGORY: ELisp
3780 If the file does not specify a category, then file's base name
3781 is used instead.")
3782 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3784 (defcustom org-agenda-files nil
3785 "The files to be used for agenda display.
3787 If an entry is a directory, all files in that directory that are matched
3788 by `org-agenda-file-regexp' will be part of the file list.
3790 If the value of the variable is not a list but a single file name, then
3791 the list of agenda files is actually stored and maintained in that file,
3792 one agenda file per line. In this file paths can be given relative to
3793 `org-directory'. Tilde expansion and environment variable substitution
3794 are also made.
3796 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3797 and removed with `\\[org-remove-file]'."
3798 :group 'org-agenda
3799 :type '(choice
3800 (repeat :tag "List of files and directories" file)
3801 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3803 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3804 "Regular expression to match files for `org-agenda-files'.
3805 If any element in the list in that variable contains a directory instead
3806 of a normal file, all files in that directory that are matched by this
3807 regular expression will be included."
3808 :group 'org-agenda
3809 :type 'regexp)
3811 (defcustom org-agenda-text-search-extra-files nil
3812 "List of extra files to be searched by text search commands.
3813 These files will be searched in addition to the agenda files by the
3814 commands `org-search-view' (`\\[org-agenda] s') \
3815 and `org-occur-in-agenda-files'.
3816 Note that these files will only be searched for text search commands,
3817 not for the other agenda views like todo lists, tag searches or the weekly
3818 agenda. This variable is intended to list notes and possibly archive files
3819 that should also be searched by these two commands.
3820 In fact, if the first element in the list is the symbol `agenda-archives',
3821 then all archive files of all agenda files will be added to the search
3822 scope."
3823 :group 'org-agenda
3824 :type '(set :greedy t
3825 (const :tag "Agenda Archives" agenda-archives)
3826 (repeat :inline t (file))))
3828 (defvaralias 'org-agenda-multi-occur-extra-files
3829 'org-agenda-text-search-extra-files)
3831 (defcustom org-agenda-skip-unavailable-files nil
3832 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3833 A nil value means to remove them, after a query, from the list."
3834 :group 'org-agenda
3835 :type 'boolean)
3837 (defcustom org-calendar-to-agenda-key [?c]
3838 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3839 The command `org-calendar-goto-agenda' will be bound to this key. The
3840 default is the character `c' because then `c' can be used to switch back and
3841 forth between agenda and calendar."
3842 :group 'org-agenda
3843 :type 'sexp)
3845 (defcustom org-calendar-insert-diary-entry-key [?i]
3846 "The key to be installed in `calendar-mode-map' for adding diary entries.
3847 This option is irrelevant until `org-agenda-diary-file' has been configured
3848 to point to an Org file. When that is the case, the command
3849 `org-agenda-diary-entry' will be bound to the key given here, by default
3850 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3851 if you want to continue doing this, you need to change this to a different
3852 key."
3853 :group 'org-agenda
3854 :type 'sexp)
3856 (defcustom org-agenda-diary-file 'diary-file
3857 "File to which to add new entries with the `i' key in agenda and calendar.
3858 When this is the symbol `diary-file', the functionality in the Emacs
3859 calendar will be used to add entries to the `diary-file'. But when this
3860 points to a file, `org-agenda-diary-entry' will be used instead."
3861 :group 'org-agenda
3862 :type '(choice
3863 (const :tag "The standard Emacs diary file" diary-file)
3864 (file :tag "Special Org file diary entries")))
3866 (eval-after-load "calendar"
3867 '(progn
3868 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3869 'org-calendar-goto-agenda)
3870 (add-hook 'calendar-mode-hook
3871 (lambda ()
3872 (unless (eq org-agenda-diary-file 'diary-file)
3873 (define-key calendar-mode-map
3874 org-calendar-insert-diary-entry-key
3875 'org-agenda-diary-entry))))))
3877 (defgroup org-latex nil
3878 "Options for embedding LaTeX code into Org mode."
3879 :tag "Org LaTeX"
3880 :group 'org)
3882 (defcustom org-format-latex-options
3883 '(:foreground default :background default :scale 1.0
3884 :html-foreground "Black" :html-background "Transparent"
3885 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3886 "Options for creating images from LaTeX fragments.
3887 This is a property list with the following properties:
3888 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3889 `default' means use the foreground of the default face.
3890 `auto' means use the foreground from the text face.
3891 :background the background color, or \"Transparent\".
3892 `default' means use the background of the default face.
3893 `auto' means use the background from the text face.
3894 :scale a scaling factor for the size of the images, to get more pixels
3895 :html-foreground, :html-background, :html-scale
3896 the same numbers for HTML export.
3897 :matchers a list indicating which matchers should be used to
3898 find LaTeX fragments. Valid members of this list are:
3899 \"begin\" find environments
3900 \"$1\" find single characters surrounded by $.$
3901 \"$\" find math expressions surrounded by $...$
3902 \"$$\" find math expressions surrounded by $$....$$
3903 \"\\(\" find math expressions surrounded by \\(...\\)
3904 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3905 :group 'org-latex
3906 :type 'plist)
3908 (defcustom org-format-latex-signal-error t
3909 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3910 When nil, just push out a message."
3911 :group 'org-latex
3912 :version "24.1"
3913 :type 'boolean)
3915 (defcustom org-latex-to-mathml-jar-file nil
3916 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3917 Use this to specify additional executable file say a jar file.
3919 When using MathToWeb as the converter, specify the full-path to
3920 your mathtoweb.jar file."
3921 :group 'org-latex
3922 :version "24.1"
3923 :type '(choice
3924 (const :tag "None" nil)
3925 (file :tag "JAR file" :must-match t)))
3927 (defcustom org-latex-to-mathml-convert-command nil
3928 "Command to convert LaTeX fragments to MathML.
3929 Replace format-specifiers in the command as noted below and use
3930 `shell-command' to convert LaTeX to MathML.
3931 %j: Executable file in fully expanded form as specified by
3932 `org-latex-to-mathml-jar-file'.
3933 %I: Input LaTeX file in fully expanded form.
3934 %i: The latex fragment to be converted.
3935 %o: Output MathML file.
3937 This command is used by `org-create-math-formula'.
3939 When using MathToWeb as the converter, set this option to
3940 \"java -jar %j -unicode -force -df %o %I\".
3942 When using LaTeXML set this option to
3943 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3944 :group 'org-latex
3945 :version "24.1"
3946 :type '(choice
3947 (const :tag "None" nil)
3948 (string :tag "\nShell command")))
3950 (defcustom org-preview-latex-default-process 'dvipng
3951 "The default process to convert LaTeX fragments to image files.
3952 All available processes and theirs documents can be found in
3953 `org-preview-latex-process-alist', which see."
3954 :group 'org-latex
3955 :version "26.1"
3956 :package-version '(Org . "9.0")
3957 :type 'symbol)
3959 (defcustom org-preview-latex-process-alist
3960 '((dvipng
3961 :programs ("latex" "dvipng")
3962 :description "dvi > png"
3963 :message "you need to install the programs: latex and dvipng."
3964 :image-input-type "dvi"
3965 :image-output-type "png"
3966 :image-size-adjust (1.0 . 1.0)
3967 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3968 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3969 (dvisvgm
3970 :programs ("latex" "dvisvgm")
3971 :description "dvi > svg"
3972 :message "you need to install the programs: latex and dvisvgm."
3973 :use-xcolor t
3974 :image-input-type "dvi"
3975 :image-output-type "svg"
3976 :image-size-adjust (1.7 . 1.5)
3977 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3978 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3979 (imagemagick
3980 :programs ("latex" "convert")
3981 :description "pdf > png"
3982 :message "you need to install the programs: latex and imagemagick."
3983 :use-xcolor t
3984 :image-input-type "pdf"
3985 :image-output-type "png"
3986 :image-size-adjust (1.0 . 1.0)
3987 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3988 :image-converter
3989 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3990 "Definitions of external processes for LaTeX previewing.
3991 Org mode can use some external commands to generate TeX snippet's images for
3992 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3993 `org-create-formula-image' how to call them.
3995 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3996 PROPERTIES accepts the following attributes:
3998 :programs list of strings, required programs.
3999 :description string, describe the process.
4000 :message string, message it when required programs cannot be found.
4001 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4002 :image-output-type string, output file type of image converter (e.g., \"png\").
4003 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4004 deal with background and foreground color of image.
4005 Otherwise, dvipng style background and foregroud color
4006 format are generated. You may then refer to them in
4007 command options with \"%F\" and \"%B\".
4008 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4009 image size showed in buffer and the cdr element is for
4010 HTML file. This option is only useful for process
4011 developers, users should use variable
4012 `org-format-latex-options' instead.
4013 :post-clean list of strings, files matched are to be cleaned up once
4014 the image is generated. When nil, the files with \".dvi\",
4015 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4016 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4017 be cleaned up.
4018 :latex-header list of strings, the LaTeX header of the snippet file.
4019 When nil, the fallback value is used instead, which is
4020 controlled by `org-format-latex-header',
4021 `org-latex-default-packages-alist' and
4022 `org-latex-packages-alist', which see.
4023 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4024 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4025 replaced with values defined below.
4026 :image-converter list of image converter commands strings. Each of them is
4027 given to the shell and supports any of the following
4028 place-holders defined below.
4030 Place-holders used by `:image-converter' and `:latex-compiler':
4032 %f input file name
4033 %b base name of input file
4034 %o base directory of input file
4035 %O absolute output file name
4037 Place-holders only used by `:image-converter':
4039 %F foreground of image
4040 %B background of image
4041 %D dpi, which is used to adjust image size by some processing commands.
4042 %S the image size scale ratio, which is used to adjust image size by some
4043 processing commands."
4044 :group 'org-latex
4045 :version "26.1"
4046 :package-version '(Org . "9.0")
4047 :type '(alist :tag "LaTeX to image backends"
4048 :value-type (plist)))
4050 (defcustom org-preview-latex-image-directory "ltximg/"
4051 "Path to store latex preview images.
4052 A relative path here creates many directories relative to the
4053 processed org files paths. An absolute path puts all preview
4054 images at the same place."
4055 :group 'org-latex
4056 :version "26.1"
4057 :package-version '(Org . "9.0")
4058 :type 'string)
4060 (defun org-format-latex-mathml-available-p ()
4061 "Return t if `org-latex-to-mathml-convert-command' is usable."
4062 (save-match-data
4063 (when (and (boundp 'org-latex-to-mathml-convert-command)
4064 org-latex-to-mathml-convert-command)
4065 (let ((executable (car (split-string
4066 org-latex-to-mathml-convert-command))))
4067 (when (executable-find executable)
4068 (if (string-match
4069 "%j" org-latex-to-mathml-convert-command)
4070 (file-readable-p org-latex-to-mathml-jar-file)
4071 t))))))
4073 (defcustom org-format-latex-header "\\documentclass{article}
4074 \\usepackage[usenames]{color}
4075 \[PACKAGES]
4076 \[DEFAULT-PACKAGES]
4077 \\pagestyle{empty} % do not remove
4078 % The settings below are copied from fullpage.sty
4079 \\setlength{\\textwidth}{\\paperwidth}
4080 \\addtolength{\\textwidth}{-3cm}
4081 \\setlength{\\oddsidemargin}{1.5cm}
4082 \\addtolength{\\oddsidemargin}{-2.54cm}
4083 \\setlength{\\evensidemargin}{\\oddsidemargin}
4084 \\setlength{\\textheight}{\\paperheight}
4085 \\addtolength{\\textheight}{-\\headheight}
4086 \\addtolength{\\textheight}{-\\headsep}
4087 \\addtolength{\\textheight}{-\\footskip}
4088 \\addtolength{\\textheight}{-3cm}
4089 \\setlength{\\topmargin}{1.5cm}
4090 \\addtolength{\\topmargin}{-2.54cm}"
4091 "The document header used for processing LaTeX fragments.
4092 It is imperative that this header make sure that no page number
4093 appears on the page. The package defined in the variables
4094 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4095 will either replace the placeholder \"[PACKAGES]\" in this
4096 header, or they will be appended."
4097 :group 'org-latex
4098 :type 'string)
4100 (defun org-set-packages-alist (var val)
4101 "Set the packages alist and make sure it has 3 elements per entry."
4102 (set var (mapcar (lambda (x)
4103 (if (and (consp x) (= (length x) 2))
4104 (list (car x) (nth 1 x) t)
4106 val)))
4108 (defun org-get-packages-alist (var)
4109 "Get the packages alist and make sure it has 3 elements per entry."
4110 (mapcar (lambda (x)
4111 (if (and (consp x) (= (length x) 2))
4112 (list (car x) (nth 1 x) t)
4114 (default-value var)))
4116 (defcustom org-latex-default-packages-alist
4117 '(("AUTO" "inputenc" t ("pdflatex"))
4118 ("T1" "fontenc" t ("pdflatex"))
4119 ("" "graphicx" t)
4120 ("" "grffile" t)
4121 ("" "longtable" nil)
4122 ("" "wrapfig" nil)
4123 ("" "rotating" nil)
4124 ("normalem" "ulem" t)
4125 ("" "amsmath" t)
4126 ("" "textcomp" t)
4127 ("" "amssymb" t)
4128 ("" "capt-of" nil)
4129 ("" "hyperref" nil))
4130 "Alist of default packages to be inserted in the header.
4132 Change this only if one of the packages here causes an
4133 incompatibility with another package you are using.
4135 The packages in this list are needed by one part or another of
4136 Org mode to function properly:
4138 - inputenc, fontenc: for basic font and character selection
4139 - graphicx: for including images
4140 - grffile: allow periods and spaces in graphics file names
4141 - longtable: For multipage tables
4142 - wrapfig: for figure placement
4143 - rotating: for sideways figures and tables
4144 - ulem: for underline and strike-through
4145 - amsmath: for subscript and superscript and math environments
4146 - textcomp, amssymb: for various symbols used
4147 for interpreting the entities in `org-entities'. You can skip
4148 some of these packages if you don't use any of their symbols.
4149 - capt-of: for captions outside of floats
4150 - hyperref: for cross references
4152 Therefore you should not modify this variable unless you know
4153 what you are doing. The one reason to change it anyway is that
4154 you might be loading some other package that conflicts with one
4155 of the default packages. Each element is either a cell or
4156 a string.
4158 A cell is of the format
4160 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4162 If SNIPPET-FLAG is non-nil, the package also needs to be included
4163 when compiling LaTeX snippets into images for inclusion into
4164 non-LaTeX output. COMPILERS is a list of compilers that should
4165 include the package, see `org-latex-compiler'. If the document
4166 compiler is not in the list, and the list is non-nil, the package
4167 will not be inserted in the final document.
4169 A string will be inserted as-is in the header of the document."
4170 :group 'org-latex
4171 :group 'org-export-latex
4172 :set 'org-set-packages-alist
4173 :get 'org-get-packages-alist
4174 :version "26.1"
4175 :package-version '(Org . "8.3")
4176 :type '(repeat
4177 (choice
4178 (list :tag "options/package pair"
4179 (string :tag "options")
4180 (string :tag "package")
4181 (boolean :tag "Snippet"))
4182 (string :tag "A line of LaTeX"))))
4184 (defcustom org-latex-packages-alist nil
4185 "Alist of packages to be inserted in every LaTeX header.
4187 These will be inserted after `org-latex-default-packages-alist'.
4188 Each element is either a cell or a string.
4190 A cell is of the format:
4192 (\"options\" \"package\" SNIPPET-FLAG)
4194 SNIPPET-FLAG, when non-nil, indicates that this package is also
4195 needed when turning LaTeX snippets into images for inclusion into
4196 non-LaTeX output.
4198 A string will be inserted as-is in the header of the document.
4200 Make sure that you only list packages here which:
4202 - you want in every file;
4203 - do not conflict with the setup in `org-format-latex-header';
4204 - do not conflict with the default packages in
4205 `org-latex-default-packages-alist'."
4206 :group 'org-latex
4207 :group 'org-export-latex
4208 :set 'org-set-packages-alist
4209 :get 'org-get-packages-alist
4210 :type '(repeat
4211 (choice
4212 (list :tag "options/package pair"
4213 (string :tag "options")
4214 (string :tag "package")
4215 (boolean :tag "Snippet"))
4216 (string :tag "A line of LaTeX"))))
4218 (defgroup org-appearance nil
4219 "Settings for Org mode appearance."
4220 :tag "Org Appearance"
4221 :group 'org)
4223 (defcustom org-level-color-stars-only nil
4224 "Non-nil means fontify only the stars in each headline.
4225 When nil, the entire headline is fontified.
4226 Changing it requires restart of `font-lock-mode' to become effective
4227 also in regions already fontified."
4228 :group 'org-appearance
4229 :type 'boolean)
4231 (defcustom org-hide-leading-stars nil
4232 "Non-nil means hide the first N-1 stars in a headline.
4233 This works by using the face `org-hide' for these stars. This
4234 face is white for a light background, and black for a dark
4235 background. You may have to customize the face `org-hide' to
4236 make this work.
4237 Changing it requires restart of `font-lock-mode' to become effective
4238 also in regions already fontified.
4239 You may also set this on a per-file basis by adding one of the following
4240 lines to the buffer:
4242 #+STARTUP: hidestars
4243 #+STARTUP: showstars"
4244 :group 'org-appearance
4245 :type 'boolean)
4247 (defcustom org-hidden-keywords nil
4248 "List of symbols corresponding to keywords to be hidden the org buffer.
4249 For example, a value \\='(title) for this list will make the document's title
4250 appear in the buffer without the initial #+TITLE: keyword."
4251 :group 'org-appearance
4252 :version "24.1"
4253 :type '(set (const :tag "#+AUTHOR" author)
4254 (const :tag "#+DATE" date)
4255 (const :tag "#+EMAIL" email)
4256 (const :tag "#+TITLE" title)))
4258 (defcustom org-custom-properties nil
4259 "List of properties (as strings) with a special meaning.
4260 The default use of these custom properties is to let the user
4261 hide them with `org-toggle-custom-properties-visibility'."
4262 :group 'org-properties
4263 :group 'org-appearance
4264 :version "24.3"
4265 :type '(repeat (string :tag "Property Name")))
4267 (defcustom org-fontify-done-headline nil
4268 "Non-nil means change the face of a headline if it is marked DONE.
4269 Normally, only the TODO/DONE keyword indicates the state of a headline.
4270 When this is non-nil, the headline after the keyword is set to the
4271 `org-headline-done' as an additional indication."
4272 :group 'org-appearance
4273 :type 'boolean)
4275 (defcustom org-fontify-emphasized-text t
4276 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4277 Changing this variable requires a restart of Emacs to take effect."
4278 :group 'org-appearance
4279 :type 'boolean)
4281 (defcustom org-fontify-whole-heading-line nil
4282 "Non-nil means fontify the whole line for headings.
4283 This is useful when setting a background color for the
4284 org-level-* faces."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-highlight-latex-and-related nil
4289 "Non-nil means highlight LaTeX related syntax in the buffer.
4290 When non nil, the value should be a list containing any of the
4291 following symbols:
4292 `latex' Highlight LaTeX snippets and environments.
4293 `script' Highlight subscript and superscript.
4294 `entities' Highlight entities."
4295 :group 'org-appearance
4296 :version "24.4"
4297 :package-version '(Org . "8.0")
4298 :type '(choice
4299 (const :tag "No highlighting" nil)
4300 (set :greedy t :tag "Highlight"
4301 (const :tag "LaTeX snippets and environments" latex)
4302 (const :tag "Subscript and superscript" script)
4303 (const :tag "Entities" entities))))
4305 (defcustom org-hide-emphasis-markers nil
4306 "Non-nil mean font-lock should hide the emphasis marker characters."
4307 :group 'org-appearance
4308 :type 'boolean)
4310 (defcustom org-hide-macro-markers nil
4311 "Non-nil mean font-lock should hide the brackets marking macro calls."
4312 :group 'org-appearance
4313 :type 'boolean)
4315 (defcustom org-pretty-entities nil
4316 "Non-nil means show entities as UTF8 characters.
4317 When nil, the \\name form remains in the buffer."
4318 :group 'org-appearance
4319 :version "24.1"
4320 :type 'boolean)
4322 (defcustom org-pretty-entities-include-sub-superscripts t
4323 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4324 :group 'org-appearance
4325 :version "24.1"
4326 :type 'boolean)
4328 (defvar org-emph-re nil
4329 "Regular expression for matching emphasis.
4330 After a match, the match groups contain these elements:
4331 0 The match of the full regular expression, including the characters
4332 before and after the proper match
4333 1 The character before the proper match, or empty at beginning of line
4334 2 The proper match, including the leading and trailing markers
4335 3 The leading marker like * or /, indicating the type of highlighting
4336 4 The text between the emphasis markers, not including the markers
4337 5 The character after the match, empty at the end of a line")
4339 (defvar org-verbatim-re nil
4340 "Regular expression for matching verbatim text.")
4342 (defvar org-emphasis-regexp-components) ; defined just below
4343 (defvar org-emphasis-alist) ; defined just below
4344 (defun org-set-emph-re (var val)
4345 "Set variable and compute the emphasis regular expression."
4346 (set var val)
4347 (when (and (boundp 'org-emphasis-alist)
4348 (boundp 'org-emphasis-regexp-components)
4349 org-emphasis-alist org-emphasis-regexp-components)
4350 (pcase-let*
4351 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4352 (body (if (<= nl 0) body
4353 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4354 (template
4355 (format (concat "\\([%s]\\|^\\)" ;before markers
4356 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4357 "\\([%s]\\|$\\)") ;after markers
4358 pre border border body border post)))
4359 (setq org-emph-re (format template "*/_+"))
4360 (setq org-verbatim-re (format template "=~")))))
4362 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4363 ;; set this option proved cumbersome. See this message/thread:
4364 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4365 (defvar org-emphasis-regexp-components
4366 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4367 "Components used to build the regular expression for emphasis.
4368 This is a list with five entries. Terminology: In an emphasis string
4369 like \" *strong word* \", we call the initial space PREMATCH, the final
4370 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4371 and \"trong wor\" is the body. The different components in this variable
4372 specify what is allowed/forbidden in each part:
4374 pre Chars allowed as prematch. Beginning of line will be allowed too.
4375 post Chars allowed as postmatch. End of line will be allowed too.
4376 border The chars *forbidden* as border characters.
4377 body-regexp A regexp like \".\" to match a body character. Don't use
4378 non-shy groups here, and don't allow newline here.
4379 newline The maximum number of newlines allowed in an emphasis exp.
4381 You need to reload Org or to restart Emacs after customizing this.")
4383 (defcustom org-emphasis-alist
4384 '(("*" bold)
4385 ("/" italic)
4386 ("_" underline)
4387 ("=" org-verbatim verbatim)
4388 ("~" org-code verbatim)
4389 ("+" (:strike-through t)))
4390 "Alist of characters and faces to emphasize text.
4391 Text starting and ending with a special character will be emphasized,
4392 for example *bold*, _underlined_ and /italic/. This variable sets the
4393 marker characters and the face to be used by font-lock for highlighting
4394 in Org buffers.
4396 You need to reload Org or to restart Emacs after customizing this."
4397 :group 'org-appearance
4398 :set 'org-set-emph-re
4399 :version "24.4"
4400 :package-version '(Org . "8.0")
4401 :type '(repeat
4402 (list
4403 (string :tag "Marker character")
4404 (choice
4405 (face :tag "Font-lock-face")
4406 (plist :tag "Face property list"))
4407 (option (const verbatim)))))
4409 (defvar org-protecting-blocks '("src" "example" "export")
4410 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4411 This is needed for font-lock setup.")
4413 ;;; Functions and variables from their packages
4414 ;; Declared here to avoid compiler warnings
4415 (defvar mark-active)
4417 ;; Various packages
4418 (declare-function calc-eval "calc" (str &optional separator &rest args))
4419 (declare-function calendar-forward-day "cal-move" (arg))
4420 (declare-function calendar-goto-date "cal-move" (date))
4421 (declare-function calendar-goto-today "cal-move" ())
4422 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4423 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4424 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4425 (declare-function cdlatex-tab "ext:cdlatex" ())
4426 (declare-function dired-get-filename
4427 "dired"
4428 (&optional localp no-error-if-not-filep))
4429 (declare-function iswitchb-read-buffer
4430 "iswitchb"
4431 (prompt &optional
4432 default require-match _predicate start matches-set))
4433 (declare-function org-agenda-change-all-lines
4434 "org-agenda"
4435 (newhead hdmarker &optional fixface just-this))
4436 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4437 "org-agenda"
4438 (&optional end))
4439 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4440 (declare-function org-agenda-format-item
4441 "org-agenda"
4442 (extra txt &optional level category tags dotime
4443 remove-re habitp))
4444 (declare-function org-agenda-maybe-redo "org-agenda" ())
4445 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4446 (declare-function org-agenda-save-markers-for-cut-and-paste
4447 "org-agenda"
4448 (beg end))
4449 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4450 (declare-function org-agenda-skip "org-agenda" ())
4451 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4452 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4453 (declare-function org-indent-mode "org-indent" (&optional arg))
4454 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4455 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4456 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4457 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4458 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4459 (declare-function parse-time-string "parse-time" (string))
4460 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4462 (defvar align-mode-rules-list)
4463 (defvar calc-embedded-close-formula)
4464 (defvar calc-embedded-open-formula)
4465 (defvar calc-embedded-open-mode)
4466 (defvar font-lock-unfontify-region-function)
4467 (defvar iswitchb-temp-buflist)
4468 (defvar org-agenda-tags-todo-honor-ignore-options)
4469 (defvar remember-data-file)
4470 (defvar texmathp-why)
4472 ;;;###autoload
4473 (defun turn-on-orgtbl ()
4474 "Unconditionally turn on `orgtbl-mode'."
4475 (require 'org-table)
4476 (orgtbl-mode 1))
4478 (defun org-at-table-p (&optional table-type)
4479 "Non-nil if the cursor is inside an Org table.
4480 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4481 If `org-enable-table-editor' is nil, return nil unconditionally."
4482 (and
4483 org-enable-table-editor
4484 (save-excursion
4485 (beginning-of-line)
4486 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4487 (or (not (derived-mode-p 'org-mode))
4488 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4489 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4491 (defun org-at-table.el-p ()
4492 "Non-nil when point is at a table.el table."
4493 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4494 (let ((element (org-element-at-point)))
4495 (and (eq (org-element-type element) 'table)
4496 (eq (org-element-property :type element) 'table.el)))))
4498 (defun org-at-table-hline-p ()
4499 "Non-nil when point is inside a hline in a table.
4500 Assume point is already in a table. If `org-enable-table-editor'
4501 is nil, return nil unconditionally."
4502 (and org-enable-table-editor
4503 (save-excursion
4504 (beginning-of-line)
4505 (looking-at org-table-hline-regexp))))
4507 (defun org-table-map-tables (function &optional quietly)
4508 "Apply FUNCTION to the start of all tables in the buffer."
4509 (org-with-wide-buffer
4510 (goto-char (point-min))
4511 (while (re-search-forward org-table-any-line-regexp nil t)
4512 (unless quietly
4513 (message "Mapping tables: %d%%"
4514 (floor (* 100.0 (point)) (buffer-size))))
4515 (beginning-of-line 1)
4516 (when (and (looking-at org-table-line-regexp)
4517 ;; Exclude tables in src/example/verbatim/clocktable blocks
4518 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4519 (save-excursion (funcall function))
4520 (or (looking-at org-table-line-regexp)
4521 (forward-char 1)))
4522 (re-search-forward org-table-any-border-regexp nil 1)))
4523 (unless quietly (message "Mapping tables: done")))
4525 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4526 (declare-function org-clock-update-mode-line "org-clock" ())
4527 (declare-function org-resolve-clocks "org-clock"
4528 (&optional also-non-dangling-p prompt last-valid))
4530 (defun org-at-TBLFM-p (&optional pos)
4531 "Non-nil when point (or POS) is in #+TBLFM line."
4532 (save-excursion
4533 (goto-char (or pos (point)))
4534 (beginning-of-line)
4535 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4536 (eq (org-element-type (org-element-at-point)) 'table))))
4538 (defvar org-clock-start-time)
4539 (defvar org-clock-marker (make-marker)
4540 "Marker recording the last clock-in.")
4541 (defvar org-clock-hd-marker (make-marker)
4542 "Marker recording the last clock-in, but the headline position.")
4543 (defvar org-clock-heading ""
4544 "The heading of the current clock entry.")
4545 (defun org-clock-is-active ()
4546 "Return the buffer where the clock is currently running.
4547 Return nil if no clock is running."
4548 (marker-buffer org-clock-marker))
4550 (defun org-check-running-clock ()
4551 "Check if the current buffer contains the running clock.
4552 If yes, offer to stop it and to save the buffer with the changes."
4553 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4554 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4555 (buffer-name))))
4556 (org-clock-out)
4557 (when (y-or-n-p "Save changed buffer?")
4558 (save-buffer))))
4560 (defun org-clocktable-try-shift (dir n)
4561 "Check if this line starts a clock table, if yes, shift the time block."
4562 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4563 (org-clocktable-shift dir n)))
4565 ;;;###autoload
4566 (defun org-clock-persistence-insinuate ()
4567 "Set up hooks for clock persistence."
4568 (require 'org-clock)
4569 (add-hook 'org-mode-hook 'org-clock-load)
4570 (add-hook 'kill-emacs-hook 'org-clock-save))
4572 (defgroup org-archive nil
4573 "Options concerning archiving in Org mode."
4574 :tag "Org Archive"
4575 :group 'org-structure)
4577 (defcustom org-archive-location "%s_archive::"
4578 "The location where subtrees should be archived.
4580 The value of this variable is a string, consisting of two parts,
4581 separated by a double-colon. The first part is a filename and
4582 the second part is a headline.
4584 When the filename is omitted, archiving happens in the same file.
4585 %s in the filename will be replaced by the current file
4586 name (without the directory part). Archiving to a different file
4587 is useful to keep archived entries from contributing to the
4588 Org Agenda.
4590 The archived entries will be filed as subtrees of the specified
4591 headline. When the headline is omitted, the subtrees are simply
4592 filed away at the end of the file, as top-level entries. Also in
4593 the heading you can use %s to represent the file name, this can be
4594 useful when using the same archive for a number of different files.
4596 Here are a few examples:
4597 \"%s_archive::\"
4598 If the current file is Projects.org, archive in file
4599 Projects.org_archive, as top-level trees. This is the default.
4601 \"::* Archived Tasks\"
4602 Archive in the current file, under the top-level headline
4603 \"* Archived Tasks\".
4605 \"~/org/archive.org::\"
4606 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4608 \"~/org/archive.org::* From %s\"
4609 Archive in file ~/org/archive.org (absolute path), under headlines
4610 \"From FILENAME\" where file name is the current file name.
4612 \"~/org/datetree.org::datetree/* Finished Tasks\"
4613 The \"datetree/\" string is special, signifying to archive
4614 items to the datetree. Items are placed in either the CLOSED
4615 date of the item, or the current date if there is no CLOSED date.
4616 The heading will be a subentry to the current date. There doesn't
4617 need to be a heading, but there always needs to be a slash after
4618 datetree. For example, to store archived items directly in the
4619 datetree, use \"~/org/datetree.org::datetree/\".
4621 \"basement::** Finished Tasks\"
4622 Archive in file ./basement (relative path), as level 3 trees
4623 below the level 2 heading \"** Finished Tasks\".
4625 You may set this option on a per-file basis by adding to the buffer a
4626 line like
4628 #+ARCHIVE: basement::** Finished Tasks
4630 You may also define it locally for a subtree by setting an ARCHIVE property
4631 in the entry. If such a property is found in an entry, or anywhere up
4632 the hierarchy, it will be used."
4633 :group 'org-archive
4634 :type 'string)
4636 (defcustom org-agenda-skip-archived-trees t
4637 "Non-nil means the agenda will skip any items located in archived trees.
4638 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4639 variable is no longer recommended, you should leave it at the value t.
4640 Instead, use the key `v' to cycle the archives-mode in the agenda."
4641 :group 'org-archive
4642 :group 'org-agenda-skip
4643 :type 'boolean)
4645 (defcustom org-columns-skip-archived-trees t
4646 "Non-nil means ignore archived trees when creating column view."
4647 :group 'org-archive
4648 :group 'org-properties
4649 :type 'boolean)
4651 (defcustom org-cycle-open-archived-trees nil
4652 "Non-nil means `org-cycle' will open archived trees.
4653 An archived tree is a tree marked with the tag ARCHIVE.
4654 When nil, archived trees will stay folded. You can still open them with
4655 normal outline commands like `show-all', but not with the cycling commands."
4656 :group 'org-archive
4657 :group 'org-cycle
4658 :type 'boolean)
4660 (defcustom org-sparse-tree-open-archived-trees nil
4661 "Non-nil means sparse tree construction shows matches in archived trees.
4662 When nil, matches in these trees are highlighted, but the trees are kept in
4663 collapsed state."
4664 :group 'org-archive
4665 :group 'org-sparse-trees
4666 :type 'boolean)
4668 (defcustom org-sparse-tree-default-date-type nil
4669 "The default date type when building a sparse tree.
4670 When this is nil, a date is a scheduled or a deadline timestamp.
4671 Otherwise, these types are allowed:
4673 all: all timestamps
4674 active: only active timestamps (<...>)
4675 inactive: only inactive timestamps ([...])
4676 scheduled: only scheduled timestamps
4677 deadline: only deadline timestamps"
4678 :type '(choice (const :tag "Scheduled or deadline" nil)
4679 (const :tag "All timestamps" all)
4680 (const :tag "Only active timestamps" active)
4681 (const :tag "Only inactive timestamps" inactive)
4682 (const :tag "Only scheduled timestamps" scheduled)
4683 (const :tag "Only deadline timestamps" deadline)
4684 (const :tag "Only closed timestamps" closed))
4685 :version "26.1"
4686 :package-version '(Org . "8.3")
4687 :group 'org-sparse-trees)
4689 (defun org-cycle-hide-archived-subtrees (state)
4690 "Re-hide all archived subtrees after a visibility state change."
4691 (when (and (not org-cycle-open-archived-trees)
4692 (not (memq state '(overview folded))))
4693 (save-excursion
4694 (let* ((globalp (memq state '(contents all)))
4695 (beg (if globalp (point-min) (point)))
4696 (end (if globalp (point-max) (org-end-of-subtree t))))
4697 (org-hide-archived-subtrees beg end)
4698 (goto-char beg)
4699 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4700 (message "%s" (substitute-command-keys
4701 "Subtree is archived and stays closed. Use \
4702 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4704 (defun org-force-cycle-archived ()
4705 "Cycle subtree even if it is archived."
4706 (interactive)
4707 (setq this-command 'org-cycle)
4708 (let ((org-cycle-open-archived-trees t))
4709 (call-interactively 'org-cycle)))
4711 (defun org-hide-archived-subtrees (beg end)
4712 "Re-hide all archived subtrees after a visibility state change."
4713 (org-with-wide-buffer
4714 (let ((case-fold-search nil)
4715 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4716 (goto-char beg)
4717 ;; Include headline point is currently on.
4718 (beginning-of-line)
4719 (while (and (< (point) end) (re-search-forward re end t))
4720 (when (member org-archive-tag (org-get-tags))
4721 (org-flag-subtree t)
4722 (org-end-of-subtree t))))))
4724 (declare-function outline-end-of-heading "outline" ())
4725 (declare-function outline-flag-region "outline" (from to flag))
4726 (defun org-flag-subtree (flag)
4727 (save-excursion
4728 (org-back-to-heading t)
4729 (outline-end-of-heading)
4730 (outline-flag-region (point)
4731 (progn (org-end-of-subtree t) (point))
4732 flag)))
4734 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4736 ;; Declare Column View Code
4738 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4739 (declare-function org-columns-compute "org-colview" (property))
4741 ;; Declare ID code
4743 (declare-function org-id-store-link "org-id")
4744 (declare-function org-id-locations-load "org-id")
4745 (declare-function org-id-locations-save "org-id")
4746 (defvar org-id-track-globally)
4748 ;;; Variables for pre-computed regular expressions, all buffer local
4750 (defvar-local org-todo-regexp nil
4751 "Matches any of the TODO state keywords.
4752 Since TODO keywords are case-sensitive, `case-fold-search' is
4753 expected to be bound to nil when matching against this regexp.")
4755 (defvar-local org-not-done-regexp nil
4756 "Matches any of the TODO state keywords except the last one.
4757 Since TODO keywords are case-sensitive, `case-fold-search' is
4758 expected to be bound to nil when matching against this regexp.")
4760 (defvar-local org-not-done-heading-regexp nil
4761 "Matches a TODO headline that is not done.
4762 Since TODO keywords are case-sensitive, `case-fold-search' is
4763 expected to be bound to nil when matching against this regexp.")
4765 (defvar-local org-todo-line-regexp nil
4766 "Matches a headline and puts TODO state into group 2 if present.
4767 Since TODO keywords are case-sensitive, `case-fold-search' is
4768 expected to be bound to nil when matching against this regexp.")
4770 (defvar-local org-complex-heading-regexp nil
4771 "Matches a headline and puts everything into groups:
4773 group 1: Stars
4774 group 2: The TODO keyword, maybe
4775 group 3: Priority cookie
4776 group 4: True headline
4777 group 5: Tags
4779 Since TODO keywords are case-sensitive, `case-fold-search' is
4780 expected to be bound to nil when matching against this regexp.")
4782 (defvar-local org-complex-heading-regexp-format nil
4783 "Printf format to make regexp to match an exact headline.
4784 This regexp will match the headline of any node which has the
4785 exact headline text that is put into the format, but may have any
4786 TODO state, priority and tags.")
4788 (defvar-local org-todo-line-tags-regexp nil
4789 "Matches a headline and puts TODO state into group 2 if present.
4790 Also put tags into group 4 if tags are present.")
4792 (defconst org-plain-time-of-day-regexp
4793 (concat
4794 "\\(\\<[012]?[0-9]"
4795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4796 "\\(--?"
4797 "\\(\\<[012]?[0-9]"
4798 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4799 "\\)?")
4800 "Regular expression to match a plain time or time range.
4801 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4802 groups carry important information:
4803 0 the full match
4804 1 the first time, range or not
4805 8 the second time, if it is a range.")
4807 (defconst org-plain-time-extension-regexp
4808 (concat
4809 "\\(\\<[012]?[0-9]"
4810 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4811 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4812 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4813 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4814 groups carry important information:
4815 0 the full match
4816 7 hours of duration
4817 9 minutes of duration")
4819 (defconst org-stamp-time-of-day-regexp
4820 (concat
4821 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4822 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4823 "\\(--?"
4824 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4825 "Regular expression to match a timestamp time or time range.
4826 After a match, the following groups carry important information:
4827 0 the full match
4828 1 date plus weekday, for back referencing to make sure both times are on the same day
4829 2 the first time, range or not
4830 4 the second time, if it is a range.")
4832 (defconst org-startup-options
4833 '(("fold" org-startup-folded t)
4834 ("overview" org-startup-folded t)
4835 ("nofold" org-startup-folded nil)
4836 ("showall" org-startup-folded nil)
4837 ("showeverything" org-startup-folded showeverything)
4838 ("content" org-startup-folded content)
4839 ("indent" org-startup-indented t)
4840 ("noindent" org-startup-indented nil)
4841 ("hidestars" org-hide-leading-stars t)
4842 ("showstars" org-hide-leading-stars nil)
4843 ("odd" org-odd-levels-only t)
4844 ("oddeven" org-odd-levels-only nil)
4845 ("align" org-startup-align-all-tables t)
4846 ("noalign" org-startup-align-all-tables nil)
4847 ("inlineimages" org-startup-with-inline-images t)
4848 ("noinlineimages" org-startup-with-inline-images nil)
4849 ("latexpreview" org-startup-with-latex-preview t)
4850 ("nolatexpreview" org-startup-with-latex-preview nil)
4851 ("customtime" org-display-custom-times t)
4852 ("logdone" org-log-done time)
4853 ("lognotedone" org-log-done note)
4854 ("nologdone" org-log-done nil)
4855 ("lognoteclock-out" org-log-note-clock-out t)
4856 ("nolognoteclock-out" org-log-note-clock-out nil)
4857 ("logrepeat" org-log-repeat state)
4858 ("lognoterepeat" org-log-repeat note)
4859 ("logdrawer" org-log-into-drawer t)
4860 ("nologdrawer" org-log-into-drawer nil)
4861 ("logstatesreversed" org-log-states-order-reversed t)
4862 ("nologstatesreversed" org-log-states-order-reversed nil)
4863 ("nologrepeat" org-log-repeat nil)
4864 ("logreschedule" org-log-reschedule time)
4865 ("lognotereschedule" org-log-reschedule note)
4866 ("nologreschedule" org-log-reschedule nil)
4867 ("logredeadline" org-log-redeadline time)
4868 ("lognoteredeadline" org-log-redeadline note)
4869 ("nologredeadline" org-log-redeadline nil)
4870 ("logrefile" org-log-refile time)
4871 ("lognoterefile" org-log-refile note)
4872 ("nologrefile" org-log-refile nil)
4873 ("fninline" org-footnote-define-inline t)
4874 ("nofninline" org-footnote-define-inline nil)
4875 ("fnlocal" org-footnote-section nil)
4876 ("fnauto" org-footnote-auto-label t)
4877 ("fnprompt" org-footnote-auto-label nil)
4878 ("fnconfirm" org-footnote-auto-label confirm)
4879 ("fnplain" org-footnote-auto-label plain)
4880 ("fnadjust" org-footnote-auto-adjust t)
4881 ("nofnadjust" org-footnote-auto-adjust nil)
4882 ("constcgs" constants-unit-system cgs)
4883 ("constSI" constants-unit-system SI)
4884 ("noptag" org-tag-persistent-alist nil)
4885 ("hideblocks" org-hide-block-startup t)
4886 ("nohideblocks" org-hide-block-startup nil)
4887 ("beamer" org-startup-with-beamer-mode t)
4888 ("entitiespretty" org-pretty-entities t)
4889 ("entitiesplain" org-pretty-entities nil))
4890 "Variable associated with STARTUP options for org-mode.
4891 Each element is a list of three items: the startup options (as written
4892 in the #+STARTUP line), the corresponding variable, and the value to set
4893 this variable to if the option is found. An optional forth element PUSH
4894 means to push this value onto the list in the variable.")
4896 (defcustom org-group-tags t
4897 "When non-nil (the default), use group tags.
4898 This can be turned on/off through `org-toggle-tags-groups'."
4899 :group 'org-tags
4900 :group 'org-startup
4901 :type 'boolean)
4903 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4905 (defun org-toggle-tags-groups ()
4906 "Toggle support for group tags.
4907 Support for group tags is controlled by the option
4908 `org-group-tags', which is non-nil by default."
4909 (interactive)
4910 (setq org-group-tags (not org-group-tags))
4911 (cond ((and (derived-mode-p 'org-agenda-mode)
4912 org-group-tags)
4913 (org-agenda-redo))
4914 ((derived-mode-p 'org-mode)
4915 (let ((org-inhibit-startup t)) (org-mode))))
4916 (message "Groups tags support has been turned %s"
4917 (if org-group-tags "on" "off")))
4919 (defun org-set-regexps-and-options (&optional tags-only)
4920 "Precompute regular expressions used in the current buffer.
4921 When optional argument TAGS-ONLY is non-nil, only compute tags
4922 related expressions."
4923 (when (derived-mode-p 'org-mode)
4924 (let ((alist (org--setup-collect-keywords
4925 (org-make-options-regexp
4926 (append '("FILETAGS" "TAGS" "SETUPFILE")
4927 (and (not tags-only)
4928 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4929 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4930 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4931 ;; Startup options. Get this early since it does change
4932 ;; behavior for other options (e.g., tags).
4933 (let ((startup (cdr (assq 'startup alist))))
4934 (dolist (option startup)
4935 (let ((entry (assoc-string option org-startup-options t)))
4936 (when entry
4937 (let ((var (nth 1 entry))
4938 (val (nth 2 entry)))
4939 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4940 (unless (listp (symbol-value var))
4941 (set (make-local-variable var) nil))
4942 (add-to-list var val)))))))
4943 (setq-local org-file-tags
4944 (mapcar #'org-add-prop-inherited
4945 (cdr (assq 'filetags alist))))
4946 (setq org-current-tag-alist
4947 (append org-tag-persistent-alist
4948 (let ((tags (cdr (assq 'tags alist))))
4949 (if tags (org-tag-string-to-alist tags)
4950 org-tag-alist))))
4951 (setq org-tag-groups-alist
4952 (org-tag-alist-to-groups org-current-tag-alist))
4953 (unless tags-only
4954 ;; File properties.
4955 (setq-local org-file-properties (cdr (assq 'property alist)))
4956 ;; Archive location.
4957 (let ((archive (cdr (assq 'archive alist))))
4958 (when archive (setq-local org-archive-location archive)))
4959 ;; Category.
4960 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4961 (when cat
4962 (setq-local org-category (intern cat))
4963 (setq-local org-file-properties
4964 (org--update-property-plist
4965 "CATEGORY" cat org-file-properties))))
4966 ;; Columns.
4967 (let ((column (cdr (assq 'columns alist))))
4968 (when column (setq-local org-columns-default-format column)))
4969 ;; Constants.
4970 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4971 ;; Link abbreviations.
4972 (let ((links (cdr (assq 'link alist))))
4973 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4974 ;; Priorities.
4975 (let ((priorities (cdr (assq 'priorities alist))))
4976 (when priorities
4977 (setq-local org-highest-priority (nth 0 priorities))
4978 (setq-local org-lowest-priority (nth 1 priorities))
4979 (setq-local org-default-priority (nth 2 priorities))))
4980 ;; Scripts.
4981 (let ((scripts (assq 'scripts alist)))
4982 (when scripts
4983 (setq-local org-use-sub-superscripts (cdr scripts))))
4984 ;; TODO keywords.
4985 (setq-local org-todo-kwd-alist nil)
4986 (setq-local org-todo-key-alist nil)
4987 (setq-local org-todo-key-trigger nil)
4988 (setq-local org-todo-keywords-1 nil)
4989 (setq-local org-done-keywords nil)
4990 (setq-local org-todo-heads nil)
4991 (setq-local org-todo-sets nil)
4992 (setq-local org-todo-log-states nil)
4993 (let ((todo-sequences
4994 (or (nreverse (cdr (assq 'todo alist)))
4995 (let ((d (default-value 'org-todo-keywords)))
4996 (if (not (stringp (car d))) d
4997 ;; XXX: Backward compatibility code.
4998 (list (cons org-todo-interpretation d)))))))
4999 (dolist (sequence todo-sequences)
5000 (let* ((sequence (or (run-hook-with-args-until-success
5001 'org-todo-setup-filter-hook sequence)
5002 sequence))
5003 (sequence-type (car sequence))
5004 (keywords (cdr sequence))
5005 (sep (member "|" keywords))
5006 names alist)
5007 (dolist (k (remove "|" keywords))
5008 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5010 (error "Invalid TODO keyword %s" k))
5011 (let ((name (match-string 1 k))
5012 (key (match-string 2 k))
5013 (log (org-extract-log-state-settings k)))
5014 (push name names)
5015 (push (cons name (and key (string-to-char key))) alist)
5016 (when log (push log org-todo-log-states))))
5017 (let* ((names (nreverse names))
5018 (done (if sep (org-remove-keyword-keys (cdr sep))
5019 (last names)))
5020 (head (car names))
5021 (tail (list sequence-type head (car done) (org-last done))))
5022 (add-to-list 'org-todo-heads head 'append)
5023 (push names org-todo-sets)
5024 (setq org-done-keywords (append org-done-keywords done nil))
5025 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5026 (setq org-todo-key-alist
5027 (append org-todo-key-alist
5028 (and alist
5029 (append '((:startgroup))
5030 (nreverse alist)
5031 '((:endgroup))))))
5032 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5033 (setq org-todo-sets (nreverse org-todo-sets)
5034 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5035 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5036 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5037 ;; Compute the regular expressions and other local variables.
5038 ;; Using `org-outline-regexp-bol' would complicate them much,
5039 ;; because of the fixed white space at the end of that string.
5040 (unless org-done-keywords
5041 (setq org-done-keywords
5042 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5043 (setq org-not-done-keywords
5044 (org-delete-all org-done-keywords
5045 (copy-sequence org-todo-keywords-1))
5046 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5047 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5048 org-not-done-heading-regexp
5049 (format org-heading-keyword-regexp-format org-not-done-regexp)
5050 org-todo-line-regexp
5051 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5052 org-complex-heading-regexp
5053 (concat "^\\(\\*+\\)"
5054 "\\(?: +" org-todo-regexp "\\)?"
5055 "\\(?: +\\(\\[#.\\]\\)\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5058 "[ \t]*$")
5059 org-complex-heading-regexp-format
5060 (concat "^\\(\\*+\\)"
5061 "\\(?: +" org-todo-regexp "\\)?"
5062 "\\(?: +\\(\\[#.\\]\\)\\)?"
5063 "\\(?: +"
5064 ;; Stats cookies can be stuck to body.
5065 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5066 "\\(%s\\)"
5067 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5068 "\\)"
5069 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5070 "[ \t]*$")
5071 org-todo-line-tags-regexp
5072 (concat "^\\(\\*+\\)"
5073 "\\(?: +" org-todo-regexp "\\)?"
5074 "\\(?: +\\(.*?\\)\\)??"
5075 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5076 "[ \t]*$"))
5077 (org-compute-latex-and-related-regexp)))))
5079 (defun org--setup-collect-keywords (regexp &optional files alist)
5080 "Return setup keywords values as an alist.
5082 REGEXP matches a subset of setup keywords. FILES is a list of
5083 file names already visited. It is used to avoid circular setup
5084 files. ALIST, when non-nil, is the alist computed so far.
5086 Return value contains the following keys: `archive', `category',
5087 `columns', `constants', `filetags', `link', `priorities',
5088 `property', `scripts', `startup', `tags' and `todo'."
5089 (org-with-wide-buffer
5090 (goto-char (point-min))
5091 (let ((case-fold-search t))
5092 (while (re-search-forward regexp nil t)
5093 (let ((element (org-element-at-point)))
5094 (when (eq (org-element-type element) 'keyword)
5095 (let ((key (org-element-property :key element))
5096 (value (org-element-property :value element)))
5097 (cond
5098 ((equal key "ARCHIVE")
5099 (when (org-string-nw-p value)
5100 (push (cons 'archive value) alist)))
5101 ((equal key "CATEGORY") (push (cons 'category value) alist))
5102 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5103 ((equal key "CONSTANTS")
5104 (let* ((constants (assq 'constants alist))
5105 (store (cdr constants)))
5106 (dolist (pair (org-split-string value))
5107 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5108 pair)
5109 (let* ((name (match-string 1 pair))
5110 (value (match-string 2 pair))
5111 (old (assoc name store)))
5112 (if old (setcdr old value)
5113 (push (cons name value) store)))))
5114 (if constants (setcdr constants store)
5115 (push (cons 'constants store) alist))))
5116 ((equal key "FILETAGS")
5117 (when (org-string-nw-p value)
5118 (let ((old (assq 'filetags alist))
5119 (new (apply #'nconc
5120 (mapcar (lambda (x) (org-split-string x ":"))
5121 (org-split-string value)))))
5122 (if old (setcdr old (append new (cdr old)))
5123 (push (cons 'filetags new) alist)))))
5124 ((equal key "LINK")
5125 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5126 (let ((links (assq 'link alist))
5127 (pair (cons (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value))))
5129 (if links (push pair (cdr links))
5130 (push (list 'link pair) alist)))))
5131 ((equal key "OPTIONS")
5132 (when (and (org-string-nw-p value)
5133 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5134 (push (cons 'scripts (read (match-string 1 value))) alist)))
5135 ((equal key "PRIORITIES")
5136 (push (cons 'priorities
5137 (let ((prio (org-split-string value)))
5138 (if (< (length prio) 3) '(?A ?C ?B)
5139 (mapcar #'string-to-char prio))))
5140 alist))
5141 ((equal key "PROPERTY")
5142 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5143 (let* ((property (assq 'property alist))
5144 (value (org--update-property-plist
5145 (match-string-no-properties 1 value)
5146 (match-string-no-properties 2 value)
5147 (cdr property))))
5148 (if property (setcdr property value)
5149 (push (cons 'property value) alist)))))
5150 ((equal key "STARTUP")
5151 (let ((startup (assq 'startup alist)))
5152 (if startup
5153 (setcdr startup
5154 (append (cdr startup) (org-split-string value)))
5155 (push (cons 'startup (org-split-string value)) alist))))
5156 ((equal key "TAGS")
5157 (let ((tag-cell (assq 'tags alist)))
5158 (if tag-cell
5159 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5160 (push (cons 'tags value) alist))))
5161 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5162 (let ((todo (assq 'todo alist))
5163 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5164 (org-split-string value))))
5165 (if todo (push value (cdr todo))
5166 (push (list 'todo value) alist))))
5167 ((equal key "SETUPFILE")
5168 (unless buffer-read-only ; Do not check in Gnus messages.
5169 (let ((f (and (org-string-nw-p value)
5170 (expand-file-name
5171 (org-unbracket-string "\"" "\"" value)))))
5172 (when (and f (file-readable-p f) (not (member f files)))
5173 (with-temp-buffer
5174 (setq default-directory (file-name-directory f))
5175 (insert-file-contents f)
5176 (setq alist
5177 ;; Fake Org mode to benefit from cache
5178 ;; without recurring needlessly.
5179 (let ((major-mode 'org-mode))
5180 (org--setup-collect-keywords
5181 regexp (cons f files) alist)))))))))))))))
5182 alist)
5184 (defun org-tag-string-to-alist (s)
5185 "Return tag alist associated to string S.
5186 S is a value for TAGS keyword or produced with
5187 `org-tag-alist-to-string'. Return value is an alist suitable for
5188 `org-tag-alist' or `org-tag-persistent-alist'."
5189 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5190 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5191 "\\|{.+?}\\)" ; regular expression
5192 "\\(?:(\\(.\\))\\)?\\'"))
5193 alist group-flag)
5194 (dolist (tokens lines (cdr (nreverse alist)))
5195 (push '(:newline) alist)
5196 (while tokens
5197 (let ((token (pop tokens)))
5198 (pcase token
5199 ("{"
5200 (push '(:startgroup) alist)
5201 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5202 ("}"
5203 (push '(:endgroup) alist)
5204 (setq group-flag nil))
5205 ("["
5206 (push '(:startgrouptag) alist)
5207 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5208 ("]"
5209 (push '(:endgrouptag) alist)
5210 (setq group-flag nil))
5211 (":"
5212 (push '(:grouptags) alist))
5213 ((guard (string-match tag-re token))
5214 (let ((tag (match-string 1 token))
5215 (key (and (match-beginning 2)
5216 (string-to-char (match-string 2 token)))))
5217 ;; Push all tags in groups, no matter if they already
5218 ;; appear somewhere else in the list.
5219 (when (or group-flag (not (assoc tag alist)))
5220 (push (cons tag key) alist))))))))))
5222 (defun org-tag-alist-to-string (alist &optional skip-key)
5223 "Return tag string associated to ALIST.
5225 ALIST is an alist, as defined in `org-tag-alist' or
5226 `org-tag-persistent-alist', or produced with
5227 `org-tag-string-to-alist'.
5229 Return value is a string suitable as a value for \"TAGS\"
5230 keyword.
5232 When optional argument SKIP-KEY is non-nil, skip selection keys
5233 next to tags."
5234 (mapconcat (lambda (token)
5235 (pcase token
5236 (`(:startgroup) "{")
5237 (`(:endgroup) "}")
5238 (`(:startgrouptag) "[")
5239 (`(:endgrouptag) "]")
5240 (`(:grouptags) ":")
5241 (`(:newline) "\\n")
5242 ((and
5243 (guard (not skip-key))
5244 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5245 (format "%s(%c)" tag key))
5246 (`(,(and tag (pred stringp)) . ,_) tag)
5247 (_ (user-error "Invalid tag token: %S" token))))
5248 alist
5249 " "))
5251 (defun org-tag-alist-to-groups (alist)
5252 "Return group alist from tag ALIST.
5253 ALIST is an alist, as defined in `org-tag-alist' or
5254 `org-tag-persistent-alist', or produced with
5255 `org-tag-string-to-alist'. Return value is an alist following
5256 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5257 a string, summarizing TAGS, as a list of strings."
5258 (let (groups group-status current-group)
5259 (dolist (token alist (nreverse groups))
5260 (pcase token
5261 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5262 (`(,(or :endgroup :endgrouptag))
5263 (when (eq group-status 'append)
5264 (push (nreverse current-group) groups))
5265 (setq group-status nil))
5266 (`(:grouptags) (setq group-status 'append))
5267 ((and `(,tag . ,_) (guard group-status))
5268 (if (eq group-status 'append) (push tag current-group)
5269 (setq current-group (list tag))))
5270 (_ nil)))))
5272 (defun org-file-contents (file &optional noerror)
5273 "Return the contents of FILE, as a string."
5274 (if (and file (file-readable-p file))
5275 (with-temp-buffer
5276 (insert-file-contents file)
5277 (buffer-string))
5278 (funcall (if noerror 'message 'error)
5279 "Cannot read file \"%s\"%s"
5280 file
5281 (let ((from (buffer-file-name (buffer-base-buffer))))
5282 (if from (concat " (referenced in file \"" from "\")") "")))))
5284 (defun org-extract-log-state-settings (x)
5285 "Extract the log state setting from a TODO keyword string.
5286 This will extract info from a string like \"WAIT(w@/!)\"."
5287 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5288 (let ((kw (match-string 1 x))
5289 (log1 (and (match-end 3) (match-string 3 x)))
5290 (log2 (and (match-end 4) (match-string 4 x))))
5291 (and (or log1 log2)
5292 (list kw
5293 (and log1 (if (equal log1 "!") 'time 'note))
5294 (and log2 (if (equal log2 "!") 'time 'note)))))))
5296 (defun org-remove-keyword-keys (list)
5297 "Remove a pair of parenthesis at the end of each string in LIST."
5298 (mapcar (lambda (x)
5299 (if (string-match "(.*)$" x)
5300 (substring x 0 (match-beginning 0))
5302 list))
5304 (defun org-assign-fast-keys (alist)
5305 "Assign fast keys to a keyword-key alist.
5306 Respect keys that are already there."
5307 (let (new e (alt ?0))
5308 (while (setq e (pop alist))
5309 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5310 (cdr e)) ;; Key already assigned.
5311 (push e new)
5312 (let ((clist (string-to-list (downcase (car e))))
5313 (used (append new alist)))
5314 (when (= (car clist) ?@)
5315 (pop clist))
5316 (while (and clist (rassoc (car clist) used))
5317 (pop clist))
5318 (unless clist
5319 (while (rassoc alt used)
5320 (cl-incf alt)))
5321 (push (cons (car e) (or (car clist) alt)) new))))
5322 (nreverse new)))
5324 ;;; Some variables used in various places
5326 (defvar org-window-configuration nil
5327 "Used in various places to store a window configuration.")
5328 (defvar org-selected-window nil
5329 "Used in various places to store a window configuration.")
5330 (defvar org-finish-function nil
5331 "Function to be called when `C-c C-c' is used.
5332 This is for getting out of special buffers like capture.")
5333 (defvar org-last-state)
5335 ;; Defined somewhere in this file, but used before definition.
5336 (defvar org-entities) ;; defined in org-entities.el
5337 (defvar org-struct-menu)
5338 (defvar org-org-menu)
5339 (defvar org-tbl-menu)
5341 ;;;; Define the Org mode
5343 ;; We use a before-change function to check if a table might need
5344 ;; an update.
5345 (defvar org-table-may-need-update t
5346 "Indicates that a table might need an update.
5347 This variable is set by `org-before-change-function'.
5348 `org-table-align' sets it back to nil.")
5349 (defun org-before-change-function (_beg _end)
5350 "Every change indicates that a table might need an update."
5351 (setq org-table-may-need-update t))
5352 (defvar org-mode-map)
5353 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5354 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5355 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5357 (defvar org-table-buffer-is-an nil)
5359 (defvar bidi-paragraph-direction)
5360 (defvar buffer-face-mode-face)
5362 (require 'outline)
5364 ;; Other stuff we need.
5365 (require 'time-date)
5366 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5367 (require 'easymenu)
5368 (autoload 'easy-menu-add "easymenu")
5369 (require 'overlay)
5371 ;; (require 'org-macs) moved higher up in the file before it is first used
5372 (require 'org-entities)
5373 ;; (require 'org-compat) moved higher up in the file before it is first used
5374 (require 'org-faces)
5375 (require 'org-list)
5376 (require 'org-pcomplete)
5377 (require 'org-src)
5378 (require 'org-footnote)
5379 (require 'org-macro)
5381 ;; babel
5382 (require 'ob)
5384 ;;;###autoload
5385 (define-derived-mode org-mode outline-mode "Org"
5386 "Outline-based notes management and organizer, alias
5387 \"Carsten's outline-mode for keeping track of everything.\"
5389 Org mode develops organizational tasks around a NOTES file which
5390 contains information about projects as plain text. Org mode is
5391 implemented on top of Outline mode, which is ideal to keep the content
5392 of large files well structured. It supports ToDo items, deadlines and
5393 time stamps, which magically appear in the diary listing of the Emacs
5394 calendar. Tables are easily created with a built-in table editor.
5395 Plain text URL-like links connect to websites, emails (VM), Usenet
5396 messages (Gnus), BBDB entries, and any files related to the project.
5397 For printing and sharing of notes, an Org file (or a part of it)
5398 can be exported as a structured ASCII or HTML file.
5400 The following commands are available:
5402 \\{org-mode-map}"
5404 ;; Get rid of Outline menus, they are not needed
5405 ;; Need to do this here because define-derived-mode sets up
5406 ;; the keymap so late. Still, it is a waste to call this each time
5407 ;; we switch another buffer into Org mode.
5408 (define-key org-mode-map [menu-bar headings] 'undefined)
5409 (define-key org-mode-map [menu-bar hide] 'undefined)
5410 (define-key org-mode-map [menu-bar show] 'undefined)
5412 (org-load-modules-maybe)
5413 (org-install-agenda-files-menu)
5414 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5415 (add-to-invisibility-spec '(org-cwidth))
5416 (add-to-invisibility-spec '(org-hide-block . t))
5417 (setq-local outline-regexp org-outline-regexp)
5418 (setq-local outline-level 'org-outline-level)
5419 (setq bidi-paragraph-direction 'left-to-right)
5420 (when (and org-ellipsis
5421 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5422 (fboundp 'make-glyph-code))
5423 (unless org-display-table
5424 (setq org-display-table (make-display-table)))
5425 (set-display-table-slot
5426 org-display-table 4
5427 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5428 (if (stringp org-ellipsis) org-ellipsis "..."))))
5429 (setq buffer-display-table org-display-table))
5430 (org-set-regexps-and-options)
5431 (org-set-font-lock-defaults)
5432 (when (and org-tag-faces (not org-tags-special-faces-re))
5433 ;; tag faces set outside customize.... force initialization.
5434 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5435 ;; Calc embedded
5436 (setq-local calc-embedded-open-mode "# ")
5437 ;; Modify a few syntax entries
5438 (modify-syntax-entry ?@ "w")
5439 (modify-syntax-entry ?\" "\"")
5440 (modify-syntax-entry ?\\ "_")
5441 (modify-syntax-entry ?~ "_")
5442 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5443 ;; Activate before-change-function
5444 (setq-local org-table-may-need-update t)
5445 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5446 ;; Check for running clock before killing a buffer
5447 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5448 ;; Initialize macros templates.
5449 (org-macro-initialize-templates)
5450 ;; Initialize radio targets.
5451 (org-update-radio-target-regexp)
5452 ;; Indentation.
5453 (setq-local indent-line-function 'org-indent-line)
5454 (setq-local indent-region-function 'org-indent-region)
5455 ;; Filling and auto-filling.
5456 (org-setup-filling)
5457 ;; Comments.
5458 (org-setup-comments-handling)
5459 ;; Initialize cache.
5460 (org-element-cache-reset)
5461 ;; Beginning/end of defun
5462 (setq-local beginning-of-defun-function 'org-backward-element)
5463 (setq-local end-of-defun-function
5464 (lambda ()
5465 (if (not (org-at-heading-p))
5466 (org-forward-element)
5467 (org-forward-element)
5468 (forward-char -1))))
5469 ;; Next error for sparse trees
5470 (setq-local next-error-function 'org-occur-next-match)
5471 ;; Make sure dependence stuff works reliably, even for users who set it
5472 ;; too late :-(
5473 (if org-enforce-todo-dependencies
5474 (add-hook 'org-blocker-hook
5475 'org-block-todo-from-children-or-siblings-or-parent)
5476 (remove-hook 'org-blocker-hook
5477 'org-block-todo-from-children-or-siblings-or-parent))
5478 (if org-enforce-todo-checkbox-dependencies
5479 (add-hook 'org-blocker-hook
5480 'org-block-todo-from-checkboxes)
5481 (remove-hook 'org-blocker-hook
5482 'org-block-todo-from-checkboxes))
5484 ;; Align options lines
5485 (setq-local
5486 align-mode-rules-list
5487 '((org-in-buffer-settings
5488 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5489 (modes . '(org-mode)))))
5491 ;; Imenu
5492 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5494 ;; Make isearch reveal context
5495 (setq-local outline-isearch-open-invisible-function
5496 (lambda (&rest _) (org-show-context 'isearch)))
5498 ;; Setup the pcomplete hooks
5499 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5500 (setq-local pcomplete-command-name-function 'org-command-at-point)
5501 (setq-local pcomplete-default-completion-function 'ignore)
5502 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5503 (setq-local pcomplete-termination-string "")
5504 (setq-local buffer-face-mode-face 'org-default)
5506 ;; If empty file that did not turn on Org mode automatically, make
5507 ;; it to.
5508 (when (and org-insert-mode-line-in-empty-file
5509 (called-interactively-p 'any)
5510 (= (point-min) (point-max)))
5511 (insert "# -*- mode: org -*-\n\n"))
5512 (unless org-inhibit-startup
5513 (org-unmodified
5514 (when org-startup-with-beamer-mode (org-beamer-mode))
5515 (when org-startup-align-all-tables
5516 (org-table-map-tables #'org-table-align t))
5517 (when org-startup-with-inline-images (org-display-inline-images))
5518 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5519 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5520 (when org-startup-truncated (setq truncate-lines t))
5521 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5522 (org-refresh-effort-properties)))
5523 ;; Try to set `org-hide' face correctly.
5524 (let ((foreground (org-find-invisible-foreground)))
5525 (when foreground
5526 (set-face-foreground 'org-hide foreground))))
5528 ;; Update `customize-package-emacs-version-alist'
5529 (add-to-list 'customize-package-emacs-version-alist
5530 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5531 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5532 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5533 ("9.0" . "26.1")))
5535 (defvar org-mode-transpose-word-syntax-table
5536 (let ((st (make-syntax-table text-mode-syntax-table)))
5537 (dolist (c org-emphasis-alist st)
5538 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5540 (when (fboundp 'abbrev-table-put)
5541 (abbrev-table-put org-mode-abbrev-table
5542 :parents (list text-mode-abbrev-table)))
5544 (defun org-find-invisible-foreground ()
5545 (let ((candidates (remove
5546 "unspecified-bg"
5547 (nconc
5548 (list (face-background 'default)
5549 (face-background 'org-default))
5550 (mapcar
5551 (lambda (alist)
5552 (when (boundp alist)
5553 (cdr (assq 'background-color (symbol-value alist)))))
5554 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5555 (list (face-foreground 'org-hide))))))
5556 (car (remove nil candidates))))
5558 (defun org-current-time (&optional rounding-minutes past)
5559 "Current time, possibly rounded to ROUNDING-MINUTES.
5560 When ROUNDING-MINUTES is not an integer, fall back on the car of
5561 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5562 the rounding returns a past time."
5563 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5564 (car org-time-stamp-rounding-minutes)))
5565 (time (decode-time)) res)
5566 (if (< r 1)
5567 (current-time)
5568 (setq res
5569 (apply 'encode-time
5570 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5571 (nthcdr 2 time))))
5572 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5573 (seconds-to-time (- (float-time res) (* r 60)))
5574 res))))
5576 (defun org-today ()
5577 "Return today date, considering `org-extend-today-until'."
5578 (time-to-days
5579 (time-subtract (current-time)
5580 (list 0 (* 3600 org-extend-today-until) 0))))
5582 ;;;; Font-Lock stuff, including the activators
5584 (defvar org-mouse-map (make-sparse-keymap))
5585 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5586 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5587 (when org-mouse-1-follows-link
5588 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5589 (when org-tab-follows-link
5590 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5591 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5593 (require 'font-lock)
5595 (defconst org-non-link-chars "]\t\n\r<>")
5596 (defvar org-link-types-re nil
5597 "Matches a link that has a url-like prefix like \"http:\"")
5598 (defvar org-link-re-with-space nil
5599 "Matches a link with spaces, optional angular brackets around it.")
5600 (defvar org-link-re-with-space2 nil
5601 "Matches a link with spaces, optional angular brackets around it.")
5602 (defvar org-link-re-with-space3 nil
5603 "Matches a link with spaces, only for internal part in bracket links.")
5604 (defvar org-angle-link-re nil
5605 "Matches link with angular brackets, spaces are allowed.")
5606 (defvar org-plain-link-re nil
5607 "Matches plain link, without spaces.")
5608 (defvar org-bracket-link-regexp nil
5609 "Matches a link in double brackets.")
5610 (defvar org-bracket-link-analytic-regexp nil
5611 "Regular expression used to analyze links.
5612 Here is what the match groups contain after a match:
5613 1: http:
5614 2: http
5615 3: path
5616 4: [desc]
5617 5: desc")
5618 (defvar org-bracket-link-analytic-regexp++ nil
5619 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5620 (defvar org-any-link-re nil
5621 "Regular expression matching any link.")
5623 (defconst org-match-sexp-depth 3
5624 "Number of stacked braces for sub/superscript matching.")
5626 (defun org-create-multibrace-regexp (left right n)
5627 "Create a regular expression which will match a balanced sexp.
5628 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5629 as single character strings.
5630 The regexp returned will match the entire expression including the
5631 delimiters. It will also define a single group which contains the
5632 match except for the outermost delimiters. The maximum depth of
5633 stacked delimiters is N. Escaping delimiters is not possible."
5634 (let* ((nothing (concat "[^" left right "]*?"))
5635 (or "\\|")
5636 (re nothing)
5637 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5638 (while (> n 1)
5639 (setq n (1- n)
5640 re (concat re or next)
5641 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5642 (concat left "\\(" re "\\)" right)))
5644 (defconst org-match-substring-regexp
5645 (concat
5646 "\\(\\S-\\)\\([_^]\\)\\("
5647 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5648 "\\|"
5649 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5650 "\\|"
5651 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5652 "The regular expression matching a sub- or superscript.")
5654 (defconst org-match-substring-with-braces-regexp
5655 (concat
5656 "\\(\\S-\\)\\([_^]\\)"
5657 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5658 "The regular expression matching a sub- or superscript, forcing braces.")
5660 (defun org-make-link-regexps ()
5661 "Update the link regular expressions.
5662 This should be called after the variable `org-link-parameters' has changed."
5663 (let ((types-re (regexp-opt (org-link-types) t)))
5664 (setq org-link-types-re
5665 (concat "\\`" types-re ":")
5666 org-link-re-with-space
5667 (concat "<?" types-re ":"
5668 "\\([^" org-non-link-chars " ]"
5669 "[^" org-non-link-chars "]*"
5670 "[^" org-non-link-chars " ]\\)>?")
5671 org-link-re-with-space2
5672 (concat "<?" types-re ":"
5673 "\\([^" org-non-link-chars " ]"
5674 "[^\t\n\r]*"
5675 "[^" org-non-link-chars " ]\\)>?")
5676 org-link-re-with-space3
5677 (concat "<?" types-re ":"
5678 "\\([^" org-non-link-chars " ]"
5679 "[^\t\n\r]*\\)")
5680 org-angle-link-re
5681 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5682 types-re)
5683 org-plain-link-re
5684 (concat
5685 "\\<" types-re ":"
5686 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5687 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5688 org-bracket-link-regexp
5689 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5690 org-bracket-link-analytic-regexp
5691 (concat
5692 "\\[\\["
5693 "\\(" types-re ":\\)?"
5694 "\\([^]]+\\)"
5695 "\\]"
5696 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5697 "\\]")
5698 org-bracket-link-analytic-regexp++
5699 (concat
5700 "\\[\\["
5701 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5702 "\\([^]]+\\)"
5703 "\\]"
5704 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5705 "\\]")
5706 org-any-link-re
5707 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5708 org-angle-link-re "\\)\\|\\("
5709 org-plain-link-re "\\)"))))
5711 (org-make-link-regexps)
5713 (defvar org-emph-face nil)
5715 (defun org-do-emphasis-faces (limit)
5716 "Run through the buffer and emphasize strings."
5717 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5718 (car org-emphasis-regexp-components))))
5719 (catch :exit
5720 (while (re-search-forward quick-re limit t)
5721 (let* ((marker (match-string 2))
5722 (verbatim? (member marker '("~" "="))))
5723 (when (save-excursion
5724 (goto-char (match-beginning 0))
5725 ;; Do not match headline stars. Do not consider
5726 ;; stars of a headline as closing marker for bold
5727 ;; markup either.
5728 (and (not (looking-at-p org-outline-regexp-bol))
5729 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5730 (not (string-match-p
5731 (concat org-outline-regexp-bol "\\'")
5732 (match-string 0)))))
5733 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5734 (font-lock-prepend-text-property
5735 (match-beginning 2) (match-end 2) 'face face)
5736 (when verbatim?
5737 (org-remove-flyspell-overlays-in
5738 (match-beginning 0) (match-end 0)))
5739 (add-text-properties (match-beginning 2) (match-end 2)
5740 '(font-lock-multiline t org-emphasis t))
5741 (when org-hide-emphasis-markers
5742 (add-text-properties (match-end 4) (match-beginning 5)
5743 '(invisible org-link))
5744 (add-text-properties (match-beginning 3) (match-end 3)
5745 '(invisible org-link)))
5746 (throw :exit t))))))))
5748 (defun org-emphasize (&optional char)
5749 "Insert or change an emphasis, i.e. a font like bold or italic.
5750 If there is an active region, change that region to a new emphasis.
5751 If there is no region, just insert the marker characters and position
5752 the cursor between them.
5753 CHAR should be the marker character. If it is a space, it means to
5754 remove the emphasis of the selected region.
5755 If CHAR is not given (for example in an interactive call) it will be
5756 prompted for."
5757 (interactive)
5758 (let ((erc org-emphasis-regexp-components)
5759 (string "") beg end move s)
5760 (if (org-region-active-p)
5761 (setq beg (region-beginning)
5762 end (region-end)
5763 string (buffer-substring beg end))
5764 (setq move t))
5766 (unless char
5767 (message "Emphasis marker or tag: [%s]"
5768 (mapconcat #'car org-emphasis-alist ""))
5769 (setq char (read-char-exclusive)))
5770 (if (equal char ?\s)
5771 (setq s ""
5772 move nil)
5773 (unless (assoc (char-to-string char) org-emphasis-alist)
5774 (user-error "No such emphasis marker: \"%c\"" char))
5775 (setq s (char-to-string char)))
5776 (while (and (> (length string) 1)
5777 (equal (substring string 0 1) (substring string -1))
5778 (assoc (substring string 0 1) org-emphasis-alist))
5779 (setq string (substring string 1 -1)))
5780 (setq string (concat s string s))
5781 (when beg (delete-region beg end))
5782 (unless (or (bolp)
5783 (string-match (concat "[" (nth 0 erc) "\n]")
5784 (char-to-string (char-before (point)))))
5785 (insert " "))
5786 (unless (or (eobp)
5787 (string-match (concat "[" (nth 1 erc) "\n]")
5788 (char-to-string (char-after (point)))))
5789 (insert " ") (backward-char 1))
5790 (insert string)
5791 (and move (backward-char 1))))
5793 (defconst org-nonsticky-props
5794 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5796 (defsubst org-rear-nonsticky-at (pos)
5797 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5799 (defun org-activate-plain-links (limit)
5800 "Add link properties for plain links."
5801 (when (and (re-search-forward org-plain-link-re limit t)
5802 (not (org-in-src-block-p)))
5804 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5805 'face))
5806 (link (match-string-no-properties 0))
5807 (type (match-string-no-properties 1))
5808 (path (match-string-no-properties 2))
5809 (link-start (match-beginning 0))
5810 (link-end (match-end 0))
5811 (link-face (org-link-get-parameter type :face))
5812 (help-echo (org-link-get-parameter type :help-echo))
5813 (htmlize-link (org-link-get-parameter type :htmlize-link))
5814 (activate-func (org-link-get-parameter type :activate-func)))
5815 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (add-text-properties (match-beginning 0) (match-end 0)
5818 (list
5819 'mouse-face (or (org-link-get-parameter type :mouse-face)
5820 'highlight)
5821 'face (cond
5822 ;; A function that returns a face
5823 ((functionp link-face)
5824 (funcall link-face path))
5825 ;; a face
5826 ((facep link-face)
5827 link-face)
5828 ;; An anonymous face
5829 ((consp link-face)
5830 link-face)
5831 ;; default
5833 'org-link))
5834 'help-echo (cond
5835 ((stringp help-echo)
5836 help-echo)
5837 ((functionp help-echo)
5838 help-echo)
5840 (concat "LINK: "
5841 (save-match-data
5842 (org-link-unescape link)))))
5843 'htmlize-link (cond
5844 ((functionp htmlize-link)
5845 (funcall htmlize-link path))
5847 `(:uri ,link)))
5848 'keymap (or (org-link-get-parameter type :keymap)
5849 org-mouse-map)
5850 'org-link-start (match-beginning 0)))
5851 (org-rear-nonsticky-at (match-end 0))
5852 (when activate-func
5853 (funcall activate-func link-start link-end path nil))
5854 t))))
5856 (defun org-activate-code (limit)
5857 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5858 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5859 (remove-text-properties (match-beginning 0) (match-end 0)
5860 '(display t invisible t intangible t))
5863 (defcustom org-src-fontify-natively t
5864 "When non-nil, fontify code in code blocks.
5865 See also the `org-block' face."
5866 :type 'boolean
5867 :version "24.4"
5868 :package-version '(Org . "8.3")
5869 :group 'org-appearance
5870 :group 'org-babel)
5872 (defcustom org-allow-promoting-top-level-subtree nil
5873 "When non-nil, allow promoting a top level subtree.
5874 The leading star of the top level headline will be replaced
5875 by a #."
5876 :type 'boolean
5877 :version "24.1"
5878 :group 'org-appearance)
5880 (defun org-fontify-meta-lines-and-blocks (limit)
5881 (condition-case nil
5882 (org-fontify-meta-lines-and-blocks-1 limit)
5883 (error (message "org-mode fontification error in %S at %d"
5884 (current-buffer)
5885 (line-number-at-pos)))))
5887 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5888 "Fontify #+ lines and blocks."
5889 (let ((case-fold-search t))
5890 (when (re-search-forward
5891 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5892 limit t)
5893 (let ((beg (match-beginning 0))
5894 (block-start (match-end 0))
5895 (block-end nil)
5896 (lang (match-string 7))
5897 (beg1 (line-beginning-position 2))
5898 (dc1 (downcase (match-string 2)))
5899 (dc3 (downcase (match-string 3)))
5900 end end1 quoting block-type)
5901 (cond
5902 ((and (match-end 4) (equal dc3 "+begin"))
5903 ;; Truly a block
5904 (setq block-type (downcase (match-string 5))
5905 quoting (member block-type org-protecting-blocks))
5906 (when (re-search-forward
5907 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5908 nil t) ;; on purpose, we look further than LIMIT
5909 (setq end (min (point-max) (match-end 0))
5910 end1 (min (point-max) (1- (match-beginning 0))))
5911 (setq block-end (match-beginning 0))
5912 (when quoting
5913 (org-remove-flyspell-overlays-in beg1 end1)
5914 (remove-text-properties beg end
5915 '(display t invisible t intangible t)))
5916 (add-text-properties
5917 beg end '(font-lock-fontified t font-lock-multiline t))
5918 (add-text-properties beg beg1 '(face org-meta-line))
5919 (org-remove-flyspell-overlays-in beg beg1)
5920 (add-text-properties ; For end_src
5921 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5922 (org-remove-flyspell-overlays-in end1 end)
5923 (cond
5924 ((and lang (not (string= lang "")) org-src-fontify-natively)
5925 (org-src-font-lock-fontify-block lang block-start block-end)
5926 (add-text-properties beg1 block-end '(src-block t)))
5927 (quoting
5928 (add-text-properties beg1 (min (point-max) (1+ end1))
5929 (list 'face
5930 (list :inherit
5931 (let ((face-name
5932 (intern (format "org-block-%s" lang))))
5933 (append (and (facep face-name) (list face-name))
5934 '(org-block))))))) ; end of source block
5935 ((not org-fontify-quote-and-verse-blocks))
5936 ((string= block-type "quote")
5937 (add-face-text-property
5938 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5939 ((string= block-type "verse")
5940 (add-face-text-property
5941 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5942 (add-text-properties beg beg1 '(face org-block-begin-line))
5943 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5944 '(face org-block-end-line))
5946 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5947 (org-remove-flyspell-overlays-in
5948 (match-beginning 0)
5949 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5950 (add-text-properties
5951 beg (match-end 3)
5952 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5953 '(font-lock-fontified t invisible t)
5954 '(font-lock-fontified t face org-document-info-keyword)))
5955 (add-text-properties
5956 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5957 (if (string-equal dc1 "+title:")
5958 '(font-lock-fontified t face org-document-title)
5959 '(font-lock-fontified t face org-document-info))))
5960 ((string-prefix-p "+caption" dc1)
5961 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(display t invisible t intangible t))
5964 ;; Handle short captions.
5965 (save-excursion
5966 (beginning-of-line)
5967 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5968 (add-text-properties (line-beginning-position) (match-end 1)
5969 '(font-lock-fontified t face org-meta-line))
5970 (add-text-properties (match-end 0) (line-end-position)
5971 '(font-lock-fontified t face org-block))
5973 ((member dc3 '(" " ""))
5974 (org-remove-flyspell-overlays-in beg (match-end 0))
5975 (add-text-properties
5976 beg (match-end 0)
5977 '(font-lock-fontified t face font-lock-comment-face)))
5978 (t ;; just any other in-buffer setting, but not indented
5979 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5980 (remove-text-properties (match-beginning 0) (match-end 0)
5981 '(display t invisible t intangible t))
5982 (add-text-properties beg (match-end 0)
5983 '(font-lock-fontified t face org-meta-line))
5984 t))))))
5986 (defun org-fontify-drawers (limit)
5987 "Fontify drawers."
5988 (when (re-search-forward org-drawer-regexp limit t)
5989 (add-text-properties
5990 (match-beginning 0) (match-end 0)
5991 '(font-lock-fontified t face org-special-keyword))
5992 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (defun org-fontify-macros (limit)
5996 "Fontify macros."
5997 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5998 (add-text-properties
5999 (match-beginning 0) (match-end 0)
6000 '(font-lock-fontified t face org-macro))
6001 (when org-hide-macro-markers
6002 (add-text-properties (match-end 2) (match-beginning 2)
6003 '(invisible t))
6004 (add-text-properties (match-beginning 1) (match-end 1)
6005 '(invisible t)))
6006 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6009 (defun org-activate-angle-links (limit)
6010 "Add text properties for angle links."
6011 (when (and (re-search-forward org-angle-link-re limit t)
6012 (not (org-in-src-block-p)))
6013 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6014 (add-text-properties (match-beginning 0) (match-end 0)
6015 (list 'mouse-face 'highlight
6016 'keymap org-mouse-map
6017 'font-lock-multiline t))
6018 (org-rear-nonsticky-at (match-end 0))
6021 (defun org-activate-footnote-links (limit)
6022 "Add text properties for footnotes."
6023 (let ((fn (org-footnote-next-reference-or-definition limit)))
6024 (when fn
6025 (let* ((beg (nth 1 fn))
6026 (end (nth 2 fn))
6027 (label (car fn))
6028 (referencep (/= (line-beginning-position) beg)))
6029 (when (and referencep (nth 3 fn))
6030 (save-excursion
6031 (goto-char beg)
6032 (search-forward (or label "fn:"))
6033 (org-remove-flyspell-overlays-in beg (match-end 0))))
6034 (add-text-properties beg end
6035 (list 'mouse-face 'highlight
6036 'keymap org-mouse-map
6037 'help-echo
6038 (if referencep "Footnote reference"
6039 "Footnote definition")
6040 'font-lock-fontified t
6041 'font-lock-multiline t
6042 'face 'org-footnote))))))
6044 (defun org-activate-bracket-links (limit)
6045 "Add text properties for bracketed links."
6046 (when (and (re-search-forward org-bracket-link-regexp limit t)
6047 (not (org-in-src-block-p)))
6048 (let* ((hl (save-match-data
6049 (org-link-expand-abbrev (match-string-no-properties 1))))
6050 (type (save-match-data
6051 (and (string-match org-plain-link-re hl)
6052 (match-string-no-properties 1 hl))))
6053 (path (save-match-data
6054 (and (string-match org-plain-link-re hl)
6055 (match-string-no-properties 2 hl))))
6056 (link-start (match-beginning 0))
6057 (link-end (match-end 0))
6058 (bracketp t)
6059 (help-echo (org-link-get-parameter type :help-echo))
6060 (help (cond
6061 ((stringp help-echo)
6062 help-echo)
6063 ((functionp help-echo)
6064 help-echo)
6066 (concat "LINK: "
6067 (save-match-data
6068 (org-link-unescape hl))))))
6069 (link-face (org-link-get-parameter type :face))
6070 (face (cond
6071 ;; A function that returns a face
6072 ((functionp link-face)
6073 (funcall link-face path))
6074 ;; a face
6075 ((facep link-face)
6076 link-face)
6077 ;; An anonymous face
6078 ((consp link-face)
6079 link-face)
6080 ;; default
6082 'org-link)))
6083 (keymap (or (org-link-get-parameter type :keymap)
6084 org-mouse-map))
6085 (mouse-face (or (org-link-get-parameter type :mouse-face)
6086 'highlight))
6087 (htmlize (org-link-get-parameter type :htmlize-link))
6088 (htmlize-link (cond
6089 ((functionp htmlize)
6090 (funcall htmlize))
6092 `(:uri ,(format "%s:%s" type path)))))
6093 (activate-func (org-link-get-parameter type :activate-func))
6094 ;; invisible part
6095 (ip (list 'invisible (or
6096 (org-link-get-parameter type :display)
6097 'org-link)
6098 'face face
6099 'keymap keymap
6100 'mouse-face mouse-face
6101 'font-lock-multiline t
6102 'help-echo help
6103 'htmlize-link htmlize-link))
6104 ;; visible part
6105 (vp (list 'keymap keymap
6106 'face face
6107 'mouse-face mouse-face
6108 'font-lock-multiline t
6109 'help-echo help
6110 'htmlize-link htmlize-link)))
6111 ;; We need to remove the invisible property here. Table narrowing
6112 ;; may have made some of this invisible.
6113 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6114 (remove-text-properties (match-beginning 0) (match-end 0)
6115 '(invisible nil))
6116 (if (match-end 3)
6117 (progn
6118 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6119 (org-rear-nonsticky-at (match-beginning 3))
6120 (add-text-properties (match-beginning 3) (match-end 3) vp)
6121 (org-rear-nonsticky-at (match-end 3))
6122 (add-text-properties (match-end 3) (match-end 0) ip)
6123 (org-rear-nonsticky-at (match-end 0)))
6124 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6125 (org-rear-nonsticky-at (match-beginning 1))
6126 (add-text-properties (match-beginning 1) (match-end 1) vp)
6127 (org-rear-nonsticky-at (match-end 1))
6128 (add-text-properties (match-end 1) (match-end 0) ip)
6129 (org-rear-nonsticky-at (match-end 0)))
6130 (when activate-func
6131 (funcall activate-func link-start link-end path bracketp))
6132 t)))
6134 (defun org-activate-dates (limit)
6135 "Add text properties for dates."
6136 (when (and (re-search-forward org-tsr-regexp-both limit t)
6137 (not (equal (char-before (match-beginning 0)) 91)))
6138 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6139 (add-text-properties (match-beginning 0) (match-end 0)
6140 (list 'mouse-face 'highlight
6141 'keymap org-mouse-map))
6142 (org-rear-nonsticky-at (match-end 0))
6143 (when org-display-custom-times
6144 (if (match-end 3)
6145 (org-display-custom-time (match-beginning 3) (match-end 3))
6146 (org-display-custom-time (match-beginning 1) (match-end 1))))
6149 (defvar-local org-target-link-regexp nil
6150 "Regular expression matching radio targets in plain text.")
6152 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6153 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6154 border border border))
6155 "Regular expression matching a link target.")
6157 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6158 "Regular expression matching a radio target.")
6160 (defconst org-any-target-regexp
6161 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6162 "Regular expression matching any target.")
6164 (defun org-activate-target-links (limit)
6165 "Add text properties for target matches."
6166 (when org-target-link-regexp
6167 (let ((case-fold-search t))
6168 (when (re-search-forward org-target-link-regexp limit t)
6169 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6170 (add-text-properties (match-beginning 1) (match-end 1)
6171 (list 'mouse-face 'highlight
6172 'keymap org-mouse-map
6173 'help-echo "Radio target link"
6174 'org-linked-text t))
6175 (org-rear-nonsticky-at (match-end 1))
6176 t))))
6178 (defun org-update-radio-target-regexp ()
6179 "Find all radio targets in this file and update the regular expression.
6180 Also refresh fontification if needed."
6181 (interactive)
6182 (let ((old-regexp org-target-link-regexp)
6183 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6184 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6185 (targets
6186 (org-with-wide-buffer
6187 (goto-char (point-min))
6188 (let (rtn)
6189 (while (re-search-forward org-radio-target-regexp nil t)
6190 ;; Make sure point is really within the object.
6191 (backward-char)
6192 (let ((obj (org-element-context)))
6193 (when (eq (org-element-type obj) 'radio-target)
6194 (cl-pushnew (org-element-property :value obj) rtn
6195 :test #'equal))))
6196 rtn))))
6197 (setq org-target-link-regexp
6198 (and targets
6199 (concat before-re
6200 (mapconcat
6201 (lambda (x)
6202 (replace-regexp-in-string
6203 " +" "\\s-+" (regexp-quote x) t t))
6204 targets
6205 "\\|")
6206 after-re)))
6207 (unless (equal old-regexp org-target-link-regexp)
6208 ;; Clean-up cache.
6209 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6210 ((not org-target-link-regexp) old-regexp)
6212 (concat before-re
6213 (mapconcat
6214 (lambda (re)
6215 (substring re (length before-re)
6216 (- (length after-re))))
6217 (list old-regexp org-target-link-regexp)
6218 "\\|")
6219 after-re)))))
6220 (org-with-wide-buffer
6221 (goto-char (point-min))
6222 (while (re-search-forward regexp nil t)
6223 (org-element-cache-refresh (match-beginning 1)))))
6224 ;; Re fontify buffer.
6225 (when (memq 'radio org-highlight-links)
6226 (org-restart-font-lock)))))
6228 (defun org-hide-wide-columns (limit)
6229 (let (s e)
6230 (setq s (text-property-any (point) (or limit (point-max))
6231 'org-cwidth t))
6232 (when s
6233 (setq e (next-single-property-change s 'org-cwidth))
6234 (add-text-properties s e '(invisible org-cwidth))
6235 (goto-char e)
6236 t)))
6238 (defvar org-latex-and-related-regexp nil
6239 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6241 (defun org-compute-latex-and-related-regexp ()
6242 "Compute regular expression for LaTeX, entities and sub/superscript.
6243 Result depends on variable `org-highlight-latex-and-related'."
6244 (setq-local
6245 org-latex-and-related-regexp
6246 (let* ((re-sub
6247 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6248 ((eq org-use-sub-superscripts '{})
6249 (list org-match-substring-with-braces-regexp))
6250 (org-use-sub-superscripts (list org-match-substring-regexp))))
6251 (re-latex
6252 (when (memq 'latex org-highlight-latex-and-related)
6253 (let ((matchers (plist-get org-format-latex-options :matchers)))
6254 (delq nil
6255 (mapcar (lambda (x)
6256 (and (member (car x) matchers) (nth 1 x)))
6257 org-latex-regexps)))))
6258 (re-entities
6259 (when (memq 'entities org-highlight-latex-and-related)
6260 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6261 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6263 (defun org-do-latex-and-related (limit)
6264 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6265 LIMIT bounds the search for syntax to highlight. Stop at first
6266 highlighted object, if any. Return t if some highlighting was
6267 done, nil otherwise."
6268 (when (org-string-nw-p org-latex-and-related-regexp)
6269 (catch 'found
6270 (while (re-search-forward org-latex-and-related-regexp limit t)
6271 (unless
6272 (cl-some
6273 (lambda (f)
6274 (memq f '(org-code org-verbatim underline org-special-keyword)))
6275 (save-excursion
6276 (goto-char (1+ (match-beginning 0)))
6277 (face-at-point nil t)))
6278 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6279 '(?_ ?^))
6281 0)))
6282 (font-lock-prepend-text-property
6283 (+ offset (match-beginning 0)) (match-end 0)
6284 'face 'org-latex-and-related)
6285 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6286 '(font-lock-multiline t)))
6287 (throw 'found t)))
6288 nil)))
6290 (defun org-restart-font-lock ()
6291 "Restart `font-lock-mode', to force refontification."
6292 (when (and (boundp 'font-lock-mode) font-lock-mode)
6293 (font-lock-mode -1)
6294 (font-lock-mode 1)))
6296 (defun org-activate-tags (limit)
6297 (when (re-search-forward
6298 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6299 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6300 (add-text-properties (match-beginning 1) (match-end 1)
6301 (list 'mouse-face 'highlight
6302 'keymap org-mouse-map))
6303 (org-rear-nonsticky-at (match-end 1))
6306 (defun org-outline-level ()
6307 "Compute the outline level of the heading at point.
6309 If this is called at a normal headline, the level is the number
6310 of stars. Use `org-reduced-level' to remove the effect of
6311 `org-odd-levels'. Unlike to `org-current-level', this function
6312 takes into consideration inlinetasks."
6313 (org-with-wide-buffer
6314 (end-of-line)
6315 (if (re-search-backward org-outline-regexp-bol nil t)
6316 (1- (- (match-end 0) (match-beginning 0)))
6317 0)))
6319 (defvar org-font-lock-keywords nil)
6321 (defsubst org-re-property (property &optional literal allow-null value)
6322 "Return a regexp matching a PROPERTY line.
6324 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6325 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6326 non-nil, match properties even without a value.
6328 Match group 3 is set to the value when it exists. If there is no
6329 value and ALLOW-NULL is non-nil, it is set to the empty string.
6331 With optional argument VALUE, match only property lines with
6332 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6333 unless LITERAL is non-nil."
6334 (concat
6335 "^\\(?4:[ \t]*\\)"
6336 (format "\\(?1::\\(?2:%s\\):\\)"
6337 (if literal property (regexp-quote property)))
6338 (cond (value
6339 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6340 (if literal value (regexp-quote value))))
6341 (allow-null
6342 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6344 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6346 (defconst org-property-re
6347 (org-re-property "\\S-+" 'literal t)
6348 "Regular expression matching a property line.
6349 There are four matching groups:
6350 1: :PROPKEY: including the leading and trailing colon,
6351 2: PROPKEY without the leading and trailing colon,
6352 3: PROPVAL without leading or trailing spaces,
6353 4: the indentation of the current line,
6354 5: trailing whitespace.")
6356 (defvar org-font-lock-hook nil
6357 "Functions to be called for special font lock stuff.")
6359 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6361 (defvar org-font-lock-set-keywords-hook nil
6362 "Functions that can manipulate `org-font-lock-extra-keywords'.
6363 This is called after `org-font-lock-extra-keywords' is defined, but before
6364 it is installed to be used by font lock. This can be useful if something
6365 needs to be inserted at a specific position in the font-lock sequence.")
6367 (defun org-font-lock-hook (limit)
6368 "Run `org-font-lock-hook' within LIMIT."
6369 (run-hook-with-args 'org-font-lock-hook limit))
6371 (defun org-set-font-lock-defaults ()
6372 "Set font lock defaults for the current buffer."
6373 (let* ((em org-fontify-emphasized-text)
6374 (lk org-highlight-links)
6375 (org-font-lock-extra-keywords
6376 (list
6377 ;; Call the hook
6378 '(org-font-lock-hook)
6379 ;; Headlines
6380 `(,(if org-fontify-whole-heading-line
6381 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6382 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6383 (1 (org-get-level-face 1))
6384 (2 (org-get-level-face 2))
6385 (3 (org-get-level-face 3)))
6386 ;; Table lines
6387 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6388 (1 'org-table t))
6389 ;; Table internals
6390 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6391 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6392 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6393 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6394 ;; Drawers
6395 '(org-fontify-drawers)
6396 ;; Properties
6397 (list org-property-re
6398 '(1 'org-special-keyword t)
6399 '(3 'org-property-value t))
6400 ;; Links
6401 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6402 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6403 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6404 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6405 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6406 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6407 (when (memq 'footnote lk) '(org-activate-footnote-links))
6408 ;; Targets.
6409 (list org-any-target-regexp '(0 'org-target t))
6410 ;; Diary sexps.
6411 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6412 ;; Macro
6413 '(org-fontify-macros)
6414 '(org-hide-wide-columns (0 nil append))
6415 ;; TODO keyword
6416 (list (format org-heading-keyword-regexp-format
6417 org-todo-regexp)
6418 '(2 (org-get-todo-face 2) t))
6419 ;; DONE
6420 (if org-fontify-done-headline
6421 (list (format org-heading-keyword-regexp-format
6422 (concat
6423 "\\(?:"
6424 (mapconcat 'regexp-quote org-done-keywords "\\|")
6425 "\\)"))
6426 '(2 'org-headline-done t))
6427 nil)
6428 ;; Priorities
6429 '(org-font-lock-add-priority-faces)
6430 ;; Tags
6431 '(org-font-lock-add-tag-faces)
6432 ;; Tags groups
6433 (when (and org-group-tags org-tag-groups-alist)
6434 (list (concat org-outline-regexp-bol ".+\\(:"
6435 (regexp-opt (mapcar 'car org-tag-groups-alist))
6436 ":\\).*$")
6437 '(1 'org-tag-group prepend)))
6438 ;; Special keywords
6439 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6440 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6441 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6442 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6443 ;; Emphasis
6444 (when em '(org-do-emphasis-faces))
6445 ;; Checkboxes
6446 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6447 1 'org-checkbox prepend)
6448 (when (cdr (assq 'checkbox org-list-automatic-rules))
6449 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6450 (0 (org-get-checkbox-statistics-face) t)))
6451 ;; Description list items
6452 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6453 1 'org-list-dt prepend)
6454 ;; ARCHIVEd headings
6455 (list (concat
6456 org-outline-regexp-bol
6457 "\\(.*:" org-archive-tag ":.*\\)")
6458 '(1 'org-archived prepend))
6459 ;; Specials
6460 '(org-do-latex-and-related)
6461 '(org-fontify-entities)
6462 '(org-raise-scripts)
6463 ;; Code
6464 '(org-activate-code (1 'org-code t))
6465 ;; COMMENT
6466 (list (format
6467 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6468 org-todo-regexp
6469 org-comment-string)
6470 '(9 'org-special-keyword t))
6471 ;; Blocks and meta lines
6472 '(org-fontify-meta-lines-and-blocks))))
6473 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6474 (run-hooks 'org-font-lock-set-keywords-hook)
6475 ;; Now set the full font-lock-keywords
6476 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6477 (setq-local font-lock-defaults
6478 '(org-font-lock-keywords t nil nil backward-paragraph))
6479 (kill-local-variable 'font-lock-keywords)
6480 nil))
6482 (defun org-toggle-pretty-entities ()
6483 "Toggle the composition display of entities as UTF8 characters."
6484 (interactive)
6485 (setq-local org-pretty-entities (not org-pretty-entities))
6486 (org-restart-font-lock)
6487 (if org-pretty-entities
6488 (message "Entities are now displayed as UTF8 characters")
6489 (save-restriction
6490 (widen)
6491 (decompose-region (point-min) (point-max))
6492 (message "Entities are now displayed as plain text"))))
6494 (defvar-local org-custom-properties-overlays nil
6495 "List of overlays used for custom properties.")
6497 (defun org-toggle-custom-properties-visibility ()
6498 "Display or hide properties in `org-custom-properties'."
6499 (interactive)
6500 (if org-custom-properties-overlays
6501 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6502 (setq org-custom-properties-overlays nil))
6503 (when org-custom-properties
6504 (org-with-wide-buffer
6505 (goto-char (point-min))
6506 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6507 (while (re-search-forward regexp nil t)
6508 (let ((end (cdr (save-match-data (org-get-property-block)))))
6509 (when (and end (< (point) end))
6510 ;; Hide first custom property in current drawer.
6511 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6512 (overlay-put o 'invisible t)
6513 (overlay-put o 'org-custom-property t)
6514 (push o org-custom-properties-overlays))
6515 ;; Hide additional custom properties in the same drawer.
6516 (while (re-search-forward regexp end t)
6517 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6518 (overlay-put o 'invisible t)
6519 (overlay-put o 'org-custom-property t)
6520 (push o org-custom-properties-overlays)))))
6521 ;; Each entry is limited to a single property drawer.
6522 (outline-next-heading)))))))
6524 (defun org-fontify-entities (limit)
6525 "Find an entity to fontify."
6526 (let (ee)
6527 (when org-pretty-entities
6528 (catch 'match
6529 ;; "\_ "-family is left out on purpose. Only the first one,
6530 ;; i.e., "\_ ", could be fontified anyway, and it would be
6531 ;; confusing when adding a second white space character.
6532 (while (re-search-forward
6533 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6534 limit t)
6535 (when (and (not (org-at-comment-p))
6536 (setq ee (org-entity-get (match-string 1)))
6537 (= (length (nth 6 ee)) 1))
6538 (let* ((end (if (equal (match-string 2) "{}")
6539 (match-end 2)
6540 (match-end 1))))
6541 (add-text-properties
6542 (match-beginning 0) end
6543 (list 'font-lock-fontified t))
6544 (compose-region (match-beginning 0) end
6545 (nth 6 ee) nil)
6546 (backward-char 1)
6547 (throw 'match t))))
6548 nil))))
6550 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6551 "Fontify string S like in Org mode."
6552 (with-temp-buffer
6553 (insert s)
6554 (let ((org-odd-levels-only odd-levels))
6555 (org-mode)
6556 (org-font-lock-ensure)
6557 (buffer-string))))
6559 (defvar org-m nil)
6560 (defvar org-l nil)
6561 (defvar org-f nil)
6562 (defun org-get-level-face (n)
6563 "Get the right face for match N in font-lock matching of headlines."
6564 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6565 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6566 (if org-cycle-level-faces
6567 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6568 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6569 (cond
6570 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6571 ((eq n 2) org-f)
6572 (t (unless org-level-color-stars-only org-f))))
6574 (defun org-face-from-face-or-color (context inherit face-or-color)
6575 "Create a face list that inherits INHERIT, but sets the foreground color.
6576 When FACE-OR-COLOR is not a string, just return it."
6577 (if (stringp face-or-color)
6578 (list :inherit inherit
6579 (cdr (assoc context org-faces-easy-properties))
6580 face-or-color)
6581 face-or-color))
6583 (defun org-get-todo-face (kwd)
6584 "Get the right face for a TODO keyword KWD.
6585 If KWD is a number, get the corresponding match group."
6586 (when (numberp kwd) (setq kwd (match-string kwd)))
6587 (or (org-face-from-face-or-color
6588 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6589 (and (member kwd org-done-keywords) 'org-done)
6590 'org-todo))
6592 (defun org-get-priority-face (priority)
6593 "Get the right face for PRIORITY.
6594 PRIORITY is a character."
6595 (or (org-face-from-face-or-color
6596 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6597 'org-priority))
6599 (defun org-get-tag-face (tag)
6600 "Get the right face for TAG.
6601 If TAG is a number, get the corresponding match group."
6602 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6603 (or (org-face-from-face-or-color
6604 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6605 'org-tag)))
6607 (defun org-font-lock-add-priority-faces (limit)
6608 "Add the special priority faces."
6609 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6610 (add-text-properties
6611 (match-beginning 1) (match-end 1)
6612 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6613 'font-lock-fontified t))))
6615 (defun org-font-lock-add-tag-faces (limit)
6616 "Add the special tag faces."
6617 (when (and org-tag-faces org-tags-special-faces-re)
6618 (while (re-search-forward org-tags-special-faces-re limit t)
6619 (add-text-properties (match-beginning 1) (match-end 1)
6620 (list 'face (org-get-tag-face 1)
6621 'font-lock-fontified t))
6622 (backward-char 1))))
6624 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6625 "Remove fontification and activation overlays from links."
6626 (font-lock-default-unfontify-region beg end)
6627 (let* ((buffer-undo-list t)
6628 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6629 (inhibit-modification-hooks t)
6630 deactivate-mark buffer-file-name buffer-file-truename)
6631 (decompose-region beg end)
6632 (remove-text-properties beg end
6633 '(mouse-face t keymap t org-linked-text t
6634 invisible t intangible t
6635 org-emphasis t))
6636 (org-remove-font-lock-display-properties beg end)))
6638 (defconst org-script-display '(((raise -0.3) (height 0.7))
6639 ((raise 0.3) (height 0.7))
6640 ((raise -0.5))
6641 ((raise 0.5)))
6642 "Display properties for showing superscripts and subscripts.")
6644 (defun org-remove-font-lock-display-properties (beg end)
6645 "Remove specific display properties that have been added by font lock.
6646 The will remove the raise properties that are used to show superscripts
6647 and subscripts."
6648 (let (next prop)
6649 (while (< beg end)
6650 (setq next (next-single-property-change beg 'display nil end)
6651 prop (get-text-property beg 'display))
6652 (when (member prop org-script-display)
6653 (put-text-property beg next 'display nil))
6654 (setq beg next))))
6656 (defun org-raise-scripts (limit)
6657 "Add raise properties to sub/superscripts."
6658 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6659 (re-search-forward
6660 (if (eq org-use-sub-superscripts t)
6661 org-match-substring-regexp
6662 org-match-substring-with-braces-regexp)
6663 limit t))
6664 (let* ((pos (point)) table-p comment-p
6665 (mpos (match-beginning 3))
6666 (emph-p (get-text-property mpos 'org-emphasis))
6667 (link-p (get-text-property mpos 'mouse-face))
6668 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6669 (goto-char (point-at-bol))
6670 (setq table-p (looking-at-p org-table-dataline-regexp)
6671 comment-p (looking-at-p "^[ \t]*#[ +]"))
6672 (goto-char pos)
6673 ;; Handle a_b^c
6674 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6675 (unless (or comment-p emph-p link-p keyw-p)
6676 (put-text-property (match-beginning 3) (match-end 0)
6677 'display
6678 (if (equal (char-after (match-beginning 2)) ?^)
6679 (nth (if table-p 3 1) org-script-display)
6680 (nth (if table-p 2 0) org-script-display)))
6681 (add-text-properties (match-beginning 2) (match-end 2)
6682 (list 'invisible t
6683 'org-dwidth t 'org-dwidth-n 1))
6684 (if (and (eq (char-after (match-beginning 3)) ?{)
6685 (eq (char-before (match-end 3)) ?}))
6686 (progn
6687 (add-text-properties
6688 (match-beginning 3) (1+ (match-beginning 3))
6689 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6690 (add-text-properties
6691 (1- (match-end 3)) (match-end 3)
6692 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6693 t)))
6695 ;;;; Visibility cycling, including org-goto and indirect buffer
6697 ;;; Cycling
6699 (defvar-local org-cycle-global-status nil)
6700 (put 'org-cycle-global-status 'org-state t)
6701 (defvar-local org-cycle-subtree-status nil)
6702 (put 'org-cycle-subtree-status 'org-state t)
6704 (defvar org-inlinetask-min-level)
6706 (defun org-unlogged-message (&rest args)
6707 "Display a message, but avoid logging it in the *Messages* buffer."
6708 (let ((message-log-max nil))
6709 (apply 'message args)))
6711 ;;;###autoload
6712 (defun org-cycle (&optional arg)
6713 "TAB-action and visibility cycling for Org mode.
6715 This is the command invoked in Org mode by the `TAB' key. Its main
6716 purpose is outline visibility cycling, but it also invokes other actions
6717 in special contexts.
6719 When this function is called with a `\\[universal-argument]' prefix, rotate \
6720 the entire
6721 buffer through 3 states (global cycling)
6722 1. OVERVIEW: Show only top-level headlines.
6723 2. CONTENTS: Show all headlines of all levels, but no body text.
6724 3. SHOW ALL: Show everything.
6726 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6727 switch to the startup visibility,
6728 determined by the variable `org-startup-folded', and by any VISIBILITY
6729 properties in the buffer.
6731 With a `\\[universal-argument] \\[universal-argument] \
6732 \\[universal-argument]' prefix argument, show the entire buffer, including
6733 any drawers.
6735 When inside a table, re-align the table and move to the next field.
6737 When point is at the beginning of a headline, rotate the subtree started
6738 by this line through 3 different states (local cycling)
6739 1. FOLDED: Only the main headline is shown.
6740 2. CHILDREN: The main headline and the direct children are shown.
6741 From this state, you can move to one of the children
6742 and zoom in further.
6743 3. SUBTREE: Show the entire subtree, including body text.
6744 If there is no subtree, switch directly from CHILDREN to FOLDED.
6746 When point is at the beginning of an empty headline and the variable
6747 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6748 of the headline by demoting and promoting it to likely levels. This
6749 speeds up creation document structure by pressing `TAB' once or several
6750 times right after creating a new headline.
6752 When there is a numeric prefix, go up to a heading with level ARG, do
6753 a `show-subtree' and return to the previous cursor position. If ARG
6754 is negative, go up that many levels.
6756 When point is not at the beginning of a headline, execute the global
6757 binding for `TAB', which is re-indenting the line. See the option
6758 `org-cycle-emulate-tab' for details.
6760 As a special case, if point is at the beginning of the buffer and there is
6761 no headline in line 1, this function will act as if called with prefix arg
6762 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6763 prefix arg, but only
6764 if the variable `org-cycle-global-at-bob' is t."
6765 (interactive "P")
6766 (org-load-modules-maybe)
6767 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6768 (and org-cycle-level-after-item/entry-creation
6769 (or (org-cycle-level)
6770 (org-cycle-item-indentation))))
6771 (let* ((limit-level
6772 (or org-cycle-max-level
6773 (and (boundp 'org-inlinetask-min-level)
6774 org-inlinetask-min-level
6775 (1- org-inlinetask-min-level))))
6776 (nstars (and limit-level
6777 (if org-odd-levels-only
6778 (and limit-level (1- (* limit-level 2)))
6779 limit-level)))
6780 (org-outline-regexp
6781 (if (not (derived-mode-p 'org-mode))
6782 outline-regexp
6783 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6784 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6785 (not (looking-at org-outline-regexp))))
6786 (org-cycle-hook
6787 (if bob-special
6788 (delq 'org-optimize-window-after-visibility-change
6789 (copy-sequence org-cycle-hook))
6790 org-cycle-hook))
6791 (pos (point)))
6793 (cond
6795 ((equal arg '(16))
6796 (setq last-command 'dummy)
6797 (org-set-startup-visibility)
6798 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6800 ((equal arg '(64))
6801 (outline-show-all)
6802 (org-unlogged-message "Entire buffer visible, including drawers"))
6804 ((equal arg '(4)) (org-cycle-internal-global))
6806 ;; Try hiding block at point.
6807 ((org-hide-block-toggle-maybe))
6809 ;; Try cdlatex TAB completion
6810 ((org-try-cdlatex-tab))
6812 ;; Table: enter it or move to the next field.
6813 ((org-at-table-p 'any)
6814 (if (org-at-table.el-p)
6815 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6816 Use `\\[org-edit-special]' to edit table.el tables"))
6817 (if arg (org-table-edit-field t)
6818 (org-table-justify-field-maybe)
6819 (call-interactively 'org-table-next-field))))
6821 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6823 ;; Global cycling: delegate to `org-cycle-internal-global'.
6824 (bob-special (org-cycle-internal-global))
6826 ;; Drawers: delegate to `org-flag-drawer'.
6827 ((save-excursion
6828 (beginning-of-line 1)
6829 (looking-at org-drawer-regexp))
6830 (org-flag-drawer ; toggle block visibility
6831 (not (get-char-property (match-end 0) 'invisible))))
6833 ;; Show-subtree, ARG levels up from here.
6834 ((integerp arg)
6835 (save-excursion
6836 (org-back-to-heading)
6837 (outline-up-heading (if (< arg 0) (- arg)
6838 (- (funcall outline-level) arg)))
6839 (org-show-subtree)))
6841 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6842 ((and (featurep 'org-inlinetask)
6843 (org-inlinetask-at-task-p)
6844 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6845 (org-inlinetask-toggle-visibility))
6847 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6848 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6849 (save-excursion (move-beginning-of-line 1)
6850 (looking-at org-outline-regexp)))
6851 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6852 (org-cycle-internal-local))
6854 ;; From there: TAB emulation and template completion.
6855 (buffer-read-only (org-back-to-heading))
6857 ((run-hook-with-args-until-success
6858 'org-tab-after-check-for-cycling-hook))
6860 ((org-try-structure-completion))
6862 ((run-hook-with-args-until-success
6863 'org-tab-before-tab-emulation-hook))
6865 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6866 (or (not (bolp))
6867 (not (looking-at org-outline-regexp))))
6868 (call-interactively (global-key-binding "\t")))
6870 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6871 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6872 (or (and (eq org-cycle-emulate-tab 'white)
6873 (= (match-end 0) (point-at-eol)))
6874 (and (eq org-cycle-emulate-tab 'whitestart)
6875 (>= (match-end 0) pos))))
6877 (eq org-cycle-emulate-tab t))
6878 (call-interactively (global-key-binding "\t")))
6880 (t (save-excursion
6881 (org-back-to-heading)
6882 (org-cycle)))))))
6884 (defun org-cycle-internal-global ()
6885 "Do the global cycling action."
6886 ;; Hack to avoid display of messages for .org attachments in Gnus
6887 (let ((ga (string-match "\\*fontification" (buffer-name))))
6888 (cond
6889 ((and (eq last-command this-command)
6890 (eq org-cycle-global-status 'overview))
6891 ;; We just created the overview - now do table of contents
6892 ;; This can be slow in very large buffers, so indicate action
6893 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6894 (unless ga (org-unlogged-message "CONTENTS..."))
6895 (org-content)
6896 (unless ga (org-unlogged-message "CONTENTS...done"))
6897 (setq org-cycle-global-status 'contents)
6898 (run-hook-with-args 'org-cycle-hook 'contents))
6900 ((and (eq last-command this-command)
6901 (eq org-cycle-global-status 'contents))
6902 ;; We just showed the table of contents - now show everything
6903 (run-hook-with-args 'org-pre-cycle-hook 'all)
6904 (outline-show-all)
6905 (unless ga (org-unlogged-message "SHOW ALL"))
6906 (setq org-cycle-global-status 'all)
6907 (run-hook-with-args 'org-cycle-hook 'all))
6910 ;; Default action: go to overview
6911 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6912 (org-overview)
6913 (unless ga (org-unlogged-message "OVERVIEW"))
6914 (setq org-cycle-global-status 'overview)
6915 (run-hook-with-args 'org-cycle-hook 'overview)))))
6917 (defvar org-called-with-limited-levels nil
6918 "Non-nil when `org-with-limited-levels' is currently active.")
6920 (defun org-cycle-internal-local ()
6921 "Do the local cycling action."
6922 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6923 ;; First, determine end of headline (EOH), end of subtree or item
6924 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6925 (save-excursion
6926 (if (org-at-item-p)
6927 (progn
6928 (beginning-of-line)
6929 (setq struct (org-list-struct))
6930 (setq eoh (point-at-eol))
6931 (setq eos (org-list-get-item-end-before-blank (point) struct))
6932 (setq has-children (org-list-has-child-p (point) struct)))
6933 (org-back-to-heading)
6934 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6935 (setq eos (save-excursion (org-end-of-subtree t t)
6936 (when (bolp) (backward-char)) (point)))
6937 (setq has-children
6938 (or (save-excursion
6939 (let ((level (funcall outline-level)))
6940 (outline-next-heading)
6941 (and (org-at-heading-p t)
6942 (> (funcall outline-level) level))))
6943 (save-excursion
6944 (org-list-search-forward (org-item-beginning-re) eos t)))))
6945 ;; Determine end invisible part of buffer (EOL)
6946 (beginning-of-line 2)
6947 (while (and (not (eobp)) ;This is like `next-line'.
6948 (get-char-property (1- (point)) 'invisible))
6949 (goto-char (next-single-char-property-change (point) 'invisible))
6950 (and (eolp) (beginning-of-line 2)))
6951 (setq eol (point)))
6952 ;; Find out what to do next and set `this-command'
6953 (cond
6954 ((= eos eoh)
6955 ;; Nothing is hidden behind this heading
6956 (unless (org-before-first-heading-p)
6957 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6958 (org-unlogged-message "EMPTY ENTRY")
6959 (setq org-cycle-subtree-status nil)
6960 (save-excursion
6961 (goto-char eos)
6962 (outline-next-heading)
6963 (when (outline-invisible-p) (org-flag-heading nil))))
6964 ((and (or (>= eol eos)
6965 (not (string-match "\\S-" (buffer-substring eol eos))))
6966 (or has-children
6967 (not (setq children-skipped
6968 org-cycle-skip-children-state-if-no-children))))
6969 ;; Entire subtree is hidden in one line: children view
6970 (unless (org-before-first-heading-p)
6971 (run-hook-with-args 'org-pre-cycle-hook 'children))
6972 (if (org-at-item-p)
6973 (org-list-set-item-visibility (point-at-bol) struct 'children)
6974 (org-show-entry)
6975 (org-with-limited-levels (org-show-children))
6976 ;; FIXME: This slows down the func way too much.
6977 ;; How keep drawers hidden in subtree anyway?
6978 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6979 ;; (org-cycle-hide-drawers 'subtree))
6981 ;; Fold every list in subtree to top-level items.
6982 (when (eq org-cycle-include-plain-lists 'integrate)
6983 (save-excursion
6984 (org-back-to-heading)
6985 (while (org-list-search-forward (org-item-beginning-re) eos t)
6986 (beginning-of-line 1)
6987 (let* ((struct (org-list-struct))
6988 (prevs (org-list-prevs-alist struct))
6989 (end (org-list-get-bottom-point struct)))
6990 (dolist (e (org-list-get-all-items (point) struct prevs))
6991 (org-list-set-item-visibility e struct 'folded))
6992 (goto-char (if (< end eos) end eos)))))))
6993 (org-unlogged-message "CHILDREN")
6994 (save-excursion
6995 (goto-char eos)
6996 (outline-next-heading)
6997 (when (outline-invisible-p) (org-flag-heading nil)))
6998 (setq org-cycle-subtree-status 'children)
6999 (unless (org-before-first-heading-p)
7000 (run-hook-with-args 'org-cycle-hook 'children)))
7001 ((or children-skipped
7002 (and (eq last-command this-command)
7003 (eq org-cycle-subtree-status 'children)))
7004 ;; We just showed the children, or no children are there,
7005 ;; now show everything.
7006 (unless (org-before-first-heading-p)
7007 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7008 (outline-flag-region eoh eos nil)
7009 (org-unlogged-message
7010 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7011 (setq org-cycle-subtree-status 'subtree)
7012 (unless (org-before-first-heading-p)
7013 (run-hook-with-args 'org-cycle-hook 'subtree)))
7015 ;; Default action: hide the subtree.
7016 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7017 (outline-flag-region eoh eos t)
7018 (org-unlogged-message "FOLDED")
7019 (setq org-cycle-subtree-status 'folded)
7020 (unless (org-before-first-heading-p)
7021 (run-hook-with-args 'org-cycle-hook 'folded))))))
7023 ;;;###autoload
7024 (defun org-global-cycle (&optional arg)
7025 "Cycle the global visibility. For details see `org-cycle'.
7026 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7027 With a numeric prefix, show all headlines up to that level."
7028 (interactive "P")
7029 (let ((org-cycle-include-plain-lists
7030 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7031 (cond
7032 ((integerp arg)
7033 (outline-show-all)
7034 (outline-hide-sublevels arg)
7035 (setq org-cycle-global-status 'contents))
7036 ((equal arg '(4))
7037 (org-set-startup-visibility)
7038 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7040 (org-cycle '(4))))))
7042 (defun org-set-startup-visibility ()
7043 "Set the visibility required by startup options and properties."
7044 (cond
7045 ((eq org-startup-folded t)
7046 (org-overview))
7047 ((eq org-startup-folded 'content)
7048 (org-content))
7049 ((or (eq org-startup-folded 'showeverything)
7050 (eq org-startup-folded nil))
7051 (outline-show-all)))
7052 (unless (eq org-startup-folded 'showeverything)
7053 (when org-hide-block-startup (org-hide-block-all))
7054 (org-set-visibility-according-to-property 'no-cleanup)
7055 (org-cycle-hide-archived-subtrees 'all)
7056 (org-cycle-hide-drawers 'all)
7057 (org-cycle-show-empty-lines t)))
7059 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7060 "Switch subtree visibilities according to :VISIBILITY: property."
7061 (interactive)
7062 (org-with-wide-buffer
7063 (goto-char (point-min))
7064 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7065 (if (not (org-at-property-p)) (outline-next-heading)
7066 (let ((state (match-string 3)))
7067 (save-excursion
7068 (org-back-to-heading t)
7069 (outline-hide-subtree)
7070 (org-reveal)
7071 (cond
7072 ((equal state "folded")
7073 (outline-hide-subtree))
7074 ((equal state "children")
7075 (org-show-hidden-entry)
7076 (org-show-children))
7077 ((equal state "content")
7078 (save-excursion
7079 (save-restriction
7080 (org-narrow-to-subtree)
7081 (org-content))))
7082 ((member state '("all" "showall"))
7083 (outline-show-subtree)))))))
7084 (unless no-cleanup
7085 (org-cycle-hide-archived-subtrees 'all)
7086 (org-cycle-hide-drawers 'all)
7087 (org-cycle-show-empty-lines 'all))))
7089 ;; This function uses outline-regexp instead of the more fundamental
7090 ;; org-outline-regexp so that org-cycle-global works outside of Org
7091 ;; buffers, where outline-regexp is needed.
7092 (defun org-overview ()
7093 "Switch to overview mode, showing only top-level headlines.
7094 This shows all headlines with a level equal or greater than the level
7095 of the first headline in the buffer. This is important, because if the
7096 first headline is not level one, then (hide-sublevels 1) gives confusing
7097 results."
7098 (interactive)
7099 (save-excursion
7100 (let ((level
7101 (save-excursion
7102 (goto-char (point-min))
7103 (when (re-search-forward (concat "^" outline-regexp) nil t)
7104 (goto-char (match-beginning 0))
7105 (funcall outline-level)))))
7106 (and level (outline-hide-sublevels level)))))
7108 (defun org-content (&optional arg)
7109 "Show all headlines in the buffer, like a table of contents.
7110 With numerical argument N, show content up to level N."
7111 (interactive "P")
7112 (org-overview)
7113 (save-excursion
7114 ;; Visit all headings and show their offspring
7115 (and (integerp arg) (org-overview))
7116 (goto-char (point-max))
7117 (catch 'exit
7118 (while (and (progn (condition-case nil
7119 (outline-previous-visible-heading 1)
7120 (error (goto-char (point-min))))
7122 (looking-at org-outline-regexp))
7123 (if (integerp arg)
7124 (org-show-children (1- arg))
7125 (outline-show-branches))
7126 (when (bobp) (throw 'exit nil))))))
7128 (defun org-optimize-window-after-visibility-change (state)
7129 "Adjust the window after a change in outline visibility.
7130 This function is the default value of the hook `org-cycle-hook'."
7131 (when (get-buffer-window (current-buffer))
7132 (cond
7133 ((eq state 'content) nil)
7134 ((eq state 'all) nil)
7135 ((eq state 'folded) nil)
7136 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7137 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7139 (defun org-remove-empty-overlays-at (pos)
7140 "Remove outline overlays that do not contain non-white stuff."
7141 (dolist (o (overlays-at pos))
7142 (and (eq 'outline (overlay-get o 'invisible))
7143 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7144 (overlay-end o))))
7145 (delete-overlay o))))
7147 (defun org-clean-visibility-after-subtree-move ()
7148 "Fix visibility issues after moving a subtree."
7149 ;; First, find a reasonable region to look at:
7150 ;; Start two siblings above, end three below
7151 (let* ((beg (save-excursion
7152 (and (org-get-last-sibling)
7153 (org-get-last-sibling))
7154 (point)))
7155 (end (save-excursion
7156 (and (org-get-next-sibling)
7157 (org-get-next-sibling)
7158 (org-get-next-sibling))
7159 (if (org-at-heading-p)
7160 (point-at-eol)
7161 (point))))
7162 (level (looking-at "\\*+"))
7163 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7164 (save-excursion
7165 (save-restriction
7166 (narrow-to-region beg end)
7167 (when re
7168 ;; Properly fold already folded siblings
7169 (goto-char (point-min))
7170 (while (re-search-forward re nil t)
7171 (when (and (not (outline-invisible-p))
7172 (save-excursion
7173 (goto-char (point-at-eol)) (outline-invisible-p)))
7174 (outline-hide-entry))))
7175 (org-cycle-show-empty-lines 'overview)
7176 (org-cycle-hide-drawers 'overview)))))
7178 (defun org-cycle-show-empty-lines (state)
7179 "Show empty lines above all visible headlines.
7180 The region to be covered depends on STATE when called through
7181 `org-cycle-hook'. Lisp program can use t for STATE to get the
7182 entire buffer covered. Note that an empty line is only shown if there
7183 are at least `org-cycle-separator-lines' empty lines before the headline."
7184 (when (/= org-cycle-separator-lines 0)
7185 (save-excursion
7186 (let* ((n (abs org-cycle-separator-lines))
7187 (re (cond
7188 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7189 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7190 (t (let ((ns (number-to-string (- n 2))))
7191 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7192 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7193 beg end)
7194 (cond
7195 ((memq state '(overview contents t))
7196 (setq beg (point-min) end (point-max)))
7197 ((memq state '(children folded))
7198 (setq beg (point)
7199 end (progn (org-end-of-subtree t t)
7200 (line-beginning-position 2)))))
7201 (when beg
7202 (goto-char beg)
7203 (while (re-search-forward re end t)
7204 (unless (get-char-property (match-end 1) 'invisible)
7205 (let ((e (match-end 1))
7206 (b (if (>= org-cycle-separator-lines 0)
7207 (match-beginning 1)
7208 (save-excursion
7209 (goto-char (match-beginning 0))
7210 (skip-chars-backward " \t\n")
7211 (line-end-position)))))
7212 (outline-flag-region b e nil))))))))
7213 ;; Never hide empty lines at the end of the file.
7214 (save-excursion
7215 (goto-char (point-max))
7216 (outline-previous-heading)
7217 (outline-end-of-heading)
7218 (when (and (looking-at "[ \t\n]+")
7219 (= (match-end 0) (point-max)))
7220 (outline-flag-region (point) (match-end 0) nil))))
7222 (defun org-show-empty-lines-in-parent ()
7223 "Move to the parent and re-show empty lines before visible headlines."
7224 (save-excursion
7225 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7226 (org-cycle-show-empty-lines context))))
7228 (defun org-files-list ()
7229 "Return `org-agenda-files' list, plus all open Org files.
7230 This is useful for operations that need to scan all of a user's
7231 open and agenda-wise Org files."
7232 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7233 (dolist (buf (buffer-list))
7234 (with-current-buffer buf
7235 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7236 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7237 files))
7239 (defsubst org-entry-beginning-position ()
7240 "Return the beginning position of the current entry."
7241 (save-excursion (org-back-to-heading t) (point)))
7243 (defsubst org-entry-end-position ()
7244 "Return the end position of the current entry."
7245 (save-excursion (outline-next-heading) (point)))
7247 (defun org-cycle-hide-drawers (state &optional exceptions)
7248 "Re-hide all drawers after a visibility state change.
7249 When non-nil, optional argument EXCEPTIONS is a list of strings
7250 specifying which drawers should not be hidden."
7251 (when (and (derived-mode-p 'org-mode)
7252 (not (memq state '(overview folded contents))))
7253 (save-excursion
7254 (let* ((globalp (memq state '(contents all)))
7255 (beg (if globalp (point-min) (point)))
7256 (end (if globalp (point-max)
7257 (if (eq state 'children)
7258 (save-excursion (outline-next-heading) (point))
7259 (org-end-of-subtree t)))))
7260 (goto-char beg)
7261 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7262 (unless (member-ignore-case (match-string 1) exceptions)
7263 (let ((drawer (org-element-at-point)))
7264 (when (memq (org-element-type drawer) '(drawer property-drawer))
7265 (org-flag-drawer t drawer)
7266 ;; Make sure to skip drawer entirely or we might flag
7267 ;; it another time when matching its ending line with
7268 ;; `org-drawer-regexp'.
7269 (goto-char (org-element-property :end drawer))))))))))
7271 (defun org-flag-drawer (flag &optional element)
7272 "When FLAG is non-nil, hide the drawer we are at.
7273 Otherwise make it visible. When optional argument ELEMENT is
7274 a parsed drawer, as returned by `org-element-at-point', hide or
7275 show that drawer instead."
7276 (let ((drawer (or element
7277 (and (save-excursion
7278 (beginning-of-line)
7279 (looking-at-p org-drawer-regexp))
7280 (org-element-at-point)))))
7281 (when (memq (org-element-type drawer) '(drawer property-drawer))
7282 (let ((post (org-element-property :post-affiliated drawer)))
7283 (save-excursion
7284 (outline-flag-region
7285 (progn (goto-char post) (line-end-position))
7286 (progn (goto-char (org-element-property :end drawer))
7287 (skip-chars-backward " \r\t\n")
7288 (line-end-position))
7289 flag))
7290 ;; When the drawer is hidden away, make sure point lies in
7291 ;; a visible part of the buffer.
7292 (when (and flag (> (line-beginning-position) post))
7293 (goto-char post))))))
7295 (defun org-subtree-end-visible-p ()
7296 "Is the end of the current subtree visible?"
7297 (pos-visible-in-window-p
7298 (save-excursion (org-end-of-subtree t) (point))))
7300 (defun org-first-headline-recenter ()
7301 "Move cursor to the first headline and recenter the headline."
7302 (let ((window (get-buffer-window)))
7303 (when window
7304 (goto-char (point-min))
7305 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7306 (set-window-start window (line-beginning-position))))))
7308 ;;; Saving and restoring visibility
7310 (defun org-outline-overlay-data (&optional use-markers)
7311 "Return a list of the locations of all outline overlays.
7312 These are overlays with the `invisible' property value `outline'.
7313 The return value is a list of cons cells, with start and stop
7314 positions for each overlay.
7315 If USE-MARKERS is set, return the positions as markers."
7316 (let (beg end)
7317 (org-with-wide-buffer
7318 (delq nil
7319 (mapcar (lambda (o)
7320 (when (eq (overlay-get o 'invisible) 'outline)
7321 (setq beg (overlay-start o)
7322 end (overlay-end o))
7323 (and beg end (> end beg)
7324 (if use-markers
7325 (cons (copy-marker beg)
7326 (copy-marker end t))
7327 (cons beg end)))))
7328 (overlays-in (point-min) (point-max)))))))
7330 (defun org-set-outline-overlay-data (data)
7331 "Create visibility overlays for all positions in DATA.
7332 DATA should have been made by `org-outline-overlay-data'."
7333 (org-with-wide-buffer
7334 (outline-show-all)
7335 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7337 ;;; Folding of blocks
7339 (defvar-local org-hide-block-overlays nil
7340 "Overlays hiding blocks.")
7342 (defun org-block-map (function &optional start end)
7343 "Call FUNCTION at the head of all source blocks in the current buffer.
7344 Optional arguments START and END can be used to limit the range."
7345 (let ((start (or start (point-min)))
7346 (end (or end (point-max))))
7347 (save-excursion
7348 (goto-char start)
7349 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7350 (save-excursion
7351 (save-match-data
7352 (goto-char (match-beginning 0))
7353 (funcall function)))))))
7355 (defun org-hide-block-toggle-all ()
7356 "Toggle the visibility of all blocks in the current buffer."
7357 (org-block-map 'org-hide-block-toggle))
7359 (defun org-hide-block-all ()
7360 "Fold all blocks in the current buffer."
7361 (interactive)
7362 (org-show-block-all)
7363 (org-block-map 'org-hide-block-toggle-maybe))
7365 (defun org-show-block-all ()
7366 "Unfold all blocks in the current buffer."
7367 (interactive)
7368 (mapc #'delete-overlay org-hide-block-overlays)
7369 (setq org-hide-block-overlays nil))
7371 (defun org-hide-block-toggle-maybe ()
7372 "Toggle visibility of block at point.
7373 Unlike to `org-hide-block-toggle', this function does not throw
7374 an error. Return a non-nil value when toggling is successful."
7375 (interactive)
7376 (ignore-errors (org-hide-block-toggle)))
7378 (defun org-hide-block-toggle (&optional force)
7379 "Toggle the visibility of the current block.
7380 When optional argument FORCE is `off', make block visible. If it
7381 is non-nil, hide it unconditionally. Throw an error when not at
7382 a block. Return a non-nil value when toggling is successful."
7383 (interactive)
7384 (let ((element (org-element-at-point)))
7385 (unless (memq (org-element-type element)
7386 '(center-block comment-block dynamic-block example-block
7387 export-block quote-block special-block
7388 src-block verse-block))
7389 (user-error "Not at a block"))
7390 (let* ((start (save-excursion
7391 (goto-char (org-element-property :post-affiliated element))
7392 (line-end-position)))
7393 (end (save-excursion
7394 (goto-char (org-element-property :end element))
7395 (skip-chars-backward " \r\t\n")
7396 (line-end-position)))
7397 (overlays (overlays-at start)))
7398 (cond
7399 ;; Do nothing when not before or at the block opening line or
7400 ;; at the block closing line.
7401 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7402 ((and (not (eq force 'off))
7403 (not (memq t (mapcar
7404 (lambda (o)
7405 (eq (overlay-get o 'invisible) 'org-hide-block))
7406 overlays))))
7407 (let ((ov (make-overlay start end)))
7408 (overlay-put ov 'invisible 'org-hide-block)
7409 ;; Make the block accessible to `isearch'.
7410 (overlay-put
7411 ov 'isearch-open-invisible
7412 (lambda (ov)
7413 (when (memq ov org-hide-block-overlays)
7414 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7415 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7416 (delete-overlay ov))))
7417 (push ov org-hide-block-overlays)
7418 ;; When the block is hidden away, make sure point is left in
7419 ;; a visible part of the buffer.
7420 (when (> (line-beginning-position) start)
7421 (goto-char start)
7422 (beginning-of-line))
7423 ;; Signal successful toggling.
7425 ((or (not force) (eq force 'off))
7426 (dolist (ov overlays t)
7427 (when (memq ov org-hide-block-overlays)
7428 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7429 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7430 (delete-overlay ov))))))))
7432 ;; Remove overlays when changing major mode
7433 (add-hook 'org-mode-hook
7434 (lambda () (add-hook 'change-major-mode-hook
7435 'org-show-block-all 'append 'local)))
7437 ;;; Org-goto
7439 (defvar org-goto-window-configuration nil)
7440 (defvar org-goto-marker nil)
7441 (defvar org-goto-map)
7442 (defun org-goto-map ()
7443 "Set the keymap `org-goto'."
7444 (setq org-goto-map
7445 (let ((map (make-sparse-keymap)))
7446 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7447 mouse-drag-region universal-argument org-occur)))
7448 (dolist (cmd cmds)
7449 (substitute-key-definition cmd cmd map global-map)))
7450 (suppress-keymap map)
7451 (org-defkey map "\C-m" 'org-goto-ret)
7452 (org-defkey map [(return)] 'org-goto-ret)
7453 (org-defkey map [(left)] 'org-goto-left)
7454 (org-defkey map [(right)] 'org-goto-right)
7455 (org-defkey map [(control ?g)] 'org-goto-quit)
7456 (org-defkey map "\C-i" 'org-cycle)
7457 (org-defkey map [(tab)] 'org-cycle)
7458 (org-defkey map [(down)] 'outline-next-visible-heading)
7459 (org-defkey map [(up)] 'outline-previous-visible-heading)
7460 (if org-goto-auto-isearch
7461 (if (fboundp 'define-key-after)
7462 (define-key-after map [t] 'org-goto-local-auto-isearch)
7463 nil)
7464 (org-defkey map "q" 'org-goto-quit)
7465 (org-defkey map "n" 'outline-next-visible-heading)
7466 (org-defkey map "p" 'outline-previous-visible-heading)
7467 (org-defkey map "f" 'outline-forward-same-level)
7468 (org-defkey map "b" 'outline-backward-same-level)
7469 (org-defkey map "u" 'outline-up-heading))
7470 (org-defkey map "/" 'org-occur)
7471 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7472 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7473 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7474 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7475 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7476 map)))
7478 (defconst org-goto-help
7479 "Browse buffer copy, to find location or copy text.%s
7480 RET=jump to location C-g=quit and return to previous location
7481 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7483 (defvar org-goto-start-pos) ; dynamically scoped parameter
7485 (defun org-goto (&optional alternative-interface)
7486 "Look up a different location in the current file, keeping current visibility.
7488 When you want look-up or go to a different location in a
7489 document, the fastest way is often to fold the entire buffer and
7490 then dive into the tree. This method has the disadvantage, that
7491 the previous location will be folded, which may not be what you
7492 want.
7494 This command works around this by showing a copy of the current
7495 buffer in an indirect buffer, in overview mode. You can dive
7496 into the tree in that copy, use org-occur and incremental search
7497 to find a location. When pressing RET or `Q', the command
7498 returns to the original buffer in which the visibility is still
7499 unchanged. After RET it will also jump to the location selected
7500 in the indirect buffer and expose the headline hierarchy above.
7502 With a prefix argument, use the alternative interface: e.g., if
7503 `org-goto-interface' is `outline' use `outline-path-completion'."
7504 (interactive "P")
7505 (org-goto-map)
7506 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7507 (org-refile-use-outline-path t)
7508 (org-refile-target-verify-function nil)
7509 (interface
7510 (if (not alternative-interface)
7511 org-goto-interface
7512 (if (eq org-goto-interface 'outline)
7513 'outline-path-completion
7514 'outline)))
7515 (org-goto-start-pos (point))
7516 (selected-point
7517 (if (eq interface 'outline)
7518 (car (org-get-location (current-buffer) org-goto-help))
7519 (let ((pa (org-refile-get-location "Goto")))
7520 (org-refile-check-position pa)
7521 (nth 3 pa)))))
7522 (if selected-point
7523 (progn
7524 (org-mark-ring-push org-goto-start-pos)
7525 (goto-char selected-point)
7526 (when (or (outline-invisible-p) (org-invisible-p2))
7527 (org-show-context 'org-goto)))
7528 (message "Quit"))))
7530 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7531 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7532 (defvar org-goto-local-auto-isearch-map) ; defined below
7534 (defun org-get-location (_buf help)
7535 "Let the user select a location in current buffer.
7536 This function uses a recursive edit. It returns the selected position
7537 or nil."
7538 (org-no-popups
7539 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7540 (isearch-hide-immediately nil)
7541 (isearch-search-fun-function
7542 (lambda () 'org-goto-local-search-headings))
7543 (org-goto-selected-point org-goto-exit-command))
7544 (save-excursion
7545 (save-window-excursion
7546 (delete-other-windows)
7547 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7548 (pop-to-buffer-same-window
7549 (condition-case nil
7550 (make-indirect-buffer (current-buffer) "*org-goto*")
7551 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7552 (with-output-to-temp-buffer "*Org Help*"
7553 (princ (format help (if org-goto-auto-isearch
7554 " Just type for auto-isearch."
7555 " n/p/f/b/u to navigate, q to quit."))))
7556 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7557 (setq buffer-read-only nil)
7558 (let ((org-startup-truncated t)
7559 (org-startup-folded nil)
7560 (org-startup-align-all-tables nil))
7561 (org-mode)
7562 (org-overview))
7563 (setq buffer-read-only t)
7564 (if (and (boundp 'org-goto-start-pos)
7565 (integer-or-marker-p org-goto-start-pos))
7566 (progn (goto-char org-goto-start-pos)
7567 (when (outline-invisible-p)
7568 (org-show-set-visibility 'lineage)))
7569 (goto-char (point-min)))
7570 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7571 (message "Select location and press RET")
7572 (use-local-map org-goto-map)
7573 (recursive-edit)))
7574 (kill-buffer "*org-goto*")
7575 (cons org-goto-selected-point org-goto-exit-command))))
7577 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7578 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7579 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7580 (if (fboundp 'isearch-other-control-char)
7581 (progn
7582 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7583 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7584 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7585 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7586 (define-key org-goto-local-auto-isearch-map [return] nil))
7588 (defun org-goto-local-search-headings (string bound noerror)
7589 "Search and make sure that any matches are in headlines."
7590 (catch 'return
7591 (while (if isearch-forward
7592 (search-forward string bound noerror)
7593 (search-backward string bound noerror))
7594 (when (save-match-data
7595 (and (save-excursion
7596 (beginning-of-line)
7597 (looking-at org-complex-heading-regexp))
7598 (or (not (match-beginning 5))
7599 (< (point) (match-beginning 5)))))
7600 (throw 'return (point))))))
7602 (defun org-goto-local-auto-isearch ()
7603 "Start isearch."
7604 (interactive)
7605 (goto-char (point-min))
7606 (let ((keys (this-command-keys)))
7607 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7608 (isearch-mode t)
7609 (isearch-process-search-char (string-to-char keys)))))
7611 (defun org-goto-ret (&optional _arg)
7612 "Finish `org-goto' by going to the new location."
7613 (interactive "P")
7614 (setq org-goto-selected-point (point))
7615 (setq org-goto-exit-command 'return)
7616 (throw 'exit nil))
7618 (defun org-goto-left ()
7619 "Finish `org-goto' by going to the new location."
7620 (interactive)
7621 (if (org-at-heading-p)
7622 (progn
7623 (beginning-of-line 1)
7624 (setq org-goto-selected-point (point)
7625 org-goto-exit-command 'left)
7626 (throw 'exit nil))
7627 (user-error "Not on a heading")))
7629 (defun org-goto-right ()
7630 "Finish `org-goto' by going to the new location."
7631 (interactive)
7632 (if (org-at-heading-p)
7633 (progn
7634 (setq org-goto-selected-point (point)
7635 org-goto-exit-command 'right)
7636 (throw 'exit nil))
7637 (user-error "Not on a heading")))
7639 (defun org-goto-quit ()
7640 "Finish `org-goto' without cursor motion."
7641 (interactive)
7642 (setq org-goto-selected-point nil)
7643 (setq org-goto-exit-command 'quit)
7644 (throw 'exit nil))
7646 ;;; Indirect buffer display of subtrees
7648 (defvar org-indirect-dedicated-frame nil
7649 "This is the frame being used for indirect tree display.")
7650 (defvar org-last-indirect-buffer nil)
7652 (defun org-tree-to-indirect-buffer (&optional arg)
7653 "Create indirect buffer and narrow it to current subtree.
7655 With a numerical prefix ARG, go up to this level and then take that tree.
7656 If ARG is negative, go up that many levels.
7658 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7659 indirect buffer previously made with this command, to avoid proliferation of
7660 indirect buffers. However, when you call the command with a \
7661 `\\[universal-argument]' prefix, or
7662 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7663 so that you can work with several indirect buffers at the same time. If
7664 `org-indirect-buffer-display' is `dedicated-frame', the \
7665 `\\[universal-argument]' prefix also
7666 requests that a new frame be made for the new buffer, so that the dedicated
7667 frame is not changed."
7668 (interactive "P")
7669 (let ((cbuf (current-buffer))
7670 (cwin (selected-window))
7671 (pos (point))
7672 beg end level heading ibuf)
7673 (save-excursion
7674 (org-back-to-heading t)
7675 (when (numberp arg)
7676 (setq level (org-outline-level))
7677 (when (< arg 0) (setq arg (+ level arg)))
7678 (while (> (setq level (org-outline-level)) arg)
7679 (org-up-heading-safe)))
7680 (setq beg (point)
7681 heading (org-get-heading 'no-tags))
7682 (org-end-of-subtree t t)
7683 (when (org-at-heading-p) (backward-char 1))
7684 (setq end (point)))
7685 (when (and (buffer-live-p org-last-indirect-buffer)
7686 (not (eq org-indirect-buffer-display 'new-frame))
7687 (not arg))
7688 (kill-buffer org-last-indirect-buffer))
7689 (setq ibuf (org-get-indirect-buffer cbuf heading)
7690 org-last-indirect-buffer ibuf)
7691 (cond
7692 ((or (eq org-indirect-buffer-display 'new-frame)
7693 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7694 (select-frame (make-frame))
7695 (delete-other-windows)
7696 (pop-to-buffer-same-window ibuf)
7697 (org-set-frame-title heading))
7698 ((eq org-indirect-buffer-display 'dedicated-frame)
7699 (raise-frame
7700 (select-frame (or (and org-indirect-dedicated-frame
7701 (frame-live-p org-indirect-dedicated-frame)
7702 org-indirect-dedicated-frame)
7703 (setq org-indirect-dedicated-frame (make-frame)))))
7704 (delete-other-windows)
7705 (pop-to-buffer-same-window ibuf)
7706 (org-set-frame-title (concat "Indirect: " heading)))
7707 ((eq org-indirect-buffer-display 'current-window)
7708 (pop-to-buffer-same-window ibuf))
7709 ((eq org-indirect-buffer-display 'other-window)
7710 (pop-to-buffer ibuf))
7711 (t (error "Invalid value")))
7712 (narrow-to-region beg end)
7713 (outline-show-all)
7714 (goto-char pos)
7715 (run-hook-with-args 'org-cycle-hook 'all)
7716 (and (window-live-p cwin) (select-window cwin))))
7718 (defun org-get-indirect-buffer (&optional buffer heading)
7719 (setq buffer (or buffer (current-buffer)))
7720 (let ((n 1) (base (buffer-name buffer)) bname)
7721 (while (buffer-live-p
7722 (get-buffer
7723 (setq bname
7724 (concat base "-"
7725 (if heading (concat heading "-" (number-to-string n))
7726 (number-to-string n))))))
7727 (setq n (1+ n)))
7728 (condition-case nil
7729 (make-indirect-buffer buffer bname 'clone)
7730 (error (make-indirect-buffer buffer bname)))))
7732 (defun org-set-frame-title (title)
7733 "Set the title of the current frame to the string TITLE."
7734 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7736 ;;;; Structure editing
7738 ;;; Inserting headlines
7740 (defun org--line-empty-p (n)
7741 "Is the Nth next line empty?
7743 Counts the current line as N = 1 and the previous line as N = 0;
7744 see `beginning-of-line'."
7745 (save-excursion
7746 (and (not (bobp))
7747 (or (beginning-of-line n) t)
7748 (save-match-data
7749 (looking-at "[ \t]*$")))))
7751 (defun org-previous-line-empty-p ()
7752 "Is the previous line a blank line?
7753 When NEXT is non-nil, check the next line instead."
7754 (org--line-empty-p 0))
7756 (defun org-next-line-empty-p ()
7757 "Is the previous line a blank line?
7758 When NEXT is non-nil, check the next line instead."
7759 (org--line-empty-p 2))
7761 (defun org--blank-before-heading-p (&optional parent)
7762 "Non-nil when an empty line should precede a new heading here.
7763 When optional argument PARENT is non-nil, consider parent
7764 headline instead of current one."
7765 (pcase (assq 'heading org-blank-before-new-entry)
7766 (`(heading . auto)
7767 (save-excursion
7768 (org-with-limited-levels
7769 (unless (and (org-before-first-heading-p)
7770 (not (outline-next-heading)))
7771 (org-back-to-heading t)
7772 (when parent (org-up-heading-safe))
7773 (cond ((not (bobp))
7774 (org-previous-line-empty-p))
7775 ((outline-next-heading)
7776 (org-previous-line-empty-p))
7777 ;; Ignore trailing spaces on last buffer line.
7778 ((progn (skip-chars-backward " \t") (bolp))
7779 (org-previous-line-empty-p))
7780 (t nil))))))
7781 (`(heading . ,value) value)
7782 (_ nil)))
7784 (defun org-insert-heading (&optional arg invisible-ok top)
7785 "Insert a new heading or an item with the same depth at point.
7787 If point is at the beginning of a heading, insert a new heading
7788 or a new headline above the current one. When at the beginning
7789 of a regular line of text, turn it into a heading.
7791 If point is in the middle of a line, split it and create a new
7792 headline with the text in the current line after point (see
7793 `org-M-RET-may-split-line' on how to modify this behavior). As
7794 a special case, on a headline, splitting can only happen on the
7795 title itself. E.g., this excludes breaking stars or tags.
7797 With a `\\[universal-argument]' prefix, set \
7798 `org-insert-heading-respect-content' to
7799 a non-nil value for the duration of the command. This forces the
7800 insertion of a heading after the current subtree, independently
7801 on the location of point.
7803 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7804 insert the heading at the end of the tree
7805 above the current heading. For example, if point is within a
7806 2nd-level heading, then it will insert a 2nd-level heading at
7807 the end of the 1st-level parent subtree.
7809 When INVISIBLE-OK is set, stop at invisible headlines when going
7810 back. This is important for non-interactive uses of the
7811 command.
7813 When optional argument TOP is non-nil, insert a level 1 heading,
7814 unconditionally."
7815 (interactive "P")
7816 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7817 (level (org-current-level))
7818 (stars (make-string (if (and level (not top)) level 1) ?*)))
7819 (cond
7820 ((or org-insert-heading-respect-content
7821 (member arg '((4) (16)))
7822 (and (not invisible-ok)
7823 (invisible-p (max (1- (point)) (point-min)))))
7824 ;; Position point at the location of insertion.
7825 (if (not level) ;before first headline
7826 (org-with-limited-levels (outline-next-heading))
7827 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7828 ;; is nil.
7829 (org-with-limited-levels (org-back-to-heading invisible-ok))
7830 (cond ((equal arg '(16))
7831 (org-up-heading-safe)
7832 (org-end-of-subtree t t))
7834 (org-end-of-subtree t t))))
7835 (unless (bolp) (insert "\n")) ;ensure final newline
7836 (unless (and blank? (org-previous-line-empty-p))
7837 (org-N-empty-lines-before-current (if blank? 1 0)))
7838 (insert stars " \n")
7839 (forward-char -1))
7840 ;; At a headline...
7841 ((org-at-heading-p)
7842 (cond ((bolp)
7843 (when blank? (save-excursion (insert "\n")))
7844 (save-excursion (insert stars " \n"))
7845 (unless (and blank? (org-previous-line-empty-p))
7846 (org-N-empty-lines-before-current (if blank? 1 0)))
7847 (end-of-line))
7848 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7849 (org-match-line org-complex-heading-regexp)
7850 (org-pos-in-match-range (point) 4))
7851 ;; Grab the text that should moved to the new headline.
7852 ;; Preserve tags.
7853 (let ((split (delete-and-extract-region (point) (match-end 4))))
7854 (if (looking-at "[ \t]*$") (replace-match "")
7855 (org-set-tags nil t))
7856 (end-of-line)
7857 (when blank? (insert "\n"))
7858 (insert "\n" stars " ")
7859 (when (org-string-nw-p split) (insert split))
7860 (when (eobp) (save-excursion (insert "\n")))))
7862 (end-of-line)
7863 (when blank? (insert "\n"))
7864 (insert "\n" stars " ")
7865 (when (eobp) (save-excursion (insert "\n"))))))
7866 ;; On regular text, turn line into a headline or split, if
7867 ;; appropriate.
7868 ((bolp)
7869 (insert stars " ")
7870 (unless (and blank? (org-previous-line-empty-p))
7871 (org-N-empty-lines-before-current (if blank? 1 0))))
7873 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7874 (end-of-line))
7875 (insert "\n" stars " ")
7876 (unless (and blank? (org-previous-line-empty-p))
7877 (org-N-empty-lines-before-current (if blank? 1 0))))))
7878 (run-hooks 'org-insert-heading-hook))
7880 (defun org-N-empty-lines-before-current (n)
7881 "Make the number of empty lines before current exactly N.
7882 So this will delete or add empty lines."
7883 (let ((column (current-column))
7884 (empty-lines (make-string n ?\n)))
7885 (beginning-of-line)
7886 (let ((p (point)))
7887 (skip-chars-backward " \r\t\n")
7888 (unless (bolp) (forward-line))
7889 (delete-region (point) p))
7890 (insert empty-lines)
7891 (move-to-column column)))
7893 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7894 "Return the heading of the current entry, without the stars.
7895 When NO-TAGS is non-nil, don't include tags.
7896 When NO-TODO is non-nil, don't include TODO keywords.
7897 When NO-PRIORITY is non-nil, don't include priority cookie.
7898 When NO-COMMENT is non-nil, don't include COMMENT string."
7899 (save-excursion
7900 (org-back-to-heading t)
7901 (let ((case-fold-search nil))
7902 (looking-at org-complex-heading-regexp)
7903 (let ((todo (and (not no-todo) (match-string 2)))
7904 (priority (and (not no-priority) (match-string 3)))
7905 (headline (pcase (match-string 4)
7906 (`nil "")
7907 ((and (guard no-comment) h)
7908 (replace-regexp-in-string
7909 (eval-when-compile
7910 (format "\\`%s[ \t]+" org-comment-string))
7911 "" h))
7912 (h h)))
7913 (tags (and (not no-tags) (match-string 5))))
7914 (mapconcat #'identity
7915 (delq nil (list todo priority headline tags))
7916 " ")))))
7918 (defvar orgstruct-mode) ; defined below
7920 (defun org-heading-components ()
7921 "Return the components of the current heading.
7922 This is a list with the following elements:
7923 - the level as an integer
7924 - the reduced level, different if `org-odd-levels-only' is set.
7925 - the TODO keyword, or nil
7926 - the priority character, like ?A, or nil if no priority is given
7927 - the headline text itself, or the tags string if no headline text
7928 - the tags string, or nil."
7929 (save-excursion
7930 (org-back-to-heading t)
7931 (when (let (case-fold-search)
7932 (looking-at
7933 (if orgstruct-mode
7934 org-heading-regexp
7935 org-complex-heading-regexp)))
7936 (if orgstruct-mode
7937 (list (length (match-string 1))
7938 (org-reduced-level (length (match-string 1)))
7941 (match-string 2)
7942 nil)
7943 (list (length (match-string 1))
7944 (org-reduced-level (length (match-string 1)))
7945 (match-string-no-properties 2)
7946 (and (match-end 3) (aref (match-string 3) 2))
7947 (match-string-no-properties 4)
7948 (match-string-no-properties 5))))))
7950 (defun org-get-entry ()
7951 "Get the entry text, after heading, entire subtree."
7952 (save-excursion
7953 (org-back-to-heading t)
7954 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7956 (defun org-edit-headline (&optional heading)
7957 "Edit the current headline.
7958 Set it to HEADING when provided."
7959 (interactive)
7960 (org-with-wide-buffer
7961 (org-back-to-heading t)
7962 (let ((case-fold-search nil))
7963 (when (looking-at org-complex-heading-regexp)
7964 (let* ((old (match-string-no-properties 4))
7965 (new (save-match-data
7966 (org-trim (or heading (read-string "Edit: " old))))))
7967 (unless (equal old new)
7968 (if old (replace-match new t t nil 4)
7969 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7970 (insert " " new))
7971 (org-set-tags nil t)
7972 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7974 (defun org-insert-heading-after-current ()
7975 "Insert a new heading with same level as current, after current subtree."
7976 (interactive)
7977 (org-back-to-heading)
7978 (org-insert-heading)
7979 (org-move-subtree-down)
7980 (end-of-line 1))
7982 (defun org-insert-heading-respect-content (&optional invisible-ok)
7983 "Insert heading with `org-insert-heading-respect-content' set to t."
7984 (interactive)
7985 (org-insert-heading '(4) invisible-ok))
7987 (defun org-insert-todo-heading-respect-content (&optional force-state)
7988 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7989 (interactive)
7990 (org-insert-todo-heading force-state '(4)))
7992 (defun org-insert-todo-heading (arg &optional force-heading)
7993 "Insert a new heading with the same level and TODO state as current heading.
7995 If the heading has no TODO state, or if the state is DONE, use
7996 the first state (TODO by default). Also with one prefix arg,
7997 force first state. With two prefix args, force inserting at the
7998 end of the parent subtree.
8000 When called at a plain list item, insert a new item with an
8001 unchecked check box."
8002 (interactive "P")
8003 (when (or force-heading (not (org-insert-item 'checkbox)))
8004 (org-insert-heading (or (and (equal arg '(16)) '(16))
8005 force-heading))
8006 (save-excursion
8007 (org-back-to-heading)
8008 (outline-previous-heading)
8009 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8010 (let* ((new-mark-x
8011 (if (or (equal arg '(4))
8012 (not (match-beginning 2))
8013 (member (match-string 2) org-done-keywords))
8014 (car org-todo-keywords-1)
8015 (match-string 2)))
8016 (new-mark
8018 (run-hook-with-args-until-success
8019 'org-todo-get-default-hook new-mark-x nil)
8020 new-mark-x)))
8021 (beginning-of-line 1)
8022 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8023 (if org-treat-insert-todo-heading-as-state-change
8024 (org-todo new-mark)
8025 (insert new-mark " "))))
8026 (when org-provide-todo-statistics
8027 (org-update-parent-todo-statistics))))
8029 (defun org-insert-subheading (arg)
8030 "Insert a new subheading and demote it.
8031 Works for outline headings and for plain lists alike."
8032 (interactive "P")
8033 (org-insert-heading arg)
8034 (cond
8035 ((org-at-heading-p) (org-do-demote))
8036 ((org-at-item-p) (org-indent-item))))
8038 (defun org-insert-todo-subheading (arg)
8039 "Insert a new subheading with TODO keyword or checkbox and demote it.
8040 Works for outline headings and for plain lists alike."
8041 (interactive "P")
8042 (org-insert-todo-heading arg)
8043 (cond
8044 ((org-at-heading-p) (org-do-demote))
8045 ((org-at-item-p) (org-indent-item))))
8047 ;;; Promotion and Demotion
8049 (defvar org-after-demote-entry-hook nil
8050 "Hook run after an entry has been demoted.
8051 The cursor will be at the beginning of the entry.
8052 When a subtree is being demoted, the hook will be called for each node.")
8054 (defvar org-after-promote-entry-hook nil
8055 "Hook run after an entry has been promoted.
8056 The cursor will be at the beginning of the entry.
8057 When a subtree is being promoted, the hook will be called for each node.")
8059 (defun org-promote-subtree ()
8060 "Promote the entire subtree.
8061 See also `org-promote'."
8062 (interactive)
8063 (save-excursion
8064 (org-with-limited-levels (org-map-tree 'org-promote)))
8065 (org-fix-position-after-promote))
8067 (defun org-demote-subtree ()
8068 "Demote the entire subtree.
8069 See `org-demote' and `org-promote'."
8070 (interactive)
8071 (save-excursion
8072 (org-with-limited-levels (org-map-tree 'org-demote)))
8073 (org-fix-position-after-promote))
8075 (defun org-do-promote ()
8076 "Promote the current heading higher up the tree.
8077 If the region is active in `transient-mark-mode', promote all
8078 headings in the region."
8079 (interactive)
8080 (save-excursion
8081 (if (org-region-active-p)
8082 (org-map-region 'org-promote (region-beginning) (region-end))
8083 (org-promote)))
8084 (org-fix-position-after-promote))
8086 (defun org-do-demote ()
8087 "Demote the current heading lower down the tree.
8088 If the region is active in `transient-mark-mode', demote all
8089 headings in the region."
8090 (interactive)
8091 (save-excursion
8092 (if (org-region-active-p)
8093 (org-map-region 'org-demote (region-beginning) (region-end))
8094 (org-demote)))
8095 (org-fix-position-after-promote))
8097 (defun org-fix-position-after-promote ()
8098 "Fix cursor position and indentation after demoting/promoting."
8099 (let ((pos (point)))
8100 (when (save-excursion
8101 (beginning-of-line)
8102 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8103 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8104 (cond ((eobp) (insert " "))
8105 ((eolp) (insert " "))
8106 ((equal (char-after) ?\s) (forward-char 1))))))
8108 (defun org-current-level ()
8109 "Return the level of the current entry, or nil if before the first headline.
8110 The level is the number of stars at the beginning of the
8111 headline. Use `org-reduced-level' to remove the effect of
8112 `org-odd-levels'. Unlike to `org-outline-level', this function
8113 ignores inlinetasks."
8114 (let ((level (org-with-limited-levels (org-outline-level))))
8115 (and (> level 0) level)))
8117 (defun org-get-previous-line-level ()
8118 "Return the outline depth of the last headline before the current line.
8119 Returns 0 for the first headline in the buffer, and nil if before the
8120 first headline."
8121 (and (org-current-level)
8122 (or (and (/= (line-beginning-position) (point-min))
8123 (save-excursion (beginning-of-line 0) (org-current-level)))
8124 0)))
8126 (defun org-reduced-level (l)
8127 "Compute the effective level of a heading.
8128 This takes into account the setting of `org-odd-levels-only'."
8129 (cond
8130 ((zerop l) 0)
8131 (org-odd-levels-only (1+ (floor (/ l 2))))
8132 (t l)))
8134 (defun org-level-increment ()
8135 "Return the number of stars that will be added or removed at a
8136 time to headlines when structure editing, based on the value of
8137 `org-odd-levels-only'."
8138 (if org-odd-levels-only 2 1))
8140 (defun org-get-valid-level (level &optional change)
8141 "Rectify a level change under the influence of `org-odd-levels-only'.
8142 LEVEL is a current level, CHANGE is by how much the level should
8143 be modified. Even if CHANGE is nil, LEVEL may be returned
8144 modified because even level numbers will become the next higher
8145 odd number. Returns values greater than 0."
8146 (if org-odd-levels-only
8147 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8148 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8149 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8150 (max 1 (+ level (or change 0)))))
8152 (defun org-promote ()
8153 "Promote the current heading higher up the tree."
8154 (org-with-wide-buffer
8155 (org-back-to-heading t)
8156 (let* ((after-change-functions (remq 'flyspell-after-change-function
8157 after-change-functions))
8158 (level (save-match-data (funcall outline-level)))
8159 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8160 (diff (abs (- level (length up-head) -1))))
8161 (cond
8162 ((and (= level 1) org-allow-promoting-top-level-subtree)
8163 (replace-match "# " nil t))
8164 ((= level 1)
8165 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8166 (t (replace-match up-head nil t)))
8167 (unless (= level 1)
8168 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8169 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8170 (run-hooks 'org-after-promote-entry-hook))))
8172 (defun org-demote ()
8173 "Demote the current heading lower down the tree."
8174 (org-with-wide-buffer
8175 (org-back-to-heading t)
8176 (let* ((after-change-functions (remq 'flyspell-after-change-function
8177 after-change-functions))
8178 (level (save-match-data (funcall outline-level)))
8179 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8180 (diff (abs (- level (length down-head) -1))))
8181 (replace-match down-head nil t)
8182 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8183 (when org-adapt-indentation (org-fixup-indentation diff))
8184 (run-hooks 'org-after-demote-entry-hook))))
8186 (defun org-cycle-level ()
8187 "Cycle the level of an empty headline through possible states.
8188 This goes first to child, then to parent, level, then up the hierarchy.
8189 After top level, it switches back to sibling level."
8190 (interactive)
8191 (let ((org-adapt-indentation nil))
8192 (when (org-point-at-end-of-empty-headline)
8193 (setq this-command 'org-cycle-level) ; Only needed for caching
8194 (let ((cur-level (org-current-level))
8195 (prev-level (org-get-previous-line-level)))
8196 (cond
8197 ;; If first headline in file, promote to top-level.
8198 ((= prev-level 0)
8199 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8200 do (org-do-promote)))
8201 ;; If same level as prev, demote one.
8202 ((= prev-level cur-level)
8203 (org-do-demote))
8204 ;; If parent is top-level, promote to top level if not already.
8205 ((= prev-level 1)
8206 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8207 do (org-do-promote)))
8208 ;; If top-level, return to prev-level.
8209 ((= cur-level 1)
8210 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8211 do (org-do-demote)))
8212 ;; If less than prev-level, promote one.
8213 ((< cur-level prev-level)
8214 (org-do-promote))
8215 ;; If deeper than prev-level, promote until higher than
8216 ;; prev-level.
8217 ((> cur-level prev-level)
8218 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8219 do (org-do-promote))))
8220 t))))
8222 (defun org-map-tree (fun)
8223 "Call FUN for every heading underneath the current one."
8224 (org-back-to-heading t)
8225 (let ((level (funcall outline-level)))
8226 (save-excursion
8227 (funcall fun)
8228 (while (and (progn
8229 (outline-next-heading)
8230 (> (funcall outline-level) level))
8231 (not (eobp)))
8232 (funcall fun)))))
8234 (defun org-map-region (fun beg end)
8235 "Call FUN for every heading between BEG and END."
8236 (let ((org-ignore-region t))
8237 (save-excursion
8238 (setq end (copy-marker end))
8239 (goto-char beg)
8240 (when (and (re-search-forward org-outline-regexp-bol nil t)
8241 (< (point) end))
8242 (funcall fun))
8243 (while (and (progn
8244 (outline-next-heading)
8245 (< (point) end))
8246 (not (eobp)))
8247 (funcall fun)))))
8249 (defun org-fixup-indentation (diff)
8250 "Change the indentation in the current entry by DIFF.
8252 DIFF is an integer. Indentation is done according to the
8253 following rules:
8255 - Planning information and property drawers are always indented
8256 according to the new level of the headline;
8258 - Footnote definitions and their contents are ignored;
8260 - Inlinetasks' boundaries are not shifted;
8262 - Empty lines are ignored;
8264 - Other lines' indentation are shifted by DIFF columns, unless
8265 it would introduce a structural change in the document, in
8266 which case no shifting is done at all.
8268 Assume point is at a heading or an inlinetask beginning."
8269 (org-with-wide-buffer
8270 (narrow-to-region (line-beginning-position)
8271 (save-excursion
8272 (if (org-with-limited-levels (org-at-heading-p))
8273 (org-with-limited-levels (outline-next-heading))
8274 (org-inlinetask-goto-end))
8275 (point)))
8276 (forward-line)
8277 ;; Indent properly planning info and property drawer.
8278 (when (looking-at-p org-planning-line-re)
8279 (org-indent-line)
8280 (forward-line))
8281 (when (looking-at org-property-drawer-re)
8282 (goto-char (match-end 0))
8283 (forward-line)
8284 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8285 (catch 'no-shift
8286 (when (zerop diff) (throw 'no-shift nil))
8287 ;; If DIFF is negative, first check if a shift is possible at all
8288 ;; (e.g., it doesn't break structure). This can only happen if
8289 ;; some contents are not properly indented.
8290 (let ((case-fold-search t))
8291 (when (< diff 0)
8292 (let ((diff (- diff))
8293 (forbidden-re (concat org-outline-regexp
8294 "\\|"
8295 (substring org-footnote-definition-re 1))))
8296 (save-excursion
8297 (while (not (eobp))
8298 (cond
8299 ((looking-at-p "[ \t]*$") (forward-line))
8300 ((and (looking-at-p org-footnote-definition-re)
8301 (let ((e (org-element-at-point)))
8302 (and (eq (org-element-type e) 'footnote-definition)
8303 (goto-char (org-element-property :end e))))))
8304 ((looking-at-p org-outline-regexp) (forward-line))
8305 ;; Give up if shifting would move before column 0 or
8306 ;; if it would introduce a headline or a footnote
8307 ;; definition.
8309 (skip-chars-forward " \t")
8310 (let ((ind (current-column)))
8311 (when (or (< ind diff)
8312 (and (= ind diff) (looking-at-p forbidden-re)))
8313 (throw 'no-shift nil)))
8314 ;; Ignore contents of example blocks and source
8315 ;; blocks if their indentation is meant to be
8316 ;; preserved. Jump to block's closing line.
8317 (beginning-of-line)
8318 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8319 (let ((e (org-element-at-point)))
8320 (and (memq (org-element-type e)
8321 '(example-block src-block))
8322 (or org-src-preserve-indentation
8323 (org-element-property :preserve-indent e))
8324 (goto-char (org-element-property :end e))
8325 (progn (skip-chars-backward " \r\t\n")
8326 (beginning-of-line)
8327 t))))
8328 (forward-line))))))))
8329 ;; Shift lines but footnote definitions, inlinetasks boundaries
8330 ;; by DIFF. Also skip contents of source or example blocks
8331 ;; when indentation is meant to be preserved.
8332 (while (not (eobp))
8333 (cond
8334 ((and (looking-at-p org-footnote-definition-re)
8335 (let ((e (org-element-at-point)))
8336 (and (eq (org-element-type e) 'footnote-definition)
8337 (goto-char (org-element-property :end e))))))
8338 ((looking-at-p org-outline-regexp) (forward-line))
8339 ((looking-at-p "[ \t]*$") (forward-line))
8341 (indent-line-to (+ (org-get-indentation) diff))
8342 (beginning-of-line)
8343 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8344 (let ((e (org-element-at-point)))
8345 (and (memq (org-element-type e)
8346 '(example-block src-block))
8347 (or org-src-preserve-indentation
8348 (org-element-property :preserve-indent e))
8349 (goto-char (org-element-property :end e))
8350 (progn (skip-chars-backward " \r\t\n")
8351 (beginning-of-line)
8352 t))))
8353 (forward-line)))))))))
8355 (defun org-convert-to-odd-levels ()
8356 "Convert an Org file with all levels allowed to one with odd levels.
8357 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8358 level 5 etc."
8359 (interactive)
8360 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8361 (let ((outline-level 'org-outline-level)
8362 (org-odd-levels-only nil) n)
8363 (save-excursion
8364 (goto-char (point-min))
8365 (while (re-search-forward "^\\*\\*+ " nil t)
8366 (setq n (- (length (match-string 0)) 2))
8367 (while (>= (setq n (1- n)) 0)
8368 (org-demote))
8369 (end-of-line 1))))))
8371 (defun org-convert-to-oddeven-levels ()
8372 "Convert an Org file with only odd levels to one with odd/even levels.
8373 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8374 file contains a section with an even level, conversion would
8375 destroy the structure of the file. An error is signaled in this
8376 case."
8377 (interactive)
8378 (goto-char (point-min))
8379 ;; First check if there are no even levels
8380 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8381 (org-show-set-visibility 'canonical)
8382 (error "Not all levels are odd in this file. Conversion not possible"))
8383 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8384 (let ((outline-regexp org-outline-regexp)
8385 (outline-level 'org-outline-level)
8386 (org-odd-levels-only nil) n)
8387 (save-excursion
8388 (goto-char (point-min))
8389 (while (re-search-forward "^\\*\\*+ " nil t)
8390 (setq n (/ (1- (length (match-string 0))) 2))
8391 (while (>= (setq n (1- n)) 0)
8392 (org-promote))
8393 (end-of-line 1))))))
8395 (defun org-tr-level (n)
8396 "Make N odd if required."
8397 (if org-odd-levels-only (1+ (/ n 2)) n))
8399 ;;; Vertical tree motion, cutting and pasting of subtrees
8401 (defun org-move-subtree-up (&optional arg)
8402 "Move the current subtree up past ARG headlines of the same level."
8403 (interactive "p")
8404 (org-move-subtree-down (- (prefix-numeric-value arg))))
8406 (defun org-move-subtree-down (&optional arg)
8407 "Move the current subtree down past ARG headlines of the same level."
8408 (interactive "p")
8409 (setq arg (prefix-numeric-value arg))
8410 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8411 'org-get-last-sibling))
8412 (ins-point (make-marker))
8413 (cnt (abs arg))
8414 (col (current-column))
8415 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8416 ;; Select the tree
8417 (org-back-to-heading)
8418 (setq beg0 (point))
8419 (save-excursion
8420 (setq ne-beg (org-back-over-empty-lines))
8421 (setq beg (point)))
8422 (save-match-data
8423 (save-excursion (outline-end-of-heading)
8424 (setq folded (outline-invisible-p)))
8425 (progn (org-end-of-subtree nil t)
8426 (unless (eobp) (backward-char))))
8427 (outline-next-heading)
8428 (setq ne-end (org-back-over-empty-lines))
8429 (setq end (point))
8430 (goto-char beg0)
8431 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8432 ;; include less whitespace
8433 (save-excursion
8434 (goto-char beg)
8435 (forward-line (- ne-beg ne-end))
8436 (setq beg (point))))
8437 ;; Find insertion point, with error handling
8438 (while (> cnt 0)
8439 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8440 (progn (goto-char beg0)
8441 (user-error "Cannot move past superior level or buffer limit")))
8442 (setq cnt (1- cnt)))
8443 (when (> arg 0)
8444 ;; Moving forward - still need to move over subtree
8445 (org-end-of-subtree t t)
8446 (save-excursion
8447 (org-back-over-empty-lines)
8448 (or (bolp) (newline))))
8449 (setq ne-ins (org-back-over-empty-lines))
8450 (move-marker ins-point (point))
8451 (setq txt (buffer-substring beg end))
8452 (org-save-markers-in-region beg end)
8453 (delete-region beg end)
8454 (org-remove-empty-overlays-at beg)
8455 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8456 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8457 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8458 (let ((bbb (point)))
8459 (insert-before-markers txt)
8460 (org-reinstall-markers-in-region bbb)
8461 (move-marker ins-point bbb))
8462 (or (bolp) (insert "\n"))
8463 (setq ins-end (point))
8464 (goto-char ins-point)
8465 (org-skip-whitespace)
8466 (when (and (< arg 0)
8467 (org-first-sibling-p)
8468 (> ne-ins ne-beg))
8469 ;; Move whitespace back to beginning
8470 (save-excursion
8471 (goto-char ins-end)
8472 (let ((kill-whole-line t))
8473 (kill-line (- ne-ins ne-beg)) (point)))
8474 (insert (make-string (- ne-ins ne-beg) ?\n)))
8475 (move-marker ins-point nil)
8476 (if folded
8477 (outline-hide-subtree)
8478 (org-show-entry)
8479 (org-show-children)
8480 (org-cycle-hide-drawers 'children))
8481 (org-clean-visibility-after-subtree-move)
8482 ;; move back to the initial column we were at
8483 (move-to-column col)))
8485 (defvar org-subtree-clip ""
8486 "Clipboard for cut and paste of subtrees.
8487 This is actually only a copy of the kill, because we use the normal kill
8488 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8490 (defvar org-subtree-clip-folded nil
8491 "Was the last copied subtree folded?
8492 This is used to fold the tree back after pasting.")
8494 (defun org-cut-subtree (&optional n)
8495 "Cut the current subtree into the clipboard.
8496 With prefix arg N, cut this many sequential subtrees.
8497 This is a short-hand for marking the subtree and then cutting it."
8498 (interactive "p")
8499 (org-copy-subtree n 'cut))
8501 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8502 "Copy the current subtree it in the clipboard.
8503 With prefix arg N, copy this many sequential subtrees.
8504 This is a short-hand for marking the subtree and then copying it.
8505 If CUT is non-nil, actually cut the subtree.
8506 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8507 of some markers in the region, even if CUT is non-nil. This is
8508 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8509 (interactive "p")
8510 (let (beg end folded (beg0 (point)))
8511 (if (called-interactively-p 'any)
8512 (org-back-to-heading nil) ; take what looks like a subtree
8513 (org-back-to-heading t)) ; take what is really there
8514 (setq beg (point))
8515 (skip-chars-forward " \t\r\n")
8516 (save-match-data
8517 (if nosubtrees
8518 (outline-next-heading)
8519 (save-excursion (outline-end-of-heading)
8520 (setq folded (outline-invisible-p)))
8521 (ignore-errors (org-forward-heading-same-level (1- n) t))
8522 (org-end-of-subtree t t)))
8523 ;; Include the end of an inlinetask
8524 (when (and (featurep 'org-inlinetask)
8525 (looking-at-p (concat (org-inlinetask-outline-regexp)
8526 "END[ \t]*$")))
8527 (end-of-line))
8528 (setq end (point))
8529 (goto-char beg0)
8530 (when (> end beg)
8531 (setq org-subtree-clip-folded folded)
8532 (when (or cut force-store-markers)
8533 (org-save-markers-in-region beg end))
8534 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8535 (setq org-subtree-clip (current-kill 0))
8536 (message "%s: Subtree(s) with %d characters"
8537 (if cut "Cut" "Copied")
8538 (length org-subtree-clip)))))
8540 (defun org-paste-subtree (&optional level tree for-yank remove)
8541 "Paste the clipboard as a subtree, with modification of headline level.
8542 The entire subtree is promoted or demoted in order to match a new headline
8543 level.
8545 If the cursor is at the beginning of a headline, the same level as
8546 that headline is used to paste the tree.
8548 If not, the new level is derived from the *visible* headings
8549 before and after the insertion point, and taken to be the inferior headline
8550 level of the two. So if the previous visible heading is level 3 and the
8551 next is level 4 (or vice versa), level 4 will be used for insertion.
8552 This makes sure that the subtree remains an independent subtree and does
8553 not swallow low level entries.
8555 You can also force a different level, either by using a numeric prefix
8556 argument, or by inserting the heading marker by hand. For example, if the
8557 cursor is after \"*****\", then the tree will be shifted to level 5.
8559 If optional TREE is given, use this text instead of the kill ring.
8561 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8562 move back over whitespace before inserting, and move point to the end of
8563 the inserted text when done.
8565 When REMOVE is non-nil, remove the subtree from the clipboard."
8566 (interactive "P")
8567 (setq tree (or tree (and kill-ring (current-kill 0))))
8568 (unless (org-kill-is-subtree-p tree)
8569 (user-error "%s"
8570 (substitute-command-keys
8571 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8572 (org-with-limited-levels
8573 (let* ((visp (not (outline-invisible-p)))
8574 (txt tree)
8575 (^re_ "\\(\\*+\\)[ \t]*")
8576 (old-level (if (string-match org-outline-regexp-bol txt)
8577 (- (match-end 0) (match-beginning 0) 1)
8578 -1))
8579 (force-level (cond (level (prefix-numeric-value level))
8580 ((and (looking-at "[ \t]*$")
8581 (string-match
8582 "^\\*+$" (buffer-substring
8583 (point-at-bol) (point))))
8584 (- (match-end 0) (match-beginning 0)))
8585 ((and (bolp)
8586 (looking-at org-outline-regexp))
8587 (- (match-end 0) (point) 1))))
8588 (previous-level (save-excursion
8589 (condition-case nil
8590 (progn
8591 (outline-previous-visible-heading 1)
8592 (if (looking-at ^re_)
8593 (- (match-end 0) (match-beginning 0) 1)
8595 (error 1))))
8596 (next-level (save-excursion
8597 (condition-case nil
8598 (progn
8599 (or (looking-at org-outline-regexp)
8600 (outline-next-visible-heading 1))
8601 (if (looking-at ^re_)
8602 (- (match-end 0) (match-beginning 0) 1)
8604 (error 1))))
8605 (new-level (or force-level (max previous-level next-level)))
8606 (shift (if (or (= old-level -1)
8607 (= new-level -1)
8608 (= old-level new-level))
8610 (- new-level old-level)))
8611 (delta (if (> shift 0) -1 1))
8612 (func (if (> shift 0) 'org-demote 'org-promote))
8613 (org-odd-levels-only nil)
8614 beg end newend)
8615 ;; Remove the forced level indicator
8616 (when force-level
8617 (delete-region (point-at-bol) (point)))
8618 ;; Paste
8619 (beginning-of-line (if (bolp) 1 2))
8620 (setq beg (point))
8621 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8622 (insert-before-markers txt)
8623 (unless (string-suffix-p "\n" txt) (insert "\n"))
8624 (setq newend (point))
8625 (org-reinstall-markers-in-region beg)
8626 (setq end (point))
8627 (goto-char beg)
8628 (skip-chars-forward " \t\n\r")
8629 (setq beg (point))
8630 (when (and (outline-invisible-p) visp)
8631 (save-excursion (outline-show-heading)))
8632 ;; Shift if necessary
8633 (unless (= shift 0)
8634 (save-restriction
8635 (narrow-to-region beg end)
8636 (while (not (= shift 0))
8637 (org-map-region func (point-min) (point-max))
8638 (setq shift (+ delta shift)))
8639 (goto-char (point-min))
8640 (setq newend (point-max))))
8641 (when (or (called-interactively-p 'interactive) for-yank)
8642 (message "Clipboard pasted as level %d subtree" new-level))
8643 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8644 kill-ring
8645 (eq org-subtree-clip (current-kill 0))
8646 org-subtree-clip-folded)
8647 ;; The tree was folded before it was killed/copied
8648 (outline-hide-subtree))
8649 (and for-yank (goto-char newend))
8650 (and remove (setq kill-ring (cdr kill-ring))))))
8652 (defun org-kill-is-subtree-p (&optional txt)
8653 "Check if the current kill is an outline subtree, or a set of trees.
8654 Returns nil if kill does not start with a headline, or if the first
8655 headline level is not the largest headline level in the tree.
8656 So this will actually accept several entries of equal levels as well,
8657 which is OK for `org-paste-subtree'.
8658 If optional TXT is given, check this string instead of the current kill."
8659 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8660 (re (org-get-limited-outline-regexp))
8661 (^re (concat "^" re))
8662 (start-level (and kill
8663 (string-match
8664 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8665 kill)
8666 (- (match-end 2) (match-beginning 2) 1)))
8667 (start (1+ (or (match-beginning 2) -1))))
8668 (if (not start-level)
8669 (progn
8670 nil) ;; does not even start with a heading
8671 (catch 'exit
8672 (while (setq start (string-match ^re kill (1+ start)))
8673 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8674 (throw 'exit nil)))
8675 t))))
8677 (defvar org-markers-to-move nil
8678 "Markers that should be moved with a cut-and-paste operation.
8679 Those markers are stored together with their positions relative to
8680 the start of the region.")
8682 (defun org-save-markers-in-region (beg end)
8683 "Check markers in region.
8684 If these markers are between BEG and END, record their position relative
8685 to BEG, so that after moving the block of text, we can put the markers back
8686 into place.
8687 This function gets called just before an entry or tree gets cut from the
8688 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8689 called immediately, to move the markers with the entries."
8690 (setq org-markers-to-move nil)
8691 (when (featurep 'org-clock)
8692 (org-clock-save-markers-for-cut-and-paste beg end))
8693 (when (featurep 'org-agenda)
8694 (org-agenda-save-markers-for-cut-and-paste beg end)))
8696 (defun org-check-and-save-marker (marker beg end)
8697 "Check if MARKER is between BEG and END.
8698 If yes, remember the marker and the distance to BEG."
8699 (when (and (marker-buffer marker)
8700 (equal (marker-buffer marker) (current-buffer))
8701 (>= marker beg) (< marker end))
8702 (push (cons marker (- marker beg)) org-markers-to-move)))
8704 (defun org-reinstall-markers-in-region (beg)
8705 "Move all remembered markers to their position relative to BEG."
8706 (dolist (x org-markers-to-move)
8707 (move-marker (car x) (+ beg (cdr x))))
8708 (setq org-markers-to-move nil))
8710 (defun org-narrow-to-subtree ()
8711 "Narrow buffer to the current subtree."
8712 (interactive)
8713 (save-excursion
8714 (save-match-data
8715 (org-with-limited-levels
8716 (narrow-to-region
8717 (progn (org-back-to-heading t) (point))
8718 (progn (org-end-of-subtree t t)
8719 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8720 (point)))))))
8722 (defun org-narrow-to-block ()
8723 "Narrow buffer to the current block."
8724 (interactive)
8725 (let* ((case-fold-search t)
8726 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8727 "^[ \t]*#\\+end_.*")))
8728 (if blockp
8729 (narrow-to-region (car blockp) (cdr blockp))
8730 (user-error "Not in a block"))))
8732 (defun org-clone-subtree-with-time-shift (n &optional shift)
8733 "Clone the task (subtree) at point N times.
8734 The clones will be inserted as siblings.
8736 In interactive use, the user will be prompted for the number of
8737 clones to be produced. If the entry has a timestamp, the user
8738 will also be prompted for a time shift, which may be a repeater
8739 as used in time stamps, for example `+3d'. To disable this,
8740 you can call the function with a universal prefix argument.
8742 When a valid repeater is given and the entry contains any time
8743 stamps, the clones will become a sequence in time, with time
8744 stamps in the subtree shifted for each clone produced. If SHIFT
8745 is nil or the empty string, time stamps will be left alone. The
8746 ID property of the original subtree is removed.
8748 In each clone, all the CLOCK entries will be removed. This
8749 prevents Org from considering that the clocked times overlap.
8751 If the original subtree did contain time stamps with a repeater,
8752 the following will happen:
8753 - the repeater will be removed in each clone
8754 - an additional clone will be produced, with the current, unshifted
8755 date(s) in the entry.
8756 - the original entry will be placed *after* all the clones, with
8757 repeater intact.
8758 - the start days in the repeater in the original entry will be shifted
8759 to past the last clone.
8760 In this way you can spell out a number of instances of a repeating task,
8761 and still retain the repeater to cover future instances of the task.
8763 As described above, N+1 clones are produced when the original
8764 subtree has a repeater. Setting N to 0, then, can be used to
8765 remove the repeater from a subtree and create a shifted clone
8766 with the original repeater."
8767 (interactive "nNumber of clones to produce: ")
8768 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8769 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8770 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8771 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8772 (shift
8773 (or shift
8774 (if (and (not (equal current-prefix-arg '(4)))
8775 (save-excursion
8776 (goto-char beg)
8777 (re-search-forward org-ts-regexp-both end-of-tree t)))
8778 (read-from-minibuffer
8779 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8780 ""))) ;No time shift
8781 (doshift
8782 (and (org-string-nw-p shift)
8783 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8784 shift)
8785 (user-error "Invalid shift specification %s" shift)))))
8786 (goto-char end-of-tree)
8787 (unless (bolp) (insert "\n"))
8788 (let* ((end (point))
8789 (template (buffer-substring beg end))
8790 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8791 (shift-what (pcase (and doshift (match-string 2 shift))
8792 (`nil nil)
8793 ("d" 'day)
8794 ("w" (setq shift-n (* 7 shift-n)) 'day)
8795 ("m" 'month)
8796 ("y" 'year)
8797 (_ (error "Unsupported time unit"))))
8798 (nmin 1)
8799 (nmax n)
8800 (n-no-remove -1)
8801 (idprop (org-entry-get nil "ID")))
8802 (when (and doshift
8803 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8804 template))
8805 (delete-region beg end)
8806 (setq end beg)
8807 (setq nmin 0)
8808 (setq nmax (1+ nmax))
8809 (setq n-no-remove nmax))
8810 (goto-char end)
8811 (cl-loop for n from nmin to nmax do
8812 (insert
8813 ;; Prepare clone.
8814 (with-temp-buffer
8815 (insert template)
8816 (org-mode)
8817 (goto-char (point-min))
8818 (org-show-subtree)
8819 (and idprop (if org-clone-delete-id
8820 (org-entry-delete nil "ID")
8821 (org-id-get-create t)))
8822 (unless (= n 0)
8823 (while (re-search-forward org-clock-line-re nil t)
8824 (delete-region (line-beginning-position)
8825 (line-beginning-position 2)))
8826 (goto-char (point-min))
8827 (while (re-search-forward org-drawer-regexp nil t)
8828 (org-remove-empty-drawer-at (point))))
8829 (goto-char (point-min))
8830 (when doshift
8831 (while (re-search-forward org-ts-regexp-both nil t)
8832 (org-timestamp-change (* n shift-n) shift-what))
8833 (unless (= n n-no-remove)
8834 (goto-char (point-min))
8835 (while (re-search-forward org-ts-regexp nil t)
8836 (save-excursion
8837 (goto-char (match-beginning 0))
8838 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8839 (delete-region (match-beginning 1) (match-end 1)))))))
8840 (buffer-string)))))
8841 (goto-char beg)))
8843 ;;; Outline Sorting
8845 (defun org-sort (with-case)
8846 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8847 Optional argument WITH-CASE means sort case-sensitively."
8848 (interactive "P")
8849 (cond
8850 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8851 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8853 (org-call-with-arg 'org-sort-entries with-case))))
8855 (defun org-sort-remove-invisible (s)
8856 "Remove invisible part of links and emphasis markers from string S."
8857 (remove-text-properties 0 (length s) org-rm-props s)
8858 (replace-regexp-in-string
8859 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8860 (replace-regexp-in-string
8861 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8862 (org-link-display-format s)
8863 t t) t t))
8865 (defvar org-priority-regexp) ; defined later in the file
8867 (defvar org-after-sorting-entries-or-items-hook nil
8868 "Hook that is run after a bunch of entries or items have been sorted.
8869 When children are sorted, the cursor is in the parent line when this
8870 hook gets called. When a region or a plain list is sorted, the cursor
8871 will be in the first entry of the sorted region/list.")
8873 (defun org-sort-entries
8874 (&optional with-case sorting-type getkey-func compare-func property)
8875 "Sort entries on a certain level of an outline tree.
8876 If there is an active region, the entries in the region are sorted.
8877 Else, if the cursor is before the first entry, sort the top-level items.
8878 Else, the children of the entry at point are sorted.
8880 Sorting can be alphabetically, numerically, by date/time as given by
8881 a time stamp, by a property, by priority order, or by a custom function.
8883 The command prompts for the sorting type unless it has been given to the
8884 function through the SORTING-TYPE argument, which needs to be a character,
8885 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8886 the precise meaning of each character:
8888 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8889 c By creation time, which is assumed to be the first inactive time stamp
8890 at the beginning of a line.
8891 d By deadline date/time.
8892 k By clocking time.
8893 n Numerically, by converting the beginning of the entry/item to a number.
8894 o By order of TODO keywords.
8895 p By priority according to the cookie.
8896 r By the value of a property.
8897 s By scheduled date/time.
8898 t By date/time, either the first active time stamp in the entry, or, if
8899 none exist, by the first inactive one.
8901 Capital letters will reverse the sort order.
8903 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8904 called with point at the beginning of the record. It must return either
8905 a string or a number that should serve as the sorting key for that record.
8907 Comparing entries ignores case by default. However, with an optional argument
8908 WITH-CASE, the sorting considers case as well.
8910 Sorting is done against the visible part of the headlines, it ignores hidden
8911 links.
8913 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8914 (interactive "P")
8915 (let ((case-func (if with-case 'identity 'downcase))
8916 (cmstr
8917 ;; The clock marker is lost when using `sort-subr', let's
8918 ;; store the clocking string.
8919 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8920 (save-excursion
8921 (goto-char org-clock-marker)
8922 (buffer-substring-no-properties (line-beginning-position)
8923 (point)))))
8924 start beg end stars re re2
8925 txt what tmp)
8926 ;; Find beginning and end of region to sort
8927 (cond
8928 ((org-region-active-p)
8929 ;; we will sort the region
8930 (setq end (region-end)
8931 what "region")
8932 (goto-char (region-beginning))
8933 (unless (org-at-heading-p) (outline-next-heading))
8934 (setq start (point)))
8935 ((or (org-at-heading-p)
8936 (ignore-errors (progn (org-back-to-heading) t)))
8937 ;; we will sort the children of the current headline
8938 (org-back-to-heading)
8939 (setq start (point)
8940 end (progn (org-end-of-subtree t t)
8941 (or (bolp) (insert "\n"))
8942 (when (>= (org-back-over-empty-lines) 1)
8943 (forward-line 1))
8944 (point))
8945 what "children")
8946 (goto-char start)
8947 (outline-show-subtree)
8948 (outline-next-heading))
8950 ;; we will sort the top-level entries in this file
8951 (goto-char (point-min))
8952 (or (org-at-heading-p) (outline-next-heading))
8953 (setq start (point))
8954 (goto-char (point-max))
8955 (beginning-of-line 1)
8956 (when (looking-at ".*?\\S-")
8957 ;; File ends in a non-white line
8958 (end-of-line 1)
8959 (insert "\n"))
8960 (setq end (point-max))
8961 (setq what "top-level")
8962 (goto-char start)
8963 (outline-show-all)))
8965 (setq beg (point))
8966 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8968 (looking-at "\\(\\*+\\)")
8969 (setq stars (match-string 1)
8970 re (concat "^" (regexp-quote stars) " +")
8971 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8972 txt (buffer-substring beg end))
8973 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8974 (when (and (not (equal stars "*")) (string-match re2 txt))
8975 (user-error "Region to sort contains a level above the first entry"))
8977 (unless sorting-type
8978 (message
8979 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8980 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8981 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8982 what)
8983 (setq sorting-type (read-char-exclusive))
8985 (unless getkey-func
8986 (and (= (downcase sorting-type) ?f)
8987 (setq getkey-func
8988 (completing-read "Sort using function: "
8989 obarray 'fboundp t nil nil))
8990 (setq getkey-func (intern getkey-func))))
8992 (and (= (downcase sorting-type) ?r)
8993 (not property)
8994 (setq property
8995 (completing-read "Property: "
8996 (mapcar #'list (org-buffer-property-keys t))
8997 nil t))))
8999 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9000 (message "Sorting entries...")
9002 (save-restriction
9003 (narrow-to-region start end)
9004 (let ((dcst (downcase sorting-type))
9005 (case-fold-search nil)
9006 (now (current-time)))
9007 (sort-subr
9008 (/= dcst sorting-type)
9009 ;; This function moves to the beginning character of the "record" to
9010 ;; be sorted.
9011 (lambda nil
9012 (if (re-search-forward re nil t)
9013 (goto-char (match-beginning 0))
9014 (goto-char (point-max))))
9015 ;; This function moves to the last character of the "record" being
9016 ;; sorted.
9017 (lambda nil
9018 (save-match-data
9019 (condition-case nil
9020 (outline-forward-same-level 1)
9021 (error
9022 (goto-char (point-max))))))
9023 ;; This function returns the value that gets sorted against.
9024 (lambda nil
9025 (cond
9026 ((= dcst ?n)
9027 (if (looking-at org-complex-heading-regexp)
9028 (string-to-number (org-sort-remove-invisible (match-string 4)))
9029 nil))
9030 ((= dcst ?a)
9031 (if (looking-at org-complex-heading-regexp)
9032 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9033 nil))
9034 ((= dcst ?k)
9035 (or (get-text-property (point) :org-clock-minutes) 0))
9036 ((= dcst ?t)
9037 (let ((end (save-excursion (outline-next-heading) (point))))
9038 (if (or (re-search-forward org-ts-regexp end t)
9039 (re-search-forward org-ts-regexp-both end t))
9040 (org-time-string-to-seconds (match-string 0))
9041 (float-time now))))
9042 ((= dcst ?c)
9043 (let ((end (save-excursion (outline-next-heading) (point))))
9044 (if (re-search-forward
9045 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9046 end t)
9047 (org-time-string-to-seconds (match-string 0))
9048 (float-time now))))
9049 ((= dcst ?s)
9050 (let ((end (save-excursion (outline-next-heading) (point))))
9051 (if (re-search-forward org-scheduled-time-regexp end t)
9052 (org-time-string-to-seconds (match-string 1))
9053 (float-time now))))
9054 ((= dcst ?d)
9055 (let ((end (save-excursion (outline-next-heading) (point))))
9056 (if (re-search-forward org-deadline-time-regexp end t)
9057 (org-time-string-to-seconds (match-string 1))
9058 (float-time now))))
9059 ((= dcst ?p)
9060 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9061 (string-to-char (match-string 2))
9062 org-default-priority))
9063 ((= dcst ?r)
9064 (or (org-entry-get nil property) ""))
9065 ((= dcst ?o)
9066 (when (looking-at org-complex-heading-regexp)
9067 (let* ((m (match-string 2))
9068 (s (if (member m org-done-keywords) '- '+)))
9069 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9070 ((= dcst ?f)
9071 (if getkey-func
9072 (progn
9073 (setq tmp (funcall getkey-func))
9074 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9075 tmp)
9076 (error "Invalid key function `%s'" getkey-func)))
9077 (t (error "Invalid sorting type `%c'" sorting-type))))
9079 (cond
9080 ((= dcst ?a) 'string<)
9081 ((= dcst ?f) compare-func)
9082 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9083 (run-hooks 'org-after-sorting-entries-or-items-hook)
9084 ;; Reset the clock marker if needed
9085 (when cmstr
9086 (save-excursion
9087 (goto-char start)
9088 (search-forward cmstr nil t)
9089 (move-marker org-clock-marker (point))))
9090 (message "Sorting entries...done")))
9092 ;;; The orgstruct minor mode
9094 ;; Define a minor mode which can be used in other modes in order to
9095 ;; integrate the Org mode structure editing commands.
9097 ;; This is really a hack, because the Org mode structure commands use
9098 ;; keys which normally belong to the major mode. Here is how it
9099 ;; works: The minor mode defines all the keys necessary to operate the
9100 ;; structure commands, but wraps the commands into a function which
9101 ;; tests if the cursor is currently at a headline or a plain list
9102 ;; item. If that is the case, the structure command is used,
9103 ;; temporarily setting many Org mode variables like regular
9104 ;; expressions for filling etc. However, when any of those keys is
9105 ;; used at a different location, function uses `key-binding' to look
9106 ;; up if the key has an associated command in another currently active
9107 ;; keymap (minor modes, major mode, global), and executes that
9108 ;; command. There might be problems if any of the keys is otherwise
9109 ;; used as a prefix key.
9111 (defcustom orgstruct-heading-prefix-regexp ""
9112 "Regexp that matches the custom prefix of Org headlines in
9113 orgstruct(++)-mode."
9114 :group 'org
9115 :version "24.4"
9116 :package-version '(Org . "8.3")
9117 :type 'regexp)
9118 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9120 (defcustom orgstruct-setup-hook nil
9121 "Hook run after orgstruct-mode-map is filled."
9122 :group 'org
9123 :version "24.4"
9124 :package-version '(Org . "8.0")
9125 :type 'hook)
9127 (defvar orgstruct-initialized nil)
9129 (defvar org-local-vars nil
9130 "List of local variables, for use by `orgstruct-mode'.")
9132 ;;;###autoload
9133 (define-minor-mode orgstruct-mode
9134 "Toggle the minor mode `orgstruct-mode'.
9135 This mode is for using Org mode structure commands in other
9136 modes. The following keys behave as if Org mode were active, if
9137 the cursor is on a headline, or on a plain list item (both as
9138 defined by Org mode)."
9139 nil " OrgStruct" (make-sparse-keymap)
9140 (funcall (if orgstruct-mode
9141 'add-to-invisibility-spec
9142 'remove-from-invisibility-spec)
9143 '(outline . t))
9144 (when orgstruct-mode
9145 (org-load-modules-maybe)
9146 (unless orgstruct-initialized
9147 (orgstruct-setup)
9148 (setq orgstruct-initialized t))))
9150 ;;;###autoload
9151 (defun turn-on-orgstruct ()
9152 "Unconditionally turn on `orgstruct-mode'."
9153 (orgstruct-mode 1))
9155 (defvar-local orgstruct-is-++ nil
9156 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9157 (defvar-local org-fb-vars nil)
9158 (defun orgstruct++-mode (&optional arg)
9159 "Toggle `orgstruct-mode', the enhanced version of it.
9160 In addition to setting orgstruct-mode, this also exports all
9161 indentation and autofilling variables from Org mode into the
9162 buffer. It will also recognize item context in multiline items."
9163 (interactive "P")
9164 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9165 (if (< arg 1)
9166 (progn (orgstruct-mode -1)
9167 (dolist (v org-fb-vars)
9168 (set (make-local-variable (car v))
9169 (if (eq (car-safe (cadr v)) 'quote)
9170 (cl-cadadr v)
9171 (nth 1 v)))))
9172 (orgstruct-mode 1)
9173 (setq org-fb-vars nil)
9174 (unless org-local-vars
9175 (setq org-local-vars (org-get-local-variables)))
9176 (let (var val)
9177 (dolist (x org-local-vars)
9178 (when (string-match
9179 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9180 \\|fill-prefix\\|indent-\\)"
9181 (symbol-name (car x)))
9182 (setq var (car x) val (nth 1 x))
9183 (push (list var `(quote ,(eval var))) org-fb-vars)
9184 (set (make-local-variable var)
9185 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9186 (setq-local orgstruct-is-++ t))))
9188 ;;;###autoload
9189 (defun turn-on-orgstruct++ ()
9190 "Unconditionally turn on `orgstruct++-mode'."
9191 (orgstruct++-mode 1))
9193 (defun orgstruct-error ()
9194 "Error when there is no default binding for a structure key."
9195 (interactive)
9196 (funcall (if (fboundp 'user-error)
9197 'user-error
9198 'error)
9199 "This key has no function outside structure elements"))
9201 (defun orgstruct-setup ()
9202 "Setup orgstruct keymap."
9203 (dolist (cell '((org-demote . t)
9204 (org-metaleft . t)
9205 (org-metaright . t)
9206 (org-promote . t)
9207 (org-shiftmetaleft . t)
9208 (org-shiftmetaright . t)
9209 org-backward-element
9210 org-backward-heading-same-level
9211 org-ctrl-c-ret
9212 org-ctrl-c-minus
9213 org-ctrl-c-star
9214 org-cycle
9215 org-force-cycle-archived
9216 org-forward-heading-same-level
9217 org-insert-heading
9218 org-insert-heading-respect-content
9219 org-kill-note-or-show-branches
9220 org-mark-subtree
9221 org-meta-return
9222 org-metadown
9223 org-metaup
9224 org-narrow-to-subtree
9225 org-promote-subtree
9226 org-reveal
9227 org-shiftdown
9228 org-shiftleft
9229 org-shiftmetadown
9230 org-shiftmetaup
9231 org-shiftright
9232 org-shifttab
9233 org-shifttab
9234 org-shiftup
9235 org-show-children
9236 org-show-subtree
9237 org-sort
9238 org-up-element
9239 outline-demote
9240 outline-next-visible-heading
9241 outline-previous-visible-heading
9242 outline-promote
9243 outline-up-heading))
9244 (let ((f (or (car-safe cell) cell))
9245 (disable-when-heading-prefix (cdr-safe cell)))
9246 (when (fboundp f)
9247 (let ((new-bindings))
9248 (dolist (binding (nconc (where-is-internal f org-mode-map)
9249 (where-is-internal f outline-mode-map)))
9250 (push binding new-bindings)
9251 ;; TODO use local-function-key-map
9252 (dolist (rep '(("<tab>" . "TAB")
9253 ("<return>" . "RET")
9254 ("<escape>" . "ESC")
9255 ("<delete>" . "DEL")))
9256 (setq binding (read-kbd-macro
9257 (let ((case-fold-search))
9258 (replace-regexp-in-string
9259 (regexp-quote (cdr rep))
9260 (car rep)
9261 (key-description binding)))))
9262 (cl-pushnew binding new-bindings :test 'equal)))
9263 (dolist (binding new-bindings)
9264 (let ((key (lookup-key orgstruct-mode-map binding)))
9265 (when (or (not key) (numberp key))
9266 (ignore-errors
9267 (org-defkey orgstruct-mode-map
9268 binding
9269 (orgstruct-make-binding
9270 f binding disable-when-heading-prefix))))))))))
9271 (run-hooks 'orgstruct-setup-hook))
9273 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9274 "Create a function for binding in the structure minor mode.
9275 FUN is the command to call inside a table. KEY is the key that
9276 should be checked in for a command to execute outside of tables.
9277 Non-nil `disable-when-heading-prefix' means to disable the command
9278 if `orgstruct-heading-prefix-regexp' is not empty."
9279 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9280 (let ((nname name)
9281 (i 0))
9282 (while (fboundp (intern nname))
9283 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9284 (setq name (intern nname)))
9285 (eval
9286 (let ((bindings '((org-heading-regexp
9287 (concat "^"
9288 orgstruct-heading-prefix-regexp
9289 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9290 (org-outline-regexp
9291 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9292 (org-outline-regexp-bol
9293 (concat "^" org-outline-regexp))
9294 (outline-regexp org-outline-regexp)
9295 (outline-heading-end-regexp "\n")
9296 (outline-level 'org-outline-level)
9297 (outline-heading-alist))))
9298 `(defun ,name (arg)
9299 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9300 "Outside of structure, run the binding of `"
9301 (key-description key) "'."
9302 (when disable-when-heading-prefix
9303 (concat
9304 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9305 "back to the default binding due to limitations of Org's implementation of\n"
9306 "`" (symbol-name fun) "'.")))
9307 (interactive "p")
9308 (let* ((disable
9309 ,(and disable-when-heading-prefix
9310 '(not (string= orgstruct-heading-prefix-regexp ""))))
9311 (fallback
9312 (or disable
9313 (not
9314 (let* ,bindings
9315 (org-context-p 'headline 'item
9316 ,(when (memq fun
9317 '(org-insert-heading
9318 org-insert-heading-respect-content
9319 org-meta-return))
9320 '(when orgstruct-is-++
9321 'item-body))))))))
9322 (if fallback
9323 (let* ((orgstruct-mode)
9324 (binding
9325 (let ((key ,key))
9326 (catch 'exit
9327 (dolist
9328 (rep
9329 '(nil
9330 ("<\\([^>]*\\)tab>" . "\\1TAB")
9331 ("<\\([^>]*\\)return>" . "\\1RET")
9332 ("<\\([^>]*\\)escape>" . "\\1ESC")
9333 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9334 nil)
9335 (when rep
9336 (setq key (read-kbd-macro
9337 (let ((case-fold-search))
9338 (replace-regexp-in-string
9339 (car rep)
9340 (cdr rep)
9341 (key-description key))))))
9342 (when (key-binding key)
9343 (throw 'exit (key-binding key))))))))
9344 (if (keymapp binding)
9345 (org-set-transient-map binding)
9346 (let ((func (or binding
9347 (unless disable
9348 'orgstruct-error))))
9349 (when func
9350 (call-interactively func)))))
9351 (org-run-like-in-org-mode
9352 (lambda ()
9353 (interactive)
9354 (let* ,bindings
9355 (call-interactively ',fun)))))))))
9356 name))
9358 (defun org-contextualize-keys (alist contexts)
9359 "Return valid elements in ALIST depending on CONTEXTS.
9361 `org-agenda-custom-commands' or `org-capture-templates' are the
9362 values used for ALIST, and `org-agenda-custom-commands-contexts'
9363 or `org-capture-templates-contexts' are the associated contexts
9364 definitions."
9365 (let ((contexts
9366 ;; normalize contexts
9367 (mapcar
9368 (lambda(c) (cond ((listp (cadr c))
9369 (list (car c) (car c) (nth 1 c)))
9370 ((string= "" (cadr c))
9371 (list (car c) (car c) (nth 2 c)))
9372 (t c)))
9373 contexts))
9374 (a alist) r s)
9375 ;; loop over all commands or templates
9376 (dolist (c a)
9377 (let (vrules repl)
9378 (cond
9379 ((not (assoc (car c) contexts))
9380 (push c r))
9381 ((and (assoc (car c) contexts)
9382 (setq vrules (org-contextualize-validate-key
9383 (car c) contexts)))
9384 (mapc (lambda (vr)
9385 (unless (equal (car vr) (cadr vr))
9386 (setq repl vr)))
9387 vrules)
9388 (if (not repl) (push c r)
9389 (push (cadr repl) s)
9390 (push
9391 (cons (car c)
9392 (cdr (or (assoc (cadr repl) alist)
9393 (error "Undefined key `%s' as contextual replacement for `%s'"
9394 (cadr repl) (car c)))))
9395 r))))))
9396 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9397 (delq
9399 (delete-dups
9400 (mapcar (lambda (x)
9401 (let ((tpl (car x)))
9402 (unless (delq
9404 (mapcar (lambda (y)
9405 (equal y tpl))
9407 x)))
9408 (reverse r))))))
9410 (defun org-contextualize-validate-key (key contexts)
9411 "Check CONTEXTS for agenda or capture KEY."
9412 (let (res)
9413 (dolist (r contexts)
9414 (dolist (rr (car (last r)))
9415 (when
9416 (and (equal key (car r))
9417 (if (functionp rr) (funcall rr)
9418 (or (and (eq (car rr) 'in-file)
9419 (buffer-file-name)
9420 (string-match (cdr rr) (buffer-file-name)))
9421 (and (eq (car rr) 'in-mode)
9422 (string-match (cdr rr) (symbol-name major-mode)))
9423 (and (eq (car rr) 'in-buffer)
9424 (string-match (cdr rr) (buffer-name)))
9425 (when (and (eq (car rr) 'not-in-file)
9426 (buffer-file-name))
9427 (not (string-match (cdr rr) (buffer-file-name))))
9428 (when (eq (car rr) 'not-in-mode)
9429 (not (string-match (cdr rr) (symbol-name major-mode))))
9430 (when (eq (car rr) 'not-in-buffer)
9431 (not (string-match (cdr rr) (buffer-name)))))))
9432 (push r res))))
9433 (delete-dups (delq nil res))))
9435 (defun org-context-p (&rest contexts)
9436 "Check if local context is any of CONTEXTS.
9437 Possible values in the list of contexts are `table', `headline', and `item'."
9438 (let ((pos (point)))
9439 (goto-char (point-at-bol))
9440 (prog1 (or (and (memq 'table contexts)
9441 (looking-at "[ \t]*|"))
9442 (and (memq 'headline contexts)
9443 (looking-at org-outline-regexp))
9444 (and (memq 'item contexts)
9445 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9446 (and (memq 'item-body contexts)
9447 (org-in-item-p)))
9448 (goto-char pos))))
9450 (defconst org-unique-local-variables
9451 '(org-element--cache
9452 org-element--cache-objects
9453 org-element--cache-sync-keys
9454 org-element--cache-sync-requests
9455 org-element--cache-sync-timer)
9456 "List of local variables that cannot be transferred to another buffer.")
9458 (defun org-get-local-variables ()
9459 "Return a list of all local variables in an Org mode buffer."
9460 (delq nil
9461 (mapcar
9462 (lambda (x)
9463 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9464 (name (car binding)))
9465 (and (not (get name 'org-state))
9466 (not (memq name org-unique-local-variables))
9467 (string-match-p
9468 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9469 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9470 (symbol-name name))
9471 binding)))
9472 (with-temp-buffer
9473 (org-mode)
9474 (buffer-local-variables)))))
9476 (defun org-clone-local-variables (from-buffer &optional regexp)
9477 "Clone local variables from FROM-BUFFER.
9478 Optional argument REGEXP selects variables to clone."
9479 (dolist (pair (buffer-local-variables from-buffer))
9480 (let ((name (car pair)))
9481 (when (and (symbolp name)
9482 (not (memq name org-unique-local-variables))
9483 (or (null regexp) (string-match regexp (symbol-name name))))
9484 (set (make-local-variable name) (cdr pair))))))
9486 ;;;###autoload
9487 (defun org-run-like-in-org-mode (cmd)
9488 "Run a command, pretending that the current buffer is in Org mode.
9489 This will temporarily bind local variables that are typically bound in
9490 Org mode to the values they have in Org mode, and then interactively
9491 call CMD."
9492 (org-load-modules-maybe)
9493 (unless org-local-vars
9494 (setq org-local-vars (org-get-local-variables)))
9495 (let (binds)
9496 (dolist (var org-local-vars)
9497 (when (or (not (boundp (car var)))
9498 (eq (symbol-value (car var))
9499 (default-value (car var))))
9500 (push (list (car var) `(quote ,(cadr var))) binds)))
9501 (eval `(let ,binds
9502 (call-interactively (quote ,cmd))))))
9504 (defun org-get-category (&optional pos force-refresh)
9505 "Get the category applying to position POS."
9506 (save-match-data
9507 (when force-refresh (org-refresh-category-properties))
9508 (let ((pos (or pos (point))))
9509 (or (get-text-property pos 'org-category)
9510 (progn (org-refresh-category-properties)
9511 (get-text-property pos 'org-category))))))
9513 ;;; Refresh properties
9515 (defun org-refresh-properties (dprop tprop)
9516 "Refresh buffer text properties.
9517 DPROP is the drawer property and TPROP is either the
9518 corresponding text property to set, or an alist with each element
9519 being a text property (as a symbol) and a function to apply to
9520 the value of the drawer property."
9521 (let* ((case-fold-search t)
9522 (inhibit-read-only t)
9523 (inherit? (org-property-inherit-p dprop))
9524 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9525 (global (and inherit? (org--property-global-value dprop nil))))
9526 (org-with-silent-modifications
9527 (org-with-point-at 1
9528 ;; Set global values (e.g., values defined through
9529 ;; "#+PROPERTY:" keywords) to the whole buffer.
9530 (when global (put-text-property (point-min) (point-max) tprop global))
9531 ;; Set local values.
9532 (while (re-search-forward property-re nil t)
9533 (when (org-at-property-p)
9534 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9535 (outline-next-heading))))))
9537 (defun org-refresh-property (tprop p &optional inherit)
9538 "Refresh the buffer text property TPROP from the drawer property P.
9539 The refresh happens only for the current headline, or the whole
9540 sub-tree if optional argument INHERIT is non-nil."
9541 (unless (org-before-first-heading-p)
9542 (save-excursion
9543 (org-back-to-heading t)
9544 (let ((start (point))
9545 (end (save-excursion
9546 (if inherit (org-end-of-subtree t t)
9547 (or (outline-next-heading) (point-max))))))
9548 (if (symbolp tprop)
9549 ;; TPROP is a text property symbol.
9550 (put-text-property start end tprop p)
9551 ;; TPROP is an alist with (property . function) elements.
9552 (pcase-dolist (`(,prop . ,f) tprop)
9553 (put-text-property start end prop (funcall f p))))))))
9555 (defun org-refresh-category-properties ()
9556 "Refresh category text properties in the buffer."
9557 (let ((case-fold-search t)
9558 (inhibit-read-only t)
9559 (default-category
9560 (cond ((null org-category)
9561 (if buffer-file-name
9562 (file-name-sans-extension
9563 (file-name-nondirectory buffer-file-name))
9564 "???"))
9565 ((symbolp org-category) (symbol-name org-category))
9566 (t org-category))))
9567 (org-with-silent-modifications
9568 (org-with-wide-buffer
9569 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9570 ;; This is the default category for the buffer. If none is
9571 ;; found, fall-back to `org-category' or buffer file name.
9572 (put-text-property
9573 (point-min) (point-max)
9574 'org-category
9575 (catch 'buffer-category
9576 (goto-char (point-max))
9577 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9578 (let ((element (org-element-at-point)))
9579 (when (eq (org-element-type element) 'keyword)
9580 (throw 'buffer-category
9581 (org-element-property :value element)))))
9582 default-category))
9583 ;; Set sub-tree specific categories.
9584 (goto-char (point-min))
9585 (let ((regexp (org-re-property "CATEGORY")))
9586 (while (re-search-forward regexp nil t)
9587 (let ((value (match-string-no-properties 3)))
9588 (when (org-at-property-p)
9589 (put-text-property
9590 (save-excursion (org-back-to-heading t) (point))
9591 (save-excursion (org-end-of-subtree t t) (point))
9592 'org-category
9593 value)))))))))
9595 (defun org-refresh-stats-properties ()
9596 "Refresh stats text properties in the buffer."
9597 (let (stats)
9598 (org-with-silent-modifications
9599 (org-with-wide-buffer
9600 (goto-char (point-min))
9601 (while (re-search-forward
9602 (concat org-outline-regexp-bol ".*"
9603 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9604 nil t)
9605 (setq stats (cond ((equal (match-string 3) "0") 0)
9606 ((match-string 2)
9607 (/ (* (string-to-number (match-string 2)) 100)
9608 (string-to-number (match-string 3))))
9609 (t (string-to-number (match-string 1)))))
9610 (org-back-to-heading t)
9611 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9612 'org-stats stats))))))
9614 (defun org-refresh-effort-properties ()
9615 "Refresh effort properties"
9616 (org-refresh-properties
9617 org-effort-property
9618 '((effort . identity)
9619 (effort-minutes . org-duration-to-minutes))))
9621 ;;;; Link Stuff
9623 ;;; Link abbreviations
9625 (defun org-link-expand-abbrev (link)
9626 "Apply replacements as defined in `org-link-abbrev-alist'."
9627 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9628 (let* ((key (match-string 1 link))
9629 (as (or (assoc key org-link-abbrev-alist-local)
9630 (assoc key org-link-abbrev-alist)))
9631 (tag (and (match-end 2) (match-string 3 link)))
9632 rpl)
9633 (if (not as)
9634 link
9635 (setq rpl (cdr as))
9636 (cond
9637 ((symbolp rpl) (funcall rpl tag))
9638 ((string-match "%(\\([^)]+\\))" rpl)
9639 (replace-match
9640 (save-match-data
9641 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9642 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9643 ((string-match "%h" rpl)
9644 (replace-match (url-hexify-string (or tag "")) t t rpl))
9645 (t (concat rpl tag)))))
9646 link))
9648 ;;; Storing and inserting links
9650 (defvar org-insert-link-history nil
9651 "Minibuffer history for links inserted with `org-insert-link'.")
9653 (defvar org-stored-links nil
9654 "Contains the links stored with `org-store-link'.")
9656 (defvar org-store-link-plist nil
9657 "Plist with info about the most recently link created with `org-store-link'.")
9659 (defun org-store-link-functions ()
9660 "Return a list of functions that are called to create and store a link.
9661 The functions defined in the :store property of
9662 `org-link-parameters'.
9664 Each function will be called in turn until one returns a non-nil
9665 value. Each function should check if it is responsible for
9666 creating this link (for example by looking at the major mode).
9667 If not, it must exit and return nil. If yes, it should return
9668 a non-nil value after calling `org-store-link-props' with a list
9669 of properties and values. Special properties are:
9671 :type The link prefix, like \"http\". This must be given.
9672 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9673 This is obligatory as well.
9674 :description Optional default description for the second pair
9675 of brackets in an Org mode link. The user can still change
9676 this when inserting this link into an Org mode buffer.
9678 In addition to these, any additional properties can be specified
9679 and then used in capture templates."
9680 (cl-loop for link in org-link-parameters
9681 with store-func
9682 do (setq store-func (org-link-get-parameter (car link) :store))
9683 if store-func
9684 collect store-func))
9686 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9687 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9689 ;;;###autoload
9690 (defun org-store-link (arg)
9691 "Store an org-link to the current location.
9692 \\<org-mode-map>
9693 This link is added to `org-stored-links' and can later be inserted
9694 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9696 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9697 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9698 For file links, ARG negates `org-context-in-file-links'.
9700 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9701 skipping storing functions that are not
9702 part of Org core.
9704 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9705 prefix ARG forces storing a link for each line in the
9706 active region."
9707 (interactive "P")
9708 (org-load-modules-maybe)
9709 (if (and (equal arg '(64)) (org-region-active-p))
9710 (save-excursion
9711 (let ((end (region-end)))
9712 (goto-char (region-beginning))
9713 (set-mark (point))
9714 (while (< (point-at-eol) end)
9715 (move-end-of-line 1) (activate-mark)
9716 (let (current-prefix-arg)
9717 (call-interactively 'org-store-link))
9718 (move-beginning-of-line 2)
9719 (set-mark (point)))))
9720 (setq org-store-link-plist nil)
9721 (let (link cpltxt desc description search
9722 txt custom-id agenda-link sfuns sfunsn)
9723 (cond
9725 ;; Store a link using an external link type
9726 ((and (not (equal arg '(16)))
9727 (setq sfuns
9728 (delq
9729 nil (mapcar (lambda (f)
9730 (let (fs) (if (funcall f) (push f fs))))
9731 (org-store-link-functions)))
9732 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9733 (or (and (cdr sfuns)
9734 (funcall (intern
9735 (completing-read
9736 "Which function for creating the link? "
9737 sfunsn nil t (car sfunsn)))))
9738 (funcall (caar sfuns)))
9739 (setq link (plist-get org-store-link-plist :link)
9740 desc (or (plist-get org-store-link-plist
9741 :description)
9742 link))))
9744 ;; Store a link from a source code buffer.
9745 ((org-src-edit-buffer-p)
9746 (let ((coderef-format (org-src-coderef-format)))
9747 (cond ((save-excursion
9748 (beginning-of-line)
9749 (looking-at (org-src-coderef-regexp coderef-format)))
9750 (setq link (format "(%s)" (match-string-no-properties 3))))
9751 ((called-interactively-p 'any)
9752 (let ((label (read-string "Code line label: ")))
9753 (end-of-line)
9754 (setq link (format coderef-format label))
9755 (let ((gc (- 79 (length link))))
9756 (if (< (current-column) gc)
9757 (org-move-to-column gc t)
9758 (insert " ")))
9759 (insert link)
9760 (setq link (concat "(" label ")"))
9761 (setq desc nil)))
9762 (t (setq link nil)))))
9764 ;; We are in the agenda, link to referenced location
9765 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9766 (let ((m (or (get-text-property (point) 'org-hd-marker)
9767 (get-text-property (point) 'org-marker))))
9768 (when m
9769 (org-with-point-at m
9770 (setq agenda-link
9771 (if (called-interactively-p 'any)
9772 (call-interactively 'org-store-link)
9773 (org-store-link nil)))))))
9775 ((eq major-mode 'calendar-mode)
9776 (let ((cd (calendar-cursor-to-date)))
9777 (setq link
9778 (format-time-string
9779 (car org-time-stamp-formats)
9780 (apply 'encode-time
9781 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9782 nil nil nil))))
9783 (org-store-link-props :type "calendar" :date cd)))
9785 ((eq major-mode 'help-mode)
9786 (setq link (concat "help:" (save-excursion
9787 (goto-char (point-min))
9788 (looking-at "^[^ ]+")
9789 (match-string 0))))
9790 (org-store-link-props :type "help"))
9792 ((eq major-mode 'w3-mode)
9793 (setq cpltxt (if (and (buffer-name)
9794 (not (string-match "Untitled" (buffer-name))))
9795 (buffer-name)
9796 (url-view-url t))
9797 link (url-view-url t))
9798 (org-store-link-props :type "w3" :url (url-view-url t)))
9800 ((eq major-mode 'image-mode)
9801 (setq cpltxt (concat "file:"
9802 (abbreviate-file-name buffer-file-name))
9803 link cpltxt)
9804 (org-store-link-props :type "image" :file buffer-file-name))
9806 ;; In dired, store a link to the file of the current line
9807 ((derived-mode-p 'dired-mode)
9808 (let ((file (dired-get-filename nil t)))
9809 (setq file (if file
9810 (abbreviate-file-name
9811 (expand-file-name (dired-get-filename nil t)))
9812 ;; otherwise, no file so use current directory.
9813 default-directory))
9814 (setq cpltxt (concat "file:" file)
9815 link cpltxt)))
9817 ((setq search (run-hook-with-args-until-success
9818 'org-create-file-search-functions))
9819 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9820 "::" search))
9821 (setq cpltxt (or description link)))
9823 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9824 (org-with-limited-levels
9825 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9826 (cond
9827 ;; Store a link using the target at point
9828 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9829 (setq cpltxt
9830 (concat "file:"
9831 (abbreviate-file-name
9832 (buffer-file-name (buffer-base-buffer)))
9833 "::" (match-string 1))
9834 link cpltxt))
9835 ((and (featurep 'org-id)
9836 (or (eq org-id-link-to-org-use-id t)
9837 (and (called-interactively-p 'any)
9838 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9839 (and (eq org-id-link-to-org-use-id
9840 'create-if-interactive-and-no-custom-id)
9841 (not custom-id))))
9842 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9843 ;; Store a link using the ID at point
9844 (setq link (condition-case nil
9845 (prog1 (org-id-store-link)
9846 (setq desc (or (plist-get org-store-link-plist
9847 :description)
9848 "")))
9849 (error
9850 ;; Probably before first headline, link only to file
9851 (concat "file:"
9852 (abbreviate-file-name
9853 (buffer-file-name (buffer-base-buffer))))))))
9855 ;; Just link to current headline
9856 (setq cpltxt (concat "file:"
9857 (abbreviate-file-name
9858 (buffer-file-name (buffer-base-buffer)))))
9859 ;; Add a context search string
9860 (when (org-xor org-context-in-file-links arg)
9861 (let* ((element (org-element-at-point))
9862 (name (org-element-property :name element)))
9863 (setq txt (cond
9864 ((org-at-heading-p) nil)
9865 (name)
9866 ((org-region-active-p)
9867 (buffer-substring (region-beginning) (region-end)))))
9868 (when (or (null txt) (string-match "\\S-" txt))
9869 (setq cpltxt
9870 (concat cpltxt "::"
9871 (condition-case nil
9872 (org-make-org-heading-search-string txt)
9873 (error "")))
9874 desc (or name
9875 (nth 4 (ignore-errors (org-heading-components)))
9876 "NONE")))))
9877 (when (string-match "::\\'" cpltxt)
9878 (setq cpltxt (substring cpltxt 0 -2)))
9879 (setq link cpltxt)))))
9881 ((buffer-file-name (buffer-base-buffer))
9882 ;; Just link to this file here.
9883 (setq cpltxt (concat "file:"
9884 (abbreviate-file-name
9885 (buffer-file-name (buffer-base-buffer)))))
9886 ;; Add a context string.
9887 (when (org-xor org-context-in-file-links arg)
9888 (setq txt (if (org-region-active-p)
9889 (buffer-substring (region-beginning) (region-end))
9890 (buffer-substring (point-at-bol) (point-at-eol))))
9891 ;; Only use search option if there is some text.
9892 (when (string-match "\\S-" txt)
9893 (setq cpltxt
9894 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9895 desc "NONE")))
9896 (setq link cpltxt))
9898 ((called-interactively-p 'interactive)
9899 (user-error "No method for storing a link from this buffer"))
9901 (t (setq link nil)))
9903 ;; We're done setting link and desc, clean up
9904 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9905 (setq link (or link cpltxt)
9906 desc (or desc cpltxt))
9907 (cond ((not desc))
9908 ((equal desc "NONE") (setq desc nil))
9909 (t (setq desc
9910 (replace-regexp-in-string
9911 org-bracket-link-analytic-regexp
9912 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9913 desc))))
9914 ;; Return the link
9915 (if (not (and (or (called-interactively-p 'any)
9916 executing-kbd-macro)
9917 link))
9918 (or agenda-link (and link (org-make-link-string link desc)))
9919 (push (list link desc) org-stored-links)
9920 (message "Stored: %s" (or desc link))
9921 (when custom-id
9922 (setq link (concat "file:" (abbreviate-file-name
9923 (buffer-file-name)) "::#" custom-id))
9924 (push (list link desc) org-stored-links))
9925 (car org-stored-links)))))
9927 (defun org-store-link-props (&rest plist)
9928 "Store link properties, extract names, addresses and dates."
9929 (let ((x (plist-get plist :from)))
9930 (when x
9931 (let ((adr (mail-extract-address-components x)))
9932 (setq plist (plist-put plist :fromname (car adr)))
9933 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9934 (let ((x (plist-get plist :to)))
9935 (when x
9936 (let ((adr (mail-extract-address-components x)))
9937 (setq plist (plist-put plist :toname (car adr)))
9938 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9939 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9940 (when x
9941 (setq plist (plist-put plist :date-timestamp
9942 (format-time-string
9943 (org-time-stamp-format t) x)))
9944 (setq plist (plist-put plist :date-timestamp-inactive
9945 (format-time-string
9946 (org-time-stamp-format t t) x)))))
9947 (let ((from (plist-get plist :from))
9948 (to (plist-get plist :to)))
9949 (when (and from to org-from-is-user-regexp)
9950 (setq plist
9951 (plist-put plist :fromto
9952 (if (string-match org-from-is-user-regexp from)
9953 (concat "to %t")
9954 (concat "from %f"))))))
9955 (setq org-store-link-plist plist))
9957 (defun org-add-link-props (&rest plist)
9958 "Add these properties to the link property list."
9959 (let (key value)
9960 (while plist
9961 (setq key (pop plist) value (pop plist))
9962 (setq org-store-link-plist
9963 (plist-put org-store-link-plist key value)))))
9965 (defun org-email-link-description (&optional fmt)
9966 "Return the description part of an email link.
9967 This takes information from `org-store-link-plist' and formats it
9968 according to FMT (default from `org-email-link-description-format')."
9969 (setq fmt (or fmt org-email-link-description-format))
9970 (let* ((p org-store-link-plist)
9971 (to (plist-get p :toaddress))
9972 (from (plist-get p :fromaddress))
9973 (table
9974 (list
9975 (cons "%c" (plist-get p :fromto))
9976 (cons "%F" (plist-get p :from))
9977 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9978 (cons "%T" (plist-get p :to))
9979 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9980 (cons "%s" (plist-get p :subject))
9981 (cons "%d" (plist-get p :date))
9982 (cons "%m" (plist-get p :message-id)))))
9983 (when (string-match "%c" fmt)
9984 ;; Check if the user wrote this message
9985 (if (and org-from-is-user-regexp from to
9986 (save-match-data (string-match org-from-is-user-regexp from)))
9987 (setq fmt (replace-match "to %t" t t fmt))
9988 (setq fmt (replace-match "from %f" t t fmt))))
9989 (org-replace-escapes fmt table)))
9991 (defun org-make-org-heading-search-string (&optional string)
9992 "Make search string for the current headline or STRING."
9993 (let ((s (or string
9994 (and (derived-mode-p 'org-mode)
9995 (save-excursion
9996 (org-back-to-heading t)
9997 (org-element-property :raw-value (org-element-at-point))))))
9998 (lines org-context-in-file-links))
9999 (or string (setq s (concat "*" s))) ; Add * for headlines
10000 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10001 (when (and string (integerp lines) (> lines 0))
10002 (let ((slines (org-split-string s "\n")))
10003 (when (< lines (length slines))
10004 (setq s (mapconcat
10005 'identity
10006 (reverse (nthcdr (- (length slines) lines)
10007 (reverse slines))) "\n")))))
10008 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10010 (defun org-make-link-string (link &optional description)
10011 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10012 (unless (org-string-nw-p link) (error "Empty link"))
10013 (let ((uri (cond ((string-match org-link-types-re link)
10014 (concat (match-string 1 link)
10015 (org-link-escape (substring link (match-end 1)))))
10016 ;; For readability, url-encode internal links only
10017 ;; when absolutely needed (i.e, when they contain
10018 ;; square brackets). File links however, are
10019 ;; encoded since, e.g., spaces are significant.
10020 ((or (file-name-absolute-p link)
10021 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10022 (org-link-escape link))
10023 (t link)))
10024 (description
10025 (and (org-string-nw-p description)
10026 ;; Remove brackets from description, as they are fatal.
10027 (replace-regexp-in-string
10028 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10029 (org-trim description)))))
10030 (format "[[%s]%s]"
10032 (if description (format "[%s]" description) ""))))
10034 (defconst org-link-escape-chars
10035 ;;%20 %5B %5D %25
10036 '(?\s ?\[ ?\] ?%)
10037 "List of characters that should be escaped in a link when stored to Org.
10038 This is the list that is used for internal purposes.")
10040 (defun org-link-escape (text &optional table merge)
10041 "Return percent escaped representation of TEXT.
10042 TEXT is a string with the text to escape.
10043 Optional argument TABLE is a list with characters that should be
10044 escaped. When nil, `org-link-escape-chars' is used.
10045 If optional argument MERGE is set, merge TABLE into
10046 `org-link-escape-chars'."
10047 (let ((characters-to-encode
10048 (cond ((null table) org-link-escape-chars)
10049 (merge (append org-link-escape-chars table))
10050 (t table))))
10051 (mapconcat
10052 (lambda (c)
10053 (if (or (memq c characters-to-encode)
10054 (and org-url-hexify-p (or (< c 32) (> c 126))))
10055 (mapconcat (lambda (e) (format "%%%.2X" e))
10056 (or (encode-coding-char c 'utf-8)
10057 (error "Unable to percent escape character: %c" c))
10059 (char-to-string c)))
10060 text "")))
10062 (defun org-link-unescape (str)
10063 "Unhex hexified Unicode parts in string STR.
10064 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10065 reciprocal of `org-link-escape', which see."
10066 (if (org-string-nw-p str)
10067 (replace-regexp-in-string
10068 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10069 str))
10071 (defun org-link-unescape-compound (hex)
10072 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10073 Note: this function also decodes single byte encodings like
10074 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10075 (save-match-data
10076 (let* ((bytes (cdr (split-string hex "%")))
10077 (ret "")
10078 (eat 0)
10079 (sum 0))
10080 (while bytes
10081 (let* ((val (string-to-number (pop bytes) 16))
10082 (shift-xor
10083 (if (= 0 eat)
10084 (cond
10085 ((>= val 252) (cons 6 252))
10086 ((>= val 248) (cons 5 248))
10087 ((>= val 240) (cons 4 240))
10088 ((>= val 224) (cons 3 224))
10089 ((>= val 192) (cons 2 192))
10090 (t (cons 0 0)))
10091 (cons 6 128))))
10092 (when (>= val 192) (setq eat (car shift-xor)))
10093 (setq val (logxor val (cdr shift-xor)))
10094 (setq sum (+ (lsh sum (car shift-xor)) val))
10095 (when (> eat 0) (setq eat (- eat 1)))
10096 (cond
10097 ((= 0 eat) ;multi byte
10098 (setq ret (concat ret (char-to-string sum)))
10099 (setq sum 0))
10100 ((not bytes) ; single byte(s)
10101 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10102 ret)))
10104 (defun org-link-unescape-single-byte-sequence (hex)
10105 "Unhexify hex-encoded single byte character sequences."
10106 (mapconcat (lambda (byte)
10107 (char-to-string (string-to-number byte 16)))
10108 (cdr (split-string hex "%")) ""))
10110 (defun org-xor (a b)
10111 "Exclusive or."
10112 (if a (not b) b))
10114 (defun org-fixup-message-id-for-http (s)
10115 "Replace special characters in a message id, so it can be used in an http query."
10116 (when (string-match "%" s)
10117 (setq s (mapconcat (lambda (c)
10118 (if (eq c ?%)
10119 "%25"
10120 (char-to-string c)))
10121 s "")))
10122 (while (string-match "<" s)
10123 (setq s (replace-match "%3C" t t s)))
10124 (while (string-match ">" s)
10125 (setq s (replace-match "%3E" t t s)))
10126 (while (string-match "@" s)
10127 (setq s (replace-match "%40" t t s)))
10130 (defun org-link-prettify (link)
10131 "Return a human-readable representation of LINK.
10132 The car of LINK must be a raw link.
10133 The cdr of LINK must be either a link description or nil."
10134 (let ((desc (or (cadr link) "<no description>")))
10135 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10136 "<" (car link) ">")))
10138 ;;;###autoload
10139 (defun org-insert-link-global ()
10140 "Insert a link like Org mode does.
10141 This command can be called in any mode to insert a link in Org syntax."
10142 (interactive)
10143 (org-load-modules-maybe)
10144 (org-run-like-in-org-mode 'org-insert-link))
10146 (defun org-insert-all-links (arg &optional pre post)
10147 "Insert all links in `org-stored-links'.
10148 When a universal prefix, do not delete the links from `org-stored-links'.
10149 When `ARG' is a number, insert the last N link(s).
10150 `PRE' and `POST' are optional arguments to define a string to
10151 prepend or to append."
10152 (interactive "P")
10153 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10154 (links (copy-sequence org-stored-links))
10155 (pr (or pre "- "))
10156 (po (or post "\n"))
10157 (cnt 1) l)
10158 (if (null org-stored-links)
10159 (message "No link to insert")
10160 (while (and (or (listp arg) (>= arg cnt))
10161 (setq l (if (listp arg)
10162 (pop links)
10163 (pop org-stored-links))))
10164 (setq cnt (1+ cnt))
10165 (insert pr)
10166 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10167 (insert po)))))
10169 (defun org-insert-last-stored-link (arg)
10170 "Insert the last link stored in `org-stored-links'."
10171 (interactive "p")
10172 (org-insert-all-links arg "" "\n"))
10174 (defun org-link-fontify-links-to-this-file ()
10175 "Fontify links to the current file in `org-stored-links'."
10176 (let ((f (buffer-file-name)) a b)
10177 (setq a (mapcar (lambda(l)
10178 (let ((ll (car l)))
10179 (when (and (string-match "^file:\\(.+\\)::" ll)
10180 (equal f (expand-file-name (match-string 1 ll))))
10181 ll)))
10182 org-stored-links))
10183 (when (featurep 'org-id)
10184 (setq b (mapcar (lambda(l)
10185 (let ((ll (car l)))
10186 (when (and (string-match "^id:\\(.+\\)$" ll)
10187 (equal f (expand-file-name
10188 (or (org-id-find-id-file
10189 (match-string 1 ll)) ""))))
10190 ll)))
10191 org-stored-links)))
10192 (mapcar (lambda(l)
10193 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10194 (delq nil (append a b)))))
10196 (defvar org--links-history nil)
10197 (defun org-insert-link (&optional complete-file link-location default-description)
10198 "Insert a link. At the prompt, enter the link.
10200 Completion can be used to insert any of the link protocol prefixes in use.
10202 The history can be used to select a link previously stored with
10203 `org-store-link'. When the empty string is entered (i.e. if you just
10204 press `RET' at the prompt), the link defaults to the most recently
10205 stored link. As `SPC' triggers completion in the minibuffer, you need to
10206 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10208 You will also be prompted for a description, and if one is given, it will
10209 be displayed in the buffer instead of the link.
10211 If there is already a link at point, this command will allow you to edit
10212 link and description parts.
10214 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10215 file name can be
10216 selected using completion. The path to the file will be relative to the
10217 current directory if the file is in the current directory or a subdirectory.
10218 Otherwise, the link will be the absolute path as completed in the minibuffer
10219 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10220 option `org-link-file-path-type'.
10222 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10223 absolute path even if the file is in
10224 the current directory or below.
10226 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10227 prefix negates `org-keep-stored-link-after-insertion'.
10229 If `org-make-link-description-function' is non-nil, this function will be
10230 called with the link target, and the result will be the default
10231 link description.
10233 If the LINK-LOCATION parameter is non-nil, this value will be used as
10234 the link location instead of reading one interactively.
10236 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10237 as the default description."
10238 (interactive "P")
10239 (let* ((wcf (current-window-configuration))
10240 (origbuf (current-buffer))
10241 (region (when (org-region-active-p)
10242 (buffer-substring (region-beginning) (region-end))))
10243 (remove (and region (list (region-beginning) (region-end))))
10244 (desc region)
10245 (link link-location)
10246 (abbrevs org-link-abbrev-alist-local)
10247 entry all-prefixes auto-desc)
10248 (cond
10249 (link-location) ; specified by arg, just use it.
10250 ((org-in-regexp org-bracket-link-regexp 1)
10251 ;; We do have a link at point, and we are going to edit it.
10252 (setq remove (list (match-beginning 0) (match-end 0)))
10253 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10254 (setq link (read-string "Link: "
10255 (org-link-unescape
10256 (match-string-no-properties 1)))))
10257 ((or (org-in-regexp org-angle-link-re)
10258 (org-in-regexp org-plain-link-re))
10259 ;; Convert to bracket link
10260 (setq remove (list (match-beginning 0) (match-end 0))
10261 link (read-string "Link: "
10262 (org-unbracket-string "<" ">" (match-string 0)))))
10263 ((member complete-file '((4) (16)))
10264 ;; Completing read for file names.
10265 (setq link (org-file-complete-link complete-file)))
10267 ;; Read link, with completion for stored links.
10268 (org-link-fontify-links-to-this-file)
10269 (org-switch-to-buffer-other-window "*Org Links*")
10270 (with-current-buffer "*Org Links*"
10271 (erase-buffer)
10272 (insert "Insert a link.
10273 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10274 (when org-stored-links
10275 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10276 (insert (mapconcat 'org-link-prettify
10277 (reverse org-stored-links) "\n")))
10278 (goto-char (point-min)))
10279 (let ((cw (selected-window)))
10280 (select-window (get-buffer-window "*Org Links*" 'visible))
10281 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10282 (unless (pos-visible-in-window-p (point-max))
10283 (org-fit-window-to-buffer))
10284 (and (window-live-p cw) (select-window cw)))
10285 (setq all-prefixes (append (mapcar 'car abbrevs)
10286 (mapcar 'car org-link-abbrev-alist)
10287 (org-link-types)))
10288 (unwind-protect
10289 ;; Fake a link history, containing the stored links.
10290 (let ((org--links-history
10291 (append (mapcar #'car org-stored-links)
10292 org-insert-link-history)))
10293 (setq link
10294 (org-completing-read
10295 "Link: "
10296 (append
10297 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10298 (mapcar #'car org-stored-links))
10299 nil nil nil
10300 'org--links-history
10301 (caar org-stored-links)))
10302 (unless (org-string-nw-p link) (user-error "No link selected"))
10303 (dolist (l org-stored-links)
10304 (when (equal link (cadr l))
10305 (setq link (car l))
10306 (setq auto-desc t)))
10307 (when (or (member link all-prefixes)
10308 (and (equal ":" (substring link -1))
10309 (member (substring link 0 -1) all-prefixes)
10310 (setq link (substring link 0 -1))))
10311 (setq link (with-current-buffer origbuf
10312 (org-link-try-special-completion link)))))
10313 (set-window-configuration wcf)
10314 (kill-buffer "*Org Links*"))
10315 (setq entry (assoc link org-stored-links))
10316 (or entry (push link org-insert-link-history))
10317 (setq desc (or desc (nth 1 entry)))))
10319 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10320 (not org-keep-stored-link-after-insertion))
10321 (setq org-stored-links (delq (assoc link org-stored-links)
10322 org-stored-links)))
10324 (when (and (string-match org-plain-link-re link)
10325 (not (string-match org-ts-regexp link)))
10326 ;; URL-like link, normalize the use of angular brackets.
10327 (setq link (org-unbracket-string "<" ">" link)))
10329 ;; Check if we are linking to the current file with a search
10330 ;; option If yes, simplify the link by using only the search
10331 ;; option.
10332 (when (and buffer-file-name
10333 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10334 (let* ((path (match-string 1 link))
10335 (case-fold-search nil)
10336 (search (match-string 2 link)))
10337 (save-match-data
10338 (when (equal (file-truename buffer-file-name) (file-truename path))
10339 ;; We are linking to this same file, with a search option
10340 (setq link search)))))
10342 ;; Check if we can/should use a relative path. If yes, simplify the link
10343 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10344 (let* ((type (match-string 1 link))
10345 (path (match-string 2 link))
10346 (origpath path)
10347 (case-fold-search nil))
10348 (cond
10349 ((or (eq org-link-file-path-type 'absolute)
10350 (equal complete-file '(16)))
10351 (setq path (abbreviate-file-name (expand-file-name path))))
10352 ((eq org-link-file-path-type 'noabbrev)
10353 (setq path (expand-file-name path)))
10354 ((eq org-link-file-path-type 'relative)
10355 (setq path (file-relative-name path)))
10357 (save-match-data
10358 (if (string-match (concat "^" (regexp-quote
10359 (expand-file-name
10360 (file-name-as-directory
10361 default-directory))))
10362 (expand-file-name path))
10363 ;; We are linking a file with relative path name.
10364 (setq path (substring (expand-file-name path)
10365 (match-end 0)))
10366 (setq path (abbreviate-file-name (expand-file-name path)))))))
10367 (setq link (concat type path))
10368 (when (equal desc origpath)
10369 (setq desc path))))
10371 (if org-make-link-description-function
10372 (setq desc
10373 (or (condition-case nil
10374 (funcall org-make-link-description-function link desc)
10375 (error (progn (message "Can't get link description from `%s'"
10376 (symbol-name org-make-link-description-function))
10377 (sit-for 2) nil)))
10378 (read-string "Description: " default-description)))
10379 (if default-description (setq desc default-description)
10380 (setq desc (or (and auto-desc desc)
10381 (read-string "Description: " desc)))))
10383 (unless (string-match "\\S-" desc) (setq desc nil))
10384 (when remove (apply 'delete-region remove))
10385 (insert (org-make-link-string link desc))
10386 ;; Redisplay so as the new link has proper invisible characters.
10387 (sit-for 0)))
10389 (defun org-link-try-special-completion (type)
10390 "If there is completion support for link type TYPE, offer it."
10391 (let ((fun (org-link-get-parameter type :complete)))
10392 (if (functionp fun)
10393 (funcall fun)
10394 (read-string "Link (no completion support): " (concat type ":")))))
10396 (defun org-file-complete-link (&optional arg)
10397 "Create a file link using completion."
10398 (let ((file (read-file-name "File: "))
10399 (pwd (file-name-as-directory (expand-file-name ".")))
10400 (pwd1 (file-name-as-directory (abbreviate-file-name
10401 (expand-file-name ".")))))
10402 (cond ((equal arg '(16))
10403 (concat "file:"
10404 (abbreviate-file-name (expand-file-name file))))
10405 ((string-match
10406 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10407 (concat "file:" (match-string 1 file)))
10408 ((string-match
10409 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10410 (expand-file-name file))
10411 (concat "file:"
10412 (match-string 1 (expand-file-name file))))
10413 (t (concat "file:" file)))))
10415 (defun org-completing-read (&rest args)
10416 "Completing-read with SPACE being a normal character."
10417 (let ((enable-recursive-minibuffers t)
10418 (minibuffer-local-completion-map
10419 (copy-keymap minibuffer-local-completion-map)))
10420 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10421 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10422 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10423 'org-time-stamp-inactive)
10424 (apply #'completing-read args)))
10426 ;;; Opening/following a link
10428 (defvar org-link-search-failed nil)
10430 (defvar org-open-link-functions nil
10431 "Hook for functions finding a plain text link.
10432 These functions must take a single argument, the link content.
10433 They will be called for links that look like [[link text][description]]
10434 when LINK TEXT does not have a protocol like \"http:\" and does not look
10435 like a filename (e.g. \"./blue.png\").
10437 These functions will be called *before* Org attempts to resolve the
10438 link by doing text searches in the current buffer - so if you want a
10439 link \"[[target]]\" to still find \"<<target>>\", your function should
10440 handle this as a special case.
10442 When the function does handle the link, it must return a non-nil value.
10443 If it decides that it is not responsible for this link, it must return
10444 nil to indicate that that Org can continue with other options like
10445 exact and fuzzy text search.")
10447 (defun org-next-link (&optional search-backward)
10448 "Move forward to the next link.
10449 If the link is in hidden text, expose it."
10450 (interactive "P")
10451 (when (and org-link-search-failed (eq this-command last-command))
10452 (goto-char (point-min))
10453 (message "Link search wrapped back to beginning of buffer"))
10454 (setq org-link-search-failed nil)
10455 (let* ((pos (point))
10456 (ct (org-context))
10457 (a (assq :link ct))
10458 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10459 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10460 ((looking-at org-any-link-re)
10461 ;; Don't stay stuck at link without an org-link face
10462 (forward-char (if search-backward -1 1))))
10463 (if (funcall srch-fun org-any-link-re nil t)
10464 (progn
10465 (goto-char (match-beginning 0))
10466 (when (outline-invisible-p) (org-show-context)))
10467 (goto-char pos)
10468 (setq org-link-search-failed t)
10469 (message "No further link found"))))
10471 (defun org-previous-link ()
10472 "Move backward to the previous link.
10473 If the link is in hidden text, expose it."
10474 (interactive)
10475 (funcall 'org-next-link t))
10477 (defun org-translate-link (s)
10478 "Translate a link string if a translation function has been defined."
10479 (with-temp-buffer
10480 (insert (org-trim s))
10481 (org-trim (org-element-interpret-data (org-element-context)))))
10483 (defun org-translate-link-from-planner (type path)
10484 "Translate a link from Emacs Planner syntax so that Org can follow it.
10485 This is still an experimental function, your mileage may vary."
10486 (cond
10487 ((member type '("http" "https" "news" "ftp"))
10488 ;; standard Internet links are the same.
10489 nil)
10490 ((and (equal type "irc") (string-match "^//" path))
10491 ;; Planner has two / at the beginning of an irc link, we have 1.
10492 ;; We should have zero, actually....
10493 (setq path (substring path 1)))
10494 ((and (equal type "lisp") (string-match "^/" path))
10495 ;; Planner has a slash, we do not.
10496 (setq type "elisp" path (substring path 1)))
10497 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10498 ;; A typical message link. Planner has the id after the final slash,
10499 ;; we separate it with a hash mark
10500 (setq path (concat (match-string 1 path) "#"
10501 (org-unbracket-string "<" ">" (match-string 2 path))))))
10502 (cons type path))
10504 (defun org-find-file-at-mouse (ev)
10505 "Open file link or URL at mouse."
10506 (interactive "e")
10507 (mouse-set-point ev)
10508 (org-open-at-point 'in-emacs))
10510 (defun org-open-at-mouse (ev)
10511 "Open file link or URL at mouse.
10512 See the docstring of `org-open-file' for details."
10513 (interactive "e")
10514 (mouse-set-point ev)
10515 (when (eq major-mode 'org-agenda-mode)
10516 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10517 (org-open-at-point))
10519 (defvar org-window-config-before-follow-link nil
10520 "The window configuration before following a link.
10521 This is saved in case the need arises to restore it.")
10523 ;;;###autoload
10524 (defun org-open-at-point-global ()
10525 "Follow a link or time-stamp like Org mode does.
10526 This command can be called in any mode to follow an external link
10527 or a time-stamp that has Org mode syntax. Its behavior is
10528 undefined when called on internal links (e.g., fuzzy links).
10529 Raise an error when there is nothing to follow. "
10530 (interactive)
10531 (cond ((org-in-regexp org-any-link-re)
10532 (org-open-link-from-string (match-string-no-properties 0)))
10533 ((or (org-in-regexp org-ts-regexp-both nil t)
10534 (org-in-regexp org-tsr-regexp-both nil t))
10535 (org-follow-timestamp-link))
10536 (t (user-error "No link found"))))
10538 ;;;###autoload
10539 (defun org-open-link-from-string (s &optional arg reference-buffer)
10540 "Open a link in the string S, as if it was in Org mode."
10541 (interactive "sLink: \nP")
10542 (let ((reference-buffer (or reference-buffer (current-buffer))))
10543 (with-temp-buffer
10544 (let ((org-inhibit-startup (not reference-buffer)))
10545 (org-mode)
10546 (insert s)
10547 (goto-char (point-min))
10548 (when reference-buffer
10549 (setq org-link-abbrev-alist-local
10550 (with-current-buffer reference-buffer
10551 org-link-abbrev-alist-local)))
10552 (org-open-at-point arg reference-buffer)))))
10554 (defvar org-open-at-point-functions nil
10555 "Hook that is run when following a link at point.
10557 Functions in this hook must return t if they identify and follow
10558 a link at point. If they don't find anything interesting at point,
10559 they must return nil.")
10561 (defvar org-link-search-inhibit-query nil)
10562 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10563 (defun org--open-doi-link (path)
10564 "Open a \"doi\" type link.
10565 PATH is a the path to search for, as a string."
10566 (browse-url (url-encode-url (concat org-doi-server-url path))))
10568 (defun org--open-elisp-link (path)
10569 "Open a \"elisp\" type link.
10570 PATH is the sexp to evaluate, as a string."
10571 (let ((cmd path))
10572 (if (or (and (org-string-nw-p
10573 org-confirm-elisp-link-not-regexp)
10574 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10575 (not org-confirm-elisp-link-function)
10576 (funcall org-confirm-elisp-link-function
10577 (format "Execute \"%s\" as elisp? "
10578 (org-add-props cmd nil 'face 'org-warning))))
10579 (message "%s => %s" cmd
10580 (if (eq (string-to-char cmd) ?\()
10581 (eval (read cmd))
10582 (call-interactively (read cmd))))
10583 (user-error "Abort"))))
10585 (defun org--open-help-link (path)
10586 "Open a \"help\" type link.
10587 PATH is a symbol name, as a string."
10588 (pcase (intern path)
10589 ((and (pred fboundp) variable) (describe-function variable))
10590 ((and (pred boundp) function) (describe-variable function))
10591 (name (user-error "Unknown function or variable: %s" name))))
10593 (defun org--open-shell-link (path)
10594 "Open a \"shell\" type link.
10595 PATH is the command to execute, as a string."
10596 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10597 (cmd path))
10598 (if (or (and (org-string-nw-p
10599 org-confirm-shell-link-not-regexp)
10600 (string-match
10601 org-confirm-shell-link-not-regexp cmd))
10602 (not org-confirm-shell-link-function)
10603 (funcall org-confirm-shell-link-function
10604 (format "Execute \"%s\" in shell? "
10605 (org-add-props cmd nil
10606 'face 'org-warning))))
10607 (progn
10608 (message "Executing %s" cmd)
10609 (shell-command cmd buf)
10610 (when (featurep 'midnight)
10611 (setq clean-buffer-list-kill-buffer-names
10612 (cons (buffer-name buf)
10613 clean-buffer-list-kill-buffer-names))))
10614 (user-error "Abort"))))
10616 (defun org-open-at-point (&optional arg reference-buffer)
10617 "Open link, timestamp, footnote or tags at point.
10619 When point is on a link, follow it. Normally, files will be
10620 opened by an appropriate application. If the optional prefix
10621 argument ARG is non-nil, Emacs will visit the file. With
10622 a double prefix argument, try to open outside of Emacs, in the
10623 application the system uses for this file type.
10625 When point is on a timestamp, open the agenda at the day
10626 specified.
10628 When point is a footnote definition, move to the first reference
10629 found. If it is on a reference, move to the associated
10630 definition.
10632 When point is on a headline, display a list of every link in the
10633 entry, so it is possible to pick one, or all, of them. If point
10634 is on a tag, call `org-tags-view' instead.
10636 When optional argument REFERENCE-BUFFER is non-nil, it should
10637 specify a buffer from where the link search should happen. This
10638 is used internally by `org-open-link-from-string'.
10640 On top of syntactically correct links, this function will open
10641 the link at point in comments or comment blocks and the first
10642 link in a property drawer line."
10643 (interactive "P")
10644 ;; On a code block, open block's results.
10645 (unless (call-interactively 'org-babel-open-src-block-result)
10646 (org-load-modules-maybe)
10647 (setq org-window-config-before-follow-link (current-window-configuration))
10648 (org-remove-occur-highlights nil nil t)
10649 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10650 (let* ((context
10651 ;; Only consider supported types, even if they are not
10652 ;; the closest one.
10653 (org-element-lineage
10654 (org-element-context)
10655 '(clock comment comment-block footnote-definition
10656 footnote-reference headline inlinetask keyword link
10657 node-property timestamp)
10659 (type (org-element-type context))
10660 (value (org-element-property :value context)))
10661 (cond
10662 ((not context) (user-error "No link found"))
10663 ;; Exception: open timestamps and links in properties
10664 ;; drawers, keywords and comments.
10665 ((memq type '(comment comment-block keyword node-property))
10666 (call-interactively #'org-open-at-point-global))
10667 ;; On a headline or an inlinetask, but not on a timestamp,
10668 ;; a link, a footnote reference or on tags.
10669 ((and (memq type '(headline inlinetask))
10670 ;; Not on tags.
10671 (let ((case-fold-search nil))
10672 (save-excursion
10673 (beginning-of-line)
10674 (looking-at org-complex-heading-regexp))
10675 (or (not (match-beginning 5))
10676 (< (point) (match-beginning 5)))))
10677 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10678 (links (car data))
10679 (links-end (cdr data)))
10680 (if links
10681 (dolist (link (if (stringp links) (list links) links))
10682 (search-forward link nil links-end)
10683 (goto-char (match-beginning 0))
10684 (org-open-at-point))
10685 (require 'org-attach)
10686 (org-attach-reveal 'if-exists))))
10687 ;; On a clock line, make sure point is on the timestamp
10688 ;; before opening it.
10689 ((and (eq type 'clock)
10690 value
10691 (>= (point) (org-element-property :begin value))
10692 (<= (point) (org-element-property :end value)))
10693 (org-follow-timestamp-link))
10694 ;; Do nothing on white spaces after an object.
10695 ((>= (point)
10696 (save-excursion
10697 (goto-char (org-element-property :end context))
10698 (skip-chars-backward " \t")
10699 (point)))
10700 (user-error "No link found"))
10701 ((eq type 'timestamp) (org-follow-timestamp-link))
10702 ;; On tags within a headline or an inlinetask.
10703 ((and (memq type '(headline inlinetask))
10704 (let ((case-fold-search nil))
10705 (save-excursion (beginning-of-line)
10706 (looking-at org-complex-heading-regexp))
10707 (and (match-beginning 5)
10708 (>= (point) (match-beginning 5)))))
10709 (org-tags-view arg (substring (match-string 5) 0 -1)))
10710 ((eq type 'link)
10711 (let ((type (org-element-property :type context))
10712 (path (org-link-unescape (org-element-property :path context))))
10713 ;; Switch back to REFERENCE-BUFFER needed when called in
10714 ;; a temporary buffer through `org-open-link-from-string'.
10715 (with-current-buffer (or reference-buffer (current-buffer))
10716 (cond
10717 ((equal type "file")
10718 (if (string-match "[*?{]" (file-name-nondirectory path))
10719 (dired path)
10720 ;; Look into `org-link-parameters' in order to find
10721 ;; a DEDICATED-FUNCTION to open file. The function
10722 ;; will be applied on raw link instead of parsed
10723 ;; link due to the limitation in `org-add-link-type'
10724 ;; ("open" function called with a single argument).
10725 ;; If no such function is found, fallback to
10726 ;; `org-open-file'.
10727 (let* ((option (org-element-property :search-option context))
10728 (app (org-element-property :application context))
10729 (dedicated-function
10730 (org-link-get-parameter
10731 (if app (concat type "+" app) type)
10732 :follow)))
10733 (if dedicated-function
10734 (funcall dedicated-function
10735 (concat path
10736 (and option (concat "::" option))))
10737 (apply #'org-open-file
10738 path
10739 (cond (arg)
10740 ((equal app "emacs") 'emacs)
10741 ((equal app "sys") 'system))
10742 (cond ((not option) nil)
10743 ((string-match-p "\\`[0-9]+\\'" option)
10744 (list (string-to-number option)))
10745 (t (list nil
10746 (org-link-unescape option)))))))))
10747 ((functionp (org-link-get-parameter type :follow))
10748 (funcall (org-link-get-parameter type :follow) path))
10749 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10750 (unless (run-hook-with-args-until-success
10751 'org-open-link-functions path)
10752 (if (not arg) (org-mark-ring-push)
10753 (switch-to-buffer-other-window
10754 (org-get-buffer-for-internal-link (current-buffer))))
10755 (let ((destination
10756 (org-with-wide-buffer
10757 (if (equal type "radio")
10758 (org-search-radio-target
10759 (org-element-property :path context))
10760 (org-link-search
10761 (if (member type '("custom-id" "coderef"))
10762 (org-element-property :raw-link context)
10763 path)
10764 ;; Prevent fuzzy links from matching
10765 ;; themselves.
10766 (and (equal type "fuzzy")
10767 (+ 2 (org-element-property :begin context)))))
10768 (point))))
10769 (unless (and (<= (point-min) destination)
10770 (>= (point-max) destination))
10771 (widen))
10772 (goto-char destination))))
10773 (t (browse-url-at-point))))))
10774 ;; On a footnote reference or at a footnote definition's label.
10775 ((or (eq type 'footnote-reference)
10776 (and (eq type 'footnote-definition)
10777 (save-excursion
10778 ;; Do not validate action when point is on the
10779 ;; spaces right after the footnote label, in
10780 ;; order to be on par with behaviour on links.
10781 (skip-chars-forward " \t")
10782 (let ((begin
10783 (org-element-property :contents-begin context)))
10784 (if begin (< (point) begin)
10785 (= (org-element-property :post-affiliated context)
10786 (line-beginning-position)))))))
10787 (org-footnote-action))
10788 (t (user-error "No link found")))))
10789 (run-hook-with-args 'org-follow-link-hook)))
10791 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10792 "Offer links in the current entry and return the selected link.
10793 If there is only one link, return it.
10794 If NTH is an integer, return the NTH link found.
10795 If ZERO is a string, check also this string for a link, and if
10796 there is one, return it."
10797 (with-current-buffer buffer
10798 (org-with-wide-buffer
10799 (goto-char marker)
10800 (let ((cnt ?0)
10801 have-zero end links link c)
10802 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10803 (push (match-string 0 zero) links)
10804 (setq cnt (1- cnt) have-zero t))
10805 (save-excursion
10806 (org-back-to-heading t)
10807 (setq end (save-excursion (outline-next-heading) (point)))
10808 (while (re-search-forward org-any-link-re end t)
10809 (push (match-string 0) links))
10810 (setq links (org-uniquify (reverse links))))
10811 (cond
10812 ((null links)
10813 (message "No links"))
10814 ((equal (length links) 1)
10815 (setq link (car links)))
10816 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10817 (setq link (nth (if have-zero nth (1- nth)) links)))
10818 (t ; we have to select a link
10819 (save-excursion
10820 (save-window-excursion
10821 (delete-other-windows)
10822 (with-output-to-temp-buffer "*Select Link*"
10823 (dolist (l links)
10824 (cond
10825 ((not (string-match org-bracket-link-regexp l))
10826 (princ (format "[%c] %s\n" (cl-incf cnt)
10827 (org-unbracket-string "<" ">" l))))
10828 ((match-end 3)
10829 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10830 (match-string 3 l) (match-string 1 l))))
10831 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10832 (match-string 1 l)))))))
10833 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10834 (message "Select link to open, RET to open all:")
10835 (setq c (read-char-exclusive))
10836 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10837 (when (equal c ?q) (user-error "Abort"))
10838 (if (equal c ?\C-m)
10839 (setq link links)
10840 (setq nth (- c ?0))
10841 (when have-zero (setq nth (1+ nth)))
10842 (unless (and (integerp nth) (>= (length links) nth))
10843 (user-error "Invalid link selection"))
10844 (setq link (nth (1- nth) links)))))
10845 (cons link end)))))
10847 ;; TODO: These functions are deprecated since `org-open-at-point'
10848 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10849 (defun org-open-file-with-system (path)
10850 "Open file at PATH using the system way of opening it."
10851 (org-open-file path 'system))
10852 (defun org-open-file-with-emacs (path)
10853 "Open file at PATH in Emacs."
10854 (org-open-file path 'emacs))
10857 ;;; File search
10859 (defvar org-create-file-search-functions nil
10860 "List of functions to construct the right search string for a file link.
10861 These functions are called in turn with point at the location to
10862 which the link should point.
10864 A function in the hook should first test if it would like to
10865 handle this file type, for example by checking the `major-mode'
10866 or the file extension. If it decides not to handle this file, it
10867 should just return nil to give other functions a chance. If it
10868 does handle the file, it must return the search string to be used
10869 when following the link. The search string will be part of the
10870 file link, given after a double colon, and `org-open-at-point'
10871 will automatically search for it. If special measures must be
10872 taken to make the search successful, another function should be
10873 added to the companion hook `org-execute-file-search-functions',
10874 which see.
10876 A function in this hook may also use `setq' to set the variable
10877 `description' to provide a suggestion for the descriptive text to
10878 be used for this link when it gets inserted into an Org buffer
10879 with \\[org-insert-link].")
10881 (defvar org-execute-file-search-functions nil
10882 "List of functions to execute a file search triggered by a link.
10884 Functions added to this hook must accept a single argument, the
10885 search string that was part of the file link, the part after the
10886 double colon. The function must first check if it would like to
10887 handle this search, for example by checking the `major-mode' or
10888 the file extension. If it decides not to handle this search, it
10889 should just return nil to give other functions a chance. If it
10890 does handle the search, it must return a non-nil value to keep
10891 other functions from trying.
10893 Each function can access the current prefix argument through the
10894 variable `current-prefix-arg'. Note that a single prefix is used
10895 to force opening a link in Emacs, so it may be good to only use a
10896 numeric or double prefix to guide the search function.
10898 In case this is needed, a function in this hook can also restore
10899 the window configuration before `org-open-at-point' was called using:
10901 (set-window-configuration org-window-config-before-follow-link)")
10903 (defun org-search-radio-target (target)
10904 "Search a radio target matching TARGET in current buffer.
10905 White spaces are not significant."
10906 (let ((re (format "<<<%s>>>"
10907 (mapconcat #'regexp-quote
10908 (org-split-string target "[ \t\n]+")
10909 "[ \t]+\\(?:\n[ \t]*\\)?")))
10910 (origin (point)))
10911 (goto-char (point-min))
10912 (catch :radio-match
10913 (while (re-search-forward re nil t)
10914 (backward-char)
10915 (let ((object (org-element-context)))
10916 (when (eq (org-element-type object) 'radio-target)
10917 (goto-char (org-element-property :begin object))
10918 (org-show-context 'link-search)
10919 (throw :radio-match nil))))
10920 (goto-char origin)
10921 (user-error "No match for radio target: %s" target))))
10923 (defun org-link-search (s &optional avoid-pos stealth)
10924 "Search for a search string S.
10926 If S starts with \"#\", it triggers a custom ID search.
10928 If S is enclosed within parenthesis, it initiates a coderef
10929 search.
10931 If S is surrounded by forward slashes, it is interpreted as
10932 a regular expression. In Org mode files, this will create an
10933 `org-occur' sparse tree. In ordinary files, `occur' will be used
10934 to list matches. If the current buffer is in `dired-mode', grep
10935 will be used to search in all files.
10937 When AVOID-POS is given, ignore matches near that position.
10939 When optional argument STEALTH is non-nil, do not modify
10940 visibility around point, thus ignoring `org-show-context-detail'
10941 variable.
10943 Search is case-insensitive and ignores white spaces. Return type
10944 of matched result, which is either `dedicated' or `fuzzy'."
10945 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10946 (let* ((case-fold-search t)
10947 (origin (point))
10948 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10949 (starred (eq (string-to-char normalized) ?*))
10950 (words (split-string (if starred (substring s 1) s)))
10951 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10952 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10953 type)
10954 (cond
10955 ;; Check if there are any special search functions.
10956 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10957 ((eq (string-to-char s) ?#)
10958 ;; Look for a custom ID S if S starts with "#".
10959 (let* ((id (substring normalized 1))
10960 (match (org-find-property "CUSTOM_ID" id)))
10961 (if match (progn (goto-char match) (setf type 'dedicated))
10962 (error "No match for custom ID: %s" id))))
10963 ((string-match "\\`(\\(.*\\))\\'" normalized)
10964 ;; Look for coderef targets if S is enclosed within parenthesis.
10965 (let ((coderef (match-string-no-properties 1 normalized))
10966 (re (substring s-single-re 1 -1)))
10967 (goto-char (point-min))
10968 (catch :coderef-match
10969 (while (re-search-forward re nil t)
10970 (let ((element (org-element-at-point)))
10971 (when (and (memq (org-element-type element)
10972 '(example-block src-block))
10973 ;; Build proper regexp according to current
10974 ;; block's label format.
10975 (let ((label-fmt
10976 (regexp-quote
10977 (or (org-element-property :label-fmt element)
10978 org-coderef-label-format))))
10979 (save-excursion
10980 (beginning-of-line)
10981 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10982 (format label-fmt coderef))))))
10983 (setq type 'dedicated)
10984 (goto-char (match-beginning 1))
10985 (throw :coderef-match nil))))
10986 (goto-char origin)
10987 (error "No match for coderef: %s" coderef))))
10988 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10989 ;; Look for a regular expression.
10990 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10991 (match-string 1 s)))
10992 ;; From here, we handle fuzzy links.
10994 ;; Look for targets, only if not in a headline search.
10995 ((and (not starred)
10996 (let ((target (format "<<%s>>" s-multi-re)))
10997 (catch :target-match
10998 (goto-char (point-min))
10999 (while (re-search-forward target nil t)
11000 (backward-char)
11001 (let ((context (org-element-context)))
11002 (when (eq (org-element-type context) 'target)
11003 (setq type 'dedicated)
11004 (goto-char (org-element-property :begin context))
11005 (throw :target-match t))))
11006 nil))))
11007 ;; Look for elements named after S, only if not in a headline
11008 ;; search.
11009 ((and (not starred)
11010 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11011 (catch :name-match
11012 (goto-char (point-min))
11013 (while (re-search-forward name nil t)
11014 (let ((element (org-element-at-point)))
11015 (when (equal words
11016 (split-string
11017 (org-element-property :name element)))
11018 (setq type 'dedicated)
11019 (beginning-of-line)
11020 (throw :name-match t))))
11021 nil))))
11022 ;; Regular text search. Prefer headlines in Org mode buffers.
11023 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11024 ;; statistics cookies and tags.
11025 ((and (derived-mode-p 'org-mode)
11026 (let ((title-re
11027 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11028 org-outline-regexp-bol
11029 org-comment-string
11030 (mapconcat #'regexp-quote words ".+")))
11031 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11032 (comment-re (eval-when-compile
11033 (format "\\`%s[ \t]+" org-comment-string))))
11034 (goto-char (point-min))
11035 (catch :found
11036 (while (re-search-forward title-re nil t)
11037 (when (equal words
11038 (split-string
11039 (replace-regexp-in-string
11040 cookie-re ""
11041 (replace-regexp-in-string
11042 comment-re "" (org-get-heading t t t)))))
11043 (throw :found t)))
11044 nil)))
11045 (beginning-of-line)
11046 (setq type 'dedicated))
11047 ;; Offer to create non-existent headline depending on
11048 ;; `org-link-search-must-match-exact-headline'.
11049 ((and (derived-mode-p 'org-mode)
11050 (not org-link-search-inhibit-query)
11051 (eq org-link-search-must-match-exact-headline 'query-to-create)
11052 (yes-or-no-p "No match - create this as a new heading? "))
11053 (goto-char (point-max))
11054 (unless (bolp) (newline))
11055 (org-insert-heading nil t t)
11056 (insert s "\n")
11057 (beginning-of-line 0))
11058 ;; Only headlines are looked after. No need to process
11059 ;; further: throw an error.
11060 ((and (derived-mode-p 'org-mode)
11061 (or starred org-link-search-must-match-exact-headline))
11062 (goto-char origin)
11063 (error "No match for fuzzy expression: %s" normalized))
11064 ;; Regular text search.
11065 ((catch :fuzzy-match
11066 (goto-char (point-min))
11067 (while (re-search-forward s-multi-re nil t)
11068 ;; Skip match if it contains AVOID-POS or it is included in
11069 ;; a link with a description but outside the description.
11070 (unless (or (and avoid-pos
11071 (<= (match-beginning 0) avoid-pos)
11072 (> (match-end 0) avoid-pos))
11073 (and (save-match-data
11074 (org-in-regexp org-bracket-link-regexp))
11075 (match-beginning 3)
11076 (or (> (match-beginning 3) (point))
11077 (<= (match-end 3) (point)))
11078 (org-element-lineage
11079 (save-match-data (org-element-context))
11080 '(link) t)))
11081 (goto-char (match-beginning 0))
11082 (setq type 'fuzzy)
11083 (throw :fuzzy-match t)))
11084 nil))
11085 ;; All failed. Throw an error.
11086 (t (goto-char origin)
11087 (error "No match for fuzzy expression: %s" normalized)))
11088 ;; Disclose surroundings of match, if appropriate.
11089 (when (and (derived-mode-p 'org-mode) (not stealth))
11090 (org-show-context 'link-search))
11091 type))
11093 (defun org-get-buffer-for-internal-link (buffer)
11094 "Return a buffer to be used for displaying the link target of internal links."
11095 (cond
11096 ((not org-display-internal-link-with-indirect-buffer)
11097 buffer)
11098 ((string-suffix-p "(Clone)" (buffer-name buffer))
11099 (message "Buffer is already a clone, not making another one")
11100 ;; we also do not modify visibility in this case
11101 buffer)
11102 (t ; make a new indirect buffer for displaying the link
11103 (let* ((bn (buffer-name buffer))
11104 (ibn (concat bn "(Clone)"))
11105 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11106 (with-current-buffer ib (org-overview))
11107 ib))))
11109 (defun org-do-occur (regexp &optional cleanup)
11110 "Call the Emacs command `occur'.
11111 If CLEANUP is non-nil, remove the printout of the regular expression
11112 in the *Occur* buffer. This is useful if the regex is long and not useful
11113 to read."
11114 (occur regexp)
11115 (when cleanup
11116 (let ((cwin (selected-window)) win beg end)
11117 (when (setq win (get-buffer-window "*Occur*"))
11118 (select-window win))
11119 (goto-char (point-min))
11120 (when (re-search-forward "match[a-z]+" nil t)
11121 (setq beg (match-end 0))
11122 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11123 (setq end (1- (match-beginning 0)))))
11124 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11125 (goto-char (point-min))
11126 (select-window cwin))))
11128 ;;; The mark ring for links jumps
11130 (defvar org-mark-ring nil
11131 "Mark ring for positions before jumps in Org mode.")
11132 (defvar org-mark-ring-last-goto nil
11133 "Last position in the mark ring used to go back.")
11134 ;; Fill and close the ring
11135 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11136 (dotimes (_ org-mark-ring-length)
11137 (push (make-marker) org-mark-ring))
11138 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11139 org-mark-ring)
11141 (defun org-mark-ring-push (&optional pos buffer)
11142 "Put the current position or POS into the mark ring and rotate it."
11143 (interactive)
11144 (setq pos (or pos (point)))
11145 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11146 (move-marker (car org-mark-ring)
11147 (or pos (point))
11148 (or buffer (current-buffer)))
11149 (message "%s"
11150 (substitute-command-keys
11151 "Position saved to mark ring, go back with \
11152 `\\[org-mark-ring-goto]'.")))
11154 (defun org-mark-ring-goto (&optional n)
11155 "Jump to the previous position in the mark ring.
11156 With prefix arg N, jump back that many stored positions. When
11157 called several times in succession, walk through the entire ring.
11158 Org mode commands jumping to a different position in the current file,
11159 or to another Org file, automatically push the old position onto the ring."
11160 (interactive "p")
11161 (let (p m)
11162 (if (eq last-command this-command)
11163 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11164 (setq p org-mark-ring))
11165 (setq org-mark-ring-last-goto p)
11166 (setq m (car p))
11167 (pop-to-buffer-same-window (marker-buffer m))
11168 (goto-char m)
11169 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11171 (defun org-add-angle-brackets (s)
11172 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11173 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11176 ;;; Following specific links
11178 (defvar org-agenda-buffer-tmp-name)
11179 (defvar org-agenda-start-on-weekday)
11180 (defun org-follow-timestamp-link ()
11181 "Open an agenda view for the time-stamp date/range at point."
11182 (cond
11183 ((org-at-date-range-p t)
11184 (let ((org-agenda-start-on-weekday)
11185 (t1 (match-string 1))
11186 (t2 (match-string 2)) tt1 tt2)
11187 (setq tt1 (time-to-days (org-time-string-to-time t1))
11188 tt2 (time-to-days (org-time-string-to-time t2)))
11189 (let ((org-agenda-buffer-tmp-name
11190 (format "*Org Agenda(a:%s)"
11191 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11192 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11193 ((org-at-timestamp-p t)
11194 (let ((org-agenda-buffer-tmp-name
11195 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11196 (org-agenda-list nil (time-to-days (org-time-string-to-time
11197 (substring (match-string 1) 0 10)))
11198 1)))
11199 (t (error "This should not happen"))))
11202 ;;; Following file links
11203 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11204 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11205 (declare-function mailcap-mime-info
11206 "mailcap" (string &optional request no-decode))
11207 (defvar org-wait nil)
11208 (defun org-open-file (path &optional in-emacs line search)
11209 "Open the file at PATH.
11210 First, this expands any special file name abbreviations. Then the
11211 configuration variable `org-file-apps' is checked if it contains an
11212 entry for this file type, and if yes, the corresponding command is launched.
11214 If no application is found, Emacs simply visits the file.
11216 With optional prefix argument IN-EMACS, Emacs will visit the file.
11217 With a double \\[universal-argument] \\[universal-argument] \
11218 prefix arg, Org tries to avoid opening in Emacs
11219 and to use an external application to visit the file.
11221 Optional LINE specifies a line to go to, optional SEARCH a string
11222 to search for. If LINE or SEARCH is given, the file will be
11223 opened in Emacs, unless an entry from org-file-apps that makes
11224 use of groups in a regexp matches.
11226 If you want to change the way frames are used when following a
11227 link, please customize `org-link-frame-setup'.
11229 If the file does not exist, an error is thrown."
11230 (let* ((file (if (equal path "")
11231 buffer-file-name
11232 (substitute-in-file-name (expand-file-name path))))
11233 (file-apps (append org-file-apps (org-default-apps)))
11234 (apps (cl-remove-if
11235 'org-file-apps-entry-match-against-dlink-p file-apps))
11236 (apps-dlink (cl-remove-if-not
11237 'org-file-apps-entry-match-against-dlink-p file-apps))
11238 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11239 (dirp (unless remp (file-directory-p file)))
11240 (file (if (and dirp org-open-directory-means-index-dot-org)
11241 (concat (file-name-as-directory file) "index.org")
11242 file))
11243 (a-m-a-p (assq 'auto-mode apps))
11244 (dfile (downcase file))
11245 ;; Reconstruct the original link from the PATH, LINE and
11246 ;; SEARCH args.
11247 (link (cond (line (concat file "::" (number-to-string line)))
11248 (search (concat file "::" search))
11249 (t file)))
11250 (dlink (downcase link))
11251 (ext
11252 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11253 (match-string 1 dfile)))
11254 (save-position-maybe
11255 (let ((old-buffer (current-buffer))
11256 (old-pos (point))
11257 (old-mode major-mode))
11258 (lambda ()
11259 (and (derived-mode-p 'org-mode)
11260 (eq old-mode 'org-mode)
11261 (or (not (eq old-buffer (current-buffer)))
11262 (not (eq old-pos (point))))
11263 (org-mark-ring-push old-pos old-buffer)))))
11264 cmd link-match-data)
11265 (cond
11266 ((member in-emacs '((16) system))
11267 (setq cmd (cdr (assq 'system apps))))
11268 (in-emacs (setq cmd 'emacs))
11270 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11271 (and dirp (cdr (assq 'directory apps)))
11272 ;; First, try matching against apps-dlink if we
11273 ;; get a match here, store the match data for
11274 ;; later.
11275 (let ((match (assoc-default dlink apps-dlink
11276 'string-match)))
11277 (if match
11278 (progn (setq link-match-data (match-data))
11279 match)
11280 (progn (setq in-emacs (or in-emacs line search))
11281 nil))) ; if we have no match in apps-dlink,
11282 ; always open the file in emacs if line or search
11283 ; is given (for backwards compatibility)
11284 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11285 'string-match)
11286 (cdr (assoc ext apps))
11287 (cdr (assq t apps))))))
11288 (when (eq cmd 'system)
11289 (setq cmd (cdr (assq 'system apps))))
11290 (when (eq cmd 'default)
11291 (setq cmd (cdr (assoc t apps))))
11292 (when (eq cmd 'mailcap)
11293 (require 'mailcap)
11294 (mailcap-parse-mailcaps)
11295 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11296 (command (mailcap-mime-info mime-type)))
11297 (if (stringp command)
11298 (setq cmd command)
11299 (setq cmd 'emacs))))
11300 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11301 (not (file-exists-p file))
11302 (not org-open-non-existing-files))
11303 (user-error "No such file: %s" file))
11304 (cond
11305 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11306 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11307 (while (string-match "['\"]%s['\"]" cmd)
11308 (setq cmd (replace-match "%s" t t cmd)))
11309 (setq cmd (replace-regexp-in-string
11310 "%s"
11311 (shell-quote-argument (convert-standard-filename file))
11313 nil t))
11315 ;; Replace "%1", "%2" etc. in command with group matches from regex
11316 (save-match-data
11317 (let ((match-index 1)
11318 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11319 (set-match-data link-match-data)
11320 (while (<= match-index number-of-groups)
11321 (let ((regex (concat "%" (number-to-string match-index)))
11322 (replace-with (match-string match-index dlink)))
11323 (while (string-match regex cmd)
11324 (setq cmd (replace-match replace-with t t cmd))))
11325 (setq match-index (+ match-index 1)))))
11327 (save-window-excursion
11328 (message "Running %s...done" cmd)
11329 (start-process-shell-command cmd nil cmd)
11330 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11331 ((or (stringp cmd)
11332 (eq cmd 'emacs))
11333 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11334 (widen)
11335 (cond (line (org-goto-line line)
11336 (when (derived-mode-p 'org-mode) (org-reveal)))
11337 (search (condition-case err
11338 (org-link-search search)
11339 ;; Save position before error-ing out so user
11340 ;; can easily move back to the original buffer.
11341 (error (funcall save-position-maybe)
11342 (error (nth 1 err)))))))
11343 ((functionp cmd)
11344 (save-match-data
11345 (set-match-data link-match-data)
11346 (condition-case nil
11347 (funcall cmd file link)
11348 ;; FIXME: Remove this check when most default installations
11349 ;; of Emacs have at least Org 9.0.
11350 ((debug wrong-number-of-arguments wrong-type-argument
11351 invalid-function)
11352 (user-error "Please see Org News for version 9.0 about \
11353 `org-file-apps'--Lisp error: %S" cmd)))))
11354 ((consp cmd)
11355 ;; FIXME: Remove this check when most default installations of
11356 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11357 ;; fall back to `org-link-frame-setup' for an old usage of
11358 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11359 (user-error "Please see Org News for version 9.0 about \
11360 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11361 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11362 (funcall save-position-maybe)))
11364 (defun org-file-apps-entry-match-against-dlink-p (entry)
11365 "This function returns non-nil if `entry' uses a regular
11366 expression which should be matched against the whole link by
11367 org-open-file.
11369 It assumes that is the case when the entry uses a regular
11370 expression which has at least one grouping construct and the
11371 action is either a lisp form or a command string containing
11372 `%1', i.e. using at least one subexpression match as a
11373 parameter."
11374 (let ((selector (car entry))
11375 (action (cdr entry)))
11376 (if (stringp selector)
11377 (and (> (regexp-opt-depth selector) 0)
11378 (or (and (stringp action)
11379 (string-match "%[0-9]" action))
11380 (consp action)))
11381 nil)))
11383 (defun org-default-apps ()
11384 "Return the default applications for this operating system."
11385 (cond
11386 ((eq system-type 'darwin)
11387 org-file-apps-defaults-macosx)
11388 ((eq system-type 'windows-nt)
11389 org-file-apps-defaults-windowsnt)
11390 (t org-file-apps-defaults-gnu)))
11392 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11393 "Convert extensions to regular expressions in the cars of LIST.
11394 Also, weed out any non-string entries, because the return value is used
11395 only for regexp matching.
11396 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11397 point to the symbol `emacs', indicating that the file should
11398 be opened in Emacs."
11399 (append
11400 (delq nil
11401 (mapcar (lambda (x)
11402 (unless (not (stringp (car x)))
11403 (if (string-match "\\W" (car x))
11405 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11406 list))
11407 (when add-auto-mode
11408 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11410 (defvar ange-ftp-name-format)
11411 (defun org-file-remote-p (file)
11412 "Test whether FILE specifies a location on a remote system.
11413 Return non-nil if the location is indeed remote.
11415 For example, the filename \"/user@host:/foo\" specifies a location
11416 on the system \"/user@host:\"."
11417 (cond ((fboundp 'file-remote-p)
11418 (file-remote-p file))
11419 ((fboundp 'tramp-handle-file-remote-p)
11420 (tramp-handle-file-remote-p file))
11421 ((and (boundp 'ange-ftp-name-format)
11422 (string-match (car ange-ftp-name-format) file))
11423 t)))
11426 ;;;; Refiling
11428 (defun org-get-org-file ()
11429 "Read a filename, with default directory `org-directory'."
11430 (let ((default (or org-default-notes-file remember-data-file)))
11431 (read-file-name (format "File name [%s]: " default)
11432 (file-name-as-directory org-directory)
11433 default)))
11435 (defun org-notes-order-reversed-p ()
11436 "Check if the current file should receive notes in reversed order."
11437 (cond
11438 ((not org-reverse-note-order) nil)
11439 ((eq t org-reverse-note-order) t)
11440 ((not (listp org-reverse-note-order)) nil)
11441 (t (catch 'exit
11442 (dolist (entry org-reverse-note-order)
11443 (when (string-match (car entry) buffer-file-name)
11444 (throw 'exit (cdr entry))))))))
11446 (defvar org-refile-target-table nil
11447 "The list of refile targets, created by `org-refile'.")
11449 (defvar org-agenda-new-buffers nil
11450 "Buffers created to visit agenda files.")
11452 (defvar org-refile-cache nil
11453 "Cache for refile targets.")
11455 (defvar org-refile-markers nil
11456 "All the markers used for caching refile locations.")
11458 (defun org-refile-marker (pos)
11459 "Get a new refile marker, but only if caching is in use."
11460 (if (not org-refile-use-cache)
11462 (let ((m (make-marker)))
11463 (move-marker m pos)
11464 (push m org-refile-markers)
11465 m)))
11467 (defun org-refile-cache-clear ()
11468 "Clear the refile cache and disable all the markers."
11469 (dolist (m org-refile-markers) (move-marker m nil))
11470 (setq org-refile-markers nil)
11471 (setq org-refile-cache nil)
11472 (message "Refile cache has been cleared"))
11474 (defun org-refile-cache-check-set (set)
11475 "Check if all the markers in the cache still have live buffers."
11476 (let (marker)
11477 (catch 'exit
11478 (while (and set (setq marker (nth 3 (pop set))))
11479 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11480 (when (and marker (null (marker-buffer marker)))
11481 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11482 (sit-for 3)
11483 (throw 'exit nil)))
11484 t)))
11486 (defun org-refile-cache-put (set &rest identifiers)
11487 "Push the refile targets SET into the cache, under IDENTIFIERS."
11488 (let* ((key (sha1 (prin1-to-string identifiers)))
11489 (entry (assoc key org-refile-cache)))
11490 (if entry
11491 (setcdr entry set)
11492 (push (cons key set) org-refile-cache))))
11494 (defun org-refile-cache-get (&rest identifiers)
11495 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11496 (cond
11497 ((not org-refile-cache) nil)
11498 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11500 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11501 org-refile-cache))))
11502 (and set (org-refile-cache-check-set set) set)))))
11504 (defvar org-outline-path-cache nil
11505 "Alist between buffer positions and outline paths.
11506 It value is an alist (POSITION . PATH) where POSITION is the
11507 buffer position at the beginning of an entry and PATH is a list
11508 of strings describing the outline path for that entry, in reverse
11509 order.")
11511 (defun org-refile-get-targets (&optional default-buffer)
11512 "Produce a table with refile targets."
11513 (let ((case-fold-search nil)
11514 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11515 (entries (or org-refile-targets '((nil . (:level . 1)))))
11516 targets tgs files desc descre)
11517 (message "Getting targets...")
11518 (with-current-buffer (or default-buffer (current-buffer))
11519 (dolist (entry entries)
11520 (setq files (car entry) desc (cdr entry))
11521 (cond
11522 ((null files) (setq files (list (current-buffer))))
11523 ((eq files 'org-agenda-files)
11524 (setq files (org-agenda-files 'unrestricted)))
11525 ((and (symbolp files) (fboundp files))
11526 (setq files (funcall files)))
11527 ((and (symbolp files) (boundp files))
11528 (setq files (symbol-value files))))
11529 (when (stringp files) (setq files (list files)))
11530 (cond
11531 ((eq (car desc) :tag)
11532 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11533 ((eq (car desc) :todo)
11534 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11535 ((eq (car desc) :regexp)
11536 (setq descre (cdr desc)))
11537 ((eq (car desc) :level)
11538 (setq descre (concat "^\\*\\{" (number-to-string
11539 (if org-odd-levels-only
11540 (1- (* 2 (cdr desc)))
11541 (cdr desc)))
11542 "\\}[ \t]")))
11543 ((eq (car desc) :maxlevel)
11544 (setq descre (concat "^\\*\\{1," (number-to-string
11545 (if org-odd-levels-only
11546 (1- (* 2 (cdr desc)))
11547 (cdr desc)))
11548 "\\}[ \t]")))
11549 (t (error "Bad refiling target description %s" desc)))
11550 (dolist (f files)
11551 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11553 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11554 (progn
11555 (when (bufferp f)
11556 (setq f (buffer-file-name (buffer-base-buffer f))))
11557 (setq f (and f (expand-file-name f)))
11558 (when (eq org-refile-use-outline-path 'file)
11559 (push (list (file-name-nondirectory f) f nil nil) tgs))
11560 (org-with-wide-buffer
11561 (goto-char (point-min))
11562 (setq org-outline-path-cache nil)
11563 (while (re-search-forward descre nil t)
11564 (beginning-of-line)
11565 (let ((case-fold-search nil))
11566 (looking-at org-complex-heading-regexp))
11567 (let ((begin (point))
11568 (heading (match-string-no-properties 4)))
11569 (unless (or (and
11570 org-refile-target-verify-function
11571 (not
11572 (funcall org-refile-target-verify-function)))
11573 (not heading))
11574 (let ((re (format org-complex-heading-regexp-format
11575 (regexp-quote heading)))
11576 (target
11577 (if (not org-refile-use-outline-path) heading
11578 (mapconcat
11579 #'org-protect-slash
11580 (append
11581 (pcase org-refile-use-outline-path
11582 (`file (list (file-name-nondirectory
11583 (buffer-file-name
11584 (buffer-base-buffer)))))
11585 (`full-file-path
11586 (list (buffer-file-name
11587 (buffer-base-buffer))))
11588 (_ nil))
11589 (org-get-outline-path t t))
11590 "/"))))
11591 (push (list target f re (org-refile-marker (point)))
11592 tgs)))
11593 (when (= (point) begin)
11594 ;; Verification function has not moved point.
11595 (end-of-line)))))))
11596 (when org-refile-use-cache
11597 (org-refile-cache-put tgs (buffer-file-name) descre))
11598 (setq targets (append tgs targets))))))
11599 (message "Getting targets...done")
11600 (nreverse targets)))
11602 (defun org-protect-slash (s)
11603 (replace-regexp-in-string "/" "\\/" s nil t))
11605 (defun org--get-outline-path-1 (&optional use-cache)
11606 "Return outline path to current headline.
11608 Outline path is a list of strings, in reverse order. When
11609 optional argument USE-CACHE is non-nil, make use of a cache. See
11610 `org-get-outline-path' for details.
11612 Assume buffer is widened and point is on a headline."
11613 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11614 (let ((p (point))
11615 (heading (let ((case-fold-search nil))
11616 (looking-at org-complex-heading-regexp)
11617 (if (not (match-end 4)) ""
11618 ;; Remove statistics cookies.
11619 (org-trim
11620 (org-link-display-format
11621 (replace-regexp-in-string
11622 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11623 (match-string-no-properties 4))))))))
11624 (if (org-up-heading-safe)
11625 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11626 (when use-cache
11627 (push (cons p path) org-outline-path-cache))
11628 path)
11629 ;; This is a new root node. Since we assume we are moving
11630 ;; forward, we can drop previous cache so as to limit number
11631 ;; of associations there.
11632 (let ((path (list heading)))
11633 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11634 path)))))
11636 (defun org-get-outline-path (&optional with-self use-cache)
11637 "Return the outline path to the current entry.
11639 An outline path is a list of ancestors for current headline, as
11640 a list of strings. Statistics cookies are removed and links are
11641 replaced with their description, if any, or their path otherwise.
11643 When optional argument WITH-SELF is non-nil, the path also
11644 includes the current headline.
11646 When optional argument USE-CACHE is non-nil, cache outline paths
11647 between calls to this function so as to avoid backtracking. This
11648 argument is useful when planning to find more than one outline
11649 path in the same document. In that case, there are two
11650 conditions to satisfy:
11651 - `org-outline-path-cache' is set to nil before starting the
11652 process;
11653 - outline paths are computed by increasing buffer positions."
11654 (org-with-wide-buffer
11655 (and (or (and with-self (org-back-to-heading t))
11656 (org-up-heading-safe))
11657 (reverse (org--get-outline-path-1 use-cache)))))
11659 (defun org-format-outline-path (path &optional width prefix separator)
11660 "Format the outline path PATH for display.
11661 WIDTH is the maximum number of characters that is available.
11662 PREFIX is a prefix to be included in the returned string,
11663 such as the file name.
11664 SEPARATOR is inserted between the different parts of the path,
11665 the default is \"/\"."
11666 (setq width (or width 79))
11667 (setq path (delq nil path))
11668 (unless (> width 0)
11669 (user-error "Argument `width' must be positive"))
11670 (setq separator (or separator "/"))
11671 (let* ((org-odd-levels-only nil)
11672 (fpath (concat
11673 prefix (and prefix path separator)
11674 (mapconcat
11675 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11676 (cl-loop for head in path
11677 for n from 0
11678 collect (org-add-props
11679 head nil 'face
11680 (nth (% n org-n-level-faces) org-level-faces)))
11681 separator))))
11682 (when (> (length fpath) width)
11683 (if (< width 7)
11684 ;; It's unlikely that `width' will be this small, but don't
11685 ;; waste characters by adding ".." if it is.
11686 (setq fpath (substring fpath 0 width))
11687 (setf (substring fpath (- width 2)) "..")))
11688 fpath))
11690 (defun org-display-outline-path (&optional file current separator just-return-string)
11691 "Display the current outline path in the echo area.
11693 If FILE is non-nil, prepend the output with the file name.
11694 If CURRENT is non-nil, append the current heading to the output.
11695 SEPARATOR is passed through to `org-format-outline-path'. It separates
11696 the different parts of the path and defaults to \"/\".
11697 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11698 (interactive "P")
11699 (let* (case-fold-search
11700 (bfn (buffer-file-name (buffer-base-buffer)))
11701 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11702 res)
11703 (when current (setq path (append path
11704 (save-excursion
11705 (org-back-to-heading t)
11706 (when (looking-at org-complex-heading-regexp)
11707 (list (match-string 4)))))))
11708 (setq res
11709 (org-format-outline-path
11710 path
11711 (1- (frame-width))
11712 (and file bfn (concat (file-name-nondirectory bfn) separator))
11713 separator))
11714 (if just-return-string
11715 (org-no-properties res)
11716 (org-unlogged-message "%s" res))))
11718 (defvar org-refile-history nil
11719 "History for refiling operations.")
11721 (defvar org-after-refile-insert-hook nil
11722 "Hook run after `org-refile' has inserted its stuff at the new location.
11723 Note that this is still *before* the stuff will be removed from
11724 the *old* location.")
11726 (defvar org-capture-last-stored-marker)
11727 (defvar org-refile-keep nil
11728 "Non-nil means `org-refile' will copy instead of refile.")
11730 (defun org-copy ()
11731 "Like `org-refile', but copy."
11732 (interactive)
11733 (let ((org-refile-keep t))
11734 (funcall 'org-refile nil nil nil "Copy")))
11736 (defun org-refile (&optional arg default-buffer rfloc msg)
11737 "Move the entry or entries at point to another heading.
11739 The list of target headings is compiled using the information in
11740 `org-refile-targets', which see.
11742 At the target location, the entry is filed as a subitem of the
11743 target heading. Depending on `org-reverse-note-order', the new
11744 subitem will either be the first or the last subitem.
11746 If there is an active region, all entries in that region will be
11747 refiled. However, the region must fulfill the requirement that
11748 the first heading sets the top-level of the moved text.
11750 With a `\\[universal-argument]' ARG, the command will only visit the target \
11751 location
11752 and not actually move anything.
11754 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11755 location where the last
11756 refiling operation has put the subtree.
11758 With a numeric prefix argument of `2', refile to the running clock.
11760 With a numeric prefix argument of `3', emulate `org-refile-keep'
11761 being set to t and copy to the target location, don't move it.
11762 Beware that keeping refiled entries may result in duplicated ID
11763 properties.
11765 RFLOC can be a refile location obtained in a different way.
11767 MSG is a string to replace \"Refile\" in the default prompt with
11768 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11770 See also `org-refile-use-outline-path'.
11772 If you are using target caching (see `org-refile-use-cache'), you
11773 have to clear the target cache in order to find new targets.
11774 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11775 prefix argument (`C-u C-u C-u C-c C-w')."
11776 (interactive "P")
11777 (if (member arg '(0 (64)))
11778 (org-refile-cache-clear)
11779 (let* ((actionmsg (cond (msg msg)
11780 ((equal arg 3) "Refile (and keep)")
11781 (t "Refile")))
11782 (regionp (org-region-active-p))
11783 (region-start (and regionp (region-beginning)))
11784 (region-end (and regionp (region-end)))
11785 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11786 pos it nbuf file level reversed)
11787 (setq last-command nil)
11788 (when regionp
11789 (goto-char region-start)
11790 (or (bolp) (goto-char (point-at-bol)))
11791 (setq region-start (point))
11792 (unless (or (org-kill-is-subtree-p
11793 (buffer-substring region-start region-end))
11794 (prog1 org-refile-active-region-within-subtree
11795 (let ((s (point-at-eol)))
11796 (org-toggle-heading)
11797 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11798 (user-error "The region is not a (sequence of) subtree(s)")))
11799 (if (equal arg '(16))
11800 (org-refile-goto-last-stored)
11801 (when (or
11802 (and (equal arg 2)
11803 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11804 (prog1
11805 (setq it (list (or org-clock-heading "running clock")
11806 (buffer-file-name
11807 (marker-buffer org-clock-hd-marker))
11809 (marker-position org-clock-hd-marker)))
11810 (setq arg nil)))
11811 (setq it
11812 (or rfloc
11813 (let (heading-text)
11814 (save-excursion
11815 (unless (and arg (listp arg))
11816 (org-back-to-heading t)
11817 (setq heading-text
11818 (replace-regexp-in-string
11819 org-bracket-link-regexp
11820 "\\3"
11821 (or (nth 4 (org-heading-components))
11822 ""))))
11823 (org-refile-get-location
11824 (cond ((and arg (listp arg)) "Goto")
11825 (regionp (concat actionmsg " region to"))
11826 (t (concat actionmsg " subtree \""
11827 heading-text "\" to")))
11828 default-buffer
11829 (and (not (equal '(4) arg))
11830 org-refile-allow-creating-parent-nodes)))))))
11831 (setq file (nth 1 it)
11832 pos (nth 3 it))
11833 (when (and (not arg)
11835 (equal (buffer-file-name) file)
11836 (if regionp
11837 (and (>= pos region-start)
11838 (<= pos region-end))
11839 (and (>= pos (point))
11840 (< pos (save-excursion
11841 (org-end-of-subtree t t))))))
11842 (error "Cannot refile to position inside the tree or region"))
11843 (setq nbuf (or (find-buffer-visiting file)
11844 (find-file-noselect file)))
11845 (if (and arg (not (equal arg 3)))
11846 (progn
11847 (pop-to-buffer-same-window nbuf)
11848 (goto-char pos)
11849 (org-show-context 'org-goto))
11850 (if regionp
11851 (progn
11852 (org-kill-new (buffer-substring region-start region-end))
11853 (org-save-markers-in-region region-start region-end))
11854 (org-copy-subtree 1 nil t))
11855 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11856 (find-file-noselect file)))
11857 (setq reversed (org-notes-order-reversed-p))
11858 (org-with-wide-buffer
11859 (if pos
11860 (progn
11861 (goto-char pos)
11862 (setq level (org-get-valid-level (funcall outline-level) 1))
11863 (goto-char
11864 (if reversed
11865 (or (outline-next-heading) (point-max))
11866 (or (save-excursion (org-get-next-sibling))
11867 (org-end-of-subtree t t)
11868 (point-max)))))
11869 (setq level 1)
11870 (if (not reversed)
11871 (goto-char (point-max))
11872 (goto-char (point-min))
11873 (or (outline-next-heading) (goto-char (point-max)))))
11874 (unless (bolp) (newline))
11875 (org-paste-subtree level nil nil t)
11876 (when org-log-refile
11877 (org-add-log-setup 'refile nil nil org-log-refile)
11878 (unless (eq org-log-refile 'note)
11879 (save-excursion (org-add-log-note))))
11880 (and org-auto-align-tags
11881 (let ((org-loop-over-headlines-in-active-region nil))
11882 (org-set-tags nil t)))
11883 (let ((bookmark-name (plist-get org-bookmark-names-plist
11884 :last-refile)))
11885 (when bookmark-name
11886 (with-demoted-errors
11887 (bookmark-set bookmark-name))))
11888 ;; If we are refiling for capture, make sure that the
11889 ;; last-capture pointers point here
11890 (when (bound-and-true-p org-capture-is-refiling)
11891 (let ((bookmark-name (plist-get org-bookmark-names-plist
11892 :last-capture-marker)))
11893 (when bookmark-name
11894 (with-demoted-errors
11895 (bookmark-set bookmark-name))))
11896 (move-marker org-capture-last-stored-marker (point)))
11897 (when (fboundp 'deactivate-mark) (deactivate-mark))
11898 (run-hooks 'org-after-refile-insert-hook)))
11899 (unless org-refile-keep
11900 (if regionp
11901 (delete-region (point) (+ (point) (- region-end region-start)))
11902 (delete-region
11903 (and (org-back-to-heading t) (point))
11904 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11905 (when (featurep 'org-inlinetask)
11906 (org-inlinetask-remove-END-maybe))
11907 (setq org-markers-to-move nil)
11908 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11910 (defun org-refile-goto-last-stored ()
11911 "Go to the location where the last refile was stored."
11912 (interactive)
11913 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11914 (message "This is the location of the last refile"))
11916 (defun org-refile--get-location (refloc tbl)
11917 "When user refile to REFLOC, find the associated target in TBL.
11918 Also check `org-refile-target-table'."
11919 (car (delq
11921 (mapcar
11922 (lambda (r) (or (assoc r tbl)
11923 (assoc r org-refile-target-table)))
11924 (list (replace-regexp-in-string "/$" "" refloc)
11925 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11927 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11928 "Prompt the user for a refile location, using PROMPT.
11929 PROMPT should not be suffixed with a colon and a space, because
11930 this function appends the default value from
11931 `org-refile-history' automatically, if that is not empty."
11932 (let ((org-refile-targets org-refile-targets)
11933 (org-refile-use-outline-path org-refile-use-outline-path))
11934 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11935 (unless org-refile-target-table
11936 (user-error "No refile targets"))
11937 (let* ((cbuf (current-buffer))
11938 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11939 (cfunc (if (and org-refile-use-outline-path
11940 org-outline-path-complete-in-steps)
11941 #'org-olpath-completing-read
11942 #'completing-read))
11943 (extra (if org-refile-use-outline-path "/" ""))
11944 (cbnex (concat (buffer-name) extra))
11945 (filename (and cfn (expand-file-name cfn)))
11946 (tbl (mapcar
11947 (lambda (x)
11948 (if (and (not (member org-refile-use-outline-path
11949 '(file full-file-path)))
11950 (not (equal filename (nth 1 x))))
11951 (cons (concat (car x) extra " ("
11952 (file-name-nondirectory (nth 1 x)) ")")
11953 (cdr x))
11954 (cons (concat (car x) extra) (cdr x))))
11955 org-refile-target-table))
11956 (completion-ignore-case t)
11957 cdef
11958 (prompt (concat prompt
11959 (or (and (car org-refile-history)
11960 (concat " (default " (car org-refile-history) ")"))
11961 (and (assoc cbnex tbl) (setq cdef cbnex)
11962 (concat " (default " cbnex ")"))) ": "))
11963 pa answ parent-target child parent old-hist)
11964 (setq old-hist org-refile-history)
11965 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11966 nil 'org-refile-history (or cdef (car org-refile-history))))
11967 (if (setq pa (org-refile--get-location answ tbl))
11968 (progn
11969 (org-refile-check-position pa)
11970 (when (or (not org-refile-history)
11971 (not (eq old-hist org-refile-history))
11972 (not (equal (car pa) (car org-refile-history))))
11973 (setq org-refile-history
11974 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11975 org-refile-history
11976 (cdr org-refile-history))))
11977 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11978 (pop org-refile-history)))
11980 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11981 (progn
11982 (setq parent (match-string 1 answ)
11983 child (match-string 2 answ))
11984 (setq parent-target (org-refile--get-location parent tbl))
11985 (when (and parent-target
11986 (or (eq new-nodes t)
11987 (and (eq new-nodes 'confirm)
11988 (y-or-n-p (format "Create new node \"%s\"? "
11989 child)))))
11990 (org-refile-new-child parent-target child)))
11991 (user-error "Invalid target location")))))
11993 (declare-function org-string-nw-p "org-macs" (s))
11994 (defun org-refile-check-position (refile-pointer)
11995 "Check if the refile pointer matches the headline to which it points."
11996 (let* ((file (nth 1 refile-pointer))
11997 (re (nth 2 refile-pointer))
11998 (pos (nth 3 refile-pointer))
11999 buffer)
12000 (if (and (not (markerp pos)) (not file))
12001 (user-error "Please indicate a target file in the refile path")
12002 (when (org-string-nw-p re)
12003 (setq buffer (if (markerp pos)
12004 (marker-buffer pos)
12005 (or (find-buffer-visiting file)
12006 (find-file-noselect file))))
12007 (with-current-buffer buffer
12008 (org-with-wide-buffer
12009 (goto-char pos)
12010 (beginning-of-line 1)
12011 (unless (looking-at-p re)
12012 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12014 (defun org-refile-new-child (parent-target child)
12015 "Use refile target PARENT-TARGET to add new CHILD below it."
12016 (unless parent-target
12017 (error "Cannot find parent for new node"))
12018 (let ((file (nth 1 parent-target))
12019 (pos (nth 3 parent-target))
12020 level)
12021 (with-current-buffer (or (find-buffer-visiting file)
12022 (find-file-noselect file))
12023 (org-with-wide-buffer
12024 (if pos
12025 (goto-char pos)
12026 (goto-char (point-max))
12027 (unless (bolp) (newline)))
12028 (when (looking-at org-outline-regexp)
12029 (setq level (funcall outline-level))
12030 (org-end-of-subtree t t))
12031 (org-back-over-empty-lines)
12032 (insert "\n" (make-string
12033 (if pos (org-get-valid-level level 1) 1) ?*)
12034 " " child "\n")
12035 (beginning-of-line 0)
12036 (list (concat (car parent-target) "/" child) file "" (point))))))
12038 (defun org-olpath-completing-read (prompt collection &rest args)
12039 "Read an outline path like a file name."
12040 (let ((thetable collection))
12041 (apply #'completing-read
12042 prompt
12043 (lambda (string predicate &optional flag)
12044 (cond
12045 ((eq flag nil) (try-completion string thetable))
12046 ((eq flag t)
12047 (let ((l (length string)))
12048 (mapcar (lambda (x)
12049 (let ((r (substring x l))
12050 (f (if (string-match " ([^)]*)$" x)
12051 (match-string 0 x)
12052 "")))
12053 (if (string-match "/" r)
12054 (concat string (substring r 0 (match-end 0)) f)
12055 x)))
12056 (all-completions string thetable predicate))))
12057 ;; Exact match?
12058 ((eq flag 'lambda) (assoc string thetable))))
12059 args)))
12061 ;;;; Dynamic blocks
12063 (defun org-find-dblock (name)
12064 "Find the first dynamic block with name NAME in the buffer.
12065 If not found, stay at current position and return nil."
12066 (let ((case-fold-search t) pos)
12067 (save-excursion
12068 (goto-char (point-min))
12069 (setq pos (and (re-search-forward
12070 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12071 (match-beginning 0))))
12072 (when pos (goto-char pos))
12073 pos))
12075 (defun org-create-dblock (plist)
12076 "Create a dynamic block section, with parameters taken from PLIST.
12077 PLIST must contain a :name entry which is used as the name of the block."
12078 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12079 (end-of-line 1)
12080 (newline))
12081 (let ((col (current-column))
12082 (name (plist-get plist :name)))
12083 (insert "#+BEGIN: " name)
12084 (while plist
12085 (if (eq (car plist) :name)
12086 (setq plist (cddr plist))
12087 (insert " " (prin1-to-string (pop plist)))))
12088 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12089 (beginning-of-line -2)))
12091 (defun org-prepare-dblock ()
12092 "Prepare dynamic block for refresh.
12093 This empties the block, puts the cursor at the insert position and returns
12094 the property list including an extra property :name with the block name."
12095 (unless (looking-at org-dblock-start-re)
12096 (user-error "Not at a dynamic block"))
12097 (let* ((begdel (1+ (match-end 0)))
12098 (name (org-no-properties (match-string 1)))
12099 (params (append (list :name name)
12100 (read (concat "(" (match-string 3) ")")))))
12101 (save-excursion
12102 (beginning-of-line 1)
12103 (skip-chars-forward " \t")
12104 (setq params (plist-put params :indentation-column (current-column))))
12105 (unless (re-search-forward org-dblock-end-re nil t)
12106 (error "Dynamic block not terminated"))
12107 (setq params
12108 (append params
12109 (list :content (buffer-substring
12110 begdel (match-beginning 0)))))
12111 (delete-region begdel (match-beginning 0))
12112 (goto-char begdel)
12113 (open-line 1)
12114 params))
12116 (defun org-map-dblocks (&optional command)
12117 "Apply COMMAND to all dynamic blocks in the current buffer.
12118 If COMMAND is not given, use `org-update-dblock'."
12119 (let ((cmd (or command 'org-update-dblock)))
12120 (save-excursion
12121 (goto-char (point-min))
12122 (while (re-search-forward org-dblock-start-re nil t)
12123 (goto-char (match-beginning 0))
12124 (save-excursion
12125 (condition-case nil
12126 (funcall cmd)
12127 (error (message "Error during update of dynamic block"))))
12128 (unless (re-search-forward org-dblock-end-re nil t)
12129 (error "Dynamic block not terminated"))))))
12131 (defun org-dblock-update (&optional arg)
12132 "User command for updating dynamic blocks.
12133 Update the dynamic block at point. With prefix ARG, update all dynamic
12134 blocks in the buffer."
12135 (interactive "P")
12136 (if arg
12137 (org-update-all-dblocks)
12138 (or (looking-at org-dblock-start-re)
12139 (org-beginning-of-dblock))
12140 (org-update-dblock)))
12142 (defun org-update-dblock ()
12143 "Update the dynamic block at point.
12144 This means to empty the block, parse for parameters and then call
12145 the correct writing function."
12146 (interactive)
12147 (save-excursion
12148 (let* ((win (selected-window))
12149 (pos (point))
12150 (line (org-current-line))
12151 (params (org-prepare-dblock))
12152 (name (plist-get params :name))
12153 (indent (plist-get params :indentation-column))
12154 (cmd (intern (concat "org-dblock-write:" name))))
12155 (message "Updating dynamic block `%s' at line %d..." name line)
12156 (funcall cmd params)
12157 (message "Updating dynamic block `%s' at line %d...done" name line)
12158 (goto-char pos)
12159 (when (and indent (> indent 0))
12160 (setq indent (make-string indent ?\ ))
12161 (save-excursion
12162 (select-window win)
12163 (org-beginning-of-dblock)
12164 (forward-line 1)
12165 (while (not (looking-at org-dblock-end-re))
12166 (insert indent)
12167 (beginning-of-line 2))
12168 (when (looking-at org-dblock-end-re)
12169 (and (looking-at "[ \t]+")
12170 (replace-match ""))
12171 (insert indent)))))))
12173 (defun org-beginning-of-dblock ()
12174 "Find the beginning of the dynamic block at point.
12175 Error if there is no such block at point."
12176 (let ((pos (point))
12177 beg)
12178 (end-of-line 1)
12179 (if (and (re-search-backward org-dblock-start-re nil t)
12180 (setq beg (match-beginning 0))
12181 (re-search-forward org-dblock-end-re nil t)
12182 (> (match-end 0) pos))
12183 (goto-char beg)
12184 (goto-char pos)
12185 (error "Not in a dynamic block"))))
12187 (defun org-update-all-dblocks ()
12188 "Update all dynamic blocks in the buffer.
12189 This function can be used in a hook."
12190 (interactive)
12191 (when (derived-mode-p 'org-mode)
12192 (org-map-dblocks 'org-update-dblock)))
12195 ;;;; Completion
12197 (declare-function org-export-backend-options "ox" (cl-x) t)
12198 (defun org-get-export-keywords ()
12199 "Return a list of all currently understood export keywords.
12200 Export keywords include options, block names, attributes and
12201 keywords relative to each registered export back-end."
12202 (let (keywords)
12203 (dolist (backend
12204 (bound-and-true-p org-export-registered-backends)
12205 (delq nil keywords))
12206 ;; Back-end name (for keywords, like #+LATEX:)
12207 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12208 (dolist (option-entry (org-export-backend-options backend))
12209 ;; Back-end options.
12210 (push (nth 1 option-entry) keywords)))))
12212 (defconst org-options-keywords
12213 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12214 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12215 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12216 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12217 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12219 (defcustom org-structure-template-alist
12220 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12221 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12222 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12223 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12224 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12225 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12226 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12227 ("L" "#+LaTeX: ")
12228 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12229 ("H" "#+HTML: ")
12230 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12231 ("A" "#+ASCII: ")
12232 ("i" "#+INDEX: ?")
12233 ("I" "#+INCLUDE: %file ?"))
12234 "Structure completion elements.
12235 This is a list of abbreviation keys and values. The value gets inserted
12236 if you type `<' followed by the key and then press the completion key,
12237 usually `TAB'. %file will be replaced by a file name after prompting
12238 for the file using completion. The cursor will be placed at the position
12239 of the `?' in the template.
12240 There are two templates for each key, the first uses the original Org syntax,
12241 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12242 the default when the /org-mtags.el/ module has been loaded. See also the
12243 variable `org-mtags-prefer-muse-templates'."
12244 :group 'org-completion
12245 :type '(repeat
12246 (list
12247 (string :tag "Key")
12248 (string :tag "Template")))
12249 :version "26.1"
12250 :package-version '(Org . "8.3"))
12252 (defun org-try-structure-completion ()
12253 "Try to complete a structure template before point.
12254 This looks for strings like \"<e\" on an otherwise empty line and
12255 expands them."
12256 (let ((l (buffer-substring (point-at-bol) (point)))
12258 (when (and (looking-at "[ \t]*$")
12259 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12260 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12261 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12262 (match-beginning 1)) a)
12263 t)))
12265 (defun org-complete-expand-structure-template (start cell)
12266 "Expand a structure template."
12267 (let ((rpl (nth 1 cell))
12268 (ind ""))
12269 (delete-region start (point))
12270 (when (string-match "\\`[ \t]*#\\+" rpl)
12271 (cond
12272 ((bolp))
12273 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12274 (setq ind (buffer-substring (point-at-bol) (point))))
12275 (t (newline))))
12276 (setq start (point))
12277 (when (string-match "%file" rpl)
12278 (setq rpl (replace-match
12279 (concat
12280 "\""
12281 (save-match-data
12282 (abbreviate-file-name (read-file-name "Include file: ")))
12283 "\"")
12284 t t rpl)))
12285 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12286 (concat "\n" ind)))
12287 (insert rpl)
12288 (when (re-search-backward "\\?" start t) (delete-char 1))))
12290 ;;;; TODO, DEADLINE, Comments
12292 (defun org-toggle-comment ()
12293 "Change the COMMENT state of an entry."
12294 (interactive)
12295 (save-excursion
12296 (org-back-to-heading)
12297 (let ((case-fold-search nil))
12298 (looking-at org-complex-heading-regexp))
12299 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12300 (skip-chars-forward " \t")
12301 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12302 (if (org-in-commented-heading-p t)
12303 (delete-region (point)
12304 (progn (search-forward " " (line-end-position) 'move)
12305 (skip-chars-forward " \t")
12306 (point)))
12307 (insert org-comment-string)
12308 (unless (eolp) (insert " ")))))
12310 (defvar org-last-todo-state-is-todo nil
12311 "This is non-nil when the last TODO state change led to a TODO state.
12312 If the last change removed the TODO tag or switched to DONE, then
12313 this is nil.")
12315 (defvar org-setting-tags nil) ; dynamically skipped
12317 (defvar org-todo-setup-filter-hook nil
12318 "Hook for functions that pre-filter todo specs.
12319 Each function takes a todo spec and returns either nil or the spec
12320 transformed into canonical form." )
12322 (defvar org-todo-get-default-hook nil
12323 "Hook for functions that get a default item for todo.
12324 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12325 nil or a string to be used for the todo mark." )
12327 (defvar org-agenda-headline-snapshot-before-repeat)
12329 (defun org-current-effective-time ()
12330 "Return current time adjusted for `org-extend-today-until' variable."
12331 (let* ((ct (org-current-time))
12332 (dct (decode-time ct))
12333 (ct1
12334 (cond
12335 (org-use-last-clock-out-time-as-effective-time
12336 (or (org-clock-get-last-clock-out-time) ct))
12337 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12338 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12339 (t ct))))
12340 ct1))
12342 (defun org-todo-yesterday (&optional arg)
12343 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12344 (interactive "P")
12345 (if (eq major-mode 'org-agenda-mode)
12346 (apply 'org-agenda-todo-yesterday arg)
12347 (let* ((org-use-effective-time t)
12348 (hour (nth 2 (decode-time (org-current-time))))
12349 (org-extend-today-until (1+ hour)))
12350 (org-todo arg))))
12352 (defvar org-block-entry-blocking ""
12353 "First entry preventing the TODO state change.")
12355 (defun org-cancel-repeater ()
12356 "Cancel a repeater by setting its numeric value to zero."
12357 (interactive)
12358 (save-excursion
12359 (org-back-to-heading t)
12360 (let ((bound1 (point))
12361 (bound0 (save-excursion (outline-next-heading) (point))))
12362 (when (and (re-search-forward
12363 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12364 org-deadline-time-regexp "\\)\\|\\("
12365 org-ts-regexp "\\)")
12366 bound0 t)
12367 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12368 bound1 t))
12369 (replace-match "0" t nil nil 1)))))
12371 (defvar org-state) ;; dynamically scoped into this function
12372 (defun org-todo (&optional arg)
12373 "Change the TODO state of an item.
12375 The state of an item is given by a keyword at the start of the heading,
12376 like
12377 *** TODO Write paper
12378 *** DONE Call mom
12380 The different keywords are specified in the variable `org-todo-keywords'.
12381 By default the available states are \"TODO\" and \"DONE\". So, for this
12382 example: when the item starts with TODO, it is changed to DONE.
12383 When it starts with DONE, the DONE is removed. And when neither TODO nor
12384 DONE are present, add TODO at the beginning of the heading.
12386 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12387 state.
12388 With numeric prefix ARG, switch to that state.
12389 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12390 next set of TODO \
12391 keywords (nextset).
12392 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12393 prefix, circumvent any state blocking.
12394 With a numeric prefix arg of 0, inhibit note taking for the change.
12395 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12397 When called through ELisp, arg is also interpreted in the following way:
12398 `none' -> empty state
12399 \"\" -> switch to empty state
12400 `done' -> switch to DONE
12401 `nextset' -> switch to the next set of keywords
12402 `previousset' -> switch to the previous set of keywords
12403 \"WAITING\" -> switch to the specified keyword, but only if it
12404 really is a member of `org-todo-keywords'."
12405 (interactive "P")
12406 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12407 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12408 'region-start-level 'region))
12409 org-loop-over-headlines-in-active-region)
12410 (org-map-entries
12411 `(org-todo ,arg)
12412 org-loop-over-headlines-in-active-region
12413 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12414 (when (equal arg '(16)) (setq arg 'nextset))
12415 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12416 (let ((org-blocker-hook org-blocker-hook)
12417 commentp
12418 case-fold-search)
12419 (when (equal arg '(64))
12420 (setq arg nil org-blocker-hook nil))
12421 (when (and org-blocker-hook
12422 (or org-inhibit-blocking
12423 (org-entry-get nil "NOBLOCKING")))
12424 (setq org-blocker-hook nil))
12425 (save-excursion
12426 (catch 'exit
12427 (org-back-to-heading t)
12428 (when (org-in-commented-heading-p t)
12429 (org-toggle-comment)
12430 (setq commentp t))
12431 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12432 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12433 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12434 (let* ((match-data (match-data))
12435 (startpos (point-at-bol))
12436 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12437 (org-log-done org-log-done)
12438 (org-log-repeat org-log-repeat)
12439 (org-todo-log-states org-todo-log-states)
12440 (org-inhibit-logging
12441 (if (equal arg 0)
12442 (progn (setq arg nil) 'note) org-inhibit-logging))
12443 (this (match-string 1))
12444 (hl-pos (match-beginning 0))
12445 (head (org-get-todo-sequence-head this))
12446 (ass (assoc head org-todo-kwd-alist))
12447 (interpret (nth 1 ass))
12448 (done-word (nth 3 ass))
12449 (final-done-word (nth 4 ass))
12450 (org-last-state (or this ""))
12451 (completion-ignore-case t)
12452 (member (member this org-todo-keywords-1))
12453 (tail (cdr member))
12454 (org-state (cond
12455 ((and org-todo-key-trigger
12456 (or (and (equal arg '(4))
12457 (eq org-use-fast-todo-selection 'prefix))
12458 (and (not arg) org-use-fast-todo-selection
12459 (not (eq org-use-fast-todo-selection
12460 'prefix)))))
12461 ;; Use fast selection
12462 (org-fast-todo-selection))
12463 ((and (equal arg '(4))
12464 (or (not org-use-fast-todo-selection)
12465 (not org-todo-key-trigger)))
12466 ;; Read a state with completion
12467 (completing-read
12468 "State: " (mapcar #'list org-todo-keywords-1)
12469 nil t))
12470 ((eq arg 'right)
12471 (if this
12472 (if tail (car tail) nil)
12473 (car org-todo-keywords-1)))
12474 ((eq arg 'left)
12475 (unless (equal member org-todo-keywords-1)
12476 (if this
12477 (nth (- (length org-todo-keywords-1)
12478 (length tail) 2)
12479 org-todo-keywords-1)
12480 (org-last org-todo-keywords-1))))
12481 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12482 (setq arg nil))) ; hack to fall back to cycling
12483 (arg
12484 ;; user or caller requests a specific state
12485 (cond
12486 ((equal arg "") nil)
12487 ((eq arg 'none) nil)
12488 ((eq arg 'done) (or done-word (car org-done-keywords)))
12489 ((eq arg 'nextset)
12490 (or (car (cdr (member head org-todo-heads)))
12491 (car org-todo-heads)))
12492 ((eq arg 'previousset)
12493 (let ((org-todo-heads (reverse org-todo-heads)))
12494 (or (car (cdr (member head org-todo-heads)))
12495 (car org-todo-heads))))
12496 ((car (member arg org-todo-keywords-1)))
12497 ((stringp arg)
12498 (user-error "State `%s' not valid in this file" arg))
12499 ((nth (1- (prefix-numeric-value arg))
12500 org-todo-keywords-1))))
12501 ((null member) (or head (car org-todo-keywords-1)))
12502 ((equal this final-done-word) nil) ;; -> make empty
12503 ((null tail) nil) ;; -> first entry
12504 ((memq interpret '(type priority))
12505 (if (eq this-command last-command)
12506 (car tail)
12507 (if (> (length tail) 0)
12508 (or done-word (car org-done-keywords))
12509 nil)))
12511 (car tail))))
12512 (org-state (or
12513 (run-hook-with-args-until-success
12514 'org-todo-get-default-hook org-state org-last-state)
12515 org-state))
12516 (next (if org-state (concat " " org-state " ") " "))
12517 (change-plist (list :type 'todo-state-change :from this :to org-state
12518 :position startpos))
12519 dolog now-done-p)
12520 (when org-blocker-hook
12521 (setq org-last-todo-state-is-todo
12522 (not (member this org-done-keywords)))
12523 (unless (save-excursion
12524 (save-match-data
12525 (org-with-wide-buffer
12526 (run-hook-with-args-until-failure
12527 'org-blocker-hook change-plist))))
12528 (if (called-interactively-p 'interactive)
12529 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12530 this org-state org-block-entry-blocking)
12531 ;; fail silently
12532 (message "TODO state change from %s to %s blocked (by \"%s\")"
12533 this org-state org-block-entry-blocking)
12534 (throw 'exit nil))))
12535 (store-match-data match-data)
12536 (replace-match next t t)
12537 (cond ((equal this org-state)
12538 (message "TODO state was already %s" (org-trim next)))
12539 ((pos-visible-in-window-p hl-pos)
12540 (message "TODO state changed to %s" (org-trim next))))
12541 (unless head
12542 (setq head (org-get-todo-sequence-head org-state)
12543 ass (assoc head org-todo-kwd-alist)
12544 interpret (nth 1 ass)
12545 done-word (nth 3 ass)
12546 final-done-word (nth 4 ass)))
12547 (when (memq arg '(nextset previousset))
12548 (message "Keyword-Set %d/%d: %s"
12549 (- (length org-todo-sets) -1
12550 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12551 (length org-todo-sets)
12552 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12553 (setq org-last-todo-state-is-todo
12554 (not (member org-state org-done-keywords)))
12555 (setq now-done-p (and (member org-state org-done-keywords)
12556 (not (member this org-done-keywords))))
12557 (and logging (org-local-logging logging))
12558 (when (and (or org-todo-log-states org-log-done)
12559 (not (eq org-inhibit-logging t))
12560 (not (memq arg '(nextset previousset))))
12561 ;; we need to look at recording a time and note
12562 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12563 (nth 2 (assoc this org-todo-log-states))))
12564 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12565 (setq dolog 'time))
12566 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12567 (and org-state
12568 (member org-state org-not-done-keywords)
12569 (not (member this org-not-done-keywords))))
12570 ;; This is now a todo state and was not one before
12571 ;; If there was a CLOSED time stamp, get rid of it.
12572 (org-add-planning-info nil nil 'closed))
12573 (when (and now-done-p org-log-done)
12574 ;; It is now done, and it was not done before
12575 (org-add-planning-info 'closed (org-current-effective-time))
12576 (when (and (not dolog) (eq 'note org-log-done))
12577 (org-add-log-setup 'done org-state this 'note)))
12578 (when (and org-state dolog)
12579 ;; This is a non-nil state, and we need to log it
12580 (org-add-log-setup 'state org-state this dolog)))
12581 ;; Fixup tag positioning
12582 (org-todo-trigger-tag-changes org-state)
12583 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12584 (when org-provide-todo-statistics
12585 (org-update-parent-todo-statistics))
12586 (run-hooks 'org-after-todo-state-change-hook)
12587 (when (and arg (not (member org-state org-done-keywords)))
12588 (setq head (org-get-todo-sequence-head org-state)))
12589 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12590 ;; Do we need to trigger a repeat?
12591 (when now-done-p
12592 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12593 ;; This is for the agenda, take a snapshot of the headline.
12594 (save-match-data
12595 (setq org-agenda-headline-snapshot-before-repeat
12596 (org-get-heading))))
12597 (org-auto-repeat-maybe org-state))
12598 ;; Fixup cursor location if close to the keyword
12599 (when (and (outline-on-heading-p)
12600 (not (bolp))
12601 (save-excursion (beginning-of-line 1)
12602 (looking-at org-todo-line-regexp))
12603 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12604 (goto-char (or (match-end 2) (match-end 1)))
12605 (and (looking-at " ") (just-one-space)))
12606 (when org-trigger-hook
12607 (save-excursion
12608 (run-hook-with-args 'org-trigger-hook change-plist)))
12609 (when commentp (org-toggle-comment))))))))
12611 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12612 "Block turning an entry into a TODO, using the hierarchy.
12613 This checks whether the current task should be blocked from state
12614 changes. Such blocking occurs when:
12616 1. The task has children which are not all in a completed state.
12618 2. A task has a parent with the property :ORDERED:, and there
12619 are siblings prior to the current task with incomplete
12620 status.
12622 3. The parent of the task is blocked because it has siblings that should
12623 be done first, or is child of a block grandparent TODO entry."
12625 (if (not org-enforce-todo-dependencies)
12626 t ; if locally turned off don't block
12627 (catch 'dont-block
12628 ;; If this is not a todo state change, or if this entry is already DONE,
12629 ;; do not block
12630 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12631 (member (plist-get change-plist :from)
12632 (cons 'done org-done-keywords))
12633 (member (plist-get change-plist :to)
12634 (cons 'todo org-not-done-keywords))
12635 (not (plist-get change-plist :to)))
12636 (throw 'dont-block t))
12637 ;; If this task has children, and any are undone, it's blocked
12638 (save-excursion
12639 (org-back-to-heading t)
12640 (let ((this-level (funcall outline-level)))
12641 (outline-next-heading)
12642 (let ((child-level (funcall outline-level)))
12643 (while (and (not (eobp))
12644 (> child-level this-level))
12645 ;; this todo has children, check whether they are all
12646 ;; completed
12647 (when (and (not (org-entry-is-done-p))
12648 (org-entry-is-todo-p))
12649 (setq org-block-entry-blocking (org-get-heading))
12650 (throw 'dont-block nil))
12651 (outline-next-heading)
12652 (setq child-level (funcall outline-level))))))
12653 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12654 ;; any previous siblings are undone, it's blocked
12655 (save-excursion
12656 (org-back-to-heading t)
12657 (let* ((pos (point))
12658 (parent-pos (and (org-up-heading-safe) (point)))
12659 (case-fold-search nil))
12660 (unless parent-pos (throw 'dont-block t)) ; no parent
12661 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12662 (forward-line 1)
12663 (re-search-forward org-not-done-heading-regexp pos t))
12664 (setq org-block-entry-blocking (match-string 0))
12665 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12666 ;; Search further up the hierarchy, to see if an ancestor is blocked
12667 (while t
12668 (goto-char parent-pos)
12669 (unless (looking-at org-not-done-heading-regexp)
12670 (throw 'dont-block t)) ; do not block, parent is not a TODO
12671 (setq pos (point))
12672 (setq parent-pos (and (org-up-heading-safe) (point)))
12673 (unless parent-pos (throw 'dont-block t)) ; no parent
12674 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12675 (forward-line 1)
12676 (re-search-forward org-not-done-heading-regexp pos t)
12677 (setq org-block-entry-blocking (org-get-heading)))
12678 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12680 (defcustom org-track-ordered-property-with-tag nil
12681 "Should the ORDERED property also be shown as a tag?
12682 The ORDERED property decides if an entry should require subtasks to be
12683 completed in sequence. Since a property is not very visible, setting
12684 this option means that toggling the ORDERED property with the command
12685 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12686 not relevant for the behavior, but it makes things more visible.
12688 Note that toggling the tag with tags commands will not change the property
12689 and therefore not influence behavior!
12691 This can be t, meaning the tag ORDERED should be used, It can also be a
12692 string to select a different tag for this task."
12693 :group 'org-todo
12694 :type '(choice
12695 (const :tag "No tracking" nil)
12696 (const :tag "Track with ORDERED tag" t)
12697 (string :tag "Use other tag")))
12699 (defun org-toggle-ordered-property ()
12700 "Toggle the ORDERED property of the current entry.
12701 For better visibility, you can track the value of this property with a tag.
12702 See variable `org-track-ordered-property-with-tag'."
12703 (interactive)
12704 (let* ((t1 org-track-ordered-property-with-tag)
12705 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12706 (save-excursion
12707 (org-back-to-heading)
12708 (if (org-entry-get nil "ORDERED")
12709 (progn
12710 (org-delete-property "ORDERED")
12711 (and tag (org-toggle-tag tag 'off))
12712 (message "Subtasks can be completed in arbitrary order"))
12713 (org-entry-put nil "ORDERED" "t")
12714 (and tag (org-toggle-tag tag 'on))
12715 (message "Subtasks must be completed in sequence")))))
12717 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12718 (defun org-block-todo-from-checkboxes (change-plist)
12719 "Block turning an entry into a TODO, using checkboxes.
12720 This checks whether the current task should be blocked from state
12721 changes because there are unchecked boxes in this entry."
12722 (if (not org-enforce-todo-checkbox-dependencies)
12723 t ; if locally turned off don't block
12724 (catch 'dont-block
12725 ;; If this is not a todo state change, or if this entry is already DONE,
12726 ;; do not block
12727 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12728 (member (plist-get change-plist :from)
12729 (cons 'done org-done-keywords))
12730 (member (plist-get change-plist :to)
12731 (cons 'todo org-not-done-keywords))
12732 (not (plist-get change-plist :to)))
12733 (throw 'dont-block t))
12734 ;; If this task has checkboxes that are not checked, it's blocked
12735 (save-excursion
12736 (org-back-to-heading t)
12737 (let ((beg (point)) end)
12738 (outline-next-heading)
12739 (setq end (point))
12740 (goto-char beg)
12741 (when (org-list-search-forward
12742 (concat (org-item-beginning-re)
12743 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12744 "\\[[- ]\\]")
12745 end t)
12746 (when (boundp 'org-blocked-by-checkboxes)
12747 (setq org-blocked-by-checkboxes t))
12748 (throw 'dont-block nil))))
12749 t))) ; do not block
12751 (defun org-entry-blocked-p ()
12752 "Non-nil if entry at point is blocked."
12753 (and (not (org-entry-get nil "NOBLOCKING"))
12754 (member (org-entry-get nil "TODO") org-not-done-keywords)
12755 (not (run-hook-with-args-until-failure
12756 'org-blocker-hook
12757 (list :type 'todo-state-change
12758 :position (point)
12759 :from 'todo
12760 :to 'done)))))
12762 (defun org-update-statistics-cookies (all)
12763 "Update the statistics cookie, either from TODO or from checkboxes.
12764 This should be called with the cursor in a line with a statistics
12765 cookie. When called with a \\[universal-argument] prefix, update
12766 all statistics cookies in the buffer."
12767 (interactive "P")
12768 (if all
12769 (progn
12770 (org-update-checkbox-count 'all)
12771 (org-map-entries 'org-update-parent-todo-statistics))
12772 (if (not (org-at-heading-p))
12773 (org-update-checkbox-count)
12774 (let ((pos (point-marker))
12775 end l1 l2)
12776 (ignore-errors (org-back-to-heading t))
12777 (if (not (org-at-heading-p))
12778 (org-update-checkbox-count)
12779 (setq l1 (org-outline-level))
12780 (setq end (save-excursion
12781 (outline-next-heading)
12782 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12783 (point)))
12784 (if (and (save-excursion
12785 (re-search-forward
12786 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12787 (not (save-excursion (re-search-forward
12788 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12789 (org-update-checkbox-count)
12790 (if (and l2 (> l2 l1))
12791 (progn
12792 (goto-char end)
12793 (org-update-parent-todo-statistics))
12794 (goto-char pos)
12795 (beginning-of-line 1)
12796 (while (re-search-forward
12797 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12798 (point-at-eol) t)
12799 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12800 (goto-char pos)
12801 (move-marker pos nil)))))
12803 (defvar org-entry-property-inherited-from) ;; defined below
12804 (defun org-update-parent-todo-statistics ()
12805 "Update any statistics cookie in the parent of the current headline.
12806 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12807 the entire subtree and this will travel up the hierarchy and update
12808 statistics everywhere."
12809 (let* ((prop (save-excursion (org-up-heading-safe)
12810 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12811 (recursive (or (not org-hierarchical-todo-statistics)
12812 (and prop (string-match "\\<recursive\\>" prop))))
12813 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12815 (first t)
12816 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12817 level ltoggle l1 new ndel
12818 (cnt-all 0) (cnt-done 0) is-percent kwd
12819 checkbox-beg cookie-present)
12820 (catch 'exit
12821 (save-excursion
12822 (beginning-of-line 1)
12823 (setq ltoggle (funcall outline-level))
12824 ;; Three situations are to consider:
12826 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12827 ;; to the top-level ancestor on the headline;
12829 ;; 2. If parent has "recursive" property, repeat up to the
12830 ;; headline setting that property, taking inheritance into
12831 ;; account;
12833 ;; 3. Else, move up to direct parent and proceed only once.
12834 (while (and (setq level (org-up-heading-safe))
12835 (or recursive first)
12836 (>= (point) lim))
12837 (setq first nil cookie-present nil)
12838 (unless (and level
12839 (not (string-match
12840 "\\<checkbox\\>"
12841 (downcase (or (org-entry-get nil "COOKIE_DATA")
12842 "")))))
12843 (throw 'exit nil))
12844 (while (re-search-forward box-re (point-at-eol) t)
12845 (setq cnt-all 0 cnt-done 0 cookie-present t)
12846 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12847 (save-match-data
12848 (unless (outline-next-heading) (throw 'exit nil))
12849 (while (and (looking-at org-complex-heading-regexp)
12850 (> (setq l1 (length (match-string 1))) level))
12851 (setq kwd (and (or recursive (= l1 ltoggle))
12852 (match-string 2)))
12853 (if (or (eq org-provide-todo-statistics 'all-headlines)
12854 (and (eq org-provide-todo-statistics t)
12855 (or (member kwd org-done-keywords)))
12856 (and (listp org-provide-todo-statistics)
12857 (stringp (car org-provide-todo-statistics))
12858 (or (member kwd org-provide-todo-statistics)
12859 (member kwd org-done-keywords)))
12860 (and (listp org-provide-todo-statistics)
12861 (listp (car org-provide-todo-statistics))
12862 (or (member kwd (car org-provide-todo-statistics))
12863 (and (member kwd org-done-keywords)
12864 (member kwd (cadr org-provide-todo-statistics))))))
12865 (setq cnt-all (1+ cnt-all))
12866 (and (eq org-provide-todo-statistics t)
12868 (setq cnt-all (1+ cnt-all))))
12869 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12870 (member kwd org-done-keywords))
12871 (and (listp org-provide-todo-statistics)
12872 (listp (car org-provide-todo-statistics))
12873 (member kwd org-done-keywords)
12874 (member kwd (cadr org-provide-todo-statistics)))
12875 (and (listp org-provide-todo-statistics)
12876 (stringp (car org-provide-todo-statistics))
12877 (member kwd org-done-keywords)))
12878 (setq cnt-done (1+ cnt-done)))
12879 (outline-next-heading)))
12880 (setq new
12881 (if is-percent
12882 (format "[%d%%]" (floor (* 100.0 cnt-done)
12883 (max 1 cnt-all)))
12884 (format "[%d/%d]" cnt-done cnt-all))
12885 ndel (- (match-end 0) checkbox-beg))
12886 (goto-char checkbox-beg)
12887 (insert new)
12888 (delete-region (point) (+ (point) ndel))
12889 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12890 (when cookie-present
12891 (run-hook-with-args 'org-after-todo-statistics-hook
12892 cnt-done (- cnt-all cnt-done))))))
12893 (run-hooks 'org-todo-statistics-hook)))
12895 (defvar org-after-todo-statistics-hook nil
12896 "Hook that is called after a TODO statistics cookie has been updated.
12897 Each function is called with two arguments: the number of not-done entries
12898 and the number of done entries.
12900 For example, the following function, when added to this hook, will switch
12901 an entry to DONE when all children are done, and back to TODO when new
12902 entries are set to a TODO status. Note that this hook is only called
12903 when there is a statistics cookie in the headline!
12905 (defun org-summary-todo (n-done n-not-done)
12906 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12907 (let (org-log-done org-log-states) ; turn off logging
12908 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12911 (defvar org-todo-statistics-hook nil
12912 "Hook that is run whenever Org thinks TODO statistics should be updated.
12913 This hook runs even if there is no statistics cookie present, in which case
12914 `org-after-todo-statistics-hook' would not run.")
12916 (defun org-todo-trigger-tag-changes (state)
12917 "Apply the changes defined in `org-todo-state-tags-triggers'."
12918 (let ((l org-todo-state-tags-triggers)
12919 changes)
12920 (when (or (not state) (equal state ""))
12921 (setq changes (append changes (cdr (assoc "" l)))))
12922 (when (and (stringp state) (> (length state) 0))
12923 (setq changes (append changes (cdr (assoc state l)))))
12924 (when (member state org-not-done-keywords)
12925 (setq changes (append changes (cdr (assq 'todo l)))))
12926 (when (member state org-done-keywords)
12927 (setq changes (append changes (cdr (assq 'done l)))))
12928 (dolist (c changes)
12929 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12931 (defun org-local-logging (value)
12932 "Get logging settings from a property VALUE."
12933 ;; Directly set the variables, they are already local.
12934 (setq org-log-done nil
12935 org-log-repeat nil
12936 org-todo-log-states nil)
12937 (dolist (w (org-split-string value))
12938 (let (a)
12939 (cond
12940 ((setq a (assoc w org-startup-options))
12941 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12942 (set (nth 1 a) (nth 2 a))))
12943 ((setq a (org-extract-log-state-settings w))
12944 (and (member (car a) org-todo-keywords-1)
12945 (push a org-todo-log-states)))))))
12947 (defun org-get-todo-sequence-head (kwd)
12948 "Return the head of the TODO sequence to which KWD belongs.
12949 If KWD is not set, check if there is a text property remembering the
12950 right sequence."
12951 (let (p)
12952 (cond
12953 ((not kwd)
12954 (or (get-text-property (point-at-bol) 'org-todo-head)
12955 (progn
12956 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12957 nil (point-at-eol)))
12958 (get-text-property p 'org-todo-head))))
12959 ((not (member kwd org-todo-keywords-1))
12960 (car org-todo-keywords-1))
12961 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12963 (defun org-fast-todo-selection ()
12964 "Fast TODO keyword selection with single keys.
12965 Returns the new TODO keyword, or nil if no state change should occur."
12966 (let* ((fulltable org-todo-key-alist)
12967 (done-keywords org-done-keywords) ;; needed for the faces.
12968 (maxlen (apply 'max (mapcar
12969 (lambda (x)
12970 (if (stringp (car x)) (string-width (car x)) 0))
12971 fulltable)))
12972 (expert nil)
12973 (fwidth (+ maxlen 3 1 3))
12974 (ncol (/ (- (window-width) 4) fwidth))
12975 tg cnt e c tbl
12976 groups ingroup)
12977 (save-excursion
12978 (save-window-excursion
12979 (if expert
12980 (set-buffer (get-buffer-create " *Org todo*"))
12981 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12982 (erase-buffer)
12983 (setq-local org-done-keywords done-keywords)
12984 (setq tbl fulltable cnt 0)
12985 (while (setq e (pop tbl))
12986 (cond
12987 ((equal e '(:startgroup))
12988 (push '() groups) (setq ingroup t)
12989 (unless (= cnt 0)
12990 (setq cnt 0)
12991 (insert "\n"))
12992 (insert "{ "))
12993 ((equal e '(:endgroup))
12994 (setq ingroup nil cnt 0)
12995 (insert "}\n"))
12996 ((equal e '(:newline))
12997 (unless (= cnt 0)
12998 (setq cnt 0)
12999 (insert "\n")
13000 (setq e (car tbl))
13001 (while (equal (car tbl) '(:newline))
13002 (insert "\n")
13003 (setq tbl (cdr tbl)))))
13005 (setq tg (car e) c (cdr e))
13006 (when ingroup (push tg (car groups)))
13007 (setq tg (org-add-props tg nil 'face
13008 (org-get-todo-face tg)))
13009 (when (and (= cnt 0) (not ingroup)) (insert " "))
13010 (insert "[" c "] " tg (make-string
13011 (- fwidth 4 (length tg)) ?\ ))
13012 (when (= (setq cnt (1+ cnt)) ncol)
13013 (insert "\n")
13014 (when ingroup (insert " "))
13015 (setq cnt 0)))))
13016 (insert "\n")
13017 (goto-char (point-min))
13018 (unless expert (org-fit-window-to-buffer))
13019 (message "[a-z..]:Set [SPC]:clear")
13020 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13021 (cond
13022 ((or (= c ?\C-g)
13023 (and (= c ?q) (not (rassoc c fulltable))))
13024 (setq quit-flag t))
13025 ((= c ?\ ) nil)
13026 ((setq e (rassoc c fulltable) tg (car e))
13028 (t (setq quit-flag t)))))))
13030 (defun org-entry-is-todo-p ()
13031 (member (org-get-todo-state) org-not-done-keywords))
13033 (defun org-entry-is-done-p ()
13034 (member (org-get-todo-state) org-done-keywords))
13036 (defun org-get-todo-state ()
13037 "Return the TODO keyword of the current subtree."
13038 (save-excursion
13039 (org-back-to-heading t)
13040 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13041 (match-end 2)
13042 (match-string 2))))
13044 (defun org-at-date-range-p (&optional inactive-ok)
13045 "Non-nil if point is inside a date range.
13047 When optional argument INACTIVE-OK is non-nil, also consider
13048 inactive time ranges.
13050 When this function returns a non-nil value, match data is set
13051 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13052 on INACTIVE-OK."
13053 (interactive)
13054 (save-excursion
13055 (catch 'exit
13056 (let ((pos (point)))
13057 (skip-chars-backward "^[<\r\n")
13058 (skip-chars-backward "<[")
13059 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13060 (>= (match-end 0) pos)
13061 (throw 'exit t))
13062 (skip-chars-backward "^<[\r\n")
13063 (skip-chars-backward "<[")
13064 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13065 (>= (match-end 0) pos)
13066 (throw 'exit t)))
13067 nil)))
13069 (defun org-get-repeat (&optional timestamp)
13070 "Check if there is a time-stamp with repeater in this entry.
13072 Return the repeater, as a string, or nil. Also return nil when
13073 this function is called before first heading.
13075 When optional argument TIMESTAMP is a string, extract the
13076 repeater from there instead."
13077 (save-match-data
13078 (cond (timestamp
13079 (and (string-match org-repeat-re timestamp)
13080 (match-string-no-properties 1 timestamp)))
13081 ((org-before-first-heading-p) nil)
13083 (save-excursion
13084 (org-back-to-heading t)
13085 (let ((end (org-entry-end-position)))
13086 (catch :repeat
13087 (while (re-search-forward org-repeat-re end t)
13088 (when (save-match-data (org-at-timestamp-p))
13089 (throw :repeat (match-string-no-properties 1)))))))))))
13091 (defvar org-last-changed-timestamp)
13092 (defvar org-last-inserted-timestamp)
13093 (defvar org-log-post-message)
13094 (defvar org-log-note-purpose)
13095 (defvar org-log-note-how nil)
13096 (defvar org-log-note-extra)
13097 (defun org-auto-repeat-maybe (done-word)
13098 "Check if the current headline contains a repeated time-stamp.
13100 If yes, set TODO state back to what it was and change the base date
13101 of repeating deadline/scheduled time stamps to new date.
13103 This function is run automatically after each state change to a DONE state."
13104 (let* ((repeat (org-get-repeat))
13105 (aa (assoc org-last-state org-todo-kwd-alist))
13106 (interpret (nth 1 aa))
13107 (head (nth 2 aa))
13108 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13109 (msg "Entry repeats: ")
13110 (org-log-done nil)
13111 (org-todo-log-states nil)
13112 (end (copy-marker (org-entry-end-position))))
13113 (unwind-protect
13114 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13115 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13116 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13117 org-todo-repeat-to-state)))
13118 (org-todo (cond
13119 ((and to-state (member to-state org-todo-keywords-1))
13120 to-state)
13121 ((eq interpret 'type) org-last-state)
13122 (head)
13123 (t 'none))))
13124 (org-back-to-heading t)
13125 (org-add-planning-info nil nil 'closed)
13126 ;; When `org-log-repeat' is non-nil or entry contains
13127 ;; a clock, set LAST_REPEAT property.
13128 (when (or org-log-repeat
13129 (catch :clock
13130 (while (re-search-forward org-clock-line-re end t)
13131 (when (org-at-clock-log-p) (throw :clock t)))))
13132 (org-entry-put nil "LAST_REPEAT" (format-time-string
13133 (org-time-stamp-format t t)
13134 (current-time))))
13135 (when org-log-repeat
13136 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13137 (memq 'org-add-log-note post-command-hook))
13138 ;; We are already setup for some record.
13139 (when (eq org-log-repeat 'note)
13140 ;; Make sure we take a note, not only a time stamp.
13141 (setq org-log-note-how 'note))
13142 ;; Set up for taking a record.
13143 (org-add-log-setup 'state
13144 (or done-word (car org-done-keywords))
13145 org-last-state
13146 org-log-repeat)))
13147 (let ((planning-re (regexp-opt
13148 (list org-scheduled-string org-deadline-string))))
13149 (while (re-search-forward org-ts-regexp end t)
13150 (let* ((ts (match-string 0))
13151 (planning? (org-at-planning-p))
13152 (type (if (not planning?) "Plain:"
13153 (save-excursion
13154 (re-search-backward
13155 planning-re (line-beginning-position) t)
13156 (match-string 0)))))
13157 (cond
13158 ;; Ignore fake time-stamps (e.g., within comments).
13159 ((not (org-at-timestamp-p t)))
13160 ;; Time-stamps without a repeater are usually
13161 ;; skipped. However, a SCHEDULED time-stamp without
13162 ;; one is removed, as they are no longer relevant.
13163 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13164 ts))
13165 (when (equal type org-scheduled-string)
13166 (org-remove-timestamp-with-keyword type)))
13168 (let ((n (string-to-number (match-string 2 ts)))
13169 (what (match-string 3 ts)))
13170 (when (equal what "w") (setq n (* n 7) what "d"))
13171 (when (and (equal what "h")
13172 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13173 ts)))
13174 (user-error
13175 "Cannot repeat in Repeat in %d hour(s) because no hour \
13176 has been set"
13178 ;; Preparation, see if we need to modify the start
13179 ;; date for the change.
13180 (when (match-end 1)
13181 (let ((time (save-match-data
13182 (org-time-string-to-time ts))))
13183 (cond
13184 ((equal (match-string 1 ts) ".")
13185 ;; Shift starting date to today
13186 (org-timestamp-change
13187 (- (org-today) (time-to-days time))
13188 'day))
13189 ((equal (match-string 1 ts) "+")
13190 (let ((nshiftmax 10)
13191 (nshift 0))
13192 (while (or (= nshift 0)
13193 (not (time-less-p (current-time) time)))
13194 (when (= (cl-incf nshift) nshiftmax)
13195 (or (y-or-n-p
13196 (format "%d repeater intervals were not \
13197 enough to shift date past today. Continue? "
13198 nshift))
13199 (user-error "Abort")))
13200 (org-timestamp-change n (cdr (assoc what whata)))
13201 (org-in-regexp org-ts-regexp3)
13202 (setq ts (match-string 1))
13203 (setq time
13204 (save-match-data
13205 (org-time-string-to-time ts)))))
13206 (org-timestamp-change (- n) (cdr (assoc what whata)))
13207 ;; Rematch, so that we have everything in place
13208 ;; for the real shift.
13209 (org-in-regexp org-ts-regexp3)
13210 (setq ts (match-string 1))
13211 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13212 ts)))))
13213 (save-excursion
13214 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13215 (setq msg
13216 (concat
13217 msg type " " org-last-changed-timestamp " "))))))))
13218 (setq org-log-post-message msg)
13219 (message "%s" msg))
13220 (set-marker end nil))))
13222 (defun org-show-todo-tree (arg)
13223 "Make a compact tree which shows all headlines marked with TODO.
13224 The tree will show the lines where the regexp matches, and all higher
13225 headlines above the match.
13226 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13227 With a numeric prefix N, construct a sparse tree for the Nth element
13228 of `org-todo-keywords-1'."
13229 (interactive "P")
13230 (let ((case-fold-search nil)
13231 (kwd-re
13232 (cond ((null arg) org-not-done-regexp)
13233 ((equal arg '(4))
13234 (let ((kwd
13235 (completing-read "Keyword (or KWD1|KWD2|...): "
13236 (mapcar #'list org-todo-keywords-1))))
13237 (concat "\\("
13238 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13239 "\\)\\>")))
13240 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13241 (regexp-quote (nth (1- (prefix-numeric-value arg))
13242 org-todo-keywords-1)))
13243 (t (user-error "Invalid prefix argument: %s" arg)))))
13244 (message "%d TODO entries found"
13245 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13247 (defun org--deadline-or-schedule (arg type time)
13248 "Insert DEADLINE or SCHEDULE information in current entry.
13249 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13250 `org-schedule' for information about ARG and TIME arguments."
13251 (let* ((deadline? (eq type 'deadline))
13252 (keyword (if deadline? org-deadline-string org-scheduled-string))
13253 (log (if deadline? org-log-redeadline org-log-reschedule))
13254 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13255 (old-date-time (and old-date (org-time-string-to-time old-date)))
13256 ;; Save repeater cookie from either TIME or current scheduled
13257 ;; time stamp. We are going to insert it back at the end of
13258 ;; the process.
13259 (repeater (or (and (org-string-nw-p time)
13260 ;; We use `org-repeat-re' because we need
13261 ;; to tell the difference between a real
13262 ;; repeater and a time delta, e.g. "+2d".
13263 (string-match org-repeat-re time)
13264 (match-string 1 time))
13265 (and (org-string-nw-p old-date)
13266 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13267 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13268 old-date)
13269 (match-string 1 old-date)))))
13270 (pcase arg
13271 (`(4)
13272 (when (and old-date log)
13273 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13274 nil old-date log))
13275 (org-remove-timestamp-with-keyword keyword)
13276 (message (if deadline? "Item no longer has a deadline."
13277 "Item is no longer scheduled.")))
13278 (`(16)
13279 (save-excursion
13280 (org-back-to-heading t)
13281 (let ((regexp (if deadline? org-deadline-time-regexp
13282 org-scheduled-time-regexp)))
13283 (if (not (re-search-forward regexp (line-end-position 2) t))
13284 (user-error (if deadline? "No deadline information to update"
13285 "No scheduled information to update"))
13286 (let* ((rpl0 (match-string 1))
13287 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13288 (msg (if deadline? "Warn starting from" "Delay until")))
13289 (replace-match
13290 (concat keyword
13291 " <" rpl
13292 (format " -%dd"
13293 (abs (- (time-to-days
13294 (save-match-data
13295 (org-read-date
13296 nil t nil msg old-date-time)))
13297 (time-to-days old-date-time))))
13298 ">") t t))))))
13300 (org-add-planning-info type time 'closed)
13301 (when (and old-date
13303 (not (equal old-date org-last-inserted-timestamp)))
13304 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13305 org-last-inserted-timestamp
13306 old-date
13307 log))
13308 (when repeater
13309 (save-excursion
13310 (org-back-to-heading t)
13311 (when (re-search-forward
13312 (concat keyword " " org-last-inserted-timestamp)
13313 (line-end-position 2)
13315 (goto-char (1- (match-end 0)))
13316 (insert " " repeater)
13317 (setq org-last-inserted-timestamp
13318 (concat (substring org-last-inserted-timestamp 0 -1)
13319 " " repeater
13320 (substring org-last-inserted-timestamp -1))))))
13321 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13322 org-last-inserted-timestamp)))))
13324 (defun org-deadline (arg &optional time)
13325 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13326 With one universal prefix argument, remove any deadline from the item.
13327 With two universal prefix arguments, prompt for a warning delay.
13328 With argument TIME, set the deadline at the corresponding date. TIME
13329 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13330 (interactive "P")
13331 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13332 (org-map-entries
13333 (lambda () (org--deadline-or-schedule arg 'deadline time))
13335 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13336 'region-start-level
13337 'region)
13338 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13339 (org--deadline-or-schedule arg 'deadline time)))
13341 (defun org-schedule (arg &optional time)
13342 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13343 With one universal prefix argument, remove any scheduling date from the item.
13344 With two universal prefix arguments, prompt for a delay cookie.
13345 With argument TIME, scheduled at the corresponding date. TIME can
13346 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13347 (interactive "P")
13348 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13349 (org-map-entries
13350 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13352 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13353 'region-start-level
13354 'region)
13355 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13356 (org--deadline-or-schedule arg 'scheduled time)))
13358 (defun org-get-scheduled-time (pom &optional inherit)
13359 "Get the scheduled time as a time tuple, of a format suitable
13360 for calling org-schedule with, or if there is no scheduling,
13361 returns nil."
13362 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13363 (when time
13364 (apply 'encode-time (org-parse-time-string time)))))
13366 (defun org-get-deadline-time (pom &optional inherit)
13367 "Get the deadline as a time tuple, of a format suitable for
13368 calling org-deadline with, or if there is no scheduling, returns
13369 nil."
13370 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13371 (when time
13372 (apply 'encode-time (org-parse-time-string time)))))
13374 (defun org-remove-timestamp-with-keyword (keyword)
13375 "Remove all time stamps with KEYWORD in the current entry."
13376 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13377 beg)
13378 (save-excursion
13379 (org-back-to-heading t)
13380 (setq beg (point))
13381 (outline-next-heading)
13382 (while (re-search-backward re beg t)
13383 (replace-match "")
13384 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13385 (equal (char-before) ?\ ))
13386 (backward-delete-char 1)
13387 (when (string-match "^[ \t]*$" (buffer-substring
13388 (point-at-bol) (point-at-eol)))
13389 (delete-region (point-at-bol)
13390 (min (point-max) (1+ (point-at-eol))))))))))
13392 (defvar org-time-was-given) ; dynamically scoped parameter
13393 (defvar org-end-time-was-given) ; dynamically scoped parameter
13395 (defun org-at-planning-p ()
13396 "Non-nil when point is on a planning info line."
13397 ;; This is as accurate and faster than `org-element-at-point' since
13398 ;; planning info location is fixed in the section.
13399 (org-with-wide-buffer
13400 (beginning-of-line)
13401 (and (looking-at-p org-planning-line-re)
13402 (eq (point)
13403 (ignore-errors
13404 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13405 (org-back-to-heading t)
13406 (org-with-limited-levels (org-back-to-heading t)))
13407 (line-beginning-position 2))))))
13409 (defun org-add-planning-info (what &optional time &rest remove)
13410 "Insert new timestamp with keyword in the planning line.
13411 WHAT indicates what kind of time stamp to add. It is a symbol
13412 among `closed', `deadline', `scheduled' and nil. TIME indicates
13413 the time to use. If none is given, the user is prompted for
13414 a date. REMOVE indicates what kind of entries to remove. An old
13415 WHAT entry will also be removed."
13416 (let (org-time-was-given org-end-time-was-given default-time default-input)
13417 (catch 'exit
13418 (when (and (memq what '(scheduled deadline))
13419 (or (not time)
13420 (and (stringp time)
13421 (string-match "^[-+]+[0-9]" time))))
13422 ;; Try to get a default date/time from existing timestamp
13423 (save-excursion
13424 (org-back-to-heading t)
13425 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13426 (when (re-search-forward (if (eq what 'scheduled)
13427 org-scheduled-time-regexp
13428 org-deadline-time-regexp)
13429 end t)
13430 (setq ts (match-string 1)
13431 default-time (apply 'encode-time (org-parse-time-string ts))
13432 default-input (and ts (org-get-compact-tod ts)))))))
13433 (when what
13434 (setq time
13435 (if (stringp time)
13436 ;; This is a string (relative or absolute), set
13437 ;; proper date.
13438 (apply #'encode-time
13439 (org-read-date-analyze
13440 time default-time (decode-time default-time)))
13441 ;; If necessary, get the time from the user
13442 (or time (org-read-date nil 'to-time nil nil
13443 default-time default-input)))))
13445 (org-with-wide-buffer
13446 (org-back-to-heading t)
13447 (forward-line)
13448 (unless (bolp) (insert "\n"))
13449 (cond ((looking-at-p org-planning-line-re)
13450 ;; Move to current indentation.
13451 (skip-chars-forward " \t")
13452 ;; Check if we have to remove something.
13453 (dolist (type (if what (cons what remove) remove))
13454 (save-excursion
13455 (when (re-search-forward
13456 (cl-case type
13457 (closed org-closed-time-regexp)
13458 (deadline org-deadline-time-regexp)
13459 (scheduled org-scheduled-time-regexp)
13460 (otherwise
13461 (error "Invalid planning type: %s" type)))
13462 (line-end-position) t)
13463 ;; Delete until next keyword or end of line.
13464 (delete-region
13465 (match-beginning 0)
13466 (if (re-search-forward org-keyword-time-not-clock-regexp
13467 (line-end-position)
13469 (match-beginning 0)
13470 (line-end-position))))))
13471 ;; If there is nothing more to add and no more keyword
13472 ;; is left, remove the line completely.
13473 (if (and (looking-at-p "[ \t]*$") (not what))
13474 (delete-region (line-beginning-position)
13475 (line-beginning-position 2))
13476 ;; If we removed last keyword, do not leave trailing
13477 ;; white space at the end of line.
13478 (let ((p (point)))
13479 (save-excursion
13480 (end-of-line)
13481 (unless (= (skip-chars-backward " \t" p) 0)
13482 (delete-region (point) (line-end-position)))))))
13483 ((not what) (throw 'exit nil)) ; Nothing to do.
13484 (t (insert-before-markers "\n")
13485 (backward-char 1)
13486 (when org-adapt-indentation
13487 (indent-to-column (1+ (org-outline-level))))))
13488 (when what
13489 ;; Insert planning keyword.
13490 (insert (cl-case what
13491 (closed org-closed-string)
13492 (deadline org-deadline-string)
13493 (scheduled org-scheduled-string)
13494 (otherwise (error "Invalid planning type: %s" what)))
13495 " ")
13496 ;; Insert associated timestamp.
13497 (let ((ts (org-insert-time-stamp
13498 time
13499 (or org-time-was-given
13500 (and (eq what 'closed) org-log-done-with-time))
13501 (eq what 'closed)
13502 nil nil (list org-end-time-was-given))))
13503 (unless (eolp) (insert " "))
13504 ts))))))
13506 (defvar org-log-note-marker (make-marker)
13507 "Marker pointing at the entry where the note is to be inserted.")
13508 (defvar org-log-note-purpose nil)
13509 (defvar org-log-note-state nil)
13510 (defvar org-log-note-previous-state nil)
13511 (defvar org-log-note-extra nil)
13512 (defvar org-log-note-window-configuration nil)
13513 (defvar org-log-note-return-to (make-marker))
13514 (defvar org-log-note-effective-time nil
13515 "Remembered current time so that dynamically scoped
13516 `org-extend-today-until' affects timestamps in state change log")
13518 (defvar org-log-post-message nil
13519 "Message to be displayed after a log note has been stored.
13520 The auto-repeater uses this.")
13522 (defun org-add-note ()
13523 "Add a note to the current entry.
13524 This is done in the same way as adding a state change note."
13525 (interactive)
13526 (org-add-log-setup 'note))
13528 (defun org-log-beginning (&optional create)
13529 "Return expected start of log notes in current entry.
13530 When optional argument CREATE is non-nil, the function creates
13531 a drawer to store notes, if necessary. Returned position ignores
13532 narrowing."
13533 (org-with-wide-buffer
13534 (let ((drawer (org-log-into-drawer)))
13535 (cond
13536 (drawer
13537 (org-end-of-meta-data)
13538 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13539 (end (if (org-at-heading-p) (point)
13540 (save-excursion (outline-next-heading) (point))))
13541 (case-fold-search t))
13542 (catch 'exit
13543 ;; Try to find existing drawer.
13544 (while (re-search-forward regexp end t)
13545 (let ((element (org-element-at-point)))
13546 (when (eq (org-element-type element) 'drawer)
13547 (let ((cend (org-element-property :contents-end element)))
13548 (when (and (not org-log-states-order-reversed) cend)
13549 (goto-char cend)))
13550 (throw 'exit nil))))
13551 ;; No drawer found. Create one, if permitted.
13552 (when create
13553 (unless (bolp) (insert "\n"))
13554 (let ((beg (point)))
13555 (insert ":" drawer ":\n:END:\n")
13556 (org-indent-region beg (point)))
13557 (end-of-line -1)))))
13559 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13560 (skip-chars-forward " \t\n")
13561 (beginning-of-line)
13562 (unless org-log-states-order-reversed
13563 (org-skip-over-state-notes)
13564 (skip-chars-backward " \t\n")
13565 (forward-line)))))
13566 (if (bolp) (point) (line-beginning-position 2))))
13568 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13569 "Set up the post command hook to take a note.
13570 If this is about to TODO state change, the new state is expected in STATE.
13571 HOW is an indicator what kind of note should be created.
13572 EXTRA is additional text that will be inserted into the notes buffer."
13573 (move-marker org-log-note-marker (point))
13574 (setq org-log-note-purpose purpose
13575 org-log-note-state state
13576 org-log-note-previous-state prev-state
13577 org-log-note-how how
13578 org-log-note-extra extra
13579 org-log-note-effective-time (org-current-effective-time))
13580 (add-hook 'post-command-hook 'org-add-log-note 'append))
13582 (defun org-skip-over-state-notes ()
13583 "Skip past the list of State notes in an entry."
13584 (when (ignore-errors (goto-char (org-in-item-p)))
13585 (let* ((struct (org-list-struct))
13586 (prevs (org-list-prevs-alist struct))
13587 (regexp
13588 (concat "[ \t]*- +"
13589 (replace-regexp-in-string
13590 " +" " +"
13591 (org-replace-escapes
13592 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13593 `(("%d" . ,org-ts-regexp-inactive)
13594 ("%D" . ,org-ts-regexp)
13595 ("%s" . "\"\\S-+\"")
13596 ("%S" . "\"\\S-+\"")
13597 ("%t" . ,org-ts-regexp-inactive)
13598 ("%T" . ,org-ts-regexp)
13599 ("%u" . ".*?")
13600 ("%U" . ".*?")))))))
13601 (while (looking-at-p regexp)
13602 (goto-char (or (org-list-get-next-item (point) struct prevs)
13603 (org-list-get-item-end (point) struct)))))))
13605 (defun org-add-log-note (&optional _purpose)
13606 "Pop up a window for taking a note, and add this note later."
13607 (remove-hook 'post-command-hook 'org-add-log-note)
13608 (setq org-log-note-window-configuration (current-window-configuration))
13609 (delete-other-windows)
13610 (move-marker org-log-note-return-to (point))
13611 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13612 (goto-char org-log-note-marker)
13613 (org-switch-to-buffer-other-window "*Org Note*")
13614 (erase-buffer)
13615 (if (memq org-log-note-how '(time state))
13616 (let (current-prefix-arg) (org-store-log-note))
13617 (let ((org-inhibit-startup t)) (org-mode))
13618 (insert (format "# Insert note for %s.
13619 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13620 (cond
13621 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13622 ((eq org-log-note-purpose 'done) "closed todo item")
13623 ((eq org-log-note-purpose 'state)
13624 (format "state change from \"%s\" to \"%s\""
13625 (or org-log-note-previous-state "")
13626 (or org-log-note-state "")))
13627 ((eq org-log-note-purpose 'reschedule)
13628 "rescheduling")
13629 ((eq org-log-note-purpose 'delschedule)
13630 "no longer scheduled")
13631 ((eq org-log-note-purpose 'redeadline)
13632 "changing deadline")
13633 ((eq org-log-note-purpose 'deldeadline)
13634 "removing deadline")
13635 ((eq org-log-note-purpose 'refile)
13636 "refiling")
13637 ((eq org-log-note-purpose 'note)
13638 "this entry")
13639 (t (error "This should not happen")))))
13640 (when org-log-note-extra (insert org-log-note-extra))
13641 (setq-local org-finish-function 'org-store-log-note)
13642 (run-hooks 'org-log-buffer-setup-hook)))
13644 (defvar org-note-abort nil) ; dynamically scoped
13645 (defun org-store-log-note ()
13646 "Finish taking a log note, and insert it to where it belongs."
13647 (let ((txt (prog1 (buffer-string)
13648 (kill-buffer)))
13649 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13650 lines)
13651 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13652 (setq txt (replace-match "" t t txt)))
13653 (when (string-match "\\s-+\\'" txt)
13654 (setq txt (replace-match "" t t txt)))
13655 (setq lines (org-split-string txt "\n"))
13656 (when (org-string-nw-p note)
13657 (setq note
13658 (org-replace-escapes
13659 note
13660 (list (cons "%u" (user-login-name))
13661 (cons "%U" user-full-name)
13662 (cons "%t" (format-time-string
13663 (org-time-stamp-format 'long 'inactive)
13664 org-log-note-effective-time))
13665 (cons "%T" (format-time-string
13666 (org-time-stamp-format 'long nil)
13667 org-log-note-effective-time))
13668 (cons "%d" (format-time-string
13669 (org-time-stamp-format nil 'inactive)
13670 org-log-note-effective-time))
13671 (cons "%D" (format-time-string
13672 (org-time-stamp-format nil nil)
13673 org-log-note-effective-time))
13674 (cons "%s" (cond
13675 ((not org-log-note-state) "")
13676 ((string-match-p org-ts-regexp
13677 org-log-note-state)
13678 (format "\"[%s]\""
13679 (substring org-log-note-state 1 -1)))
13680 (t (format "\"%s\"" org-log-note-state))))
13681 (cons "%S"
13682 (cond
13683 ((not org-log-note-previous-state) "")
13684 ((string-match-p org-ts-regexp
13685 org-log-note-previous-state)
13686 (format "\"[%s]\""
13687 (substring
13688 org-log-note-previous-state 1 -1)))
13689 (t (format "\"%s\""
13690 org-log-note-previous-state)))))))
13691 (when lines (setq note (concat note " \\\\")))
13692 (push note lines))
13693 (when (and lines (not (or current-prefix-arg org-note-abort)))
13694 (with-current-buffer (marker-buffer org-log-note-marker)
13695 (org-with-wide-buffer
13696 ;; Find location for the new note.
13697 (goto-char org-log-note-marker)
13698 (set-marker org-log-note-marker nil)
13699 ;; Note associated to a clock is to be located right after
13700 ;; the clock. Do not move point.
13701 (unless (eq org-log-note-purpose 'clock-out)
13702 (goto-char (org-log-beginning t)))
13703 ;; Make sure point is at the beginning of an empty line.
13704 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13705 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13706 ;; In an existing list, add a new item at the top level.
13707 ;; Otherwise, indent line like a regular one.
13708 (let ((itemp (org-in-item-p)))
13709 (if itemp
13710 (indent-line-to
13711 (let ((struct (save-excursion
13712 (goto-char itemp) (org-list-struct))))
13713 (org-list-get-ind (org-list-get-top-point struct) struct)))
13714 (org-indent-line)))
13715 (insert (org-list-bullet-string "-") (pop lines))
13716 (let ((ind (org-list-item-body-column (line-beginning-position))))
13717 (dolist (line lines)
13718 (insert "\n")
13719 (indent-line-to ind)
13720 (insert line)))
13721 (message "Note stored")
13722 (org-back-to-heading t)
13723 (org-cycle-hide-drawers 'children))
13724 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13725 ;; from within `org-add-log-note' because `buffer-undo-list'
13726 ;; is then modified outside of `org-with-remote-undo'.
13727 (when (eq this-command 'org-agenda-todo)
13728 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13729 ;; Don't add undo information when called from `org-agenda-todo'.
13730 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13731 (set-window-configuration org-log-note-window-configuration)
13732 (with-current-buffer (marker-buffer org-log-note-return-to)
13733 (goto-char org-log-note-return-to))
13734 (move-marker org-log-note-return-to nil)
13735 (when org-log-post-message (message "%s" org-log-post-message))))
13737 (defun org-remove-empty-drawer-at (pos)
13738 "Remove an empty drawer at position POS.
13739 POS may also be a marker."
13740 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13741 (org-with-wide-buffer
13742 (goto-char pos)
13743 (let ((drawer (org-element-at-point)))
13744 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13745 (not (org-element-property :contents-begin drawer)))
13746 (delete-region (org-element-property :begin drawer)
13747 (progn (goto-char (org-element-property :end drawer))
13748 (skip-chars-backward " \r\t\n")
13749 (forward-line)
13750 (point))))))))
13752 (defvar org-ts-type nil)
13753 (defun org-sparse-tree (&optional arg type)
13754 "Create a sparse tree, prompt for the details.
13755 This command can create sparse trees. You first need to select the type
13756 of match used to create the tree:
13758 t Show all TODO entries.
13759 T Show entries with a specific TODO keyword.
13760 m Show entries selected by a tags/property match.
13761 p Enter a property name and its value (both with completion on existing
13762 names/values) and show entries with that property.
13763 r Show entries matching a regular expression (`/' can be used as well).
13764 b Show deadlines and scheduled items before a date.
13765 a Show deadlines and scheduled items after a date.
13766 d Show deadlines due within `org-deadline-warning-days'.
13767 D Show deadlines and scheduled items between a date range."
13768 (interactive "P")
13769 (setq type (or type org-sparse-tree-default-date-type))
13770 (setq org-ts-type type)
13771 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13772 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13773 \[c]ycle through date types: %s"
13774 (cl-case type
13775 (all "all timestamps")
13776 (scheduled "only scheduled")
13777 (deadline "only deadline")
13778 (active "only active timestamps")
13779 (inactive "only inactive timestamps")
13780 (closed "with a closed time-stamp")
13781 (otherwise "scheduled/deadline")))
13782 (let ((answer (read-char-exclusive)))
13783 (cl-case answer
13785 (org-sparse-tree
13787 (cadr
13788 (memq type '(nil all scheduled deadline active inactive closed)))))
13789 (?d (call-interactively 'org-check-deadlines))
13790 (?b (call-interactively 'org-check-before-date))
13791 (?a (call-interactively 'org-check-after-date))
13792 (?D (call-interactively 'org-check-dates-range))
13793 (?t (call-interactively 'org-show-todo-tree))
13794 (?T (org-show-todo-tree '(4)))
13795 (?m (call-interactively 'org-match-sparse-tree))
13796 ((?p ?P)
13797 (let* ((kwd (completing-read
13798 "Property: " (mapcar #'list (org-buffer-property-keys))))
13799 (value (completing-read
13800 "Value: " (mapcar #'list (org-property-values kwd)))))
13801 (unless (string-match "\\`{.*}\\'" value)
13802 (setq value (concat "\"" value "\"")))
13803 (org-match-sparse-tree arg (concat kwd "=" value))))
13804 ((?r ?R ?/) (call-interactively 'org-occur))
13805 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13807 (defvar-local org-occur-highlights nil
13808 "List of overlays used for occur matches.")
13809 (defvar-local org-occur-parameters nil
13810 "Parameters of the active org-occur calls.
13811 This is a list, each call to org-occur pushes as cons cell,
13812 containing the regular expression and the callback, onto the list.
13813 The list can contain several entries if `org-occur' has been called
13814 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13815 will only contain one set of parameters. When the highlights are
13816 removed (for example with `C-c C-c', or with the next edit (depending
13817 on `org-remove-highlights-with-change'), this variable is emptied
13818 as well.")
13820 (defun org-occur (regexp &optional keep-previous callback)
13821 "Make a compact tree which shows all matches of REGEXP.
13823 The tree will show the lines where the regexp matches, and any other context
13824 defined in `org-show-context-detail', which see.
13826 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13827 done by a previous call to `org-occur' will be kept, to allow stacking of
13828 calls to this command.
13830 Optional argument CALLBACK can be a function of no argument. In this case,
13831 it is called with point at the end of the match, match data being set
13832 accordingly. Current match is shown only if the return value is non-nil.
13833 The function must neither move point nor alter narrowing."
13834 (interactive "sRegexp: \nP")
13835 (when (equal regexp "")
13836 (user-error "Regexp cannot be empty"))
13837 (unless keep-previous
13838 (org-remove-occur-highlights nil nil t))
13839 (push (cons regexp callback) org-occur-parameters)
13840 (let ((cnt 0))
13841 (save-excursion
13842 (goto-char (point-min))
13843 (when (or (not keep-previous) ; do not want to keep
13844 (not org-occur-highlights)) ; no previous matches
13845 ;; hide everything
13846 (org-overview))
13847 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13848 (isearch-no-upper-case-p regexp t)
13849 org-occur-case-fold-search)))
13850 (while (re-search-forward regexp nil t)
13851 (when (or (not callback)
13852 (save-match-data (funcall callback)))
13853 (setq cnt (1+ cnt))
13854 (when org-highlight-sparse-tree-matches
13855 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13856 (org-show-context 'occur-tree)))))
13857 (when org-remove-highlights-with-change
13858 (add-hook 'before-change-functions 'org-remove-occur-highlights
13859 nil 'local))
13860 (unless org-sparse-tree-open-archived-trees
13861 (org-hide-archived-subtrees (point-min) (point-max)))
13862 (run-hooks 'org-occur-hook)
13863 (when (called-interactively-p 'interactive)
13864 (message "%d match(es) for regexp %s" cnt regexp))
13865 cnt))
13867 (defun org-occur-next-match (&optional n _reset)
13868 "Function for `next-error-function' to find sparse tree matches.
13869 N is the number of matches to move, when negative move backwards.
13870 This function always goes back to the starting point when no
13871 match is found."
13872 (let* ((limit (if (< n 0) (point-min) (point-max)))
13873 (search-func (if (< n 0)
13874 'previous-single-char-property-change
13875 'next-single-char-property-change))
13876 (n (abs n))
13877 (pos (point))
13879 (catch 'exit
13880 (while (setq p1 (funcall search-func (point) 'org-type))
13881 (when (equal p1 limit)
13882 (goto-char pos)
13883 (user-error "No more matches"))
13884 (when (equal (get-char-property p1 'org-type) 'org-occur)
13885 (setq n (1- n))
13886 (when (= n 0)
13887 (goto-char p1)
13888 (throw 'exit (point))))
13889 (goto-char p1))
13890 (goto-char p1)
13891 (user-error "No more matches"))))
13893 (defun org-show-context (&optional key)
13894 "Make sure point and context are visible.
13895 Optional argument KEY, when non-nil, is a symbol. See
13896 `org-show-context-detail' for allowed values and how much is to
13897 be shown."
13898 (org-show-set-visibility
13899 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13900 ((cdr (assq key org-show-context-detail)))
13901 (t (cdr (assq 'default org-show-context-detail))))))
13903 (defun org-show-set-visibility (detail)
13904 "Set visibility around point according to DETAIL.
13905 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13906 `tree', `canonical' or t. See `org-show-context-detail' for more
13907 information."
13908 ;; Show current heading and possibly its entry, following headline
13909 ;; or all children.
13910 (if (and (org-at-heading-p) (not (eq detail 'local)))
13911 (org-flag-heading nil)
13912 (org-show-entry)
13913 ;; If point is hidden within a drawer or a block, make sure to
13914 ;; expose it.
13915 (dolist (o (overlays-at (point)))
13916 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13917 (delete-overlay o)))
13918 (unless (org-before-first-heading-p)
13919 (org-with-limited-levels
13920 (cl-case detail
13921 ((tree canonical t) (org-show-children))
13922 ((nil minimal ancestors))
13923 (t (save-excursion
13924 (outline-next-heading)
13925 (org-flag-heading nil)))))))
13926 ;; Show all siblings.
13927 (when (eq detail 'lineage) (org-show-siblings))
13928 ;; Show ancestors, possibly with their children.
13929 (when (memq detail '(ancestors lineage tree canonical t))
13930 (save-excursion
13931 (while (org-up-heading-safe)
13932 (org-flag-heading nil)
13933 (when (memq detail '(canonical t)) (org-show-entry))
13934 (when (memq detail '(tree canonical t)) (org-show-children))))))
13936 (defvar org-reveal-start-hook nil
13937 "Hook run before revealing a location.")
13939 (defun org-reveal (&optional siblings)
13940 "Show current entry, hierarchy above it, and the following headline.
13942 This can be used to show a consistent set of context around
13943 locations exposed with `org-show-context'.
13945 With optional argument SIBLINGS, on each level of the hierarchy all
13946 siblings are shown. This repairs the tree structure to what it would
13947 look like when opened with hierarchical calls to `org-cycle'.
13949 With a \\[universal-argument] \\[universal-argument] prefix, \
13950 go to the parent and show the entire tree."
13951 (interactive "P")
13952 (run-hooks 'org-reveal-start-hook)
13953 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13954 ((equal siblings '(16))
13955 (save-excursion
13956 (when (org-up-heading-safe)
13957 (org-show-subtree)
13958 (run-hook-with-args 'org-cycle-hook 'subtree))))
13959 (t (org-show-set-visibility 'lineage))))
13961 (defun org-highlight-new-match (beg end)
13962 "Highlight from BEG to END and mark the highlight is an occur headline."
13963 (let ((ov (make-overlay beg end)))
13964 (overlay-put ov 'face 'secondary-selection)
13965 (overlay-put ov 'org-type 'org-occur)
13966 (push ov org-occur-highlights)))
13968 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13969 "Remove the occur highlights from the buffer.
13970 BEG and END are ignored. If NOREMOVE is nil, remove this function
13971 from the `before-change-functions' in the current buffer."
13972 (interactive)
13973 (unless org-inhibit-highlight-removal
13974 (mapc #'delete-overlay org-occur-highlights)
13975 (setq org-occur-highlights nil)
13976 (setq org-occur-parameters nil)
13977 (unless noremove
13978 (remove-hook 'before-change-functions
13979 'org-remove-occur-highlights 'local))))
13981 ;;;; Priorities
13983 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13984 "Regular expression matching the priority indicator.")
13986 (defvar org-remove-priority-next-time nil)
13988 (defun org-priority-up ()
13989 "Increase the priority of the current item."
13990 (interactive)
13991 (org-priority 'up))
13993 (defun org-priority-down ()
13994 "Decrease the priority of the current item."
13995 (interactive)
13996 (org-priority 'down))
13998 (defun org-priority (&optional action _show)
13999 "Change the priority of an item.
14000 ACTION can be `set', `up', `down', or a character."
14001 (interactive "P")
14002 (if (equal action '(4))
14003 (org-show-priority)
14004 (unless org-enable-priority-commands
14005 (user-error "Priority commands are disabled"))
14006 (setq action (or action 'set))
14007 (let (current new news have remove)
14008 (save-excursion
14009 (org-back-to-heading t)
14010 (when (looking-at org-priority-regexp)
14011 (setq current (string-to-char (match-string 2))
14012 have t))
14013 (cond
14014 ((eq action 'remove)
14015 (setq remove t new ?\ ))
14016 ((or (eq action 'set)
14017 (integerp action))
14018 (if (not (eq action 'set))
14019 (setq new action)
14020 (message "Priority %c-%c, SPC to remove: "
14021 org-highest-priority org-lowest-priority)
14022 (save-match-data
14023 (setq new (read-char-exclusive))))
14024 (when (and (= (upcase org-highest-priority) org-highest-priority)
14025 (= (upcase org-lowest-priority) org-lowest-priority))
14026 (setq new (upcase new)))
14027 (cond ((equal new ?\ ) (setq remove t))
14028 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14029 (user-error "Priority must be between `%c' and `%c'"
14030 org-highest-priority org-lowest-priority))))
14031 ((eq action 'up)
14032 (setq new (if have
14033 (1- current) ; normal cycling
14034 ;; last priority was empty
14035 (if (eq last-command this-command)
14036 org-lowest-priority ; wrap around empty to lowest
14037 ;; default
14038 (if org-priority-start-cycle-with-default
14039 org-default-priority
14040 (1- org-default-priority))))))
14041 ((eq action 'down)
14042 (setq new (if have
14043 (1+ current) ; normal cycling
14044 ;; last priority was empty
14045 (if (eq last-command this-command)
14046 org-highest-priority ; wrap around empty to highest
14047 ;; default
14048 (if org-priority-start-cycle-with-default
14049 org-default-priority
14050 (1+ org-default-priority))))))
14051 (t (user-error "Invalid action")))
14052 (when (or (< (upcase new) org-highest-priority)
14053 (> (upcase new) org-lowest-priority))
14054 (if (and (memq action '(up down))
14055 (not have) (not (eq last-command this-command)))
14056 ;; `new' is from default priority
14057 (error
14058 "The default can not be set, see `org-default-priority' why")
14059 ;; normal cycling: `new' is beyond highest/lowest priority
14060 ;; and is wrapped around to the empty priority
14061 (setq remove t)))
14062 (setq news (format "%c" new))
14063 (if have
14064 (if remove
14065 (replace-match "" t t nil 1)
14066 (replace-match news t t nil 2))
14067 (if remove
14068 (user-error "No priority cookie found in line")
14069 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14070 (if (match-end 2)
14071 (progn
14072 (goto-char (match-end 2))
14073 (insert " [#" news "]"))
14074 (goto-char (match-beginning 3))
14075 (insert "[#" news "] "))))
14076 (org-set-tags nil 'align))
14077 (if remove
14078 (message "Priority removed")
14079 (message "Priority of current item set to %s" news)))))
14081 (defun org-show-priority ()
14082 "Show the priority of the current item.
14083 This priority is composed of the main priority given with the [#A] cookies,
14084 and by additional input from the age of a schedules or deadline entry."
14085 (interactive)
14086 (let ((pri (if (eq major-mode 'org-agenda-mode)
14087 (org-get-at-bol 'priority)
14088 (save-excursion
14089 (save-match-data
14090 (beginning-of-line)
14091 (and (looking-at org-heading-regexp)
14092 (org-get-priority (match-string 0))))))))
14093 (message "Priority is %d" (if pri pri -1000))))
14095 (defun org-get-priority (s)
14096 "Find priority cookie and return priority."
14097 (save-match-data
14098 (if (functionp org-get-priority-function)
14099 (funcall org-get-priority-function)
14100 (if (not (string-match org-priority-regexp s))
14101 (* 1000 (- org-lowest-priority org-default-priority))
14102 (* 1000 (- org-lowest-priority
14103 (string-to-char (match-string 2 s))))))))
14105 ;;;; Tags
14107 (defvar org-agenda-archives-mode)
14108 (defvar org-map-continue-from nil
14109 "Position from where mapping should continue.
14110 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14112 (defvar org-scanner-tags nil
14113 "The current tag list while the tags scanner is running.")
14115 (defvar org-trust-scanner-tags nil
14116 "Should `org-get-tags-at' use the tags for the scanner.
14117 This is for internal dynamical scoping only.
14118 When this is non-nil, the function `org-get-tags-at' will return the value
14119 of `org-scanner-tags' instead of building the list by itself. This
14120 can lead to large speed-ups when the tags scanner is used in a file with
14121 many entries, and when the list of tags is retrieved, for example to
14122 obtain a list of properties. Building the tags list for each entry in such
14123 a file becomes an N^2 operation - but with this variable set, it scales
14124 as N.")
14126 (defvar org--matcher-tags-todo-only nil)
14128 (defun org-scan-tags (action matcher todo-only &optional start-level)
14129 "Scan headline tags with inheritance and produce output ACTION.
14131 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14132 or `agenda' to produce an entry list for an agenda view. It can also be
14133 a Lisp form or a function that should be called at each matched headline, in
14134 this case the return value is a list of all return values from these calls.
14136 MATCHER is a function accepting three arguments, returning
14137 a non-nil value whenever a given set of tags qualifies a headline
14138 for inclusion. See `org-make-tags-matcher' for more information.
14139 As a special case, it can also be set to t (respectively nil) in
14140 order to match all (respectively none) headline.
14142 When TODO-ONLY is non-nil, only lines with a not-done TODO
14143 keyword are included in the output.
14145 START-LEVEL can be a string with asterisks, reducing the scope to
14146 headlines matching this string."
14147 (require 'org-agenda)
14148 (let* ((re (concat "^"
14149 (if start-level
14150 ;; Get the correct level to match
14151 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14152 org-outline-regexp)
14153 " *\\(\\<\\("
14154 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14155 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14156 (props (list 'face 'default
14157 'done-face 'org-agenda-done
14158 'undone-face 'default
14159 'mouse-face 'highlight
14160 'org-not-done-regexp org-not-done-regexp
14161 'org-todo-regexp org-todo-regexp
14162 'org-complex-heading-regexp org-complex-heading-regexp
14163 'help-echo
14164 (format "mouse-2 or RET jump to org file %s"
14165 (abbreviate-file-name
14166 (or (buffer-file-name (buffer-base-buffer))
14167 (buffer-name (buffer-base-buffer)))))))
14168 (org-map-continue-from nil)
14169 lspos tags tags-list
14170 (tags-alist (list (cons 0 org-file-tags)))
14171 (llast 0) rtn rtn1 level category i txt
14172 todo marker entry priority
14173 ts-date ts-date-type ts-date-pair)
14174 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14175 (setq action (list 'lambda nil action)))
14176 (save-excursion
14177 (goto-char (point-min))
14178 (when (eq action 'sparse-tree)
14179 (org-overview)
14180 (org-remove-occur-highlights))
14181 (while (let (case-fold-search)
14182 (re-search-forward re nil t))
14183 (setq org-map-continue-from nil)
14184 (catch :skip
14185 (setq todo
14186 ;; TODO: is the 1-2 difference a bug?
14187 (when (match-end 1) (match-string-no-properties 2))
14188 tags (when (match-end 4) (match-string-no-properties 4)))
14189 (goto-char (setq lspos (match-beginning 0)))
14190 (setq level (org-reduced-level (org-outline-level))
14191 category (org-get-category))
14192 (when (eq action 'agenda)
14193 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14194 ts-date (car ts-date-pair)
14195 ts-date-type (cdr ts-date-pair)))
14196 (setq i llast llast level)
14197 ;; remove tag lists from same and sublevels
14198 (while (>= i level)
14199 (when (setq entry (assoc i tags-alist))
14200 (setq tags-alist (delete entry tags-alist)))
14201 (setq i (1- i)))
14202 ;; add the next tags
14203 (when tags
14204 (setq tags (org-split-string tags ":")
14205 tags-alist
14206 (cons (cons level tags) tags-alist)))
14207 ;; compile tags for current headline
14208 (setq tags-list
14209 (if org-use-tag-inheritance
14210 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14211 tags)
14212 org-scanner-tags tags-list)
14213 (when org-use-tag-inheritance
14214 (setcdr (car tags-alist)
14215 (mapcar (lambda (x)
14216 (setq x (copy-sequence x))
14217 (org-add-prop-inherited x))
14218 (cdar tags-alist))))
14219 (when (and tags org-use-tag-inheritance
14220 (or (not (eq t org-use-tag-inheritance))
14221 org-tags-exclude-from-inheritance))
14222 ;; Selective inheritance, remove uninherited ones.
14223 (setcdr (car tags-alist)
14224 (org-remove-uninherited-tags (cdar tags-alist))))
14225 (when (and
14227 ;; eval matcher only when the todo condition is OK
14228 (and (or (not todo-only) (member todo org-not-done-keywords))
14229 (if (functionp matcher)
14230 (let ((case-fold-search t) (org-trust-scanner-tags t))
14231 (funcall matcher todo tags-list level))
14232 matcher))
14234 ;; Call the skipper, but return t if it does not
14235 ;; skip, so that the `and' form continues evaluating.
14236 (progn
14237 (unless (eq action 'sparse-tree) (org-agenda-skip))
14240 ;; Check if timestamps are deselecting this entry
14241 (or (not todo-only)
14242 (and (member todo org-not-done-keywords)
14243 (or (not org-agenda-tags-todo-honor-ignore-options)
14244 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14246 ;; select this headline
14247 (cond
14248 ((eq action 'sparse-tree)
14249 (and org-highlight-sparse-tree-matches
14250 (org-get-heading) (match-end 0)
14251 (org-highlight-new-match
14252 (match-beginning 1) (match-end 1)))
14253 (org-show-context 'tags-tree))
14254 ((eq action 'agenda)
14255 (setq txt (org-agenda-format-item
14257 (concat
14258 (if (eq org-tags-match-list-sublevels 'indented)
14259 (make-string (1- level) ?.) "")
14260 (org-get-heading))
14261 (make-string level ?\s)
14262 category
14263 tags-list)
14264 priority (org-get-priority txt))
14265 (goto-char lspos)
14266 (setq marker (org-agenda-new-marker))
14267 (org-add-props txt props
14268 'org-marker marker 'org-hd-marker marker 'org-category category
14269 'todo-state todo
14270 'ts-date ts-date
14271 'priority priority
14272 'type (concat "tagsmatch" ts-date-type))
14273 (push txt rtn))
14274 ((functionp action)
14275 (setq org-map-continue-from nil)
14276 (save-excursion
14277 (setq rtn1 (funcall action))
14278 (push rtn1 rtn)))
14279 (t (user-error "Invalid action")))
14281 ;; if we are to skip sublevels, jump to end of subtree
14282 (unless org-tags-match-list-sublevels
14283 (org-end-of-subtree t)
14284 (backward-char 1))))
14285 ;; Get the correct position from where to continue
14286 (if org-map-continue-from
14287 (goto-char org-map-continue-from)
14288 (and (= (point) lspos) (end-of-line 1)))))
14289 (when (and (eq action 'sparse-tree)
14290 (not org-sparse-tree-open-archived-trees))
14291 (org-hide-archived-subtrees (point-min) (point-max)))
14292 (nreverse rtn)))
14294 (defun org-remove-uninherited-tags (tags)
14295 "Remove all tags that are not inherited from the list TAGS."
14296 (cond
14297 ((eq org-use-tag-inheritance t)
14298 (if org-tags-exclude-from-inheritance
14299 (org-delete-all org-tags-exclude-from-inheritance tags)
14300 tags))
14301 ((not org-use-tag-inheritance) nil)
14302 ((stringp org-use-tag-inheritance)
14303 (delq nil (mapcar
14304 (lambda (x)
14305 (if (and (string-match org-use-tag-inheritance x)
14306 (not (member x org-tags-exclude-from-inheritance)))
14307 x nil))
14308 tags)))
14309 ((listp org-use-tag-inheritance)
14310 (delq nil (mapcar
14311 (lambda (x)
14312 (if (member x org-use-tag-inheritance) x nil))
14313 tags)))))
14315 (defun org-match-sparse-tree (&optional todo-only match)
14316 "Create a sparse tree according to tags string MATCH.
14318 MATCH is a string with match syntax. It can contain a selection
14319 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14320 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14321 those. See the manual for details.
14323 If optional argument TODO-ONLY is non-nil, only select lines that
14324 are also TODO tasks."
14325 (interactive "P")
14326 (org-agenda-prepare-buffers (list (current-buffer)))
14327 (let ((org--matcher-tags-todo-only todo-only))
14328 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14329 org--matcher-tags-todo-only)))
14331 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14333 (defvar org-cached-props nil)
14334 (defun org-cached-entry-get (pom property)
14335 (if (or (eq t org-use-property-inheritance)
14336 (and (stringp org-use-property-inheritance)
14337 (let ((case-fold-search t))
14338 (string-match-p org-use-property-inheritance property)))
14339 (and (listp org-use-property-inheritance)
14340 (member-ignore-case property org-use-property-inheritance)))
14341 ;; Caching is not possible, check it directly.
14342 (org-entry-get pom property 'inherit)
14343 ;; Get all properties, so we can do complicated checks easily.
14344 (cdr (assoc-string property
14345 (or org-cached-props
14346 (setq org-cached-props (org-entry-properties pom)))
14347 t))))
14349 (defun org-global-tags-completion-table (&optional files)
14350 "Return the list of all tags in all agenda buffer/files.
14351 Optional FILES argument is a list of files which can be used
14352 instead of the agenda files."
14353 (save-excursion
14354 (org-uniquify
14355 (delq nil
14356 (apply #'append
14357 (mapcar
14358 (lambda (file)
14359 (set-buffer (find-file-noselect file))
14360 (mapcar (lambda (x)
14361 (and (stringp (car-safe x))
14362 (list (car-safe x))))
14363 (or org-current-tag-alist (org-get-buffer-tags))))
14364 (if (car-safe files) files
14365 (org-agenda-files))))))))
14367 (defun org-make-tags-matcher (match)
14368 "Create the TAGS/TODO matcher form for the selection string MATCH.
14370 Returns a cons of the selection string MATCH and a function
14371 implementing the matcher.
14373 The matcher is to be called at an Org entry, with point on the
14374 headline, and returns non-nil if the entry matches the selection
14375 string MATCH. It must be called with three arguments: the TODO
14376 keyword at the entry (or nil if none), the list of all tags at
14377 the entry including inherited ones and the reduced level of the
14378 headline. Additionally, the category of the entry, if any, must
14379 be specified as the text property `org-category' on the headline.
14381 This function sets the variable `org--matcher-tags-todo-only' to
14382 a non-nil value if the matcher restricts matching to TODO
14383 entries, otherwise it is not touched.
14385 See also `org-scan-tags'."
14386 (unless match
14387 ;; Get a new match request, with completion against the global
14388 ;; tags table and the local tags in current buffer.
14389 (let ((org-last-tags-completion-table
14390 (org-uniquify
14391 (delq nil (append (org-get-buffer-tags)
14392 (org-global-tags-completion-table))))))
14393 (setq match
14394 (completing-read
14395 "Match: "
14396 'org-tags-completion-function nil nil nil 'org-tags-history))))
14398 (let ((match0 match)
14399 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14400 (start 0)
14401 tagsmatch todomatch tagsmatcher todomatcher)
14403 ;; Expand group tags.
14404 (setq match (org-tags-expand match))
14406 ;; Check if there is a TODO part of this match, which would be the
14407 ;; part after a "/". To make sure that this slash is not part of
14408 ;; a property value to be matched against, we also check that
14409 ;; there is no / after that slash. First, find the last slash.
14410 (let ((s 0))
14411 (while (string-match "/+" match s)
14412 (setq start (match-beginning 0))
14413 (setq s (match-end 0))))
14414 (if (and (string-match "/+" match start)
14415 (not (string-match-p "\"" match start)))
14416 ;; Match contains also a TODO-matching request.
14417 (progn
14418 (setq tagsmatch (substring match 0 (match-beginning 0)))
14419 (setq todomatch (substring match (match-end 0)))
14420 (when (string-prefix-p "!" todomatch)
14421 (setq org--matcher-tags-todo-only t)
14422 (setq todomatch (substring todomatch 1)))
14423 (when (string-match "\\`\\s-*\\'" todomatch)
14424 (setq todomatch nil)))
14425 ;; Only matching tags.
14426 (setq tagsmatch match)
14427 (setq todomatch nil))
14429 ;; Make the tags matcher.
14430 (when (org-string-nw-p tagsmatch)
14431 (let ((orlist nil)
14432 (orterms (org-split-string tagsmatch "|"))
14433 term)
14434 (while (setq term (pop orterms))
14435 (while (and (equal (substring term -1) "\\") orterms)
14436 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14437 (while (string-match re term)
14438 (let* ((rest (substring term (match-end 0)))
14439 (minus (and (match-end 1)
14440 (equal (match-string 1 term) "-")))
14441 (tag (save-match-data
14442 (replace-regexp-in-string
14443 "\\\\-" "-" (match-string 2 term))))
14444 (regexp (eq (string-to-char tag) ?{))
14445 (levelp (match-end 4))
14446 (propp (match-end 5))
14448 (cond
14449 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14450 (levelp
14451 `(,(org-op-to-function (match-string 3 term))
14452 level
14453 ,(string-to-number (match-string 4 term))))
14454 (propp
14455 (let* ((gv (pcase (upcase (match-string 5 term))
14456 ("CATEGORY"
14457 '(get-text-property (point) 'org-category))
14458 ("TODO" 'todo)
14459 (p `(org-cached-entry-get nil ,p))))
14460 (pv (match-string 7 term))
14461 (regexp (eq (string-to-char pv) ?{))
14462 (strp (eq (string-to-char pv) ?\"))
14463 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14464 (po (org-op-to-function (match-string 6 term)
14465 (if timep 'time strp))))
14466 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14467 (when timep (setq pv (org-matcher-time pv)))
14468 (cond ((and regexp (eq po 'org<>))
14469 `(not (string-match ,pv (or ,gv ""))))
14470 (regexp `(string-match ,pv (or ,gv "")))
14471 (strp `(,po (or ,gv "") ,pv))
14473 `(,po
14474 (string-to-number (or ,gv ""))
14475 ,(string-to-number pv))))))
14476 (t `(member ,tag tags-list)))))
14477 (push (if minus `(not ,mm) mm) tagsmatcher)
14478 (setq term rest)))
14479 (push `(and ,@tagsmatcher) orlist)
14480 (setq tagsmatcher nil))
14481 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14483 ;; Make the TODO matcher.
14484 (when (org-string-nw-p todomatch)
14485 (let ((orlist nil))
14486 (dolist (term (org-split-string todomatch "|"))
14487 (while (string-match re term)
14488 (let* ((minus (and (match-end 1)
14489 (equal (match-string 1 term) "-")))
14490 (kwd (match-string 2 term))
14491 (regexp (eq (string-to-char kwd) ?{))
14492 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14493 `(equal todo ,kwd))))
14494 (push (if minus `(not ,mm) mm) todomatcher))
14495 (setq term (substring term (match-end 0))))
14496 (push (if (> (length todomatcher) 1)
14497 (cons 'and todomatcher)
14498 (car todomatcher))
14499 orlist)
14500 (setq todomatcher nil))
14501 (setq todomatcher (cons 'or orlist))))
14503 ;; Return the string and function of the matcher. If no
14504 ;; tags-specific or todo-specific matcher exists, match
14505 ;; everything.
14506 (let ((matcher (if (and tagsmatcher todomatcher)
14507 `(and ,tagsmatcher ,todomatcher)
14508 (or tagsmatcher todomatcher t))))
14509 (when org--matcher-tags-todo-only
14510 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14511 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14513 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14514 "Expand group tags in MATCH.
14516 This replaces every group tag in MATCH with a regexp tag search.
14517 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14518 will be replaced like this:
14520 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14521 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14522 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14524 Replacing by a regexp preserves the structure of the match.
14525 E.g., this expansion
14527 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14529 will match anything tagged with \"Lab\" and \"Home\", or tagged
14530 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14532 A group tag in MATCH can contain regular expressions of its own.
14533 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14534 will be replaced like this:
14536 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14538 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14539 assumed to be a single group tag, and the function will return
14540 the list of tags in this group.
14542 When DOWNCASE is non-nil, expand downcased TAGS."
14543 (if org-group-tags
14544 (let* ((case-fold-search t)
14545 (stable org-mode-syntax-table)
14546 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14547 (taggroups (if downcased
14548 (mapcar (lambda (tg) (mapcar #'downcase tg))
14549 taggroups)
14550 taggroups))
14551 (taggroups-keys (mapcar #'car taggroups))
14552 (return-match (if downcased (downcase match) match))
14553 (count 0)
14554 (work-already-expanded tags-already-expanded)
14555 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14556 ;; @ and _ are allowed as word-components in tags.
14557 (modify-syntax-entry ?@ "w" stable)
14558 (modify-syntax-entry ?_ "w" stable)
14559 ;; Temporarily replace regexp-expressions in the match-expression.
14560 (while (string-match "{.+?}" return-match)
14561 (cl-incf count)
14562 (push (match-string 0 return-match) regexps-in-match)
14563 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14564 (while (and taggroups-keys
14565 (with-syntax-table stable
14566 (string-match
14567 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14568 (regexp-opt taggroups-keys) "\\>\\)")
14569 return-match)))
14570 (let* ((dir (match-string 1 return-match))
14571 (tag (match-string 2 return-match))
14572 (tag (if downcased (downcase tag) tag)))
14573 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14574 (member tag work-already-expanded))
14575 (setq tags-in-group (assoc tag taggroups))
14576 (push tag work-already-expanded)
14577 ;; Recursively expand each tag in the group, if the tag hasn't
14578 ;; already been expanded. Restore the match-data after all recursive calls.
14579 (save-match-data
14580 (let (tags-expanded)
14581 (dolist (x (cdr tags-in-group))
14582 (if (and (member x taggroups-keys)
14583 (not (member x work-already-expanded)))
14584 (setq tags-expanded
14585 (delete-dups
14586 (append
14587 (org-tags-expand x t downcased
14588 work-already-expanded)
14589 tags-expanded)))
14590 (setq tags-expanded
14591 (append (list x) tags-expanded)))
14592 (setq work-already-expanded
14593 (delete-dups
14594 (append tags-expanded
14595 work-already-expanded))))
14596 (setq tags-in-group
14597 (delete-dups (cons (car tags-in-group)
14598 tags-expanded)))))
14599 ;; Filter tag-regexps from tags.
14600 (setq regexp-in-group-escaped
14601 (delq nil (mapcar (lambda (x)
14602 (if (stringp x)
14603 (and (equal "{" (substring x 0 1))
14604 (equal "}" (substring x -1))
14607 tags-in-group))
14608 regexp-in-group
14609 (mapcar (lambda (x)
14610 (substring x 1 -1))
14611 regexp-in-group-escaped)
14612 tags-in-group
14613 (delq nil (mapcar (lambda (x)
14614 (if (stringp x)
14615 (and (not (equal "{" (substring x 0 1)))
14616 (not (equal "}" (substring x -1)))
14619 tags-in-group)))
14620 ;; If single-as-list, do no more in the while-loop.
14621 (if (not single-as-list)
14622 (progn
14623 (when regexp-in-group
14624 (setq regexp-in-group
14625 (concat "\\|"
14626 (mapconcat 'identity regexp-in-group
14627 "\\|"))))
14628 (setq tags-in-group
14629 (concat dir
14630 "{\\<"
14631 (regexp-opt tags-in-group)
14632 "\\>"
14633 regexp-in-group
14634 "}"))
14635 (when (stringp tags-in-group)
14636 (org-add-props tags-in-group '(grouptag t)))
14637 (setq return-match
14638 (replace-match tags-in-group t t return-match)))
14639 (setq tags-in-group
14640 (append regexp-in-group-escaped tags-in-group))))
14641 (setq taggroups-keys (delete tag taggroups-keys))))
14642 ;; Add the regular expressions back into the match-expression again.
14643 (while regexps-in-match
14644 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14645 (pop regexps-in-match)
14646 return-match t t))
14647 (cl-decf count))
14648 (if single-as-list
14649 (if tags-in-group tags-in-group (list return-match))
14650 return-match))
14651 (if single-as-list
14652 (list (if downcased (downcase match) match))
14653 match)))
14655 (defun org-op-to-function (op &optional stringp)
14656 "Turn an operator into the appropriate function."
14657 (setq op
14658 (cond
14659 ((equal op "<" ) '(< string< org-time<))
14660 ((equal op ">" ) '(> org-string> org-time>))
14661 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14662 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14663 ((member op '("=" "==")) '(= string= org-time=))
14664 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14665 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14667 (defun org<> (a b) (not (= a b)))
14668 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14669 (defun org-string>= (a b) (not (string< a b)))
14670 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14671 (defun org-string<> (a b) (not (string= a b)))
14672 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14673 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14674 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14675 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14676 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14677 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14678 (defun org-2ft (s)
14679 "Convert S to a floating point time.
14680 If S is already a number, just return it. If it is a string, parse
14681 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14682 (cond
14683 ((numberp s) s)
14684 ((stringp s)
14685 (condition-case nil
14686 (float-time (apply 'encode-time (org-parse-time-string s)))
14687 (error 0.)))
14688 (t 0.)))
14690 (defun org-time-today ()
14691 "Time in seconds today at 0:00.
14692 Returns the float number of seconds since the beginning of the
14693 epoch to the beginning of today (00:00)."
14694 (float-time (apply 'encode-time
14695 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14697 (defun org-matcher-time (s)
14698 "Interpret a time comparison value."
14699 (save-match-data
14700 (cond
14701 ((string= s "<now>") (float-time))
14702 ((string= s "<today>") (org-time-today))
14703 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14704 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14705 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14706 (+ (org-time-today)
14707 (* (string-to-number (match-string 1 s))
14708 (cdr (assoc (match-string 2 s)
14709 '(("d" . 86400.0) ("w" . 604800.0)
14710 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14711 (t (org-2ft s)))))
14713 (defun org-match-any-p (re list)
14714 "Does re match any element of list?"
14715 (setq list (mapcar (lambda (x) (string-match re x)) list))
14716 (delq nil list))
14718 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14719 (defvar org-tags-overlay (make-overlay 1 1))
14720 (delete-overlay org-tags-overlay)
14722 (defun org-get-local-tags-at (&optional pos)
14723 "Get a list of tags defined in the current headline."
14724 (org-get-tags-at pos 'local))
14726 (defun org-get-local-tags ()
14727 "Get a list of tags defined in the current headline."
14728 (org-get-tags-at nil 'local))
14730 (defun org-get-tags-at (&optional pos local)
14731 "Get a list of all headline tags applicable at POS.
14732 POS defaults to point. If tags are inherited, the list contains
14733 the targets in the same sequence as the headlines appear, i.e.
14734 the tags of the current headline come last.
14735 When LOCAL is non-nil, only return tags from the current headline,
14736 ignore inherited ones."
14737 (interactive)
14738 (if (and org-trust-scanner-tags
14739 (or (not pos) (equal pos (point)))
14740 (not local))
14741 org-scanner-tags
14742 (let (tags ltags lastpos parent)
14743 (save-excursion
14744 (save-restriction
14745 (widen)
14746 (goto-char (or pos (point)))
14747 (save-match-data
14748 (catch 'done
14749 (condition-case nil
14750 (progn
14751 (org-back-to-heading t)
14752 (while (not (equal lastpos (point)))
14753 (setq lastpos (point))
14754 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14755 (setq ltags (org-split-string
14756 (match-string-no-properties 1) ":"))
14757 (when parent
14758 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14759 (setq tags (append
14760 (if parent
14761 (org-remove-uninherited-tags ltags)
14762 ltags)
14763 tags)))
14764 (or org-use-tag-inheritance (throw 'done t))
14765 (when local (throw 'done t))
14766 (or (org-up-heading-safe) (error nil))
14767 (setq parent t)))
14768 (error nil)))))
14769 (if local
14770 tags
14771 (reverse (delete-dups
14772 (reverse (append
14773 (org-remove-uninherited-tags
14774 org-file-tags)
14775 tags)))))))))
14777 (defun org-add-prop-inherited (s)
14778 (add-text-properties 0 (length s) '(inherited t) s)
14781 (defun org-toggle-tag (tag &optional onoff)
14782 "Toggle the tag TAG for the current line.
14783 If ONOFF is `on' or `off', don't toggle but set to this state."
14784 (let (res current)
14785 (save-excursion
14786 (org-back-to-heading t)
14787 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14788 (point-at-eol) t)
14789 (progn
14790 (setq current (match-string 1))
14791 (replace-match ""))
14792 (setq current ""))
14793 (setq current (nreverse (org-split-string current ":")))
14794 (cond
14795 ((eq onoff 'on)
14796 (setq res t)
14797 (or (member tag current) (push tag current)))
14798 ((eq onoff 'off)
14799 (or (not (member tag current)) (setq current (delete tag current))))
14800 (t (if (member tag current)
14801 (setq current (delete tag current))
14802 (setq res t)
14803 (push tag current))))
14804 (end-of-line 1)
14805 (if current
14806 (progn
14807 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14808 (org-set-tags nil t))
14809 (delete-horizontal-space))
14810 (run-hooks 'org-after-tags-change-hook))
14811 res))
14813 (defun org--align-tags-here (to-col)
14814 "Align tags on the current headline to TO-COL.
14815 Assume point is on a headline."
14816 (let ((pos (point)))
14817 (beginning-of-line)
14818 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14819 (>= pos (match-beginning 2)))
14820 ;; No tags or point within tags: do not align.
14821 (goto-char pos)
14822 (goto-char (match-beginning 1))
14823 (let ((shift (max (- (if (>= to-col 0) to-col
14824 (- (abs to-col) (string-width (match-string 2))))
14825 (current-column))
14826 1)))
14827 (replace-match (make-string shift ?\s) nil nil nil 1)
14828 ;; Preserve initial position, if possible. In any case, stop
14829 ;; before tags.
14830 (when (< pos (point)) (goto-char pos))))))
14832 (defun org-set-tags-command (&optional arg just-align)
14833 "Call the set-tags command for the current entry."
14834 (interactive "P")
14835 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14836 (org-set-tags arg just-align)
14837 (save-excursion
14838 (unless (and (org-region-active-p)
14839 org-loop-over-headlines-in-active-region)
14840 (org-back-to-heading t))
14841 (org-set-tags arg just-align))))
14843 (defun org-set-tags-to (data)
14844 "Set the tags of the current entry to DATA, replacing the current tags.
14845 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14846 If DATA is nil or the empty string, any tags will be removed."
14847 (interactive "sTags: ")
14848 (setq data
14849 (cond
14850 ((eq data nil) "")
14851 ((equal data "") "")
14852 ((stringp data)
14853 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14854 ":"))
14855 ((listp data)
14856 (concat ":" (mapconcat 'identity data ":") ":"))))
14857 (when data
14858 (save-excursion
14859 (org-back-to-heading t)
14860 (when (let ((case-fold-search nil))
14861 (looking-at org-complex-heading-regexp))
14862 (if (match-end 5)
14863 (progn
14864 (goto-char (match-beginning 5))
14865 (insert data)
14866 (delete-region (point) (point-at-eol))
14867 (org-set-tags nil 'align))
14868 (goto-char (point-at-eol))
14869 (insert " " data)
14870 (org-set-tags nil 'align)))
14871 (beginning-of-line 1)
14872 (when (looking-at ".*?\\([ \t]+\\)$")
14873 (delete-region (match-beginning 1) (match-end 1))))))
14875 (defun org-align-all-tags ()
14876 "Align the tags in all headings."
14877 (interactive)
14878 (save-excursion
14879 (or (ignore-errors (org-back-to-heading t))
14880 (outline-next-heading))
14881 (if (org-at-heading-p)
14882 (org-set-tags t)
14883 (message "No headings"))))
14885 (defvar org-indent-indentation-per-level)
14886 (defun org-set-tags (&optional arg just-align)
14887 "Set the tags for the current headline.
14888 With prefix ARG, realign all tags in headings in the current buffer.
14889 When JUST-ALIGN is non-nil, only align tags."
14890 (interactive "P")
14891 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14892 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14893 'region-start-level
14894 'region))
14895 org-loop-over-headlines-in-active-region)
14896 (org-map-entries
14897 ;; We don't use ARG and JUST-ALIGN here because these args
14898 ;; are not useful when looping over headlines.
14899 #'org-set-tags
14900 org-loop-over-headlines-in-active-region
14902 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14903 (let ((org-setting-tags t))
14904 (if arg
14905 (save-excursion
14906 (goto-char (point-min))
14907 (while (re-search-forward org-outline-regexp-bol nil t)
14908 (org-set-tags nil t)
14909 (end-of-line))
14910 (message "All tags realigned to column %d" org-tags-column))
14911 (let* ((current (org-get-tags-string))
14912 (tags
14913 (if just-align current
14914 ;; Get a new set of tags from the user.
14915 (save-excursion
14916 (let* ((seen)
14917 (table
14918 (setq
14919 org-last-tags-completion-table
14920 ;; Uniquify tags in alists, yet preserve
14921 ;; structure (i.e., keywords).
14922 (delq nil
14923 (mapcar
14924 (lambda (pair)
14925 (let ((head (car pair)))
14926 (cond ((symbolp head) pair)
14927 ((member head seen) nil)
14928 (t (push head seen)
14929 pair))))
14930 (append
14931 (or org-current-tag-alist
14932 (org-get-buffer-tags))
14933 (and
14934 org-complete-tags-always-offer-all-agenda-tags
14935 (org-global-tags-completion-table
14936 (org-agenda-files))))))))
14937 (current-tags (org-split-string current ":"))
14938 (inherited-tags
14939 (nreverse (nthcdr (length current-tags)
14940 (nreverse (org-get-tags-at))))))
14941 (replace-regexp-in-string
14942 "\\([-+&]+\\|,\\)"
14944 (if (or (eq t org-use-fast-tag-selection)
14945 (and org-use-fast-tag-selection
14946 (delq nil (mapcar #'cdr table))))
14947 (org-fast-tag-selection
14948 current-tags inherited-tags table
14949 (and org-fast-tag-selection-include-todo
14950 org-todo-key-alist))
14951 (let ((org-add-colon-after-tag-completion
14952 (< 1 (length table))))
14953 (org-trim
14954 (completing-read
14955 "Tags: "
14956 #'org-tags-completion-function
14957 nil nil current 'org-tags-history))))))))))
14959 (when org-tags-sort-function
14960 (setq tags
14961 (mapconcat
14962 #'identity
14963 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14964 org-tags-sort-function)
14965 ":")))
14967 (if (not (org-string-nw-p tags)) (setq tags "")
14968 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14969 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14971 ;; Insert new tags at the correct column.
14972 (unless (equal current tags)
14973 (save-excursion
14974 (beginning-of-line)
14975 (let ((case-fold-search nil))
14976 (looking-at org-complex-heading-regexp))
14977 ;; Remove current tags, if any.
14978 (when (match-end 5) (replace-match "" nil nil nil 5))
14979 ;; Insert new tags, if any. Otherwise, remove trailing
14980 ;; white spaces.
14981 (end-of-line)
14982 (if (not (equal tags ""))
14983 ;; When text is being inserted on an invisible
14984 ;; region boundary, it can be inadvertently sucked
14985 ;; into invisibility.
14986 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14987 (skip-chars-backward " \t")
14988 (delete-region (point) (line-end-position)))))
14989 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14990 ;; is on.
14991 (unless (equal tags "")
14992 (let* ((level (save-excursion
14993 (beginning-of-line)
14994 (skip-chars-forward "\\*")))
14995 (offset (if (bound-and-true-p org-indent-mode)
14996 (* (1- org-indent-indentation-per-level)
14997 (1- level))
14999 (tags-column
15000 (+ org-tags-column
15001 (if (> org-tags-column 0) (- offset) offset))))
15002 (org--align-tags-here tags-column))))
15003 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15005 (defun org-change-tag-in-region (beg end tag off)
15006 "Add or remove TAG for each entry in the region.
15007 This works in the agenda, and also in an Org buffer."
15008 (interactive
15009 (list (region-beginning) (region-end)
15010 (let ((org-last-tags-completion-table
15011 (if (derived-mode-p 'org-mode)
15012 (org-uniquify
15013 (delq nil (append (org-get-buffer-tags)
15014 (org-global-tags-completion-table))))
15015 (org-global-tags-completion-table))))
15016 (completing-read
15017 "Tag: " 'org-tags-completion-function nil nil nil
15018 'org-tags-history))
15019 (progn
15020 (message "[s]et or [r]emove? ")
15021 (equal (read-char-exclusive) ?r))))
15022 (when (fboundp 'deactivate-mark) (deactivate-mark))
15023 (let ((agendap (equal major-mode 'org-agenda-mode))
15024 l1 l2 m buf pos newhead (cnt 0))
15025 (goto-char end)
15026 (setq l2 (1- (org-current-line)))
15027 (goto-char beg)
15028 (setq l1 (org-current-line))
15029 (cl-loop for l from l1 to l2 do
15030 (org-goto-line l)
15031 (setq m (get-text-property (point) 'org-hd-marker))
15032 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15033 (and agendap m))
15034 (setq buf (if agendap (marker-buffer m) (current-buffer))
15035 pos (if agendap m (point)))
15036 (with-current-buffer buf
15037 (save-excursion
15038 (save-restriction
15039 (goto-char pos)
15040 (setq cnt (1+ cnt))
15041 (org-toggle-tag tag (if off 'off 'on))
15042 (setq newhead (org-get-heading)))))
15043 (and agendap (org-agenda-change-all-lines newhead m))))
15044 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15046 (defun org-tags-completion-function (string _predicate &optional flag)
15047 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15048 (confirm (lambda (x) (stringp (car x)))))
15049 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15050 (setq s1 (match-string 1 string)
15051 s2 (match-string 2 string))
15052 (setq s1 "" s2 string))
15053 (cond
15054 ((eq flag nil)
15055 ;; try completion
15056 (setq rtn (try-completion s2 ctable confirm))
15057 (when (stringp rtn)
15058 (setq rtn
15059 (concat s1 s2 (substring rtn (length s2))
15060 (if (and org-add-colon-after-tag-completion
15061 (assoc rtn ctable))
15062 ":" ""))))
15063 rtn)
15064 ((eq flag t)
15065 ;; all-completions
15066 (all-completions s2 ctable confirm))
15067 ((eq flag 'lambda)
15068 ;; exact match?
15069 (assoc s2 ctable)))))
15071 (defun org-fast-tag-insert (kwd tags face &optional end)
15072 "Insert KDW, and the TAGS, the latter with face FACE.
15073 Also insert END."
15074 (insert (format "%-12s" (concat kwd ":"))
15075 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15076 (or end "")))
15078 (defun org-fast-tag-show-exit (flag)
15079 (save-excursion
15080 (org-goto-line 3)
15081 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15082 (replace-match ""))
15083 (when flag
15084 (end-of-line 1)
15085 (org-move-to-column (- (window-width) 19) t)
15086 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15088 (defun org-set-current-tags-overlay (current prefix)
15089 "Add an overlay to CURRENT tag with PREFIX."
15090 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15091 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15092 (org-overlay-display org-tags-overlay (concat prefix s))))
15094 (defvar org-last-tag-selection-key nil)
15095 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15096 "Fast tag selection with single keys.
15097 CURRENT is the current list of tags in the headline, INHERITED is the
15098 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15099 possibly with grouping information. TODO-TABLE is a similar table with
15100 TODO keywords, should these have keys assigned to them.
15101 If the keys are nil, a-z are automatically assigned.
15102 Returns the new tags string, or nil to not change the current settings."
15103 (let* ((fulltable (append table todo-table))
15104 (maxlen (apply 'max (mapcar
15105 (lambda (x)
15106 (if (stringp (car x)) (string-width (car x)) 0))
15107 fulltable)))
15108 (buf (current-buffer))
15109 (expert (eq org-fast-tag-selection-single-key 'expert))
15110 (buffer-tags nil)
15111 (fwidth (+ maxlen 3 1 3))
15112 (ncol (/ (- (window-width) 4) fwidth))
15113 (i-face 'org-done)
15114 (c-face 'org-todo)
15115 tg cnt e c char c1 c2 ntable tbl rtn
15116 ov-start ov-end ov-prefix
15117 (exit-after-next org-fast-tag-selection-single-key)
15118 (done-keywords org-done-keywords)
15119 groups ingroup intaggroup)
15120 (save-excursion
15121 (beginning-of-line 1)
15122 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15123 (setq ov-start (match-beginning 1)
15124 ov-end (match-end 1)
15125 ov-prefix "")
15126 (setq ov-start (1- (point-at-eol))
15127 ov-end (1+ ov-start))
15128 (skip-chars-forward "^\n\r")
15129 (setq ov-prefix
15130 (concat
15131 (buffer-substring (1- (point)) (point))
15132 (if (> (current-column) org-tags-column)
15134 (make-string (- org-tags-column (current-column)) ?\ ))))))
15135 (move-overlay org-tags-overlay ov-start ov-end)
15136 (save-window-excursion
15137 (if expert
15138 (set-buffer (get-buffer-create " *Org tags*"))
15139 (delete-other-windows)
15140 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15141 (org-switch-to-buffer-other-window " *Org tags*"))
15142 (erase-buffer)
15143 (setq-local org-done-keywords done-keywords)
15144 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15145 (org-fast-tag-insert "Current" current c-face "\n\n")
15146 (org-fast-tag-show-exit exit-after-next)
15147 (org-set-current-tags-overlay current ov-prefix)
15148 (setq tbl fulltable char ?a cnt 0)
15149 (while (setq e (pop tbl))
15150 (cond
15151 ((eq (car e) :startgroup)
15152 (push '() groups) (setq ingroup t)
15153 (unless (zerop cnt)
15154 (setq cnt 0)
15155 (insert "\n"))
15156 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15157 ((eq (car e) :endgroup)
15158 (setq ingroup nil cnt 0)
15159 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15160 ((eq (car e) :startgrouptag)
15161 (setq intaggroup t)
15162 (unless (zerop cnt)
15163 (setq cnt 0)
15164 (insert "\n"))
15165 (insert "[ "))
15166 ((eq (car e) :endgrouptag)
15167 (setq intaggroup nil cnt 0)
15168 (insert "]\n"))
15169 ((equal e '(:newline))
15170 (unless (zerop cnt)
15171 (setq cnt 0)
15172 (insert "\n")
15173 (setq e (car tbl))
15174 (while (equal (car tbl) '(:newline))
15175 (insert "\n")
15176 (setq tbl (cdr tbl)))))
15177 ((equal e '(:grouptags)) (insert " : "))
15179 (setq tg (copy-sequence (car e)) c2 nil)
15180 (if (cdr e)
15181 (setq c (cdr e))
15182 ;; automatically assign a character.
15183 (setq c1 (string-to-char
15184 (downcase (substring
15185 tg (if (= (string-to-char tg) ?@) 1 0)))))
15186 (if (or (rassoc c1 ntable) (rassoc c1 table))
15187 (while (or (rassoc char ntable) (rassoc char table))
15188 (setq char (1+ char)))
15189 (setq c2 c1))
15190 (setq c (or c2 char)))
15191 (when ingroup (push tg (car groups)))
15192 (setq tg (org-add-props tg nil 'face
15193 (cond
15194 ((not (assoc tg table))
15195 (org-get-todo-face tg))
15196 ((member tg current) c-face)
15197 ((member tg inherited) i-face))))
15198 (when (equal (caar tbl) :grouptags)
15199 (org-add-props tg nil 'face 'org-tag-group))
15200 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15201 (insert "[" c "] " tg (make-string
15202 (- fwidth 4 (length tg)) ?\ ))
15203 (push (cons tg c) ntable)
15204 (when (= (cl-incf cnt) ncol)
15205 (insert "\n")
15206 (when (or ingroup intaggroup) (insert " "))
15207 (setq cnt 0)))))
15208 (setq ntable (nreverse ntable))
15209 (insert "\n")
15210 (goto-char (point-min))
15211 (unless expert (org-fit-window-to-buffer))
15212 (setq rtn
15213 (catch 'exit
15214 (while t
15215 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15216 (if (not groups) "no " "")
15217 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15218 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15219 (setq org-last-tag-selection-key c)
15220 (cond
15221 ((= c ?\r) (throw 'exit t))
15222 ((= c ?!)
15223 (setq groups (not groups))
15224 (goto-char (point-min))
15225 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15226 ((= c ?\C-c)
15227 (if (not expert)
15228 (org-fast-tag-show-exit
15229 (setq exit-after-next (not exit-after-next)))
15230 (setq expert nil)
15231 (delete-other-windows)
15232 (set-window-buffer (split-window-vertically) " *Org tags*")
15233 (org-switch-to-buffer-other-window " *Org tags*")
15234 (org-fit-window-to-buffer)))
15235 ((or (= c ?\C-g)
15236 (and (= c ?q) (not (rassoc c ntable))))
15237 (delete-overlay org-tags-overlay)
15238 (setq quit-flag t))
15239 ((= c ?\ )
15240 (setq current nil)
15241 (when exit-after-next (setq exit-after-next 'now)))
15242 ((= c ?\t)
15243 (condition-case nil
15244 (setq tg (completing-read
15245 "Tag: "
15246 (or buffer-tags
15247 (with-current-buffer buf
15248 (setq buffer-tags
15249 (org-get-buffer-tags))))))
15250 (quit (setq tg "")))
15251 (when (string-match "\\S-" tg)
15252 (cl-pushnew (list tg) buffer-tags :test #'equal)
15253 (if (member tg current)
15254 (setq current (delete tg current))
15255 (push tg current)))
15256 (when exit-after-next (setq exit-after-next 'now)))
15257 ((setq e (rassoc c todo-table) tg (car e))
15258 (with-current-buffer buf
15259 (save-excursion (org-todo tg)))
15260 (when exit-after-next (setq exit-after-next 'now)))
15261 ((setq e (rassoc c ntable) tg (car e))
15262 (if (member tg current)
15263 (setq current (delete tg current))
15264 (cl-loop for g in groups do
15265 (when (member tg g)
15266 (dolist (x g) (setq current (delete x current)))))
15267 (push tg current))
15268 (when exit-after-next (setq exit-after-next 'now))))
15270 ;; Create a sorted list
15271 (setq current
15272 (sort current
15273 (lambda (a b)
15274 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15275 (when (eq exit-after-next 'now) (throw 'exit t))
15276 (goto-char (point-min))
15277 (beginning-of-line 2)
15278 (delete-region (point) (point-at-eol))
15279 (org-fast-tag-insert "Current" current c-face)
15280 (org-set-current-tags-overlay current ov-prefix)
15281 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15282 (setq tg (match-string 1))
15283 (add-text-properties
15284 (match-beginning 1) (match-end 1)
15285 (list 'face
15286 (cond
15287 ((member tg current) c-face)
15288 ((member tg inherited) i-face)
15289 (t (get-text-property (match-beginning 1) 'face))))))
15290 (goto-char (point-min)))))
15291 (delete-overlay org-tags-overlay)
15292 (if rtn
15293 (mapconcat 'identity current ":")
15294 nil))))
15296 (defun org-get-tags-string ()
15297 "Get the TAGS string in the current headline."
15298 (unless (org-at-heading-p t)
15299 (user-error "Not on a heading"))
15300 (save-excursion
15301 (beginning-of-line 1)
15302 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15303 (match-string-no-properties 1)
15304 "")))
15306 (defun org-get-tags ()
15307 "Get the list of tags specified in the current headline."
15308 (org-split-string (org-get-tags-string) ":"))
15310 (defun org-get-buffer-tags ()
15311 "Get a table of all tags used in the buffer, for completion."
15312 (org-with-wide-buffer
15313 (goto-char (point-min))
15314 (let ((tag-re (concat org-outline-regexp-bol
15315 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15316 tags)
15317 (while (re-search-forward tag-re nil t)
15318 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15319 (push tag tags)))
15320 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15322 ;;;; The mapping API
15324 (defvar org-agenda-skip-comment-trees)
15325 (defvar org-agenda-skip-function)
15326 (defun org-map-entries (func &optional match scope &rest skip)
15327 "Call FUNC at each headline selected by MATCH in SCOPE.
15329 FUNC is a function or a lisp form. The function will be called without
15330 arguments, with the cursor positioned at the beginning of the headline.
15331 The return values of all calls to the function will be collected and
15332 returned as a list.
15334 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15335 does not need to preserve point. After evaluation, the cursor will be
15336 moved to the end of the line (presumably of the headline of the
15337 processed entry) and search continues from there. Under some
15338 circumstances, this may not produce the wanted results. For example,
15339 if you have removed (e.g. archived) the current (sub)tree it could
15340 mean that the next entry will be skipped entirely. In such cases, you
15341 can specify the position from where search should continue by making
15342 FUNC set the variable `org-map-continue-from' to the desired buffer
15343 position.
15345 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15346 Only headlines that are matched by this query will be considered during
15347 the iteration. When MATCH is nil or t, all headlines will be
15348 visited by the iteration.
15350 SCOPE determines the scope of this command. It can be any of:
15352 nil The current buffer, respecting the restriction if any
15353 tree The subtree started with the entry at point
15354 region The entries within the active region, if any
15355 region-start-level
15356 The entries within the active region, but only those at
15357 the same level than the first one.
15358 file The current buffer, without restriction
15359 file-with-archives
15360 The current buffer, and any archives associated with it
15361 agenda All agenda files
15362 agenda-with-archives
15363 All agenda files with any archive files associated with them
15364 \(file1 file2 ...)
15365 If this is a list, all files in the list will be scanned
15367 The remaining args are treated as settings for the skipping facilities of
15368 the scanner. The following items can be given here:
15370 archive skip trees with the archive tag
15371 comment skip trees with the COMMENT keyword
15372 function or Emacs Lisp form:
15373 will be used as value for `org-agenda-skip-function', so
15374 whenever the function returns a position, FUNC will not be
15375 called for that entry and search will continue from the
15376 position returned
15378 If your function needs to retrieve the tags including inherited tags
15379 at the *current* entry, you can use the value of the variable
15380 `org-scanner-tags' which will be much faster than getting the value
15381 with `org-get-tags-at'. If your function gets properties with
15382 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15383 to t around the call to `org-entry-properties' to get the same speedup.
15384 Note that if your function moves around to retrieve tags and properties at
15385 a *different* entry, you cannot use these techniques."
15386 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15387 (not (org-region-active-p)))
15388 (let* ((org-agenda-archives-mode nil) ; just to make sure
15389 (org-agenda-skip-archived-trees (memq 'archive skip))
15390 (org-agenda-skip-comment-trees (memq 'comment skip))
15391 (org-agenda-skip-function
15392 (car (org-delete-all '(comment archive) skip)))
15393 (org-tags-match-list-sublevels t)
15394 (start-level (eq scope 'region-start-level))
15395 matcher res
15396 org-todo-keywords-for-agenda
15397 org-done-keywords-for-agenda
15398 org-todo-keyword-alist-for-agenda
15399 org-tag-alist-for-agenda
15400 org--matcher-tags-todo-only)
15402 (cond
15403 ((eq match t) (setq matcher t))
15404 ((eq match nil) (setq matcher t))
15405 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15407 (save-excursion
15408 (save-restriction
15409 (cond ((eq scope 'tree)
15410 (org-back-to-heading t)
15411 (org-narrow-to-subtree)
15412 (setq scope nil))
15413 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15414 (org-region-active-p))
15415 ;; If needed, set start-level to a string like "2"
15416 (when start-level
15417 (save-excursion
15418 (goto-char (region-beginning))
15419 (unless (org-at-heading-p) (outline-next-heading))
15420 (setq start-level (org-current-level))))
15421 (narrow-to-region (region-beginning)
15422 (save-excursion
15423 (goto-char (region-end))
15424 (unless (and (bolp) (org-at-heading-p))
15425 (outline-next-heading))
15426 (point)))
15427 (setq scope nil)))
15429 (if (not scope)
15430 (progn
15431 (org-agenda-prepare-buffers
15432 (and buffer-file-name (list buffer-file-name)))
15433 (setq res
15434 (org-scan-tags
15435 func matcher org--matcher-tags-todo-only start-level)))
15436 ;; Get the right scope
15437 (cond
15438 ((and scope (listp scope) (symbolp (car scope)))
15439 (setq scope (eval scope)))
15440 ((eq scope 'agenda)
15441 (setq scope (org-agenda-files t)))
15442 ((eq scope 'agenda-with-archives)
15443 (setq scope (org-agenda-files t))
15444 (setq scope (org-add-archive-files scope)))
15445 ((eq scope 'file)
15446 (setq scope (and buffer-file-name (list buffer-file-name))))
15447 ((eq scope 'file-with-archives)
15448 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15449 (org-agenda-prepare-buffers scope)
15450 (dolist (file scope)
15451 (with-current-buffer (org-find-base-buffer-visiting file)
15452 (org-with-wide-buffer
15453 (goto-char (point-min))
15454 (setq res
15455 (append
15457 (org-scan-tags
15458 func matcher org--matcher-tags-todo-only)))))))))
15459 res)))
15461 ;;; Properties API
15463 (defconst org-special-properties
15464 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15465 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15466 "The special properties valid in Org mode.
15467 These are properties that are not defined in the property drawer,
15468 but in some other way.")
15470 (defconst org-default-properties
15471 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15472 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15473 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15474 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15475 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15476 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15477 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15478 "Some properties that are used by Org mode for various purposes.
15479 Being in this list makes sure that they are offered for completion.")
15481 (defun org--valid-property-p (property)
15482 "Non nil when string PROPERTY is a valid property name."
15483 (not
15484 (or (equal property "")
15485 (string-match-p "\\s-" property))))
15487 (defun org--update-property-plist (key val props)
15488 "Associate KEY to VAL in alist PROPS.
15489 Modifications are made by side-effect. Return new alist."
15490 (let* ((appending (string= (substring key -1) "+"))
15491 (key (if appending (substring key 0 -1) key))
15492 (old (assoc-string key props t)))
15493 (if (not old) (cons (cons key val) props)
15494 (setcdr old (if appending (concat (cdr old) " " val) val))
15495 props)))
15497 (defun org-get-property-block (&optional beg force)
15498 "Return the (beg . end) range of the body of the property drawer.
15499 BEG is the beginning of the current subtree, or of the part
15500 before the first headline. If it is not given, it will be found.
15501 If the drawer does not exist, create it if FORCE is non-nil, or
15502 return nil."
15503 (org-with-wide-buffer
15504 (when beg (goto-char beg))
15505 (unless (org-before-first-heading-p)
15506 (let ((beg (cond (beg)
15507 ((or (not (featurep 'org-inlinetask))
15508 (org-inlinetask-in-task-p))
15509 (org-back-to-heading t))
15510 (t (org-with-limited-levels (org-back-to-heading t))))))
15511 (forward-line)
15512 (when (looking-at-p org-planning-line-re) (forward-line))
15513 (cond ((looking-at org-property-drawer-re)
15514 (forward-line)
15515 (cons (point) (progn (goto-char (match-end 0))
15516 (line-beginning-position))))
15517 (force
15518 (goto-char beg)
15519 (org-insert-property-drawer)
15520 (let ((pos (save-excursion (search-forward ":END:")
15521 (line-beginning-position))))
15522 (cons pos pos))))))))
15524 (defun org-at-property-p ()
15525 "Non-nil when point is inside a property drawer.
15526 See `org-property-re' for match data, if applicable."
15527 (save-excursion
15528 (beginning-of-line)
15529 (and (looking-at org-property-re)
15530 (let ((property-drawer (save-match-data (org-get-property-block))))
15531 (and property-drawer
15532 (>= (point) (car property-drawer))
15533 (< (point) (cdr property-drawer)))))))
15535 (defun org-property-action ()
15536 "Do an action on properties."
15537 (interactive)
15538 (unless (org-at-property-p) (user-error "Not at a property"))
15539 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15540 (let ((c (read-char-exclusive)))
15541 (cl-case c
15542 (?s (call-interactively #'org-set-property))
15543 (?d (call-interactively #'org-delete-property))
15544 (?D (call-interactively #'org-delete-property-globally))
15545 (?c (call-interactively #'org-compute-property-at-point))
15546 (otherwise (user-error "No such property action %c" c)))))
15548 (defun org-inc-effort ()
15549 "Increment the value of the effort property in the current entry."
15550 (interactive)
15551 (org-set-effort nil t))
15553 (defvar org-clock-effort) ; Defined in org-clock.el.
15554 (defvar org-clock-current-task) ; Defined in org-clock.el.
15555 (defun org-set-effort (&optional value increment)
15556 "Set the effort property of the current entry.
15557 With numerical prefix arg, use the nth allowed value, 0 stands for the
15558 10th allowed value.
15560 When INCREMENT is non-nil, set the property to the next allowed value."
15561 (interactive "P")
15562 (when (equal value 0) (setq value 10))
15563 (let* ((completion-ignore-case t)
15564 (prop org-effort-property)
15565 (cur (org-entry-get nil prop))
15566 (allowed (org-property-get-allowed-values nil prop 'table))
15567 (existing (mapcar 'list (org-property-values prop)))
15568 (heading (nth 4 (org-heading-components)))
15570 (val (cond
15571 ((stringp value) value)
15572 ((and allowed (integerp value))
15573 (or (car (nth (1- value) allowed))
15574 (car (org-last allowed))))
15575 ((and allowed increment)
15576 (or (cl-caadr (member (list cur) allowed))
15577 (user-error "Allowed effort values are not set")))
15578 (allowed
15579 (message "Select 1-9,0, [RET%s]: %s"
15580 (if cur (concat "=" cur) "")
15581 (mapconcat 'car allowed " "))
15582 (setq rpl (read-char-exclusive))
15583 (if (equal rpl ?\r)
15585 (setq rpl (- rpl ?0))
15586 (when (equal rpl 0) (setq rpl 10))
15587 (if (and (> rpl 0) (<= rpl (length allowed)))
15588 (car (nth (1- rpl) allowed))
15589 (org-completing-read "Effort: " allowed nil))))
15591 (org-completing-read
15592 (concat "Effort" (and cur (string-match "\\S-" cur)
15593 (concat " [" cur "]"))
15594 ": ")
15595 existing nil nil "" nil cur)))))
15596 (unless (equal (org-entry-get nil prop) val)
15597 (org-entry-put nil prop val))
15598 (org-refresh-property
15599 '((effort . identity)
15600 (effort-minutes . org-duration-to-minutes))
15601 val)
15602 (when (equal heading (bound-and-true-p org-clock-current-task))
15603 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15604 (org-clock-update-mode-line))
15605 (message "%s is now %s" prop val)))
15607 (defun org-entry-properties (&optional pom which)
15608 "Get all properties of the current entry.
15610 When POM is a buffer position, get all properties from the entry
15611 there instead.
15613 This includes the TODO keyword, the tags, time strings for
15614 deadline, scheduled, and clocking, and any additional properties
15615 defined in the entry.
15617 If WHICH is nil or `all', get all properties. If WHICH is
15618 `special' or `standard', only get that subclass. If WHICH is
15619 a string, only get that property.
15621 Return value is an alist. Keys are properties, as upcased
15622 strings."
15623 (org-with-point-at pom
15624 (when (and (derived-mode-p 'org-mode)
15625 (ignore-errors (org-back-to-heading t)))
15626 (catch 'exit
15627 (let* ((beg (point))
15628 (specific (and (stringp which) (upcase which)))
15629 (which (cond ((not specific) which)
15630 ((member specific org-special-properties) 'special)
15631 (t 'standard)))
15632 props)
15633 ;; Get the special properties, like TODO and TAGS.
15634 (when (memq which '(nil all special))
15635 (when (or (not specific) (string= specific "CLOCKSUM"))
15636 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15637 (when clocksum
15638 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15639 props)))
15640 (when specific (throw 'exit props)))
15641 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15642 (let ((clocksumt (get-text-property (point)
15643 :org-clock-minutes-today)))
15644 (when clocksumt
15645 (push (cons "CLOCKSUM_T"
15646 (org-duration-from-minutes clocksumt))
15647 props)))
15648 (when specific (throw 'exit props)))
15649 (when (or (not specific) (string= specific "ITEM"))
15650 (let ((case-fold-search nil))
15651 (when (looking-at org-complex-heading-regexp)
15652 (push (cons "ITEM"
15653 (let ((title (match-string-no-properties 4)))
15654 (if (org-string-nw-p title)
15655 (org-remove-tabs title)
15656 "")))
15657 props)))
15658 (when specific (throw 'exit props)))
15659 (when (or (not specific) (string= specific "TODO"))
15660 (let ((case-fold-search nil))
15661 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15662 (push (cons "TODO" (match-string-no-properties 2)) props)))
15663 (when specific (throw 'exit props)))
15664 (when (or (not specific) (string= specific "PRIORITY"))
15665 (push (cons "PRIORITY"
15666 (if (looking-at org-priority-regexp)
15667 (match-string-no-properties 2)
15668 (char-to-string org-default-priority)))
15669 props)
15670 (when specific (throw 'exit props)))
15671 (when (or (not specific) (string= specific "FILE"))
15672 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15673 props)
15674 (when specific (throw 'exit props)))
15675 (when (or (not specific) (string= specific "TAGS"))
15676 (let ((value (org-string-nw-p (org-get-tags-string))))
15677 (when value (push (cons "TAGS" value) props)))
15678 (when specific (throw 'exit props)))
15679 (when (or (not specific) (string= specific "ALLTAGS"))
15680 (let ((value (org-get-tags-at)))
15681 (when value
15682 (push (cons "ALLTAGS"
15683 (format ":%s:" (mapconcat #'identity value ":")))
15684 props)))
15685 (when specific (throw 'exit props)))
15686 (when (or (not specific) (string= specific "BLOCKED"))
15687 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15688 (when specific (throw 'exit props)))
15689 (when (or (not specific)
15690 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15691 (forward-line)
15692 (when (looking-at-p org-planning-line-re)
15693 (end-of-line)
15694 (let ((bol (line-beginning-position))
15695 ;; Backward compatibility: time keywords used to
15696 ;; be configurable (before 8.3). Make sure we
15697 ;; get the correct keyword.
15698 (key-assoc `(("CLOSED" . ,org-closed-string)
15699 ("DEADLINE" . ,org-deadline-string)
15700 ("SCHEDULED" . ,org-scheduled-string))))
15701 (dolist (pair (if specific (list (assoc specific key-assoc))
15702 key-assoc))
15703 (save-excursion
15704 (when (search-backward (cdr pair) bol t)
15705 (goto-char (match-end 0))
15706 (skip-chars-forward " \t")
15707 (and (looking-at org-ts-regexp-both)
15708 (push (cons (car pair)
15709 (match-string-no-properties 0))
15710 props)))))))
15711 (when specific (throw 'exit props)))
15712 (when (or (not specific)
15713 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15714 (let ((find-ts
15715 (lambda (end ts)
15716 ;; Fix next time-stamp before END. TS is the
15717 ;; list of time-stamps found so far.
15718 (let ((ts ts)
15719 (regexp (cond
15720 ((string= specific "TIMESTAMP")
15721 org-ts-regexp)
15722 ((string= specific "TIMESTAMP_IA")
15723 org-ts-regexp-inactive)
15724 ((assoc "TIMESTAMP_IA" ts)
15725 org-ts-regexp)
15726 ((assoc "TIMESTAMP" ts)
15727 org-ts-regexp-inactive)
15728 (t org-ts-regexp-both))))
15729 (catch 'next
15730 (while (re-search-forward regexp end t)
15731 (backward-char)
15732 (let ((object (org-element-context)))
15733 ;; Accept to match timestamps in node
15734 ;; properties, too.
15735 (when (memq (org-element-type object)
15736 '(node-property timestamp))
15737 (let ((type
15738 (org-element-property :type object)))
15739 (cond
15740 ((and (memq type '(active active-range))
15741 (not (equal specific "TIMESTAMP_IA")))
15742 (unless (assoc "TIMESTAMP" ts)
15743 (push (cons "TIMESTAMP"
15744 (org-element-property
15745 :raw-value object))
15747 (when specific (throw 'exit ts))))
15748 ((and (memq type '(inactive inactive-range))
15749 (not (string= specific "TIMESTAMP")))
15750 (unless (assoc "TIMESTAMP_IA" ts)
15751 (push (cons "TIMESTAMP_IA"
15752 (org-element-property
15753 :raw-value object))
15755 (when specific (throw 'exit ts))))))
15756 ;; Both timestamp types are found,
15757 ;; move to next part.
15758 (when (= (length ts) 2) (throw 'next ts)))))
15759 ts)))))
15760 (goto-char beg)
15761 ;; First look for timestamps within headline.
15762 (let ((ts (funcall find-ts (line-end-position) nil)))
15763 (if (= (length ts) 2) (setq props (nconc ts props))
15764 ;; Then find timestamps in the section, skipping
15765 ;; planning line.
15766 (let ((end (save-excursion (outline-next-heading))))
15767 (forward-line)
15768 (when (looking-at-p org-planning-line-re) (forward-line))
15769 (setq props (nconc (funcall find-ts end ts) props))))))))
15770 ;; Get the standard properties, like :PROP:.
15771 (when (memq which '(nil all standard))
15772 ;; If we are looking after a specific property, delegate
15773 ;; to `org-entry-get', which is faster. However, make an
15774 ;; exception for "CATEGORY", since it can be also set
15775 ;; through keywords (i.e. #+CATEGORY).
15776 (if (and specific (not (equal specific "CATEGORY")))
15777 (let ((value (org-entry-get beg specific nil t)))
15778 (throw 'exit (and value (list (cons specific value)))))
15779 (let ((range (org-get-property-block beg)))
15780 (when range
15781 (let ((end (cdr range)) seen-base)
15782 (goto-char (car range))
15783 ;; Unlike to `org--update-property-plist', we
15784 ;; handle the case where base values is found
15785 ;; after its extension. We also forbid standard
15786 ;; properties to be named as special properties.
15787 (while (re-search-forward org-property-re end t)
15788 (let* ((key (upcase (match-string-no-properties 2)))
15789 (extendp (string-match-p "\\+\\'" key))
15790 (key-base (if extendp (substring key 0 -1) key))
15791 (value (match-string-no-properties 3)))
15792 (cond
15793 ((member-ignore-case key-base org-special-properties))
15794 (extendp
15795 (setq props
15796 (org--update-property-plist key value props)))
15797 ((member key seen-base))
15798 (t (push key seen-base)
15799 (let ((p (assoc-string key props t)))
15800 (if p (setcdr p (concat value " " (cdr p)))
15801 (push (cons key value) props))))))))))))
15802 (unless (assoc "CATEGORY" props)
15803 (push (cons "CATEGORY" (org-get-category beg)) props)
15804 (when (string= specific "CATEGORY") (throw 'exit props)))
15805 ;; Return value.
15806 props)))))
15808 (defun org--property-local-values (property literal-nil)
15809 "Return value for PROPERTY in current entry.
15810 Value is a list whose car is the base value for PROPERTY and cdr
15811 a list of accumulated values. Return nil if neither is found in
15812 the entry. Also return nil when PROPERTY is set to \"nil\",
15813 unless LITERAL-NIL is non-nil."
15814 (let ((range (org-get-property-block)))
15815 (when range
15816 (goto-char (car range))
15817 (let* ((case-fold-search t)
15818 (end (cdr range))
15819 (value
15820 ;; Base value.
15821 (save-excursion
15822 (let ((v (and (re-search-forward
15823 (org-re-property property nil t) end t)
15824 (match-string-no-properties 3))))
15825 (list (if literal-nil v (org-not-nil v)))))))
15826 ;; Find additional values.
15827 (let* ((property+ (org-re-property (concat property "+") nil t)))
15828 (while (re-search-forward property+ end t)
15829 (push (match-string-no-properties 3) value)))
15830 ;; Return final values.
15831 (and (not (equal value '(nil))) (nreverse value))))))
15833 (defun org--property-global-value (property literal-nil)
15834 "Return value for PROPERTY in current buffer.
15835 Return value is a string. Return nil if property is not set
15836 globally. Also return nil when PROPERTY is set to \"nil\",
15837 unless LITERAL-NIL is non-nil."
15838 (let ((global
15839 (cdr (or (assoc-string property org-file-properties t)
15840 (assoc-string property org-global-properties t)
15841 (assoc-string property org-global-properties-fixed t)))))
15842 (if literal-nil global (org-not-nil global))))
15844 (defun org-entry-get (pom property &optional inherit literal-nil)
15845 "Get value of PROPERTY for entry or content at point-or-marker POM.
15847 If INHERIT is non-nil and the entry does not have the property,
15848 then also check higher levels of the hierarchy. If INHERIT is
15849 the symbol `selective', use inheritance only if the setting in
15850 `org-use-property-inheritance' selects PROPERTY for inheritance.
15852 If the property is present but empty, the return value is the
15853 empty string. If the property is not present at all, nil is
15854 returned. In any other case, return the value as a string.
15855 Search is case-insensitive.
15857 If LITERAL-NIL is set, return the string value \"nil\" as
15858 a string, do not interpret it as the list atom nil. This is used
15859 for inheritance when a \"nil\" value can supersede a non-nil
15860 value higher up the hierarchy."
15861 (org-with-point-at pom
15862 (cond
15863 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15864 ;; We need a special property. Use `org-entry-properties' to
15865 ;; retrieve it, but specify the wanted property.
15866 (cdr (assoc-string property (org-entry-properties nil property))))
15867 ((and inherit
15868 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15869 (org-entry-get-with-inheritance property literal-nil))
15871 (let* ((local (org--property-local-values property literal-nil))
15872 (value (and local (mapconcat #'identity (delq nil local) " "))))
15873 (if literal-nil value (org-not-nil value)))))))
15875 (defun org-property-or-variable-value (var &optional inherit)
15876 "Check if there is a property fixing the value of VAR.
15877 If yes, return this value. If not, return the current value of the variable."
15878 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15879 (if (and prop (stringp prop) (string-match "\\S-" prop))
15880 (read prop)
15881 (symbol-value var))))
15883 (defun org-entry-delete (pom property)
15884 "Delete PROPERTY from entry at point-or-marker POM.
15885 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15886 non-nil when a property was removed."
15887 (org-with-point-at pom
15888 (pcase (org-get-property-block)
15889 (`(,begin . ,origin)
15890 (let* ((end (copy-marker origin))
15891 (re (org-re-property
15892 (concat (regexp-quote property) "\\+?") t t)))
15893 (goto-char begin)
15894 (while (re-search-forward re end t)
15895 (delete-region (match-beginning 0) (line-beginning-position 2)))
15896 ;; If drawer is empty, remove it altogether.
15897 (when (= begin end)
15898 (delete-region (line-beginning-position 0)
15899 (line-beginning-position 2)))
15900 ;; Return non-nil if some property was removed.
15901 (prog1 (/= end origin) (set-marker end nil))))
15902 (_ nil))))
15904 ;; Multi-values properties are properties that contain multiple values
15905 ;; These values are assumed to be single words, separated by whitespace.
15906 (defun org-entry-add-to-multivalued-property (pom property value)
15907 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15908 (let* ((old (org-entry-get pom property))
15909 (values (and old (org-split-string old "[ \t]"))))
15910 (setq value (org-entry-protect-space value))
15911 (unless (member value values)
15912 (setq values (append values (list value)))
15913 (org-entry-put pom property
15914 (mapconcat 'identity values " ")))))
15916 (defun org-entry-remove-from-multivalued-property (pom property value)
15917 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15918 (let* ((old (org-entry-get pom property))
15919 (values (and old (org-split-string old "[ \t]"))))
15920 (setq value (org-entry-protect-space value))
15921 (when (member value values)
15922 (setq values (delete value values))
15923 (org-entry-put pom property
15924 (mapconcat 'identity values " ")))))
15926 (defun org-entry-member-in-multivalued-property (pom property value)
15927 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15928 (let* ((old (org-entry-get pom property))
15929 (values (and old (org-split-string old "[ \t]"))))
15930 (setq value (org-entry-protect-space value))
15931 (member value values)))
15933 (defun org-entry-get-multivalued-property (pom property)
15934 "Return a list of values in a multivalued property."
15935 (let* ((value (org-entry-get pom property))
15936 (values (and value (org-split-string value "[ \t]"))))
15937 (mapcar 'org-entry-restore-space values)))
15939 (defun org-entry-put-multivalued-property (pom property &rest values)
15940 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15941 VALUES should be a list of strings. Spaces will be protected."
15942 (org-entry-put pom property
15943 (mapconcat 'org-entry-protect-space values " "))
15944 (let* ((value (org-entry-get pom property))
15945 (values (and value (org-split-string value "[ \t]"))))
15946 (mapcar 'org-entry-restore-space values)))
15948 (defun org-entry-protect-space (s)
15949 "Protect spaces and newline in string S."
15950 (while (string-match " " s)
15951 (setq s (replace-match "%20" t t s)))
15952 (while (string-match "\n" s)
15953 (setq s (replace-match "%0A" t t s)))
15956 (defun org-entry-restore-space (s)
15957 "Restore spaces and newline in string S."
15958 (while (string-match "%20" s)
15959 (setq s (replace-match " " t t s)))
15960 (while (string-match "%0A" s)
15961 (setq s (replace-match "\n" t t s)))
15964 (defvar org-entry-property-inherited-from (make-marker)
15965 "Marker pointing to the entry from where a property was inherited.
15966 Each call to `org-entry-get-with-inheritance' will set this marker to the
15967 location of the entry where the inheritance search matched. If there was
15968 no match, the marker will point nowhere.
15969 Note that also `org-entry-get' calls this function, if the INHERIT flag
15970 is set.")
15972 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15973 "Get PROPERTY of entry or content at point, search higher levels if needed.
15974 The search will stop at the first ancestor which has the property defined.
15975 If the value found is \"nil\", return nil to show that the property
15976 should be considered as undefined (this is the meaning of nil here).
15977 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15978 (move-marker org-entry-property-inherited-from nil)
15979 (org-with-wide-buffer
15980 (let (value)
15981 (catch 'exit
15982 (while t
15983 (let ((v (org--property-local-values property literal-nil)))
15984 (when v
15985 (setq value
15986 (concat (mapconcat #'identity (delq nil v) " ")
15987 (and value " ")
15988 value)))
15989 (cond
15990 ((car v)
15991 (org-back-to-heading t)
15992 (move-marker org-entry-property-inherited-from (point))
15993 (throw 'exit nil))
15994 ((org-up-heading-safe))
15996 (let ((global (org--property-global-value property literal-nil)))
15997 (cond ((not global))
15998 (value (setq value (concat global " " value)))
15999 (t (setq value global))))
16000 (throw 'exit nil))))))
16001 (if literal-nil value (org-not-nil value)))))
16003 (defvar org-property-changed-functions nil
16004 "Hook called when the value of a property has changed.
16005 Each hook function should accept two arguments, the name of the property
16006 and the new value.")
16008 (defun org-entry-put (pom property value)
16009 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16011 If the value is nil, it is converted to the empty string. If it
16012 is not a string, an error is raised. Also raise an error on
16013 invalid property names.
16015 PROPERTY can be any regular property (see
16016 `org-special-properties'). It can also be \"TODO\",
16017 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16019 For the last two properties, VALUE may have any of the special
16020 values \"earlier\" and \"later\". The function then increases or
16021 decreases scheduled or deadline date by one day."
16022 (cond ((null value) (setq value ""))
16023 ((not (stringp value)) (error "Properties values should be strings"))
16024 ((not (org--valid-property-p property))
16025 (user-error "Invalid property name: \"%s\"" property)))
16026 (org-with-point-at pom
16027 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16028 (org-back-to-heading t)
16029 (org-with-limited-levels (org-back-to-heading t)))
16030 (let ((beg (point)))
16031 (cond
16032 ((equal property "TODO")
16033 (cond ((not (org-string-nw-p value)) (setq value 'none))
16034 ((not (member value org-todo-keywords-1))
16035 (user-error "\"%s\" is not a valid TODO state" value)))
16036 (org-todo value)
16037 (org-set-tags nil 'align))
16038 ((equal property "PRIORITY")
16039 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16040 (org-set-tags nil 'align))
16041 ((equal property "SCHEDULED")
16042 (forward-line)
16043 (if (and (looking-at-p org-planning-line-re)
16044 (re-search-forward
16045 org-scheduled-time-regexp (line-end-position) t))
16046 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16047 ((string= value "later") (org-timestamp-change 1 'day))
16048 ((string= value "") (org-schedule '(4)))
16049 (t (org-schedule nil value)))
16050 (if (member value '("earlier" "later" ""))
16051 (call-interactively #'org-schedule)
16052 (org-schedule nil value))))
16053 ((equal property "DEADLINE")
16054 (forward-line)
16055 (if (and (looking-at-p org-planning-line-re)
16056 (re-search-forward
16057 org-deadline-time-regexp (line-end-position) t))
16058 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16059 ((string= value "later") (org-timestamp-change 1 'day))
16060 ((string= value "") (org-deadline '(4)))
16061 (t (org-deadline nil value)))
16062 (if (member value '("earlier" "later" ""))
16063 (call-interactively #'org-deadline)
16064 (org-deadline nil value))))
16065 ((member property org-special-properties)
16066 (error "The %s property cannot be set with `org-entry-put'" property))
16068 (let* ((range (org-get-property-block beg 'force))
16069 (end (cdr range))
16070 (case-fold-search t))
16071 (goto-char (car range))
16072 (if (re-search-forward (org-re-property property nil t) end t)
16073 (progn (delete-region (match-beginning 0) (match-end 0))
16074 (goto-char (match-beginning 0)))
16075 (goto-char end)
16076 (insert "\n")
16077 (backward-char))
16078 (insert ":" property ":")
16079 (when value (insert " " value))
16080 (org-indent-line)))))
16081 (run-hook-with-args 'org-property-changed-functions property value)))
16083 (defun org-buffer-property-keys
16084 (&optional specials defaults columns ignore-malformed)
16085 "Get all property keys in the current buffer.
16087 When SPECIALS is non-nil, also list the special properties that
16088 reflect things like tags and TODO state.
16090 When DEFAULTS is non-nil, also include properties that has
16091 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16092 DESCRIPTION, LOCATION, and LOGGING and others.
16094 When COLUMNS in non-nil, also include property names given in
16095 COLUMN formats in the current buffer.
16097 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16098 automatically performed, such drawers will be silently ignored."
16099 (let ((case-fold-search t)
16100 (props (append
16101 (and specials org-special-properties)
16102 (and defaults (cons org-effort-property org-default-properties))
16103 nil)))
16104 (org-with-wide-buffer
16105 (goto-char (point-min))
16106 (while (re-search-forward org-property-start-re nil t)
16107 (let ((range (org-get-property-block)))
16108 (catch 'skip
16109 (unless range
16110 (when (and (not ignore-malformed)
16111 (not (org-before-first-heading-p))
16112 (y-or-n-p (format "Malformed drawer at %d, repair?"
16113 (line-beginning-position))))
16114 (org-get-property-block nil t))
16115 (throw 'skip nil))
16116 (goto-char (car range))
16117 (let ((begin (car range))
16118 (end (cdr range)))
16119 ;; Make sure that found property block is not located
16120 ;; before current point, as it would generate an infloop.
16121 ;; It can happen, for example, in the following
16122 ;; situation:
16124 ;; * Headline
16125 ;; :PROPERTIES:
16126 ;; ...
16127 ;; :END:
16128 ;; *************** Inlinetask
16129 ;; #+BEGIN_EXAMPLE
16130 ;; :PROPERTIES:
16131 ;; #+END_EXAMPLE
16133 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16134 (while (< (point) end)
16135 (let ((p (progn (looking-at org-property-re)
16136 (match-string-no-properties 2))))
16137 ;; Only add true property name, not extension symbol.
16138 (push (if (not (string-match-p "\\+\\'" p)) p
16139 (substring p 0 -1))
16140 props))
16141 (forward-line))))
16142 (outline-next-heading)))
16143 (when columns
16144 (goto-char (point-min))
16145 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16146 (let ((element (org-element-at-point)))
16147 (when (memq (org-element-type element) '(keyword node-property))
16148 (let ((value (org-element-property :value element))
16149 (start 0))
16150 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16151 (setq start (match-end 0))
16152 (let ((p (match-string-no-properties 1 value)))
16153 (unless (member-ignore-case p org-special-properties)
16154 (push p props))))))))))
16155 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16157 (defun org-property-values (key)
16158 "List all non-nil values of property KEY in current buffer."
16159 (org-with-wide-buffer
16160 (goto-char (point-min))
16161 (let ((case-fold-search t)
16162 (re (org-re-property key))
16163 values)
16164 (while (re-search-forward re nil t)
16165 (push (org-entry-get (point) key) values))
16166 (delete-dups values))))
16168 (defun org-insert-property-drawer ()
16169 "Insert a property drawer into the current entry."
16170 (org-with-wide-buffer
16171 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16172 (org-back-to-heading t)
16173 (org-with-limited-levels (org-back-to-heading t)))
16174 (forward-line)
16175 (when (looking-at-p org-planning-line-re) (forward-line))
16176 (unless (looking-at-p org-property-drawer-re)
16177 ;; Make sure we start editing a line from current entry, not from
16178 ;; next one. It prevents extending text properties or overlays
16179 ;; belonging to the latter.
16180 (when (bolp) (backward-char))
16181 (let ((begin (1+ (point)))
16182 (inhibit-read-only t))
16183 (insert "\n:PROPERTIES:\n:END:")
16184 (when (eobp) (insert "\n"))
16185 (org-indent-region begin (point))))))
16187 (defun org-insert-drawer (&optional arg drawer)
16188 "Insert a drawer at point.
16190 When optional argument ARG is non-nil, insert a property drawer.
16192 Optional argument DRAWER, when non-nil, is a string representing
16193 drawer's name. Otherwise, the user is prompted for a name.
16195 If a region is active, insert the drawer around that region
16196 instead.
16198 Point is left between drawer's boundaries."
16199 (interactive "P")
16200 (let* ((drawer (if arg "PROPERTIES"
16201 (or drawer (read-from-minibuffer "Drawer: ")))))
16202 (cond
16203 ;; With C-u, fall back on `org-insert-property-drawer'
16204 (arg (org-insert-property-drawer))
16205 ;; Check validity of suggested drawer's name.
16206 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16207 (user-error "Invalid drawer name"))
16208 ;; With an active region, insert a drawer at point.
16209 ((not (org-region-active-p))
16210 (progn
16211 (unless (bolp) (insert "\n"))
16212 (insert (format ":%s:\n\n:END:\n" drawer))
16213 (forward-line -2)))
16214 ;; Otherwise, insert the drawer at point
16216 (let ((rbeg (region-beginning))
16217 (rend (copy-marker (region-end))))
16218 (unwind-protect
16219 (progn
16220 (goto-char rbeg)
16221 (beginning-of-line)
16222 (when (save-excursion
16223 (re-search-forward org-outline-regexp-bol rend t))
16224 (user-error "Drawers cannot contain headlines"))
16225 ;; Position point at the beginning of the first
16226 ;; non-blank line in region. Insert drawer's opening
16227 ;; there, then indent it.
16228 (org-skip-whitespace)
16229 (beginning-of-line)
16230 (insert ":" drawer ":\n")
16231 (forward-line -1)
16232 (indent-for-tab-command)
16233 ;; Move point to the beginning of the first blank line
16234 ;; after the last non-blank line in region. Insert
16235 ;; drawer's closing, then indent it.
16236 (goto-char rend)
16237 (skip-chars-backward " \r\t\n")
16238 (insert "\n:END:")
16239 (deactivate-mark t)
16240 (indent-for-tab-command)
16241 (unless (eolp) (insert "\n")))
16242 ;; Clear marker, whatever the outcome of insertion is.
16243 (set-marker rend nil)))))))
16245 (defvar org-property-set-functions-alist nil
16246 "Property set function alist.
16247 Each entry should have the following format:
16249 (PROPERTY . READ-FUNCTION)
16251 The read function will be called with the same argument as
16252 `org-completing-read'.")
16254 (defun org-set-property-function (property)
16255 "Get the function that should be used to set PROPERTY.
16256 This is computed according to `org-property-set-functions-alist'."
16257 (or (cdr (assoc property org-property-set-functions-alist))
16258 'org-completing-read))
16260 (defun org-read-property-value (property)
16261 "Read PROPERTY value from user."
16262 (let* ((completion-ignore-case t)
16263 (allowed (org-property-get-allowed-values nil property 'table))
16264 (cur (org-entry-get nil property))
16265 (prompt (concat property " value"
16266 (if (and cur (string-match "\\S-" cur))
16267 (concat " [" cur "]") "") ": "))
16268 (set-function (org-set-property-function property))
16269 (val (if allowed
16270 (funcall set-function prompt allowed nil
16271 (not (get-text-property 0 'org-unrestricted
16272 (caar allowed))))
16273 (funcall set-function prompt
16274 (mapcar 'list (org-property-values property))
16275 nil nil "" nil cur))))
16276 (org-trim val)))
16278 (defvar org-last-set-property nil)
16279 (defvar org-last-set-property-value nil)
16280 (defun org-read-property-name ()
16281 "Read a property name."
16282 (let ((completion-ignore-case t)
16283 (default-prop (or (and (org-at-property-p)
16284 (match-string-no-properties 2))
16285 org-last-set-property)))
16286 (org-completing-read
16287 (concat "Property"
16288 (if default-prop (concat " [" default-prop "]") "")
16289 ": ")
16290 (mapcar #'list (org-buffer-property-keys nil t t))
16291 nil nil nil nil default-prop)))
16293 (defun org-set-property-and-value (use-last)
16294 "Allow to set [PROPERTY]: [value] direction from prompt.
16295 When use-default, don't even ask, just use the last
16296 \"[PROPERTY]: [value]\" string from the history."
16297 (interactive "P")
16298 (let* ((completion-ignore-case t)
16299 (pv (or (and use-last org-last-set-property-value)
16300 (org-completing-read
16301 "Enter a \"[Property]: [value]\" pair: "
16302 nil nil nil nil nil
16303 org-last-set-property-value)))
16304 prop val)
16305 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16306 (setq prop (match-string 1 pv)
16307 val (match-string 2 pv))
16308 (org-set-property prop val))))
16310 (defun org-set-property (property value)
16311 "In the current entry, set PROPERTY to VALUE.
16313 When called interactively, this will prompt for a property name, offering
16314 completion on existing and default properties. And then it will prompt
16315 for a value, offering completion either on allowed values (via an inherited
16316 xxx_ALL property) or on existing values in other instances of this property
16317 in the current file.
16319 Throw an error when trying to set a property with an invalid name."
16320 (interactive (list nil nil))
16321 (let ((property (or property (org-read-property-name))))
16322 ;; `org-entry-put' also makes the following check, but this one
16323 ;; avoids polluting `org-last-set-property' and
16324 ;; `org-last-set-property-value' needlessly.
16325 (unless (org--valid-property-p property)
16326 (user-error "Invalid property name: \"%s\"" property))
16327 (let ((value (or value (org-read-property-value property)))
16328 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16329 (setq org-last-set-property property)
16330 (setq org-last-set-property-value (concat property ": " value))
16331 ;; Possibly postprocess the inserted value:
16332 (when fn (setq value (funcall fn value)))
16333 (unless (equal (org-entry-get nil property) value)
16334 (org-entry-put nil property value)))))
16336 (defun org-find-property (property &optional value)
16337 "Find first entry in buffer that sets PROPERTY.
16339 When optional argument VALUE is non-nil, only consider an entry
16340 if it contains PROPERTY set to this value. If PROPERTY should be
16341 explicitly set to nil, use string \"nil\" for VALUE.
16343 Return position where the entry begins, or nil if there is no
16344 such entry. If narrowing is in effect, only search the visible
16345 part of the buffer."
16346 (save-excursion
16347 (goto-char (point-min))
16348 (let ((case-fold-search t)
16349 (re (org-re-property property nil (not value) value)))
16350 (catch 'exit
16351 (while (re-search-forward re nil t)
16352 (when (if value (org-at-property-p)
16353 (org-entry-get (point) property nil t))
16354 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16356 (defun org-delete-property (property)
16357 "In the current entry, delete PROPERTY."
16358 (interactive
16359 (let* ((completion-ignore-case t)
16360 (cat (org-entry-get (point) "CATEGORY"))
16361 (props0 (org-entry-properties nil 'standard))
16362 (props (if cat props0
16363 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16364 (prop (if (< 1 (length props))
16365 (completing-read "Property: " props nil t)
16366 (caar props))))
16367 (list prop)))
16368 (if (not property)
16369 (message "No property to delete in this entry")
16370 (org-entry-delete nil property)
16371 (message "Property \"%s\" deleted" property)))
16373 (defun org-delete-property-globally (property)
16374 "Remove PROPERTY globally, from all entries.
16375 This function ignores narrowing, if any."
16376 (interactive
16377 (let* ((completion-ignore-case t)
16378 (prop (completing-read
16379 "Globally remove property: "
16380 (mapcar #'list (org-buffer-property-keys)))))
16381 (list prop)))
16382 (org-with-wide-buffer
16383 (goto-char (point-min))
16384 (let ((count 0)
16385 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16386 (while (re-search-forward re nil t)
16387 (when (org-entry-delete (point) property) (cl-incf count)))
16388 (message "Property \"%s\" removed from %d entries" property count))))
16390 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16392 (defun org-compute-property-at-point ()
16393 "Compute the property at point.
16394 This looks for an enclosing column format, extracts the operator and
16395 then applies it to the property in the column format's scope."
16396 (interactive)
16397 (unless (org-at-property-p)
16398 (user-error "Not at a property"))
16399 (let ((prop (match-string-no-properties 2)))
16400 (org-columns-get-format-and-top-level)
16401 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16402 (user-error "No operator defined for property %s" prop))
16403 (org-columns-compute prop)))
16405 (defvar org-property-allowed-value-functions nil
16406 "Hook for functions supplying allowed values for a specific property.
16407 The functions must take a single argument, the name of the property, and
16408 return a flat list of allowed values. If \":ETC\" is one of
16409 the values, this means that these values are intended as defaults for
16410 completion, but that other values should be allowed too.
16411 The functions must return nil if they are not responsible for this
16412 property.")
16414 (defun org-property-get-allowed-values (pom property &optional table)
16415 "Get allowed values for the property PROPERTY.
16416 When TABLE is non-nil, return an alist that can directly be used for
16417 completion."
16418 (let (vals)
16419 (cond
16420 ((equal property "TODO")
16421 (setq vals (org-with-point-at pom
16422 (append org-todo-keywords-1 '("")))))
16423 ((equal property "PRIORITY")
16424 (let ((n org-lowest-priority))
16425 (while (>= n org-highest-priority)
16426 (push (char-to-string n) vals)
16427 (setq n (1- n)))))
16428 ((equal property "CATEGORY"))
16429 ((member property org-special-properties))
16430 ((setq vals (run-hook-with-args-until-success
16431 'org-property-allowed-value-functions property)))
16433 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16434 (when (and vals (string-match "\\S-" vals))
16435 (setq vals (car (read-from-string (concat "(" vals ")"))))
16436 (setq vals (mapcar (lambda (x)
16437 (cond ((stringp x) x)
16438 ((numberp x) (number-to-string x))
16439 ((symbolp x) (symbol-name x))
16440 (t "???")))
16441 vals)))))
16442 (when (member ":ETC" vals)
16443 (setq vals (remove ":ETC" vals))
16444 (org-add-props (car vals) '(org-unrestricted t)))
16445 (if table (mapcar 'list vals) vals)))
16447 (defun org-property-previous-allowed-value (&optional _previous)
16448 "Switch to the next allowed value for this property."
16449 (interactive)
16450 (org-property-next-allowed-value t))
16452 (defun org-property-next-allowed-value (&optional previous)
16453 "Switch to the next allowed value for this property."
16454 (interactive)
16455 (unless (org-at-property-p)
16456 (user-error "Not at a property"))
16457 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16458 (key (match-string 2))
16459 (value (match-string 3))
16460 (allowed (or (org-property-get-allowed-values (point) key)
16461 (and (member value '("[ ]" "[-]" "[X]"))
16462 '("[ ]" "[X]"))))
16463 (heading (save-match-data (nth 4 (org-heading-components))))
16464 nval)
16465 (unless allowed
16466 (user-error "Allowed values for this property have not been defined"))
16467 (when previous (setq allowed (reverse allowed)))
16468 (when (member value allowed)
16469 (setq nval (car (cdr (member value allowed)))))
16470 (setq nval (or nval (car allowed)))
16471 (when (equal nval value)
16472 (user-error "Only one allowed value for this property"))
16473 (org-at-property-p)
16474 (replace-match (concat " :" key ": " nval) t t)
16475 (org-indent-line)
16476 (beginning-of-line 1)
16477 (skip-chars-forward " \t")
16478 (when (equal prop org-effort-property)
16479 (org-refresh-property
16480 '((effort . identity)
16481 (effort-minutes . org-duration-to-minutes))
16482 nval)
16483 (when (string= org-clock-current-task heading)
16484 (setq org-clock-effort nval)
16485 (org-clock-update-mode-line)))
16486 (run-hook-with-args 'org-property-changed-functions key nval)))
16488 (defun org-find-olp (path &optional this-buffer)
16489 "Return a marker pointing to the entry at outline path OLP.
16490 If anything goes wrong, throw an error.
16491 You can wrap this call to catch the error like this:
16493 (condition-case msg
16494 (org-mobile-locate-entry (match-string 4))
16495 (error (nth 1 msg)))
16497 The return value will then be either a string with the error message,
16498 or a marker if everything is OK.
16500 If THIS-BUFFER is set, the outline path does not contain a file,
16501 only headings."
16502 (let* ((file (if this-buffer buffer-file-name (pop path)))
16503 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16504 (level 1)
16505 (lmin 1)
16506 (lmax 1)
16507 end found flevel)
16508 (unless buffer (error "File not found :%s" file))
16509 (with-current-buffer buffer
16510 (org-with-wide-buffer
16511 (goto-char (point-min))
16512 (dolist (heading path)
16513 (let ((re (format org-complex-heading-regexp-format
16514 (regexp-quote heading)))
16515 (cnt 0))
16516 (while (re-search-forward re end t)
16517 (setq level (- (match-end 1) (match-beginning 1)))
16518 (when (and (>= level lmin) (<= level lmax))
16519 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16520 (when (= cnt 0)
16521 (error "Heading not found on level %d: %s" lmax heading))
16522 (when (> cnt 1)
16523 (error "Heading not unique on level %d: %s" lmax heading))
16524 (goto-char found)
16525 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16526 (setq end (save-excursion (org-end-of-subtree t t)))))
16527 (when (org-at-heading-p)
16528 (point-marker))))))
16530 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16531 "Find node HEADING in BUFFER.
16532 Return a marker to the heading if it was found, or nil if not.
16533 If POS-ONLY is set, return just the position instead of a marker.
16535 The heading text must match exact, but it may have a TODO keyword,
16536 a priority cookie and tags in the standard locations."
16537 (with-current-buffer (or buffer (current-buffer))
16538 (org-with-wide-buffer
16539 (goto-char (point-min))
16540 (let (case-fold-search)
16541 (when (re-search-forward
16542 (format org-complex-heading-regexp-format
16543 (regexp-quote heading)) nil t)
16544 (if pos-only
16545 (match-beginning 0)
16546 (move-marker (make-marker) (match-beginning 0))))))))
16548 (defun org-find-exact-heading-in-directory (heading &optional dir)
16549 "Find Org node headline HEADING in all .org files in directory DIR.
16550 When the target headline is found, return a marker to this location."
16551 (let ((files (directory-files (or dir default-directory)
16552 t "\\`[^.#].*\\.org\\'"))
16553 visiting m buffer)
16554 (catch 'found
16555 (dolist (file files)
16556 (message "trying %s" file)
16557 (setq visiting (org-find-base-buffer-visiting file))
16558 (setq buffer (or visiting (find-file-noselect file)))
16559 (setq m (org-find-exact-headline-in-buffer
16560 heading buffer))
16561 (when (and (not m) (not visiting)) (kill-buffer buffer))
16562 (and m (throw 'found m))))))
16564 (defun org-find-entry-with-id (ident)
16565 "Locate the entry that contains the ID property with exact value IDENT.
16566 IDENT can be a string, a symbol or a number, this function will search for
16567 the string representation of it.
16568 Return the position where this entry starts, or nil if there is no such entry."
16569 (interactive "sID: ")
16570 (let ((id (cond
16571 ((stringp ident) ident)
16572 ((symbolp ident) (symbol-name ident))
16573 ((numberp ident) (number-to-string ident))
16574 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16575 (org-with-wide-buffer (org-find-property "ID" id))))
16577 ;;;; Timestamps
16579 (defvar org-last-changed-timestamp nil)
16580 (defvar org-last-inserted-timestamp nil
16581 "The last time stamp inserted with `org-insert-time-stamp'.")
16583 (defun org-time-stamp (arg &optional inactive)
16584 "Prompt for a date/time and insert a time stamp.
16586 If the user specifies a time like HH:MM or if this command is
16587 called with at least one prefix argument, the time stamp contains
16588 the date and the time. Otherwise, only the date is included.
16590 All parts of a date not specified by the user are filled in from
16591 the timestamp at point, if any, or the current date/time
16592 otherwise.
16594 If there is already a timestamp at the cursor, it is replaced.
16596 With two universal prefix arguments, insert an active timestamp
16597 with the current time without prompting the user.
16599 When called from lisp, the timestamp is inactive if INACTIVE is
16600 non-nil."
16601 (interactive "P")
16602 (let* ((ts (cond
16603 ((org-at-date-range-p t)
16604 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16605 ((org-at-timestamp-p t) (match-string 0))))
16606 ;; Default time is either the timestamp at point or today.
16607 ;; When entering a range, only the range start is considered.
16608 (default-time (if (not ts) (current-time)
16609 (apply #'encode-time (org-parse-time-string ts))))
16610 (default-input (and ts (org-get-compact-tod ts)))
16611 (repeater (and ts
16612 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16613 (match-string 0 ts)))
16614 org-time-was-given
16615 org-end-time-was-given
16616 (time
16617 (and (if (equal arg '(16)) (current-time)
16618 ;; Preserve `this-command' and `last-command'.
16619 (let ((this-command this-command)
16620 (last-command last-command))
16621 (org-read-date
16622 arg 'totime nil nil default-time default-input
16623 inactive))))))
16624 (cond
16625 ((and ts
16626 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16627 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16628 (insert "--")
16629 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16631 ;; Make sure we're on a timestamp. When in the middle of a date
16632 ;; range, move arbitrarily to range end.
16633 (unless (org-at-timestamp-p t)
16634 (skip-chars-forward "-")
16635 (org-at-timestamp-p t))
16636 (replace-match "")
16637 (setq org-last-changed-timestamp
16638 (org-insert-time-stamp
16639 time (or org-time-was-given arg)
16640 inactive nil nil (list org-end-time-was-given)))
16641 (when repeater
16642 (backward-char)
16643 (insert " " repeater)
16644 (setq org-last-changed-timestamp
16645 (concat (substring org-last-inserted-timestamp 0 -1)
16646 " " repeater ">")))
16647 (message "Timestamp updated"))
16648 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16649 (t (org-insert-time-stamp
16650 time (or org-time-was-given arg) inactive nil nil
16651 (list org-end-time-was-given))))))
16653 ;; FIXME: can we use this for something else, like computing time differences?
16654 (defun org-get-compact-tod (s)
16655 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16656 (let* ((t1 (match-string 1 s))
16657 (h1 (string-to-number (match-string 2 s)))
16658 (m1 (string-to-number (match-string 3 s)))
16659 (t2 (and (match-end 4) (match-string 5 s)))
16660 (h2 (and t2 (string-to-number (match-string 6 s))))
16661 (m2 (and t2 (string-to-number (match-string 7 s))))
16662 dh dm)
16663 (if (not t2)
16665 (setq dh (- h2 h1) dm (- m2 m1))
16666 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16667 (concat t1 "+" (number-to-string dh)
16668 (and (/= 0 dm) (format ":%02d" dm)))))))
16670 (defun org-time-stamp-inactive (&optional arg)
16671 "Insert an inactive time stamp.
16672 An inactive time stamp is enclosed in square brackets instead of angle
16673 brackets. It is inactive in the sense that it does not trigger agenda entries,
16674 does not link to the calendar and cannot be changed with the S-cursor keys.
16675 So these are more for recording a certain time/date."
16676 (interactive "P")
16677 (org-time-stamp arg 'inactive))
16679 (defvar org-date-ovl (make-overlay 1 1))
16680 (overlay-put org-date-ovl 'face 'org-date-selected)
16681 (delete-overlay org-date-ovl)
16683 (defvar org-ans1) ; dynamically scoped parameter
16684 (defvar org-ans2) ; dynamically scoped parameter
16686 (defvar org-plain-time-of-day-regexp) ; defined below
16688 (defvar org-overriding-default-time nil) ; dynamically scoped
16689 (defvar org-read-date-overlay nil)
16690 (defvar org-dcst nil) ; dynamically scoped
16691 (defvar org-read-date-history nil)
16692 (defvar org-read-date-final-answer nil)
16693 (defvar org-read-date-analyze-futurep nil)
16694 (defvar org-read-date-analyze-forced-year nil)
16695 (defvar org-read-date-inactive)
16697 (defvar org-read-date-minibuffer-local-map
16698 (let* ((map (make-sparse-keymap)))
16699 (set-keymap-parent map minibuffer-local-map)
16700 (org-defkey map (kbd ".")
16701 (lambda () (interactive)
16702 ;; Are we at the beginning of the prompt?
16703 (if (looking-back "^[^:]+: "
16704 (let ((inhibit-field-text-motion t))
16705 (line-beginning-position)))
16706 (org-eval-in-calendar '(calendar-goto-today))
16707 (insert "."))))
16708 (org-defkey map (kbd "C-.")
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(calendar-goto-today))))
16711 (org-defkey map [(meta shift left)]
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(calendar-backward-month 1))))
16714 (org-defkey map [(meta shift right)]
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-forward-month 1))))
16717 (org-defkey map [(meta shift up)]
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(calendar-backward-year 1))))
16720 (org-defkey map [(meta shift down)]
16721 (lambda () (interactive)
16722 (org-eval-in-calendar '(calendar-forward-year 1))))
16723 (org-defkey map [?\e (shift left)]
16724 (lambda () (interactive)
16725 (org-eval-in-calendar '(calendar-backward-month 1))))
16726 (org-defkey map [?\e (shift right)]
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-forward-month 1))))
16729 (org-defkey map [?\e (shift up)]
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(calendar-backward-year 1))))
16732 (org-defkey map [?\e (shift down)]
16733 (lambda () (interactive)
16734 (org-eval-in-calendar '(calendar-forward-year 1))))
16735 (org-defkey map [(shift up)]
16736 (lambda () (interactive)
16737 (org-eval-in-calendar '(calendar-backward-week 1))))
16738 (org-defkey map [(shift down)]
16739 (lambda () (interactive)
16740 (org-eval-in-calendar '(calendar-forward-week 1))))
16741 (org-defkey map [(shift left)]
16742 (lambda () (interactive)
16743 (org-eval-in-calendar '(calendar-backward-day 1))))
16744 (org-defkey map [(shift right)]
16745 (lambda () (interactive)
16746 (org-eval-in-calendar '(calendar-forward-day 1))))
16747 (org-defkey map "!"
16748 (lambda () (interactive)
16749 (org-eval-in-calendar '(diary-view-entries))
16750 (message "")))
16751 (org-defkey map ">"
16752 (lambda () (interactive)
16753 (org-eval-in-calendar '(calendar-scroll-left 1))))
16754 (org-defkey map "<"
16755 (lambda () (interactive)
16756 (org-eval-in-calendar '(calendar-scroll-right 1))))
16757 (org-defkey map "\C-v"
16758 (lambda () (interactive)
16759 (org-eval-in-calendar
16760 '(calendar-scroll-left-three-months 1))))
16761 (org-defkey map "\M-v"
16762 (lambda () (interactive)
16763 (org-eval-in-calendar
16764 '(calendar-scroll-right-three-months 1))))
16765 map)
16766 "Keymap for minibuffer commands when using `org-read-date'.")
16768 (defvar org-def)
16769 (defvar org-defdecode)
16770 (defvar org-with-time)
16772 (defvar calendar-setup) ; Dynamically scoped.
16773 (defun org-read-date (&optional with-time to-time from-string prompt
16774 default-time default-input inactive)
16775 "Read a date, possibly a time, and make things smooth for the user.
16776 The prompt will suggest to enter an ISO date, but you can also enter anything
16777 which will at least partially be understood by `parse-time-string'.
16778 Unrecognized parts of the date will default to the current day, month, year,
16779 hour and minute. If this command is called to replace a timestamp at point,
16780 or to enter the second timestamp of a range, the default time is taken
16781 from the existing stamp. Furthermore, the command prefers the future,
16782 so if you are giving a date where the year is not given, and the day-month
16783 combination is already past in the current year, it will assume you
16784 mean next year. For details, see the manual. A few examples:
16786 3-2-5 --> 2003-02-05
16787 feb 15 --> currentyear-02-15
16788 2/15 --> currentyear-02-15
16789 sep 12 9 --> 2009-09-12
16790 12:45 --> today 12:45
16791 22 sept 0:34 --> currentyear-09-22 0:34
16792 12 --> currentyear-currentmonth-12
16793 Fri --> nearest Friday after today
16794 -Tue --> last Tuesday
16795 etc.
16797 Furthermore you can specify a relative date by giving, as the *first* thing
16798 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16799 change in days weeks, months, years.
16800 With a single plus or minus, the date is relative to today. With a double
16801 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16802 +4d --> four days from today
16803 +4 --> same as above
16804 +2w --> two weeks from today
16805 ++5 --> five days from default date
16807 The function understands only English month and weekday abbreviations.
16809 While prompting, a calendar is popped up - you can also select the
16810 date with the mouse (button 1). The calendar shows a period of three
16811 months. To scroll it to other months, use the keys `>' and `<'.
16812 If you don't like the calendar, turn it off with
16813 (setq org-read-date-popup-calendar nil)
16815 With optional argument TO-TIME, the date will immediately be converted
16816 to an internal time.
16817 With an optional argument WITH-TIME, the prompt will suggest to
16818 also insert a time. Note that when WITH-TIME is not set, you can
16819 still enter a time, and this function will inform the calling routine
16820 about this change. The calling routine may then choose to change the
16821 format used to insert the time stamp into the buffer to include the time.
16822 With optional argument FROM-STRING, read from this string instead from
16823 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16824 the time/date that is used for everything that is not specified by the
16825 user."
16826 (require 'parse-time)
16827 (let* ((org-with-time with-time)
16828 (org-time-stamp-rounding-minutes
16829 (if (equal org-with-time '(16))
16830 '(0 0)
16831 org-time-stamp-rounding-minutes))
16832 (org-dcst org-display-custom-times)
16833 (ct (org-current-time))
16834 (org-def (or org-overriding-default-time default-time ct))
16835 (org-defdecode (decode-time org-def))
16836 (cur-frame (selected-frame))
16837 (mouse-autoselect-window nil) ; Don't let the mouse jump
16838 (calendar-setup
16839 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16840 (calendar-move-hook nil)
16841 (calendar-view-diary-initially-flag nil)
16842 (calendar-view-holidays-initially-flag nil)
16843 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16844 ;; Rationalize `org-def' and `org-defdecode', if required.
16845 (when (< (nth 2 org-defdecode) org-extend-today-until)
16846 (setf (nth 2 org-defdecode) -1)
16847 (setf (nth 1 org-defdecode) 59)
16848 (setq org-def (apply #'encode-time org-defdecode))
16849 (setq org-defdecode (decode-time org-def)))
16850 (let* ((timestr (format-time-string
16851 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16852 org-def))
16853 (prompt (concat (if prompt (concat prompt " ") "")
16854 (format "Date+time [%s]: " timestr))))
16855 (cond
16856 (from-string (setq ans from-string))
16857 (org-read-date-popup-calendar
16858 (save-excursion
16859 (save-window-excursion
16860 (calendar)
16861 (when (eq calendar-setup 'calendar-only)
16862 (setq cal-frame
16863 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16864 (select-frame cal-frame))
16865 (org-eval-in-calendar '(setq cursor-type nil) t)
16866 (unwind-protect
16867 (progn
16868 (calendar-forward-day (- (time-to-days org-def)
16869 (calendar-absolute-from-gregorian
16870 (calendar-current-date))))
16871 (org-eval-in-calendar nil t)
16872 (let* ((old-map (current-local-map))
16873 (map (copy-keymap calendar-mode-map))
16874 (minibuffer-local-map
16875 (copy-keymap org-read-date-minibuffer-local-map)))
16876 (org-defkey map (kbd "RET") 'org-calendar-select)
16877 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16878 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16879 (unwind-protect
16880 (progn
16881 (use-local-map map)
16882 (setq org-read-date-inactive inactive)
16883 (add-hook 'post-command-hook 'org-read-date-display)
16884 (setq org-ans0
16885 (read-string prompt
16886 default-input
16887 'org-read-date-history
16888 nil))
16889 ;; org-ans0: from prompt
16890 ;; org-ans1: from mouse click
16891 ;; org-ans2: from calendar motion
16892 (setq ans
16893 (concat org-ans0 " " (or org-ans1 org-ans2))))
16894 (remove-hook 'post-command-hook 'org-read-date-display)
16895 (use-local-map old-map)
16896 (when org-read-date-overlay
16897 (delete-overlay org-read-date-overlay)
16898 (setq org-read-date-overlay nil)))))
16899 (bury-buffer "*Calendar*")
16900 (when cal-frame
16901 (delete-frame cal-frame)
16902 (select-frame-set-input-focus cur-frame))))))
16904 (t ; Naked prompt only
16905 (unwind-protect
16906 (setq ans (read-string prompt default-input
16907 'org-read-date-history timestr))
16908 (when org-read-date-overlay
16909 (delete-overlay org-read-date-overlay)
16910 (setq org-read-date-overlay nil))))))
16912 (setq final (org-read-date-analyze ans org-def org-defdecode))
16914 (when org-read-date-analyze-forced-year
16915 (message "Year was forced into %s"
16916 (if org-read-date-force-compatible-dates
16917 "compatible range (1970-2037)"
16918 "range representable on this machine"))
16919 (ding))
16921 ;; One round trip to get rid of 34th of August and stuff like that....
16922 (setq final (decode-time (apply 'encode-time final)))
16924 (setq org-read-date-final-answer ans)
16926 (if to-time
16927 (apply 'encode-time final)
16928 (if (and (boundp 'org-time-was-given) org-time-was-given)
16929 (format "%04d-%02d-%02d %02d:%02d"
16930 (nth 5 final) (nth 4 final) (nth 3 final)
16931 (nth 2 final) (nth 1 final))
16932 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16934 (defun org-read-date-display ()
16935 "Display the current date prompt interpretation in the minibuffer."
16936 (when org-read-date-display-live
16937 (when org-read-date-overlay
16938 (delete-overlay org-read-date-overlay))
16939 (when (minibufferp (current-buffer))
16940 (save-excursion
16941 (end-of-line 1)
16942 (while (not (equal (buffer-substring
16943 (max (point-min) (- (point) 4)) (point))
16944 " "))
16945 (insert " ")))
16946 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16947 " " (or org-ans1 org-ans2)))
16948 (org-end-time-was-given nil)
16949 (f (org-read-date-analyze ans org-def org-defdecode))
16950 (fmts (if org-dcst
16951 org-time-stamp-custom-formats
16952 org-time-stamp-formats))
16953 (fmt (if (or org-with-time
16954 (and (boundp 'org-time-was-given) org-time-was-given))
16955 (cdr fmts)
16956 (car fmts)))
16957 (txt (format-time-string fmt (apply 'encode-time f)))
16958 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16959 (txt (concat "=> " txt)))
16960 (when (and org-end-time-was-given
16961 (string-match org-plain-time-of-day-regexp txt))
16962 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16963 org-end-time-was-given
16964 (substring txt (match-end 0)))))
16965 (when org-read-date-analyze-futurep
16966 (setq txt (concat txt " (=>F)")))
16967 (setq org-read-date-overlay
16968 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16969 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16971 (defun org-read-date-analyze (ans def defdecode)
16972 "Analyze the combined answer of the date prompt."
16973 ;; FIXME: cleanup and comment
16974 ;; Pass `current-time' result to `decode-time' (instead of calling
16975 ;; without arguments) so that only `current-time' has to be
16976 ;; overriden in tests.
16977 (let ((org-def def)
16978 (org-defdecode defdecode)
16979 (nowdecode (decode-time (current-time)))
16980 delta deltan deltaw deltadef year month day
16981 hour minute second wday pm h2 m2 tl wday1
16982 iso-year iso-weekday iso-week iso-date futurep kill-year)
16983 (setq org-read-date-analyze-futurep nil
16984 org-read-date-analyze-forced-year nil)
16985 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16986 (setq ans "+0"))
16988 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16989 (setq ans (replace-match "" t t ans)
16990 deltan (car delta)
16991 deltaw (nth 1 delta)
16992 deltadef (nth 2 delta)))
16994 ;; Check if there is an iso week date in there. If yes, store the
16995 ;; info and postpone interpreting it until the rest of the parsing
16996 ;; is done.
16997 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16998 (setq iso-year (when (match-end 1)
16999 (org-small-year-to-year
17000 (string-to-number (match-string 1 ans))))
17001 iso-weekday (when (match-end 3)
17002 (string-to-number (match-string 3 ans)))
17003 iso-week (string-to-number (match-string 2 ans)))
17004 (setq ans (replace-match "" t t ans)))
17006 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17007 (when (string-match
17008 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17009 (setq year (if (match-end 2)
17010 (string-to-number (match-string 2 ans))
17011 (progn (setq kill-year t)
17012 (string-to-number (format-time-string "%Y"))))
17013 month (string-to-number (match-string 3 ans))
17014 day (string-to-number (match-string 4 ans)))
17015 (setq year (org-small-year-to-year year))
17016 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17017 t nil ans)))
17019 ;; Help matching dotted european dates
17020 (when (string-match
17021 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17022 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17023 (setq kill-year t)
17024 (string-to-number (format-time-string "%Y")))
17025 day (string-to-number (match-string 1 ans))
17026 month (string-to-number (match-string 2 ans))
17027 ans (replace-match (format "%04d-%02d-%02d" year month day)
17028 t nil ans)))
17030 ;; Help matching american dates, like 5/30 or 5/30/7
17031 (when (string-match
17032 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17033 (setq year (if (match-end 4)
17034 (string-to-number (match-string 4 ans))
17035 (progn (setq kill-year t)
17036 (string-to-number (format-time-string "%Y"))))
17037 month (string-to-number (match-string 1 ans))
17038 day (string-to-number (match-string 2 ans)))
17039 (setq year (org-small-year-to-year year))
17040 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17041 t nil ans)))
17042 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17043 ;; If there is a time with am/pm, and *no* time without it, we convert
17044 ;; so that matching will be successful.
17045 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17046 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17047 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17048 (setq hour (string-to-number (match-string 1 ans))
17049 minute (if (match-end 3)
17050 (string-to-number (match-string 3 ans))
17052 pm (equal ?p
17053 (string-to-char (downcase (match-string 4 ans)))))
17054 (if (and (= hour 12) (not pm))
17055 (setq hour 0)
17056 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17057 (setq ans (replace-match (format "%02d:%02d" hour minute)
17058 t t ans))))
17060 ;; Check if a time range is given as a duration
17061 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17062 (setq hour (string-to-number (match-string 1 ans))
17063 h2 (+ hour (string-to-number (match-string 3 ans)))
17064 minute (string-to-number (match-string 2 ans))
17065 m2 (+ minute (if (match-end 5) (string-to-number
17066 (match-string 5 ans))0)))
17067 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17068 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17069 t t ans)))
17071 ;; Check if there is a time range
17072 (when (boundp 'org-end-time-was-given)
17073 (setq org-time-was-given nil)
17074 (when (and (string-match org-plain-time-of-day-regexp ans)
17075 (match-end 8))
17076 (setq org-end-time-was-given (match-string 8 ans))
17077 (setq ans (concat (substring ans 0 (match-beginning 7))
17078 (substring ans (match-end 7))))))
17080 (setq tl (parse-time-string ans)
17081 day (or (nth 3 tl) (nth 3 org-defdecode))
17082 month
17083 (cond ((nth 4 tl))
17084 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17085 ;; Day was specified. Make sure DAY+MONTH
17086 ;; combination happens in the future.
17087 ((nth 3 tl)
17088 (setq futurep t)
17089 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17090 (nth 4 nowdecode)))
17091 (t (nth 4 org-defdecode)))
17092 year
17093 (cond ((and (not kill-year) (nth 5 tl)))
17094 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17095 ;; Month was guessed in the future and is at least
17096 ;; equal to NOWDECODE's. Fix year accordingly.
17097 (futurep
17098 (if (or (> month (nth 4 nowdecode))
17099 (>= day (nth 3 nowdecode)))
17100 (nth 5 nowdecode)
17101 (1+ (nth 5 nowdecode))))
17102 ;; Month was specified. Make sure MONTH+YEAR
17103 ;; combination happens in the future.
17104 ((nth 4 tl)
17105 (setq futurep t)
17106 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17107 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17108 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17109 (t (nth 5 nowdecode))))
17110 (t (nth 5 org-defdecode)))
17111 hour (or (nth 2 tl) (nth 2 org-defdecode))
17112 minute (or (nth 1 tl) (nth 1 org-defdecode))
17113 second (or (nth 0 tl) 0)
17114 wday (nth 6 tl))
17116 (when (and (eq org-read-date-prefer-future 'time)
17117 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17118 (equal day (nth 3 nowdecode))
17119 (equal month (nth 4 nowdecode))
17120 (equal year (nth 5 nowdecode))
17121 (nth 2 tl)
17122 (or (< (nth 2 tl) (nth 2 nowdecode))
17123 (and (= (nth 2 tl) (nth 2 nowdecode))
17124 (nth 1 tl)
17125 (< (nth 1 tl) (nth 1 nowdecode)))))
17126 (setq day (1+ day)
17127 futurep t))
17129 ;; Special date definitions below
17130 (cond
17131 (iso-week
17132 ;; There was an iso week
17133 (require 'cal-iso)
17134 (setq futurep nil)
17135 (setq year (or iso-year year)
17136 day (or iso-weekday wday 1)
17137 wday nil ; to make sure that the trigger below does not match
17138 iso-date (calendar-gregorian-from-absolute
17139 (calendar-iso-to-absolute
17140 (list iso-week day year))))
17141 ; FIXME: Should we also push ISO weeks into the future?
17142 ; (when (and org-read-date-prefer-future
17143 ; (not iso-year)
17144 ; (< (calendar-absolute-from-gregorian iso-date)
17145 ; (time-to-days (current-time))))
17146 ; (setq year (1+ year)
17147 ; iso-date (calendar-gregorian-from-absolute
17148 ; (calendar-iso-to-absolute
17149 ; (list iso-week day year)))))
17150 (setq month (car iso-date)
17151 year (nth 2 iso-date)
17152 day (nth 1 iso-date)))
17153 (deltan
17154 (setq futurep nil)
17155 (unless deltadef
17156 ;; Pass `current-time' result to `decode-time' (instead of
17157 ;; calling without arguments) so that only `current-time' has
17158 ;; to be overriden in tests.
17159 (let ((now (decode-time (current-time))))
17160 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17161 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17162 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17163 ((equal deltaw "m") (setq month (+ month deltan)))
17164 ((equal deltaw "y") (setq year (+ year deltan)))))
17165 ((and wday (not (nth 3 tl)))
17166 ;; Weekday was given, but no day, so pick that day in the week
17167 ;; on or after the derived date.
17168 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17169 (unless (equal wday wday1)
17170 (setq day (+ day (% (- wday wday1 -7) 7))))))
17171 (when (and (boundp 'org-time-was-given)
17172 (nth 2 tl))
17173 (setq org-time-was-given t))
17174 (when (< year 100) (setq year (+ 2000 year)))
17175 ;; Check of the date is representable
17176 (if org-read-date-force-compatible-dates
17177 (progn
17178 (when (< year 1970)
17179 (setq year 1970 org-read-date-analyze-forced-year t))
17180 (when (> year 2037)
17181 (setq year 2037 org-read-date-analyze-forced-year t)))
17182 (condition-case nil
17183 (ignore (encode-time second minute hour day month year))
17184 (error
17185 (setq year (nth 5 org-defdecode))
17186 (setq org-read-date-analyze-forced-year t))))
17187 (setq org-read-date-analyze-futurep futurep)
17188 (list second minute hour day month year)))
17190 (defvar parse-time-weekdays)
17191 (defun org-read-date-get-relative (s today default)
17192 "Check string S for special relative date string.
17193 TODAY and DEFAULT are internal times, for today and for a default.
17194 Return shift list (N what def-flag)
17195 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17196 N is the number of WHATs to shift.
17197 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17198 the DEFAULT date rather than TODAY."
17199 (require 'parse-time)
17200 (when (and
17201 (string-match
17202 (concat
17203 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17204 "\\([0-9]+\\)?"
17205 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17206 "\\([ \t]\\|$\\)") s)
17207 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17208 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17209 (string-to-char (substring (match-string 1 s) -1))
17210 ?+))
17211 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17212 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17213 (what (if (match-end 3) (match-string 3 s) "d"))
17214 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17215 (date (if rel default today))
17216 (wday (nth 6 (decode-time date)))
17217 delta)
17218 (if wday1
17219 (progn
17220 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17221 (when (= delta 0) (setq delta 7))
17222 (when (= dir ?-)
17223 (setq delta (- delta 7))
17224 (when (= delta 0) (setq delta -7)))
17225 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17226 (list delta "d" rel))
17227 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17229 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17230 "Turn a user-specified date into the internal representation.
17231 The internal representation needed by the calendar is (month day year).
17232 This is a wrapper to handle the brain-dead convention in calendar that
17233 user function argument order change dependent on argument order."
17234 (pcase calendar-date-style
17235 (`american (list arg1 arg2 arg3))
17236 (`european (list arg2 arg1 arg3))
17237 (`iso (list arg2 arg3 arg1))))
17239 (defun org-eval-in-calendar (form &optional keepdate)
17240 "Eval FORM in the calendar window and return to current window.
17241 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17242 (let ((sf (selected-frame))
17243 (sw (selected-window)))
17244 (select-window (get-buffer-window "*Calendar*" t))
17245 (eval form)
17246 (when (and (not keepdate) (calendar-cursor-to-date))
17247 (let* ((date (calendar-cursor-to-date))
17248 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17249 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17250 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17251 (select-window sw)
17252 (select-frame-set-input-focus sf)))
17254 (defun org-calendar-select ()
17255 "Return to `org-read-date' with the date currently selected.
17256 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17257 (interactive)
17258 (when (calendar-cursor-to-date)
17259 (let* ((date (calendar-cursor-to-date))
17260 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17261 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17262 (when (active-minibuffer-window) (exit-minibuffer))))
17264 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17265 "Insert a date stamp for the date given by the internal TIME.
17266 See `format-time-string' for the format of TIME.
17267 WITH-HM means use the stamp format that includes the time of the day.
17268 INACTIVE means use square brackets instead of angular ones, so that the
17269 stamp will not contribute to the agenda.
17270 PRE and POST are optional strings to be inserted before and after the
17271 stamp.
17272 The command returns the inserted time stamp."
17273 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17274 stamp)
17275 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17276 (insert-before-markers (or pre ""))
17277 (when (listp extra)
17278 (setq extra (car extra))
17279 (if (and (stringp extra)
17280 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17281 (setq extra (format "-%02d:%02d"
17282 (string-to-number (match-string 1 extra))
17283 (string-to-number (match-string 2 extra))))
17284 (setq extra nil)))
17285 (when extra
17286 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17287 (insert-before-markers (setq stamp (format-time-string fmt time)))
17288 (insert-before-markers (or post ""))
17289 (setq org-last-inserted-timestamp stamp)))
17291 (defun org-toggle-time-stamp-overlays ()
17292 "Toggle the use of custom time stamp formats."
17293 (interactive)
17294 (setq org-display-custom-times (not org-display-custom-times))
17295 (unless org-display-custom-times
17296 (let ((p (point-min)) (bmp (buffer-modified-p)))
17297 (while (setq p (next-single-property-change p 'display))
17298 (when (and (get-text-property p 'display)
17299 (eq (get-text-property p 'face) 'org-date))
17300 (remove-text-properties
17301 p (setq p (next-single-property-change p 'display))
17302 '(display t))))
17303 (set-buffer-modified-p bmp)))
17304 (org-restart-font-lock)
17305 (setq org-table-may-need-update t)
17306 (if org-display-custom-times
17307 (message "Time stamps are overlaid with custom format")
17308 (message "Time stamp overlays removed")))
17310 (defun org-display-custom-time (beg end)
17311 "Overlay modified time stamp format over timestamp between BEG and END."
17312 (let* ((ts (buffer-substring beg end))
17313 t1 w1 with-hm tf time str w2 (off 0))
17314 (save-match-data
17315 (setq t1 (org-parse-time-string ts t))
17316 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17317 (setq off (- (match-end 0) (match-beginning 0)))))
17318 (setq end (- end off))
17319 (setq w1 (- end beg)
17320 with-hm (and (nth 1 t1) (nth 2 t1))
17321 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17322 time (org-fix-decoded-time t1)
17323 str (org-add-props
17324 (format-time-string
17325 (substring tf 1 -1) (apply 'encode-time time))
17326 nil 'mouse-face 'highlight)
17327 w2 (length str))
17328 (unless (= w2 w1)
17329 (add-text-properties (1+ beg) (+ 2 beg)
17330 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17331 (put-text-property beg end 'display str)))
17333 (defun org-fix-decoded-time (time)
17334 "Set 0 instead of nil for the first 6 elements of time.
17335 Don't touch the rest."
17336 (let ((n 0))
17337 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17339 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17340 "Difference between TIMESTAMP-STRING and now in days.
17341 If SECONDS is non-nil, return the difference in seconds."
17342 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17343 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17344 (funcall fdiff (current-time)))))
17346 (defun org-deadline-close-p (timestamp-string &optional ndays)
17347 "Is the time in TIMESTAMP-STRING close to the current date?"
17348 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17349 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17350 (not (org-entry-is-done-p))))
17352 (defun org-get-wdays (ts &optional delay zero-delay)
17353 "Get the deadline lead time appropriate for timestring TS.
17354 When DELAY is non-nil, get the delay time for scheduled items
17355 instead of the deadline lead time. When ZERO-DELAY is non-nil
17356 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17357 don't try to find the delay cookie in the scheduled timestamp."
17358 (let ((tv (if delay org-scheduled-delay-days
17359 org-deadline-warning-days)))
17360 (cond
17361 ((or (and delay (< tv 0))
17362 (and delay zero-delay (<= tv 0))
17363 (and (not delay) (<= tv 0)))
17364 ;; Enforce this value no matter what
17365 (- tv))
17366 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17367 ;; lead time is specified.
17368 (floor (* (string-to-number (match-string 1 ts))
17369 (cdr (assoc (match-string 2 ts)
17370 '(("d" . 1) ("w" . 7)
17371 ("m" . 30.4) ("y" . 365.25)
17372 ("h" . 0.041667)))))))
17373 ;; go for the default.
17374 (t tv))))
17376 (defun org-calendar-select-mouse (ev)
17377 "Return to `org-read-date' with the date currently selected.
17378 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17379 (interactive "e")
17380 (mouse-set-point ev)
17381 (when (calendar-cursor-to-date)
17382 (let* ((date (calendar-cursor-to-date))
17383 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17384 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17385 (when (active-minibuffer-window) (exit-minibuffer))))
17387 (defun org-check-deadlines (ndays)
17388 "Check if there are any deadlines due or past due.
17389 A deadline is considered due if it happens within `org-deadline-warning-days'
17390 days from today's date. If the deadline appears in an entry marked DONE,
17391 it is not shown. A numeric prefix argument NDAYS can be used to test that
17392 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17393 are shown."
17394 (interactive "P")
17395 (let* ((org-warn-days
17396 (cond
17397 ((equal ndays '(4)) 100000)
17398 (ndays (prefix-numeric-value ndays))
17399 (t (abs org-deadline-warning-days))))
17400 (case-fold-search nil)
17401 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17402 (callback
17403 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17404 (message "%d deadlines past-due or due within %d days"
17405 (org-occur regexp nil callback)
17406 org-warn-days)))
17408 (defsubst org-re-timestamp (type)
17409 "Return a regexp for timestamp TYPE.
17410 Allowed values for TYPE are:
17412 all: all timestamps
17413 active: only active timestamps (<...>)
17414 inactive: only inactive timestamps ([...])
17415 scheduled: only scheduled timestamps
17416 deadline: only deadline timestamps
17417 closed: only closed time-stamps
17419 When TYPE is nil, fall back on returning a regexp that matches
17420 both scheduled and deadline timestamps."
17421 (cl-case type
17422 (all org-ts-regexp-both)
17423 (active org-ts-regexp)
17424 (inactive org-ts-regexp-inactive)
17425 (scheduled org-scheduled-time-regexp)
17426 (deadline org-deadline-time-regexp)
17427 (closed org-closed-time-regexp)
17428 (otherwise
17429 (concat "\\<"
17430 (regexp-opt (list org-deadline-string org-scheduled-string))
17431 " *<\\([^>]+\\)>"))))
17433 (defun org-check-before-date (d)
17434 "Check if there are deadlines or scheduled entries before date D."
17435 (interactive (list (org-read-date)))
17436 (let* ((case-fold-search nil)
17437 (regexp (org-re-timestamp org-ts-type))
17438 (ts-type org-ts-type)
17439 (callback
17440 (lambda ()
17441 (let ((match (match-string 1)))
17442 (and (if (memq ts-type '(active inactive all))
17443 (eq (org-element-type (save-excursion
17444 (backward-char)
17445 (org-element-context)))
17446 'timestamp)
17447 (org-at-planning-p))
17448 (time-less-p
17449 (org-time-string-to-time match)
17450 (org-time-string-to-time d)))))))
17451 (message "%d entries before %s"
17452 (org-occur regexp nil callback)
17453 d)))
17455 (defun org-check-after-date (d)
17456 "Check if there are deadlines or scheduled entries after date D."
17457 (interactive (list (org-read-date)))
17458 (let* ((case-fold-search nil)
17459 (regexp (org-re-timestamp org-ts-type))
17460 (ts-type org-ts-type)
17461 (callback
17462 (lambda ()
17463 (let ((match (match-string 1)))
17464 (and (if (memq ts-type '(active inactive all))
17465 (eq (org-element-type (save-excursion
17466 (backward-char)
17467 (org-element-context)))
17468 'timestamp)
17469 (org-at-planning-p))
17470 (not (time-less-p
17471 (org-time-string-to-time match)
17472 (org-time-string-to-time d))))))))
17473 (message "%d entries after %s"
17474 (org-occur regexp nil callback)
17475 d)))
17477 (defun org-check-dates-range (start-date end-date)
17478 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17479 (interactive (list (org-read-date nil nil nil "Range starts")
17480 (org-read-date nil nil nil "Range end")))
17481 (let ((case-fold-search nil)
17482 (regexp (org-re-timestamp org-ts-type))
17483 (callback
17484 (let ((type org-ts-type))
17485 (lambda ()
17486 (let ((match (match-string 1)))
17487 (and
17488 (if (memq type '(active inactive all))
17489 (eq (org-element-type (save-excursion
17490 (backward-char)
17491 (org-element-context)))
17492 'timestamp)
17493 (org-at-planning-p))
17494 (not (time-less-p
17495 (org-time-string-to-time match)
17496 (org-time-string-to-time start-date)))
17497 (time-less-p
17498 (org-time-string-to-time match)
17499 (org-time-string-to-time end-date))))))))
17500 (message "%d entries between %s and %s"
17501 (org-occur regexp nil callback) start-date end-date)))
17503 (defun org-evaluate-time-range (&optional to-buffer)
17504 "Evaluate a time range by computing the difference between start and end.
17505 Normally the result is just printed in the echo area, but with prefix arg
17506 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17507 If the time range is actually in a table, the result is inserted into the
17508 next column.
17509 For time difference computation, a year is assumed to be exactly 365
17510 days in order to avoid rounding problems."
17511 (interactive "P")
17513 (org-clock-update-time-maybe)
17514 (save-excursion
17515 (unless (org-at-date-range-p t)
17516 (goto-char (point-at-bol))
17517 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17518 (unless (org-at-date-range-p t)
17519 (user-error "Not at a time-stamp range, and none found in current line")))
17520 (let* ((ts1 (match-string 1))
17521 (ts2 (match-string 2))
17522 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17523 (match-end (match-end 0))
17524 (time1 (org-time-string-to-time ts1))
17525 (time2 (org-time-string-to-time ts2))
17526 (t1 (float-time time1))
17527 (t2 (float-time time2))
17528 (diff (abs (- t2 t1)))
17529 (negative (< (- t2 t1) 0))
17530 ;; (ys (floor (* 365 24 60 60)))
17531 (ds (* 24 60 60))
17532 (hs (* 60 60))
17533 (fy "%dy %dd %02d:%02d")
17534 (fy1 "%dy %dd")
17535 (fd "%dd %02d:%02d")
17536 (fd1 "%dd")
17537 (fh "%02d:%02d")
17538 y d h m align)
17539 (if havetime
17540 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17542 d (floor (/ diff ds)) diff (mod diff ds)
17543 h (floor (/ diff hs)) diff (mod diff hs)
17544 m (floor (/ diff 60)))
17545 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17547 d (floor (+ (/ diff ds) 0.5))
17548 h 0 m 0))
17549 (if (not to-buffer)
17550 (message "%s" (org-make-tdiff-string y d h m))
17551 (if (org-at-table-p)
17552 (progn
17553 (goto-char match-end)
17554 (setq align t)
17555 (and (looking-at " *|") (goto-char (match-end 0))))
17556 (goto-char match-end))
17557 (when (looking-at
17558 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17559 (replace-match ""))
17560 (when negative (insert " -"))
17561 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17562 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17563 (insert " " (format fh h m))))
17564 (when align (org-table-align))
17565 (message "Time difference inserted")))))
17567 (defun org-make-tdiff-string (y d h m)
17568 (let ((fmt "")
17569 (l nil))
17570 (when (> y 0)
17571 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17572 (push y l))
17573 (when (> d 0)
17574 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17575 (push d l))
17576 (when (> h 0)
17577 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17578 (push h l))
17579 (when (> m 0)
17580 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17581 (push m l))
17582 (apply 'format fmt (nreverse l))))
17584 (defun org-time-string-to-time (s &optional buffer pos)
17585 "Convert a timestamp string into internal time."
17586 (condition-case errdata
17587 (apply 'encode-time (org-parse-time-string s))
17588 (error (error "Bad timestamp `%s'%s\nError was: %s"
17589 s (if (not (and buffer pos))
17591 (format-message " at %d in buffer `%s'" pos buffer))
17592 (cdr errdata)))))
17594 (defun org-time-string-to-seconds (s)
17595 "Convert a timestamp string to a number of seconds."
17596 (float-time (org-time-string-to-time s)))
17598 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17600 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17601 "Convert time stamp S to an absolute day number.
17603 If DAYNR in non-nil, and there is a specifier for a cyclic time
17604 stamp, get the closest date to DAYNR. If PREFER is
17605 `past' (respectively `future') return a date past (respectively
17606 after) or equal to DAYNR.
17608 POS is the location of time stamp S, as a buffer position in
17609 BUFFER.
17611 Diary sexp timestamps are matched against DAYNR, when non-nil.
17612 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17613 signalled."
17614 (cond
17615 ((string-match "\\`%%\\((.*)\\)" s)
17616 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17617 ;; only able to match individual dates. If it fails, raise an
17618 ;; error.
17619 (if (and daynr
17620 (org-diary-sexp-entry
17621 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17622 daynr
17623 (signal 'org-diary-sexp-no-match (list s))))
17624 (daynr (org-closest-date s daynr prefer))
17625 (t (time-to-days
17626 (condition-case errdata
17627 (apply #'encode-time (org-parse-time-string s))
17628 (error (error "Bad timestamp `%s'%s\nError was: %s"
17630 (if (not (and buffer pos)) ""
17631 (format-message " at %d in buffer `%s'" pos buffer))
17632 (cdr errdata))))))))
17634 (defun org-days-to-iso-week (days)
17635 "Return the iso week number."
17636 (require 'cal-iso)
17637 (car (calendar-iso-from-absolute days)))
17639 (defun org-small-year-to-year (year)
17640 "Convert 2-digit years into 4-digit years.
17641 YEAR is expanded into one of the 30 next years, if possible, or
17642 into a past one. Any year larger than 99 is returned unchanged."
17643 (if (>= year 100) year
17644 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17645 (century (/ current 100))
17646 (offset (- year (% current 100))))
17647 (cond ((> offset 30) (+ (* (1- century) 100) year))
17648 ((> offset -70) (+ (* century 100) year))
17649 (t (+ (* (1+ century) 100) year))))))
17651 (defun org-time-from-absolute (d)
17652 "Return the time corresponding to date D.
17653 D may be an absolute day number, or a calendar-type list (month day year)."
17654 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17655 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17657 (defvar org-agenda-current-date)
17658 (defun org-calendar-holiday ()
17659 "List of holidays, for Diary display in Org mode."
17660 (require 'holidays)
17661 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17662 (and hl (mapconcat #'identity hl "; "))))
17664 (defun org-diary-sexp-entry (sexp entry d)
17665 "Process a SEXP diary ENTRY for date D."
17666 (require 'diary-lib)
17667 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17668 ;; dynamically.
17669 (let* ((sexp `(let ((entry ,entry)
17670 (date ',d))
17671 ,(car (read-from-string sexp))))
17672 (result (if calendar-debug-sexp (eval sexp)
17673 (condition-case nil
17674 (eval sexp)
17675 (error
17676 (beep)
17677 (message "Bad sexp at line %d in %s: %s"
17678 (org-current-line)
17679 (buffer-file-name) sexp)
17680 (sleep-for 2))))))
17681 (cond ((stringp result) (split-string result "; "))
17682 ((and (consp result)
17683 (not (consp (cdr result)))
17684 (stringp (cdr result))) (cdr result))
17685 ((and (consp result)
17686 (stringp (car result))) result)
17687 (result entry))))
17689 (defun org-diary-to-ical-string (frombuf)
17690 "Get iCalendar entries from diary entries in buffer FROMBUF.
17691 This uses the icalendar.el library."
17692 (let* ((tmpdir temporary-file-directory)
17693 (tmpfile (make-temp-name
17694 (expand-file-name "orgics" tmpdir)))
17695 buf rtn b e)
17696 (with-current-buffer frombuf
17697 (icalendar-export-region (point-min) (point-max) tmpfile)
17698 (setq buf (find-buffer-visiting tmpfile))
17699 (set-buffer buf)
17700 (goto-char (point-min))
17701 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17702 (setq b (match-beginning 0)))
17703 (goto-char (point-max))
17704 (when (re-search-backward "^END:VEVENT" nil t)
17705 (setq e (match-end 0)))
17706 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17707 (kill-buffer buf)
17708 (delete-file tmpfile)
17709 rtn))
17711 (defun org-closest-date (start current prefer)
17712 "Return closest date to CURRENT starting from START.
17714 CURRENT and START are both time stamps.
17716 When PREFER is `past', return a date that is either CURRENT or
17717 past. When PREFER is `future', return a date that is either
17718 CURRENT or future.
17720 Only time stamps with a repeater are modified. Any other time
17721 stamp stay unchanged. In any case, return value is an absolute
17722 day number."
17723 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17724 ;; No repeater. Do not shift time stamp.
17725 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17726 (let ((value (string-to-number (match-string 1 start)))
17727 (type (match-string 2 start)))
17728 (if (= 0 value)
17729 ;; Repeater with a 0-value is considered as void.
17730 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17731 (let* ((base (org-date-to-gregorian start))
17732 (target (org-date-to-gregorian current))
17733 (sday (calendar-absolute-from-gregorian base))
17734 (cday (calendar-absolute-from-gregorian target))
17735 n1 n2)
17736 ;; If START is already past CURRENT, just return START.
17737 (if (<= cday sday) sday
17738 ;; Compute closest date before (N1) and closest date past
17739 ;; (N2) CURRENT.
17740 (pcase type
17741 ("h"
17742 (let ((missing-hours
17743 (mod (+ (- (* 24 (- cday sday))
17744 (nth 2 (org-parse-time-string start)))
17745 org-extend-today-until)
17746 value)))
17747 (setf n1 (if (= missing-hours 0) cday
17748 (- cday (1+ (/ missing-hours 24)))))
17749 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17750 ((or "d" "w")
17751 (let ((value (if (equal type "w") (* 7 value) value)))
17752 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17753 (setf n2 (+ n1 value))))
17754 ("m"
17755 (let* ((add-months
17756 (lambda (d n)
17757 ;; Add N months to gregorian date D, i.e.,
17758 ;; a list (MONTH DAY YEAR). Return a valid
17759 ;; gregorian date.
17760 (let ((m (+ (nth 0 d) n)))
17761 (list (mod m 12)
17762 (nth 1 d)
17763 (+ (/ m 12) (nth 2 d))))))
17764 (months ; Complete months to TARGET.
17765 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17766 (- (nth 0 target) (nth 0 base))
17767 ;; If START's day is greater than
17768 ;; TARGET's, remove incomplete month.
17769 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17770 value)
17771 value))
17772 (before (funcall add-months base months)))
17773 (setf n1 (calendar-absolute-from-gregorian before))
17774 (setf n2
17775 (calendar-absolute-from-gregorian
17776 (funcall add-months before value)))))
17778 (let* ((d (nth 1 base))
17779 (m (nth 0 base))
17780 (y (nth 2 base))
17781 (years ; Complete years to TARGET.
17782 (* (/ (- (nth 2 target)
17784 ;; If START's month and day are
17785 ;; greater than TARGET's, remove
17786 ;; incomplete year.
17787 (if (or (> (nth 0 target) m)
17788 (and (= (nth 0 target) m)
17789 (> (nth 1 target) d)))
17792 value)
17793 value))
17794 (before (list m d (+ y years))))
17795 (setf n1 (calendar-absolute-from-gregorian before))
17796 (setf n2 (calendar-absolute-from-gregorian
17797 (list m d (+ (nth 2 before) value)))))))
17798 ;; Handle PREFER parameter, if any.
17799 (cond
17800 ((eq prefer 'past) (if (= cday n2) n2 n1))
17801 ((eq prefer 'future) (if (= cday n1) n1 n2))
17802 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17804 (defun org-date-to-gregorian (d)
17805 "Turn any specification of date D into a Gregorian date for the calendar."
17806 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17807 ((and (listp d) (= (length d) 3)) d)
17808 ((stringp d)
17809 (let ((d (org-parse-time-string d)))
17810 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17811 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17813 (defun org-parse-time-string (s &optional nodefault)
17814 "Parse the standard Org time string.
17815 This should be a lot faster than the normal `parse-time-string'.
17816 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17817 hour and minute fields will be nil if not given."
17818 (cond ((string-match org-ts-regexp0 s)
17819 (list 0
17820 (when (or (match-beginning 8) (not nodefault))
17821 (string-to-number (or (match-string 8 s) "0")))
17822 (when (or (match-beginning 7) (not nodefault))
17823 (string-to-number (or (match-string 7 s) "0")))
17824 (string-to-number (match-string 4 s))
17825 (string-to-number (match-string 3 s))
17826 (string-to-number (match-string 2 s))
17827 nil nil nil))
17828 ((string-match "^<[^>]+>$" s)
17829 (decode-time (seconds-to-time (org-matcher-time s))))
17830 (t (error "Not a standard Org time string: %s" s))))
17832 (defun org-timestamp-up (&optional arg)
17833 "Increase the date item at the cursor by one.
17834 If the cursor is on the year, change the year. If it is on the month,
17835 the day or the time, change that.
17836 With prefix ARG, change by that many units."
17837 (interactive "p")
17838 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17840 (defun org-timestamp-down (&optional arg)
17841 "Decrease the date item at the cursor by one.
17842 If the cursor is on the year, change the year. If it is on the month,
17843 the day or the time, change that.
17844 With prefix ARG, change by that many units."
17845 (interactive "p")
17846 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17848 (defun org-timestamp-up-day (&optional arg)
17849 "Increase the date in the time stamp by one day.
17850 With prefix ARG, change that many days."
17851 (interactive "p")
17852 (if (and (not (org-at-timestamp-p t))
17853 (org-at-heading-p))
17854 (org-todo 'up)
17855 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17857 (defun org-timestamp-down-day (&optional arg)
17858 "Decrease the date in the time stamp by one day.
17859 With prefix ARG, change that many days."
17860 (interactive "p")
17861 (if (and (not (org-at-timestamp-p t))
17862 (org-at-heading-p))
17863 (org-todo 'down)
17864 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17866 (defun org-at-timestamp-p (&optional inactive-ok)
17867 "Non-nil if point is inside a timestamp.
17869 When optional argument INACTIVE-OK is non-nil, also consider
17870 inactive timestamps.
17872 When this function returns a non-nil value, match data is set
17873 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17874 INACTIVE-OK.
17876 Return the position of the point as a symbol among `bracket',
17877 `after', `year', `month', `hour', `minute', `day' or a number of
17878 character from the last know part of the time stamp.
17880 This function checks context and only return non-nil for valid
17881 time stamps. If you need to match anything looking like a time
17882 stamp, or if you are sure about the context, consider using
17883 `org-in-regexp', e.g.,
17885 (org-in-regexp org-ts-regexp)
17887 Unlike to `org-element-context', the function recognizes time
17888 stamps in properties drawers, planning lines and clocks."
17889 (interactive)
17890 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17891 (pos (point))
17892 (match
17893 (let ((boundaries (org-in-regexp tsr)))
17894 (save-match-data
17895 (cond ((null boundaries) nil)
17896 ((org-at-planning-p))
17897 ((org-at-property-p))
17898 ;; CLOCK lines only contain inactive time-stamps.
17899 ((and inactive-ok (org-at-clock-log-p)))
17901 (eq 'timestamp
17902 (save-excursion
17903 (when (= pos (cdr boundaries)) (forward-char -1))
17904 (org-element-type (org-element-context))))))))))
17905 (cond
17906 ((not match) nil)
17907 ((= pos (match-beginning 0)) 'bracket)
17908 ;; Distinguish location right before the closing bracket from
17909 ;; right after it.
17910 ((= pos (1- (match-end 0))) 'bracket)
17911 ((= pos (match-end 0)) 'after)
17912 ((org-pos-in-match-range pos 2) 'year)
17913 ((org-pos-in-match-range pos 3) 'month)
17914 ((org-pos-in-match-range pos 7) 'hour)
17915 ((org-pos-in-match-range pos 8) 'minute)
17916 ((or (org-pos-in-match-range pos 4)
17917 (org-pos-in-match-range pos 5)) 'day)
17918 ((and (> pos (or (match-end 8) (match-end 5)))
17919 (< pos (match-end 0)))
17920 (- pos (or (match-end 8) (match-end 5))))
17921 (t 'day))))
17923 (defun org-toggle-timestamp-type ()
17924 "Toggle the type (<active> or [inactive]) of a time stamp."
17925 (interactive)
17926 (when (org-at-timestamp-p t)
17927 (let ((beg (match-beginning 0)) (end (match-end 0))
17928 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17929 (save-excursion
17930 (goto-char beg)
17931 (while (re-search-forward "[][<>]" end t)
17932 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17933 t t)))
17934 (message "Timestamp is now %sactive"
17935 (if (equal (char-after beg) ?<) "" "in")))))
17937 (defun org-at-clock-log-p ()
17938 "Non-nil if point is on a clock log line."
17939 (and (org-match-line org-clock-line-re)
17940 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17942 (defvar org-clock-history) ; defined in org-clock.el
17943 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17944 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17945 "Change the date in the time stamp at point.
17946 The date will be changed by N times WHAT. WHAT can be `day', `month',
17947 `year', `minute', `second'. If WHAT is not given, the cursor position
17948 in the timestamp determines what will be changed.
17949 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17950 (let ((origin (point))
17951 (timestamp? (org-at-timestamp-p t))
17952 origin-cat
17953 with-hm inactive
17954 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17955 extra rem
17956 ts time time0 fixnext clrgx)
17957 (unless timestamp? (user-error "Not at a timestamp"))
17958 (if (and (not what) (eq timestamp? 'bracket))
17959 (org-toggle-timestamp-type)
17960 ;; Point isn't on brackets. Remember the part of the time-stamp
17961 ;; the point was in. Indeed, size of time-stamps may change,
17962 ;; but point must be kept in the same category nonetheless.
17963 (setq origin-cat timestamp?)
17964 (when (and (not what) (not (eq timestamp? 'day))
17965 org-display-custom-times
17966 (get-text-property (point) 'display)
17967 (not (get-text-property (1- (point)) 'display)))
17968 (setq timestamp? 'day))
17969 (setq timestamp? (or what timestamp?)
17970 inactive (= (char-after (match-beginning 0)) ?\[)
17971 ts (match-string 0))
17972 (replace-match "")
17973 (when (string-match
17974 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17976 (setq extra (match-string 1 ts))
17977 (when suppress-tmp-delay
17978 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17979 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17980 (setq with-hm t))
17981 (setq time0 (org-parse-time-string ts))
17982 (when (and updown
17983 (eq timestamp? 'minute)
17984 (not current-prefix-arg))
17985 ;; This looks like s-up and s-down. Change by one rounding step.
17986 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17987 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17988 (setcar (cdr time0) (+ (nth 1 time0)
17989 (if (> n 0) (- rem) (- dm rem))))))
17990 (setq time
17991 (apply #'encode-time
17992 (or (car time0) 0)
17993 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17994 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17995 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17996 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17997 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17998 (nthcdr 6 time0)))
17999 (when (and (memq timestamp? '(hour minute))
18000 extra
18001 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18002 (setq extra (org-modify-ts-extra
18003 extra
18004 (if (eq timestamp? 'hour) 2 5)
18005 n dm)))
18006 (when (integerp timestamp?)
18007 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18008 (when (eq what 'calendar)
18009 (let ((cal-date (org-get-date-from-calendar)))
18010 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18011 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18012 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18013 (setcar time0 (or (car time0) 0))
18014 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18015 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18016 (setq time (apply 'encode-time time0))))
18017 ;; Insert the new time-stamp, and ensure point stays in the same
18018 ;; category as before (i.e. not after the last position in that
18019 ;; category).
18020 (let ((pos (point)))
18021 ;; Stay before inserted string. `save-excursion' is of no use.
18022 (setq org-last-changed-timestamp
18023 (org-insert-time-stamp time with-hm inactive nil nil extra))
18024 (goto-char pos))
18025 (save-match-data
18026 (looking-at org-ts-regexp3)
18027 (goto-char
18028 (pcase origin-cat
18029 ;; `day' category ends before `hour' if any, or at the end
18030 ;; of the day name.
18031 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18032 (`hour (min (match-end 7) origin))
18033 (`minute (min (1- (match-end 8)) origin))
18034 ((pred integerp) (min (1- (match-end 0)) origin))
18035 ;; Point was right after the time-stamp. However, the
18036 ;; time-stamp length might have changed, so refer to
18037 ;; (match-end 0) instead.
18038 (`after (match-end 0))
18039 ;; `year' and `month' have both fixed size: point couldn't
18040 ;; have moved into another part.
18041 (_ origin))))
18042 ;; Update clock if on a CLOCK line.
18043 (org-clock-update-time-maybe)
18044 ;; Maybe adjust the closest clock in `org-clock-history'
18045 (when org-clock-adjust-closest
18046 (if (not (and (org-at-clock-log-p)
18047 (< 1 (length (delq nil (mapcar 'marker-position
18048 org-clock-history))))))
18049 (message "No clock to adjust")
18050 (cond ((save-excursion ; fix previous clock?
18051 (re-search-backward org-ts-regexp0 nil t)
18052 (looking-back (concat org-clock-string " \\[")
18053 (line-beginning-position)))
18054 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18055 ((save-excursion ; fix next clock?
18056 (re-search-backward org-ts-regexp0 nil t)
18057 (looking-at (concat org-ts-regexp0 "\\] =>")))
18058 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18059 (save-window-excursion
18060 ;; Find closest clock to point, adjust the previous/next one in history
18061 (let* ((p (save-excursion (org-back-to-heading t)))
18062 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18063 (clfixnth
18064 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18065 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18066 (if (not clfixpos)
18067 (message "No clock to adjust")
18068 (save-excursion
18069 (org-goto-marker-or-bmk clfixpos)
18070 (org-show-subtree)
18071 (when (re-search-forward clrgx nil t)
18072 (goto-char (match-beginning 1))
18073 (let (org-clock-adjust-closest)
18074 (org-timestamp-change n timestamp? updown))
18075 (message "Clock adjusted in %s for heading: %s"
18076 (file-name-nondirectory (buffer-file-name))
18077 (org-get-heading t t)))))))))
18078 ;; Try to recenter the calendar window, if any.
18079 (when (and org-calendar-follow-timestamp-change
18080 (get-buffer-window "*Calendar*" t)
18081 (memq timestamp? '(day month year)))
18082 (org-recenter-calendar (time-to-days time))))))
18084 (defun org-modify-ts-extra (s pos n dm)
18085 "Change the different parts of the lead-time and repeat fields in timestamp."
18086 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18087 ng h m new rem)
18088 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18089 (cond
18090 ((or (org-pos-in-match-range pos 2)
18091 (org-pos-in-match-range pos 3))
18092 (setq m (string-to-number (match-string 3 s))
18093 h (string-to-number (match-string 2 s)))
18094 (if (org-pos-in-match-range pos 2)
18095 (setq h (+ h n))
18096 (setq n (* dm (with-no-warnings (signum n))))
18097 (unless (= 0 (setq rem (% m dm)))
18098 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18099 (setq m (+ m n)))
18100 (when (< m 0) (setq m (+ m 60) h (1- h)))
18101 (when (> m 59) (setq m (- m 60) h (1+ h)))
18102 (setq h (mod h 24))
18103 (setq ng 1 new (format "-%02d:%02d" h m)))
18104 ((org-pos-in-match-range pos 6)
18105 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18106 ((org-pos-in-match-range pos 5)
18107 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18109 ((org-pos-in-match-range pos 9)
18110 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18111 ((org-pos-in-match-range pos 8)
18112 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18114 (when ng
18115 (setq s (concat
18116 (substring s 0 (match-beginning ng))
18118 (substring s (match-end ng))))))
18121 (defun org-recenter-calendar (d)
18122 "If the calendar is visible, recenter it to date D."
18123 (let ((cwin (get-buffer-window "*Calendar*" t)))
18124 (when cwin
18125 (let ((calendar-move-hook nil))
18126 (with-selected-window cwin
18127 (calendar-goto-date
18128 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18130 (defun org-goto-calendar (&optional arg)
18131 "Go to the Emacs calendar at the current date.
18132 If there is a time stamp in the current line, go to that date.
18133 A prefix ARG can be used to force the current date."
18134 (interactive "P")
18135 (let ((tsr org-ts-regexp) diff
18136 (calendar-move-hook nil)
18137 (calendar-view-holidays-initially-flag nil)
18138 (calendar-view-diary-initially-flag nil))
18139 (when (or (org-at-timestamp-p)
18140 (save-excursion
18141 (beginning-of-line 1)
18142 (looking-at (concat ".*" tsr))))
18143 (let ((d1 (time-to-days (current-time)))
18144 (d2 (time-to-days
18145 (org-time-string-to-time (match-string 1)))))
18146 (setq diff (- d2 d1))))
18147 (calendar)
18148 (calendar-goto-today)
18149 (when (and diff (not arg)) (calendar-forward-day diff))))
18151 (defun org-get-date-from-calendar ()
18152 "Return a list (month day year) of date at point in calendar."
18153 (with-current-buffer "*Calendar*"
18154 (save-match-data
18155 (calendar-cursor-to-date))))
18157 (defun org-date-from-calendar ()
18158 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18159 If there is already a time stamp at the cursor position, update it."
18160 (interactive)
18161 (if (org-at-timestamp-p t)
18162 (org-timestamp-change 0 'calendar)
18163 (let ((cal-date (org-get-date-from-calendar)))
18164 (org-insert-time-stamp
18165 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18167 (defcustom org-effort-durations
18168 `(("min" . 1)
18169 ("h" . 60)
18170 ("d" . ,(* 60 8))
18171 ("w" . ,(* 60 8 5))
18172 ("m" . ,(* 60 8 5 4))
18173 ("y" . ,(* 60 8 5 40)))
18174 "Conversion factor to minutes for an effort modifier.
18176 Each entry has the form (MODIFIER . MINUTES).
18178 In an effort string, a number followed by MODIFIER is multiplied
18179 by the specified number of MINUTES to obtain an effort in
18180 minutes.
18182 For example, if the value of this variable is ((\"hours\" . 60)), then an
18183 effort string \"2hours\" is equivalent to 120 minutes."
18184 :group 'org-agenda
18185 :version "26.1"
18186 :package-version '(Org . "8.3")
18187 :type '(alist :key-type (string :tag "Modifier")
18188 :value-type (number :tag "Minutes")))
18190 (defcustom org-image-actual-width t
18191 "Should we use the actual width of images when inlining them?
18193 When set to t, always use the image width.
18195 When set to a number, use imagemagick (when available) to set
18196 the image's width to this value.
18198 When set to a number in a list, try to get the width from any
18199 #+ATTR.* keyword if it matches a width specification like
18201 #+ATTR_HTML: :width 300px
18203 and fall back on that number if none is found.
18205 When set to nil, try to get the width from an #+ATTR.* keyword
18206 and fall back on the original width if none is found.
18208 This requires Emacs >= 24.1, build with imagemagick support."
18209 :group 'org-appearance
18210 :version "24.4"
18211 :package-version '(Org . "8.0")
18212 :type '(choice
18213 (const :tag "Use the image width" t)
18214 (integer :tag "Use a number of pixels")
18215 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18216 (const :tag "Use #+ATTR* or don't resize" nil)))
18218 (defcustom org-agenda-inhibit-startup nil
18219 "Inhibit startup when preparing agenda buffers.
18220 When this variable is t, the initialization of the Org agenda
18221 buffers is inhibited: e.g. the visibility state is not set, the
18222 tables are not re-aligned, etc."
18223 :type 'boolean
18224 :version "24.3"
18225 :group 'org-agenda)
18227 (defcustom org-agenda-ignore-properties nil
18228 "Avoid updating text properties when building the agenda.
18229 Properties are used to prepare buffers for effort estimates,
18230 appointments, statistics and subtree-local categories.
18231 If you don't use these in the agenda, you can add them to this
18232 list and agenda building will be a bit faster.
18233 The value is a list, with zero or more of the symbols `effort', `appt',
18234 `stats' or `category'."
18235 :type '(set :greedy t
18236 (const effort)
18237 (const appt)
18238 (const stats)
18239 (const category))
18240 :version "26.1"
18241 :package-version '(Org . "8.3")
18242 :group 'org-agenda)
18244 ;;;; Files
18246 (defun org-save-all-org-buffers ()
18247 "Save all Org buffers without user confirmation."
18248 (interactive)
18249 (message "Saving all Org buffers...")
18250 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18251 (when (featurep 'org-id) (org-id-locations-save))
18252 (message "Saving all Org buffers... done"))
18254 (defun org-revert-all-org-buffers ()
18255 "Revert all Org buffers.
18256 Prompt for confirmation when there are unsaved changes.
18257 Be sure you know what you are doing before letting this function
18258 overwrite your changes.
18260 This function is useful in a setup where one tracks org files
18261 with a version control system, to revert on one machine after pulling
18262 changes from another. I believe the procedure must be like this:
18264 1. M-x org-save-all-org-buffers
18265 2. Pull changes from the other machine, resolve conflicts
18266 3. M-x org-revert-all-org-buffers"
18267 (interactive)
18268 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18269 (user-error "Abort"))
18270 (save-excursion
18271 (save-window-excursion
18272 (dolist (b (buffer-list))
18273 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18274 (with-current-buffer b buffer-file-name))
18275 (pop-to-buffer-same-window b)
18276 (revert-buffer t 'no-confirm)))
18277 (when (and (featurep 'org-id) org-id-track-globally)
18278 (org-id-locations-load)))))
18280 ;;;; Agenda files
18282 ;;;###autoload
18283 (defun org-switchb (&optional arg)
18284 "Switch between Org buffers.
18286 With `\\[universal-argument]' prefix, restrict available buffers to files.
18288 With `\\[universal-argument] \\[universal-argument]' \
18289 prefix, restrict available buffers to agenda files."
18290 (interactive "P")
18291 (let ((blist (org-buffer-list
18292 (cond ((equal arg '(4)) 'files)
18293 ((equal arg '(16)) 'agenda)))))
18294 (pop-to-buffer-same-window
18295 (completing-read "Org buffer: "
18296 (mapcar #'list (mapcar #'buffer-name blist))
18297 nil t))))
18299 (defun org-buffer-list (&optional predicate exclude-tmp)
18300 "Return a list of Org buffers.
18301 PREDICATE can be `export', `files' or `agenda'.
18303 export restrict the list to Export buffers.
18304 files restrict the list to buffers visiting Org files.
18305 agenda restrict the list to buffers visiting agenda files.
18307 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18308 (let* ((bfn nil)
18309 (agenda-files (and (eq predicate 'agenda)
18310 (mapcar 'file-truename (org-agenda-files t))))
18311 (filter
18312 (cond
18313 ((eq predicate 'files)
18314 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18315 ((eq predicate 'export)
18316 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18317 ((eq predicate 'agenda)
18318 (lambda (b)
18319 (with-current-buffer b
18320 (and (derived-mode-p 'org-mode)
18321 (setq bfn (buffer-file-name b))
18322 (member (file-truename bfn) agenda-files)))))
18323 (t (lambda (b) (with-current-buffer b
18324 (or (derived-mode-p 'org-mode)
18325 (string-match "\\*Org .*Export"
18326 (buffer-name b)))))))))
18327 (delq nil
18328 (mapcar
18329 (lambda(b)
18330 (if (and (funcall filter b)
18331 (or (not exclude-tmp)
18332 (not (string-match "tmp" (buffer-name b)))))
18334 nil))
18335 (buffer-list)))))
18337 (defun org-agenda-files (&optional unrestricted archives)
18338 "Get the list of agenda files.
18339 Optional UNRESTRICTED means return the full list even if a restriction
18340 is currently in place.
18341 When ARCHIVES is t, include all archive files that are really being
18342 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18343 `org-agenda-archives-mode' is t."
18344 (let ((files
18345 (cond
18346 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18347 ((stringp org-agenda-files) (org-read-agenda-file-list))
18348 ((listp org-agenda-files) org-agenda-files)
18349 (t (error "Invalid value of `org-agenda-files'")))))
18350 (setq files (apply 'append
18351 (mapcar (lambda (f)
18352 (if (file-directory-p f)
18353 (directory-files
18354 f t org-agenda-file-regexp)
18355 (list f)))
18356 files)))
18357 (when org-agenda-skip-unavailable-files
18358 (setq files (delq nil
18359 (mapcar (function
18360 (lambda (file)
18361 (and (file-readable-p file) file)))
18362 files))))
18363 (when (or (eq archives t)
18364 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18365 (setq files (org-add-archive-files files)))
18366 files))
18368 (defun org-agenda-file-p (&optional file)
18369 "Return non-nil, if FILE is an agenda file.
18370 If FILE is omitted, use the file associated with the current
18371 buffer."
18372 (let ((fname (or file (buffer-file-name))))
18373 (and fname
18374 (member (file-truename fname)
18375 (mapcar #'file-truename (org-agenda-files t))))))
18377 (defun org-edit-agenda-file-list ()
18378 "Edit the list of agenda files.
18379 Depending on setup, this either uses customize to edit the variable
18380 `org-agenda-files', or it visits the file that is holding the list. In the
18381 latter case, the buffer is set up in a way that saving it automatically kills
18382 the buffer and restores the previous window configuration."
18383 (interactive)
18384 (if (stringp org-agenda-files)
18385 (let ((cw (current-window-configuration)))
18386 (find-file org-agenda-files)
18387 (setq-local org-window-configuration cw)
18388 (add-hook 'after-save-hook
18389 (lambda ()
18390 (set-window-configuration
18391 (prog1 org-window-configuration
18392 (kill-buffer (current-buffer))))
18393 (org-install-agenda-files-menu)
18394 (message "New agenda file list installed"))
18395 nil 'local)
18396 (message "%s" (substitute-command-keys
18397 "Edit list and finish with \\[save-buffer]")))
18398 (customize-variable 'org-agenda-files)))
18400 (defun org-store-new-agenda-file-list (list)
18401 "Set new value for the agenda file list and save it correctly."
18402 (if (stringp org-agenda-files)
18403 (let ((fe (org-read-agenda-file-list t)) b u)
18404 (while (setq b (find-buffer-visiting org-agenda-files))
18405 (kill-buffer b))
18406 (with-temp-file org-agenda-files
18407 (insert
18408 (mapconcat
18409 (lambda (f) ;; Keep un-expanded entries.
18410 (if (setq u (assoc f fe))
18411 (cdr u)
18413 list "\n")
18414 "\n")))
18415 (let ((org-mode-hook nil) (org-inhibit-startup t)
18416 (org-insert-mode-line-in-empty-file nil))
18417 (setq org-agenda-files list)
18418 (customize-save-variable 'org-agenda-files org-agenda-files))))
18420 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18421 "Read the list of agenda files from a file.
18422 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18423 filenames, used by `org-store-new-agenda-file-list' to write back
18424 un-expanded file names."
18425 (when (file-directory-p org-agenda-files)
18426 (error "`org-agenda-files' cannot be a single directory"))
18427 (when (stringp org-agenda-files)
18428 (with-temp-buffer
18429 (insert-file-contents org-agenda-files)
18430 (mapcar
18431 (lambda (f)
18432 (let ((e (expand-file-name (substitute-in-file-name f)
18433 org-directory)))
18434 (if pair-with-expansion
18435 (cons e f)
18436 e)))
18437 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18439 ;;;###autoload
18440 (defun org-cycle-agenda-files ()
18441 "Cycle through the files in `org-agenda-files'.
18442 If the current buffer visits an agenda file, find the next one in the list.
18443 If the current buffer does not, find the first agenda file."
18444 (interactive)
18445 (let* ((fs (or (org-agenda-files t)
18446 (user-error "No agenda files")))
18447 (files (copy-sequence fs))
18448 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18449 file)
18450 (when tcf
18451 (while (and (setq file (pop files))
18452 (not (equal (file-truename file) tcf)))))
18453 (find-file (car (or files fs)))
18454 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18456 (defun org-agenda-file-to-front (&optional to-end)
18457 "Move/add the current file to the top of the agenda file list.
18458 If the file is not present in the list, it is added to the front. If it is
18459 present, it is moved there. With optional argument TO-END, add/move to the
18460 end of the list."
18461 (interactive "P")
18462 (let ((org-agenda-skip-unavailable-files nil)
18463 (file-alist (mapcar (lambda (x)
18464 (cons (file-truename x) x))
18465 (org-agenda-files t)))
18466 (ctf (file-truename
18467 (or buffer-file-name
18468 (user-error "Please save the current buffer to a file"))))
18469 x had)
18470 (setq x (assoc ctf file-alist) had x)
18472 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18473 (if to-end
18474 (setq file-alist (append (delq x file-alist) (list x)))
18475 (setq file-alist (cons x (delq x file-alist))))
18476 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18477 (org-install-agenda-files-menu)
18478 (message "File %s to %s of agenda file list"
18479 (if had "moved" "added") (if to-end "end" "front"))))
18481 (defun org-remove-file (&optional file)
18482 "Remove current file from the list of files in variable `org-agenda-files'.
18483 These are the files which are being checked for agenda entries.
18484 Optional argument FILE means use this file instead of the current."
18485 (interactive)
18486 (let* ((org-agenda-skip-unavailable-files nil)
18487 (file (or file buffer-file-name
18488 (user-error "Current buffer does not visit a file")))
18489 (true-file (file-truename file))
18490 (afile (abbreviate-file-name file))
18491 (files (delq nil (mapcar
18492 (lambda (x)
18493 (unless (equal true-file
18494 (file-truename x))
18496 (org-agenda-files t)))))
18497 (if (not (= (length files) (length (org-agenda-files t))))
18498 (progn
18499 (org-store-new-agenda-file-list files)
18500 (org-install-agenda-files-menu)
18501 (message "Removed from Org Agenda list: %s" afile))
18502 (message "File was not in list: %s (not removed)" afile))))
18504 (defun org-file-menu-entry (file)
18505 (vector file (list 'find-file file) t))
18507 (defun org-check-agenda-file (file)
18508 "Make sure FILE exists. If not, ask user what to do."
18509 (unless (file-exists-p file)
18510 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18511 (abbreviate-file-name file))
18512 (let ((r (downcase (read-char-exclusive))))
18513 (cond
18514 ((equal r ?r)
18515 (org-remove-file file)
18516 (throw 'nextfile t))
18517 (t (user-error "Abort"))))))
18519 (defun org-get-agenda-file-buffer (file)
18520 "Get an agenda buffer visiting FILE.
18521 If the buffer needs to be created, add it to the list of buffers
18522 which might be released later."
18523 (let ((buf (org-find-base-buffer-visiting file)))
18524 (if buf
18525 buf ; just return it
18526 ;; Make a new buffer and remember it
18527 (setq buf (find-file-noselect file))
18528 (when buf (push buf org-agenda-new-buffers))
18529 buf)))
18531 (defun org-release-buffers (blist)
18532 "Release all buffers in list, asking the user for confirmation when needed.
18533 When a buffer is unmodified, it is just killed. When modified, it is saved
18534 \(if the user agrees) and then killed."
18535 (let (file)
18536 (dolist (buf blist)
18537 (setq file (buffer-file-name buf))
18538 (when (and (buffer-modified-p buf)
18539 file
18540 (y-or-n-p (format "Save file %s? " file)))
18541 (with-current-buffer buf (save-buffer)))
18542 (kill-buffer buf))))
18544 (defun org-agenda-prepare-buffers (files)
18545 "Create buffers for all agenda files, protect archived trees and comments."
18546 (interactive)
18547 (let ((pa '(:org-archived t))
18548 (pc '(:org-comment t))
18549 (pall '(:org-archived t :org-comment t))
18550 (inhibit-read-only t)
18551 (org-inhibit-startup org-agenda-inhibit-startup)
18552 (rea (concat ":" org-archive-tag ":"))
18553 re pos)
18554 (setq org-tag-alist-for-agenda nil
18555 org-tag-groups-alist-for-agenda nil)
18556 (save-excursion
18557 (save-restriction
18558 (dolist (file files)
18559 (catch 'nextfile
18560 (if (bufferp file)
18561 (set-buffer file)
18562 (org-check-agenda-file file)
18563 (set-buffer (org-get-agenda-file-buffer file)))
18564 (widen)
18565 (org-set-regexps-and-options 'tags-only)
18566 (setq pos (point))
18567 (or (memq 'category org-agenda-ignore-properties)
18568 (org-refresh-category-properties))
18569 (or (memq 'stats org-agenda-ignore-properties)
18570 (org-refresh-stats-properties))
18571 (or (memq 'effort org-agenda-ignore-properties)
18572 (org-refresh-effort-properties))
18573 (or (memq 'appt org-agenda-ignore-properties)
18574 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18575 (setq org-todo-keywords-for-agenda
18576 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18577 (setq org-done-keywords-for-agenda
18578 (append org-done-keywords-for-agenda org-done-keywords))
18579 (setq org-todo-keyword-alist-for-agenda
18580 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18581 (setq org-tag-alist-for-agenda
18582 (org-uniquify
18583 (append org-tag-alist-for-agenda
18584 org-current-tag-alist)))
18585 ;; Merge current file's tag groups into global
18586 ;; `org-tag-groups-alist-for-agenda'.
18587 (when org-group-tags
18588 (dolist (alist org-tag-groups-alist)
18589 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18590 (if old
18591 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18592 (push alist org-tag-groups-alist-for-agenda)))))
18593 (org-with-silent-modifications
18594 (save-excursion
18595 (remove-text-properties (point-min) (point-max) pall)
18596 (when org-agenda-skip-archived-trees
18597 (goto-char (point-min))
18598 (while (re-search-forward rea nil t)
18599 (when (org-at-heading-p t)
18600 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18601 (goto-char (point-min))
18602 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18603 (while (re-search-forward re nil t)
18604 (when (save-match-data (org-in-commented-heading-p t))
18605 (add-text-properties
18606 (match-beginning 0) (org-end-of-subtree t) pc)))))
18607 (goto-char pos)))))
18608 (setq org-todo-keywords-for-agenda
18609 (org-uniquify org-todo-keywords-for-agenda))
18610 (setq org-todo-keyword-alist-for-agenda
18611 (org-uniquify org-todo-keyword-alist-for-agenda))))
18614 ;;;; CDLaTeX minor mode
18616 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18617 "Keymap for the minor `org-cdlatex-mode'.")
18619 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18620 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18621 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18622 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18623 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18625 (defvar org-cdlatex-texmathp-advice-is-done nil
18626 "Flag remembering if we have applied the advice to texmathp already.")
18628 (define-minor-mode org-cdlatex-mode
18629 "Toggle the minor `org-cdlatex-mode'.
18630 This mode supports entering LaTeX environment and math in LaTeX fragments
18631 in Org mode.
18632 \\{org-cdlatex-mode-map}"
18633 nil " OCDL" nil
18634 (when org-cdlatex-mode
18635 (require 'cdlatex)
18636 (run-hooks 'cdlatex-mode-hook)
18637 (cdlatex-compute-tables))
18638 (unless org-cdlatex-texmathp-advice-is-done
18639 (setq org-cdlatex-texmathp-advice-is-done t)
18640 (defadvice texmathp (around org-math-always-on activate)
18641 "Always return t in Org buffers.
18642 This is because we want to insert math symbols without dollars even outside
18643 the LaTeX math segments. If Org mode thinks that point is actually inside
18644 an embedded LaTeX fragment, let `texmathp' do its job.
18645 `\\[org-cdlatex-mode-map]'"
18646 (interactive)
18647 (let (p)
18648 (cond
18649 ((not (derived-mode-p 'org-mode)) ad-do-it)
18650 ((eq this-command 'cdlatex-math-symbol)
18651 (setq ad-return-value t
18652 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18654 (let ((p (org-inside-LaTeX-fragment-p)))
18655 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18656 (setq ad-return-value t
18657 texmathp-why '("Org mode embedded math" . 0))
18658 (when p ad-do-it)))))))))
18660 (defun turn-on-org-cdlatex ()
18661 "Unconditionally turn on `org-cdlatex-mode'."
18662 (org-cdlatex-mode 1))
18664 (defun org-try-cdlatex-tab ()
18665 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18666 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18667 - inside a LaTeX fragment, or
18668 - after the first word in a line, where an abbreviation expansion could
18669 insert a LaTeX environment."
18670 (when org-cdlatex-mode
18671 (cond
18672 ;; Before any word on the line: No expansion possible.
18673 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18674 ;; Just after first word on the line: Expand it. Make sure it
18675 ;; cannot happen on headlines, though.
18676 ((save-excursion
18677 (skip-chars-backward "a-zA-Z0-9*")
18678 (skip-chars-backward " \t")
18679 (and (bolp) (not (org-at-heading-p))))
18680 (cdlatex-tab) t)
18681 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18683 (defun org-cdlatex-underscore-caret (&optional _arg)
18684 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18685 Revert to the normal definition outside of these fragments."
18686 (interactive "P")
18687 (if (org-inside-LaTeX-fragment-p)
18688 (call-interactively 'cdlatex-sub-superscript)
18689 (let (org-cdlatex-mode)
18690 (call-interactively (key-binding (vector last-input-event))))))
18692 (defun org-cdlatex-math-modify (&optional _arg)
18693 "Execute `cdlatex-math-modify' in LaTeX fragments.
18694 Revert to the normal definition outside of these fragments."
18695 (interactive "P")
18696 (if (org-inside-LaTeX-fragment-p)
18697 (call-interactively 'cdlatex-math-modify)
18698 (let (org-cdlatex-mode)
18699 (call-interactively (key-binding (vector last-input-event))))))
18701 (defun org-cdlatex-environment-indent (&optional environment item)
18702 "Execute `cdlatex-environment' and indent the inserted environment.
18704 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18706 The inserted environment is indented to current indentation
18707 unless point is at the beginning of the line, in which the
18708 environment remains unintended."
18709 (interactive)
18710 ;; cdlatex-environment always return nil. Therefore, capture output
18711 ;; first and determine if an environment was selected.
18712 (let* ((beg (point-marker))
18713 (end (copy-marker (point) t))
18714 (inserted (progn
18715 (ignore-errors (cdlatex-environment environment item))
18716 (< beg end)))
18717 ;; Figure out how many lines to move forward after the
18718 ;; environment has been inserted.
18719 (lines (when inserted
18720 (save-excursion
18721 (- (cl-loop while (< beg (point))
18722 with x = 0
18723 do (forward-line -1)
18724 (cl-incf x)
18725 finally return x)
18726 (if (progn (goto-char beg)
18727 (and (progn (skip-chars-forward " \t") (eolp))
18728 (progn (skip-chars-backward " \t") (bolp))))
18729 1 0)))))
18730 (env (org-trim (delete-and-extract-region beg end))))
18731 (when inserted
18732 ;; Get indentation of next line unless at column 0.
18733 (let ((ind (if (bolp) 0
18734 (save-excursion
18735 (org-return-indent)
18736 (prog1 (org-get-indentation)
18737 (when (progn (skip-chars-forward " \t") (eolp))
18738 (delete-region beg (point)))))))
18739 (bol (progn (skip-chars-backward " \t") (bolp))))
18740 ;; Insert a newline before environment unless at column zero
18741 ;; to "escape" the current line. Insert a newline if
18742 ;; something is one the same line as \end{ENVIRONMENT}.
18743 (insert
18744 (concat (unless bol "\n") env
18745 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18746 (unless (zerop ind)
18747 (save-excursion
18748 (goto-char beg)
18749 (while (< (point) end)
18750 (unless (eolp) (indent-line-to ind))
18751 (forward-line))))
18752 (goto-char beg)
18753 (forward-line lines)
18754 (indent-line-to ind)))
18755 (set-marker beg nil)
18756 (set-marker end nil)))
18759 ;;;; LaTeX fragments
18761 (defun org-inside-LaTeX-fragment-p ()
18762 "Test if point is inside a LaTeX fragment.
18763 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18764 sequence appearing also before point.
18765 Even though the matchers for math are configurable, this function assumes
18766 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18767 delimiters are skipped when they have been removed by customization.
18768 The return value is nil, or a cons cell with the delimiter and the
18769 position of this delimiter.
18771 This function does a reasonably good job, but can locally be fooled by
18772 for example currency specifications. For example it will assume being in
18773 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18774 fragments that are properly closed, but during editing, we have to live
18775 with the uncertainty caused by missing closing delimiters. This function
18776 looks only before point, not after."
18777 (catch 'exit
18778 (let ((pos (point))
18779 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18780 (lim (progn
18781 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18782 (point)))
18783 dd-on str (start 0) m re)
18784 (goto-char pos)
18785 (when dodollar
18786 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18787 re (nth 1 (assoc "$" org-latex-regexps)))
18788 (while (string-match re str start)
18789 (cond
18790 ((= (match-end 0) (length str))
18791 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18792 ((= (match-end 0) (- (length str) 5))
18793 (throw 'exit nil))
18794 (t (setq start (match-end 0))))))
18795 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18796 (goto-char pos)
18797 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18798 (and (match-beginning 2) (throw 'exit nil))
18799 ;; count $$
18800 (while (re-search-backward "\\$\\$" lim t)
18801 (setq dd-on (not dd-on)))
18802 (goto-char pos)
18803 (when dd-on (cons "$$" m))))))
18805 (defun org-inside-latex-macro-p ()
18806 "Is point inside a LaTeX macro or its arguments?"
18807 (save-match-data
18808 (org-in-regexp
18809 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18811 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18812 "Build an overlay between BEG and END using IMAGE file.
18813 Argument IMAGETYPE is the extension of the displayed image,
18814 as a string. It defaults to \"png\"."
18815 (let ((ov (make-overlay beg end))
18816 (imagetype (or (intern imagetype) 'png)))
18817 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18818 (overlay-put ov 'evaporate t)
18819 (overlay-put ov
18820 'modification-hooks
18821 (list (lambda (o _flag _beg _end &optional _l)
18822 (delete-overlay o))))
18823 (overlay-put ov
18824 'display
18825 (list 'image :type imagetype :file image :ascent 'center))))
18827 (defun org--list-latex-overlays (&optional beg end)
18828 "List all Org LaTeX overlays in current buffer.
18829 Limit to overlays between BEG and END when those are provided."
18830 (cl-remove-if-not
18831 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18832 (overlays-in (or beg (point-min)) (or end (point-max)))))
18834 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18835 "Remove all overlays with LaTeX fragment images in current buffer.
18836 When optional arguments BEG and END are non-nil, remove all
18837 overlays between them instead. Return a non-nil value when some
18838 overlays were removed, nil otherwise."
18839 (let ((overlays (org--list-latex-overlays beg end)))
18840 (mapc #'delete-overlay overlays)
18841 overlays))
18843 (defun org-toggle-latex-fragment (&optional arg)
18844 "Preview the LaTeX fragment at point, or all locally or globally.
18846 If the cursor is on a LaTeX fragment, create the image and overlay
18847 it over the source code, if there is none. Remove it otherwise.
18848 If there is no fragment at point, display all fragments in the
18849 current section.
18851 With prefix ARG, preview or clear image for all fragments in the
18852 current subtree or in the whole buffer when used before the first
18853 headline. With a prefix ARG `\\[universal-argument] \
18854 \\[universal-argument]' preview or clear images
18855 for all fragments in the buffer."
18856 (interactive "P")
18857 (when (display-graphic-p)
18858 (catch 'exit
18859 (save-excursion
18860 (let (beg end msg)
18861 (cond
18862 ((or (equal arg '(16))
18863 (and (equal arg '(4))
18864 (org-with-limited-levels (org-before-first-heading-p))))
18865 (if (org-remove-latex-fragment-image-overlays)
18866 (progn (message "LaTeX fragments images removed from buffer")
18867 (throw 'exit nil))
18868 (setq msg "Creating images for buffer...")))
18869 ((equal arg '(4))
18870 (org-with-limited-levels (org-back-to-heading t))
18871 (setq beg (point))
18872 (setq end (progn (org-end-of-subtree t) (point)))
18873 (if (org-remove-latex-fragment-image-overlays beg end)
18874 (progn
18875 (message "LaTeX fragment images removed from subtree")
18876 (throw 'exit nil))
18877 (setq msg "Creating images for subtree...")))
18878 ((let ((datum (org-element-context)))
18879 (when (memq (org-element-type datum)
18880 '(latex-environment latex-fragment))
18881 (setq beg (org-element-property :begin datum))
18882 (setq end (org-element-property :end datum))
18883 (if (org-remove-latex-fragment-image-overlays beg end)
18884 (progn (message "LaTeX fragment image removed")
18885 (throw 'exit nil))
18886 (setq msg "Creating image...")))))
18888 (org-with-limited-levels
18889 (setq beg (if (org-at-heading-p) (line-beginning-position)
18890 (outline-previous-heading)
18891 (point)))
18892 (setq end (progn (outline-next-heading) (point)))
18893 (if (org-remove-latex-fragment-image-overlays beg end)
18894 (progn
18895 (message "LaTeX fragment images removed from section")
18896 (throw 'exit nil))
18897 (setq msg "Creating images for section...")))))
18898 (let ((file (buffer-file-name (buffer-base-buffer))))
18899 (org-format-latex
18900 (concat org-preview-latex-image-directory "org-ltximg")
18901 beg end
18902 ;; Emacs cannot overlay images from remote hosts. Create
18903 ;; it in `temporary-file-directory' instead.
18904 (if (or (not file) (file-remote-p file))
18905 temporary-file-directory
18906 default-directory)
18907 'overlays msg 'forbuffer org-preview-latex-default-process))
18908 (message (concat msg "done")))))))
18910 (defun org-format-latex
18911 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18912 "Replace LaTeX fragments with links to an image.
18914 The function takes care of creating the replacement image.
18916 Only consider fragments between BEG and END when those are
18917 provided.
18919 When optional argument OVERLAYS is non-nil, display the image on
18920 top of the fragment instead of replacing it.
18922 PROCESSING-TYPE is the conversion method to use, as a symbol.
18924 Some of the options can be changed using the variable
18925 `org-format-latex-options', which see."
18926 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18927 (unless (eq processing-type 'verbatim)
18928 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18929 (cnt 0)
18930 checkdir-flag)
18931 (goto-char (or beg (point-min)))
18932 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18933 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18934 (overlay-recenter (or end (point-max))))
18935 (while (re-search-forward math-regexp end t)
18936 (unless (and overlays
18937 (eq (get-char-property (point) 'org-overlay-type)
18938 'org-latex-overlay))
18939 (let* ((context (org-element-context))
18940 (type (org-element-type context)))
18941 (when (memq type '(latex-environment latex-fragment))
18942 (let ((block-type (eq type 'latex-environment))
18943 (value (org-element-property :value context))
18944 (beg (org-element-property :begin context))
18945 (end (save-excursion
18946 (goto-char (org-element-property :end context))
18947 (skip-chars-backward " \r\t\n")
18948 (point))))
18949 (cond
18950 ((eq processing-type 'mathjax)
18951 ;; Prepare for MathJax processing.
18952 (if (not (string-match "\\`\\$\\$?" value))
18953 (goto-char end)
18954 (delete-region beg end)
18955 (if (string= (match-string 0 value) "$$")
18956 (insert "\\[" (substring value 2 -2) "\\]")
18957 (insert "\\(" (substring value 1 -1) "\\)"))))
18958 ((assq processing-type org-preview-latex-process-alist)
18959 ;; Process to an image.
18960 (cl-incf cnt)
18961 (goto-char beg)
18962 (let* ((processing-info
18963 (cdr (assq processing-type org-preview-latex-process-alist)))
18964 (face (face-at-point))
18965 ;; Get the colors from the face at point.
18967 (let ((color (plist-get org-format-latex-options
18968 :foreground)))
18969 (if (and forbuffer (eq color 'auto))
18970 (face-attribute face :foreground nil 'default)
18971 color)))
18973 (let ((color (plist-get org-format-latex-options
18974 :background)))
18975 (if (and forbuffer (eq color 'auto))
18976 (face-attribute face :background nil 'default)
18977 color)))
18978 (hash (sha1 (prin1-to-string
18979 (list org-format-latex-header
18980 org-latex-default-packages-alist
18981 org-latex-packages-alist
18982 org-format-latex-options
18983 forbuffer value fg bg))))
18984 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18985 (absprefix (expand-file-name prefix dir))
18986 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18987 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18988 (sep (and block-type "\n\n"))
18989 (link (concat sep "[[file:" linkfile "]]" sep))
18990 (options
18991 (org-combine-plists
18992 org-format-latex-options
18993 `(:foreground ,fg :background ,bg))))
18994 (when msg (message msg cnt))
18995 (unless checkdir-flag ; Ensure the directory exists.
18996 (setq checkdir-flag t)
18997 (let ((todir (file-name-directory absprefix)))
18998 (unless (file-directory-p todir)
18999 (make-directory todir t))))
19000 (unless (file-exists-p movefile)
19001 (org-create-formula-image
19002 value movefile options forbuffer processing-type))
19003 (if overlays
19004 (progn
19005 (dolist (o (overlays-in beg end))
19006 (when (eq (overlay-get o 'org-overlay-type)
19007 'org-latex-overlay)
19008 (delete-overlay o)))
19009 (org--format-latex-make-overlay beg end movefile imagetype)
19010 (goto-char end))
19011 (delete-region beg end)
19012 (insert
19013 (org-add-props link
19014 (list 'org-latex-src
19015 (replace-regexp-in-string "\"" "" value)
19016 'org-latex-src-embed-type
19017 (if block-type 'paragraph 'character)))))))
19018 ((eq processing-type 'mathml)
19019 ;; Process to MathML.
19020 (unless (org-format-latex-mathml-available-p)
19021 (user-error "LaTeX to MathML converter not configured"))
19022 (cl-incf cnt)
19023 (when msg (message msg cnt))
19024 (goto-char beg)
19025 (delete-region beg end)
19026 (insert (org-format-latex-as-mathml
19027 value block-type prefix dir)))
19029 (error "Unknown conversion process %s for LaTeX fragments"
19030 processing-type)))))))))))
19032 (defun org-create-math-formula (latex-frag &optional mathml-file)
19033 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19034 Use `org-latex-to-mathml-convert-command'. If the conversion is
19035 sucessful, return the portion between \"<math...> </math>\"
19036 elements otherwise return nil. When MATHML-FILE is specified,
19037 write the results in to that file. When invoked as an
19038 interactive command, prompt for LATEX-FRAG, with initial value
19039 set to the current active region and echo the results for user
19040 inspection."
19041 (interactive (list (let ((frag (when (org-region-active-p)
19042 (buffer-substring-no-properties
19043 (region-beginning) (region-end)))))
19044 (read-string "LaTeX Fragment: " frag nil frag))))
19045 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19046 (let* ((tmp-in-file
19047 (let ((file (file-relative-name
19048 (make-temp-name (expand-file-name "ltxmathml-in")))))
19049 (write-region latex-frag nil file)
19050 file))
19051 (tmp-out-file (file-relative-name
19052 (make-temp-name (expand-file-name "ltxmathml-out"))))
19053 (cmd (format-spec
19054 org-latex-to-mathml-convert-command
19055 `((?j . ,(and org-latex-to-mathml-jar-file
19056 (shell-quote-argument
19057 (expand-file-name
19058 org-latex-to-mathml-jar-file))))
19059 (?I . ,(shell-quote-argument tmp-in-file))
19060 (?i . ,latex-frag)
19061 (?o . ,(shell-quote-argument tmp-out-file)))))
19062 mathml shell-command-output)
19063 (when (called-interactively-p 'any)
19064 (unless (org-format-latex-mathml-available-p)
19065 (user-error "LaTeX to MathML converter not configured")))
19066 (message "Running %s" cmd)
19067 (setq shell-command-output (shell-command-to-string cmd))
19068 (setq mathml
19069 (when (file-readable-p tmp-out-file)
19070 (with-current-buffer (find-file-noselect tmp-out-file t)
19071 (goto-char (point-min))
19072 (when (re-search-forward
19073 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19074 (regexp-quote
19075 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19076 nil t)
19077 (prog1 (match-string 0) (kill-buffer))))))
19078 (cond
19079 (mathml
19080 (setq mathml
19081 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19082 (when mathml-file
19083 (write-region mathml nil mathml-file))
19084 (when (called-interactively-p 'any)
19085 (message mathml)))
19086 ((message "LaTeX to MathML conversion failed")
19087 (message shell-command-output)))
19088 (delete-file tmp-in-file)
19089 (when (file-exists-p tmp-out-file)
19090 (delete-file tmp-out-file))
19091 mathml))
19093 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19094 prefix &optional dir)
19095 "Use `org-create-math-formula' but check local cache first."
19096 (let* ((absprefix (expand-file-name prefix dir))
19097 (print-length nil) (print-level nil)
19098 (formula-id (concat
19099 "formula-"
19100 (sha1
19101 (prin1-to-string
19102 (list latex-frag
19103 org-latex-to-mathml-convert-command)))))
19104 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19105 (formula-cache-dir (file-name-directory formula-cache)))
19107 (unless (file-directory-p formula-cache-dir)
19108 (make-directory formula-cache-dir t))
19110 (unless (file-exists-p formula-cache)
19111 (org-create-math-formula latex-frag formula-cache))
19113 (if (file-exists-p formula-cache)
19114 ;; Successful conversion. Return the link to MathML file.
19115 (org-add-props
19116 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19117 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19118 'org-latex-src-embed-type (if latex-frag-type
19119 'paragraph 'character)))
19120 ;; Failed conversion. Return the LaTeX fragment verbatim
19121 latex-frag)))
19123 (defun org--get-display-dpi ()
19124 "Get the DPI of the display.
19125 The function assumes that the display has the same pixel width in
19126 the horizontal and vertical directions."
19127 (if (display-graphic-p)
19128 (round (/ (display-pixel-height)
19129 (/ (display-mm-height) 25.4)))
19130 (error "Attempt to calculate the dpi of a non-graphic display")))
19132 (defun org-create-formula-image
19133 (string tofile options buffer &optional processing-type)
19134 "Create an image from LaTeX source using external processes.
19136 The LaTeX STRING is saved to a temporary LaTeX file, then
19137 converted to an image file by process PROCESSING-TYPE defined in
19138 `org-preview-latex-process-alist'. A nil value defaults to
19139 `org-preview-latex-default-process'.
19141 The generated image file is eventually moved to TOFILE.
19143 The OPTIONS argument controls the size, foreground color and
19144 background color of the generated image.
19146 When BUFFER non-nil, this function is used for LaTeX previewing.
19147 Otherwise, it is used to deal with LaTeX snippets showed in
19148 a HTML file."
19149 (let* ((processing-type (or processing-type
19150 org-preview-latex-default-process))
19151 (processing-info
19152 (cdr (assq processing-type org-preview-latex-process-alist)))
19153 (programs (plist-get processing-info :programs))
19154 (error-message (or (plist-get processing-info :message) ""))
19155 (use-xcolor (plist-get processing-info :use-xcolor))
19156 (image-input-type (plist-get processing-info :image-input-type))
19157 (image-output-type (plist-get processing-info :image-output-type))
19158 (post-clean (or (plist-get processing-info :post-clean)
19159 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19160 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19161 (latex-header
19162 (or (plist-get processing-info :latex-header)
19163 (org-latex-make-preamble
19164 (org-export-get-environment (org-export-get-backend 'latex))
19165 org-format-latex-header
19166 'snippet)))
19167 (latex-compiler (plist-get processing-info :latex-compiler))
19168 (image-converter (plist-get processing-info :image-converter))
19169 (tmpdir temporary-file-directory)
19170 (texfilebase (make-temp-name
19171 (expand-file-name "orgtex" tmpdir)))
19172 (texfile (concat texfilebase ".tex"))
19173 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19174 '(1.0 . 1.0)))
19175 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19176 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19177 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19178 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19179 "Black"))
19180 (bg (or (plist-get options (if buffer :background :html-background))
19181 "Transparent"))
19182 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19183 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19184 (dolist (program programs)
19185 (org-check-external-command program error-message))
19186 (if use-xcolor
19187 (progn (if (eq fg 'default)
19188 (setq fg (org-latex-color :foreground))
19189 (setq fg (org-latex-color-format fg)))
19190 (if (eq bg 'default)
19191 (setq bg (org-latex-color :background))
19192 (setq bg (org-latex-color-format
19193 (if (string= bg "Transparent") "white" bg))))
19194 (with-temp-file texfile
19195 (insert latex-header)
19196 (insert "\n\\begin{document}\n"
19197 "\\definecolor{fg}{rgb}{" fg "}\n"
19198 "\\definecolor{bg}{rgb}{" bg "}\n"
19199 "\n\\pagecolor{bg}\n"
19200 "\n{\\color{fg}\n"
19201 string
19202 "\n}\n"
19203 "\n\\end{document}\n")))
19204 (if (eq fg 'default)
19205 (setq fg (org-dvipng-color :foreground))
19206 (unless (string= fg "Transparent")
19207 (setq fg (org-dvipng-color-format fg))))
19208 (if (eq bg 'default)
19209 (setq bg (org-dvipng-color :background))
19210 (unless (string= bg "Transparent")
19211 (setq bg (org-dvipng-color-format bg))))
19212 (with-temp-file texfile
19213 (insert latex-header)
19214 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19216 (let* ((err-msg (format "Please adjust '%s' part of \
19217 `org-preview-latex-process-alist'."
19218 processing-type))
19219 (image-input-file
19220 (org-compile-file
19221 texfile latex-compiler image-input-type err-msg log-buf))
19222 (image-output-file
19223 (org-compile-file
19224 image-input-file image-converter image-output-type err-msg log-buf
19225 `((?F . ,(shell-quote-argument fg))
19226 (?B . ,(shell-quote-argument bg))
19227 (?D . ,(shell-quote-argument (format "%s" dpi)))
19228 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19229 (copy-file image-output-file tofile 'replace)
19230 (dolist (e post-clean)
19231 (when (file-exists-p (concat texfilebase e))
19232 (delete-file (concat texfilebase e))))
19233 image-output-file)))
19235 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19236 "Fill a LaTeX header template TPL.
19237 In the template, the following place holders will be recognized:
19239 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19240 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19241 [PACKAGES] \\usepackage statements for PKG
19242 [NO-PACKAGES] do not include PKG
19243 [EXTRA] the string EXTRA
19244 [NO-EXTRA] do not include EXTRA
19246 For backward compatibility, if both the positive and the negative place
19247 holder is missing, the positive one (without the \"NO-\") will be
19248 assumed to be present at the end of the template.
19249 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19250 EXTRA is a string.
19251 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19252 (let (rpl (end ""))
19253 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19254 (setq rpl (if (or (match-end 1) (not def-pkg))
19255 "" (org-latex-packages-to-string def-pkg snippets-p t))
19256 tpl (replace-match rpl t t tpl))
19257 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19259 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19260 (setq rpl (if (or (match-end 1) (not pkg))
19261 "" (org-latex-packages-to-string pkg snippets-p t))
19262 tpl (replace-match rpl t t tpl))
19263 (when pkg (setq end
19264 (concat end "\n"
19265 (org-latex-packages-to-string pkg snippets-p)))))
19267 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19268 (setq rpl (if (or (match-end 1) (not extra))
19269 "" (concat extra "\n"))
19270 tpl (replace-match rpl t t tpl))
19271 (when (and extra (string-match "\\S-" extra))
19272 (setq end (concat end "\n" extra))))
19274 (if (string-match "\\S-" end)
19275 (concat tpl "\n" end)
19276 tpl)))
19278 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19279 "Turn an alist of packages into a string with the \\usepackage macros."
19280 (setq pkg (mapconcat (lambda(p)
19281 (cond
19282 ((stringp p) p)
19283 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19284 (format "%% Package %s omitted" (cadr p)))
19285 ((equal "" (car p))
19286 (format "\\usepackage{%s}" (cadr p)))
19288 (format "\\usepackage[%s]{%s}"
19289 (car p) (cadr p)))))
19291 "\n"))
19292 (if newline (concat pkg "\n") pkg))
19294 (defun org-dvipng-color (attr)
19295 "Return a RGB color specification for dvipng."
19296 (org-dvipng-color-format (face-attribute 'default attr nil)))
19298 (defun org-dvipng-color-format (color-name)
19299 "Convert COLOR-NAME to a RGB color value for dvipng."
19300 (apply #'format "rgb %s %s %s"
19301 (mapcar 'org-normalize-color
19302 (color-values color-name))))
19304 (defun org-latex-color (attr)
19305 "Return a RGB color for the LaTeX color package."
19306 (org-latex-color-format (face-attribute 'default attr nil)))
19308 (defun org-latex-color-format (color-name)
19309 "Convert COLOR-NAME to a RGB color value."
19310 (apply #'format "%s,%s,%s"
19311 (mapcar 'org-normalize-color
19312 (color-values color-name))))
19314 (defun org-normalize-color (value)
19315 "Return string to be used as color value for an RGB component."
19316 (format "%g" (/ value 65535.0)))
19320 ;; Image display
19322 (defvar-local org-inline-image-overlays nil)
19324 (defun org-toggle-inline-images (&optional include-linked)
19325 "Toggle the display of inline images.
19326 INCLUDE-LINKED is passed to `org-display-inline-images'."
19327 (interactive "P")
19328 (if org-inline-image-overlays
19329 (progn
19330 (org-remove-inline-images)
19331 (when (called-interactively-p 'interactive)
19332 (message "Inline image display turned off")))
19333 (org-display-inline-images include-linked)
19334 (when (called-interactively-p 'interactive)
19335 (message (if org-inline-image-overlays
19336 (format "%d images displayed inline"
19337 (length org-inline-image-overlays))
19338 "No images to display inline")))))
19340 (defun org-redisplay-inline-images ()
19341 "Refresh the display of inline images."
19342 (interactive)
19343 (if (not org-inline-image-overlays)
19344 (org-toggle-inline-images)
19345 (org-toggle-inline-images)
19346 (org-toggle-inline-images)))
19348 (defun org-display-inline-images (&optional include-linked refresh beg end)
19349 "Display inline images.
19351 An inline image is a link which follows either of these
19352 conventions:
19354 1. Its path is a file with an extension matching return value
19355 from `image-file-name-regexp' and it has no contents.
19357 2. Its description consists in a single link of the previous
19358 type.
19360 When optional argument INCLUDE-LINKED is non-nil, also links with
19361 a text description part will be inlined. This can be nice for
19362 a quick look at those images, but it does not reflect what
19363 exported files will look like.
19365 When optional argument REFRESH is non-nil, refresh existing
19366 images between BEG and END. This will create new image displays
19367 only if necessary. BEG and END default to the buffer
19368 boundaries."
19369 (interactive "P")
19370 (when (display-graphic-p)
19371 (unless refresh
19372 (org-remove-inline-images)
19373 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19374 (org-with-wide-buffer
19375 (goto-char (or beg (point-min)))
19376 (let ((case-fold-search t)
19377 (file-extension-re (image-file-name-regexp)))
19378 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19379 (let ((link (save-match-data (org-element-context))))
19380 ;; Check if we're at an inline image.
19381 (when (and (equal (org-element-property :type link) "file")
19382 (or include-linked
19383 (not (org-element-property :contents-begin link)))
19384 (let ((parent (org-element-property :parent link)))
19385 (or (not (eq (org-element-type parent) 'link))
19386 (not (cdr (org-element-contents parent)))))
19387 (string-match-p file-extension-re
19388 (org-element-property :path link)))
19389 (let ((file (expand-file-name
19390 (org-link-unescape
19391 (org-element-property :path link)))))
19392 (when (file-exists-p file)
19393 (let ((width
19394 ;; Apply `org-image-actual-width' specifications.
19395 (cond
19396 ((not (image-type-available-p 'imagemagick)) nil)
19397 ((eq org-image-actual-width t) nil)
19398 ((listp org-image-actual-width)
19400 ;; First try to find a width among
19401 ;; attributes associated to the paragraph
19402 ;; containing link.
19403 (let ((paragraph
19404 (let ((e link))
19405 (while (and (setq e (org-element-property
19406 :parent e))
19407 (not (eq (org-element-type e)
19408 'paragraph))))
19409 e)))
19410 (when paragraph
19411 (save-excursion
19412 (goto-char (org-element-property :begin paragraph))
19413 (when
19414 (re-search-forward
19415 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19416 (org-element-property
19417 :post-affiliated paragraph)
19419 (string-to-number (match-string 1))))))
19420 ;; Otherwise, fall-back to provided number.
19421 (car org-image-actual-width)))
19422 ((numberp org-image-actual-width)
19423 org-image-actual-width)))
19424 (old (get-char-property-and-overlay
19425 (org-element-property :begin link)
19426 'org-image-overlay)))
19427 (if (and (car-safe old) refresh)
19428 (image-refresh (overlay-get (cdr old) 'display))
19429 (let ((image (create-image file
19430 (and width 'imagemagick)
19432 :width width)))
19433 (when image
19434 (let* ((link
19435 ;; If inline image is the description
19436 ;; of another link, be sure to
19437 ;; consider the latter as the one to
19438 ;; apply the overlay on.
19439 (let ((parent
19440 (org-element-property :parent link)))
19441 (if (eq (org-element-type parent) 'link)
19442 parent
19443 link)))
19444 (ov (make-overlay
19445 (org-element-property :begin link)
19446 (progn
19447 (goto-char
19448 (org-element-property :end link))
19449 (skip-chars-backward " \t")
19450 (point)))))
19451 (overlay-put ov 'display image)
19452 (overlay-put ov 'face 'default)
19453 (overlay-put ov 'org-image-overlay t)
19454 (overlay-put
19455 ov 'modification-hooks
19456 (list 'org-display-inline-remove-overlay))
19457 (push ov org-inline-image-overlays)))))))))))))))
19459 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19460 "Remove inline-display overlay if a corresponding region is modified."
19461 (let ((inhibit-modification-hooks t))
19462 (when (and ov after)
19463 (delete ov org-inline-image-overlays)
19464 (delete-overlay ov))))
19466 (defun org-remove-inline-images ()
19467 "Remove inline display of images."
19468 (interactive)
19469 (mapc #'delete-overlay org-inline-image-overlays)
19470 (setq org-inline-image-overlays nil))
19472 ;;;; Key bindings
19474 ;; Outline functions from `outline-mode-prefix-map'
19475 ;; that can be remapped in Org:
19476 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19477 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19478 (define-key org-mode-map [remap outline-forward-same-level]
19479 'org-forward-heading-same-level)
19480 (define-key org-mode-map [remap outline-backward-same-level]
19481 'org-backward-heading-same-level)
19482 (define-key org-mode-map [remap outline-show-branches]
19483 'org-kill-note-or-show-branches)
19484 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19485 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19486 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19487 (define-key org-mode-map [remap outline-next-visible-heading]
19488 'org-next-visible-heading)
19489 (define-key org-mode-map [remap outline-previous-visible-heading]
19490 'org-previous-visible-heading)
19491 (define-key org-mode-map [remap show-children] 'org-show-children)
19493 ;; Outline functions from `outline-mode-prefix-map' that can not
19494 ;; be remapped in Org:
19496 ;; - the column "key binding" shows whether the Outline function is still
19497 ;; available in Org mode on the same key that it has been bound to in
19498 ;; Outline mode:
19499 ;; - "overridden": key used for a different functionality in Org mode
19500 ;; - else: key still bound to the same Outline function in Org mode
19502 ;; | Outline function | key binding | Org replacement |
19503 ;; |------------------------------------+-------------+--------------------------|
19504 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19505 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19506 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19507 ;; | `show-entry' | overridden | no replacement |
19508 ;; | `show-branches' | `C-c C-k' | still same function |
19509 ;; | `show-subtree' | overridden | visibility cycling |
19510 ;; | `show-all' | overridden | no replacement |
19511 ;; | `hide-subtree' | overridden | visibility cycling |
19512 ;; | `hide-body' | overridden | no replacement |
19513 ;; | `hide-entry' | overridden | visibility cycling |
19514 ;; | `hide-leaves' | overridden | no replacement |
19515 ;; | `hide-sublevels' | overridden | no replacement |
19516 ;; | `hide-other' | overridden | no replacement |
19518 ;; Make `C-c C-x' a prefix key
19519 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19521 ;; TAB key with modifiers
19522 (org-defkey org-mode-map "\C-i" 'org-cycle)
19523 (org-defkey org-mode-map [(tab)] 'org-cycle)
19524 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19525 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19526 ;; The following line is necessary under Suse GNU/Linux
19527 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19528 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19529 (define-key org-mode-map [backtab] 'org-shifttab)
19531 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19532 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19533 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19535 ;; Cursor keys with modifiers
19536 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19537 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19538 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19539 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19541 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19542 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19543 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19544 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19545 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19546 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19548 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19549 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19550 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19551 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19553 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19554 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19555 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19556 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19558 ;; Babel keys
19559 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19560 (dolist (pair org-babel-key-bindings)
19561 (define-key org-babel-map (car pair) (cdr pair)))
19563 ;;; Extra keys for tty access.
19564 ;; We only set them when really needed because otherwise the
19565 ;; menus don't show the simple keys
19567 (when (or org-use-extra-keys (not window-system))
19568 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19569 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19570 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19571 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19572 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19573 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19574 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19575 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19576 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19577 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19578 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19579 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19580 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19581 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19582 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19583 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19584 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19585 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19586 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19587 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19588 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19589 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19590 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19591 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19592 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19593 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19594 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19595 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19597 ;; All the other keys
19599 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19600 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19601 (if (boundp 'narrow-map)
19602 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19603 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19604 (if (boundp 'narrow-map)
19605 (org-defkey narrow-map "b" 'org-narrow-to-block)
19606 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19607 (if (boundp 'narrow-map)
19608 (org-defkey narrow-map "e" 'org-narrow-to-element)
19609 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19610 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19611 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19612 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19613 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19614 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19615 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19616 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19617 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19618 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19619 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19620 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19621 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19622 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19623 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19624 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19625 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19626 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19627 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19628 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19629 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19630 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19631 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19632 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19633 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19634 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19635 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19636 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19637 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19638 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19639 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19640 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19641 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19642 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19643 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19644 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19645 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19646 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19647 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19648 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19649 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19650 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19651 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19652 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19653 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19654 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19655 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19656 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19657 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19658 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19659 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19660 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19661 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19662 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19663 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19664 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19665 (org-defkey org-mode-map "\C-c^" 'org-sort)
19666 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19667 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19668 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19669 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19670 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19671 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19672 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19673 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19674 (org-defkey org-mode-map "\C-m" 'org-return)
19675 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19676 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19677 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19678 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19679 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19680 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19681 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19682 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19683 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19684 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19685 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19686 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19687 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19688 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19689 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19690 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19691 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19692 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19693 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19694 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19695 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19696 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19697 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19698 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19699 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19701 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19702 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19703 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19705 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19706 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19707 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19708 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19709 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19710 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19711 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19712 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19713 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19714 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19715 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19716 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19717 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19718 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19719 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19720 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19721 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19722 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19723 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19724 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19725 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19726 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19728 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19729 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19730 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19731 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19732 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19734 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19736 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19738 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19739 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19741 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19744 (defconst org-speed-commands-default
19746 ("Outline Navigation")
19747 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19748 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19749 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19750 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19751 ("F" . org-next-block)
19752 ("B" . org-previous-block)
19753 ("u" . (org-speed-move-safe 'outline-up-heading))
19754 ("j" . org-goto)
19755 ("g" . (org-refile t))
19756 ("Outline Visibility")
19757 ("c" . org-cycle)
19758 ("C" . org-shifttab)
19759 (" " . org-display-outline-path)
19760 ("s" . org-narrow-to-subtree)
19761 ("=" . org-columns)
19762 ("Outline Structure Editing")
19763 ("U" . org-metaup)
19764 ("D" . org-metadown)
19765 ("r" . org-metaright)
19766 ("l" . org-metaleft)
19767 ("R" . org-shiftmetaright)
19768 ("L" . org-shiftmetaleft)
19769 ("i" . (progn (forward-char 1) (call-interactively
19770 'org-insert-heading-respect-content)))
19771 ("^" . org-sort)
19772 ("w" . org-refile)
19773 ("a" . org-archive-subtree-default-with-confirmation)
19774 ("@" . org-mark-subtree)
19775 ("#" . org-toggle-comment)
19776 ("Clock Commands")
19777 ("I" . org-clock-in)
19778 ("O" . org-clock-out)
19779 ("Meta Data Editing")
19780 ("t" . org-todo)
19781 ("," . (org-priority))
19782 ("0" . (org-priority ?\ ))
19783 ("1" . (org-priority ?A))
19784 ("2" . (org-priority ?B))
19785 ("3" . (org-priority ?C))
19786 (":" . org-set-tags-command)
19787 ("e" . org-set-effort)
19788 ("E" . org-inc-effort)
19789 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19790 (org-entry-put (point) "APPT_WARNTIME" m)))
19791 ("Agenda Views etc")
19792 ("v" . org-agenda)
19793 ("/" . org-sparse-tree)
19794 ("Misc")
19795 ("o" . org-open-at-point)
19796 ("?" . org-speed-command-help)
19797 ("<" . (org-agenda-set-restriction-lock 'subtree))
19798 (">" . (org-agenda-remove-restriction-lock))
19800 "The default speed commands.")
19802 (defun org-print-speed-command (e)
19803 (if (> (length (car e)) 1)
19804 (progn
19805 (princ "\n")
19806 (princ (car e))
19807 (princ "\n")
19808 (princ (make-string (length (car e)) ?-))
19809 (princ "\n"))
19810 (princ (car e))
19811 (princ " ")
19812 (if (symbolp (cdr e))
19813 (princ (symbol-name (cdr e)))
19814 (prin1 (cdr e)))
19815 (princ "\n")))
19817 (defun org-speed-command-help ()
19818 "Show the available speed commands."
19819 (interactive)
19820 (if (not org-use-speed-commands)
19821 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19822 (with-output-to-temp-buffer "*Help*"
19823 (princ "User-defined Speed commands\n===========================\n")
19824 (mapc #'org-print-speed-command org-speed-commands-user)
19825 (princ "\n")
19826 (princ "Built-in Speed commands\n=======================\n")
19827 (mapc #'org-print-speed-command org-speed-commands-default))
19828 (with-current-buffer "*Help*"
19829 (setq truncate-lines t))))
19831 (defun org-speed-move-safe (cmd)
19832 "Execute CMD, but make sure that the cursor always ends up in a headline.
19833 If not, return to the original position and throw an error."
19834 (interactive)
19835 (let ((pos (point)))
19836 (call-interactively cmd)
19837 (unless (and (bolp) (org-at-heading-p))
19838 (goto-char pos)
19839 (error "Boundary reached while executing %s" cmd))))
19841 (defvar org-self-insert-command-undo-counter 0)
19843 (defvar org-table-auto-blank-field) ; defined in org-table.el
19844 (defvar org-speed-command nil)
19846 (defun org-speed-command-activate (keys)
19847 "Hook for activating single-letter speed commands.
19848 `org-speed-commands-default' specifies a minimal command set.
19849 Use `org-speed-commands-user' for further customization."
19850 (when (or (and (bolp) (looking-at org-outline-regexp))
19851 (and (functionp org-use-speed-commands)
19852 (funcall org-use-speed-commands)))
19853 (cdr (assoc keys (append org-speed-commands-user
19854 org-speed-commands-default)))))
19856 (defun org-babel-speed-command-activate (keys)
19857 "Hook for activating single-letter code block commands."
19858 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19859 (cdr (assoc keys org-babel-key-bindings))))
19861 (defcustom org-speed-command-hook
19862 '(org-speed-command-activate org-babel-speed-command-activate)
19863 "Hook for activating speed commands at strategic locations.
19864 Hook functions are called in sequence until a valid handler is
19865 found.
19867 Each hook takes a single argument, a user-pressed command key
19868 which is also a `self-insert-command' from the global map.
19870 Within the hook, examine the cursor position and the command key
19871 and return nil or a valid handler as appropriate. Handler could
19872 be one of an interactive command, a function, or a form.
19874 Set `org-use-speed-commands' to non-nil value to enable this
19875 hook. The default setting is `org-speed-command-activate'."
19876 :group 'org-structure
19877 :version "24.1"
19878 :type 'hook)
19880 (defun org-self-insert-command (N)
19881 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19882 If the cursor is in a table looking at whitespace, the whitespace is
19883 overwritten, and the table is not marked as requiring realignment."
19884 (interactive "p")
19885 (org-check-before-invisible-edit 'insert)
19886 (cond
19887 ((and org-use-speed-commands
19888 (let ((kv (this-command-keys-vector)))
19889 (setq org-speed-command
19890 (run-hook-with-args-until-success
19891 'org-speed-command-hook
19892 (make-string 1 (aref kv (1- (length kv))))))))
19893 (cond
19894 ((commandp org-speed-command)
19895 (setq this-command org-speed-command)
19896 (call-interactively org-speed-command))
19897 ((functionp org-speed-command)
19898 (funcall org-speed-command))
19899 ((and org-speed-command (listp org-speed-command))
19900 (eval org-speed-command))
19901 (t (let (org-use-speed-commands)
19902 (call-interactively 'org-self-insert-command)))))
19903 ((and
19904 (org-at-table-p)
19905 (progn
19906 ;; Check if we blank the field, and if that triggers align.
19907 (and (featurep 'org-table) org-table-auto-blank-field
19908 (memq last-command
19909 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19910 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19911 ;; Got extra space, this field does not determine
19912 ;; column width.
19913 (let (org-table-may-need-update) (org-table-blank-field))
19914 ;; No extra space, this field may determine column
19915 ;; width.
19916 (org-table-blank-field)))
19918 (eq N 1)
19919 (looking-at "[^|\n]* \\( \\)|"))
19920 ;; There is room for insertion without re-aligning the table.
19921 (delete-region (match-beginning 1) (match-end 1))
19922 (self-insert-command N))
19924 (setq org-table-may-need-update t)
19925 (self-insert-command N)
19926 (org-fix-tags-on-the-fly)
19927 (when org-self-insert-cluster-for-undo
19928 (if (not (eq last-command 'org-self-insert-command))
19929 (setq org-self-insert-command-undo-counter 1)
19930 (if (>= org-self-insert-command-undo-counter 20)
19931 (setq org-self-insert-command-undo-counter 1)
19932 (and (> org-self-insert-command-undo-counter 0)
19933 buffer-undo-list (listp buffer-undo-list)
19934 (not (cadr buffer-undo-list)) ; remove nil entry
19935 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19936 (setq org-self-insert-command-undo-counter
19937 (1+ org-self-insert-command-undo-counter))))))))
19939 (defun org-check-before-invisible-edit (kind)
19940 "Check is editing if kind KIND would be dangerous with invisible text around.
19941 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19942 ;; First, try to get out of here as quickly as possible, to reduce overhead
19943 (when (and org-catch-invisible-edits
19944 (or (not (boundp 'visible-mode)) (not visible-mode))
19945 (or (get-char-property (point) 'invisible)
19946 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19947 ;; OK, we need to take a closer look
19948 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19949 (invisible-before-point (unless (bobp) (get-char-property
19950 (1- (point)) 'invisible)))
19951 (border-and-ok-direction
19953 ;; Check if we are acting predictably before invisible text
19954 (and invisible-at-point (not invisible-before-point)
19955 (memq kind '(insert delete-backward)))
19956 ;; Check if we are acting predictably after invisible text
19957 ;; This works not well, and I have turned it off. It seems
19958 ;; better to always show and stop after invisible text.
19959 ;; (and (not invisible-at-point) invisible-before-point
19960 ;; (memq kind '(insert delete)))
19962 (when (or (memq invisible-at-point '(outline org-hide-block t))
19963 (memq invisible-before-point '(outline org-hide-block t)))
19964 (when (eq org-catch-invisible-edits 'error)
19965 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19966 (if (and org-custom-properties-overlays
19967 (y-or-n-p "Display invisible properties in this buffer? "))
19968 (org-toggle-custom-properties-visibility)
19969 ;; Make the area visible
19970 (save-excursion
19971 (when invisible-before-point
19972 (goto-char (previous-single-char-property-change
19973 (point) 'invisible)))
19974 (outline-show-subtree))
19975 (cond
19976 ((eq org-catch-invisible-edits 'show)
19977 ;; That's it, we do the edit after showing
19978 (message
19979 "Unfolding invisible region around point before editing")
19980 (sit-for 1))
19981 ((and (eq org-catch-invisible-edits 'smart)
19982 border-and-ok-direction)
19983 (message "Unfolding invisible region around point before editing"))
19985 ;; Don't do the edit, make the user repeat it in full visibility
19986 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19988 (defun org-fix-tags-on-the-fly ()
19989 "Align tags in headline at point.
19990 Unlike to `org-set-tags', it ignores region and sorting."
19991 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19992 (org-at-heading-p))
19993 (let ((org-ignore-region t)
19994 (org-tags-sort-function nil))
19995 (org-set-tags nil t))))
19997 (defun org-delete-backward-char (N)
19998 "Like `delete-backward-char', insert whitespace at field end in tables.
19999 When deleting backwards, in tables this function will insert whitespace in
20000 front of the next \"|\" separator, to keep the table aligned. The table will
20001 still be marked for re-alignment if the field did fill the entire column,
20002 because, in this case the deletion might narrow the column."
20003 (interactive "p")
20004 (save-match-data
20005 (org-check-before-invisible-edit 'delete-backward)
20006 (if (and (org-at-table-p)
20007 (eq N 1)
20008 (string-match "|" (buffer-substring (point-at-bol) (point)))
20009 (looking-at ".*?|"))
20010 (let ((pos (point))
20011 (noalign (looking-at "[^|\n\r]* |"))
20012 (c org-table-may-need-update))
20013 (backward-delete-char N)
20014 (unless overwrite-mode
20015 (skip-chars-forward "^|")
20016 (insert " ")
20017 (goto-char (1- pos)))
20018 ;; noalign: if there were two spaces at the end, this field
20019 ;; does not determine the width of the column.
20020 (when noalign (setq org-table-may-need-update c)))
20021 (backward-delete-char N)
20022 (org-fix-tags-on-the-fly))))
20024 (defun org-delete-char (N)
20025 "Like `delete-char', but insert whitespace at field end in tables.
20026 When deleting characters, in tables this function will insert whitespace in
20027 front of the next \"|\" separator, to keep the table aligned. The table will
20028 still be marked for re-alignment if the field did fill the entire column,
20029 because, in this case the deletion might narrow the column."
20030 (interactive "p")
20031 (save-match-data
20032 (org-check-before-invisible-edit 'delete)
20033 (if (and (org-at-table-p)
20034 (not (bolp))
20035 (not (= (char-after) ?|))
20036 (eq N 1))
20037 (if (looking-at ".*?|")
20038 (let ((pos (point))
20039 (noalign (looking-at "[^|\n\r]* |"))
20040 (c org-table-may-need-update))
20041 (replace-match
20042 (concat (substring (match-string 0) 1 -1) " |") nil t)
20043 (goto-char pos)
20044 ;; noalign: if there were two spaces at the end, this field
20045 ;; does not determine the width of the column.
20046 (when noalign (setq org-table-may-need-update c)))
20047 (delete-char N))
20048 (delete-char N)
20049 (org-fix-tags-on-the-fly))))
20051 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20052 (put 'org-self-insert-command 'delete-selection
20053 (lambda ()
20054 (not (run-hook-with-args-until-success
20055 'self-insert-uses-region-functions))))
20056 (put 'orgtbl-self-insert-command 'delete-selection
20057 (lambda ()
20058 (not (run-hook-with-args-until-success
20059 'self-insert-uses-region-functions))))
20060 (put 'org-delete-char 'delete-selection 'supersede)
20061 (put 'org-delete-backward-char 'delete-selection 'supersede)
20062 (put 'org-yank 'delete-selection 'yank)
20064 ;; Make `flyspell-mode' delay after some commands
20065 (put 'org-self-insert-command 'flyspell-delayed t)
20066 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20067 (put 'org-delete-char 'flyspell-delayed t)
20068 (put 'org-delete-backward-char 'flyspell-delayed t)
20070 ;; Make pabbrev-mode expand after Org mode commands
20071 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20072 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20074 (defun org-remap (map &rest commands)
20075 "In MAP, remap the functions given in COMMANDS.
20076 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20077 (let (new old)
20078 (while commands
20079 (setq old (pop commands) new (pop commands))
20080 (org-defkey map (vector 'remap old) new))))
20082 (defun org-transpose-words ()
20083 "Transpose words for Org.
20084 This uses the `org-mode-transpose-word-syntax-table' syntax
20085 table, which interprets characters in `org-emphasis-alist' as
20086 word constituents."
20087 (interactive)
20088 (with-syntax-table org-mode-transpose-word-syntax-table
20089 (call-interactively 'transpose-words)))
20090 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20092 (when (eq org-enable-table-editor 'optimized)
20093 ;; If the user wants maximum table support, we need to hijack
20094 ;; some standard editing functions
20095 (org-remap org-mode-map
20096 'self-insert-command 'org-self-insert-command
20097 'delete-char 'org-delete-char
20098 'delete-backward-char 'org-delete-backward-char)
20099 (org-defkey org-mode-map "|" 'org-force-self-insert))
20101 (defvar org-ctrl-c-ctrl-c-hook nil
20102 "Hook for functions attaching themselves to `C-c C-c'.
20104 This can be used to add additional functionality to the C-c C-c
20105 key which executes context-dependent commands. This hook is run
20106 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20107 run after the last test.
20109 Each function will be called with no arguments. The function
20110 must check if the context is appropriate for it to act. If yes,
20111 it should do its thing and then return a non-nil value. If the
20112 context is wrong, just do nothing and return nil.")
20114 (defvar org-ctrl-c-ctrl-c-final-hook nil
20115 "Hook for functions attaching themselves to `C-c C-c'.
20117 This can be used to add additional functionality to the C-c C-c
20118 key which executes context-dependent commands. This hook is run
20119 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20120 before the first test.
20122 Each function will be called with no arguments. The function
20123 must check if the context is appropriate for it to act. If yes,
20124 it should do its thing and then return a non-nil value. If the
20125 context is wrong, just do nothing and return nil.")
20127 (defvar org-tab-first-hook nil
20128 "Hook for functions to attach themselves to TAB.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.
20130 This hook runs as the first action when TAB is pressed, even before
20131 `org-cycle' messes around with the `outline-regexp' to cater for
20132 inline tasks and plain list item folding.
20133 If any function in this hook returns t, any other actions that
20134 would have been caused by TAB (such as table field motion or visibility
20135 cycling) will not occur.")
20137 (defvar org-tab-after-check-for-table-hook nil
20138 "Hook for functions to attach themselves to TAB.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.
20140 This hook runs after it has been established that the cursor is not in a
20141 table, but before checking if the cursor is in a headline or if global cycling
20142 should be done.
20143 If any function in this hook returns t, not other actions like visibility
20144 cycling will be done.")
20146 (defvar org-tab-after-check-for-cycling-hook nil
20147 "Hook for functions to attach themselves to TAB.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.
20149 This hook runs after it has been established that not table field motion and
20150 not visibility should be done because of current context. This is probably
20151 the place where a package like yasnippets can hook in.")
20153 (defvar org-tab-before-tab-emulation-hook nil
20154 "Hook for functions to attach themselves to TAB.
20155 See `org-ctrl-c-ctrl-c-hook' for more information.
20156 This hook runs after every other options for TAB have been exhausted, but
20157 before indentation and \t insertion takes place.")
20159 (defvar org-metaleft-hook nil
20160 "Hook for functions attaching themselves to `M-left'.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.")
20162 (defvar org-metaright-hook nil
20163 "Hook for functions attaching themselves to `M-right'.
20164 See `org-ctrl-c-ctrl-c-hook' for more information.")
20165 (defvar org-metaup-hook nil
20166 "Hook for functions attaching themselves to `M-up'.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defvar org-metadown-hook nil
20169 "Hook for functions attaching themselves to `M-down'.
20170 See `org-ctrl-c-ctrl-c-hook' for more information.")
20171 (defvar org-shiftmetaleft-hook nil
20172 "Hook for functions attaching themselves to `M-S-left'.
20173 See `org-ctrl-c-ctrl-c-hook' for more information.")
20174 (defvar org-shiftmetaright-hook nil
20175 "Hook for functions attaching themselves to `M-S-right'.
20176 See `org-ctrl-c-ctrl-c-hook' for more information.")
20177 (defvar org-shiftmetaup-hook nil
20178 "Hook for functions attaching themselves to `M-S-up'.
20179 See `org-ctrl-c-ctrl-c-hook' for more information.")
20180 (defvar org-shiftmetadown-hook nil
20181 "Hook for functions attaching themselves to `M-S-down'.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-metareturn-hook nil
20184 "Hook for functions attaching themselves to `M-RET'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftup-hook nil
20187 "Hook for functions attaching themselves to `S-up'.
20188 See `org-ctrl-c-ctrl-c-hook' for more information.")
20189 (defvar org-shiftup-final-hook nil
20190 "Hook for functions attaching themselves to `S-up'.
20191 This one runs after all other options except shift-select have been excluded.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftdown-hook nil
20194 "Hook for functions attaching themselves to `S-down'.
20195 See `org-ctrl-c-ctrl-c-hook' for more information.")
20196 (defvar org-shiftdown-final-hook nil
20197 "Hook for functions attaching themselves to `S-down'.
20198 This one runs after all other options except shift-select have been excluded.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftleft-hook nil
20201 "Hook for functions attaching themselves to `S-left'.
20202 See `org-ctrl-c-ctrl-c-hook' for more information.")
20203 (defvar org-shiftleft-final-hook nil
20204 "Hook for functions attaching themselves to `S-left'.
20205 This one runs after all other options except shift-select have been excluded.
20206 See `org-ctrl-c-ctrl-c-hook' for more information.")
20207 (defvar org-shiftright-hook nil
20208 "Hook for functions attaching themselves to `S-right'.
20209 See `org-ctrl-c-ctrl-c-hook' for more information.")
20210 (defvar org-shiftright-final-hook nil
20211 "Hook for functions attaching themselves to `S-right'.
20212 This one runs after all other options except shift-select have been excluded.
20213 See `org-ctrl-c-ctrl-c-hook' for more information.")
20215 (defun org-modifier-cursor-error ()
20216 "Throw an error, a modified cursor command was applied in wrong context."
20217 (user-error "This command is active in special context like tables, headlines or items"))
20219 (defun org-shiftselect-error ()
20220 "Throw an error because Shift-Cursor command was applied in wrong context."
20221 (if (and (boundp 'shift-select-mode) shift-select-mode)
20222 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20223 (user-error "This command works only in special context like headlines or timestamps")))
20225 (defun org-call-for-shift-select (cmd)
20226 (let ((this-command-keys-shift-translated t))
20227 (call-interactively cmd)))
20229 (defun org-shifttab (&optional arg)
20230 "Global visibility cycling or move to previous table field.
20231 Call `org-table-previous-field' within a table.
20232 When ARG is nil, cycle globally through visibility states.
20233 When ARG is a numeric prefix, show contents of this level."
20234 (interactive "P")
20235 (cond
20236 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20237 ((integerp arg)
20238 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20239 (message "Content view to level: %d" arg)
20240 (org-content (prefix-numeric-value arg2))
20241 (org-cycle-show-empty-lines t)
20242 (setq org-cycle-global-status 'overview)))
20243 (t (call-interactively 'org-global-cycle))))
20245 (defun org-shiftmetaleft ()
20246 "Promote subtree or delete table column.
20247 Calls `org-promote-subtree', `org-outdent-item-tree', or
20248 `org-table-delete-column', depending on context. See the
20249 individual commands for more information."
20250 (interactive)
20251 (cond
20252 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20253 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20254 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20255 ((if (not (org-region-active-p)) (org-at-item-p)
20256 (save-excursion (goto-char (region-beginning))
20257 (org-at-item-p)))
20258 (call-interactively 'org-outdent-item-tree))
20259 (t (org-modifier-cursor-error))))
20261 (defun org-shiftmetaright ()
20262 "Demote subtree or insert table column.
20263 Calls `org-demote-subtree', `org-indent-item-tree', or
20264 `org-table-insert-column', depending on context. See the
20265 individual commands for more information."
20266 (interactive)
20267 (cond
20268 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20269 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20270 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20271 ((if (not (org-region-active-p)) (org-at-item-p)
20272 (save-excursion (goto-char (region-beginning))
20273 (org-at-item-p)))
20274 (call-interactively 'org-indent-item-tree))
20275 (t (org-modifier-cursor-error))))
20277 (defun org-shiftmetaup (&optional _arg)
20278 "Drag the line at point up.
20279 In a table, kill the current row.
20280 On a clock timestamp, update the value of the timestamp like `S-<up>'
20281 but also adjust the previous clocked item in the clock history.
20282 Everywhere else, drag the line at point up."
20283 (interactive "P")
20284 (cond
20285 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20286 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20287 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20288 (call-interactively 'org-timestamp-up)))
20289 (t (call-interactively 'org-drag-line-backward))))
20291 (defun org-shiftmetadown (&optional _arg)
20292 "Drag the line at point down.
20293 In a table, insert an empty row at the current line.
20294 On a clock timestamp, update the value of the timestamp like `S-<down>'
20295 but also adjust the previous clocked item in the clock history.
20296 Everywhere else, drag the line at point down."
20297 (interactive "P")
20298 (cond
20299 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20300 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20301 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20302 (call-interactively 'org-timestamp-down)))
20303 (t (call-interactively 'org-drag-line-forward))))
20305 (defsubst org-hidden-tree-error ()
20306 (user-error
20307 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20309 (defun org-metaleft (&optional _arg)
20310 "Promote heading, list item at point or move table column left.
20312 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20313 depending on context. With no specific context, calls the Emacs
20314 default `backward-word'. See the individual commands for more
20315 information.
20317 This function runs the hook `org-metaleft-hook' as a first step,
20318 and returns at first non-nil value."
20319 (interactive "P")
20320 (cond
20321 ((run-hook-with-args-until-success 'org-metaleft-hook))
20322 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20323 ((org-with-limited-levels
20324 (or (org-at-heading-p)
20325 (and (org-region-active-p)
20326 (save-excursion
20327 (goto-char (region-beginning))
20328 (org-at-heading-p)))))
20329 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20330 (call-interactively 'org-do-promote))
20331 ;; At an inline task.
20332 ((org-at-heading-p)
20333 (call-interactively 'org-inlinetask-promote))
20334 ((or (org-at-item-p)
20335 (and (org-region-active-p)
20336 (save-excursion
20337 (goto-char (region-beginning))
20338 (org-at-item-p))))
20339 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20340 (call-interactively 'org-outdent-item))
20341 (t (call-interactively 'backward-word))))
20343 (defun org-metaright (&optional _arg)
20344 "Demote heading, list item at point or move table column right.
20346 In front of a drawer or a block keyword, indent it correctly.
20348 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20349 `org-indent-drawer' or `org-indent-block' depending on context.
20350 With no specific context, calls the Emacs default `forward-word'.
20351 See the individual commands for more information.
20353 This function runs the hook `org-metaright-hook' as a first step,
20354 and returns at first non-nil value."
20355 (interactive "P")
20356 (cond
20357 ((run-hook-with-args-until-success 'org-metaright-hook))
20358 ((org-at-table-p) (call-interactively 'org-table-move-column))
20359 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20360 ((org-at-block-p) (call-interactively 'org-indent-block))
20361 ((org-with-limited-levels
20362 (or (org-at-heading-p)
20363 (and (org-region-active-p)
20364 (save-excursion
20365 (goto-char (region-beginning))
20366 (org-at-heading-p)))))
20367 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20368 (call-interactively 'org-do-demote))
20369 ;; At an inline task.
20370 ((org-at-heading-p)
20371 (call-interactively 'org-inlinetask-demote))
20372 ((or (org-at-item-p)
20373 (and (org-region-active-p)
20374 (save-excursion
20375 (goto-char (region-beginning))
20376 (org-at-item-p))))
20377 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20378 (call-interactively 'org-indent-item))
20379 (t (call-interactively 'forward-word))))
20381 (defun org-check-for-hidden (what)
20382 "Check if there are hidden headlines/items in the current visual line.
20383 WHAT can be either `headlines' or `items'. If the current line is
20384 an outline or item heading and it has a folded subtree below it,
20385 this function returns t, nil otherwise."
20386 (let ((re (cond
20387 ((eq what 'headlines) org-outline-regexp-bol)
20388 ((eq what 'items) (org-item-beginning-re))
20389 (t (error "This should not happen"))))
20390 beg end)
20391 (save-excursion
20392 (catch 'exit
20393 (unless (org-region-active-p)
20394 (setq beg (point-at-bol))
20395 (beginning-of-line 2)
20396 (while (and (not (eobp)) ;; this is like `next-line'
20397 (get-char-property (1- (point)) 'invisible))
20398 (beginning-of-line 2))
20399 (setq end (point))
20400 (goto-char beg)
20401 (goto-char (point-at-eol))
20402 (setq end (max end (point)))
20403 (while (re-search-forward re end t)
20404 (when (get-char-property (match-beginning 0) 'invisible)
20405 (throw 'exit t))))
20406 nil))))
20408 (defun org-metaup (&optional _arg)
20409 "Move subtree up or move table row up.
20410 Calls `org-move-subtree-up' or `org-table-move-row' or
20411 `org-move-item-up', depending on context. See the individual commands
20412 for more information."
20413 (interactive "P")
20414 (cond
20415 ((run-hook-with-args-until-success 'org-metaup-hook))
20416 ((org-region-active-p)
20417 (let* ((a (min (region-beginning) (region-end)))
20418 (b (1- (max (region-beginning) (region-end))))
20419 (c (save-excursion (goto-char a)
20420 (move-beginning-of-line 0)))
20421 (d (save-excursion (goto-char a)
20422 (move-end-of-line 0) (point))))
20423 (transpose-regions a b c d)
20424 (goto-char c)))
20425 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20426 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20427 ((org-at-item-p) (call-interactively 'org-move-item-up))
20428 (t (org-drag-element-backward))))
20430 (defun org-metadown (&optional _arg)
20431 "Move subtree down or move table row down.
20432 Calls `org-move-subtree-down' or `org-table-move-row' or
20433 `org-move-item-down', depending on context. See the individual
20434 commands for more information."
20435 (interactive "P")
20436 (cond
20437 ((run-hook-with-args-until-success 'org-metadown-hook))
20438 ((org-region-active-p)
20439 (let* ((a (min (region-beginning) (region-end)))
20440 (b (max (region-beginning) (region-end)))
20441 (c (save-excursion (goto-char b)
20442 (move-beginning-of-line 1)))
20443 (d (save-excursion (goto-char b)
20444 (move-end-of-line 1) (1+ (point)))))
20445 (transpose-regions a b c d)
20446 (goto-char d)))
20447 ((org-at-table-p) (call-interactively 'org-table-move-row))
20448 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20449 ((org-at-item-p) (call-interactively 'org-move-item-down))
20450 (t (org-drag-element-forward))))
20452 (defun org-shiftup (&optional arg)
20453 "Increase item in timestamp or increase priority of current headline.
20454 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20455 depending on context. See the individual commands for more information."
20456 (interactive "P")
20457 (cond
20458 ((run-hook-with-args-until-success 'org-shiftup-hook))
20459 ((and org-support-shift-select (org-region-active-p))
20460 (org-call-for-shift-select 'previous-line))
20461 ((org-at-timestamp-p t)
20462 (call-interactively (if org-edit-timestamp-down-means-later
20463 'org-timestamp-down 'org-timestamp-up)))
20464 ((and (not (eq org-support-shift-select 'always))
20465 org-enable-priority-commands
20466 (org-at-heading-p))
20467 (call-interactively 'org-priority-up))
20468 ((and (not org-support-shift-select) (org-at-item-p))
20469 (call-interactively 'org-previous-item))
20470 ((org-clocktable-try-shift 'up arg))
20471 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20472 (org-support-shift-select
20473 (org-call-for-shift-select 'previous-line))
20474 (t (org-shiftselect-error))))
20476 (defun org-shiftdown (&optional arg)
20477 "Decrease item in timestamp or decrease priority of current headline.
20478 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20479 depending on context. See the individual commands for more information."
20480 (interactive "P")
20481 (cond
20482 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20483 ((and org-support-shift-select (org-region-active-p))
20484 (org-call-for-shift-select 'next-line))
20485 ((org-at-timestamp-p t)
20486 (call-interactively (if org-edit-timestamp-down-means-later
20487 'org-timestamp-up 'org-timestamp-down)))
20488 ((and (not (eq org-support-shift-select 'always))
20489 org-enable-priority-commands
20490 (org-at-heading-p))
20491 (call-interactively 'org-priority-down))
20492 ((and (not org-support-shift-select) (org-at-item-p))
20493 (call-interactively 'org-next-item))
20494 ((org-clocktable-try-shift 'down arg))
20495 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20496 (org-support-shift-select
20497 (org-call-for-shift-select 'next-line))
20498 (t (org-shiftselect-error))))
20500 (defun org-shiftright (&optional arg)
20501 "Cycle the thing at point or in the current line, depending on context.
20502 Depending on context, this does one of the following:
20504 - switch a timestamp at point one day into the future
20505 - on a headline, switch to the next TODO keyword.
20506 - on an item, switch entire list to the next bullet type
20507 - on a property line, switch to the next allowed value
20508 - on a clocktable definition line, move time block into the future"
20509 (interactive "P")
20510 (cond
20511 ((run-hook-with-args-until-success 'org-shiftright-hook))
20512 ((and org-support-shift-select (org-region-active-p))
20513 (org-call-for-shift-select 'forward-char))
20514 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20515 ((and (not (eq org-support-shift-select 'always))
20516 (org-at-heading-p))
20517 (let ((org-inhibit-logging
20518 (not org-treat-S-cursor-todo-selection-as-state-change))
20519 (org-inhibit-blocking
20520 (not org-treat-S-cursor-todo-selection-as-state-change)))
20521 (org-call-with-arg 'org-todo 'right)))
20522 ((or (and org-support-shift-select
20523 (not (eq org-support-shift-select 'always))
20524 (org-at-item-bullet-p))
20525 (and (not org-support-shift-select) (org-at-item-p)))
20526 (org-call-with-arg 'org-cycle-list-bullet nil))
20527 ((and (not (eq org-support-shift-select 'always))
20528 (org-at-property-p))
20529 (call-interactively 'org-property-next-allowed-value))
20530 ((org-clocktable-try-shift 'right arg))
20531 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20532 (org-support-shift-select
20533 (org-call-for-shift-select 'forward-char))
20534 (t (org-shiftselect-error))))
20536 (defun org-shiftleft (&optional arg)
20537 "Cycle the thing at point or in the current line, depending on context.
20538 Depending on context, this does one of the following:
20540 - switch a timestamp at point one day into the past
20541 - on a headline, switch to the previous TODO keyword.
20542 - on an item, switch entire list to the previous bullet type
20543 - on a property line, switch to the previous allowed value
20544 - on a clocktable definition line, move time block into the past"
20545 (interactive "P")
20546 (cond
20547 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20548 ((and org-support-shift-select (org-region-active-p))
20549 (org-call-for-shift-select 'backward-char))
20550 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20551 ((and (not (eq org-support-shift-select 'always))
20552 (org-at-heading-p))
20553 (let ((org-inhibit-logging
20554 (not org-treat-S-cursor-todo-selection-as-state-change))
20555 (org-inhibit-blocking
20556 (not org-treat-S-cursor-todo-selection-as-state-change)))
20557 (org-call-with-arg 'org-todo 'left)))
20558 ((or (and org-support-shift-select
20559 (not (eq org-support-shift-select 'always))
20560 (org-at-item-bullet-p))
20561 (and (not org-support-shift-select) (org-at-item-p)))
20562 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20563 ((and (not (eq org-support-shift-select 'always))
20564 (org-at-property-p))
20565 (call-interactively 'org-property-previous-allowed-value))
20566 ((org-clocktable-try-shift 'left arg))
20567 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20568 (org-support-shift-select
20569 (org-call-for-shift-select 'backward-char))
20570 (t (org-shiftselect-error))))
20572 (defun org-shiftcontrolright ()
20573 "Switch to next TODO set."
20574 (interactive)
20575 (cond
20576 ((and org-support-shift-select (org-region-active-p))
20577 (org-call-for-shift-select 'forward-word))
20578 ((and (not (eq org-support-shift-select 'always))
20579 (org-at-heading-p))
20580 (org-call-with-arg 'org-todo 'nextset))
20581 (org-support-shift-select
20582 (org-call-for-shift-select 'forward-word))
20583 (t (org-shiftselect-error))))
20585 (defun org-shiftcontrolleft ()
20586 "Switch to previous TODO set."
20587 (interactive)
20588 (cond
20589 ((and org-support-shift-select (org-region-active-p))
20590 (org-call-for-shift-select 'backward-word))
20591 ((and (not (eq org-support-shift-select 'always))
20592 (org-at-heading-p))
20593 (org-call-with-arg 'org-todo 'previousset))
20594 (org-support-shift-select
20595 (org-call-for-shift-select 'backward-word))
20596 (t (org-shiftselect-error))))
20598 (defun org-shiftcontrolup (&optional n)
20599 "Change timestamps synchronously up in CLOCK log lines.
20600 Optional argument N tells to change by that many units."
20601 (interactive "P")
20602 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20603 (let (org-support-shift-select)
20604 (org-clock-timestamps-up n))
20605 (user-error "Not at a clock log")))
20607 (defun org-shiftcontroldown (&optional n)
20608 "Change timestamps synchronously down in CLOCK log lines.
20609 Optional argument N tells to change by that many units."
20610 (interactive "P")
20611 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20612 (let (org-support-shift-select)
20613 (org-clock-timestamps-down n))
20614 (user-error "Not at a clock log")))
20616 (defun org-increase-number-at-point (&optional inc)
20617 "Increment the number at point.
20618 With an optional prefix numeric argument INC, increment using
20619 this numeric value."
20620 (interactive "p")
20621 (if (not (number-at-point))
20622 (user-error "Not on a number")
20623 (unless inc (setq inc 1))
20624 (let ((pos (point))
20625 (beg (skip-chars-backward "-+^/*0-9eE."))
20626 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20627 (setq nap (buffer-substring-no-properties
20628 (+ pos beg) (+ pos beg end)))
20629 (delete-region (+ pos beg) (+ pos beg end))
20630 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20631 (when (org-at-table-p)
20632 (org-table-align)
20633 (org-table-end-of-field 1))))
20635 (defun org-decrease-number-at-point (&optional inc)
20636 "Decrement the number at point.
20637 With an optional prefix numeric argument INC, decrement using
20638 this numeric value."
20639 (interactive "p")
20640 (org-increase-number-at-point (- (or inc 1))))
20642 (defun org-ctrl-c-ret ()
20643 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20644 (interactive)
20645 (cond
20646 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20647 (t (call-interactively 'org-insert-heading))))
20649 (defun org-find-visible ()
20650 (let ((s (point)))
20651 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20652 (get-char-property s 'invisible)))
20654 (defun org-find-invisible ()
20655 (let ((s (point)))
20656 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20657 (not (get-char-property s 'invisible))))
20660 (defun org-copy-visible (beg end)
20661 "Copy the visible parts of the region."
20662 (interactive "r")
20663 (let (snippets s)
20664 (save-excursion
20665 (save-restriction
20666 (narrow-to-region beg end)
20667 (setq s (goto-char (point-min)))
20668 (while (not (= (point) (point-max)))
20669 (goto-char (org-find-invisible))
20670 (push (buffer-substring s (point)) snippets)
20671 (setq s (goto-char (org-find-visible))))))
20672 (kill-new (apply 'concat (nreverse snippets)))))
20674 (defun org-copy-special ()
20675 "Copy region in table or copy current subtree.
20676 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20677 context. See the individual commands for more information."
20678 (interactive)
20679 (call-interactively
20680 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20682 (defun org-cut-special ()
20683 "Cut region in table or cut current subtree.
20684 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20685 context. See the individual commands for more information."
20686 (interactive)
20687 (call-interactively
20688 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20690 (defun org-paste-special (arg)
20691 "Paste rectangular region into table, or past subtree relative to level.
20692 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20693 See the individual commands for more information."
20694 (interactive "P")
20695 (if (org-at-table-p)
20696 (org-table-paste-rectangle)
20697 (org-paste-subtree arg)))
20699 (defun org-edit-special (&optional arg)
20700 "Call a special editor for the element at point.
20701 When at a table, call the formula editor with `org-table-edit-formulas'.
20702 When in a source code block, call `org-edit-src-code'.
20703 When in a fixed-width region, call `org-edit-fixed-width-region'.
20704 When in an export block, call `org-edit-export-block'.
20705 When in a LaTeX environment, call `org-edit-latex-environment'.
20706 When at an #+INCLUDE keyword, visit the included file.
20707 When at a footnote reference, call `org-edit-footnote-reference'
20708 On a link, call `ffap' to visit the link at point.
20709 Otherwise, return a user error."
20710 (interactive "P")
20711 (let ((element (org-element-at-point)))
20712 (barf-if-buffer-read-only)
20713 (pcase (org-element-type element)
20714 (`src-block
20715 (if (not arg) (org-edit-src-code)
20716 (let* ((info (org-babel-get-src-block-info))
20717 (lang (nth 0 info))
20718 (params (nth 2 info))
20719 (session (cdr (assq :session params))))
20720 (if (not session) (org-edit-src-code)
20721 ;; At a src-block with a session and function called with
20722 ;; an ARG: switch to the buffer related to the inferior
20723 ;; process.
20724 (switch-to-buffer
20725 (funcall (intern (concat "org-babel-prep-session:" lang))
20726 session params))))))
20727 (`keyword
20728 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20729 (org-open-link-from-string
20730 (format "[[%s]]"
20731 (expand-file-name
20732 (let ((value (org-element-property :value element)))
20733 (cond ((not (org-string-nw-p value))
20734 (user-error "No file to edit"))
20735 ((string-match "\\`\"\\(.*?\\)\"" value)
20736 (match-string 1 value))
20737 ((string-match "\\`[^ \t\"]\\S-*" value)
20738 (match-string 0 value))
20739 (t (user-error "No valid file specified")))))))
20740 (user-error "No special environment to edit here")))
20741 (`table
20742 (if (eq (org-element-property :type element) 'table.el)
20743 (org-edit-table.el)
20744 (call-interactively 'org-table-edit-formulas)))
20745 ;; Only Org tables contain `table-row' type elements.
20746 (`table-row (call-interactively 'org-table-edit-formulas))
20747 (`example-block (org-edit-src-code))
20748 (`export-block (org-edit-export-block))
20749 (`fixed-width (org-edit-fixed-width-region))
20750 (`latex-environment (org-edit-latex-environment))
20752 ;; No notable element at point. Though, we may be at a link or
20753 ;; a footnote reference, which are objects. Thus, scan deeper.
20754 (let ((context (org-element-context element)))
20755 (pcase (org-element-type context)
20756 (`footnote-reference (org-edit-footnote-reference))
20757 (`inline-src-block (org-edit-inline-src-code))
20758 (`link (call-interactively #'ffap))
20759 (_ (user-error "No special environment to edit here"))))))))
20761 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20762 (defun org-ctrl-c-ctrl-c (&optional arg)
20763 "Set tags in headline, or update according to changed information at point.
20765 This command does many different things, depending on context:
20767 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20768 this is what we do.
20770 - If the cursor is on a statistics cookie, update it.
20772 - If the cursor is in a headline, prompt for tags and insert them
20773 into the current line, aligned to `org-tags-column'. When called
20774 with prefix arg, realign all tags in the current buffer.
20776 - If the cursor is in one of the special #+KEYWORD lines, this
20777 triggers scanning the buffer for these lines and updating the
20778 information.
20780 - If the cursor is inside a table, realign the table. This command
20781 works even if the automatic table editor has been turned off.
20783 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20784 the entire table.
20786 - If the cursor is at a footnote reference or definition, jump to
20787 the corresponding definition or references, respectively.
20789 - If the cursor is a the beginning of a dynamic block, update it.
20791 - If the current buffer is a capture buffer, close note and file it.
20793 - If the cursor is on a <<<target>>>, update radio targets and
20794 corresponding links in this buffer.
20796 - If the cursor is on a numbered item in a plain list, renumber the
20797 ordered list.
20799 - If the cursor is on a checkbox, toggle it.
20801 - If the cursor is on a code block, evaluate it. The variable
20802 `org-confirm-babel-evaluate' can be used to control prompting
20803 before code block evaluation, by default every code block
20804 evaluation requires confirmation. Code block evaluation can be
20805 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20806 (interactive "P")
20807 (cond
20808 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20809 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20810 (org-remove-occur-highlights)
20811 (message "Temporary highlights/overlays removed from current buffer"))
20812 ((and (local-variable-p 'org-finish-function)
20813 (fboundp org-finish-function))
20814 (funcall org-finish-function))
20815 ((org-babel-hash-at-point))
20816 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20818 (let* ((context
20819 (org-element-lineage
20820 (org-element-context)
20821 ;; Limit to supported contexts.
20822 '(babel-call clock dynamic-block footnote-definition
20823 footnote-reference inline-babel-call inline-src-block
20824 inlinetask item keyword node-property paragraph
20825 plain-list property-drawer radio-target src-block
20826 statistics-cookie table table-cell table-row
20827 timestamp)
20829 (type (org-element-type context)))
20830 ;; For convenience: at the first line of a paragraph on the same
20831 ;; line as an item, apply function on that item instead.
20832 (when (eq type 'paragraph)
20833 (let ((parent (org-element-property :parent context)))
20834 (when (and (eq (org-element-type parent) 'item)
20835 (= (line-beginning-position)
20836 (org-element-property :begin parent)))
20837 (setq context parent)
20838 (setq type 'item))))
20839 ;; Act according to type of element or object at point.
20841 ;; Do nothing on a blank line, except if it is contained in
20842 ;; a src block. Hence, we first check if point is in such
20843 ;; a block and then if it is at a blank line.
20844 (pcase type
20845 ((or `inline-src-block `src-block)
20846 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20847 (org-babel-eval-wipe-error-buffer)
20848 (org-babel-execute-src-block
20849 current-prefix-arg (org-babel-get-src-block-info nil context))))
20850 ((guard (org-match-line "[ \t]*$"))
20851 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20852 (user-error
20853 (substitute-command-keys
20854 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20855 ((or `babel-call `inline-babel-call)
20856 (let ((info (org-babel-lob-get-info context)))
20857 (when info (org-babel-execute-src-block nil info))))
20858 (`clock (org-clock-update-time-maybe))
20859 (`dynamic-block
20860 (save-excursion
20861 (goto-char (org-element-property :post-affiliated context))
20862 (org-update-dblock)))
20863 (`footnote-definition
20864 (goto-char (org-element-property :post-affiliated context))
20865 (call-interactively 'org-footnote-action))
20866 (`footnote-reference (call-interactively #'org-footnote-action))
20867 ((or `headline `inlinetask)
20868 (save-excursion (goto-char (org-element-property :begin context))
20869 (call-interactively #'org-set-tags)))
20870 (`item
20871 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20872 ;; unconditionally, whereas `C-u' will toggle its presence.
20873 ;; Without a universal argument, if the item has a checkbox,
20874 ;; toggle it. Otherwise repair the list.
20875 (let* ((box (org-element-property :checkbox context))
20876 (struct (org-element-property :structure context))
20877 (old-struct (copy-tree struct))
20878 (parents (org-list-parents-alist struct))
20879 (prevs (org-list-prevs-alist struct))
20880 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20881 (org-list-set-checkbox
20882 (org-element-property :begin context) struct
20883 (cond ((equal arg '(16)) "[-]")
20884 ((and (not box) (equal arg '(4))) "[ ]")
20885 ((or (not box) (equal arg '(4))) nil)
20886 ((eq box 'on) "[ ]")
20887 (t "[X]")))
20888 ;; Mimic `org-list-write-struct' but with grabbing a return
20889 ;; value from `org-list-struct-fix-box'.
20890 (org-list-struct-fix-ind struct parents 2)
20891 (org-list-struct-fix-item-end struct)
20892 (org-list-struct-fix-bul struct prevs)
20893 (org-list-struct-fix-ind struct parents)
20894 (let ((block-item
20895 (org-list-struct-fix-box struct parents prevs orderedp)))
20896 (if (and box (equal struct old-struct))
20897 (if (equal arg '(16))
20898 (message "Checkboxes already reset")
20899 (user-error "Cannot toggle this checkbox: %s"
20900 (if (eq box 'on)
20901 "all subitems checked"
20902 "unchecked subitems")))
20903 (org-list-struct-apply-struct struct old-struct)
20904 (org-update-checkbox-count-maybe))
20905 (when block-item
20906 (message "Checkboxes were removed due to empty box at line %d"
20907 (org-current-line block-item))))))
20908 (`keyword
20909 (let ((org-inhibit-startup-visibility-stuff t)
20910 (org-startup-align-all-tables nil))
20911 (when (boundp 'org-table-coordinate-overlays)
20912 (mapc #'delete-overlay org-table-coordinate-overlays)
20913 (setq org-table-coordinate-overlays nil))
20914 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20915 (message "Local setup has been refreshed"))
20916 (`plain-list
20917 ;; At a plain list, with a double C-u argument, set
20918 ;; checkboxes of each item to "[-]", whereas a single one
20919 ;; will toggle their presence according to the state of the
20920 ;; first item in the list. Without an argument, repair the
20921 ;; list.
20922 (let* ((begin (org-element-property :contents-begin context))
20923 (beginm (move-marker (make-marker) begin))
20924 (struct (org-element-property :structure context))
20925 (old-struct (copy-tree struct))
20926 (first-box (save-excursion
20927 (goto-char begin)
20928 (looking-at org-list-full-item-re)
20929 (match-string-no-properties 3)))
20930 (new-box (cond ((equal arg '(16)) "[-]")
20931 ((equal arg '(4)) (unless first-box "[ ]"))
20932 ((equal first-box "[X]") "[ ]")
20933 (t "[X]"))))
20934 (cond
20935 (arg
20936 (dolist (pos
20937 (org-list-get-all-items
20938 begin struct (org-list-prevs-alist struct)))
20939 (org-list-set-checkbox pos struct new-box)))
20940 ((and first-box (eq (point) begin))
20941 ;; For convenience, when point is at bol on the first
20942 ;; item of the list and no argument is provided, simply
20943 ;; toggle checkbox of that item, if any.
20944 (org-list-set-checkbox begin struct new-box)))
20945 (org-list-write-struct
20946 struct (org-list-parents-alist struct) old-struct)
20947 (org-update-checkbox-count-maybe)
20948 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20949 ((or `property-drawer `node-property)
20950 (call-interactively #'org-property-action))
20951 (`radio-target
20952 (call-interactively #'org-update-radio-target-regexp))
20953 (`statistics-cookie
20954 (call-interactively #'org-update-statistics-cookies))
20955 ((or `table `table-cell `table-row)
20956 ;; At a table, recalculate every field and align it. Also
20957 ;; send the table if necessary. If the table has
20958 ;; a `table.el' type, just give up. At a table row or cell,
20959 ;; maybe recalculate line but always align table.
20960 (if (eq (org-element-property :type context) 'table.el)
20961 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20962 Use `\\[org-edit-special]' to edit table.el tables"))
20963 (let ((org-enable-table-editor t))
20964 (if (or (eq type 'table)
20965 ;; Check if point is at a TBLFM line.
20966 (and (eq type 'table-row)
20967 (= (point) (org-element-property :end context))))
20968 (save-excursion
20969 (if (org-at-TBLFM-p)
20970 (progn (require 'org-table)
20971 (org-table-calc-current-TBLFM))
20972 (goto-char (org-element-property :contents-begin context))
20973 (org-call-with-arg 'org-table-recalculate (or arg t))
20974 (orgtbl-send-table 'maybe)))
20975 (org-table-maybe-eval-formula)
20976 (cond (arg (call-interactively #'org-table-recalculate))
20977 ((org-table-maybe-recalculate-line))
20978 (t (org-table-align)))))))
20979 (`timestamp (org-timestamp-change 0 'day))
20980 ((and `nil (guard (org-at-heading-p)))
20981 ;; When point is on an unsupported object type, we can miss
20982 ;; the fact that it also is at a heading. Handle it here.
20983 (call-interactively #'org-set-tags))
20984 ((guard
20985 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20987 (user-error
20988 (substitute-command-keys
20989 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20991 (defun org-mode-restart ()
20992 (interactive)
20993 (let ((indent-status (bound-and-true-p org-indent-mode)))
20994 (funcall major-mode)
20995 (hack-local-variables)
20996 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20997 (org-indent-mode -1)))
20998 (message "%s restarted" major-mode))
21000 (defun org-kill-note-or-show-branches ()
21001 "Abort storing current note, or call `outline-show-branches'."
21002 (interactive)
21003 (if (not org-finish-function)
21004 (progn
21005 (outline-hide-subtree)
21006 (call-interactively 'outline-show-branches))
21007 (let ((org-note-abort t))
21008 (funcall org-finish-function))))
21010 (defun org-delete-indentation (&optional arg)
21011 "Join current line to previous and fix whitespace at join.
21013 If previous line is a headline add to headline title. Otherwise
21014 the function calls `delete-indentation'.
21016 With a non-nil optional argument, join it to the following one."
21017 (interactive "*P")
21018 (if (save-excursion
21019 (beginning-of-line (if arg 1 0))
21020 (let ((case-fold-search nil))
21021 (looking-at org-complex-heading-regexp)))
21022 ;; At headline.
21023 (let ((tags-column (when (match-beginning 5)
21024 (save-excursion (goto-char (match-beginning 5))
21025 (current-column))))
21026 (string (concat " " (progn (when arg (forward-line 1))
21027 (org-trim (delete-and-extract-region
21028 (line-beginning-position)
21029 (line-end-position)))))))
21030 (unless (bobp) (delete-region (point) (1- (point))))
21031 (goto-char (or (match-end 4)
21032 (match-beginning 5)
21033 (match-end 0)))
21034 (skip-chars-backward " \t")
21035 (save-excursion (insert string))
21036 ;; Adjust alignment of tags.
21037 (cond
21038 ((not tags-column)) ;no tags
21039 (org-auto-align-tags (org-set-tags nil t))
21040 (t (org--align-tags-here tags-column)))) ;preserve tags column
21041 (delete-indentation arg)))
21043 (defun org-open-line (n)
21044 "Insert a new row in tables, call `open-line' elsewhere.
21045 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21046 As a special case, when a document starts with a table, allow to
21047 call `open-line' on the very first character."
21048 (interactive "*p")
21049 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21050 (org-table-insert-row)
21051 (open-line n)))
21053 (defun org-return (&optional indent)
21054 "Goto next table row or insert a newline.
21056 Calls `org-table-next-row' or `newline', depending on context.
21058 When optional INDENT argument is non-nil, call
21059 `newline-and-indent' instead of `newline'.
21061 When `org-return-follows-link' is non-nil and point is on
21062 a timestamp or a link, call `org-open-at-point'. However, it
21063 will not happen if point is in a table or on a \"dead\"
21064 object (e.g., within a comment). In these case, you need to use
21065 `org-open-at-point' directly."
21066 (interactive)
21067 (let ((context (if org-return-follows-link (org-element-context)
21068 (org-element-at-point))))
21069 (cond
21070 ;; In a table, call `org-table-next-row'.
21071 ((or (and (eq (org-element-type context) 'table)
21072 (>= (point) (org-element-property :contents-begin context))
21073 (< (point) (org-element-property :contents-end context)))
21074 (org-element-lineage context '(table-row table-cell) t))
21075 (org-table-justify-field-maybe)
21076 (call-interactively #'org-table-next-row))
21077 ;; On a link or a timestamp, call `org-open-at-point' if
21078 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21079 ;; locations, e.g., in a comment, as `org-open-at-point'.
21080 ((and org-return-follows-link
21081 (or (org-in-regexp org-ts-regexp-both nil t)
21082 (org-in-regexp org-tsr-regexp-both nil t)
21083 (org-in-regexp org-any-link-re nil t)))
21084 (call-interactively #'org-open-at-point))
21085 ;; Insert newline in heading, but preserve tags.
21086 ((and (not (bolp))
21087 (save-excursion (beginning-of-line)
21088 (let ((case-fold-search nil))
21089 (looking-at org-complex-heading-regexp))))
21090 ;; At headline. Split line. However, if point is on keyword,
21091 ;; priority cookie or tags, do not break any of them: add
21092 ;; a newline after the headline instead.
21093 (let ((tags-column (and (match-beginning 5)
21094 (save-excursion (goto-char (match-beginning 5))
21095 (current-column))))
21096 (string
21097 (when (and (match-end 4) (org-point-in-group (point) 4))
21098 (delete-and-extract-region (point) (match-end 4)))))
21099 ;; Adjust tag alignment.
21100 (cond
21101 ((not (and tags-column string)))
21102 (org-auto-align-tags (org-set-tags nil t))
21103 (t (org--align-tags-here tags-column))) ;preserve tags column
21104 (end-of-line)
21105 (org-show-entry)
21106 (if indent (newline-and-indent) (newline))
21107 (when string (save-excursion (insert (org-trim string))))))
21108 ;; In a list, make sure indenting keeps trailing text within.
21109 ((and indent
21110 (not (eolp))
21111 (org-element-lineage context '(item)))
21112 (let ((trailing-data
21113 (delete-and-extract-region (point) (line-end-position))))
21114 (newline-and-indent)
21115 (save-excursion (insert trailing-data))))
21116 (t (if indent (newline-and-indent) (newline))))))
21118 (defun org-return-indent ()
21119 "Goto next table row or insert a newline and indent.
21120 Calls `org-table-next-row' or `newline-and-indent', depending on
21121 context. See the individual commands for more information."
21122 (interactive)
21123 (org-return t))
21125 (defun org-ctrl-c-star ()
21126 "Compute table, or change heading status of lines.
21127 Calls `org-table-recalculate' or `org-toggle-heading',
21128 depending on context."
21129 (interactive)
21130 (cond
21131 ((org-at-table-p)
21132 (call-interactively 'org-table-recalculate))
21134 ;; Convert all lines in region to list items
21135 (call-interactively 'org-toggle-heading))))
21137 (defun org-ctrl-c-minus ()
21138 "Insert separator line in table or modify bullet status of line.
21139 Also turns a plain line or a region of lines into list items.
21140 Calls `org-table-insert-hline', `org-toggle-item', or
21141 `org-cycle-list-bullet', depending on context."
21142 (interactive)
21143 (cond
21144 ((org-at-table-p)
21145 (call-interactively 'org-table-insert-hline))
21146 ((org-region-active-p)
21147 (call-interactively 'org-toggle-item))
21148 ((org-in-item-p)
21149 (call-interactively 'org-cycle-list-bullet))
21151 (call-interactively 'org-toggle-item))))
21153 (defun org-toggle-heading (&optional nstars)
21154 "Convert headings to normal text, or items or text to headings.
21155 If there is no active region, only convert the current line.
21157 With a `\\[universal-argument]' prefix, convert the whole list at
21158 point into heading.
21160 In a region:
21162 - If the first non blank line is a headline, remove the stars
21163 from all headlines in the region.
21165 - If it is a normal line, turn each and every normal line (i.e.,
21166 not an heading or an item) in the region into headings. If you
21167 want to convert only the first line of this region, use one
21168 universal prefix argument.
21170 - If it is a plain list item, turn all plain list items into headings.
21172 When converting a line into a heading, the number of stars is chosen
21173 such that the lines become children of the current entry. However,
21174 when a numeric prefix argument is given, its value determines the
21175 number of stars to add."
21176 (interactive "P")
21177 (let ((skip-blanks
21178 (function
21179 ;; Return beginning of first non-blank line, starting from
21180 ;; line at POS.
21181 (lambda (pos)
21182 (save-excursion
21183 (goto-char pos)
21184 (while (org-at-comment-p) (forward-line))
21185 (skip-chars-forward " \r\t\n")
21186 (point-at-bol)))))
21187 beg end toggled)
21188 ;; Determine boundaries of changes. If a universal prefix has
21189 ;; been given, put the list in a region. If region ends at a bol,
21190 ;; do not consider the last line to be in the region.
21192 (when (and current-prefix-arg (org-at-item-p))
21193 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21194 (org-mark-element))
21196 (if (org-region-active-p)
21197 (setq beg (funcall skip-blanks (region-beginning))
21198 end (copy-marker (save-excursion
21199 (goto-char (region-end))
21200 (if (bolp) (point) (point-at-eol)))))
21201 (setq beg (funcall skip-blanks (point-at-bol))
21202 end (copy-marker (point-at-eol))))
21203 ;; Ensure inline tasks don't count as headings.
21204 (org-with-limited-levels
21205 (save-excursion
21206 (goto-char beg)
21207 (cond
21208 ;; Case 1. Started at an heading: de-star headings.
21209 ((org-at-heading-p)
21210 (while (< (point) end)
21211 (when (org-at-heading-p t)
21212 (looking-at org-outline-regexp) (replace-match "")
21213 (setq toggled t))
21214 (forward-line)))
21215 ;; Case 2. Started at an item: change items into headlines.
21216 ;; One star will be added by `org-list-to-subtree'.
21217 ((org-at-item-p)
21218 (while (< (point) end)
21219 (when (org-at-item-p)
21220 ;; Pay attention to cases when region ends before list.
21221 (let* ((struct (org-list-struct))
21222 (list-end
21223 (min (org-list-get-bottom-point struct) (1+ end))))
21224 (save-restriction
21225 (narrow-to-region (point) list-end)
21226 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21227 (setq toggled t))
21228 (forward-line)))
21229 ;; Case 3. Started at normal text: make every line an heading,
21230 ;; skipping headlines and items.
21231 (t (let* ((stars
21232 (make-string
21233 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21234 (add-stars
21235 (cond (nstars "") ; stars from prefix only
21236 ((equal stars "") "*") ; before first heading
21237 (org-odd-levels-only "**") ; inside heading, odd
21238 (t "*"))) ; inside heading, oddeven
21239 (rpl (concat stars add-stars " "))
21240 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21241 (while (< (point) (if (equal nstars '(4)) lend end))
21242 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21243 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21244 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21245 (forward-line)))))))
21246 (unless toggled (message "Cannot toggle heading from here"))))
21248 (defun org-meta-return (&optional arg)
21249 "Insert a new heading or wrap a region in a table.
21250 Calls `org-insert-heading', `org-insert-item' or
21251 `org-table-wrap-region', depending on context. When called with
21252 an argument, unconditionally call `org-insert-heading'."
21253 (interactive "P")
21254 (org-check-before-invisible-edit 'insert)
21255 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21256 (call-interactively (cond (arg #'org-insert-heading)
21257 ((org-at-table-p) #'org-table-wrap-region)
21258 ((org-in-item-p) #'org-insert-item)
21259 (t #'org-insert-heading)))))
21261 ;;; Menu entries
21263 (defsubst org-in-subtree-not-table-p ()
21264 "Are we in a subtree and not in a table?"
21265 (and (not (org-before-first-heading-p))
21266 (not (org-at-table-p))))
21268 ;; Define the Org mode menus
21269 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21270 '("Tbl"
21271 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21272 ["Next Field" org-cycle (org-at-table-p)]
21273 ["Previous Field" org-shifttab (org-at-table-p)]
21274 ["Next Row" org-return (org-at-table-p)]
21275 "--"
21276 ["Blank Field" org-table-blank-field (org-at-table-p)]
21277 ["Edit Field" org-table-edit-field (org-at-table-p)]
21278 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21279 "--"
21280 ("Column"
21281 ["Move Column Left" org-metaleft (org-at-table-p)]
21282 ["Move Column Right" org-metaright (org-at-table-p)]
21283 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21284 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21285 ("Row"
21286 ["Move Row Up" org-metaup (org-at-table-p)]
21287 ["Move Row Down" org-metadown (org-at-table-p)]
21288 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21289 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21290 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21291 "--"
21292 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21293 ("Rectangle"
21294 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21295 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21296 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21297 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21298 "--"
21299 ("Calculate"
21300 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21301 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21302 ["Edit Formulas" org-edit-special (org-at-table-p)]
21303 "--"
21304 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21305 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21306 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21307 "--"
21308 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21309 "--"
21310 ["Sum Column/Rectangle" org-table-sum
21311 (or (org-at-table-p) (org-region-active-p))]
21312 ["Which Column?" org-table-current-column (org-at-table-p)])
21313 ["Debug Formulas"
21314 org-table-toggle-formula-debugger
21315 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21316 ["Show Col/Row Numbers"
21317 org-table-toggle-coordinate-overlays
21318 :style toggle
21319 :selected (bound-and-true-p org-table-overlay-coordinates)]
21320 "--"
21321 ["Create" org-table-create (and (not (org-at-table-p))
21322 org-enable-table-editor)]
21323 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21324 ["Import from File" org-table-import (not (org-at-table-p))]
21325 ["Export to File" org-table-export (org-at-table-p)]
21326 "--"
21327 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21328 "--"
21329 ("Plot"
21330 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21331 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21333 (easy-menu-define org-org-menu org-mode-map "Org menu"
21334 '("Org"
21335 ("Show/Hide"
21336 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21337 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21338 ["Sparse Tree..." org-sparse-tree t]
21339 ["Reveal Context" org-reveal t]
21340 ["Show All" outline-show-all t]
21341 "--"
21342 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21343 "--"
21344 ["New Heading" org-insert-heading t]
21345 ("Navigate Headings"
21346 ["Up" outline-up-heading t]
21347 ["Next" outline-next-visible-heading t]
21348 ["Previous" outline-previous-visible-heading t]
21349 ["Next Same Level" outline-forward-same-level t]
21350 ["Previous Same Level" outline-backward-same-level t]
21351 "--"
21352 ["Jump" org-goto t])
21353 ("Edit Structure"
21354 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21355 "--"
21356 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21357 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21358 "--"
21359 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21360 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21361 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21362 "--"
21363 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21364 "--"
21365 ["Copy visible text" org-copy-visible t]
21366 "--"
21367 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21368 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21369 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21370 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21371 "--"
21372 ["Sort Region/Children" org-sort t]
21373 "--"
21374 ["Convert to odd levels" org-convert-to-odd-levels t]
21375 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21376 ("Editing"
21377 ["Emphasis..." org-emphasize t]
21378 ["Edit Source Example" org-edit-special t]
21379 "--"
21380 ["Footnote new/jump" org-footnote-action t]
21381 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21382 ("Archive"
21383 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21384 "--"
21385 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21386 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21387 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21389 "--"
21390 ("Hyperlinks"
21391 ["Store Link (Global)" org-store-link t]
21392 ["Find existing link to here" org-occur-link-in-agenda-files t]
21393 ["Insert Link" org-insert-link t]
21394 ["Follow Link" org-open-at-point t]
21395 "--"
21396 ["Next link" org-next-link t]
21397 ["Previous link" org-previous-link t]
21398 "--"
21399 ["Descriptive Links"
21400 org-toggle-link-display
21401 :style radio
21402 :selected org-descriptive-links
21404 ["Literal Links"
21405 org-toggle-link-display
21406 :style radio
21407 :selected (not org-descriptive-links)])
21408 "--"
21409 ("TODO Lists"
21410 ["TODO/DONE/-" org-todo t]
21411 ("Select keyword"
21412 ["Next keyword" org-shiftright (org-at-heading-p)]
21413 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21414 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21415 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21416 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21417 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21418 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21419 "--"
21420 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21421 :selected org-enforce-todo-dependencies :style toggle :active t]
21422 "Settings for tree at point"
21423 ["Do Children sequentially" org-toggle-ordered-property :style radio
21424 :selected (org-entry-get nil "ORDERED")
21425 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21426 ["Do Children parallel" org-toggle-ordered-property :style radio
21427 :selected (not (org-entry-get nil "ORDERED"))
21428 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21429 "--"
21430 ["Set Priority" org-priority t]
21431 ["Priority Up" org-shiftup t]
21432 ["Priority Down" org-shiftdown t]
21433 "--"
21434 ["Get news from all feeds" org-feed-update-all t]
21435 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21436 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21437 ("TAGS and Properties"
21438 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21439 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21440 "--"
21441 ["Set property" org-set-property (not (org-before-first-heading-p))]
21442 ["Column view of properties" org-columns t]
21443 ["Insert Column View DBlock" org-columns-insert-dblock t])
21444 ("Dates and Scheduling"
21445 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21446 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21447 ("Change Date"
21448 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21449 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21450 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21451 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21452 ["Compute Time Range" org-evaluate-time-range t]
21453 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21454 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21455 "--"
21456 ["Custom time format" org-toggle-time-stamp-overlays
21457 :style radio :selected org-display-custom-times]
21458 "--"
21459 ["Goto Calendar" org-goto-calendar t]
21460 ["Date from Calendar" org-date-from-calendar t]
21461 "--"
21462 ["Start/Restart Timer" org-timer-start t]
21463 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21464 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21465 ["Insert Timer String" org-timer t]
21466 ["Insert Timer Item" org-timer-item t])
21467 ("Logging work"
21468 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21469 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21470 ["Clock out" org-clock-out t]
21471 ["Clock cancel" org-clock-cancel t]
21472 "--"
21473 ["Mark as default task" org-clock-mark-default-task t]
21474 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21475 ["Goto running clock" org-clock-goto t]
21476 "--"
21477 ["Display times" org-clock-display t]
21478 ["Create clock table" org-clock-report t]
21479 "--"
21480 ["Record DONE time"
21481 (progn (setq org-log-done (not org-log-done))
21482 (message "Switching to %s will %s record a timestamp"
21483 (car org-done-keywords)
21484 (if org-log-done "automatically" "not")))
21485 :style toggle :selected org-log-done])
21486 "--"
21487 ["Agenda Command..." org-agenda t]
21488 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21489 ("File List for Agenda")
21490 ("Special views current file"
21491 ["TODO Tree" org-show-todo-tree t]
21492 ["Check Deadlines" org-check-deadlines t]
21493 ["Tags/Property tree" org-match-sparse-tree t])
21494 "--"
21495 ["Export/Publish..." org-export-dispatch t]
21496 ("LaTeX"
21497 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21498 :selected org-cdlatex-mode]
21499 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21500 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21501 ["Modify math symbol" org-cdlatex-math-modify
21502 (org-inside-LaTeX-fragment-p)]
21503 ["Insert citation" org-reftex-citation t])
21504 "--"
21505 ("MobileOrg"
21506 ["Push Files and Views" org-mobile-push t]
21507 ["Get Captured and Flagged" org-mobile-pull t]
21508 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21509 "--"
21510 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21511 "--"
21512 ("Documentation"
21513 ["Show Version" org-version t]
21514 ["Info Documentation" org-info t])
21515 ("Customize"
21516 ["Browse Org Group" org-customize t]
21517 "--"
21518 ["Expand This Menu" org-create-customize-menu
21519 (fboundp 'customize-menu-create)])
21520 ["Send bug report" org-submit-bug-report t]
21521 "--"
21522 ("Refresh/Reload"
21523 ["Refresh setup current buffer" org-mode-restart t]
21524 ["Reload Org (after update)" org-reload t]
21525 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21528 (defun org-info (&optional node)
21529 "Read documentation for Org in the info system.
21530 With optional NODE, go directly to that node."
21531 (interactive)
21532 (info (format "(org)%s" (or node ""))))
21534 ;;;###autoload
21535 (defun org-submit-bug-report ()
21536 "Submit a bug report on Org via mail.
21538 Don't hesitate to report any problems or inaccurate documentation.
21540 If you don't have setup sending mail from (X)Emacs, please copy the
21541 output buffer into your mail program, as it gives us important
21542 information about your Org version and configuration."
21543 (interactive)
21544 (require 'reporter)
21545 (defvar reporter-prompt-for-summary-p)
21546 (org-load-modules-maybe)
21547 (org-require-autoloaded-modules)
21548 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21549 (reporter-submit-bug-report
21550 "emacs-orgmode@gnu.org"
21551 (org-version nil 'full)
21552 (let (list)
21553 (save-window-excursion
21554 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21555 (delete-other-windows)
21556 (erase-buffer)
21557 (insert "You are about to submit a bug report to the Org mailing list.
21559 We would like to add your full Org and Outline configuration to the
21560 bug report. This greatly simplifies the work of the maintainer and
21561 other experts on the mailing list.
21563 HOWEVER, some variables you have customized may contain private
21564 information. The names of customers, colleagues, or friends, might
21565 appear in the form of file names, tags, todo states, or search strings.
21566 If you answer yes to the prompt, you might want to check and remove
21567 such private information before sending the email.")
21568 (add-text-properties (point-min) (point-max) '(face org-warning))
21569 (when (yes-or-no-p "Include your Org configuration ")
21570 (mapatoms
21571 (lambda (v)
21572 (and (boundp v)
21573 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21574 (or (and (symbol-value v)
21575 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21576 (and
21577 (get v 'custom-type) (get v 'standard-value)
21578 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21579 (push v list)))))
21580 (kill-buffer (get-buffer "*Warn about privacy*"))
21581 list))
21582 nil nil
21583 "Remember to cover the basics, that is, what you expected to happen and
21584 what in fact did happen. You don't know how to make a good report? See
21586 http://orgmode.org/manual/Feedback.html#Feedback
21588 Your bug report will be posted to the Org mailing list.
21589 ------------------------------------------------------------------------")
21590 (save-excursion
21591 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21592 (replace-match "\\1Bug: \\3 [\\2]")))))
21595 (defun org-install-agenda-files-menu ()
21596 (let ((bl (buffer-list)))
21597 (save-excursion
21598 (while bl
21599 (set-buffer (pop bl))
21600 (when (derived-mode-p 'org-mode) (setq bl nil)))
21601 (when (derived-mode-p 'org-mode)
21602 (easy-menu-change
21603 '("Org") "File List for Agenda"
21604 (append
21605 (list
21606 ["Edit File List" (org-edit-agenda-file-list) t]
21607 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21608 ["Remove Current File from List" org-remove-file t]
21609 ["Cycle through agenda files" org-cycle-agenda-files t]
21610 ["Occur in all agenda files" org-occur-in-agenda-files t]
21611 "--")
21612 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21614 ;;;; Documentation
21616 (defun org-require-autoloaded-modules ()
21617 (interactive)
21618 (mapc #'require
21619 '(org-agenda org-archive org-attach org-clock org-colview org-id
21620 org-table org-timer)))
21622 ;;;###autoload
21623 (defun org-reload (&optional uncompiled)
21624 "Reload all org lisp files.
21625 With prefix arg UNCOMPILED, load the uncompiled versions."
21626 (interactive "P")
21627 (require 'loadhist)
21628 (let* ((org-dir (org-find-library-dir "org"))
21629 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21630 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21631 (remove-re (format "\\`%s\\'"
21632 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21633 (feats (delete-dups
21634 (mapcar 'file-name-sans-extension
21635 (mapcar 'file-name-nondirectory
21636 (delq nil
21637 (mapcar 'feature-file
21638 features))))))
21639 (lfeat (append
21640 (sort
21641 (setq feats
21642 (delq nil (mapcar
21643 (lambda (f)
21644 (if (and (string-match feature-re f)
21645 (not (string-match remove-re f)))
21646 f nil))
21647 feats)))
21648 'string-lessp)
21649 (list "org-version" "org")))
21650 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21651 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21652 load-uncore load-misses)
21653 (setq load-misses
21654 (delq 't
21655 (mapcar (lambda (f)
21656 (or (org-load-noerror-mustsuffix (concat org-dir f))
21657 (and (string= org-dir contrib-dir)
21658 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21659 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21660 (add-to-list 'load-uncore f 'append)
21663 lfeat)))
21664 (when load-uncore
21665 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21666 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21667 (if load-misses
21668 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21669 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21670 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21672 ;;;###autoload
21673 (defun org-customize ()
21674 "Call the customize function with org as argument."
21675 (interactive)
21676 (org-load-modules-maybe)
21677 (org-require-autoloaded-modules)
21678 (customize-browse 'org))
21680 (defun org-create-customize-menu ()
21681 "Create a full customization menu for Org mode, insert it into the menu."
21682 (interactive)
21683 (org-load-modules-maybe)
21684 (org-require-autoloaded-modules)
21685 (if (fboundp 'customize-menu-create)
21686 (progn
21687 (easy-menu-change
21688 '("Org") "Customize"
21689 `(["Browse Org group" org-customize t]
21690 "--"
21691 ,(customize-menu-create 'org)
21692 ["Set" Custom-set t]
21693 ["Save" Custom-save t]
21694 ["Reset to Current" Custom-reset-current t]
21695 ["Reset to Saved" Custom-reset-saved t]
21696 ["Reset to Standard Settings" Custom-reset-standard t]))
21697 (message "\"Org\"-menu now contains full customization menu"))
21698 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21700 ;;;; Miscellaneous stuff
21702 ;;; Generally useful functions
21704 (defun org-get-at-eol (property n)
21705 "Get text property PROPERTY at the end of line less N characters."
21706 (get-text-property (- (point-at-eol) n) property))
21708 (defun org-find-text-property-in-string (prop s)
21709 "Return the first non-nil value of property PROP in string S."
21710 (or (get-text-property 0 prop s)
21711 (get-text-property (or (next-single-property-change 0 prop s) 0)
21712 prop s)))
21714 (defun org-display-warning (message)
21715 "Display the given MESSAGE as a warning."
21716 (display-warning 'org message :warning))
21718 (defun org-eval (form)
21719 "Eval FORM and return result."
21720 (condition-case error
21721 (eval form)
21722 (error (format "%%![Error: %s]" error))))
21724 (defun org-in-clocktable-p ()
21725 "Check if the cursor is in a clocktable."
21726 (let ((pos (point)) start)
21727 (save-excursion
21728 (end-of-line 1)
21729 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21730 (setq start (match-beginning 0))
21731 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21732 (>= (match-end 0) pos)
21733 start))))
21735 (defun org-in-verbatim-emphasis ()
21736 (save-match-data
21737 (and (org-in-regexp org-verbatim-re 2)
21738 (>= (point) (match-beginning 3))
21739 (<= (point) (match-end 4)))))
21741 (defun org-overlay-display (ovl text &optional face evap)
21742 "Make overlay OVL display TEXT with face FACE."
21743 (overlay-put ovl 'display text)
21744 (if face (overlay-put ovl 'face face))
21745 (if evap (overlay-put ovl 'evaporate t)))
21747 (defun org-overlay-before-string (ovl text &optional face evap)
21748 "Make overlay OVL display TEXT with face FACE."
21749 (if face (org-add-props text nil 'face face))
21750 (overlay-put ovl 'before-string text)
21751 (if evap (overlay-put ovl 'evaporate t)))
21753 (defun org-find-overlays (prop &optional pos delete)
21754 "Find all overlays specifying PROP at POS or point.
21755 If DELETE is non-nil, delete all those overlays."
21756 (let (found)
21757 (dolist (ov (overlays-at (or pos (point))) found)
21758 (cond ((not (overlay-get ov prop)))
21759 (delete (delete-overlay ov))
21760 (t (push ov found))))))
21762 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21763 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21764 (if (and marker (marker-buffer marker)
21765 (buffer-live-p (marker-buffer marker)))
21766 (progn
21767 (pop-to-buffer-same-window (marker-buffer marker))
21768 (when (or (> marker (point-max)) (< marker (point-min)))
21769 (widen))
21770 (goto-char marker)
21771 (org-show-context 'org-goto))
21772 (if bookmark
21773 (bookmark-jump bookmark)
21774 (error "Cannot find location"))))
21776 (defun org-quote-csv-field (s)
21777 "Quote field for inclusion in CSV material."
21778 (if (string-match "[\",]" s)
21779 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21782 (defun org-force-self-insert (N)
21783 "Needed to enforce self-insert under remapping."
21784 (interactive "p")
21785 (self-insert-command N))
21787 (defun org-string-width (s)
21788 "Compute width of string, ignoring invisible characters.
21789 This ignores character with invisibility property `org-link', and also
21790 characters with property `org-cwidth', because these will become invisible
21791 upon the next fontification round."
21792 (let (b l)
21793 (when (or (eq t buffer-invisibility-spec)
21794 (assq 'org-link buffer-invisibility-spec))
21795 (while (setq b (text-property-any 0 (length s)
21796 'invisible 'org-link s))
21797 (setq s (concat (substring s 0 b)
21798 (substring s (or (next-single-property-change
21799 b 'invisible s)
21800 (length s)))))))
21801 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21802 (setq s (concat (substring s 0 b)
21803 (substring s (or (next-single-property-change
21804 b 'org-cwidth s)
21805 (length s))))))
21806 (setq l (string-width s) b -1)
21807 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21808 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21811 (defun org-shorten-string (s maxlength)
21812 "Shorten string S so that it is no longer than MAXLENGTH characters.
21813 If the string is shorter or has length MAXLENGTH, just return the
21814 original string. If it is longer, the functions finds a space in the
21815 string, breaks this string off at that locations and adds three dots
21816 as ellipsis. Including the ellipsis, the string will not be longer
21817 than MAXLENGTH. If finding a good breaking point in the string does
21818 not work, the string is just chopped off in the middle of a word
21819 if necessary."
21820 (if (<= (length s) maxlength)
21822 (let* ((n (max (- maxlength 4) 1))
21823 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21824 (if (string-match re s)
21825 (concat (match-string 1 s) "...")
21826 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21828 (defun org-get-indentation (&optional line)
21829 "Get the indentation of the current line, interpreting tabs.
21830 When LINE is given, assume it represents a line and compute its indentation."
21831 (if line
21832 (when (string-match "^ *" (org-remove-tabs line))
21833 (match-end 0))
21834 (save-excursion
21835 (beginning-of-line 1)
21836 (skip-chars-forward " \t")
21837 (current-column))))
21839 (defun org-get-string-indentation (s)
21840 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21841 (let ((n -1) (i 0) (w tab-width) c)
21842 (catch 'exit
21843 (while (< (setq n (1+ n)) (length s))
21844 (setq c (aref s n))
21845 (cond ((= c ?\ ) (setq i (1+ i)))
21846 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21847 (t (throw 'exit t)))))
21850 (defun org-remove-tabs (s &optional width)
21851 "Replace tabulators in S with spaces.
21852 Assumes that s is a single line, starting in column 0."
21853 (setq width (or width tab-width))
21854 (while (string-match "\t" s)
21855 (setq s (replace-match
21856 (make-string
21857 (- (* width (/ (+ (match-beginning 0) width) width))
21858 (match-beginning 0)) ?\ )
21859 t t s)))
21862 (defun org-fix-indentation (line ind)
21863 "Fix indentation in LINE.
21864 IND is a cons cell with target and minimum indentation.
21865 If the current indentation in LINE is smaller than the minimum,
21866 leave it alone. If it is larger than ind, set it to the target."
21867 (let* ((l (org-remove-tabs line))
21868 (i (org-get-indentation l))
21869 (i1 (car ind)) (i2 (cdr ind)))
21870 (when (>= i i2) (setq l (substring line i2)))
21871 (if (> i1 0)
21872 (concat (make-string i1 ?\ ) l)
21873 l)))
21875 (defun org-remove-indentation (code &optional n)
21876 "Remove maximum common indentation in string CODE and return it.
21877 N may optionally be the number of columns to remove. Return CODE
21878 as-is if removal failed."
21879 (with-temp-buffer
21880 (insert code)
21881 (if (org-do-remove-indentation n) (buffer-string) code)))
21883 (defun org-do-remove-indentation (&optional n)
21884 "Remove the maximum common indentation from the buffer.
21885 When optional argument N is a positive integer, remove exactly
21886 that much characters from indentation, if possible. Return nil
21887 if it fails."
21888 (catch :exit
21889 (goto-char (point-min))
21890 ;; Find maximum common indentation, if not specified.
21891 (let ((n (or n
21892 (let ((min-ind (point-max)))
21893 (save-excursion
21894 (while (re-search-forward "^[ \t]*\\S-" nil t)
21895 (let ((ind (1- (current-column))))
21896 (if (zerop ind) (throw :exit nil)
21897 (setq min-ind (min min-ind ind))))))
21898 min-ind))))
21899 (if (zerop n) (throw :exit nil)
21900 ;; Remove exactly N indentation, but give up if not possible.
21901 (while (not (eobp))
21902 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21903 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21904 ((< ind n) (throw :exit nil))
21905 (t (indent-line-to (- ind n))))
21906 (forward-line)))
21907 ;; Signal success.
21908 t))))
21910 (defun org-fill-template (template alist)
21911 "Find each %key of ALIST in TEMPLATE and replace it."
21912 (let ((case-fold-search nil))
21913 (dolist (entry (sort (copy-sequence alist)
21914 (lambda (a b) (< (length (car a)) (length (car b))))))
21915 (setq template
21916 (replace-regexp-in-string
21917 (concat "%" (regexp-quote (car entry)))
21918 (or (cdr entry) "") template t t)))
21919 template))
21921 (defun org-base-buffer (buffer)
21922 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21923 (if (not buffer)
21924 buffer
21925 (or (buffer-base-buffer buffer)
21926 buffer)))
21928 (defun org-wrap (string &optional width lines)
21929 "Wrap string to either a number of lines, or a width in characters.
21930 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21931 that costs. If there is a word longer than WIDTH, the text is actually
21932 wrapped to the length of that word.
21933 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21934 many lines, whatever width that takes.
21935 The return value is a list of lines, without newlines at the end."
21936 (let* ((words (org-split-string string "[ \t\n]+"))
21937 (maxword (apply 'max (mapcar 'org-string-width words)))
21938 w ll)
21939 (cond (width
21940 (org-do-wrap words (max maxword width)))
21941 (lines
21942 (setq w maxword)
21943 (setq ll (org-do-wrap words maxword))
21944 (if (<= (length ll) lines)
21946 (setq ll words)
21947 (while (> (length ll) lines)
21948 (setq w (1+ w))
21949 (setq ll (org-do-wrap words w)))
21950 ll))
21951 (t (error "Cannot wrap this")))))
21953 (defun org-do-wrap (words width)
21954 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21955 (let (lines line)
21956 (while words
21957 (setq line (pop words))
21958 (while (and words (< (+ (length line) (length (car words))) width))
21959 (setq line (concat line " " (pop words))))
21960 (setq lines (push line lines)))
21961 (nreverse lines)))
21963 (defun org-split-string (string &optional separators)
21964 "Splits STRING into substrings at SEPARATORS.
21965 SEPARATORS is a regular expression.
21966 No empty strings are returned if there are matches at the beginning
21967 and end of string."
21968 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21969 (let ((start 0) notfirst list)
21970 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21971 (if (and notfirst
21972 (= start (match-beginning 0))
21973 (< start (length string)))
21974 (1+ start) start))
21975 (< (match-beginning 0) (length string)))
21976 (setq notfirst t)
21977 (or (eq (match-beginning 0) 0)
21978 (and (eq (match-beginning 0) (match-end 0))
21979 (eq (match-beginning 0) start))
21980 (push (substring string start (match-beginning 0)) list))
21981 (setq start (match-end 0)))
21982 (or (eq start (length string))
21983 (push (substring string start) list))
21984 (nreverse list)))
21986 (defun org-quote-vert (s)
21987 "Replace \"|\" with \"\\vert\"."
21988 (while (string-match "|" s)
21989 (setq s (replace-match "\\vert" t t s)))
21992 (defun org-uuidgen-p (s)
21993 "Is S an ID created by UUIDGEN?"
21994 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21996 (defun org-in-src-block-p (&optional inside)
21997 "Whether point is in a code source block.
21998 When INSIDE is non-nil, don't consider we are within a src block
21999 when point is at #+BEGIN_SRC or #+END_SRC."
22000 (let ((case-fold-search t))
22001 (or (and (eq (get-char-property (point) 'src-block) t))
22002 (and (not inside)
22003 (save-match-data
22004 (save-excursion
22005 (beginning-of-line)
22006 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22008 (defun org-context ()
22009 "Return a list of contexts of the current cursor position.
22010 If several contexts apply, all are returned.
22011 Each context entry is a list with a symbol naming the context, and
22012 two positions indicating start and end of the context. Possible
22013 contexts are:
22015 :headline anywhere in a headline
22016 :headline-stars on the leading stars in a headline
22017 :todo-keyword on a TODO keyword (including DONE) in a headline
22018 :tags on the TAGS in a headline
22019 :priority on the priority cookie in a headline
22020 :item on the first line of a plain list item
22021 :item-bullet on the bullet/number of a plain list item
22022 :checkbox on the checkbox in a plain list item
22023 :table in an Org table
22024 :table-special on a special filed in a table
22025 :table-table in a table.el table
22026 :clocktable in a clocktable
22027 :src-block in a source block
22028 :link on a hyperlink
22029 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22030 :target on a <<target>>
22031 :radio-target on a <<<radio-target>>>
22032 :latex-fragment on a LaTeX fragment
22033 :latex-preview on a LaTeX fragment with overlaid preview image
22035 This function expects the position to be visible because it uses font-lock
22036 faces as a help to recognize the following contexts: :table-special, :link,
22037 and :keyword."
22038 (let* ((f (get-text-property (point) 'face))
22039 (faces (if (listp f) f (list f)))
22040 (case-fold-search t)
22041 (p (point)) clist o)
22042 ;; First the large context
22043 (cond
22044 ((org-at-heading-p t)
22045 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22046 (when (progn
22047 (beginning-of-line 1)
22048 (looking-at org-todo-line-tags-regexp))
22049 (push (org-point-in-group p 1 :headline-stars) clist)
22050 (push (org-point-in-group p 2 :todo-keyword) clist)
22051 (push (org-point-in-group p 4 :tags) clist))
22052 (goto-char p)
22053 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22054 (when (looking-at "\\[#[A-Z0-9]\\]")
22055 (push (org-point-in-group p 0 :priority) clist)))
22057 ((org-at-item-p)
22058 (push (org-point-in-group p 2 :item-bullet) clist)
22059 (push (list :item (point-at-bol)
22060 (save-excursion (org-end-of-item) (point)))
22061 clist)
22062 (and (org-at-item-checkbox-p)
22063 (push (org-point-in-group p 0 :checkbox) clist)))
22065 ((org-at-table-p)
22066 (push (list :table (org-table-begin) (org-table-end)) clist)
22067 (when (memq 'org-formula faces)
22068 (push (list :table-special
22069 (previous-single-property-change p 'face)
22070 (next-single-property-change p 'face)) clist)))
22071 ((org-at-table-p 'any)
22072 (push (list :table-table) clist)))
22073 (goto-char p)
22075 (let ((case-fold-search t))
22076 ;; New the "medium" contexts: clocktables, source blocks
22077 (cond ((org-in-clocktable-p)
22078 (push (list :clocktable
22079 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22080 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22081 (match-beginning 1))
22082 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22083 (match-end 0))) clist))
22084 ((org-in-src-block-p)
22085 (push (list :src-block
22086 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22087 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22088 (match-beginning 1))
22089 (and (search-forward "#+END_SRC" nil t)
22090 (match-beginning 0))) clist))))
22091 (goto-char p)
22093 ;; Now the small context
22094 (cond
22095 ((org-at-timestamp-p)
22096 (push (org-point-in-group p 0 :timestamp) clist))
22097 ((memq 'org-link faces)
22098 (push (list :link
22099 (previous-single-property-change p 'face)
22100 (next-single-property-change p 'face)) clist))
22101 ((memq 'org-special-keyword faces)
22102 (push (list :keyword
22103 (previous-single-property-change p 'face)
22104 (next-single-property-change p 'face)) clist))
22105 ((org-at-target-p)
22106 (push (org-point-in-group p 0 :target) clist)
22107 (goto-char (1- (match-beginning 0)))
22108 (when (looking-at org-radio-target-regexp)
22109 (push (org-point-in-group p 0 :radio-target) clist))
22110 (goto-char p))
22111 ((setq o (cl-some
22112 (lambda (o)
22113 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22115 (overlays-at (point))))
22116 (push (list :latex-fragment
22117 (overlay-start o) (overlay-end o)) clist)
22118 (push (list :latex-preview
22119 (overlay-start o) (overlay-end o)) clist))
22120 ((org-inside-LaTeX-fragment-p)
22121 ;; FIXME: positions wrong.
22122 (push (list :latex-fragment (point) (point)) clist)))
22124 (setq clist (nreverse (delq nil clist)))
22125 clist))
22127 (defun org-in-regexp (regexp &optional nlines visually)
22128 "Check if point is inside a match of REGEXP.
22130 Normally only the current line is checked, but you can include
22131 NLINES extra lines around point into the search. If VISUALLY is
22132 set, require that the cursor is not after the match but really
22133 on, so that the block visually is on the match.
22135 Return nil or a cons cell (BEG . END) where BEG and END are,
22136 respectively, the positions at the beginning and the end of the
22137 match."
22138 (catch :exit
22139 (let ((pos (point))
22140 (eol (line-end-position (if nlines (1+ nlines) 1))))
22141 (save-excursion
22142 (beginning-of-line (- 1 (or nlines 0)))
22143 (while (and (re-search-forward regexp eol t)
22144 (<= (match-beginning 0) pos))
22145 (let ((end (match-end 0)))
22146 (when (or (> end pos) (and (= end pos) (not visually)))
22147 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22149 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22150 "Non-nil when point is between matches of START-RE and END-RE.
22152 Also return a non-nil value when point is on one of the matches.
22154 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22155 buffer positions. Default values are the positions of headlines
22156 surrounding the point.
22158 The functions returns a cons cell whose car (resp. cdr) is the
22159 position before START-RE (resp. after END-RE)."
22160 (save-match-data
22161 (let ((pos (point))
22162 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22163 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22164 beg end)
22165 (save-excursion
22166 ;; Point is on a block when on START-RE or if START-RE can be
22167 ;; found before it...
22168 (and (or (org-in-regexp start-re)
22169 (re-search-backward start-re limit-up t))
22170 (setq beg (match-beginning 0))
22171 ;; ... and END-RE after it...
22172 (goto-char (match-end 0))
22173 (re-search-forward end-re limit-down t)
22174 (> (setq end (match-end 0)) pos)
22175 ;; ... without another START-RE in-between.
22176 (goto-char (match-beginning 0))
22177 (not (re-search-backward start-re (1+ beg) t))
22178 ;; Return value.
22179 (cons beg end))))))
22181 (defun org-in-block-p (names)
22182 "Non-nil when point belongs to a block whose name belongs to NAMES.
22184 NAMES is a list of strings containing names of blocks.
22186 Return first block name matched, or nil. Beware that in case of
22187 nested blocks, the returned name may not belong to the closest
22188 block from point."
22189 (save-match-data
22190 (catch 'exit
22191 (let ((case-fold-search t)
22192 (lim-up (save-excursion (outline-previous-heading)))
22193 (lim-down (save-excursion (outline-next-heading))))
22194 (dolist (name names)
22195 (let ((n (regexp-quote name)))
22196 (when (org-between-regexps-p
22197 (concat "^[ \t]*#\\+begin_" n)
22198 (concat "^[ \t]*#\\+end_" n)
22199 lim-up lim-down)
22200 (throw 'exit n)))))
22201 nil)))
22203 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22204 "Call `multi-occur' with buffers for all agenda files."
22205 (interactive "sOrg-files matching: ")
22206 (let* ((files (org-agenda-files))
22207 (tnames (mapcar #'file-truename files))
22208 (extra org-agenda-text-search-extra-files))
22209 (when (eq (car extra) 'agenda-archives)
22210 (setq extra (cdr extra))
22211 (setq files (org-add-archive-files files)))
22212 (dolist (f extra)
22213 (unless (member (file-truename f) tnames)
22214 (unless (member f files) (setq files (append files (list f))))
22215 (setq tnames (append tnames (list (file-truename f))))))
22216 (multi-occur
22217 (mapcar (lambda (x)
22218 (with-current-buffer
22219 ;; FIXME: Why not just (find-file-noselect x)?
22220 ;; Is it to avoid the "revert buffer" prompt?
22221 (or (get-file-buffer x) (find-file-noselect x))
22222 (widen)
22223 (current-buffer)))
22224 files)
22225 regexp)))
22227 (add-hook 'occur-mode-find-occurrence-hook
22228 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22230 (defun org-occur-link-in-agenda-files ()
22231 "Create a link and search for it in the agendas.
22232 The link is not stored in `org-stored-links', it is just created
22233 for the search purpose."
22234 (interactive)
22235 (let ((link (condition-case nil
22236 (org-store-link nil)
22237 (error "Unable to create a link to here"))))
22238 (org-occur-in-agenda-files (regexp-quote link))))
22240 (defun org-reverse-string (string)
22241 "Return the reverse of STRING."
22242 (apply 'string (reverse (string-to-list string))))
22244 ;; defsubst org-uniquify must be defined before first use
22246 (defun org-uniquify-alist (alist)
22247 "Merge elements of ALIST with the same key.
22249 For example, in this alist:
22251 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22252 => \\='((a 1 3) (b 2))
22254 merge (a 1) and (a 3) into (a 1 3).
22256 The function returns the new ALIST."
22257 (let (rtn)
22258 (dolist (e alist rtn)
22259 (let (n)
22260 (if (not (assoc (car e) rtn))
22261 (push e rtn)
22262 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22263 (setq rtn (assq-delete-all (car e) rtn))
22264 (push n rtn))))))
22266 (defun org-delete-all (elts list)
22267 "Remove all elements in ELTS from LIST.
22268 Comparison is done with `equal'. It is a destructive operation
22269 that may remove elements by altering the list structure."
22270 (while elts
22271 (setq list (delete (pop elts) list)))
22272 list)
22274 (defun org-back-over-empty-lines ()
22275 "Move backwards over whitespace, to the beginning of the first empty line.
22276 Returns the number of empty lines passed."
22277 (let ((pos (point)))
22278 (if (cdr (assq 'heading org-blank-before-new-entry))
22279 (skip-chars-backward " \t\n\r")
22280 (unless (eobp)
22281 (forward-line -1)))
22282 (beginning-of-line 2)
22283 (goto-char (min (point) pos))
22284 (count-lines (point) pos)))
22286 (defun org-skip-whitespace ()
22287 (skip-chars-forward " \t\n\r"))
22289 (defun org-point-in-group (point group &optional context)
22290 "Check if POINT is in match-group GROUP.
22291 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22292 match. If the match group does not exist or point is not inside it,
22293 return nil."
22294 (and (match-beginning group)
22295 (>= point (match-beginning group))
22296 (<= point (match-end group))
22297 (if context
22298 (list context (match-beginning group) (match-end group))
22299 t)))
22301 (defun org-switch-to-buffer-other-window (&rest args)
22302 "Switch to buffer in a second window on the current frame.
22303 In particular, do not allow pop-up frames.
22304 Returns the newly created buffer."
22305 (org-no-popups
22306 (apply 'switch-to-buffer-other-window args)))
22308 (defun org-combine-plists (&rest plists)
22309 "Create a single property list from all plists in PLISTS.
22310 The process starts by copying the first list, and then setting properties
22311 from the other lists. Settings in the last list are the most significant
22312 ones and overrule settings in the other lists."
22313 (let ((rtn (copy-sequence (pop plists)))
22314 p v ls)
22315 (while plists
22316 (setq ls (pop plists))
22317 (while ls
22318 (setq p (pop ls) v (pop ls))
22319 (setq rtn (plist-put rtn p v))))
22320 rtn))
22322 (defun org-replace-escapes (string table)
22323 "Replace %-escapes in STRING with values in TABLE.
22324 TABLE is an association list with keys like \"%a\" and string values.
22325 The sequences in STRING may contain normal field width and padding information,
22326 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22327 so values can contain further %-escapes if they are define later in TABLE."
22328 (let ((tbl (copy-alist table))
22329 (case-fold-search nil)
22330 (pchg 0)
22331 re rpl)
22332 (dolist (e tbl)
22333 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22334 (when (and (cdr e) (string-match re (cdr e)))
22335 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22336 (safe "SREF"))
22337 (add-text-properties 0 3 (list 'sref sref) safe)
22338 (setcdr e (replace-match safe t t (cdr e)))))
22339 (while (string-match re string)
22340 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22341 (cdr e)))
22342 (setq string (replace-match rpl t t string))))
22343 (while (setq pchg (next-property-change pchg string))
22344 (let ((sref (get-text-property pchg 'sref string)))
22345 (when (and sref (string-match "SREF" string pchg))
22346 (setq string (replace-match sref t t string)))))
22347 string))
22349 (defun org-find-base-buffer-visiting (file)
22350 "Like `find-buffer-visiting' but always return the base buffer and
22351 not an indirect buffer."
22352 (let ((buf (or (get-file-buffer file)
22353 (find-buffer-visiting file))))
22354 (if buf
22355 (or (buffer-base-buffer buf) buf)
22356 nil)))
22358 ;;; TODO: Only called once, from ox-odt which should probably use
22359 ;;; org-export-inline-image-p or something.
22360 (defun org-file-image-p (file)
22361 "Return non-nil if FILE is an image."
22362 (save-match-data
22363 (string-match (image-file-name-regexp) file)))
22365 (defun org-get-cursor-date (&optional with-time)
22366 "Return the date at cursor in as a time.
22367 This works in the calendar and in the agenda, anywhere else it just
22368 returns the current time.
22369 If WITH-TIME is non-nil, returns the time of the event at point (in
22370 the agenda) or the current time of the day."
22371 (let (date day defd tp hod mod)
22372 (when with-time
22373 (setq tp (get-text-property (point) 'time))
22374 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22375 (setq hod (string-to-number (match-string 1 tp))
22376 mod (string-to-number (match-string 2 tp))))
22377 (or tp (let ((now (decode-time)))
22378 (setq hod (nth 2 now)
22379 mod (nth 1 now)))))
22380 (cond
22381 ((eq major-mode 'calendar-mode)
22382 (setq date (calendar-cursor-to-date)
22383 defd (encode-time 0 (or mod 0) (or hod 0)
22384 (nth 1 date) (nth 0 date) (nth 2 date))))
22385 ((eq major-mode 'org-agenda-mode)
22386 (setq day (get-text-property (point) 'day))
22387 (when day
22388 (setq date (calendar-gregorian-from-absolute day)
22389 defd (encode-time 0 (or mod 0) (or hod 0)
22390 (nth 1 date) (nth 0 date) (nth 2 date))))))
22391 (or defd (current-time))))
22393 (defun org-mark-subtree (&optional up)
22394 "Mark the current subtree.
22395 This puts point at the start of the current subtree, and mark at
22396 the end. If a numeric prefix UP is given, move up into the
22397 hierarchy of headlines by UP levels before marking the subtree."
22398 (interactive "P")
22399 (org-with-limited-levels
22400 (cond ((org-at-heading-p) (beginning-of-line))
22401 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22402 (t (outline-previous-visible-heading 1))))
22403 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22404 (if (called-interactively-p 'any)
22405 (call-interactively 'org-mark-element)
22406 (org-mark-element)))
22408 (defun org-file-newer-than-p (file time)
22409 "Non-nil if FILE is newer than TIME.
22410 FILE is a filename, as a string, TIME is a list of integers, as
22411 returned by, e.g., `current-time'."
22412 (and (file-exists-p file)
22413 ;; Only compare times up to whole seconds as some file-systems
22414 ;; (e.g. HFS+) do not retain any finer granularity. As
22415 ;; a consequence, make sure we return non-nil when the two
22416 ;; times are equal.
22417 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22418 (cl-subseq time 0 2)))))
22420 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22421 "Compile a SOURCE file using PROCESS.
22423 PROCESS is either a function or a list of shell commands, as
22424 strings. EXT is a file extension, without the leading dot, as
22425 a string. It is used to check if the process actually succeeded.
22427 PROCESS must create a file with the same base name and directory
22428 as SOURCE, but ending with EXT. The function then returns its
22429 filename. Otherwise, it raises an error. The error message can
22430 then be refined by providing string ERR-MSG, which is appended to
22431 the standard message.
22433 If PROCESS is a function, it is called with a single argument:
22434 the SOURCE file.
22436 If it is a list of commands, each of them is called using
22437 `shell-command'. By default, in each command, %b, %f, %F, %o and
22438 %O are replaced with, respectively, SOURCE base name, name, full
22439 name, directory and absolute output file name. It is possible,
22440 however, to use more place-holders by specifying them in optional
22441 argument SPEC, as an alist following the pattern
22443 (CHARACTER . REPLACEMENT-STRING).
22445 When PROCESS is a list of commands, optional argument LOG-BUF can
22446 be set to a buffer or a buffer name. `shell-command' then uses
22447 it for output."
22448 (let* ((base-name (file-name-base source))
22449 (full-name (file-truename source))
22450 (out-dir (or (file-name-directory source) "./"))
22451 (output (expand-file-name (concat base-name "." ext) out-dir))
22452 (time (current-time))
22453 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22454 (save-window-excursion
22455 (pcase process
22456 ((pred functionp) (funcall process (shell-quote-argument source)))
22457 ((pred consp)
22458 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22459 (spec (append spec
22460 `((?b . ,(shell-quote-argument base-name))
22461 (?f . ,(shell-quote-argument source))
22462 (?F . ,(shell-quote-argument full-name))
22463 (?o . ,(shell-quote-argument out-dir))
22464 (?O . ,(shell-quote-argument output))))))
22465 (dolist (command process)
22466 (shell-command (format-spec command spec) log-buf))
22467 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22468 (_ (error "No valid command to process %S%s" source err-msg))))
22469 ;; Check for process failure. Output file is expected to be
22470 ;; located in the same directory as SOURCE.
22471 (unless (org-file-newer-than-p output time)
22472 (error (format "File %S wasn't produced%s" output err-msg)))
22473 output))
22475 ;;; Indentation
22477 (defun org--get-expected-indentation (element contentsp)
22478 "Expected indentation column for current line, according to ELEMENT.
22479 ELEMENT is an element containing point. CONTENTSP is non-nil
22480 when indentation is to be computed according to contents of
22481 ELEMENT."
22482 (let ((type (org-element-type element))
22483 (start (org-element-property :begin element))
22484 (post-affiliated (org-element-property :post-affiliated element)))
22485 (org-with-wide-buffer
22486 (cond
22487 (contentsp
22488 (cl-case type
22489 ((diary-sexp footnote-definition) 0)
22490 ((headline inlinetask nil)
22491 (if (not org-adapt-indentation) 0
22492 (let ((level (org-current-level)))
22493 (if level (1+ level) 0))))
22494 ((item plain-list) (org-list-item-body-column post-affiliated))
22496 (goto-char start)
22497 (org-get-indentation))))
22498 ((memq type '(headline inlinetask nil))
22499 (if (org-match-line "[ \t]*$")
22500 (org--get-expected-indentation element t)
22502 ((memq type '(diary-sexp footnote-definition)) 0)
22503 ;; First paragraph of a footnote definition or an item.
22504 ;; Indent like parent.
22505 ((< (line-beginning-position) start)
22506 (org--get-expected-indentation
22507 (org-element-property :parent element) t))
22508 ;; At first line: indent according to previous sibling, if any,
22509 ;; ignoring footnote definitions and inline tasks, or parent's
22510 ;; contents.
22511 ((= (line-beginning-position) start)
22512 (catch 'exit
22513 (while t
22514 (if (= (point-min) start) (throw 'exit 0)
22515 (goto-char (1- start))
22516 (let* ((previous (org-element-at-point))
22517 (parent previous))
22518 (while (and parent (<= (org-element-property :end parent) start))
22519 (setq previous parent
22520 parent (org-element-property :parent parent)))
22521 (cond
22522 ((not previous) (throw 'exit 0))
22523 ((> (org-element-property :end previous) start)
22524 (throw 'exit (org--get-expected-indentation previous t)))
22525 ((memq (org-element-type previous)
22526 '(footnote-definition inlinetask))
22527 (setq start (org-element-property :begin previous)))
22528 (t (goto-char (org-element-property :begin previous))
22529 (throw 'exit
22530 (if (bolp) (org-get-indentation)
22531 ;; At first paragraph in an item or
22532 ;; a footnote definition.
22533 (org--get-expected-indentation
22534 (org-element-property :parent previous) t))))))))))
22535 ;; Otherwise, move to the first non-blank line above.
22537 (beginning-of-line)
22538 (let ((pos (point)))
22539 (skip-chars-backward " \r\t\n")
22540 (cond
22541 ;; Two blank lines end a footnote definition or a plain
22542 ;; list. When we indent an empty line after them, the
22543 ;; containing list or footnote definition is over, so it
22544 ;; qualifies as a previous sibling. Therefore, we indent
22545 ;; like its first line.
22546 ((and (memq type '(footnote-definition plain-list))
22547 (> (count-lines (point) pos) 2))
22548 (goto-char start)
22549 (org-get-indentation))
22550 ;; Line above is the first one of a paragraph at the
22551 ;; beginning of an item or a footnote definition. Indent
22552 ;; like parent.
22553 ((< (line-beginning-position) start)
22554 (org--get-expected-indentation
22555 (org-element-property :parent element) t))
22556 ;; Line above is the beginning of an element, i.e., point
22557 ;; was originally on the blank lines between element's start
22558 ;; and contents.
22559 ((= (line-beginning-position) post-affiliated)
22560 (org--get-expected-indentation element t))
22561 ;; POS is after contents in a greater element. Indent like
22562 ;; the beginning of the element.
22564 ;; As a special case, if point is at the end of a footnote
22565 ;; definition or an item, indent like the very last element
22566 ;; within. If that last element is an item, indent like its
22567 ;; contents.
22568 ((and (not (eq type 'paragraph))
22569 (let ((cend (org-element-property :contents-end element)))
22570 (and cend (<= cend pos))))
22571 (if (memq type '(footnote-definition item plain-list))
22572 (let ((last (org-element-at-point)))
22573 (org--get-expected-indentation
22574 last (eq (org-element-type last) 'item)))
22575 (goto-char start)
22576 (org-get-indentation)))
22577 ;; In any other case, indent like the current line.
22578 (t (org-get-indentation)))))))))
22580 (defun org--align-node-property ()
22581 "Align node property at point.
22582 Alignment is done according to `org-property-format', which see."
22583 (when (save-excursion
22584 (beginning-of-line)
22585 (looking-at org-property-re))
22586 (replace-match
22587 (concat (match-string 4)
22588 (org-trim
22589 (format org-property-format (match-string 1) (match-string 3))))
22590 t t)))
22592 (defun org-indent-line ()
22593 "Indent line depending on context.
22595 Indentation is done according to the following rules:
22597 - Footnote definitions, diary sexps, headlines and inline tasks
22598 have to start at column 0.
22600 - On the very first line of an element, consider, in order, the
22601 next rules until one matches:
22603 1. If there's a sibling element before, ignoring footnote
22604 definitions and inline tasks, indent like its first line.
22606 2. If element has a parent, indent like its contents. More
22607 precisely, if parent is an item, indent after the
22608 description part, if any, or the bullet (see
22609 `org-list-description-max-indent'). Else, indent like
22610 parent's first line.
22612 3. Otherwise, indent relatively to current level, if
22613 `org-adapt-indentation' is non-nil, or to left margin.
22615 - On a blank line at the end of an element, indent according to
22616 the type of the element. More precisely
22618 1. If element is a plain list, an item, or a footnote
22619 definition, indent like the very last element within.
22621 2. If element is a paragraph, indent like its last non blank
22622 line.
22624 3. Otherwise, indent like its very first line.
22626 - In the code part of a source block, use language major mode
22627 to indent current line if `org-src-tab-acts-natively' is
22628 non-nil. If it is nil, do nothing.
22630 - Otherwise, indent like the first non-blank line above.
22632 The function doesn't indent an item as it could break the whole
22633 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22634 `\\[org-shiftmetaright]'.
22636 Also align node properties according to `org-property-format'."
22637 (interactive)
22638 (cond
22639 (orgstruct-is-++
22640 (let ((indent-line-function
22641 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22642 (indent-according-to-mode)))
22643 ((org-at-heading-p) 'noindent)
22645 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22646 (type (org-element-type element)))
22647 (cond ((and (memq type '(plain-list item))
22648 (= (line-beginning-position)
22649 (org-element-property :post-affiliated element)))
22650 'noindent)
22651 ((and (eq type 'latex-environment)
22652 (>= (point) (org-element-property :post-affiliated element))
22653 (< (point) (org-with-wide-buffer
22654 (goto-char (org-element-property :end element))
22655 (skip-chars-backward " \r\t\n")
22656 (line-beginning-position 2))))
22657 'noindent)
22658 ((and (eq type 'src-block)
22659 org-src-tab-acts-natively
22660 (> (line-beginning-position)
22661 (org-element-property :post-affiliated element))
22662 (< (line-beginning-position)
22663 (org-with-wide-buffer
22664 (goto-char (org-element-property :end element))
22665 (skip-chars-backward " \r\t\n")
22666 (line-beginning-position))))
22667 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22669 (let ((column (org--get-expected-indentation element nil)))
22670 ;; Preserve current column.
22671 (if (<= (current-column) (current-indentation))
22672 (indent-line-to column)
22673 (save-excursion (indent-line-to column))))
22674 ;; Align node property. Also preserve current column.
22675 (when (eq type 'node-property)
22676 (let ((column (current-column)))
22677 (org--align-node-property)
22678 (org-move-to-column column)))))))))
22680 (defun org-indent-region (start end)
22681 "Indent each non-blank line in the region.
22682 Called from a program, START and END specify the region to
22683 indent. The function will not indent contents of example blocks,
22684 verse blocks and export blocks as leading white spaces are
22685 assumed to be significant there."
22686 (interactive "r")
22687 (save-excursion
22688 (goto-char start)
22689 (skip-chars-forward " \r\t\n")
22690 (unless (eobp) (beginning-of-line))
22691 (let ((indent-to
22692 (lambda (ind pos)
22693 ;; Set IND as indentation for all lines between point and
22694 ;; POS. Blank lines are ignored. Leave point after POS
22695 ;; once done.
22696 (let ((limit (copy-marker pos)))
22697 (while (< (point) limit)
22698 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22699 (forward-line))
22700 (set-marker limit nil))))
22701 (end (copy-marker end)))
22702 (while (< (point) end)
22703 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22704 (let* ((element (org-element-at-point))
22705 (type (org-element-type element))
22706 (element-end (copy-marker (org-element-property :end element)))
22707 (ind (org--get-expected-indentation element nil)))
22708 (cond
22709 ;; Element indented as a single block. Example blocks
22710 ;; preserving indentation are a special case since the
22711 ;; "contents" must not be indented whereas the block
22712 ;; boundaries can.
22713 ((or (memq type '(export-block latex-environment))
22714 (and (eq type 'example-block)
22715 (not
22716 (or org-src-preserve-indentation
22717 (org-element-property :preserve-indent element)))))
22718 (let ((offset (- ind (org-get-indentation))))
22719 (unless (zerop offset)
22720 (indent-rigidly (org-element-property :begin element)
22721 (org-element-property :end element)
22722 offset)))
22723 (goto-char element-end))
22724 ;; Elements indented line wise. Be sure to exclude
22725 ;; example blocks (preserving indentation) and source
22726 ;; blocks from this category as they are treated
22727 ;; specially later.
22728 ((or (memq type '(paragraph table table-row))
22729 (not (or (org-element-property :contents-begin element)
22730 (memq type '(example-block src-block)))))
22731 (when (eq type 'node-property)
22732 (org--align-node-property)
22733 (beginning-of-line))
22734 (funcall indent-to ind (min element-end end)))
22735 ;; Elements consisting of three parts: before the
22736 ;; contents, the contents, and after the contents. The
22737 ;; contents are treated specially, according to the
22738 ;; element type, or not indented at all. Other parts are
22739 ;; indented as a single block.
22741 (let* ((post (copy-marker
22742 (org-element-property :post-affiliated element)))
22743 (cbeg
22744 (copy-marker
22745 (cond
22746 ((not (org-element-property :contents-begin element))
22747 ;; Fake contents for source blocks.
22748 (org-with-wide-buffer
22749 (goto-char post)
22750 (line-beginning-position 2)))
22751 ((memq type '(footnote-definition item plain-list))
22752 ;; Contents in these elements could start on
22753 ;; the same line as the beginning of the
22754 ;; element. Make sure we start indenting
22755 ;; from the second line.
22756 (org-with-wide-buffer
22757 (goto-char post)
22758 (end-of-line)
22759 (skip-chars-forward " \r\t\n")
22760 (if (eobp) (point) (line-beginning-position))))
22761 (t (org-element-property :contents-begin element)))))
22762 (cend (copy-marker
22763 (or (org-element-property :contents-end element)
22764 ;; Fake contents for source blocks.
22765 (org-with-wide-buffer
22766 (goto-char element-end)
22767 (skip-chars-backward " \r\t\n")
22768 (line-beginning-position)))
22769 t)))
22770 ;; Do not change items indentation individually as it
22771 ;; might break the list as a whole. On the other
22772 ;; hand, when at a plain list, indent it as a whole.
22773 (cond ((eq type 'plain-list)
22774 (let ((offset (- ind (org-get-indentation))))
22775 (unless (zerop offset)
22776 (indent-rigidly (org-element-property :begin element)
22777 (org-element-property :end element)
22778 offset))
22779 (goto-char cbeg)))
22780 ((eq type 'item) (goto-char cbeg))
22781 (t (funcall indent-to ind (min cbeg end))))
22782 (when (< (point) end)
22783 (cl-case type
22784 ((example-block verse-block))
22785 (src-block
22786 ;; In a source block, indent source code
22787 ;; according to language major mode, but only if
22788 ;; `org-src-tab-acts-natively' is non-nil.
22789 (when (and (< (point) end) org-src-tab-acts-natively)
22790 (ignore-errors
22791 (org-babel-do-in-edit-buffer
22792 (indent-region (point-min) (point-max))))))
22793 (t (org-indent-region (point) (min cend end))))
22794 (goto-char (min cend end))
22795 (when (< (point) end)
22796 (funcall indent-to ind (min element-end end))))
22797 (set-marker post nil)
22798 (set-marker cbeg nil)
22799 (set-marker cend nil))))
22800 (set-marker element-end nil))))
22801 (set-marker end nil))))
22803 (defun org-indent-drawer ()
22804 "Indent the drawer at point."
22805 (interactive)
22806 (unless (save-excursion
22807 (beginning-of-line)
22808 (looking-at-p org-drawer-regexp))
22809 (user-error "Not at a drawer"))
22810 (let ((element (org-element-at-point)))
22811 (unless (memq (org-element-type element) '(drawer property-drawer))
22812 (user-error "Not at a drawer"))
22813 (org-with-wide-buffer
22814 (org-indent-region (org-element-property :begin element)
22815 (org-element-property :end element))))
22816 (message "Drawer at point indented"))
22818 (defun org-indent-block ()
22819 "Indent the block at point."
22820 (interactive)
22821 (unless (save-excursion
22822 (beginning-of-line)
22823 (let ((case-fold-search t))
22824 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22825 (user-error "Not at a block"))
22826 (let ((element (org-element-at-point)))
22827 (unless (memq (org-element-type element)
22828 '(comment-block center-block dynamic-block example-block
22829 export-block quote-block special-block
22830 src-block verse-block))
22831 (user-error "Not at a block"))
22832 (org-with-wide-buffer
22833 (org-indent-region (org-element-property :begin element)
22834 (org-element-property :end element))))
22835 (message "Block at point indented"))
22838 ;;; Filling
22840 ;; We use our own fill-paragraph and auto-fill functions.
22842 ;; `org-fill-paragraph' relies on adaptive filling and context
22843 ;; checking. Appropriate `fill-prefix' is computed with
22844 ;; `org-adaptive-fill-function'.
22846 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22847 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22848 ;; `org-adaptive-fill-function' value. Internally,
22849 ;; `org-comment-line-break-function' breaks the line.
22851 ;; `org-setup-filling' installs filling and auto-filling related
22852 ;; variables during `org-mode' initialization.
22854 (defvar org-element-paragraph-separate) ; org-element.el
22855 (defun org-setup-filling ()
22856 (require 'org-element)
22857 ;; Prevent auto-fill from inserting unwanted new items.
22858 (when (boundp 'fill-nobreak-predicate)
22859 (setq-local
22860 fill-nobreak-predicate
22861 (org-uniquify
22862 (append fill-nobreak-predicate
22863 '(org-fill-line-break-nobreak-p
22864 org-fill-paragraph-with-timestamp-nobreak-p)))))
22865 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22866 (setq-local paragraph-start paragraph-ending)
22867 (setq-local paragraph-separate paragraph-ending))
22868 (setq-local fill-paragraph-function 'org-fill-paragraph)
22869 (setq-local auto-fill-inhibit-regexp nil)
22870 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22871 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22872 (setq-local comment-line-break-function 'org-comment-line-break-function))
22874 (defun org-fill-line-break-nobreak-p ()
22875 "Non-nil when a new line at point would create an Org line break."
22876 (save-excursion
22877 (skip-chars-backward "[ \t]")
22878 (skip-chars-backward "\\\\")
22879 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22881 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22882 "Non-nil when a new line at point would split a timestamp."
22883 (and (org-at-timestamp-p t)
22884 (not (looking-at org-ts-regexp-both))))
22886 (declare-function message-in-body-p "message" ())
22887 (defvar orgtbl-line-start-regexp) ; From org-table.el
22888 (defun org-adaptive-fill-function ()
22889 "Compute a fill prefix for the current line.
22890 Return fill prefix, as a string, or nil if current line isn't
22891 meant to be filled. For convenience, if `adaptive-fill-regexp'
22892 matches in paragraphs or comments, use it."
22893 (catch 'exit
22894 (when (derived-mode-p 'message-mode)
22895 (save-excursion
22896 (beginning-of-line)
22897 (cond ((not (message-in-body-p)) (throw 'exit nil))
22898 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22899 ((looking-at message-cite-prefix-regexp)
22900 (throw 'exit (match-string-no-properties 0)))
22901 ((looking-at org-outline-regexp)
22902 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22903 (org-with-wide-buffer
22904 (unless (org-at-heading-p)
22905 (let* ((p (line-beginning-position))
22906 (element (save-excursion
22907 (beginning-of-line)
22908 (org-element-at-point)))
22909 (type (org-element-type element))
22910 (post-affiliated (org-element-property :post-affiliated element)))
22911 (unless (< p post-affiliated)
22912 (cl-case type
22913 (comment
22914 (save-excursion
22915 (beginning-of-line)
22916 (looking-at "[ \t]*")
22917 (concat (match-string 0) "# ")))
22918 (footnote-definition "")
22919 ((item plain-list)
22920 (make-string (org-list-item-body-column post-affiliated) ?\s))
22921 (paragraph
22922 ;; Fill prefix is usually the same as the current line,
22923 ;; unless the paragraph is at the beginning of an item.
22924 (let ((parent (org-element-property :parent element)))
22925 (save-excursion
22926 (beginning-of-line)
22927 (cond ((eq (org-element-type parent) 'item)
22928 (make-string (org-list-item-body-column
22929 (org-element-property :begin parent))
22930 ?\s))
22931 ((and adaptive-fill-regexp
22932 ;; Locally disable
22933 ;; `adaptive-fill-function' to let
22934 ;; `fill-context-prefix' handle
22935 ;; `adaptive-fill-regexp' variable.
22936 (let (adaptive-fill-function)
22937 (fill-context-prefix
22938 post-affiliated
22939 (org-element-property :end element)))))
22940 ((looking-at "[ \t]+") (match-string 0))
22941 (t "")))))
22942 (comment-block
22943 ;; Only fill contents if P is within block boundaries.
22944 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22945 (forward-line)
22946 (point)))
22947 (cend (save-excursion
22948 (goto-char (org-element-property :end element))
22949 (skip-chars-backward " \r\t\n")
22950 (line-beginning-position))))
22951 (when (and (>= p cbeg) (< p cend))
22952 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22953 (match-string 0)
22954 "")))))))))))
22956 (declare-function message-goto-body "message" ())
22957 (defvar message-cite-prefix-regexp) ; From message.el
22958 (defun org-fill-paragraph (&optional justify)
22959 "Fill element at point, when applicable.
22961 This function only applies to comment blocks, comments, example
22962 blocks and paragraphs. Also, as a special case, re-align table
22963 when point is at one.
22965 If JUSTIFY is non-nil (interactively, with prefix argument),
22966 justify as well. If `sentence-end-double-space' is non-nil, then
22967 period followed by one space does not end a sentence, so don't
22968 break a line there. The variable `fill-column' controls the
22969 width for filling.
22971 For convenience, when point is at a plain list, an item or
22972 a footnote definition, try to fill the first paragraph within."
22973 (interactive)
22974 (if (and (derived-mode-p 'message-mode)
22975 (or (not (message-in-body-p))
22976 (save-excursion (move-beginning-of-line 1)
22977 (looking-at message-cite-prefix-regexp))))
22978 ;; First ensure filling is correct in message-mode.
22979 (let ((fill-paragraph-function
22980 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22981 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22982 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22983 (paragraph-separate
22984 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22985 (fill-paragraph nil))
22986 (with-syntax-table org-mode-transpose-word-syntax-table
22987 ;; Move to end of line in order to get the first paragraph
22988 ;; within a plain list or a footnote definition.
22989 (let ((element (save-excursion
22990 (end-of-line)
22991 (or (ignore-errors (org-element-at-point))
22992 (user-error "An element cannot be parsed line %d"
22993 (line-number-at-pos (point)))))))
22994 ;; First check if point is in a blank line at the beginning of
22995 ;; the buffer. In that case, ignore filling.
22996 (cl-case (org-element-type element)
22997 ;; Use major mode filling function is src blocks.
22998 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22999 ;; Align Org tables, leave table.el tables as-is.
23000 (table-row (org-table-align) t)
23001 (table
23002 (when (eq (org-element-property :type element) 'org)
23003 (save-excursion
23004 (goto-char (org-element-property :post-affiliated element))
23005 (org-table-align)))
23007 (paragraph
23008 ;; Paragraphs may contain `line-break' type objects.
23009 (let ((beg (max (point-min)
23010 (org-element-property :contents-begin element)))
23011 (end (min (point-max)
23012 (org-element-property :contents-end element))))
23013 ;; Do nothing if point is at an affiliated keyword.
23014 (if (< (line-end-position) beg) t
23015 (when (derived-mode-p 'message-mode)
23016 ;; In `message-mode', do not fill following citation
23017 ;; in current paragraph nor text before message body.
23018 (let ((body-start (save-excursion (message-goto-body))))
23019 (when body-start (setq beg (max body-start beg))))
23020 (when (save-excursion
23021 (re-search-forward
23022 (concat "^" message-cite-prefix-regexp) end t))
23023 (setq end (match-beginning 0))))
23024 ;; Fill paragraph, taking line breaks into account.
23025 (save-excursion
23026 (goto-char beg)
23027 (let ((cuts (list beg)))
23028 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23029 (when (eq 'line-break
23030 (org-element-type
23031 (save-excursion (backward-char)
23032 (org-element-context))))
23033 (push (point) cuts)))
23034 (dolist (c (delq end cuts))
23035 (fill-region-as-paragraph c end justify)
23036 (setq end c))))
23037 t)))
23038 ;; Contents of `comment-block' type elements should be
23039 ;; filled as plain text, but only if point is within block
23040 ;; markers.
23041 (comment-block
23042 (let* ((case-fold-search t)
23043 (beg (save-excursion
23044 (goto-char (org-element-property :begin element))
23045 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23046 (forward-line)
23047 (point)))
23048 (end (save-excursion
23049 (goto-char (org-element-property :end element))
23050 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23051 (line-beginning-position))))
23052 (if (or (< (point) beg) (> (point) end)) t
23053 (fill-region-as-paragraph
23054 (save-excursion (end-of-line)
23055 (re-search-backward "^[ \t]*$" beg 'move)
23056 (line-beginning-position))
23057 (save-excursion (beginning-of-line)
23058 (re-search-forward "^[ \t]*$" end 'move)
23059 (line-beginning-position))
23060 justify))))
23061 ;; Fill comments.
23062 (comment
23063 (let ((begin (org-element-property :post-affiliated element))
23064 (end (org-element-property :end element)))
23065 (when (and (>= (point) begin) (<= (point) end))
23066 (let ((begin (save-excursion
23067 (end-of-line)
23068 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23069 (progn (forward-line) (point))
23070 begin)))
23071 (end (save-excursion
23072 (end-of-line)
23073 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23074 (1- (line-beginning-position))
23075 (skip-chars-backward " \r\t\n")
23076 (line-end-position)))))
23077 ;; Do not fill comments when at a blank line.
23078 (when (> end begin)
23079 (let ((fill-prefix
23080 (save-excursion
23081 (beginning-of-line)
23082 (looking-at "[ \t]*#")
23083 (let ((comment-prefix (match-string 0)))
23084 (goto-char (match-end 0))
23085 (if (looking-at adaptive-fill-regexp)
23086 (concat comment-prefix (match-string 0))
23087 (concat comment-prefix " "))))))
23088 (save-excursion
23089 (fill-region-as-paragraph begin end justify))))))
23091 ;; Ignore every other element.
23092 (otherwise t))))))
23094 (defun org-auto-fill-function ()
23095 "Auto-fill function."
23096 ;; Check if auto-filling is meaningful.
23097 (let ((fc (current-fill-column)))
23098 (when (and fc (> (current-column) fc))
23099 (let* ((fill-prefix (org-adaptive-fill-function))
23100 ;; Enforce empty fill prefix, if required. Otherwise, it
23101 ;; will be computed again.
23102 (adaptive-fill-mode (not (equal fill-prefix ""))))
23103 (when fill-prefix (do-auto-fill))))))
23105 (defun org-comment-line-break-function (&optional soft)
23106 "Break line at point and indent, continuing comment if within one.
23107 The inserted newline is marked hard if variable
23108 `use-hard-newlines' is true, unless optional argument SOFT is
23109 non-nil."
23110 (if soft (insert-and-inherit ?\n) (newline 1))
23111 (save-excursion (forward-char -1) (delete-horizontal-space))
23112 (delete-horizontal-space)
23113 (indent-to-left-margin)
23114 (insert-before-markers-and-inherit fill-prefix))
23117 ;;; Fixed Width Areas
23119 (defun org-toggle-fixed-width ()
23120 "Toggle fixed-width markup.
23122 Add or remove fixed-width markup on current line, whenever it
23123 makes sense. Return an error otherwise.
23125 If a region is active and if it contains only fixed-width areas
23126 or blank lines, remove all fixed-width markup in it. If the
23127 region contains anything else, convert all non-fixed-width lines
23128 to fixed-width ones.
23130 Blank lines at the end of the region are ignored unless the
23131 region only contains such lines."
23132 (interactive)
23133 (if (not (org-region-active-p))
23134 ;; No region:
23136 ;; Remove fixed width marker only in a fixed-with element.
23138 ;; Add fixed width maker in paragraphs, in blank lines after
23139 ;; elements or at the beginning of a headline or an inlinetask,
23140 ;; and before any one-line elements (e.g., a clock).
23141 (progn
23142 (beginning-of-line)
23143 (let* ((element (org-element-at-point))
23144 (type (org-element-type element)))
23145 (cond
23146 ((and (eq type 'fixed-width)
23147 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23148 (replace-match
23149 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23150 ((and (memq type '(babel-call clock comment diary-sexp headline
23151 horizontal-rule keyword paragraph
23152 planning))
23153 (<= (org-element-property :post-affiliated element) (point)))
23154 (skip-chars-forward " \t")
23155 (insert ": "))
23156 ((and (looking-at-p "[ \t]*$")
23157 (or (eq type 'inlinetask)
23158 (save-excursion
23159 (skip-chars-forward " \r\t\n")
23160 (<= (org-element-property :end element) (point)))))
23161 (delete-region (point) (line-end-position))
23162 (org-indent-line)
23163 (insert ": "))
23164 (t (user-error "Cannot insert a fixed-width line here")))))
23165 ;; Region active.
23166 (let* ((begin (save-excursion
23167 (goto-char (region-beginning))
23168 (line-beginning-position)))
23169 (end (copy-marker
23170 (save-excursion
23171 (goto-char (region-end))
23172 (unless (eolp) (beginning-of-line))
23173 (if (save-excursion (re-search-backward "\\S-" begin t))
23174 (progn (skip-chars-backward " \r\t\n") (point))
23175 (point)))))
23176 (all-fixed-width-p
23177 (catch 'not-all-p
23178 (save-excursion
23179 (goto-char begin)
23180 (skip-chars-forward " \r\t\n")
23181 (when (eobp) (throw 'not-all-p nil))
23182 (while (< (point) end)
23183 (let ((element (org-element-at-point)))
23184 (if (eq (org-element-type element) 'fixed-width)
23185 (goto-char (org-element-property :end element))
23186 (throw 'not-all-p nil))))
23187 t))))
23188 (if all-fixed-width-p
23189 (save-excursion
23190 (goto-char begin)
23191 (while (< (point) end)
23192 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23193 (replace-match
23194 "" nil nil nil
23195 (if (= (line-end-position) (match-end 0)) 0 1)))
23196 (forward-line)))
23197 (let ((min-ind (point-max)))
23198 ;; Find minimum indentation across all lines.
23199 (save-excursion
23200 (goto-char begin)
23201 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23202 (setq min-ind 0)
23203 (catch 'zerop
23204 (while (< (point) end)
23205 (unless (looking-at-p "[ \t]*$")
23206 (let ((ind (org-get-indentation)))
23207 (setq min-ind (min min-ind ind))
23208 (when (zerop ind) (throw 'zerop t))))
23209 (forward-line)))))
23210 ;; Loop over all lines and add fixed-width markup everywhere
23211 ;; but in fixed-width lines.
23212 (save-excursion
23213 (goto-char begin)
23214 (while (< (point) end)
23215 (cond
23216 ((org-at-heading-p)
23217 (insert ": ")
23218 (forward-line)
23219 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23220 (insert ":")
23221 (forward-line)))
23222 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23223 (let* ((element (org-element-at-point))
23224 (element-end (org-element-property :end element)))
23225 (if (eq (org-element-type element) 'fixed-width)
23226 (progn (goto-char element-end)
23227 (skip-chars-backward " \r\t\n")
23228 (forward-line))
23229 (let ((limit (min end element-end)))
23230 (while (< (point) limit)
23231 (org-move-to-column min-ind t)
23232 (insert ": ")
23233 (forward-line))))))
23235 (org-move-to-column min-ind t)
23236 (insert ": ")
23237 (forward-line)))))))
23238 (set-marker end nil))))
23241 ;;; Comments
23243 ;; Org comments syntax is quite complex. It requires the entire line
23244 ;; to be just a comment. Also, even with the right syntax at the
23245 ;; beginning of line, some some elements (i.e. verse-block or
23246 ;; example-block) don't accept comments. Usual Emacs comment commands
23247 ;; cannot cope with those requirements. Therefore, Org replaces them.
23249 ;; Org still relies on `comment-dwim', but cannot trust
23250 ;; `comment-only-p'. So, `comment-region-function' and
23251 ;; `uncomment-region-function' both point
23252 ;; to`org-comment-or-uncomment-region'. Eventually,
23253 ;; `org-insert-comment' takes care of insertion of comments at the
23254 ;; beginning of line.
23256 ;; `org-setup-comments-handling' install comments related variables
23257 ;; during `org-mode' initialization.
23259 (defun org-setup-comments-handling ()
23260 (interactive)
23261 (setq-local comment-use-syntax nil)
23262 (setq-local comment-start "# ")
23263 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23264 (setq-local comment-insert-comment-function 'org-insert-comment)
23265 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23266 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23268 (defun org-insert-comment ()
23269 "Insert an empty comment above current line.
23270 If the line is empty, insert comment at its beginning. When
23271 point is within a source block, comment according to the related
23272 major mode."
23273 (if (let ((element (org-element-at-point)))
23274 (and (eq (org-element-type element) 'src-block)
23275 (< (save-excursion
23276 (goto-char (org-element-property :post-affiliated element))
23277 (line-end-position))
23278 (point))
23279 (> (save-excursion
23280 (goto-char (org-element-property :end element))
23281 (skip-chars-backward " \r\t\n")
23282 (line-beginning-position))
23283 (point))))
23284 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23285 (beginning-of-line)
23286 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23287 (open-line 1))
23288 (org-indent-line)
23289 (insert "# ")))
23291 (defvar comment-empty-lines) ; From newcomment.el.
23292 (defun org-comment-or-uncomment-region (beg end &rest _)
23293 "Comment or uncomment each non-blank line in the region.
23294 Uncomment each non-blank line between BEG and END if it only
23295 contains commented lines. Otherwise, comment them. If region is
23296 strictly within a source block, use appropriate comment syntax."
23297 (if (let ((element (org-element-at-point)))
23298 (and (eq (org-element-type element) 'src-block)
23299 (< (save-excursion
23300 (goto-char (org-element-property :post-affiliated element))
23301 (line-end-position))
23302 beg)
23303 (>= (save-excursion
23304 (goto-char (org-element-property :end element))
23305 (skip-chars-backward " \r\t\n")
23306 (line-beginning-position))
23307 end)))
23308 ;; Translate region boundaries for the Org buffer to the source
23309 ;; buffer.
23310 (let ((offset (- end beg)))
23311 (save-excursion
23312 (goto-char beg)
23313 (org-babel-do-in-edit-buffer
23314 (comment-or-uncomment-region (point) (+ offset (point))))))
23315 (save-restriction
23316 ;; Restrict region
23317 (narrow-to-region (save-excursion (goto-char beg)
23318 (skip-chars-forward " \r\t\n" end)
23319 (line-beginning-position))
23320 (save-excursion (goto-char end)
23321 (skip-chars-backward " \r\t\n" beg)
23322 (line-end-position)))
23323 (let ((uncommentp
23324 ;; UNCOMMENTP is non-nil when every non blank line between
23325 ;; BEG and END is a comment.
23326 (save-excursion
23327 (goto-char (point-min))
23328 (while (and (not (eobp))
23329 (let ((element (org-element-at-point)))
23330 (and (eq (org-element-type element) 'comment)
23331 (goto-char (min (point-max)
23332 (org-element-property
23333 :end element)))))))
23334 (eobp))))
23335 (if uncommentp
23336 ;; Only blank lines and comments in region: uncomment it.
23337 (save-excursion
23338 (goto-char (point-min))
23339 (while (not (eobp))
23340 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23341 (replace-match "" nil nil nil 1))
23342 (forward-line)))
23343 ;; Comment each line in region.
23344 (let ((min-indent (point-max)))
23345 ;; First find the minimum indentation across all lines.
23346 (save-excursion
23347 (goto-char (point-min))
23348 (while (and (not (eobp)) (not (zerop min-indent)))
23349 (unless (looking-at "[ \t]*$")
23350 (setq min-indent (min min-indent (current-indentation))))
23351 (forward-line)))
23352 ;; Then loop over all lines.
23353 (save-excursion
23354 (goto-char (point-min))
23355 (while (not (eobp))
23356 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23357 ;; Don't get fooled by invisible text (e.g. link path)
23358 ;; when moving to column MIN-INDENT.
23359 (let ((buffer-invisibility-spec nil))
23360 (org-move-to-column min-indent t))
23361 (insert comment-start))
23362 (forward-line)))))))))
23364 (defun org-comment-dwim (_arg)
23365 "Call `comment-dwim' within a source edit buffer if needed."
23366 (interactive "*P")
23367 (if (org-in-src-block-p)
23368 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23369 (call-interactively 'comment-dwim)))
23372 ;;; Timestamps API
23374 ;; This section contains tools to operate on timestamp objects, as
23375 ;; returned by, e.g. `org-element-context'.
23377 (defun org-timestamp--to-internal-time (timestamp &optional end)
23378 "Encode TIMESTAMP object into Emacs internal time.
23379 Use end of date range or time range when END is non-nil."
23380 (apply #'encode-time
23381 (cons 0
23382 (mapcar
23383 (lambda (prop) (or (org-element-property prop timestamp) 0))
23384 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23385 '(:minute-start :hour-start :day-start :month-start
23386 :year-start))))))
23388 (defun org-timestamp-has-time-p (timestamp)
23389 "Non-nil when TIMESTAMP has a time specified."
23390 (org-element-property :hour-start timestamp))
23392 (defun org-timestamp-format (timestamp format &optional end utc)
23393 "Format a TIMESTAMP object into a string.
23395 FORMAT is a format specifier to be passed to
23396 `format-time-string'.
23398 When optional argument END is non-nil, use end of date-range or
23399 time-range, if possible.
23401 When optional argument UTC is non-nil, time will be expressed as
23402 Universal Time."
23403 (format-time-string
23404 format (org-timestamp--to-internal-time timestamp end)
23405 (and utc t)))
23407 (defun org-timestamp-split-range (timestamp &optional end)
23408 "Extract a TIMESTAMP object from a date or time range.
23410 END, when non-nil, means extract the end of the range.
23411 Otherwise, extract its start.
23413 Return a new timestamp object."
23414 (let ((type (org-element-property :type timestamp)))
23415 (if (memq type '(active inactive diary)) timestamp
23416 (let ((split-ts (org-element-copy timestamp)))
23417 ;; Set new type.
23418 (org-element-put-property
23419 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23420 ;; Copy start properties over end properties if END is
23421 ;; non-nil. Otherwise, copy end properties over `start' ones.
23422 (let ((p-alist '((:minute-start . :minute-end)
23423 (:hour-start . :hour-end)
23424 (:day-start . :day-end)
23425 (:month-start . :month-end)
23426 (:year-start . :year-end))))
23427 (dolist (p-cell p-alist)
23428 (org-element-put-property
23429 split-ts
23430 (funcall (if end #'car #'cdr) p-cell)
23431 (org-element-property
23432 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23433 ;; Eventually refresh `:raw-value'.
23434 (org-element-put-property split-ts :raw-value nil)
23435 (org-element-put-property
23436 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23438 (defun org-timestamp-translate (timestamp &optional boundary)
23439 "Translate TIMESTAMP object to custom format.
23441 Format string is defined in `org-time-stamp-custom-formats',
23442 which see.
23444 When optional argument BOUNDARY is non-nil, it is either the
23445 symbol `start' or `end'. In this case, only translate the
23446 starting or ending part of TIMESTAMP if it is a date or time
23447 range. Otherwise, translate both parts.
23449 Return timestamp as-is if `org-display-custom-times' is nil or if
23450 it has a `diary' type."
23451 (let ((type (org-element-property :type timestamp)))
23452 (if (or (not org-display-custom-times) (eq type 'diary))
23453 (org-element-interpret-data timestamp)
23454 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23455 org-time-stamp-custom-formats)))
23456 (if (and (not boundary) (memq type '(active-range inactive-range)))
23457 (concat (org-timestamp-format timestamp fmt)
23458 "--"
23459 (org-timestamp-format timestamp fmt t))
23460 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23464 ;;; Other stuff.
23466 (defvar reftex-docstruct-symbol)
23467 (defvar org--rds)
23469 (defun org-reftex-citation ()
23470 "Use reftex-citation to insert a citation into the buffer.
23471 This looks for a line like
23473 #+BIBLIOGRAPHY: foo plain option:-d
23475 and derives from it that foo.bib is the bibliography file relevant
23476 for this document. It then installs the necessary environment for RefTeX
23477 to work in this buffer and calls `reftex-citation' to insert a citation
23478 into the buffer.
23480 Export of such citations to both LaTeX and HTML is handled by the contributed
23481 package ox-bibtex by Taru Karttunen."
23482 (interactive)
23483 (let ((reftex-docstruct-symbol 'org--rds)
23484 org--rds bib)
23485 (org-with-wide-buffer
23486 (let ((case-fold-search t)
23487 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23488 (if (not (save-excursion
23489 (or (re-search-forward re nil t)
23490 (re-search-backward re nil t))))
23491 (user-error "No bibliography defined in file")
23492 (setq bib (concat (match-string 1) ".bib")
23493 org--rds (list (list 'bib bib))))))
23494 (call-interactively 'reftex-citation)))
23496 ;;;; Functions extending outline functionality
23498 (defun org-beginning-of-line (&optional n)
23499 "Go to the beginning of the current visible line.
23501 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23502 tags on the first attempt, and only move to after the tags when
23503 the cursor is already beyond the end of the headline.
23505 With argument N not nil or 1, move forward N - 1 lines first."
23506 (interactive "^p")
23507 (let ((origin (point))
23508 (special (pcase org-special-ctrl-a/e
23509 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23510 deactivate-mark)
23511 ;; First move to a visible line.
23512 (if (bound-and-true-p visual-line-mode)
23513 (beginning-of-visual-line n)
23514 (move-beginning-of-line n)
23515 ;; `move-beginning-of-line' may leave point after invisible
23516 ;; characters if line starts with such of these (e.g., with
23517 ;; a link at column 0). Really move to the beginning of the
23518 ;; current visible line.
23519 (beginning-of-line))
23520 (cond
23521 ;; No special behavior. Point is already at the beginning of
23522 ;; a line, logical or visual.
23523 ((not special))
23524 ;; `beginning-of-visual-line' left point before logical beginning
23525 ;; of line: point is at the beginning of a visual line. Bail
23526 ;; out.
23527 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23528 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23529 ;; At a headline, special position is before the title, but
23530 ;; after any TODO keyword or priority cookie.
23531 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23532 (line-end-position)))
23533 (bol (point)))
23534 (if (eq special 'reversed)
23535 (when (and (= origin bol) (eq last-command this-command))
23536 (goto-char refpos))
23537 (when (or (> origin refpos) (= origin bol))
23538 (goto-char refpos)))))
23539 ((and (looking-at org-list-full-item-re)
23540 (memq (org-element-type (save-match-data (org-element-at-point)))
23541 '(item plain-list)))
23542 ;; Set special position at first white space character after
23543 ;; bullet, and check-box, if any.
23544 (let ((after-bullet
23545 (let ((box (match-end 3)))
23546 (cond ((not box) (match-end 1))
23547 ((eq (char-after box) ?\s) (1+ box))
23548 (t box)))))
23549 (if (eq special 'reversed)
23550 (when (and (= (point) origin) (eq last-command this-command))
23551 (goto-char after-bullet))
23552 (when (or (> origin after-bullet) (= (point) origin))
23553 (goto-char after-bullet)))))
23554 ;; No special context. Point is already at beginning of line.
23555 (t nil))))
23557 (defun org-end-of-line (&optional n)
23558 "Go to the end of the line, but before ellipsis, if any.
23560 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23561 tags on the first attempt, and only move to after the tags when
23562 the cursor is already beyond the end of the headline.
23564 With argument N not nil or 1, move forward N - 1 lines first."
23565 (interactive "^p")
23566 (let ((origin (point))
23567 (special (pcase org-special-ctrl-a/e
23568 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23569 deactivate-mark)
23570 ;; First move to a visible line.
23571 (if (bound-and-true-p visual-line-mode)
23572 (beginning-of-visual-line n)
23573 (move-beginning-of-line n))
23574 (cond
23575 ;; At a headline, with tags.
23576 ((and special
23577 (save-excursion
23578 (beginning-of-line)
23579 (let ((case-fold-search nil))
23580 (looking-at org-complex-heading-regexp)))
23581 (match-end 5))
23582 (let ((tags (save-excursion
23583 (goto-char (match-beginning 5))
23584 (skip-chars-backward " \t")
23585 (point)))
23586 (visual-end (and (bound-and-true-p visual-line-mode)
23587 (save-excursion
23588 (end-of-visual-line)
23589 (point)))))
23590 ;; If `end-of-visual-line' brings us before end of line or
23591 ;; even tags, i.e., the headline spans over multiple visual
23592 ;; lines, move there.
23593 (cond ((and visual-end
23594 (< visual-end tags)
23595 (<= origin visual-end))
23596 (goto-char visual-end))
23597 ((eq special 'reversed)
23598 (if (and (= origin (line-end-position))
23599 (eq this-command last-command))
23600 (goto-char tags)
23601 (end-of-line)))
23603 (if (or (< origin tags) (= origin (line-end-position)))
23604 (goto-char tags)
23605 (end-of-line))))))
23606 ((bound-and-true-p visual-line-mode)
23607 (let ((bol (line-beginning-position)))
23608 (end-of-visual-line)
23609 ;; If `end-of-visual-line' gets us past the ellipsis at the
23610 ;; end of a line, backtrack and use `end-of-line' instead.
23611 (when (/= bol (line-beginning-position))
23612 (goto-char bol)
23613 (end-of-line))))
23614 (t (end-of-line)))))
23616 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23617 (define-key org-mode-map "\C-e" 'org-end-of-line)
23619 (defun org-backward-sentence (&optional _arg)
23620 "Go to beginning of sentence, or beginning of table field.
23621 This will call `backward-sentence' or `org-table-beginning-of-field',
23622 depending on context."
23623 (interactive)
23624 (let* ((element (org-element-at-point))
23625 (contents-begin (org-element-property :contents-begin element))
23626 (table (org-element-lineage element '(table) t)))
23627 (if (and table
23628 (> (point) contents-begin)
23629 (<= (point) (org-element-property :contents-end table)))
23630 (call-interactively #'org-table-beginning-of-field)
23631 (save-restriction
23632 (when (and contents-begin
23633 (< (point-min) contents-begin)
23634 (> (point) contents-begin))
23635 (narrow-to-region contents-begin
23636 (org-element-property :contents-end element)))
23637 (call-interactively #'backward-sentence)))))
23639 (defun org-forward-sentence (&optional _arg)
23640 "Go to end of sentence, or end of table field.
23641 This will call `forward-sentence' or `org-table-end-of-field',
23642 depending on context."
23643 (interactive)
23644 (let* ((element (org-element-at-point))
23645 (contents-end (org-element-property :contents-end element))
23646 (table (org-element-lineage element '(table) t)))
23647 (if (and table
23648 (>= (point) (org-element-property :contents-begin table))
23649 (< (point) contents-end))
23650 (call-interactively #'org-table-end-of-field)
23651 (save-restriction
23652 (when (and contents-end
23653 (> (point-max) contents-end)
23654 ;; Skip blank lines between elements.
23655 (< (org-element-property :end element)
23656 (save-excursion (goto-char contents-end)
23657 (skip-chars-forward " \r\t\n"))))
23658 (narrow-to-region (org-element-property :contents-begin element)
23659 contents-end))
23660 (call-interactively #'forward-sentence)))))
23662 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23663 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23665 (defun org-kill-line (&optional _arg)
23666 "Kill line, to tags or end of line."
23667 (interactive)
23668 (cond
23669 ((or (not org-special-ctrl-k)
23670 (bolp)
23671 (not (org-at-heading-p)))
23672 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23673 org-ctrl-k-protect-subtree
23674 (or (eq org-ctrl-k-protect-subtree 'error)
23675 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23676 (user-error "C-k aborted as it would kill a hidden subtree"))
23677 (call-interactively
23678 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23679 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23680 (kill-region (point) (match-beginning 1))
23681 (org-set-tags nil t))
23682 (t (kill-region (point) (point-at-eol)))))
23684 (define-key org-mode-map "\C-k" 'org-kill-line)
23686 (defun org-yank (&optional arg)
23687 "Yank. If the kill is a subtree, treat it specially.
23688 This command will look at the current kill and check if is a single
23689 subtree, or a series of subtrees[1]. If it passes the test, and if the
23690 cursor is at the beginning of a line or after the stars of a currently
23691 empty headline, then the yank is handled specially. How exactly depends
23692 on the value of the following variables.
23694 `org-yank-folded-subtrees'
23695 By default, this variable is non-nil, which results in
23696 subtree(s) being folded after insertion, except if doing so
23697 would swallow text after the yanked text.
23699 `org-yank-adjusted-subtrees'
23700 When non-nil (the default value is nil), the subtree will be
23701 promoted or demoted in order to fit into the local outline tree
23702 structure, which means that the level will be adjusted so that it
23703 becomes the smaller one of the two *visible* surrounding headings.
23705 Any prefix to this command will cause `yank' to be called directly with
23706 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23707 will just
23708 plainly yank the text as it is.
23710 \[1] The test checks if the first non-white line is a heading
23711 and if there are no other headings with fewer stars."
23712 (interactive "P")
23713 (org-yank-generic 'yank arg))
23715 (defun org-yank-generic (command arg)
23716 "Perform some yank-like command.
23718 This function implements the behavior described in the `org-yank'
23719 documentation. However, it has been generalized to work for any
23720 interactive command with similar behavior."
23722 ;; pretend to be command COMMAND
23723 (setq this-command command)
23725 (if arg
23726 (call-interactively command)
23728 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23729 (and (org-kill-is-subtree-p)
23730 (or (bolp)
23731 (and (looking-at "[ \t]*$")
23732 (string-match
23733 "\\`\\*+\\'"
23734 (buffer-substring (point-at-bol) (point)))))))
23735 swallowp)
23736 (cond
23737 ((and subtreep org-yank-folded-subtrees)
23738 (let ((beg (point))
23739 end)
23740 (if (and subtreep org-yank-adjusted-subtrees)
23741 (org-paste-subtree nil nil 'for-yank)
23742 (call-interactively command))
23744 (setq end (point))
23745 (goto-char beg)
23746 (when (and (bolp) subtreep
23747 (not (setq swallowp
23748 (org-yank-folding-would-swallow-text beg end))))
23749 (org-with-limited-levels
23750 (or (looking-at org-outline-regexp)
23751 (re-search-forward org-outline-regexp-bol end t))
23752 (while (and (< (point) end) (looking-at org-outline-regexp))
23753 (outline-hide-subtree)
23754 (org-cycle-show-empty-lines 'folded)
23755 (condition-case nil
23756 (outline-forward-same-level 1)
23757 (error (goto-char end))))))
23758 (when swallowp
23759 (message
23760 "Inserted text not folded because that would swallow text"))
23762 (goto-char end)
23763 (skip-chars-forward " \t\n\r")
23764 (beginning-of-line 1)
23765 (push-mark beg 'nomsg)))
23766 ((and subtreep org-yank-adjusted-subtrees)
23767 (let ((beg (point-at-bol)))
23768 (org-paste-subtree nil nil 'for-yank)
23769 (push-mark beg 'nomsg)))
23771 (call-interactively command))))))
23773 (defun org-yank-folding-would-swallow-text (beg end)
23774 "Would hide-subtree at BEG swallow any text after END?"
23775 (let (level)
23776 (org-with-limited-levels
23777 (save-excursion
23778 (goto-char beg)
23779 (when (or (looking-at org-outline-regexp)
23780 (re-search-forward org-outline-regexp-bol end t))
23781 (setq level (org-outline-level)))
23782 (goto-char end)
23783 (skip-chars-forward " \t\r\n\v\f")
23784 (not (or (eobp)
23785 (and (bolp) (looking-at-p org-outline-regexp)
23786 (<= (org-outline-level) level))))))))
23788 (define-key org-mode-map "\C-y" 'org-yank)
23790 (defun org-truely-invisible-p ()
23791 "Check if point is at a character currently not visible.
23792 This version does not only check the character property, but also
23793 `visible-mode'."
23794 ;; Early versions of noutline don't have `outline-invisible-p'.
23795 (unless (bound-and-true-p visible-mode)
23796 (outline-invisible-p)))
23798 (defun org-invisible-p2 ()
23799 "Check if point is at a character currently not visible."
23800 (save-excursion
23801 (when (and (eolp) (not (bobp))) (backward-char 1))
23802 ;; Early versions of noutline don't have `outline-invisible-p'.
23803 (outline-invisible-p)))
23805 (defun org-back-to-heading (&optional invisible-ok)
23806 "Call `outline-back-to-heading', but provide a better error message."
23807 (condition-case nil
23808 (outline-back-to-heading invisible-ok)
23809 (error (error "Before first headline at position %d in buffer %s"
23810 (point) (current-buffer)))))
23812 (defun org-before-first-heading-p ()
23813 "Before first heading?"
23814 (save-excursion
23815 (end-of-line)
23816 (null (re-search-backward org-outline-regexp-bol nil t))))
23818 (defun org-at-heading-p (&optional ignored)
23819 (outline-on-heading-p t))
23821 (defun org-in-commented-heading-p (&optional no-inheritance)
23822 "Non-nil if point is under a commented heading.
23823 This function also checks ancestors of the current headline,
23824 unless optional argument NO-INHERITANCE is non-nil."
23825 (cond
23826 ((org-before-first-heading-p) nil)
23827 ((let ((headline (nth 4 (org-heading-components))))
23828 (and headline
23829 (let ((case-fold-search nil))
23830 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23831 headline)))))
23832 (no-inheritance nil)
23834 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23836 (defun org-at-comment-p nil
23837 "Is cursor in a commented line?"
23838 (save-excursion
23839 (save-match-data
23840 (beginning-of-line)
23841 (looking-at "^[ \t]*# "))))
23843 (defun org-at-drawer-p nil
23844 "Is cursor at a drawer keyword?"
23845 (save-excursion
23846 (move-beginning-of-line 1)
23847 (looking-at org-drawer-regexp)))
23849 (defun org-at-block-p nil
23850 "Is cursor at a block keyword?"
23851 (save-excursion
23852 (move-beginning-of-line 1)
23853 (looking-at org-block-regexp)))
23855 (defun org-point-at-end-of-empty-headline ()
23856 "If point is at the end of an empty headline, return t, else nil.
23857 If the heading only contains a TODO keyword, it is still still considered
23858 empty."
23859 (let ((case-fold-search nil))
23860 (and (looking-at "[ \t]*$")
23861 org-todo-line-regexp
23862 (save-excursion
23863 (beginning-of-line)
23864 (looking-at org-todo-line-regexp)
23865 (string= (match-string 3) "")))))
23867 (defun org-at-heading-or-item-p ()
23868 (or (org-at-heading-p) (org-at-item-p)))
23870 (defun org-at-target-p ()
23871 (or (org-in-regexp org-radio-target-regexp)
23872 (org-in-regexp org-target-regexp)))
23873 ;; Compatibility alias with Org versions < 7.8.03
23874 (defalias 'org-on-target-p 'org-at-target-p)
23876 (defun org-up-heading-all (arg)
23877 "Move to the heading line of which the present line is a subheading.
23878 This function considers both visible and invisible heading lines.
23879 With argument, move up ARG levels."
23880 (outline-up-heading arg t))
23882 (defun org-up-heading-safe ()
23883 "Move to the heading line of which the present line is a subheading.
23884 This version will not throw an error. It will return the level of the
23885 headline found, or nil if no higher level is found.
23887 Also, this function will be a lot faster than `outline-up-heading',
23888 because it relies on stars being the outline starters. This can really
23889 make a significant difference in outlines with very many siblings."
23890 (when (ignore-errors (org-back-to-heading t))
23891 (let ((level-up (1- (funcall outline-level))))
23892 (and (> level-up 0)
23893 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23894 (funcall outline-level)))))
23896 (defun org-first-sibling-p ()
23897 "Is this heading the first child of its parents?"
23898 (interactive)
23899 (let ((re org-outline-regexp-bol)
23900 level l)
23901 (unless (org-at-heading-p t)
23902 (user-error "Not at a heading"))
23903 (setq level (funcall outline-level))
23904 (save-excursion
23905 (if (not (re-search-backward re nil t))
23907 (setq l (funcall outline-level))
23908 (< l level)))))
23910 (defun org-goto-sibling (&optional previous)
23911 "Goto the next sibling, even if it is invisible.
23912 When PREVIOUS is set, go to the previous sibling instead. Returns t
23913 when a sibling was found. When none is found, return nil and don't
23914 move point."
23915 (let ((fun (if previous 're-search-backward 're-search-forward))
23916 (pos (point))
23917 (re org-outline-regexp-bol)
23918 level l)
23919 (when (ignore-errors (org-back-to-heading t))
23920 (setq level (funcall outline-level))
23921 (catch 'exit
23922 (or previous (forward-char 1))
23923 (while (funcall fun re nil t)
23924 (setq l (funcall outline-level))
23925 (when (< l level) (goto-char pos) (throw 'exit nil))
23926 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23927 (goto-char pos)
23928 nil))))
23930 (defun org-show-siblings ()
23931 "Show all siblings of the current headline."
23932 (save-excursion
23933 (while (org-goto-sibling) (org-flag-heading nil)))
23934 (save-excursion
23935 (while (org-goto-sibling 'previous)
23936 (org-flag-heading nil))))
23938 (defun org-goto-first-child ()
23939 "Goto the first child, even if it is invisible.
23940 Return t when a child was found. Otherwise don't move point and
23941 return nil."
23942 (let (level (pos (point)) (re org-outline-regexp-bol))
23943 (when (ignore-errors (org-back-to-heading t))
23944 (setq level (outline-level))
23945 (forward-char 1)
23946 (if (and (re-search-forward re nil t) (> (outline-level) level))
23947 (progn (goto-char (match-beginning 0)) t)
23948 (goto-char pos) nil))))
23950 (defun org-show-hidden-entry ()
23951 "Show an entry where even the heading is hidden."
23952 (save-excursion
23953 (org-show-entry)))
23955 (defun org-flag-heading (flag &optional entry)
23956 "Flag the current heading. FLAG non-nil means make invisible.
23957 When ENTRY is non-nil, show the entire entry."
23958 (save-excursion
23959 (org-back-to-heading t)
23960 ;; Check if we should show the entire entry
23961 (if entry
23962 (progn
23963 (org-show-entry)
23964 (save-excursion
23965 (and (outline-next-heading)
23966 (org-flag-heading nil))))
23967 (outline-flag-region (max (point-min) (1- (point)))
23968 (save-excursion (outline-end-of-heading) (point))
23969 flag))))
23971 (defun org-get-next-sibling ()
23972 "Move to next heading of the same level, and return point.
23973 If there is no such heading, return nil.
23974 This is like outline-next-sibling, but invisible headings are ok."
23975 (let ((level (funcall outline-level)))
23976 (outline-next-heading)
23977 (while (and (not (eobp)) (> (funcall outline-level) level))
23978 (outline-next-heading))
23979 (unless (or (eobp) (< (funcall outline-level) level))
23980 (point))))
23982 (defun org-get-last-sibling ()
23983 "Move to previous heading of the same level, and return point.
23984 If there is no such heading, return nil."
23985 (let ((opoint (point))
23986 (level (funcall outline-level)))
23987 (outline-previous-heading)
23988 (when (and (/= (point) opoint) (outline-on-heading-p t))
23989 (while (and (> (funcall outline-level) level)
23990 (not (bobp)))
23991 (outline-previous-heading))
23992 (unless (< (funcall outline-level) level)
23993 (point)))))
23995 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23996 "Goto to the end of a subtree."
23997 ;; This contains an exact copy of the original function, but it uses
23998 ;; `org-back-to-heading', to make it work also in invisible
23999 ;; trees. And is uses an invisible-ok argument.
24000 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24001 ;; Furthermore, when used inside Org, finding the end of a large subtree
24002 ;; with many children and grandchildren etc, this can be much faster
24003 ;; than the outline version.
24004 (org-back-to-heading invisible-ok)
24005 (let ((first t)
24006 (level (funcall outline-level)))
24007 (if (and (derived-mode-p 'org-mode) (< level 1000))
24008 ;; A true heading (not a plain list item), in Org
24009 ;; This means we can easily find the end by looking
24010 ;; only for the right number of stars. Using a regexp to do
24011 ;; this is so much faster than using a Lisp loop.
24012 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24013 (forward-char 1)
24014 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24015 ;; something else, do it the slow way
24016 (while (and (not (eobp))
24017 (or first (> (funcall outline-level) level)))
24018 (setq first nil)
24019 (outline-next-heading)))
24020 (unless to-heading
24021 (when (memq (preceding-char) '(?\n ?\^M))
24022 ;; Go to end of line before heading
24023 (forward-char -1)
24024 (when (memq (preceding-char) '(?\n ?\^M))
24025 ;; leave blank line before heading
24026 (forward-char -1)))))
24027 (point))
24029 (defun org-end-of-meta-data (&optional full)
24030 "Skip planning line and properties drawer in current entry.
24031 When optional argument FULL is non-nil, also skip empty lines,
24032 clocking lines and regular drawers at the beginning of the
24033 entry."
24034 (org-back-to-heading t)
24035 (forward-line)
24036 (when (looking-at-p org-planning-line-re) (forward-line))
24037 (when (looking-at org-property-drawer-re)
24038 (goto-char (match-end 0))
24039 (forward-line))
24040 (when (and full (not (org-at-heading-p)))
24041 (catch 'exit
24042 (let ((end (save-excursion (outline-next-heading) (point)))
24043 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24044 (while (not (eobp))
24045 (cond ((looking-at-p org-drawer-regexp)
24046 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24047 (forward-line)
24048 (throw 'exit t)))
24049 ((looking-at-p re) (forward-line))
24050 (t (throw 'exit t))))))))
24052 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24053 "Move forward to the ARG'th subheading at same level as this one.
24054 Stop at the first and last subheadings of a superior heading.
24055 Normally this only looks at visible headings, but when INVISIBLE-OK is
24056 non-nil it will also look at invisible ones."
24057 (interactive "p")
24058 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24059 (if (and arg (< arg 0))
24060 (goto-char (point-min))
24061 (outline-next-heading))
24062 (org-at-heading-p)
24063 (let ((level (- (match-end 0) (match-beginning 0) 1))
24064 (f (if (and arg (< arg 0))
24065 're-search-backward
24066 're-search-forward))
24067 (count (if arg (abs arg) 1))
24068 (result (point)))
24069 (while (and (prog1 (> count 0)
24070 (forward-char (if (and arg (< arg 0)) -1 1)))
24071 (funcall f org-outline-regexp-bol nil 'move))
24072 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24073 (cond ((< l level) (setq count 0))
24074 ((and (= l level)
24075 (or invisible-ok
24076 (progn
24077 (goto-char (line-beginning-position))
24078 (not (outline-invisible-p)))))
24079 (setq count (1- count))
24080 (when (eq l level)
24081 (setq result (point)))))))
24082 (goto-char result))
24083 (beginning-of-line 1)))
24085 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24086 "Move backward to the ARG'th subheading at same level as this one.
24087 Stop at the first and last subheadings of a superior heading."
24088 (interactive "p")
24089 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24091 (defun org-next-visible-heading (arg)
24092 "Move to the next visible heading.
24094 This function wraps `outline-next-visible-heading' with
24095 `org-with-limited-levels' in order to skip over inline tasks and
24096 respect customization of `org-odd-levels-only'."
24097 (interactive "p")
24098 (org-with-limited-levels
24099 (outline-next-visible-heading arg)))
24101 (defun org-previous-visible-heading (arg)
24102 "Move to the previous visible heading.
24104 This function wraps `outline-previous-visible-heading' with
24105 `org-with-limited-levels' in order to skip over inline tasks and
24106 respect customization of `org-odd-levels-only'."
24107 (interactive "p")
24108 (org-with-limited-levels
24109 (outline-previous-visible-heading arg)))
24111 (defun org-next-block (arg &optional backward block-regexp)
24112 "Jump to the next block.
24114 With a prefix argument ARG, jump forward ARG many blocks.
24116 When BACKWARD is non-nil, jump to the previous block.
24118 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24119 Match data is set according to this regexp when the function
24120 returns.
24122 Return point at beginning of the opening line of found block.
24123 Throw an error if no block is found."
24124 (interactive "p")
24125 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24126 (case-fold-search t)
24127 (search-fn (if backward #'re-search-backward #'re-search-forward))
24128 (count (or arg 1))
24129 (origin (point))
24130 last-element)
24131 (if backward (beginning-of-line) (end-of-line))
24132 (while (and (> count 0) (funcall search-fn re nil t))
24133 (let ((element (save-excursion
24134 (goto-char (match-beginning 0))
24135 (save-match-data (org-element-at-point)))))
24136 (when (and (memq (org-element-type element)
24137 '(center-block comment-block dynamic-block
24138 example-block export-block quote-block
24139 special-block src-block verse-block))
24140 (<= (match-beginning 0)
24141 (org-element-property :post-affiliated element)))
24142 (setq last-element element)
24143 (cl-decf count))))
24144 (if (= count 0)
24145 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24146 (save-match-data (org-show-context)))
24147 (goto-char origin)
24148 (user-error "No %s code blocks" (if backward "previous" "further")))))
24150 (defun org-previous-block (arg &optional block-regexp)
24151 "Jump to the previous block.
24152 With a prefix argument ARG, jump backward ARG many source blocks.
24153 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24154 (interactive "p")
24155 (org-next-block arg t block-regexp))
24157 (defun org-forward-paragraph ()
24158 "Move forward to beginning of next paragraph or equivalent.
24160 The function moves point to the beginning of the next visible
24161 structural element, which can be a paragraph, a table, a list
24162 item, etc. It also provides some special moves for convenience:
24164 - On an affiliated keyword, jump to the beginning of the
24165 relative element.
24166 - On an item or a footnote definition, move to the second
24167 element inside, if any.
24168 - On a table or a property drawer, jump after it.
24169 - On a verse or source block, stop after blank lines."
24170 (interactive)
24171 (when (eobp) (user-error "Cannot move further down"))
24172 (let* ((deactivate-mark nil)
24173 (element (org-element-at-point))
24174 (type (org-element-type element))
24175 (post-affiliated (org-element-property :post-affiliated element))
24176 (contents-begin (org-element-property :contents-begin element))
24177 (contents-end (org-element-property :contents-end element))
24178 (end (let ((end (org-element-property :end element)) (parent element))
24179 (while (and (setq parent (org-element-property :parent parent))
24180 (= (org-element-property :contents-end parent) end))
24181 (setq end (org-element-property :end parent)))
24182 end)))
24183 (cond ((not element)
24184 (skip-chars-forward " \r\t\n")
24185 (or (eobp) (beginning-of-line)))
24186 ;; On affiliated keywords, move to element's beginning.
24187 ((< (point) post-affiliated)
24188 (goto-char post-affiliated))
24189 ;; At a table row, move to the end of the table. Similarly,
24190 ;; at a node property, move to the end of the property
24191 ;; drawer.
24192 ((memq type '(node-property table-row))
24193 (goto-char (org-element-property
24194 :end (org-element-property :parent element))))
24195 ((memq type '(property-drawer table)) (goto-char end))
24196 ;; Consider blank lines as separators in verse and source
24197 ;; blocks to ease editing.
24198 ((memq type '(src-block verse-block))
24199 (when (eq type 'src-block)
24200 (setq contents-end
24201 (save-excursion (goto-char end)
24202 (skip-chars-backward " \r\t\n")
24203 (line-beginning-position))))
24204 (beginning-of-line)
24205 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24206 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24207 (goto-char end)
24208 (skip-chars-forward " \r\t\n")
24209 (if (= (point) contents-end) (goto-char end)
24210 (beginning-of-line))))
24211 ;; With no contents, just skip element.
24212 ((not contents-begin) (goto-char end))
24213 ;; If contents are invisible, skip the element altogether.
24214 ((outline-invisible-p (line-end-position))
24215 (cl-case type
24216 (headline
24217 (org-with-limited-levels (outline-next-visible-heading 1)))
24218 ;; At a plain list, make sure we move to the next item
24219 ;; instead of skipping the whole list.
24220 (plain-list (forward-char)
24221 (org-forward-paragraph))
24222 (otherwise (goto-char end))))
24223 ((>= (point) contents-end) (goto-char end))
24224 ((>= (point) contents-begin)
24225 ;; This can only happen on paragraphs and plain lists.
24226 (cl-case type
24227 (paragraph (goto-char end))
24228 ;; At a plain list, try to move to second element in
24229 ;; first item, if possible.
24230 (plain-list (end-of-line)
24231 (org-forward-paragraph))))
24232 ;; When contents start on the middle of a line (e.g. in
24233 ;; items and footnote definitions), try to reach first
24234 ;; element starting after current line.
24235 ((> (line-end-position) contents-begin)
24236 (end-of-line)
24237 (org-forward-paragraph))
24238 (t (goto-char contents-begin)))))
24240 (defun org-backward-paragraph ()
24241 "Move backward to start of previous paragraph or equivalent.
24243 The function moves point to the beginning of the current
24244 structural element, which can be a paragraph, a table, a list
24245 item, etc., or to the beginning of the previous visible one if
24246 point is already there. It also provides some special moves for
24247 convenience:
24249 - On an affiliated keyword, jump to the first one.
24250 - On a table or a property drawer, move to its beginning.
24251 - On a verse or source block, stop before blank lines."
24252 (interactive)
24253 (when (bobp) (user-error "Cannot move further up"))
24254 (let* ((deactivate-mark nil)
24255 (element (org-element-at-point))
24256 (type (org-element-type element))
24257 (contents-begin (org-element-property :contents-begin element))
24258 (contents-end (org-element-property :contents-end element))
24259 (post-affiliated (org-element-property :post-affiliated element))
24260 (begin (org-element-property :begin element)))
24261 (cond
24262 ((not element) (goto-char (point-min)))
24263 ((= (point) begin)
24264 (backward-char)
24265 (org-backward-paragraph))
24266 ((<= (point) post-affiliated) (goto-char begin))
24267 ((memq type '(node-property table-row))
24268 (goto-char (org-element-property
24269 :post-affiliated (org-element-property :parent element))))
24270 ((memq type '(property-drawer table)) (goto-char begin))
24271 ((memq type '(src-block verse-block))
24272 (when (eq type 'src-block)
24273 (setq contents-begin
24274 (save-excursion (goto-char begin) (forward-line) (point))))
24275 (if (= (point) contents-begin) (goto-char post-affiliated)
24276 ;; Inside a verse block, see blank lines as paragraph
24277 ;; separators.
24278 (let ((origin (point)))
24279 (skip-chars-backward " \r\t\n" contents-begin)
24280 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24281 (skip-chars-forward " \r\t\n" origin)
24282 (if (= (point) origin) (goto-char contents-begin)
24283 (beginning-of-line))))))
24284 ((not contents-begin) (goto-char (or post-affiliated begin)))
24285 ((eq type 'paragraph)
24286 (goto-char contents-begin)
24287 ;; When at first paragraph in an item or a footnote definition,
24288 ;; move directly to beginning of line.
24289 (let ((parent-contents
24290 (org-element-property
24291 :contents-begin (org-element-property :parent element))))
24292 (when (and parent-contents (= parent-contents contents-begin))
24293 (beginning-of-line))))
24294 ;; At the end of a greater element, move to the beginning of the
24295 ;; last element within.
24296 ((>= (point) contents-end)
24297 (goto-char (1- contents-end))
24298 (org-backward-paragraph))
24299 (t (goto-char (or post-affiliated begin))))
24300 ;; Ensure we never leave point invisible.
24301 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24303 (defun org-forward-element ()
24304 "Move forward by one element.
24305 Move to the next element at the same level, when possible."
24306 (interactive)
24307 (cond ((eobp) (user-error "Cannot move further down"))
24308 ((org-with-limited-levels (org-at-heading-p))
24309 (let ((origin (point)))
24310 (goto-char (org-end-of-subtree nil t))
24311 (unless (org-with-limited-levels (org-at-heading-p))
24312 (goto-char origin)
24313 (user-error "Cannot move further down"))))
24315 (let* ((elem (org-element-at-point))
24316 (end (org-element-property :end elem))
24317 (parent (org-element-property :parent elem)))
24318 (cond ((and parent (= (org-element-property :contents-end parent) end))
24319 (goto-char (org-element-property :end parent)))
24320 ((integer-or-marker-p end) (goto-char end))
24321 (t (message "No element at point")))))))
24323 (defun org-backward-element ()
24324 "Move backward by one element.
24325 Move to the previous element at the same level, when possible."
24326 (interactive)
24327 (cond ((bobp) (user-error "Cannot move further up"))
24328 ((org-with-limited-levels (org-at-heading-p))
24329 ;; At a headline, move to the previous one, if any, or stay
24330 ;; here.
24331 (let ((origin (point)))
24332 (org-with-limited-levels (org-backward-heading-same-level 1))
24333 ;; When current headline has no sibling above, move to its
24334 ;; parent.
24335 (when (= (point) origin)
24336 (or (org-with-limited-levels (org-up-heading-safe))
24337 (progn (goto-char origin)
24338 (user-error "Cannot move further up"))))))
24340 (let* ((elem (org-element-at-point))
24341 (beg (org-element-property :begin elem)))
24342 (cond
24343 ;; Move to beginning of current element if point isn't
24344 ;; there already.
24345 ((null beg) (message "No element at point"))
24346 ((/= (point) beg) (goto-char beg))
24347 (t (goto-char beg)
24348 (skip-chars-backward " \r\t\n")
24349 (unless (bobp)
24350 (let ((prev (org-element-at-point)))
24351 (goto-char (org-element-property :begin prev))
24352 (while (and (setq prev (org-element-property :parent prev))
24353 (<= (org-element-property :end prev) beg))
24354 (goto-char (org-element-property :begin prev)))))))))))
24356 (defun org-up-element ()
24357 "Move to upper element."
24358 (interactive)
24359 (if (org-with-limited-levels (org-at-heading-p))
24360 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24361 (let* ((elem (org-element-at-point))
24362 (parent (org-element-property :parent elem)))
24363 (if parent (goto-char (org-element-property :begin parent))
24364 (if (org-with-limited-levels (org-before-first-heading-p))
24365 (user-error "No surrounding element")
24366 (org-with-limited-levels (org-back-to-heading)))))))
24368 (defvar org-element-greater-elements)
24369 (defun org-down-element ()
24370 "Move to inner element."
24371 (interactive)
24372 (let ((element (org-element-at-point)))
24373 (cond
24374 ((memq (org-element-type element) '(plain-list table))
24375 (goto-char (org-element-property :contents-begin element))
24376 (forward-char))
24377 ((memq (org-element-type element) org-element-greater-elements)
24378 ;; If contents are hidden, first disclose them.
24379 (when (outline-invisible-p (line-end-position)) (org-cycle))
24380 (goto-char (or (org-element-property :contents-begin element)
24381 (user-error "No content for this element"))))
24382 (t (user-error "No inner element")))))
24384 (defun org-drag-element-backward ()
24385 "Move backward element at point."
24386 (interactive)
24387 (let ((elem (or (org-element-at-point)
24388 (user-error "No element at point"))))
24389 (if (eq (org-element-type elem) 'headline)
24390 ;; Preserve point when moving a whole tree, even if point was
24391 ;; on blank lines below the headline.
24392 (let ((offset (skip-chars-backward " \t\n")))
24393 (unwind-protect (org-move-subtree-up)
24394 (forward-char (- offset))))
24395 (let ((prev-elem
24396 (save-excursion
24397 (goto-char (org-element-property :begin elem))
24398 (skip-chars-backward " \r\t\n")
24399 (unless (bobp)
24400 (let* ((beg (org-element-property :begin elem))
24401 (prev (org-element-at-point))
24402 (up prev))
24403 (while (and (setq up (org-element-property :parent up))
24404 (<= (org-element-property :end up) beg))
24405 (setq prev up))
24406 prev)))))
24407 ;; Error out if no previous element or previous element is
24408 ;; a parent of the current one.
24409 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24410 (user-error "Cannot drag element backward")
24411 (let ((pos (point)))
24412 (org-element-swap-A-B prev-elem elem)
24413 (goto-char (+ (org-element-property :begin prev-elem)
24414 (- pos (org-element-property :begin elem))))))))))
24416 (defun org-drag-element-forward ()
24417 "Move forward element at point."
24418 (interactive)
24419 (let* ((pos (point))
24420 (elem (or (org-element-at-point)
24421 (user-error "No element at point"))))
24422 (when (= (point-max) (org-element-property :end elem))
24423 (user-error "Cannot drag element forward"))
24424 (goto-char (org-element-property :end elem))
24425 (let ((next-elem (org-element-at-point)))
24426 (when (or (org-element-nested-p elem next-elem)
24427 (and (eq (org-element-type next-elem) 'headline)
24428 (not (eq (org-element-type elem) 'headline))))
24429 (goto-char pos)
24430 (user-error "Cannot drag element forward"))
24431 ;; Compute new position of point: it's shifted by NEXT-ELEM
24432 ;; body's length (without final blanks) and by the length of
24433 ;; blanks between ELEM and NEXT-ELEM.
24434 (let ((size-next (- (save-excursion
24435 (goto-char (org-element-property :end next-elem))
24436 (skip-chars-backward " \r\t\n")
24437 (forward-line)
24438 ;; Small correction if buffer doesn't end
24439 ;; with a newline character.
24440 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24441 (org-element-property :begin next-elem)))
24442 (size-blank (- (org-element-property :end elem)
24443 (save-excursion
24444 (goto-char (org-element-property :end elem))
24445 (skip-chars-backward " \r\t\n")
24446 (forward-line)
24447 (point)))))
24448 (org-element-swap-A-B elem next-elem)
24449 (goto-char (+ pos size-next size-blank))))))
24451 (defun org-drag-line-forward (arg)
24452 "Drag the line at point ARG lines forward."
24453 (interactive "p")
24454 (dotimes (_ (abs arg))
24455 (let ((c (current-column)))
24456 (if (< 0 arg)
24457 (progn
24458 (beginning-of-line 2)
24459 (transpose-lines 1)
24460 (beginning-of-line 0))
24461 (transpose-lines 1)
24462 (beginning-of-line -1))
24463 (org-move-to-column c))))
24465 (defun org-drag-line-backward (arg)
24466 "Drag the line at point ARG lines backward."
24467 (interactive "p")
24468 (org-drag-line-forward (- arg)))
24470 (defun org-mark-element ()
24471 "Put point at beginning of this element, mark at end.
24473 Interactively, if this command is repeated or (in Transient Mark
24474 mode) if the mark is active, it marks the next element after the
24475 ones already marked."
24476 (interactive)
24477 (let (deactivate-mark)
24478 (if (and (called-interactively-p 'any)
24479 (or (and (eq last-command this-command) (mark t))
24480 (and transient-mark-mode mark-active)))
24481 (set-mark
24482 (save-excursion
24483 (goto-char (mark))
24484 (goto-char (org-element-property :end (org-element-at-point)))))
24485 (let ((element (org-element-at-point)))
24486 (end-of-line)
24487 (push-mark (org-element-property :end element) t t)
24488 (goto-char (org-element-property :begin element))))))
24490 (defun org-narrow-to-element ()
24491 "Narrow buffer to current element."
24492 (interactive)
24493 (let ((elem (org-element-at-point)))
24494 (cond
24495 ((eq (car elem) 'headline)
24496 (narrow-to-region
24497 (org-element-property :begin elem)
24498 (org-element-property :end elem)))
24499 ((memq (car elem) org-element-greater-elements)
24500 (narrow-to-region
24501 (org-element-property :contents-begin elem)
24502 (org-element-property :contents-end elem)))
24504 (narrow-to-region
24505 (org-element-property :begin elem)
24506 (org-element-property :end elem))))))
24508 (defun org-transpose-element ()
24509 "Transpose current and previous elements, keeping blank lines between.
24510 Point is moved after both elements."
24511 (interactive)
24512 (org-skip-whitespace)
24513 (let ((end (org-element-property :end (org-element-at-point))))
24514 (org-drag-element-backward)
24515 (goto-char end)))
24517 (defun org-unindent-buffer ()
24518 "Un-indent the visible part of the buffer.
24519 Relative indentation (between items, inside blocks, etc.) isn't
24520 modified."
24521 (interactive)
24522 (unless (eq major-mode 'org-mode)
24523 (user-error "Cannot un-indent a buffer not in Org mode"))
24524 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24525 (unindent-tree
24526 (lambda (contents)
24527 (dolist (element (reverse contents))
24528 (if (memq (org-element-type element) '(headline section))
24529 (funcall unindent-tree (org-element-contents element))
24530 (save-excursion
24531 (save-restriction
24532 (narrow-to-region
24533 (org-element-property :begin element)
24534 (org-element-property :end element))
24535 (org-do-remove-indentation))))))))
24536 (funcall unindent-tree (org-element-contents parse-tree))))
24538 (defun org-show-children (&optional level)
24539 "Show all direct subheadings of this heading.
24540 Prefix arg LEVEL is how many levels below the current level
24541 should be shown. Default is enough to cause the following
24542 heading to appear."
24543 (interactive "p")
24544 ;; If `orgstruct-mode' is active, use the slower version.
24545 (if orgstruct-mode (call-interactively #'outline-show-children)
24546 (save-excursion
24547 (org-back-to-heading t)
24548 (let* ((current-level (funcall outline-level))
24549 (max-level (org-get-valid-level
24550 current-level
24551 (if level (prefix-numeric-value level) 1)))
24552 (end (save-excursion (org-end-of-subtree t t)))
24553 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24554 (past-first-child nil)
24555 ;; Make sure to skip inlinetasks.
24556 (re (format regexp-fmt
24557 current-level
24558 (cond
24559 ((not (featurep 'org-inlinetask)) "")
24560 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24562 (t (1- org-inlinetask-min-level))))))
24563 ;; Display parent heading.
24564 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24565 (forward-line)
24566 ;; Display children. First child may be deeper than expected
24567 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24568 ;; MAX-LEVEL accordingly.
24569 (while (re-search-forward re end t)
24570 (unless past-first-child
24571 (setq re (format regexp-fmt
24572 current-level
24573 (max (funcall outline-level) max-level)))
24574 (setq past-first-child t))
24575 (outline-flag-region
24576 (line-end-position 0) (line-end-position) nil))))))
24578 (defun org-show-subtree ()
24579 "Show everything after this heading at deeper levels."
24580 (interactive)
24581 (outline-flag-region
24582 (point)
24583 (save-excursion
24584 (org-end-of-subtree t t))
24585 nil))
24587 (defun org-show-entry ()
24588 "Show the body directly following this heading.
24589 Show the heading too, if it is currently invisible."
24590 (interactive)
24591 (save-excursion
24592 (ignore-errors
24593 (org-back-to-heading t)
24594 (outline-flag-region
24595 (max (point-min) (1- (point)))
24596 (save-excursion
24597 (if (re-search-forward
24598 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24599 (match-beginning 1)
24600 (point-max)))
24601 nil)
24602 (org-cycle-hide-drawers 'children))))
24604 (defun org-make-options-regexp (kwds &optional extra)
24605 "Make a regular expression for keyword lines.
24606 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24607 when non-nil, is a regexp matching keywords names."
24608 (concat "^[ \t]*#\\+\\("
24609 (regexp-opt kwds)
24610 (and extra (concat (and kwds "\\|") extra))
24611 "\\):[ \t]*\\(.*\\)"))
24613 ;;;; Integration with and fixes for other packages
24615 ;;; Imenu support
24617 (defvar-local org-imenu-markers nil
24618 "All markers currently used by Imenu.")
24620 (defun org-imenu-new-marker (&optional pos)
24621 "Return a new marker for use by Imenu, and remember the marker."
24622 (let ((m (make-marker)))
24623 (move-marker m (or pos (point)))
24624 (push m org-imenu-markers)
24627 (defun org-imenu-get-tree ()
24628 "Produce the index for Imenu."
24629 (dolist (x org-imenu-markers) (move-marker x nil))
24630 (setq org-imenu-markers nil)
24631 (let* ((case-fold-search nil)
24632 (n org-imenu-depth)
24633 (re (concat "^" (org-get-limited-outline-regexp)))
24634 (subs (make-vector (1+ n) nil))
24635 (last-level 0)
24636 m level head0 head)
24637 (org-with-wide-buffer
24638 (goto-char (point-max))
24639 (while (re-search-backward re nil t)
24640 (setq level (org-reduced-level (funcall outline-level)))
24641 (when (and (<= level n)
24642 (looking-at org-complex-heading-regexp)
24643 (setq head0 (match-string-no-properties 4)))
24644 (setq head (org-link-display-format head0)
24645 m (org-imenu-new-marker))
24646 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24647 (if (>= level last-level)
24648 (push (cons head m) (aref subs level))
24649 (push (cons head (aref subs (1+ level))) (aref subs level))
24650 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24651 (setq last-level level))))
24652 (aref subs 1)))
24654 (eval-after-load "imenu"
24655 '(progn
24656 (add-hook 'imenu-after-jump-hook
24657 (lambda ()
24658 (when (derived-mode-p 'org-mode)
24659 (org-show-context 'org-goto))))))
24661 (defun org-link-display-format (s)
24662 "Replace links in string S with their description.
24663 If there is no description, use the link target."
24664 (save-match-data
24665 (replace-regexp-in-string
24666 org-bracket-link-analytic-regexp
24667 (lambda (m)
24668 (if (match-end 5) (match-string 5 m)
24669 (concat (match-string 1 m) (match-string 3 m))))
24670 s nil t)))
24672 (defun org-toggle-link-display ()
24673 "Toggle the literal or descriptive display of links."
24674 (interactive)
24675 (if org-descriptive-links
24676 (progn (org-remove-from-invisibility-spec '(org-link))
24677 (org-restart-font-lock)
24678 (setq org-descriptive-links nil))
24679 (progn (add-to-invisibility-spec '(org-link))
24680 (org-restart-font-lock)
24681 (setq org-descriptive-links t))))
24683 ;; Speedbar support
24685 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24686 "Overlay marking the agenda restriction line in speedbar.")
24687 (overlay-put org-speedbar-restriction-lock-overlay
24688 'face 'org-agenda-restriction-lock)
24689 (overlay-put org-speedbar-restriction-lock-overlay
24690 'help-echo "Agendas are currently limited to this item.")
24691 (delete-overlay org-speedbar-restriction-lock-overlay)
24693 (defun org-speedbar-set-agenda-restriction ()
24694 "Restrict future agenda commands to the location at point in speedbar.
24695 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24696 (interactive)
24697 (require 'org-agenda)
24698 (let (p m tp np dir txt)
24699 (cond
24700 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24701 'org-imenu t))
24702 (setq m (get-text-property p 'org-imenu-marker))
24703 (with-current-buffer (marker-buffer m)
24704 (goto-char m)
24705 (org-agenda-set-restriction-lock 'subtree)))
24706 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24707 'speedbar-function 'speedbar-find-file))
24708 (setq tp (previous-single-property-change
24709 (1+ p) 'speedbar-function)
24710 np (next-single-property-change
24711 tp 'speedbar-function)
24712 dir (speedbar-line-directory)
24713 txt (buffer-substring-no-properties (or tp (point-min))
24714 (or np (point-max))))
24715 (with-current-buffer (find-file-noselect
24716 (let ((default-directory dir))
24717 (expand-file-name txt)))
24718 (unless (derived-mode-p 'org-mode)
24719 (user-error "Cannot restrict to non-Org mode file"))
24720 (org-agenda-set-restriction-lock 'file)))
24721 (t (user-error "Don't know how to restrict Org mode agenda")))
24722 (move-overlay org-speedbar-restriction-lock-overlay
24723 (point-at-bol) (point-at-eol))
24724 (setq current-prefix-arg nil)
24725 (org-agenda-maybe-redo)))
24727 (defvar speedbar-file-key-map)
24728 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24729 (eval-after-load "speedbar"
24730 '(progn
24731 (speedbar-add-supported-extension ".org")
24732 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24733 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24734 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24735 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24736 (add-hook 'speedbar-visiting-tag-hook
24737 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24739 ;;; Fixes and Hacks for problems with other packages
24741 (defun org--flyspell-object-check-p (element)
24742 "Non-nil when Flyspell can check object at point.
24743 ELEMENT is the element at point."
24744 (let ((object (save-excursion
24745 (when (looking-at-p "\\>") (backward-char))
24746 (org-element-context element))))
24747 (cl-case (org-element-type object)
24748 ;; Prevent checks in links due to keybinding conflict with
24749 ;; Flyspell.
24750 ((code entity export-snippet inline-babel-call
24751 inline-src-block line-break latex-fragment link macro
24752 statistics-cookie target timestamp verbatim)
24753 nil)
24754 (footnote-reference
24755 ;; Only in inline footnotes, within the definition.
24756 (and (eq (org-element-property :type object) 'inline)
24757 (< (save-excursion
24758 (goto-char (org-element-property :begin object))
24759 (search-forward ":" nil t 2))
24760 (point))))
24761 (otherwise t))))
24763 (defun org-mode-flyspell-verify ()
24764 "Function used for `flyspell-generic-check-word-predicate'."
24765 (if (org-at-heading-p)
24766 ;; At a headline or an inlinetask, check title only. This is
24767 ;; faster than relying on `org-element-at-point'.
24768 (and (save-excursion (beginning-of-line)
24769 (and (let ((case-fold-search t))
24770 (not (looking-at-p "\\*+ END[ \t]*$")))
24771 (let ((case-fold-search nil))
24772 (looking-at org-complex-heading-regexp))))
24773 (match-beginning 4)
24774 (>= (point) (match-beginning 4))
24775 (or (not (match-beginning 5))
24776 (< (point) (match-beginning 5))))
24777 (let* ((element (org-element-at-point))
24778 (post-affiliated (org-element-property :post-affiliated element)))
24779 (cond
24780 ;; Ignore checks in all affiliated keywords but captions.
24781 ((< (point) post-affiliated)
24782 (and (save-excursion
24783 (beginning-of-line)
24784 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24785 (> (point) (match-end 0))
24786 (org--flyspell-object-check-p element)))
24787 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24788 ((let ((log (org-log-into-drawer)))
24789 (and log
24790 (let ((drawer (org-element-lineage element '(drawer))))
24791 (and drawer
24792 (eq (compare-strings
24793 log nil nil
24794 (org-element-property :drawer-name drawer) nil nil t)
24795 t)))))
24796 nil)
24798 (cl-case (org-element-type element)
24799 ((comment quote-section) t)
24800 (comment-block
24801 ;; Allow checks between block markers, not on them.
24802 (and (> (line-beginning-position) post-affiliated)
24803 (save-excursion
24804 (end-of-line)
24805 (skip-chars-forward " \r\t\n")
24806 (< (point) (org-element-property :end element)))))
24807 ;; Arbitrary list of keywords where checks are meaningful.
24808 ;; Make sure point is on the value part of the element.
24809 (keyword
24810 (and (member (org-element-property :key element)
24811 '("DESCRIPTION" "TITLE"))
24812 (save-excursion
24813 (search-backward ":" (line-beginning-position) t))))
24814 ;; Check is globally allowed in paragraphs verse blocks and
24815 ;; table rows (after affiliated keywords) but some objects
24816 ;; must not be affected.
24817 ((paragraph table-row verse-block)
24818 (let ((cbeg (org-element-property :contents-begin element))
24819 (cend (org-element-property :contents-end element)))
24820 (and cbeg (>= (point) cbeg) (< (point) cend)
24821 (org--flyspell-object-check-p element))))))))))
24822 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24824 (defun org-remove-flyspell-overlays-in (beg end)
24825 "Remove flyspell overlays in region."
24826 (and (bound-and-true-p flyspell-mode)
24827 (fboundp 'flyspell-delete-region-overlays)
24828 (flyspell-delete-region-overlays beg end)))
24830 (defvar flyspell-delayed-commands)
24831 (eval-after-load "flyspell"
24832 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24834 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24835 (eval-after-load "bookmark"
24836 '(if (boundp 'bookmark-after-jump-hook)
24837 ;; We can use the hook
24838 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24839 ;; Hook not available, use advice
24840 (defadvice bookmark-jump (after org-make-visible activate)
24841 "Make the position visible."
24842 (org-bookmark-jump-unhide))))
24844 ;; Make sure saveplace shows the location if it was hidden
24845 (eval-after-load "saveplace"
24846 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24847 "Make the position visible."
24848 (org-bookmark-jump-unhide)))
24850 ;; Make sure ecb shows the location if it was hidden
24851 (eval-after-load "ecb"
24852 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24853 "Make hierarchy visible when jumping into location from ECB tree buffer."
24854 (when (derived-mode-p 'org-mode)
24855 (org-show-context))))
24857 (defun org-bookmark-jump-unhide ()
24858 "Unhide the current position, to show the bookmark location."
24859 (and (derived-mode-p 'org-mode)
24860 (or (outline-invisible-p)
24861 (save-excursion (goto-char (max (point-min) (1- (point))))
24862 (outline-invisible-p)))
24863 (org-show-context 'bookmark-jump)))
24865 (defun org-mark-jump-unhide ()
24866 "Make the point visible with `org-show-context' after jumping to the mark."
24867 (when (and (derived-mode-p 'org-mode)
24868 (outline-invisible-p))
24869 (org-show-context 'mark-goto)))
24871 (eval-after-load "simple"
24872 '(defadvice pop-to-mark-command (after org-make-visible activate)
24873 "Make the point visible with `org-show-context'."
24874 (org-mark-jump-unhide)))
24876 (eval-after-load "simple"
24877 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24878 "Make the point visible with `org-show-context'."
24879 (org-mark-jump-unhide)))
24881 (eval-after-load "simple"
24882 '(defadvice pop-global-mark (after org-make-visible activate)
24883 "Make the point visible with `org-show-context'."
24884 (org-mark-jump-unhide)))
24886 ;; Make session.el ignore our circular variable
24887 (defvar session-globals-exclude)
24888 (eval-after-load "session"
24889 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24891 ;;;; Finish up
24893 (provide 'org)
24895 (run-hooks 'org-load-hook)
24897 ;;; org.el ends here