Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob482c4fe0023a692491640f166195b652687ee5b3
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 "hledger" hledger)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "ebnf2ps" ebnf2ps))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 \\<org-mode-map>
531 An entry can be toggled between COMMENT and normal with
532 `\\[org-toggle-comment]'.")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (dolist (ext org-modules)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 (provide \\='org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " eww: Store link to url of eww" org-eww)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
715 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
716 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
717 (const :tag "C collector: Collect properties into tables" org-collector)
718 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
719 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
720 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
721 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
722 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
723 (const :tag "C eval: Include command output as text" org-eval)
724 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
725 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
726 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
727 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
728 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
729 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
730 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
731 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
732 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
733 (const :tag "C man: Support for links to manpages in Org mode" org-man)
734 (const :tag "C mew: Links to Mew folders/messages" org-mew)
735 (const :tag "C mtags: Support for muse-like tags" org-mtags)
736 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
737 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
738 (const :tag "C registry: A registry for Org links" org-registry)
739 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
740 (const :tag "C secretary: Team management with org-mode" org-secretary)
741 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
742 (const :tag "C toc: Table of contents for Org buffer" org-toc)
743 (const :tag "C track: Keep up with Org mode development" org-track)
744 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
745 (const :tag "C vm: Links to VM folders/messages" org-vm)
746 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
747 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
748 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
750 (defvar org-export-registered-backends) ; From ox.el.
751 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
752 (declare-function org-export-backend-name "ox" (backend) t)
753 (defcustom org-export-backends '(ascii html icalendar latex odt)
754 "List of export back-ends that should be always available.
756 If a description starts with <C>, the file is not part of Emacs
757 and loading it will require that you have downloaded and properly
758 installed the Org mode distribution.
760 Unlike to `org-modules', libraries in this list will not be
761 loaded along with Org, but only once the export framework is
762 needed.
764 This variable needs to be set before org.el is loaded. If you
765 need to make a change while Emacs is running, use the customize
766 interface or run the following code, where VAL stands for the new
767 value of the variable, after updating it:
769 (progn
770 (setq org-export-registered-backends
771 (cl-remove-if-not
772 (lambda (backend)
773 (let ((name (org-export-backend-name backend)))
774 (or (memq name val)
775 (catch \\='parentp
776 (dolist (b val)
777 (and (org-export-derived-backend-p b name)
778 (throw \\='parentp t)))))))
779 org-export-registered-backends))
780 (let ((new-list (mapcar #\\='org-export-backend-name
781 org-export-registered-backends)))
782 (dolist (backend val)
783 (cond
784 ((not (load (format \"ox-%s\" backend) t t))
785 (message \"Problems while trying to load export back-end \\=`%s\\='\"
786 backend))
787 ((not (memq backend new-list)) (push backend new-list))))
788 (set-default \\='org-export-backends new-list)))
790 Adding a back-end to this list will also pull the back-end it
791 depends on, if any."
792 :group 'org
793 :group 'org-export
794 :version "26.1"
795 :package-version '(Org . "9.0")
796 :initialize 'custom-initialize-set
797 :set (lambda (var val)
798 (if (not (featurep 'ox)) (set-default var val)
799 ;; Any back-end not required anymore (not present in VAL and not
800 ;; a parent of any back-end in the new value) is removed from the
801 ;; list of registered back-ends.
802 (setq org-export-registered-backends
803 (cl-remove-if-not
804 (lambda (backend)
805 (let ((name (org-export-backend-name backend)))
806 (or (memq name val)
807 (catch 'parentp
808 (dolist (b val)
809 (and (org-export-derived-backend-p b name)
810 (throw 'parentp t)))))))
811 org-export-registered-backends))
812 ;; Now build NEW-LIST of both new back-ends and required
813 ;; parents.
814 (let ((new-list (mapcar #'org-export-backend-name
815 org-export-registered-backends)))
816 (dolist (backend val)
817 (cond
818 ((not (load (format "ox-%s" backend) t t))
819 (message "Problems while trying to load export back-end `%s'"
820 backend))
821 ((not (memq backend new-list)) (push backend new-list))))
822 ;; Set VAR to that list with fixed dependencies.
823 (set-default var new-list))))
824 :type '(set :greedy t
825 (const :tag " ascii Export buffer to ASCII format" ascii)
826 (const :tag " beamer Export buffer to Beamer presentation" beamer)
827 (const :tag " html Export buffer to HTML format" html)
828 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
829 (const :tag " latex Export buffer to LaTeX format" latex)
830 (const :tag " man Export buffer to MAN format" man)
831 (const :tag " md Export buffer to Markdown format" md)
832 (const :tag " odt Export buffer to ODT format" odt)
833 (const :tag " org Export buffer to Org format" org)
834 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
835 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
836 (const :tag "C deck Export buffer to deck.js presentations" deck)
837 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
838 (const :tag "C groff Export buffer to Groff format" groff)
839 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
840 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
841 (const :tag "C s5 Export buffer to s5 presentations" s5)
842 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
844 (eval-after-load 'ox
845 '(dolist (backend org-export-backends)
846 (condition-case nil (require (intern (format "ox-%s" backend)))
847 (error (message "Problems while trying to load export back-end `%s'"
848 backend)))))
850 (defcustom org-support-shift-select nil
851 "Non-nil means make shift-cursor commands select text when possible.
852 \\<org-mode-map>\
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands:
880 `\\[org-todo]' and `\\[org-priority]' \
881 to change TODO state and priority,
882 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
883 can be used to switch TODO sets,
884 `\\[org-ctrl-c-minus]' to cycle item bullet types,
885 and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up."
889 :group 'org
890 :type '(choice
891 (const :tag "Never" nil)
892 (const :tag "When outside special context" t)
893 (const :tag "Everywhere except timestamps" always)))
895 (defcustom org-loop-over-headlines-in-active-region nil
896 "Shall some commands act upon headlines in the active region?
898 When set to t, some commands will be performed in all headlines
899 within the active region.
901 When set to `start-level', some commands will be performed in all
902 headlines within the active region, provided that these headlines
903 are of the same level than the first one.
905 When set to a string, those commands will be performed on the
906 matching headlines within the active region. Such string must be
907 a tags/property/todo match as it is used in the agenda tags view.
909 The list of commands is: `org-schedule', `org-deadline',
910 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
911 `org-archive-to-archive-sibling'. The archiving commands skip
912 already archived entries."
913 :type '(choice (const :tag "Don't loop" nil)
914 (const :tag "All headlines in active region" t)
915 (const :tag "In active region, headlines at the same level than the first one" start-level)
916 (string :tag "Tags/Property/Todo matcher"))
917 :version "24.1"
918 :group 'org-todo
919 :group 'org-archive)
921 (defgroup org-startup nil
922 "Options concerning startup of Org mode."
923 :tag "Org Startup"
924 :group 'org)
926 (defcustom org-startup-folded t
927 "Non-nil means entering Org mode will switch to OVERVIEW.
929 This can also be configured on a per-file basis by adding one of
930 the following lines anywhere in the buffer:
932 #+STARTUP: fold (or `overview', this is equivalent)
933 #+STARTUP: nofold (or `showall', this is equivalent)
934 #+STARTUP: content
935 #+STARTUP: showeverything
937 Set `org-agenda-inhibit-startup' to a non-nil value if you want
938 to ignore this option when Org opens agenda files for the first
939 time."
940 :group 'org-startup
941 :type '(choice
942 (const :tag "nofold: show all" nil)
943 (const :tag "fold: overview" t)
944 (const :tag "content: all headlines" content)
945 (const :tag "show everything, even drawers" showeverything)))
947 (defcustom org-startup-truncated t
948 "Non-nil means entering Org mode will set `truncate-lines'.
949 This is useful since some lines containing links can be very long and
950 uninteresting. Also tables look terrible when wrapped.
952 The variable `org-startup-truncated' allows to configure
953 truncation for Org mode different to the other modes that use the
954 variable `truncate-lines' and as a shortcut instead of putting
955 the variable `truncate-lines' into the `org-mode-hook'. If one
956 wants to configure truncation for Org mode not statically but
957 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
958 the variable `truncate-lines' has to be used because in such a
959 case it is too late to set the variable `org-startup-truncated'."
960 :group 'org-startup
961 :type 'boolean)
963 (defcustom org-startup-indented nil
964 "Non-nil means turn on `org-indent-mode' on startup.
965 This can also be configured on a per-file basis by adding one of
966 the following lines anywhere in the buffer:
968 #+STARTUP: indent
969 #+STARTUP: noindent"
970 :group 'org-structure
971 :type '(choice
972 (const :tag "Not" nil)
973 (const :tag "Globally (slow on startup in large files)" t)))
975 (defcustom org-use-sub-superscripts t
976 "Non-nil means interpret \"_\" and \"^\" for display.
978 If you want to control how Org exports those characters, see
979 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
980 used to be an alias for `org-export-with-sub-superscripts' in
981 Org <8.0, it is not anymore.
983 When this option is turned on, you can use TeX-like syntax for
984 sub- and superscripts within the buffer. Several characters after
985 \"_\" or \"^\" will be considered as a single item - so grouping
986 with {} is normally not needed. For example, the following things
987 will be parsed as single sub- or superscripts:
989 10^24 or 10^tau several digits will be considered 1 item.
990 10^-12 or 10^-tau a leading sign with digits or a word
991 x^2-y^3 will be read as x^2 - y^3, because items are
992 terminated by almost any nonword/nondigit char.
993 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
995 Still, ambiguity is possible. So when in doubt, use {} to enclose
996 the sub/superscript. If you set this variable to the symbol `{}',
997 the braces are *required* in order to trigger interpretations as
998 sub/superscript. This can be helpful in documents that need \"_\"
999 frequently in plain text."
1000 :group 'org-startup
1001 :version "24.4"
1002 :package-version '(Org . "8.0")
1003 :type '(choice
1004 (const :tag "Always interpret" t)
1005 (const :tag "Only with braces" {})
1006 (const :tag "Never interpret" nil)))
1008 (defcustom org-startup-with-beamer-mode nil
1009 "Non-nil means turn on `org-beamer-mode' on startup.
1010 This can also be configured on a per-file basis by adding one of
1011 the following lines anywhere in the buffer:
1013 #+STARTUP: beamer"
1014 :group 'org-startup
1015 :version "24.1"
1016 :type 'boolean)
1018 (defcustom org-startup-align-all-tables nil
1019 "Non-nil means align all tables when visiting a file.
1020 This is useful when the column width in tables is forced with <N> cookies
1021 in table fields. Such tables will look correct only after the first re-align.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: align
1025 #+STARTUP: noalign"
1026 :group 'org-startup
1027 :type 'boolean)
1029 (defcustom org-startup-with-inline-images nil
1030 "Non-nil means show inline images when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: inlineimages
1034 #+STARTUP: noinlineimages"
1035 :group 'org-startup
1036 :version "24.1"
1037 :type 'boolean)
1039 (defcustom org-startup-with-latex-preview nil
1040 "Non-nil means preview LaTeX fragments when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: latexpreview
1045 #+STARTUP: nolatexpreview"
1046 :group 'org-startup
1047 :version "24.4"
1048 :package-version '(Org . "8.0")
1049 :type 'boolean)
1051 (defcustom org-insert-mode-line-in-empty-file nil
1052 "Non-nil means insert the first line setting Org mode in empty files.
1053 When the function `org-mode' is called interactively in an empty file, this
1054 normally means that the file name does not automatically trigger Org mode.
1055 To ensure that the file will always be in Org mode in the future, a
1056 line enforcing Org mode will be inserted into the buffer, if this option
1057 has been set."
1058 :group 'org-startup
1059 :type 'boolean)
1061 (defcustom org-replace-disputed-keys nil
1062 "Non-nil means use alternative key bindings for some keys.
1063 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1064 These keys are also used by other packages like shift-selection-mode'
1065 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1066 If you want to use Org mode together with one of these other modes,
1067 or more generally if you would like to move some Org mode commands to
1068 other keys, set this variable and configure the keys with the variable
1069 `org-disputed-keys'.
1071 This option is only relevant at load-time of Org mode, and must be set
1072 *before* org.el is loaded. Changing it requires a restart of Emacs to
1073 become effective."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-use-extra-keys nil
1078 "Non-nil means use extra key sequence definitions for certain commands.
1079 This happens automatically if `window-system' is nil. This
1080 variable lets you do the same manually. You must set it before
1081 loading Org."
1082 :group 'org-startup
1083 :type 'boolean)
1085 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1087 (defcustom org-disputed-keys
1088 '(([(shift up)] . [(meta p)])
1089 ([(shift down)] . [(meta n)])
1090 ([(shift left)] . [(meta -)])
1091 ([(shift right)] . [(meta +)])
1092 ([(control shift right)] . [(meta shift +)])
1093 ([(control shift left)] . [(meta shift -)]))
1094 "Keys for which Org mode and other modes compete.
1095 This is an alist, cars are the default keys, second element specifies
1096 the alternative to use when `org-replace-disputed-keys' is t.
1098 Keys can be specified in any syntax supported by `define-key'.
1099 The value of this option takes effect only at Org mode startup,
1100 therefore you'll have to restart Emacs to apply it after changing."
1101 :group 'org-startup
1102 :type 'alist)
1104 (defun org-key (key)
1105 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1106 Or return the original if not disputed."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 key)
1114 (defun org-defkey (keymap key def)
1115 "Define a key, possibly translated, as returned by `org-key'."
1116 (define-key keymap (org-key key) def))
1118 (defcustom org-ellipsis nil
1119 "The ellipsis to use in the Org mode outline.
1121 When nil, just use the standard three dots.
1122 When a string, use that string instead.
1124 The change affects only Org mode (which will then use its own display table).
1125 Changing this requires executing `\\[org-mode]' in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (string :tag "String" :value "...#"))
1130 :safe #'string-or-null-p)
1132 (defvar org-display-table nil
1133 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((agenda . local)
1159 (bookmark-jump . lineage)
1160 (isearch . lineage)
1161 (default . ancestors))
1162 "Alist between context and visibility span when revealing a location.
1164 \\<org-mode-map>Some actions may move point into invisible
1165 locations. As a consequence, Org always expose a neighborhood
1166 around point. How much is shown depends on the initial action,
1167 or context. Valid contexts are
1169 agenda when exposing an entry from the agenda
1170 org-goto when using the command `org-goto' (`\\[org-goto]')
1171 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1172 tags-tree when constructing a sparse tree based on tags matches
1173 link-search when exposing search matches associated with a link
1174 mark-goto when exposing the jump goal of a mark
1175 bookmark-jump when exposing a bookmark location
1176 isearch when exiting from an incremental search
1177 default default for all contexts not set explicitly
1179 Allowed visibility spans are
1181 minimal show current headline; if point is not on headline,
1182 also show entry
1184 local show current headline, entry and next headline
1186 ancestors show current headline and its direct ancestors; if
1187 point is not on headline, also show entry
1189 lineage show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and first child
1193 tree show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and all children
1197 canonical show current headline, its direct ancestors along with
1198 their entries and children; if point is not located on
1199 the headline, also show current entry and all children
1201 As special cases, a nil or t value means show all contexts in
1202 `minimal' or `canonical' view, respectively.
1204 Some views can make displayed information very compact, but also
1205 make it harder to edit the location of the match. In such
1206 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1207 more context."
1208 :group 'org-reveal-location
1209 :version "26.1"
1210 :package-version '(Org . "9.0")
1211 :type '(choice
1212 (const :tag "Canonical" t)
1213 (const :tag "Minimal" nil)
1214 (repeat :greedy t :tag "Individual contexts"
1215 (cons
1216 (choice :tag "Context"
1217 (const agenda)
1218 (const org-goto)
1219 (const occur-tree)
1220 (const tags-tree)
1221 (const link-search)
1222 (const mark-goto)
1223 (const bookmark-jump)
1224 (const isearch)
1225 (const default))
1226 (choice :tag "Detail level"
1227 (const minimal)
1228 (const local)
1229 (const ancestors)
1230 (const lineage)
1231 (const tree)
1232 (const canonical))))))
1234 (defcustom org-indirect-buffer-display 'other-window
1235 "How should indirect tree buffers be displayed?
1237 This applies to indirect buffers created with the commands
1238 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1240 Valid values are:
1241 current-window Display in the current window
1242 other-window Just display in another window.
1243 dedicated-frame Create one new frame, and re-use it each time.
1244 new-frame Make a new frame each time. Note that in this case
1245 previously-made indirect buffers are kept, and you need to
1246 kill these buffers yourself."
1247 :group 'org-structure
1248 :group 'org-agenda-windows
1249 :type '(choice
1250 (const :tag "In current window" current-window)
1251 (const :tag "In current frame, other window" other-window)
1252 (const :tag "Each time a new frame" new-frame)
1253 (const :tag "One dedicated frame" dedicated-frame)))
1255 (defcustom org-use-speed-commands nil
1256 "Non-nil means activate single letter commands at beginning of a headline.
1257 This may also be a function to test for appropriate locations where speed
1258 commands should be active.
1260 For example, to activate speed commands when the point is on any
1261 star at the beginning of the headline, you can do this:
1263 (setq org-use-speed-commands
1264 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1265 :group 'org-structure
1266 :type '(choice
1267 (const :tag "Never" nil)
1268 (const :tag "At beginning of headline stars" t)
1269 (function)))
1271 (defcustom org-speed-commands-user nil
1272 "Alist of additional speed commands.
1273 This list will be checked before `org-speed-commands-default'
1274 when the variable `org-use-speed-commands' is non-nil
1275 and when the cursor is at the beginning of a headline.
1276 The car if each entry is a string with a single letter, which must
1277 be assigned to `self-insert-command' in the global map.
1278 The cdr is either a command to be called interactively, a function
1279 to be called, or a form to be evaluated.
1280 An entry that is just a list with a single string will be interpreted
1281 as a descriptive headline that will be added when listing the speed
1282 commands in the Help buffer using the `?' speed command."
1283 :group 'org-structure
1284 :type '(repeat :value ("k" . ignore)
1285 (choice :value ("k" . ignore)
1286 (list :tag "Descriptive Headline" (string :tag "Headline"))
1287 (cons :tag "Letter and Command"
1288 (string :tag "Command letter")
1289 (choice
1290 (function)
1291 (sexp))))))
1293 (defcustom org-bookmark-names-plist
1294 '(:last-capture "org-capture-last-stored"
1295 :last-refile "org-refile-last-stored"
1296 :last-capture-marker "org-capture-last-stored-marker")
1297 "Names for bookmarks automatically set by some Org commands.
1298 This can provide strings as names for a number of bookmarks Org sets
1299 automatically. The following keys are currently implemented:
1300 :last-capture
1301 :last-capture-marker
1302 :last-refile
1303 When a key does not show up in the property list, the corresponding bookmark
1304 is not set."
1305 :group 'org-structure
1306 :type 'plist)
1308 (defgroup org-cycle nil
1309 "Options concerning visibility cycling in Org mode."
1310 :tag "Org Cycle"
1311 :group 'org-structure)
1313 (defcustom org-cycle-skip-children-state-if-no-children t
1314 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 :group 'org-cycle
1316 :type 'boolean)
1318 (defcustom org-cycle-max-level nil
1319 "Maximum level which should still be subject to visibility cycling.
1320 Levels higher than this will, for cycling, be treated as text, not a headline.
1321 When `org-odd-levels-only' is set, a value of N in this variable actually
1322 means 2N-1 stars as the limiting headline.
1323 When nil, cycle all levels.
1324 Note that the limiting level of cycling is also influenced by
1325 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1326 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 than its value."
1328 :group 'org-cycle
1329 :type '(choice
1330 (const :tag "No limit" nil)
1331 (integer :tag "Maximum level")))
1333 (defcustom org-hide-block-startup nil
1334 "Non-nil means entering Org mode will fold all blocks.
1335 This can also be set in on a per-file basis with
1337 #+STARTUP: hideblocks
1338 #+STARTUP: showblocks"
1339 :group 'org-startup
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-global-at-bob nil
1344 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use `S-TAB'
1347 or `\\[universal-argument] TAB'. For this special case to work, the first \
1348 line of the buffer
1349 must not be a headline -- it may be empty or some other text.
1351 When used in this way, `org-cycle-hook' is disabled temporarily to make
1352 sure the cursor stays at the beginning of the buffer.
1354 When this option is nil, don't do anything special at the beginning of
1355 the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-hide-drawers
1420 org-cycle-show-empty-lines
1421 org-optimize-window-after-visibility-change)
1422 "Hook that is run after `org-cycle' has changed the buffer visibility.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that was set by the most recent `org-cycle' command. The
1425 argument is a symbol. After a global state change, it can have the values
1426 `overview', `contents', or `all'. After a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook
1430 :version "26.1"
1431 :package-version '(Org . "8.3"))
1433 (defgroup org-edit-structure nil
1434 "Options concerning structure editing in Org mode."
1435 :tag "Org Edit Structure"
1436 :group 'org-structure)
1438 (defcustom org-odd-levels-only nil
1439 "Non-nil means skip even levels and only use odd levels for the outline.
1440 This has the effect that two stars are being added/taken away in
1441 promotion/demotion commands. It also influences how levels are
1442 handled by the exporters.
1443 Changing it requires restart of `font-lock-mode' to become effective
1444 for fontification also in regions already fontified.
1445 You may also set this on a per-file basis by adding one of the following
1446 lines to the buffer:
1448 #+STARTUP: odd
1449 #+STARTUP: oddeven"
1450 :group 'org-edit-structure
1451 :group 'org-appearance
1452 :type 'boolean)
1454 (defcustom org-adapt-indentation t
1455 "Non-nil means adapt indentation to outline node level.
1457 When this variable is set, Org assumes that you write outlines by
1458 indenting text in each node to align with the headline (after the
1459 stars). The following issues are influenced by this variable:
1461 - The indentation is increased by one space in a demotion
1462 command, and decreased by one in a promotion command. However,
1463 in the latter case, if shifting some line in the entry body
1464 would alter document structure (e.g., insert a new headline),
1465 indentation is not changed at all.
1467 - Property drawers and planning information is inserted indented
1468 when this variable is set. When nil, they will not be indented.
1470 - TAB indents a line relative to current level. The lines below
1471 a headline will be indented when this variable is set.
1473 Note that this is all about true indentation, by adding and
1474 removing space characters. See also `org-indent.el' which does
1475 level-dependent indentation in a virtual way, i.e. at display
1476 time in Emacs."
1477 :group 'org-edit-structure
1478 :type 'boolean)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 \\<org-mode-map>
1618 When nil, the new heading is created directly after the current line.
1619 The commands `\\[org-insert-heading-respect-content]' and \
1620 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1621 for the duration of the command."
1622 :group 'org-structure
1623 :type 'boolean)
1625 (defcustom org-blank-before-new-entry '((heading . auto)
1626 (plain-list-item . auto))
1627 "Should `org-insert-heading' leave a blank line before new heading/item?
1628 The value is an alist, with `heading' and `plain-list-item' as CAR,
1629 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1630 which case Org will look at the surrounding headings/items and try to
1631 make an intelligent decision whether to insert a blank line or not."
1632 :group 'org-edit-structure
1633 :type '(list
1634 (cons (const heading)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))
1638 (cons (const plain-list-item)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))))
1643 (defcustom org-insert-heading-hook nil
1644 "Hook being run after inserting a new heading."
1645 :group 'org-edit-structure
1646 :type 'hook)
1648 (defcustom org-enable-fixed-width-editor t
1649 "Non-nil means lines starting with \":\" are treated as fixed-width.
1650 This currently only means they are never auto-wrapped.
1651 When nil, such lines will be treated like ordinary lines."
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defcustom org-goto-auto-isearch t
1656 "Non-nil means typing characters in `org-goto' starts incremental search.
1657 When nil, you can use these keybindings to navigate the buffer:
1659 q Quit the org-goto interface
1660 n Go to the next visible heading
1661 p Go to the previous visible heading
1662 f Go one heading forward on same level
1663 b Go one heading backward on same level
1664 u Go one heading up"
1665 :group 'org-edit-structure
1666 :type 'boolean)
1668 (defgroup org-sparse-trees nil
1669 "Options concerning sparse trees in Org mode."
1670 :tag "Org Sparse Trees"
1671 :group 'org-structure)
1673 (defcustom org-highlight-sparse-tree-matches t
1674 "Non-nil means highlight all matches that define a sparse tree.
1675 The highlights will automatically disappear the next time the buffer is
1676 changed by an edit command."
1677 :group 'org-sparse-trees
1678 :type 'boolean)
1680 (defcustom org-remove-highlights-with-change t
1681 "Non-nil means any change to the buffer will remove temporary highlights.
1682 \\<org-mode-map>\
1683 Such highlights are created by `org-occur' and `org-clock-display'.
1684 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1685 to get rid of the highlights.
1686 The highlights created by `org-toggle-latex-fragment' always need
1687 `\\[org-toggle-latex-fragment]' to be removed."
1688 :group 'org-sparse-trees
1689 :group 'org-time
1690 :type 'boolean)
1692 (defcustom org-occur-case-fold-search t
1693 "Non-nil means `org-occur' should be case-insensitive.
1694 If set to `smart' the search will be case-insensitive only if it
1695 doesn't specify any upper case character."
1696 :group 'org-sparse-trees
1697 :version "26.1"
1698 :type '(choice
1699 (const :tag "Case-sensitive" nil)
1700 (const :tag "Case-insensitive" t)
1701 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1703 (defcustom org-occur-hook '(org-first-headline-recenter)
1704 "Hook that is run after `org-occur' has constructed a sparse tree.
1705 This can be used to recenter the window to show as much of the structure
1706 as possible."
1707 :group 'org-sparse-trees
1708 :type 'hook)
1710 (defgroup org-imenu-and-speedbar nil
1711 "Options concerning imenu and speedbar in Org mode."
1712 :tag "Org Imenu and Speedbar"
1713 :group 'org-structure)
1715 (defcustom org-imenu-depth 2
1716 "The maximum level for Imenu access to Org headlines.
1717 This also applied for speedbar access."
1718 :group 'org-imenu-and-speedbar
1719 :type 'integer)
1721 (defgroup org-table nil
1722 "Options concerning tables in Org mode."
1723 :tag "Org Table"
1724 :group 'org)
1726 (defcustom org-enable-table-editor 'optimized
1727 "Non-nil means lines starting with \"|\" are handled by the table editor.
1728 When nil, such lines will be treated like ordinary lines.
1730 When equal to the symbol `optimized', the table editor will be optimized to
1731 do the following:
1732 - Automatic overwrite mode in front of whitespace in table fields.
1733 This makes the structure of the table stay in tact as long as the edited
1734 field does not exceed the column width.
1735 - Minimize the number of realigns. Normally, the table is aligned each time
1736 TAB or RET are pressed to move to another field. With optimization this
1737 happens only if changes to a field might have changed the column width.
1738 Optimization requires replacing the functions `self-insert-command',
1739 `delete-char', and `backward-delete-char' in Org buffers, with a
1740 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1741 good at guessing when a re-align will be necessary, but you can always
1742 force one with `\\[org-ctrl-c-ctrl-c]'.
1744 If you would like to use the optimized version in Org mode, but the
1745 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1747 This variable can be used to turn on and off the table editor during a session,
1748 but in order to toggle optimization, a restart is required.
1750 See also the variable `org-table-auto-blank-field'."
1751 :group 'org-table
1752 :type '(choice
1753 (const :tag "off" nil)
1754 (const :tag "on" t)
1755 (const :tag "on, optimized" optimized)))
1757 (defcustom org-self-insert-cluster-for-undo nil
1758 "Non-nil means cluster self-insert commands for undo when possible.
1759 If this is set, then, like in the Emacs command loop, 20 consecutive
1760 characters will be undone together.
1761 This is configurable, because there is some impact on typing performance."
1762 :group 'org-table
1763 :type 'boolean)
1765 (defcustom org-table-tab-recognizes-table.el t
1766 "Non-nil means TAB will automatically notice a table.el table.
1767 When it sees such a table, it moves point into it and - if necessary -
1768 calls `table-recognize-table'."
1769 :group 'org-table-editing
1770 :type 'boolean)
1772 (defgroup org-link nil
1773 "Options concerning links in Org mode."
1774 :tag "Org Link"
1775 :group 'org)
1777 (defvar-local org-link-abbrev-alist-local nil
1778 "Buffer-local version of `org-link-abbrev-alist', which see.
1779 The value of this is taken from the #+LINK lines.")
1781 (defcustom org-link-parameters
1782 '(("doi" :follow org--open-doi-link)
1783 ("elisp" :follow org--open-elisp-link)
1784 ("file" :complete org-file-complete-link)
1785 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1786 ("help" :follow org--open-help-link)
1787 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1788 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1789 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1790 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1791 ("shell" :follow org--open-shell-link))
1792 "An alist of properties that defines all the links in Org mode.
1793 The key in each association is a string of the link type.
1794 Subsequent optional elements make up a p-list of link properties.
1796 :follow - A function that takes the link path as an argument.
1798 :export - A function that takes the link path, description and
1799 export-backend as arguments.
1801 :store - A function responsible for storing the link. See the
1802 function `org-store-link-functions'.
1804 :complete - A function that inserts a link with completion. The
1805 function takes one optional prefix arg.
1807 :face - A face for the link, or a function that returns a face.
1808 The function takes one argument which is the link path. The
1809 default face is `org-link'.
1811 :mouse-face - The mouse-face. The default is `highlight'.
1813 :display - `full' will not fold the link in descriptive
1814 display. Default is `org-link'.
1816 :help-echo - A string or function that takes (window object position)
1817 as arguments and returns a string.
1819 :keymap - A keymap that is active on the link. The default is
1820 `org-mouse-map'.
1822 :htmlize-link - A function for the htmlize-link. Defaults
1823 to (list :uri \"type:path\")
1825 :activate-func - A function to run at the end of font-lock
1826 activation. The function must accept (link-start link-end path bracketp)
1827 as arguments."
1828 :group 'org-link
1829 :type '(alist :tag "Link display parameters"
1830 :value-type plist)
1831 :version "26.1"
1832 :package-version '(Org . "9.1"))
1834 (defun org-link-get-parameter (type key)
1835 "Get TYPE link property for KEY.
1836 TYPE is a string and KEY is a plist keyword."
1837 (plist-get
1838 (cdr (assoc type org-link-parameters))
1839 key))
1841 (defun org-link-set-parameters (type &rest parameters)
1842 "Set link TYPE properties to PARAMETERS.
1843 PARAMETERS should be :key val pairs."
1844 (let ((data (assoc type org-link-parameters)))
1845 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1846 (push (cons type parameters) org-link-parameters)
1847 (org-make-link-regexps)
1848 (org-element-update-syntax))))
1850 (defun org-link-types ()
1851 "Return a list of known link types."
1852 (mapcar #'car org-link-parameters))
1854 (defcustom org-link-abbrev-alist nil
1855 "Alist of link abbreviations.
1856 The car of each element is a string, to be replaced at the start of a link.
1857 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1858 links in Org buffers can have an optional tag after a double colon, e.g.,
1860 [[linkkey:tag][description]]
1862 The `linkkey' must be a single word, starting with a letter, followed
1863 by letters, numbers, `-' or `_'.
1865 If REPLACE is a string, the tag will simply be appended to create the link.
1866 If the string contains \"%s\", the tag will be inserted there. If the string
1867 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1868 at that point (see the function `url-hexify-string'). If the string contains
1869 the specifier \"%(my-function)\", then the custom function `my-function' will
1870 be invoked: this function takes the tag as its only argument and must return
1871 a string.
1873 REPLACE may also be a function that will be called with the tag as the
1874 only argument to create the link, which should be returned as a string.
1876 See the manual for examples."
1877 :group 'org-link
1878 :type '(repeat
1879 (cons
1880 (string :tag "Protocol")
1881 (choice
1882 (string :tag "Format")
1883 (function)))))
1885 (defcustom org-descriptive-links t
1886 "Non-nil means Org will display descriptive links.
1887 E.g. [[http://orgmode.org][Org website]] will be displayed as
1888 \"Org Website\", hiding the link itself and just displaying its
1889 description. When set to nil, Org will display the full links
1890 literally.
1892 You can interactively set the value of this variable by calling
1893 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1894 :group 'org-link
1895 :type 'boolean)
1897 (defcustom org-link-file-path-type 'adaptive
1898 "How the path name in file links should be stored.
1899 Valid values are:
1901 relative Relative to the current directory, i.e. the directory of the file
1902 into which the link is being inserted.
1903 absolute Absolute path, if possible with ~ for home directory.
1904 noabbrev Absolute path, no abbreviation of home directory.
1905 adaptive Use relative path for files in the current directory and sub-
1906 directories of it. For other files, use an absolute path."
1907 :group 'org-link
1908 :type '(choice
1909 (const relative)
1910 (const absolute)
1911 (const noabbrev)
1912 (const adaptive)))
1914 (defvaralias 'org-activate-links 'org-highlight-links)
1915 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1916 "Types of links that should be highlighted in Org files.
1918 This is a list of symbols, each one of them leading to the
1919 highlighting of a certain link type.
1921 You can still open links that are not highlighted.
1923 In principle, it does not hurt to turn on highlighting for all
1924 link types. There may be a small gain when turning off unused
1925 link types. The types are:
1927 bracket The recommended [[link][description]] or [[link]] links with hiding.
1928 angle Links in angular brackets that may contain whitespace like
1929 <bbdb:Carsten Dominik>.
1930 plain Plain links in normal text, no whitespace, like http://google.com.
1931 radio Text that is matched by a radio target, see manual for details.
1932 tag Tag settings in a headline (link to tag search).
1933 date Time stamps (link to calendar).
1934 footnote Footnote labels.
1936 If you set this variable during an Emacs session, use `org-mode-restart'
1937 in the Org buffer so that the change takes effect."
1938 :group 'org-link
1939 :group 'org-appearance
1940 :type '(set :greedy t
1941 (const :tag "Double bracket links" bracket)
1942 (const :tag "Angular bracket links" angle)
1943 (const :tag "Plain text links" plain)
1944 (const :tag "Radio target matches" radio)
1945 (const :tag "Tags" tag)
1946 (const :tag "Timestamps" date)
1947 (const :tag "Footnotes" footnote)))
1949 (defcustom org-make-link-description-function nil
1950 "Function to use for generating link descriptions from links.
1951 When nil, the link location will be used. This function must take
1952 two parameters: the first one is the link, the second one is the
1953 description generated by `org-insert-link'. The function should
1954 return the description to use."
1955 :group 'org-link
1956 :type '(choice (const nil) (function)))
1958 (defgroup org-link-store nil
1959 "Options concerning storing links in Org mode."
1960 :tag "Org Store Link"
1961 :group 'org-link)
1963 (defcustom org-url-hexify-p t
1964 "When non-nil, hexify URL when creating a link."
1965 :type 'boolean
1966 :version "24.3"
1967 :group 'org-link-store)
1969 (defcustom org-email-link-description-format "Email %c: %.30s"
1970 "Format of the description part of a link to an email or usenet message.
1971 The following %-escapes will be replaced by corresponding information:
1973 %F full \"From\" field
1974 %f name, taken from \"From\" field, address if no name
1975 %T full \"To\" field
1976 %t first name in \"To\" field, address if no name
1977 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1978 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 %s subject
1980 %d date
1981 %m message-id.
1983 You may use normal field width specification between the % and the letter.
1984 This is for example useful to limit the length of the subject.
1986 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1987 :group 'org-link-store
1988 :type 'string)
1990 (defcustom org-from-is-user-regexp
1991 (let (r1 r2)
1992 (when (and user-mail-address (not (string= user-mail-address "")))
1993 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1994 (when (and user-full-name (not (string= user-full-name "")))
1995 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1996 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1997 "Regexp matched against the \"From:\" header of an email or usenet message.
1998 It should match if the message is from the user him/herself."
1999 :group 'org-link-store
2000 :type 'regexp)
2002 (defcustom org-context-in-file-links t
2003 "Non-nil means file links from `org-store-link' contain context.
2004 \\<org-mode-map>
2005 A search string will be added to the file name with :: as separator
2006 and used to find the context when the link is activated by the command
2007 `org-open-at-point'. When this option is t, the entire active region
2008 will be placed in the search string of the file link. If set to a
2009 positive integer, only the first n lines of context will be stored.
2011 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2012 \\[org-store-link]')
2013 negates this setting for the duration of the command."
2014 :group 'org-link-store
2015 :type '(choice boolean integer))
2017 (defcustom org-keep-stored-link-after-insertion nil
2018 "Non-nil means keep link in list for entire session.
2019 \\<org-mode-map>
2020 The command `org-store-link' adds a link pointing to the current
2021 location to an internal list. These links accumulate during a session.
2022 The command `org-insert-link' can be used to insert links into any
2023 Org file (offering completion for all stored links).
2025 When this option is nil, every link which has been inserted once using
2026 `\\[org-insert-link]' will be removed from the list, to make completing the \
2027 unused
2028 links more efficient."
2029 :group 'org-link-store
2030 :type 'boolean)
2032 (defgroup org-link-follow nil
2033 "Options concerning following links in Org mode."
2034 :tag "Org Follow Link"
2035 :group 'org-link)
2037 (defcustom org-link-translation-function nil
2038 "Function to translate links with different syntax to Org syntax.
2039 This can be used to translate links created for example by the Planner
2040 or emacs-wiki packages to Org syntax.
2041 The function must accept two parameters, a TYPE containing the link
2042 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2043 which is everything after the link protocol. It should return a cons
2044 with possibly modified values of type and path.
2045 Org contains a function for this, so if you set this variable to
2046 `org-translate-link-from-planner', you should be able follow many
2047 links created by planner."
2048 :group 'org-link-follow
2049 :type '(choice (const nil) (function)))
2051 (defcustom org-follow-link-hook nil
2052 "Hook that is run after a link has been followed."
2053 :group 'org-link-follow
2054 :type 'hook)
2056 (defcustom org-tab-follows-link nil
2057 "Non-nil means on links TAB will follow the link.
2058 Needs to be set before org.el is loaded.
2059 This really should not be used, it does not make sense, and the
2060 implementation is bad."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-return-follows-link nil
2065 "Non-nil means on links RET will follow the link.
2066 In tables, the special behavior of RET has precedence."
2067 :group 'org-link-follow
2068 :type 'boolean)
2070 (defcustom org-mouse-1-follows-link
2071 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2072 "Non-nil means mouse-1 on a link will follow the link.
2073 A longer mouse click will still set point. Needs to be set
2074 before org.el is loaded."
2075 :group 'org-link-follow
2076 :version "24.4"
2077 :package-version '(Org . "8.3")
2078 :type '(choice
2079 (const :tag "A double click follows the link" double)
2080 (const :tag "Unconditionally follow the link with mouse-1" t)
2081 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2083 (defcustom org-mark-ring-length 4
2084 "Number of different positions to be recorded in the ring.
2085 Changing this requires a restart of Emacs to work correctly."
2086 :group 'org-link-follow
2087 :type 'integer)
2089 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2090 "Non-nil means internal fuzzy links can only match headlines.
2092 When nil, the a fuzzy link may point to a target or a named
2093 construct in the document. When set to the special value
2094 `query-to-create', offer to create a new headline when none
2095 matched.
2097 Spaces and statistics cookies are ignored during heading searches."
2098 :group 'org-link-follow
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "Use fuzzy text search" nil)
2102 (const :tag "Match only exact headline" t)
2103 (const :tag "Match exact headline or query to create it"
2104 query-to-create))
2105 :safe #'symbolp)
2107 (defcustom org-link-frame-setup
2108 '((vm . vm-visit-folder-other-frame)
2109 (vm-imap . vm-visit-imap-folder-other-frame)
2110 (gnus . org-gnus-no-new-news)
2111 (file . find-file-other-window)
2112 (wl . wl-other-frame))
2113 "Setup the frame configuration for following links.
2114 When following a link with Emacs, it may often be useful to display
2115 this link in another window or frame. This variable can be used to
2116 set this up for the different types of links.
2117 For VM, use any of
2118 `vm-visit-folder'
2119 `vm-visit-folder-other-window'
2120 `vm-visit-folder-other-frame'
2121 For Gnus, use any of
2122 `gnus'
2123 `gnus-other-frame'
2124 `org-gnus-no-new-news'
2125 For FILE, use any of
2126 `find-file'
2127 `find-file-other-window'
2128 `find-file-other-frame'
2129 For Wanderlust use any of
2130 `wl'
2131 `wl-other-frame'
2132 For the calendar, use the variable `calendar-setup'.
2133 For BBDB, it is currently only possible to display the matches in
2134 another window."
2135 :group 'org-link-follow
2136 :type '(list
2137 (cons (const vm)
2138 (choice
2139 (const vm-visit-folder)
2140 (const vm-visit-folder-other-window)
2141 (const vm-visit-folder-other-frame)))
2142 (cons (const vm-imap)
2143 (choice
2144 (const vm-visit-imap-folder)
2145 (const vm-visit-imap-folder-other-window)
2146 (const vm-visit-imap-folder-other-frame)))
2147 (cons (const gnus)
2148 (choice
2149 (const gnus)
2150 (const gnus-other-frame)
2151 (const org-gnus-no-new-news)))
2152 (cons (const file)
2153 (choice
2154 (const find-file)
2155 (const find-file-other-window)
2156 (const find-file-other-frame)))
2157 (cons (const wl)
2158 (choice
2159 (const wl)
2160 (const wl-other-frame)))))
2162 (defcustom org-display-internal-link-with-indirect-buffer nil
2163 "Non-nil means use indirect buffer to display infile links.
2164 Activating internal links (from one location in a file to another location
2165 in the same file) normally just jumps to the location. When the link is
2166 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2167 is displayed in
2168 another window. When this option is set, the other window actually displays
2169 an indirect buffer clone of the current buffer, to avoid any visibility
2170 changes to the current buffer."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-non-existing-files nil
2175 "Non-nil means `org-open-file' will open non-existing files.
2176 When nil, an error will be generated.
2177 This variable applies only to external applications because they
2178 might choke on non-existing files. If the link is to a file that
2179 will be opened in Emacs, the variable is ignored."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-directory-means-index-dot-org nil
2184 "Non-nil means a link to a directory really means to index.org.
2185 When nil, following a directory link will run dired or open a finder/explorer
2186 window on that directory."
2187 :group 'org-link-follow
2188 :type 'boolean)
2190 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2191 "Non-nil means ask for confirmation before executing shell links.
2192 Shell links can be dangerous: just think about a link
2194 [[shell:rm -rf ~/*][Google Search]]
2196 This link would show up in your Org document as \"Google Search\",
2197 but really it would remove your entire home directory.
2198 Therefore we advise against setting this variable to nil.
2199 Just change it to `y-or-n-p' if you want to confirm with a
2200 single keystroke rather than having to type \"yes\"."
2201 :group 'org-link-follow
2202 :type '(choice
2203 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2204 (const :tag "with y-or-n (faster)" y-or-n-p)
2205 (const :tag "no confirmation (dangerous)" nil)))
2206 (put 'org-confirm-shell-link-function
2207 'safe-local-variable
2208 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2210 (defcustom org-confirm-shell-link-not-regexp ""
2211 "A regexp to skip confirmation for shell links."
2212 :group 'org-link-follow
2213 :version "24.1"
2214 :type 'regexp)
2216 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2217 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2218 Elisp links can be dangerous: just think about a link
2220 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2222 This link would show up in your Org document as \"Google Search\",
2223 but really it would remove your entire home directory.
2224 Therefore we advise against setting this variable to nil.
2225 Just change it to `y-or-n-p' if you want to confirm with a
2226 single keystroke rather than having to type \"yes\"."
2227 :group 'org-link-follow
2228 :type '(choice
2229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2230 (const :tag "with y-or-n (faster)" y-or-n-p)
2231 (const :tag "no confirmation (dangerous)" nil)))
2232 (put 'org-confirm-shell-link-function
2233 'safe-local-variable
2234 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2236 (defcustom org-confirm-elisp-link-not-regexp ""
2237 "A regexp to skip confirmation for Elisp links."
2238 :group 'org-link-follow
2239 :version "24.1"
2240 :type 'regexp)
2242 (defconst org-file-apps-defaults-gnu
2243 '((remote . emacs)
2244 (system . mailcap)
2245 (t . mailcap))
2246 "Default file applications on a UNIX or GNU/Linux system.
2247 See `org-file-apps'.")
2249 (defconst org-file-apps-defaults-macosx
2250 '((remote . emacs)
2251 (system . "open %s")
2252 ("ps.gz" . "gv %s")
2253 ("eps.gz" . "gv %s")
2254 ("dvi" . "xdvi %s")
2255 ("fig" . "xfig %s")
2256 (t . "open %s"))
2257 "Default file applications on a macOS system.
2258 The system \"open\" is known as a default, but we use X11 applications
2259 for some files for which the OS does not have a good default.
2260 See `org-file-apps'.")
2262 (defconst org-file-apps-defaults-windowsnt
2263 (list '(remote . emacs)
2264 (cons 'system (lambda (file _path)
2265 (with-no-warnings (w32-shell-execute "open" file))))
2266 (cons t (lambda (file _path)
2267 (with-no-warnings (w32-shell-execute "open" file)))))
2268 "Default file applications on a Windows NT system.
2269 The system \"open\" is used for most files.
2270 See `org-file-apps'.")
2272 (defcustom org-file-apps
2273 '((auto-mode . emacs)
2274 ("\\.mm\\'" . default)
2275 ("\\.x?html?\\'" . default)
2276 ("\\.pdf\\'" . default))
2277 "External applications for opening `file:path' items in a document.
2278 \\<org-mode-map>\
2280 Org mode uses system defaults for different file types, but
2281 you can use this variable to set the application for a given file
2282 extension. The entries in this list are cons cells where the car identifies
2283 files and the cdr the corresponding command.
2285 Possible values for the file identifier are:
2287 \"string\" A string as a file identifier can be interpreted in different
2288 ways, depending on its contents:
2290 - Alphanumeric characters only:
2291 Match links with this file extension.
2292 Example: (\"pdf\" . \"evince %s\")
2293 to open PDFs with evince.
2295 - Regular expression: Match links where the
2296 filename matches the regexp. If you want to
2297 use groups here, use shy groups.
2299 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2300 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2301 to open *.html and *.xhtml with firefox.
2303 - Regular expression which contains (non-shy) groups:
2304 Match links where the whole link, including \"::\", and
2305 anything after that, matches the regexp.
2306 In a custom command string, %1, %2, etc. are replaced with
2307 the parts of the link that were matched by the groups.
2308 For backwards compatibility, if a command string is given
2309 that does not use any of the group matches, this case is
2310 handled identically to the second one (i.e. match against
2311 file name only).
2312 In a custom function, you can access the group matches with
2313 (match-string n link).
2315 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2316 \"evince -p %1 %s\")
2317 to open [[file:document.pdf::5]] with evince at page 5.
2319 `directory' Matches a directory
2320 `remote' Matches a remote file, accessible through tramp or efs.
2321 Remote files most likely should be visited through Emacs
2322 because external applications cannot handle such paths.
2323 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2324 so all files Emacs knows how to handle. Using this with
2325 command `emacs' will open most files in Emacs. Beware that this
2326 will also open html files inside Emacs, unless you add
2327 (\"html\" . default) to the list as well.
2328 `system' The system command to open files, like `open' on Windows
2329 and macOS, and mailcap under GNU/Linux. This is the command
2330 that will be selected if you call `org-open-at-point' with a
2331 double prefix argument (`\\[universal-argument] \
2332 \\[universal-argument] \\[org-open-at-point]').
2333 t Default for files not matched by any of the other options.
2335 Possible values for the command are:
2337 `emacs' The file will be visited by the current Emacs process.
2338 `default' Use the default application for this file type, which is the
2339 association for t in the list, most likely in the system-specific
2340 part. This can be used to overrule an unwanted setting in the
2341 system-specific variable.
2342 `system' Use the system command for opening files, like \"open\".
2343 This command is specified by the entry whose car is `system'.
2344 Most likely, the system-specific version of this variable
2345 does define this command, but you can overrule/replace it
2346 here.
2347 `mailcap' Use command specified in the mailcaps.
2348 string A command to be executed by a shell; %s will be replaced
2349 by the path to the file.
2350 function A Lisp function, which will be called with two arguments:
2351 the file path and the original link string, without the
2352 \"file:\" prefix.
2354 For more examples, see the system specific constants
2355 `org-file-apps-defaults-macosx'
2356 `org-file-apps-defaults-windowsnt'
2357 `org-file-apps-defaults-gnu'."
2358 :group 'org-link-follow
2359 :type '(repeat
2360 (cons (choice :value ""
2361 (string :tag "Extension")
2362 (const :tag "System command to open files" system)
2363 (const :tag "Default for unrecognized files" t)
2364 (const :tag "Remote file" remote)
2365 (const :tag "Links to a directory" directory)
2366 (const :tag "Any files that have Emacs modes"
2367 auto-mode))
2368 (choice :value ""
2369 (const :tag "Visit with Emacs" emacs)
2370 (const :tag "Use default" default)
2371 (const :tag "Use the system command" system)
2372 (string :tag "Command")
2373 (function :tag "Function")))))
2375 (defcustom org-doi-server-url "http://dx.doi.org/"
2376 "The URL of the DOI server."
2377 :type 'string
2378 :version "24.3"
2379 :group 'org-link-follow)
2381 (defgroup org-refile nil
2382 "Options concerning refiling entries in Org mode."
2383 :tag "Org Refile"
2384 :group 'org)
2386 (defcustom org-directory "~/org"
2387 "Directory with Org files.
2388 This is just a default location to look for Org files. There is no need
2389 at all to put your files into this directory. It is used in the
2390 following situations:
2392 1. When a capture template specifies a target file that is not an
2393 absolute path. The path will then be interpreted relative to
2394 `org-directory'
2395 2. When the value of variable `org-agenda-files' is a single file, any
2396 relative paths in this file will be taken as relative to
2397 `org-directory'."
2398 :group 'org-refile
2399 :group 'org-capture
2400 :type 'directory)
2402 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2403 "Default target for storing notes.
2404 Used as a fall back file for org-capture.el, for templates that
2405 do not specify a target file."
2406 :group 'org-refile
2407 :group 'org-capture
2408 :type 'file)
2410 (defcustom org-goto-interface 'outline
2411 "The default interface to be used for `org-goto'.
2412 Allowed values are:
2413 outline The interface shows an outline of the relevant file
2414 and the correct heading is found by moving through
2415 the outline or by searching with incremental search.
2416 outline-path-completion Headlines in the current buffer are offered via
2417 completion. This is the interface also used by
2418 the refile command."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Outline" outline)
2422 (const :tag "Outline-path-completion" outline-path-completion)))
2424 (defcustom org-goto-max-level 5
2425 "Maximum target level when running `org-goto' with refile interface."
2426 :group 'org-refile
2427 :type 'integer)
2429 (defcustom org-reverse-note-order nil
2430 "Non-nil means store new notes at the beginning of a file or entry.
2431 When nil, new notes will be filed to the end of a file or entry.
2432 This can also be a list with cons cells of regular expressions that
2433 are matched against file names, and values."
2434 :group 'org-capture
2435 :group 'org-refile
2436 :type '(choice
2437 (const :tag "Reverse always" t)
2438 (const :tag "Reverse never" nil)
2439 (repeat :tag "By file name regexp"
2440 (cons regexp boolean))))
2442 (defcustom org-log-refile nil
2443 "Information to record when a task is refiled.
2445 Possible values are:
2447 nil Don't add anything
2448 time Add a time stamp to the task
2449 note Prompt for a note and add it with template `org-log-note-headings'
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: nologrefile
2454 #+STARTUP: logrefile
2455 #+STARTUP: lognoterefile
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords.
2460 When bulk-refiling from the agenda, the value `note' is forbidden and
2461 will temporarily be changed to `time'."
2462 :group 'org-refile
2463 :group 'org-progress
2464 :version "24.1"
2465 :type '(choice
2466 (const :tag "No logging" nil)
2467 (const :tag "Record timestamp" time)
2468 (const :tag "Record timestamp with note." note)))
2470 (defcustom org-refile-targets nil
2471 "Targets for refiling entries with `\\[org-refile]'.
2472 This is a list of cons cells. Each cell contains:
2473 - a specification of the files to be considered, either a list of files,
2474 or a symbol whose function or variable value will be used to retrieve
2475 a file name or a list of file names. If you use `org-agenda-files' for
2476 that, all agenda files will be scanned for targets. Nil means consider
2477 headings in the current buffer.
2478 - A specification of how to find candidate refile targets. This may be
2479 any of:
2480 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2481 This tag has to be present in all target headlines, inheritance will
2482 not be considered.
2483 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2484 todo keyword.
2485 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2486 headlines that are refiling targets.
2487 - a cons cell (:level . N). Any headline of level N is considered a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2490 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2491 Note that, when `org-odd-levels-only' is set, level corresponds to
2492 order in hierarchy, not to the number of stars.
2494 Each element of this list generates a set of possible targets.
2495 The union of these sets is presented (with completion) to
2496 the user by `org-refile'.
2498 You can set the variable `org-refile-target-verify-function' to a function
2499 to verify each headline found by the simple criteria above.
2501 When this variable is nil, all top-level headlines in the current buffer
2502 are used, equivalent to the value `((nil . (:level . 1))'."
2503 :group 'org-refile
2504 :type '(repeat
2505 (cons
2506 (choice :value org-agenda-files
2507 (const :tag "All agenda files" org-agenda-files)
2508 (const :tag "Current buffer" nil)
2509 (function) (variable) (file))
2510 (choice :tag "Identify target headline by"
2511 (cons :tag "Specific tag" (const :value :tag) (string))
2512 (cons :tag "TODO keyword" (const :value :todo) (string))
2513 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2514 (cons :tag "Level number" (const :value :level) (integer))
2515 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2517 (defcustom org-refile-target-verify-function nil
2518 "Function to verify if the headline at point should be a refile target.
2519 The function will be called without arguments, with point at the
2520 beginning of the headline. It should return t and leave point
2521 where it is if the headline is a valid target for refiling.
2523 If the target should not be selected, the function must return nil.
2524 In addition to this, it may move point to a place from where the search
2525 should be continued. For example, the function may decide that the entire
2526 subtree of the current entry should be excluded and move point to the end
2527 of the subtree."
2528 :group 'org-refile
2529 :type '(choice
2530 (const nil)
2531 (function)))
2533 (defcustom org-refile-use-cache nil
2534 "Non-nil means cache refile targets to speed up the process.
2535 \\<org-mode-map>\
2536 The cache for a particular file will be updated automatically when
2537 the buffer has been killed, or when any of the marker used for flagging
2538 refile targets no longer points at a live buffer.
2539 If you have added new entries to a buffer that might themselves be targets,
2540 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2541 if you find that easier, \
2542 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2543 \\[org-refile]'."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defcustom org-refile-use-outline-path nil
2549 "Non-nil means provide refile targets as paths.
2550 So a level 3 headline will be available as level1/level2/level3.
2552 When the value is `file', also include the file name (without directory)
2553 into the path. In this case, you can also stop the completion after
2554 the file name, to get entries inserted as top level in the file.
2556 When `full-file-path', include the full file path.
2558 When `buffer-name', use the buffer name."
2559 :group 'org-refile
2560 :type '(choice
2561 (const :tag "Not" nil)
2562 (const :tag "Yes" t)
2563 (const :tag "Start with file name" file)
2564 (const :tag "Start with full file path" full-file-path)
2565 (const :tag "Start with buffer name" buffer-name)))
2567 (defcustom org-outline-path-complete-in-steps t
2568 "Non-nil means complete the outline path in hierarchical steps.
2569 When Org uses the refile interface to select an outline path (see
2570 `org-refile-use-outline-path'), the completion of the path can be
2571 done in a single go, or it can be done in steps down the headline
2572 hierarchy. Going in steps is probably the best if you do not use
2573 a special completion package like `ido' or `icicles'. However,
2574 when using these packages, going in one step can be very fast,
2575 while still showing the whole path to the entry."
2576 :group 'org-refile
2577 :type 'boolean)
2579 (defcustom org-refile-allow-creating-parent-nodes nil
2580 "Non-nil means allow the creation of new nodes as refile targets.
2581 New nodes are then created by adding \"/new node name\" to the completion
2582 of an existing node. When the value of this variable is `confirm',
2583 new node creation must be confirmed by the user (recommended).
2584 When nil, the completion must match an existing entry.
2586 Note that, if the new heading is not seen by the criteria
2587 listed in `org-refile-targets', multiple instances of the same
2588 heading would be created by trying again to file under the new
2589 heading."
2590 :group 'org-refile
2591 :type '(choice
2592 (const :tag "Never" nil)
2593 (const :tag "Always" t)
2594 (const :tag "Prompt for confirmation" confirm)))
2596 (defcustom org-refile-active-region-within-subtree nil
2597 "Non-nil means also refile active region within a subtree.
2599 By default `org-refile' doesn't allow refiling regions if they
2600 don't contain a set of subtrees, but it might be convenient to
2601 do so sometimes: in that case, the first line of the region is
2602 converted to a headline before refiling."
2603 :group 'org-refile
2604 :version "24.1"
2605 :type 'boolean)
2607 (defgroup org-todo nil
2608 "Options concerning TODO items in Org mode."
2609 :tag "Org TODO"
2610 :group 'org)
2612 (defgroup org-progress nil
2613 "Options concerning Progress logging in Org mode."
2614 :tag "Org Progress"
2615 :group 'org-time)
2617 (defvar org-todo-interpretation-widgets
2618 '((:tag "Sequence (cycling hits every state)" sequence)
2619 (:tag "Type (cycling directly to DONE)" type))
2620 "The available interpretation symbols for customizing `org-todo-keywords'.
2621 Interested libraries should add to this list.")
2623 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2624 "List of TODO entry keyword sequences and their interpretation.
2625 \\<org-mode-map>This is a list of sequences.
2627 Each sequence starts with a symbol, either `sequence' or `type',
2628 indicating if the keywords should be interpreted as a sequence of
2629 action steps, or as different types of TODO items. The first
2630 keywords are states requiring action - these states will select a headline
2631 for inclusion into the global TODO list Org produces. If one of the
2632 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2633 signify that no further action is necessary. If \"|\" is not found,
2634 the last keyword is treated as the only DONE state of the sequence.
2636 The command `\\[org-todo]' cycles an entry through these states, and one
2637 additional state where no keyword is present. For details about this
2638 cycling, see the manual.
2640 TODO keywords and interpretation can also be set on a per-file basis with
2641 the special #+SEQ_TODO and #+TYP_TODO lines.
2643 Each keyword can optionally specify a character for fast state selection
2644 \(in combination with the variable `org-use-fast-todo-selection')
2645 and specifiers for state change logging, using the same syntax that
2646 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2647 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2648 indicates to record a time stamp each time this state is selected.
2650 Each keyword may also specify if a timestamp or a note should be
2651 recorded when entering or leaving the state, by adding additional
2652 characters in the parenthesis after the keyword. This looks like this:
2653 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2654 record only the time of the state change. With X and Y being either
2655 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2656 Y when leaving the state if and only if the *target* state does not
2657 define X. You may omit any of the fast-selection key or X or /Y,
2658 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2660 For backward compatibility, this variable may also be just a list
2661 of keywords. In this case the interpretation (sequence or type) will be
2662 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2663 :group 'org-todo
2664 :group 'org-keywords
2665 :type '(choice
2666 (repeat :tag "Old syntax, just keywords"
2667 (string :tag "Keyword"))
2668 (repeat :tag "New syntax"
2669 (cons
2670 (choice
2671 :tag "Interpretation"
2672 ;;Quick and dirty way to see
2673 ;;`org-todo-interpretations'. This takes the
2674 ;;place of item arguments
2675 :convert-widget
2676 (lambda (widget)
2677 (widget-put widget
2678 :args (mapcar
2679 (lambda (x)
2680 (widget-convert
2681 (cons 'const x)))
2682 org-todo-interpretation-widgets))
2683 widget))
2684 (repeat
2685 (string :tag "Keyword"))))))
2687 (defvar-local org-todo-keywords-1 nil
2688 "All TODO and DONE keywords active in a buffer.")
2689 (defvar org-todo-keywords-for-agenda nil)
2690 (defvar org-done-keywords-for-agenda nil)
2691 (defvar org-todo-keyword-alist-for-agenda nil)
2692 (defvar org-tag-alist-for-agenda nil
2693 "Alist of all tags from all agenda files.")
2694 (defvar org-tag-groups-alist-for-agenda nil
2695 "Alist of all groups tags from all current agenda files.")
2696 (defvar-local org-tag-groups-alist nil)
2697 (defvar org-agenda-contributing-files nil)
2698 (defvar-local org-current-tag-alist nil
2699 "Alist of all tag groups in current buffer.
2700 This variable takes into consideration `org-tag-alist',
2701 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2702 (defvar-local org-not-done-keywords nil)
2703 (defvar-local org-done-keywords nil)
2704 (defvar-local org-todo-heads nil)
2705 (defvar-local org-todo-sets nil)
2706 (defvar-local org-todo-log-states nil)
2707 (defvar-local org-todo-kwd-alist nil)
2708 (defvar-local org-todo-key-alist nil)
2709 (defvar-local org-todo-key-trigger nil)
2711 (defcustom org-todo-interpretation 'sequence
2712 "Controls how TODO keywords are interpreted.
2713 This variable is in principle obsolete and is only used for
2714 backward compatibility, if the interpretation of todo keywords is
2715 not given already in `org-todo-keywords'. See that variable for
2716 more information."
2717 :group 'org-todo
2718 :group 'org-keywords
2719 :type '(choice (const sequence)
2720 (const type)))
2722 (defcustom org-use-fast-todo-selection t
2723 "\\<org-mode-map>\
2724 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2725 This variable describes if and under what circumstances the cycling
2726 mechanism for TODO keywords will be replaced by a single-key, direct
2727 selection scheme.
2729 When nil, fast selection is never used.
2731 When the symbol `prefix', it will be used when `org-todo' is called
2732 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2733 in an Org buffer, and
2734 `\\[universal-argument] t' in an agenda buffer.
2736 When t, fast selection is used by default. In this case, the prefix
2737 argument forces cycling instead.
2739 In all cases, the special interface is only used if access keys have
2740 actually been assigned by the user, i.e. if keywords in the configuration
2741 are followed by a letter in parenthesis, like TODO(t)."
2742 :group 'org-todo
2743 :type '(choice
2744 (const :tag "Never" nil)
2745 (const :tag "By default" t)
2746 (const :tag "Only with C-u C-c C-t" prefix)))
2748 (defcustom org-provide-todo-statistics t
2749 "Non-nil means update todo statistics after insert and toggle.
2750 ALL-HEADLINES means update todo statistics by including headlines
2751 with no TODO keyword as well, counting them as not done.
2752 A list of TODO keywords means the same, but skip keywords that are
2753 not in this list.
2754 When set to a list of two lists, the first list contains keywords
2755 to consider as TODO keywords, the second list contains keywords
2756 to consider as DONE keywords.
2758 When this is set, todo statistics is updated in the parent of the
2759 current entry each time a todo state is changed."
2760 :group 'org-todo
2761 :type '(choice
2762 (const :tag "Yes, only for TODO entries" t)
2763 (const :tag "Yes, including all entries" all-headlines)
2764 (repeat :tag "Yes, for TODOs in this list"
2765 (string :tag "TODO keyword"))
2766 (list :tag "Yes, for TODOs and DONEs in these lists"
2767 (repeat (string :tag "TODO keyword"))
2768 (repeat (string :tag "DONE keyword")))
2769 (other :tag "No TODO statistics" nil)))
2771 (defcustom org-hierarchical-todo-statistics t
2772 "Non-nil means TODO statistics covers just direct children.
2773 When nil, all entries in the subtree are considered.
2774 This has only an effect if `org-provide-todo-statistics' is set.
2775 To set this to nil for only a single subtree, use a COOKIE_DATA
2776 property and include the word \"recursive\" into the value."
2777 :group 'org-todo
2778 :type 'boolean)
2780 (defcustom org-after-todo-state-change-hook nil
2781 "Hook which is run after the state of a TODO item was changed.
2782 The new state (a string with a TODO keyword, or nil) is available in the
2783 Lisp variable `org-state'."
2784 :group 'org-todo
2785 :type 'hook)
2787 (defvar org-blocker-hook nil
2788 "Hook for functions that are allowed to block a state change.
2790 Functions in this hook should not modify the buffer.
2791 Each function gets as its single argument a property list,
2792 see `org-trigger-hook' for more information about this list.
2794 If any of the functions in this hook returns nil, the state change
2795 is blocked.")
2797 (defvar org-trigger-hook nil
2798 "Hook for functions that are triggered by a state change.
2800 Each function gets as its single argument a property list with at
2801 least the following elements:
2803 (:type type-of-change :position pos-at-entry-start
2804 :from old-state :to new-state)
2806 Depending on the type, more properties may be present.
2808 This mechanism is currently implemented for:
2810 TODO state changes
2811 ------------------
2812 :type todo-state-change
2813 :from previous state (keyword as a string), or nil, or a symbol
2814 `todo' or `done', to indicate the general type of state.
2815 :to new state, like in :from")
2817 (defcustom org-enforce-todo-dependencies nil
2818 "Non-nil means undone TODO entries will block switching the parent to DONE.
2819 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2820 be blocked if any prior sibling is not yet done.
2821 Finally, if the parent is blocked because of ordered siblings of its own,
2822 the child will also be blocked."
2823 :set (lambda (var val)
2824 (set var val)
2825 (if val
2826 (add-hook 'org-blocker-hook
2827 'org-block-todo-from-children-or-siblings-or-parent)
2828 (remove-hook 'org-blocker-hook
2829 'org-block-todo-from-children-or-siblings-or-parent)))
2830 :group 'org-todo
2831 :type 'boolean)
2833 (defcustom org-enforce-todo-checkbox-dependencies nil
2834 "Non-nil means unchecked boxes will block switching the parent to DONE.
2835 When this is nil, checkboxes have no influence on switching TODO states.
2836 When non-nil, you first need to check off all check boxes before the TODO
2837 entry can be switched to DONE.
2838 This variable needs to be set before org.el is loaded, and you need to
2839 restart Emacs after a change to make the change effective. The only way
2840 to change is while Emacs is running is through the customize interface."
2841 :set (lambda (var val)
2842 (set var val)
2843 (if val
2844 (add-hook 'org-blocker-hook
2845 'org-block-todo-from-checkboxes)
2846 (remove-hook 'org-blocker-hook
2847 'org-block-todo-from-checkboxes)))
2848 :group 'org-todo
2849 :type 'boolean)
2851 (defcustom org-treat-insert-todo-heading-as-state-change nil
2852 "Non-nil means inserting a TODO heading is treated as state change.
2853 So when the command `\\[org-insert-todo-heading]' is used, state change
2854 logging will apply if appropriate. When nil, the new TODO item will
2855 be inserted directly, and no logging will take place."
2856 :group 'org-todo
2857 :type 'boolean)
2859 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2860 "Non-nil means switching TODO states with S-cursor counts as state change.
2861 This is the default behavior. However, setting this to nil allows a
2862 convenient way to select a TODO state and bypass any logging associated
2863 with that."
2864 :group 'org-todo
2865 :type 'boolean)
2867 (defcustom org-todo-state-tags-triggers nil
2868 "Tag changes that should be triggered by TODO state changes.
2869 This is a list. Each entry is
2871 (state-change (tag . flag) .......)
2873 State-change can be a string with a state, and empty string to indicate the
2874 state that has no TODO keyword, or it can be one of the symbols `todo'
2875 or `done', meaning any not-done or done state, respectively."
2876 :group 'org-todo
2877 :group 'org-tags
2878 :type '(repeat
2879 (cons (choice :tag "When changing to"
2880 (const :tag "Not-done state" todo)
2881 (const :tag "Done state" done)
2882 (string :tag "State"))
2883 (repeat
2884 (cons :tag "Tag action"
2885 (string :tag "Tag")
2886 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2888 (defcustom org-log-done nil
2889 "Information to record when a task moves to the DONE state.
2891 Possible values are:
2893 nil Don't add anything, just change the keyword
2894 time Add a time stamp to the task
2895 note Prompt for a note and add it with template `org-log-note-headings'
2897 This option can also be set with on a per-file-basis with
2899 #+STARTUP: nologdone
2900 #+STARTUP: logdone
2901 #+STARTUP: lognotedone
2903 You can have local logging settings for a subtree by setting the LOGGING
2904 property to one or more of these keywords."
2905 :group 'org-todo
2906 :group 'org-progress
2907 :type '(choice
2908 (const :tag "No logging" nil)
2909 (const :tag "Record CLOSED timestamp" time)
2910 (const :tag "Record CLOSED timestamp with note." note)))
2912 ;; Normalize old uses of org-log-done.
2913 (cond
2914 ((eq org-log-done t) (setq org-log-done 'time))
2915 ((and (listp org-log-done) (memq 'done org-log-done))
2916 (setq org-log-done 'note)))
2918 (defcustom org-log-reschedule nil
2919 "Information to record when the scheduling date of a tasks is modified.
2921 Possible values are:
2923 nil Don't add anything, just change the date
2924 time Add a time stamp to the task
2925 note Prompt for a note and add it with template `org-log-note-headings'
2927 This option can also be set with on a per-file-basis with
2929 #+STARTUP: nologreschedule
2930 #+STARTUP: logreschedule
2931 #+STARTUP: lognotereschedule"
2932 :group 'org-todo
2933 :group 'org-progress
2934 :type '(choice
2935 (const :tag "No logging" nil)
2936 (const :tag "Record timestamp" time)
2937 (const :tag "Record timestamp with note." note)))
2939 (defcustom org-log-redeadline nil
2940 "Information to record when the deadline date of a tasks is modified.
2942 Possible values are:
2944 nil Don't add anything, just change the date
2945 time Add a time stamp to the task
2946 note Prompt for a note and add it with template `org-log-note-headings'
2948 This option can also be set with on a per-file-basis with
2950 #+STARTUP: nologredeadline
2951 #+STARTUP: logredeadline
2952 #+STARTUP: lognoteredeadline
2954 You can have local logging settings for a subtree by setting the LOGGING
2955 property to one or more of these keywords."
2956 :group 'org-todo
2957 :group 'org-progress
2958 :type '(choice
2959 (const :tag "No logging" nil)
2960 (const :tag "Record timestamp" time)
2961 (const :tag "Record timestamp with note." note)))
2963 (defcustom org-log-note-clock-out nil
2964 "Non-nil means record a note when clocking out of an item.
2965 This can also be configured on a per-file basis by adding one of
2966 the following lines anywhere in the buffer:
2968 #+STARTUP: lognoteclock-out
2969 #+STARTUP: nolognoteclock-out"
2970 :group 'org-todo
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-done-with-time t
2975 "Non-nil means the CLOSED time stamp will contain date and time.
2976 When nil, only the date will be recorded."
2977 :group 'org-progress
2978 :type 'boolean)
2980 (defcustom org-log-note-headings
2981 '((done . "CLOSING NOTE %t")
2982 (state . "State %-12s from %-12S %t")
2983 (note . "Note taken on %t")
2984 (reschedule . "Rescheduled from %S on %t")
2985 (delschedule . "Not scheduled, was %S on %t")
2986 (redeadline . "New deadline from %S on %t")
2987 (deldeadline . "Removed deadline, was %S on %t")
2988 (refile . "Refiled on %t")
2989 (clock-out . ""))
2990 "Headings for notes added to entries.
2992 The value is an alist, with the car being a symbol indicating the
2993 note context, and the cdr is the heading to be used. The heading
2994 may also be the empty string. The following placeholders can be
2995 used:
2997 %t a time stamp.
2998 %T an active time stamp instead the default inactive one
2999 %d a short-format time stamp.
3000 %D an active short-format time stamp.
3001 %s the new TODO state or time stamp (inactive), in double quotes.
3002 %S the old TODO state or time stamp (inactive), in double quotes.
3003 %u the user name.
3004 %U full user name.
3006 In fact, it is not a good idea to change the `state' entry,
3007 because Agenda Log mode depends on the format of these entries."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type '(list :greedy t
3011 (cons (const :tag "Heading when closing an item" done) string)
3012 (cons (const :tag
3013 "Heading when changing todo state (todo sequence only)"
3014 state) string)
3015 (cons (const :tag "Heading when just taking a note" note) string)
3016 (cons (const :tag "Heading when rescheduling" reschedule) string)
3017 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3018 (cons (const :tag "Heading when changing deadline" redeadline) string)
3019 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3020 (cons (const :tag "Heading when refiling" refile) string)
3021 (cons (const :tag "Heading when clocking out" clock-out) string)))
3023 (unless (assq 'note org-log-note-headings)
3024 (push '(note . "%t") org-log-note-headings))
3026 (defcustom org-log-into-drawer nil
3027 "Non-nil means insert state change notes and time stamps into a drawer.
3028 When nil, state changes notes will be inserted after the headline and
3029 any scheduling and clock lines, but not inside a drawer.
3031 The value of this variable should be the name of the drawer to use.
3032 LOGBOOK is proposed as the default drawer for this purpose, you can
3033 also set this to a string to define the drawer of your choice.
3035 A value of t is also allowed, representing \"LOGBOOK\".
3037 A value of t or nil can also be set with on a per-file-basis with
3039 #+STARTUP: logdrawer
3040 #+STARTUP: nologdrawer
3042 If this variable is set, `org-log-state-notes-insert-after-drawers'
3043 will be ignored.
3045 You can set the property LOG_INTO_DRAWER to overrule this setting for
3046 a subtree.
3048 Do not check directly this variable in a Lisp program. Call
3049 function `org-log-into-drawer' instead."
3050 :group 'org-todo
3051 :group 'org-progress
3052 :type '(choice
3053 (const :tag "Not into a drawer" nil)
3054 (const :tag "LOGBOOK" t)
3055 (string :tag "Other")))
3057 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3059 (defun org-log-into-drawer ()
3060 "Name of the log drawer, as a string, or nil.
3061 This is the value of `org-log-into-drawer'. However, if the
3062 current entry has or inherits a LOG_INTO_DRAWER property, it will
3063 be used instead of the default value."
3064 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3065 (cond ((equal p "nil") nil)
3066 ((equal p "t") "LOGBOOK")
3067 ((stringp p) p)
3068 (p "LOGBOOK")
3069 ((stringp org-log-into-drawer) org-log-into-drawer)
3070 (org-log-into-drawer "LOGBOOK"))))
3072 (defcustom org-log-state-notes-insert-after-drawers nil
3073 "Non-nil means insert state change notes after any drawers in entry.
3074 Only the drawers that *immediately* follow the headline and the
3075 deadline/scheduled line are skipped.
3076 When nil, insert notes right after the heading and perhaps the line
3077 with deadline/scheduling if present.
3079 This variable will have no effect if `org-log-into-drawer' is
3080 set."
3081 :group 'org-todo
3082 :group 'org-progress
3083 :type 'boolean)
3085 (defcustom org-log-states-order-reversed t
3086 "Non-nil means the latest state note will be directly after heading.
3087 When nil, the state change notes will be ordered according to time.
3089 This option can also be set with on a per-file-basis with
3091 #+STARTUP: logstatesreversed
3092 #+STARTUP: nologstatesreversed"
3093 :group 'org-todo
3094 :group 'org-progress
3095 :type 'boolean)
3097 (defcustom org-todo-repeat-to-state nil
3098 "The TODO state to which a repeater should return the repeating task.
3099 By default this is the first task in a TODO sequence, or the previous state
3100 in a TODO_TYP set. But you can specify another task here.
3101 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3102 :group 'org-todo
3103 :version "24.1"
3104 :type '(choice (const :tag "Head of sequence" nil)
3105 (string :tag "Specific state")))
3107 (defcustom org-log-repeat 'time
3108 "Non-nil means record moving through the DONE state when triggering repeat.
3109 An auto-repeating task is immediately switched back to TODO when
3110 marked DONE. If you are not logging state changes (by adding \"@\"
3111 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3112 record a closing note, there will be no record of the task moving
3113 through DONE. This variable forces taking a note anyway.
3115 nil Don't force a record
3116 time Record a time stamp
3117 note Prompt for a note and add it with template `org-log-note-headings'
3119 This option can also be set with on a per-file-basis with
3121 #+STARTUP: nologrepeat
3122 #+STARTUP: logrepeat
3123 #+STARTUP: lognoterepeat
3125 You can have local logging settings for a subtree by setting the LOGGING
3126 property to one or more of these keywords."
3127 :group 'org-todo
3128 :group 'org-progress
3129 :type '(choice
3130 (const :tag "Don't force a record" nil)
3131 (const :tag "Force recording the DONE state" time)
3132 (const :tag "Force recording a note with the DONE state" note)))
3135 (defgroup org-priorities nil
3136 "Priorities in Org mode."
3137 :tag "Org Priorities"
3138 :group 'org-todo)
3140 (defcustom org-enable-priority-commands t
3141 "Non-nil means priority commands are active.
3142 When nil, these commands will be disabled, so that you never accidentally
3143 set a priority."
3144 :group 'org-priorities
3145 :type 'boolean)
3147 (defcustom org-highest-priority ?A
3148 "The highest priority of TODO items. A character like ?A, ?B etc.
3149 Must have a smaller ASCII number than `org-lowest-priority'."
3150 :group 'org-priorities
3151 :type 'character)
3153 (defcustom org-lowest-priority ?C
3154 "The lowest priority of TODO items. A character like ?A, ?B etc.
3155 Must have a larger ASCII number than `org-highest-priority'."
3156 :group 'org-priorities
3157 :type 'character)
3159 (defcustom org-default-priority ?B
3160 "The default priority of TODO items.
3161 This is the priority an item gets if no explicit priority is given.
3162 When starting to cycle on an empty priority the first step in the cycle
3163 depends on `org-priority-start-cycle-with-default'. The resulting first
3164 step priority must not exceed the range from `org-highest-priority' to
3165 `org-lowest-priority' which means that `org-default-priority' has to be
3166 in this range exclusive or inclusive the range boundaries. Else the
3167 first step refuses to set the default and the second will fall back
3168 to (depending on the command used) the highest or lowest priority."
3169 :group 'org-priorities
3170 :type 'character)
3172 (defcustom org-priority-start-cycle-with-default t
3173 "Non-nil means start with default priority when starting to cycle.
3174 When this is nil, the first step in the cycle will be (depending on the
3175 command used) one higher or lower than the default priority.
3176 See also `org-default-priority'."
3177 :group 'org-priorities
3178 :type 'boolean)
3180 (defcustom org-get-priority-function nil
3181 "Function to extract the priority from a string.
3182 The string is normally the headline. If this is nil Org computes the
3183 priority from the priority cookie like [#A] in the headline. It returns
3184 an integer, increasing by 1000 for each priority level.
3185 The user can set a different function here, which should take a string
3186 as an argument and return the numeric priority."
3187 :group 'org-priorities
3188 :version "24.1"
3189 :type '(choice
3190 (const nil)
3191 (function)))
3193 (defgroup org-time nil
3194 "Options concerning time stamps and deadlines in Org mode."
3195 :tag "Org Time"
3196 :group 'org)
3198 (defcustom org-time-stamp-rounding-minutes '(0 5)
3199 "Number of minutes to round time stamps to.
3200 \\<org-mode-map>\
3201 These are two values, the first applies when first creating a time stamp.
3202 The second applies when changing it with the commands `S-up' and `S-down'.
3203 When changing the time stamp, this means that it will change in steps
3204 of N minutes, as given by the second value.
3206 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3207 numbers should be factors of 60, so for example 5, 10, 15.
3209 When this is larger than 1, you can still force an exact time stamp by using
3210 a double prefix argument to a time stamp command like \
3211 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3212 and by using a prefix arg to `S-up/down' to specify the exact number
3213 of minutes to shift."
3214 :group 'org-time
3215 :get (lambda (var) ; Make sure both elements are there
3216 (if (integerp (default-value var))
3217 (list (default-value var) 5)
3218 (default-value var)))
3219 :type '(list
3220 (integer :tag "when inserting times")
3221 (integer :tag "when modifying times")))
3223 ;; Normalize old customizations of this variable.
3224 (when (integerp org-time-stamp-rounding-minutes)
3225 (setq org-time-stamp-rounding-minutes
3226 (list org-time-stamp-rounding-minutes
3227 org-time-stamp-rounding-minutes)))
3229 (defcustom org-display-custom-times nil
3230 "Non-nil means overlay custom formats over all time stamps.
3231 The formats are defined through the variable `org-time-stamp-custom-formats'.
3232 To turn this on on a per-file basis, insert anywhere in the file:
3233 #+STARTUP: customtime"
3234 :group 'org-time
3235 :set 'set-default
3236 :type 'sexp)
3237 (make-variable-buffer-local 'org-display-custom-times)
3239 (defcustom org-time-stamp-custom-formats
3240 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3241 "Custom formats for time stamps. See `format-time-string' for the syntax.
3242 These are overlaid over the default ISO format if the variable
3243 `org-display-custom-times' is set. Time like %H:%M should be at the
3244 end of the second format. The custom formats are also honored by export
3245 commands, if custom time display is turned on at the time of export."
3246 :group 'org-time
3247 :type 'sexp)
3249 (defun org-time-stamp-format (&optional long inactive)
3250 "Get the right format for a time string."
3251 (let ((f (if long (cdr org-time-stamp-formats)
3252 (car org-time-stamp-formats))))
3253 (if inactive
3254 (concat "[" (substring f 1 -1) "]")
3255 f)))
3257 (defcustom org-deadline-warning-days 14
3258 "Number of days before expiration during which a deadline becomes active.
3259 This variable governs the display in sparse trees and in the agenda.
3260 When 0 or negative, it means use this number (the absolute value of it)
3261 even if a deadline has a different individual lead time specified.
3263 Custom commands can set this variable in the options section."
3264 :group 'org-time
3265 :group 'org-agenda-daily/weekly
3266 :type 'integer)
3268 (defcustom org-scheduled-delay-days 0
3269 "Number of days before a scheduled item becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 The default value (i.e. 0) means: don't delay scheduled item.
3272 When negative, it means use this number (the absolute value of it)
3273 even if a scheduled item has a different individual delay time
3274 specified.
3276 Custom commands can set this variable in the options section."
3277 :group 'org-time
3278 :group 'org-agenda-daily/weekly
3279 :version "24.4"
3280 :package-version '(Org . "8.0")
3281 :type 'integer)
3283 (defcustom org-read-date-prefer-future t
3284 "Non-nil means assume future for incomplete date input from user.
3285 This affects the following situations:
3286 1. The user gives a month but not a year.
3287 For example, if it is April and you enter \"feb 2\", this will be read
3288 as Feb 2, *next* year. \"May 5\", however, will be this year.
3289 2. The user gives a day, but no month.
3290 For example, if today is the 15th, and you enter \"3\", Org will read
3291 this as the third of *next* month. However, if you enter \"17\",
3292 it will be considered as *this* month.
3294 If you set this variable to the symbol `time', then also the following
3295 will work:
3297 3. If the user gives a time.
3298 If the time is before now, it will be interpreted as tomorrow.
3300 Currently none of this works for ISO week specifications.
3302 When this option is nil, the current day, month and year will always be
3303 used as defaults.
3305 See also `org-agenda-jump-prefer-future'."
3306 :group 'org-time
3307 :type '(choice
3308 (const :tag "Never" nil)
3309 (const :tag "Check month and day" t)
3310 (const :tag "Check month, day, and time" time)))
3312 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3313 "Should the agenda jump command prefer the future for incomplete dates?
3314 The default is to do the same as configured in `org-read-date-prefer-future'.
3315 But you can also set a deviating value here.
3316 This may t or nil, or the symbol `org-read-date-prefer-future'."
3317 :group 'org-agenda
3318 :group 'org-time
3319 :version "24.1"
3320 :type '(choice
3321 (const :tag "Use org-read-date-prefer-future"
3322 org-read-date-prefer-future)
3323 (const :tag "Never" nil)
3324 (const :tag "Always" t)))
3326 (defcustom org-read-date-force-compatible-dates t
3327 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3329 Depending on the system Emacs is running on, certain dates cannot
3330 be represented with the type used internally to represent time.
3331 Dates between 1970-1-1 and 2038-1-1 can always be represented
3332 correctly. Some systems allow for earlier dates, some for later,
3333 some for both. One way to find out it to insert any date into an
3334 Org buffer, putting the cursor on the year and hitting S-up and
3335 S-down to test the range.
3337 When this variable is set to t, the date/time prompt will not let
3338 you specify dates outside the 1970-2037 range, so it is certain that
3339 these dates will work in whatever version of Emacs you are
3340 running, and also that you can move a file from one Emacs implementation
3341 to another. WHenever Org is forcing the year for you, it will display
3342 a message and beep.
3344 When this variable is nil, Org will check if the date is
3345 representable in the specific Emacs implementation you are using.
3346 If not, it will force a year, usually the current year, and beep
3347 to remind you. Currently this setting is not recommended because
3348 the likelihood that you will open your Org files in an Emacs that
3349 has limited date range is not negligible.
3351 A workaround for this problem is to use diary sexp dates for time
3352 stamps outside of this range."
3353 :group 'org-time
3354 :version "24.1"
3355 :type 'boolean)
3357 (defcustom org-read-date-display-live t
3358 "Non-nil means display current interpretation of date prompt live.
3359 This display will be in an overlay, in the minibuffer."
3360 :group 'org-time
3361 :type 'boolean)
3363 (defcustom org-read-date-popup-calendar t
3364 "Non-nil means pop up a calendar when prompting for a date.
3365 In the calendar, the date can be selected with mouse-1. However, the
3366 minibuffer will also be active, and you can simply enter the date as well.
3367 When nil, only the minibuffer will be available."
3368 :group 'org-time
3369 :type 'boolean)
3370 (defvaralias 'org-popup-calendar-for-date-prompt
3371 'org-read-date-popup-calendar)
3373 (defcustom org-extend-today-until 0
3374 "The hour when your day really ends. Must be an integer.
3375 This has influence for the following applications:
3376 - When switching the agenda to \"today\". It it is still earlier than
3377 the time given here, the day recognized as TODAY is actually yesterday.
3378 - When a date is read from the user and it is still before the time given
3379 here, the current date and time will be assumed to be yesterday, 23:59.
3380 Also, timestamps inserted in capture templates follow this rule.
3382 IMPORTANT: This is a feature whose implementation is and likely will
3383 remain incomplete. Really, it is only here because past midnight seems to
3384 be the favorite working time of John Wiegley :-)"
3385 :group 'org-time
3386 :type 'integer)
3388 (defcustom org-use-effective-time nil
3389 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3390 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3391 \"effective time\" of any timestamps between midnight and 8am will be
3392 23:59 of the previous day."
3393 :group 'org-time
3394 :version "24.1"
3395 :type 'boolean)
3397 (defcustom org-use-last-clock-out-time-as-effective-time nil
3398 "When non-nil, use the last clock out time for `org-todo'.
3399 Note that this option has precedence over the combined use of
3400 `org-use-effective-time' and `org-extend-today-until'."
3401 :group 'org-time
3402 :version "24.4"
3403 :package-version '(Org . "8.0")
3404 :type 'boolean)
3406 (defcustom org-edit-timestamp-down-means-later nil
3407 "Non-nil means S-down will increase the time in a time stamp.
3408 When nil, S-up will increase."
3409 :group 'org-time
3410 :type 'boolean)
3412 (defcustom org-calendar-follow-timestamp-change t
3413 "Non-nil means make the calendar window follow timestamp changes.
3414 When a timestamp is modified and the calendar window is visible, it will be
3415 moved to the new date."
3416 :group 'org-time
3417 :type 'boolean)
3419 (defgroup org-tags nil
3420 "Options concerning tags in Org mode."
3421 :tag "Org Tags"
3422 :group 'org)
3424 (defcustom org-tag-alist nil
3425 "Default tags available in Org files.
3427 The value of this variable is an alist. Associations either:
3429 (TAG)
3430 (TAG . SELECT)
3431 (SPECIAL)
3433 where TAG is a tag as a string, SELECT is character, used to
3434 select that tag through the fast tag selection interface, and
3435 SPECIAL is one of the following keywords: `:startgroup',
3436 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3437 `:newline'. These keywords are used to define a hierarchy of
3438 tags. See manual for details.
3440 When this variable is nil, Org mode bases tag input on what is
3441 already in the buffer. The value can be overridden locally by
3442 using a TAGS keyword, e.g.,
3444 #+TAGS: tag1 tag2
3446 See also `org-tag-persistent-alist' to sidestep this behavior."
3447 :group 'org-tags
3448 :type '(repeat
3449 (choice
3450 (cons (string :tag "Tag name")
3451 (character :tag "Access char"))
3452 (const :tag "Start radio group" (:startgroup))
3453 (const :tag "Start tag group, non distinct" (:startgrouptag))
3454 (const :tag "Group tags delimiter" (:grouptags))
3455 (const :tag "End radio group" (:endgroup))
3456 (const :tag "End tag group, non distinct" (:endgrouptag))
3457 (const :tag "New line" (:newline)))))
3459 (defcustom org-tag-persistent-alist nil
3460 "Tags always available in Org files.
3462 The value of this variable is an alist. Associations either:
3464 (TAG)
3465 (TAG . SELECT)
3466 (SPECIAL)
3468 where TAG is a tag as a string, SELECT is a character, used to
3469 select that tag through the fast tag selection interface, and
3470 SPECIAL is one of the following keywords: `:startgroup',
3471 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3472 `:newline'. These keywords are used to define a hierarchy of
3473 tags. See manual for details.
3475 Unlike to `org-tag-alist', tags defined in this variable do not
3476 depend on a local TAGS keyword. Instead, to disable these tags
3477 on a per-file basis, insert anywhere in the file:
3479 #+STARTUP: noptag"
3480 :group 'org-tags
3481 :type '(repeat
3482 (choice
3483 (cons (string :tag "Tag name")
3484 (character :tag "Access char"))
3485 (const :tag "Start radio group" (:startgroup))
3486 (const :tag "Start tag group, non distinct" (:startgrouptag))
3487 (const :tag "Group tags delimiter" (:grouptags))
3488 (const :tag "End radio group" (:endgroup))
3489 (const :tag "End tag group, non distinct" (:endgrouptag))
3490 (const :tag "New line" (:newline)))))
3492 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3493 "If non-nil, always offer completion for all tags of all agenda files.
3494 Instead of customizing this variable directly, you might want to
3495 set it locally for capture buffers, because there no list of
3496 tags in that file can be created dynamically (there are none).
3498 (add-hook \\='org-capture-mode-hook
3499 (lambda ()
3500 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3501 :group 'org-tags
3502 :version "24.1"
3503 :type 'boolean)
3505 (defvar org-file-tags nil
3506 "List of tags that can be inherited by all entries in the file.
3507 The tags will be inherited if the variable `org-use-tag-inheritance'
3508 says they should be.
3509 This variable is populated from #+FILETAGS lines.")
3511 (defcustom org-use-fast-tag-selection 'auto
3512 "Non-nil means use fast tag selection scheme.
3513 This is a special interface to select and deselect tags with single keys.
3514 When nil, fast selection is never used.
3515 When the symbol `auto', fast selection is used if and only if selection
3516 characters for tags have been configured, either through the variable
3517 `org-tag-alist' or through a #+TAGS line in the buffer.
3518 When t, fast selection is always used and selection keys are assigned
3519 automatically if necessary."
3520 :group 'org-tags
3521 :type '(choice
3522 (const :tag "Always" t)
3523 (const :tag "Never" nil)
3524 (const :tag "When selection characters are configured" auto)))
3526 (defcustom org-fast-tag-selection-single-key nil
3527 "Non-nil means fast tag selection exits after first change.
3528 When nil, you have to press RET to exit it.
3529 During fast tag selection, you can toggle this flag with `C-c'.
3530 This variable can also have the value `expert'. In this case, the window
3531 displaying the tags menu is not even shown, until you press C-c again."
3532 :group 'org-tags
3533 :type '(choice
3534 (const :tag "No" nil)
3535 (const :tag "Yes" t)
3536 (const :tag "Expert" expert)))
3538 (defvar org-fast-tag-selection-include-todo nil
3539 "Non-nil means fast tags selection interface will also offer TODO states.
3540 This is an undocumented feature, you should not rely on it.")
3542 (defcustom org-tags-column -77
3543 "The column to which tags should be indented in a headline.
3544 If this number is positive, it specifies the column. If it is negative,
3545 it means that the tags should be flushright to that column. For example,
3546 -80 works well for a normal 80 character screen.
3547 When 0, place tags directly after headline text, with only one space in
3548 between."
3549 :group 'org-tags
3550 :type 'integer)
3552 (defcustom org-auto-align-tags t
3553 "Non-nil keeps tags aligned when modifying headlines.
3554 Some operations (i.e. demoting) change the length of a headline and
3555 therefore shift the tags around. With this option turned on, after
3556 each such operation the tags are again aligned to `org-tags-column'."
3557 :group 'org-tags
3558 :type 'boolean)
3560 (defcustom org-use-tag-inheritance t
3561 "Non-nil means tags in levels apply also for sublevels.
3562 When nil, only the tags directly given in a specific line apply there.
3563 This may also be a list of tags that should be inherited, or a regexp that
3564 matches tags that should be inherited. Additional control is possible
3565 with the variable `org-tags-exclude-from-inheritance' which gives an
3566 explicit list of tags to be excluded from inheritance, even if the value of
3567 `org-use-tag-inheritance' would select it for inheritance.
3569 If this option is t, a match early-on in a tree can lead to a large
3570 number of matches in the subtree when constructing the agenda or creating
3571 a sparse tree. If you only want to see the first match in a tree during
3572 a search, check out the variable `org-tags-match-list-sublevels'."
3573 :group 'org-tags
3574 :type '(choice
3575 (const :tag "Not" nil)
3576 (const :tag "Always" t)
3577 (repeat :tag "Specific tags" (string :tag "Tag"))
3578 (regexp :tag "Tags matched by regexp")))
3580 (defcustom org-tags-exclude-from-inheritance nil
3581 "List of tags that should never be inherited.
3582 This is a way to exclude a few tags from inheritance. For way to do
3583 the opposite, to actively allow inheritance for selected tags,
3584 see the variable `org-use-tag-inheritance'."
3585 :group 'org-tags
3586 :type '(repeat (string :tag "Tag")))
3588 (defun org-tag-inherit-p (tag)
3589 "Check if TAG is one that should be inherited."
3590 (cond
3591 ((member tag org-tags-exclude-from-inheritance) nil)
3592 ((eq org-use-tag-inheritance t) t)
3593 ((not org-use-tag-inheritance) nil)
3594 ((stringp org-use-tag-inheritance)
3595 (string-match org-use-tag-inheritance tag))
3596 ((listp org-use-tag-inheritance)
3597 (member tag org-use-tag-inheritance))
3598 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3600 (defcustom org-tags-match-list-sublevels t
3601 "Non-nil means list also sublevels of headlines matching a search.
3602 This variable applies to tags/property searches, and also to stuck
3603 projects because this search is based on a tags match as well.
3605 When set to the symbol `indented', sublevels are indented with
3606 leading dots.
3608 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3609 the sublevels of a headline matching a tag search often also match
3610 the same search. Listing all of them can create very long lists.
3611 Setting this variable to nil causes subtrees of a match to be skipped.
3613 This variable is semi-obsolete and probably should always be true. It
3614 is better to limit inheritance to certain tags using the variables
3615 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3616 :group 'org-tags
3617 :type '(choice
3618 (const :tag "No, don't list them" nil)
3619 (const :tag "Yes, do list them" t)
3620 (const :tag "List them, indented with leading dots" indented)))
3622 (defcustom org-tags-sort-function nil
3623 "When set, tags are sorted using this function as a comparator."
3624 :group 'org-tags
3625 :type '(choice
3626 (const :tag "No sorting" nil)
3627 (const :tag "Alphabetical" string<)
3628 (const :tag "Reverse alphabetical" string>)
3629 (function :tag "Custom function" nil)))
3631 (defvar org-tags-history nil
3632 "History of minibuffer reads for tags.")
3633 (defvar org-last-tags-completion-table nil
3634 "The last used completion table for tags.")
3635 (defvar org-after-tags-change-hook nil
3636 "Hook that is run after the tags in a line have changed.")
3638 (defgroup org-properties nil
3639 "Options concerning properties in Org mode."
3640 :tag "Org Properties"
3641 :group 'org)
3643 (defcustom org-property-format "%-10s %s"
3644 "How property key/value pairs should be formatted by `indent-line'.
3645 When `indent-line' hits a property definition, it will format the line
3646 according to this format, mainly to make sure that the values are
3647 lined-up with respect to each other."
3648 :group 'org-properties
3649 :type 'string)
3651 (defcustom org-properties-postprocess-alist nil
3652 "Alist of properties and functions to adjust inserted values.
3653 Elements of this alist must be of the form
3655 ([string] [function])
3657 where [string] must be a property name and [function] must be a
3658 lambda expression: this lambda expression must take one argument,
3659 the value to adjust, and return the new value as a string.
3661 For example, this element will allow the property \"Remaining\"
3662 to be updated wrt the relation between the \"Effort\" property
3663 and the clock summary:
3665 ((\"Remaining\" (lambda(value)
3666 (let ((clocksum (org-clock-sum-current-item))
3667 (effort (org-duration-to-minutes
3668 (org-entry-get (point) \"Effort\"))))
3669 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3670 :group 'org-properties
3671 :version "24.1"
3672 :type '(alist :key-type (string :tag "Property")
3673 :value-type (function :tag "Function")))
3675 (defcustom org-use-property-inheritance nil
3676 "Non-nil means properties apply also for sublevels.
3678 This setting is chiefly used during property searches. Turning it on can
3679 cause significant overhead when doing a search, which is why it is not
3680 on by default.
3682 When nil, only the properties directly given in the current entry count.
3683 When t, every property is inherited. The value may also be a list of
3684 properties that should have inheritance, or a regular expression matching
3685 properties that should be inherited.
3687 However, note that some special properties use inheritance under special
3688 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3689 and the properties ending in \"_ALL\" when they are used as descriptor
3690 for valid values of a property.
3692 Note for programmers:
3693 When querying an entry with `org-entry-get', you can control if inheritance
3694 should be used. By default, `org-entry-get' looks only at the local
3695 properties. You can request inheritance by setting the inherit argument
3696 to t (to force inheritance) or to `selective' (to respect the setting
3697 in this variable)."
3698 :group 'org-properties
3699 :type '(choice
3700 (const :tag "Not" nil)
3701 (const :tag "Always" t)
3702 (repeat :tag "Specific properties" (string :tag "Property"))
3703 (regexp :tag "Properties matched by regexp")))
3705 (defun org-property-inherit-p (property)
3706 "Return a non-nil value if PROPERTY should be inherited."
3707 (cond
3708 ((eq org-use-property-inheritance t) t)
3709 ((not org-use-property-inheritance) nil)
3710 ((stringp org-use-property-inheritance)
3711 (string-match org-use-property-inheritance property))
3712 ((listp org-use-property-inheritance)
3713 (member-ignore-case property org-use-property-inheritance))
3714 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3716 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3717 "The default column format, if no other format has been defined.
3718 This variable can be set on the per-file basis by inserting a line
3720 #+COLUMNS: %25ITEM ....."
3721 :group 'org-properties
3722 :type 'string)
3724 (defcustom org-columns-ellipses ".."
3725 "The ellipses to be used when a field in column view is truncated.
3726 When this is the empty string, as many characters as possible are shown,
3727 but then there will be no visual indication that the field has been truncated.
3728 When this is a string of length N, the last N characters of a truncated
3729 field are replaced by this string. If the column is narrower than the
3730 ellipses string, only part of the ellipses string will be shown."
3731 :group 'org-properties
3732 :type 'string)
3734 (defconst org-global-properties-fixed
3735 '(("VISIBILITY_ALL" . "folded children content all")
3736 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3737 "List of property/value pairs that can be inherited by any entry.
3739 These are fixed values, for the preset properties. The user variable
3740 that can be used to add to this list is `org-global-properties'.
3742 The entries in this list are cons cells where the car is a property
3743 name and cdr is a string with the value. If the value represents
3744 multiple items like an \"_ALL\" property, separate the items by
3745 spaces.")
3747 (defcustom org-global-properties nil
3748 "List of property/value pairs that can be inherited by any entry.
3750 This list will be combined with the constant `org-global-properties-fixed'.
3752 The entries in this list are cons cells where the car is a property
3753 name and cdr is a string with the value.
3755 You can set buffer-local values for the same purpose in the variable
3756 `org-file-properties' this by adding lines like
3758 #+PROPERTY: NAME VALUE"
3759 :group 'org-properties
3760 :type '(repeat
3761 (cons (string :tag "Property")
3762 (string :tag "Value"))))
3764 (defvar-local org-file-properties nil
3765 "List of property/value pairs that can be inherited by any entry.
3766 Valid for the current buffer.
3767 This variable is populated from #+PROPERTY lines.")
3769 (defgroup org-agenda nil
3770 "Options concerning agenda views in Org mode."
3771 :tag "Org Agenda"
3772 :group 'org)
3774 (defvar-local org-category nil
3775 "Variable used by org files to set a category for agenda display.
3776 Such files should use a file variable to set it, for example
3778 # -*- mode: org; org-category: \"ELisp\"
3780 or contain a special line
3782 #+CATEGORY: ELisp
3784 If the file does not specify a category, then file's base name
3785 is used instead.")
3786 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3788 (defcustom org-agenda-files nil
3789 "The files to be used for agenda display.
3791 If an entry is a directory, all files in that directory that are matched
3792 by `org-agenda-file-regexp' will be part of the file list.
3794 If the value of the variable is not a list but a single file name, then
3795 the list of agenda files is actually stored and maintained in that file,
3796 one agenda file per line. In this file paths can be given relative to
3797 `org-directory'. Tilde expansion and environment variable substitution
3798 are also made.
3800 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3801 and removed with `\\[org-remove-file]'."
3802 :group 'org-agenda
3803 :type '(choice
3804 (repeat :tag "List of files and directories" file)
3805 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3807 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3808 "Regular expression to match files for `org-agenda-files'.
3809 If any element in the list in that variable contains a directory instead
3810 of a normal file, all files in that directory that are matched by this
3811 regular expression will be included."
3812 :group 'org-agenda
3813 :type 'regexp)
3815 (defcustom org-agenda-text-search-extra-files nil
3816 "List of extra files to be searched by text search commands.
3817 These files will be searched in addition to the agenda files by the
3818 commands `org-search-view' (`\\[org-agenda] s') \
3819 and `org-occur-in-agenda-files'.
3820 Note that these files will only be searched for text search commands,
3821 not for the other agenda views like todo lists, tag searches or the weekly
3822 agenda. This variable is intended to list notes and possibly archive files
3823 that should also be searched by these two commands.
3824 In fact, if the first element in the list is the symbol `agenda-archives',
3825 then all archive files of all agenda files will be added to the search
3826 scope."
3827 :group 'org-agenda
3828 :type '(set :greedy t
3829 (const :tag "Agenda Archives" agenda-archives)
3830 (repeat :inline t (file))))
3832 (defvaralias 'org-agenda-multi-occur-extra-files
3833 'org-agenda-text-search-extra-files)
3835 (defcustom org-agenda-skip-unavailable-files nil
3836 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3837 A nil value means to remove them, after a query, from the list."
3838 :group 'org-agenda
3839 :type 'boolean)
3841 (defcustom org-calendar-to-agenda-key [?c]
3842 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3843 The command `org-calendar-goto-agenda' will be bound to this key. The
3844 default is the character `c' because then `c' can be used to switch back and
3845 forth between agenda and calendar."
3846 :group 'org-agenda
3847 :type 'sexp)
3849 (defcustom org-calendar-insert-diary-entry-key [?i]
3850 "The key to be installed in `calendar-mode-map' for adding diary entries.
3851 This option is irrelevant until `org-agenda-diary-file' has been configured
3852 to point to an Org file. When that is the case, the command
3853 `org-agenda-diary-entry' will be bound to the key given here, by default
3854 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3855 if you want to continue doing this, you need to change this to a different
3856 key."
3857 :group 'org-agenda
3858 :type 'sexp)
3860 (defcustom org-agenda-diary-file 'diary-file
3861 "File to which to add new entries with the `i' key in agenda and calendar.
3862 When this is the symbol `diary-file', the functionality in the Emacs
3863 calendar will be used to add entries to the `diary-file'. But when this
3864 points to a file, `org-agenda-diary-entry' will be used instead."
3865 :group 'org-agenda
3866 :type '(choice
3867 (const :tag "The standard Emacs diary file" diary-file)
3868 (file :tag "Special Org file diary entries")))
3870 (eval-after-load "calendar"
3871 '(progn
3872 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3873 'org-calendar-goto-agenda)
3874 (add-hook 'calendar-mode-hook
3875 (lambda ()
3876 (unless (eq org-agenda-diary-file 'diary-file)
3877 (define-key calendar-mode-map
3878 org-calendar-insert-diary-entry-key
3879 'org-agenda-diary-entry))))))
3881 (defgroup org-latex nil
3882 "Options for embedding LaTeX code into Org mode."
3883 :tag "Org LaTeX"
3884 :group 'org)
3886 (defcustom org-format-latex-options
3887 '(:foreground default :background default :scale 1.0
3888 :html-foreground "Black" :html-background "Transparent"
3889 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3890 "Options for creating images from LaTeX fragments.
3891 This is a property list with the following properties:
3892 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3893 `default' means use the foreground of the default face.
3894 `auto' means use the foreground from the text face.
3895 :background the background color, or \"Transparent\".
3896 `default' means use the background of the default face.
3897 `auto' means use the background from the text face.
3898 :scale a scaling factor for the size of the images, to get more pixels
3899 :html-foreground, :html-background, :html-scale
3900 the same numbers for HTML export.
3901 :matchers a list indicating which matchers should be used to
3902 find LaTeX fragments. Valid members of this list are:
3903 \"begin\" find environments
3904 \"$1\" find single characters surrounded by $.$
3905 \"$\" find math expressions surrounded by $...$
3906 \"$$\" find math expressions surrounded by $$....$$
3907 \"\\(\" find math expressions surrounded by \\(...\\)
3908 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3909 :group 'org-latex
3910 :type 'plist)
3912 (defcustom org-format-latex-signal-error t
3913 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3914 When nil, just push out a message."
3915 :group 'org-latex
3916 :version "24.1"
3917 :type 'boolean)
3919 (defcustom org-latex-to-mathml-jar-file nil
3920 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3921 Use this to specify additional executable file say a jar file.
3923 When using MathToWeb as the converter, specify the full-path to
3924 your mathtoweb.jar file."
3925 :group 'org-latex
3926 :version "24.1"
3927 :type '(choice
3928 (const :tag "None" nil)
3929 (file :tag "JAR file" :must-match t)))
3931 (defcustom org-latex-to-mathml-convert-command nil
3932 "Command to convert LaTeX fragments to MathML.
3933 Replace format-specifiers in the command as noted below and use
3934 `shell-command' to convert LaTeX to MathML.
3935 %j: Executable file in fully expanded form as specified by
3936 `org-latex-to-mathml-jar-file'.
3937 %I: Input LaTeX file in fully expanded form.
3938 %i: The latex fragment to be converted.
3939 %o: Output MathML file.
3941 This command is used by `org-create-math-formula'.
3943 When using MathToWeb as the converter, set this option to
3944 \"java -jar %j -unicode -force -df %o %I\".
3946 When using LaTeXML set this option to
3947 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3948 :group 'org-latex
3949 :version "24.1"
3950 :type '(choice
3951 (const :tag "None" nil)
3952 (string :tag "\nShell command")))
3954 (defcustom org-preview-latex-default-process 'dvipng
3955 "The default process to convert LaTeX fragments to image files.
3956 All available processes and theirs documents can be found in
3957 `org-preview-latex-process-alist', which see."
3958 :group 'org-latex
3959 :version "26.1"
3960 :package-version '(Org . "9.0")
3961 :type 'symbol)
3963 (defcustom org-preview-latex-process-alist
3964 '((dvipng
3965 :programs ("latex" "dvipng")
3966 :description "dvi > png"
3967 :message "you need to install the programs: latex and dvipng."
3968 :image-input-type "dvi"
3969 :image-output-type "png"
3970 :image-size-adjust (1.0 . 1.0)
3971 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3972 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3973 (dvisvgm
3974 :programs ("latex" "dvisvgm")
3975 :description "dvi > svg"
3976 :message "you need to install the programs: latex and dvisvgm."
3977 :use-xcolor t
3978 :image-input-type "dvi"
3979 :image-output-type "svg"
3980 :image-size-adjust (1.7 . 1.5)
3981 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3982 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3983 (imagemagick
3984 :programs ("latex" "convert")
3985 :description "pdf > png"
3986 :message "you need to install the programs: latex and imagemagick."
3987 :use-xcolor t
3988 :image-input-type "pdf"
3989 :image-output-type "png"
3990 :image-size-adjust (1.0 . 1.0)
3991 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3992 :image-converter
3993 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3994 "Definitions of external processes for LaTeX previewing.
3995 Org mode can use some external commands to generate TeX snippet's images for
3996 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3997 `org-create-formula-image' how to call them.
3999 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4000 PROPERTIES accepts the following attributes:
4002 :programs list of strings, required programs.
4003 :description string, describe the process.
4004 :message string, message it when required programs cannot be found.
4005 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4006 :image-output-type string, output file type of image converter (e.g., \"png\").
4007 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4008 deal with background and foreground color of image.
4009 Otherwise, dvipng style background and foregroud color
4010 format are generated. You may then refer to them in
4011 command options with \"%F\" and \"%B\".
4012 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4013 image size showed in buffer and the cdr element is for
4014 HTML file. This option is only useful for process
4015 developers, users should use variable
4016 `org-format-latex-options' instead.
4017 :post-clean list of strings, files matched are to be cleaned up once
4018 the image is generated. When nil, the files with \".dvi\",
4019 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4020 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4021 be cleaned up.
4022 :latex-header list of strings, the LaTeX header of the snippet file.
4023 When nil, the fallback value is used instead, which is
4024 controlled by `org-format-latex-header',
4025 `org-latex-default-packages-alist' and
4026 `org-latex-packages-alist', which see.
4027 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4028 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4029 replaced with values defined below.
4030 :image-converter list of image converter commands strings. Each of them is
4031 given to the shell and supports any of the following
4032 place-holders defined below.
4034 Place-holders used by `:image-converter' and `:latex-compiler':
4036 %f input file name
4037 %b base name of input file
4038 %o base directory of input file
4039 %O absolute output file name
4041 Place-holders only used by `:image-converter':
4043 %F foreground of image
4044 %B background of image
4045 %D dpi, which is used to adjust image size by some processing commands.
4046 %S the image size scale ratio, which is used to adjust image size by some
4047 processing commands."
4048 :group 'org-latex
4049 :version "26.1"
4050 :package-version '(Org . "9.0")
4051 :type '(alist :tag "LaTeX to image backends"
4052 :value-type (plist)))
4054 (defcustom org-preview-latex-image-directory "ltximg/"
4055 "Path to store latex preview images.
4056 A relative path here creates many directories relative to the
4057 processed org files paths. An absolute path puts all preview
4058 images at the same place."
4059 :group 'org-latex
4060 :version "26.1"
4061 :package-version '(Org . "9.0")
4062 :type 'string)
4064 (defun org-format-latex-mathml-available-p ()
4065 "Return t if `org-latex-to-mathml-convert-command' is usable."
4066 (save-match-data
4067 (when (and (boundp 'org-latex-to-mathml-convert-command)
4068 org-latex-to-mathml-convert-command)
4069 (let ((executable (car (split-string
4070 org-latex-to-mathml-convert-command))))
4071 (when (executable-find executable)
4072 (if (string-match
4073 "%j" org-latex-to-mathml-convert-command)
4074 (file-readable-p org-latex-to-mathml-jar-file)
4075 t))))))
4077 (defcustom org-format-latex-header "\\documentclass{article}
4078 \\usepackage[usenames]{color}
4079 \[PACKAGES]
4080 \[DEFAULT-PACKAGES]
4081 \\pagestyle{empty} % do not remove
4082 % The settings below are copied from fullpage.sty
4083 \\setlength{\\textwidth}{\\paperwidth}
4084 \\addtolength{\\textwidth}{-3cm}
4085 \\setlength{\\oddsidemargin}{1.5cm}
4086 \\addtolength{\\oddsidemargin}{-2.54cm}
4087 \\setlength{\\evensidemargin}{\\oddsidemargin}
4088 \\setlength{\\textheight}{\\paperheight}
4089 \\addtolength{\\textheight}{-\\headheight}
4090 \\addtolength{\\textheight}{-\\headsep}
4091 \\addtolength{\\textheight}{-\\footskip}
4092 \\addtolength{\\textheight}{-3cm}
4093 \\setlength{\\topmargin}{1.5cm}
4094 \\addtolength{\\topmargin}{-2.54cm}"
4095 "The document header used for processing LaTeX fragments.
4096 It is imperative that this header make sure that no page number
4097 appears on the page. The package defined in the variables
4098 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4099 will either replace the placeholder \"[PACKAGES]\" in this
4100 header, or they will be appended."
4101 :group 'org-latex
4102 :type 'string)
4104 (defun org-set-packages-alist (var val)
4105 "Set the packages alist and make sure it has 3 elements per entry."
4106 (set var (mapcar (lambda (x)
4107 (if (and (consp x) (= (length x) 2))
4108 (list (car x) (nth 1 x) t)
4110 val)))
4112 (defun org-get-packages-alist (var)
4113 "Get the packages alist and make sure it has 3 elements per entry."
4114 (mapcar (lambda (x)
4115 (if (and (consp x) (= (length x) 2))
4116 (list (car x) (nth 1 x) t)
4118 (default-value var)))
4120 (defcustom org-latex-default-packages-alist
4121 '(("AUTO" "inputenc" t ("pdflatex"))
4122 ("T1" "fontenc" t ("pdflatex"))
4123 ("" "graphicx" t)
4124 ("" "grffile" t)
4125 ("" "longtable" nil)
4126 ("" "wrapfig" nil)
4127 ("" "rotating" nil)
4128 ("normalem" "ulem" t)
4129 ("" "amsmath" t)
4130 ("" "textcomp" t)
4131 ("" "amssymb" t)
4132 ("" "capt-of" nil)
4133 ("" "hyperref" nil))
4134 "Alist of default packages to be inserted in the header.
4136 Change this only if one of the packages here causes an
4137 incompatibility with another package you are using.
4139 The packages in this list are needed by one part or another of
4140 Org mode to function properly:
4142 - inputenc, fontenc: for basic font and character selection
4143 - graphicx: for including images
4144 - grffile: allow periods and spaces in graphics file names
4145 - longtable: For multipage tables
4146 - wrapfig: for figure placement
4147 - rotating: for sideways figures and tables
4148 - ulem: for underline and strike-through
4149 - amsmath: for subscript and superscript and math environments
4150 - textcomp, amssymb: for various symbols used
4151 for interpreting the entities in `org-entities'. You can skip
4152 some of these packages if you don't use any of their symbols.
4153 - capt-of: for captions outside of floats
4154 - hyperref: for cross references
4156 Therefore you should not modify this variable unless you know
4157 what you are doing. The one reason to change it anyway is that
4158 you might be loading some other package that conflicts with one
4159 of the default packages. Each element is either a cell or
4160 a string.
4162 A cell is of the format
4164 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4166 If SNIPPET-FLAG is non-nil, the package also needs to be included
4167 when compiling LaTeX snippets into images for inclusion into
4168 non-LaTeX output. COMPILERS is a list of compilers that should
4169 include the package, see `org-latex-compiler'. If the document
4170 compiler is not in the list, and the list is non-nil, the package
4171 will not be inserted in the final document.
4173 A string will be inserted as-is in the header of the document."
4174 :group 'org-latex
4175 :group 'org-export-latex
4176 :set 'org-set-packages-alist
4177 :get 'org-get-packages-alist
4178 :version "26.1"
4179 :package-version '(Org . "8.3")
4180 :type '(repeat
4181 (choice
4182 (list :tag "options/package pair"
4183 (string :tag "options")
4184 (string :tag "package")
4185 (boolean :tag "Snippet"))
4186 (string :tag "A line of LaTeX"))))
4188 (defcustom org-latex-packages-alist nil
4189 "Alist of packages to be inserted in every LaTeX header.
4191 These will be inserted after `org-latex-default-packages-alist'.
4192 Each element is either a cell or a string.
4194 A cell is of the format:
4196 (\"options\" \"package\" SNIPPET-FLAG)
4198 SNIPPET-FLAG, when non-nil, indicates that this package is also
4199 needed when turning LaTeX snippets into images for inclusion into
4200 non-LaTeX output.
4202 A string will be inserted as-is in the header of the document.
4204 Make sure that you only list packages here which:
4206 - you want in every file;
4207 - do not conflict with the setup in `org-format-latex-header';
4208 - do not conflict with the default packages in
4209 `org-latex-default-packages-alist'."
4210 :group 'org-latex
4211 :group 'org-export-latex
4212 :set 'org-set-packages-alist
4213 :get 'org-get-packages-alist
4214 :type '(repeat
4215 (choice
4216 (list :tag "options/package pair"
4217 (string :tag "options")
4218 (string :tag "package")
4219 (boolean :tag "Snippet"))
4220 (string :tag "A line of LaTeX"))))
4222 (defgroup org-appearance nil
4223 "Settings for Org mode appearance."
4224 :tag "Org Appearance"
4225 :group 'org)
4227 (defcustom org-level-color-stars-only nil
4228 "Non-nil means fontify only the stars in each headline.
4229 When nil, the entire headline is fontified.
4230 Changing it requires restart of `font-lock-mode' to become effective
4231 also in regions already fontified."
4232 :group 'org-appearance
4233 :type 'boolean)
4235 (defcustom org-hide-leading-stars nil
4236 "Non-nil means hide the first N-1 stars in a headline.
4237 This works by using the face `org-hide' for these stars. This
4238 face is white for a light background, and black for a dark
4239 background. You may have to customize the face `org-hide' to
4240 make this work.
4241 Changing it requires restart of `font-lock-mode' to become effective
4242 also in regions already fontified.
4243 You may also set this on a per-file basis by adding one of the following
4244 lines to the buffer:
4246 #+STARTUP: hidestars
4247 #+STARTUP: showstars"
4248 :group 'org-appearance
4249 :type 'boolean)
4251 (defcustom org-hidden-keywords nil
4252 "List of symbols corresponding to keywords to be hidden the org buffer.
4253 For example, a value \\='(title) for this list will make the document's title
4254 appear in the buffer without the initial #+TITLE: keyword."
4255 :group 'org-appearance
4256 :version "24.1"
4257 :type '(set (const :tag "#+AUTHOR" author)
4258 (const :tag "#+DATE" date)
4259 (const :tag "#+EMAIL" email)
4260 (const :tag "#+TITLE" title)))
4262 (defcustom org-custom-properties nil
4263 "List of properties (as strings) with a special meaning.
4264 The default use of these custom properties is to let the user
4265 hide them with `org-toggle-custom-properties-visibility'."
4266 :group 'org-properties
4267 :group 'org-appearance
4268 :version "24.3"
4269 :type '(repeat (string :tag "Property Name")))
4271 (defcustom org-fontify-done-headline nil
4272 "Non-nil means change the face of a headline if it is marked DONE.
4273 Normally, only the TODO/DONE keyword indicates the state of a headline.
4274 When this is non-nil, the headline after the keyword is set to the
4275 `org-headline-done' as an additional indication."
4276 :group 'org-appearance
4277 :type 'boolean)
4279 (defcustom org-fontify-emphasized-text t
4280 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4281 Changing this variable requires a restart of Emacs to take effect."
4282 :group 'org-appearance
4283 :type 'boolean)
4285 (defcustom org-fontify-whole-heading-line nil
4286 "Non-nil means fontify the whole line for headings.
4287 This is useful when setting a background color for the
4288 org-level-* faces."
4289 :group 'org-appearance
4290 :type 'boolean)
4292 (defcustom org-highlight-latex-and-related nil
4293 "Non-nil means highlight LaTeX related syntax in the buffer.
4294 When non nil, the value should be a list containing any of the
4295 following symbols:
4296 `latex' Highlight LaTeX snippets and environments.
4297 `script' Highlight subscript and superscript.
4298 `entities' Highlight entities."
4299 :group 'org-appearance
4300 :version "24.4"
4301 :package-version '(Org . "8.0")
4302 :type '(choice
4303 (const :tag "No highlighting" nil)
4304 (set :greedy t :tag "Highlight"
4305 (const :tag "LaTeX snippets and environments" latex)
4306 (const :tag "Subscript and superscript" script)
4307 (const :tag "Entities" entities))))
4309 (defcustom org-hide-emphasis-markers nil
4310 "Non-nil mean font-lock should hide the emphasis marker characters."
4311 :group 'org-appearance
4312 :type 'boolean)
4314 (defcustom org-hide-macro-markers nil
4315 "Non-nil mean font-lock should hide the brackets marking macro calls."
4316 :group 'org-appearance
4317 :type 'boolean)
4319 (defcustom org-pretty-entities nil
4320 "Non-nil means show entities as UTF8 characters.
4321 When nil, the \\name form remains in the buffer."
4322 :group 'org-appearance
4323 :version "24.1"
4324 :type 'boolean)
4326 (defcustom org-pretty-entities-include-sub-superscripts t
4327 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4328 :group 'org-appearance
4329 :version "24.1"
4330 :type 'boolean)
4332 (defvar org-emph-re nil
4333 "Regular expression for matching emphasis.
4334 After a match, the match groups contain these elements:
4335 0 The match of the full regular expression, including the characters
4336 before and after the proper match
4337 1 The character before the proper match, or empty at beginning of line
4338 2 The proper match, including the leading and trailing markers
4339 3 The leading marker like * or /, indicating the type of highlighting
4340 4 The text between the emphasis markers, not including the markers
4341 5 The character after the match, empty at the end of a line")
4343 (defvar org-verbatim-re nil
4344 "Regular expression for matching verbatim text.")
4346 (defvar org-emphasis-regexp-components) ; defined just below
4347 (defvar org-emphasis-alist) ; defined just below
4348 (defun org-set-emph-re (var val)
4349 "Set variable and compute the emphasis regular expression."
4350 (set var val)
4351 (when (and (boundp 'org-emphasis-alist)
4352 (boundp 'org-emphasis-regexp-components)
4353 org-emphasis-alist org-emphasis-regexp-components)
4354 (pcase-let*
4355 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4356 (body (if (<= nl 0) body
4357 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4358 (template
4359 (format (concat "\\([%s]\\|^\\)" ;before markers
4360 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4361 "\\([%s]\\|$\\)") ;after markers
4362 pre border border body border post)))
4363 (setq org-emph-re (format template "*/_+"))
4364 (setq org-verbatim-re (format template "=~")))))
4366 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4367 ;; set this option proved cumbersome. See this message/thread:
4368 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4369 (defvar org-emphasis-regexp-components
4370 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4371 "Components used to build the regular expression for emphasis.
4372 This is a list with five entries. Terminology: In an emphasis string
4373 like \" *strong word* \", we call the initial space PREMATCH, the final
4374 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4375 and \"trong wor\" is the body. The different components in this variable
4376 specify what is allowed/forbidden in each part:
4378 pre Chars allowed as prematch. Beginning of line will be allowed too.
4379 post Chars allowed as postmatch. End of line will be allowed too.
4380 border The chars *forbidden* as border characters.
4381 body-regexp A regexp like \".\" to match a body character. Don't use
4382 non-shy groups here, and don't allow newline here.
4383 newline The maximum number of newlines allowed in an emphasis exp.
4385 You need to reload Org or to restart Emacs after customizing this.")
4387 (defcustom org-emphasis-alist
4388 '(("*" bold)
4389 ("/" italic)
4390 ("_" underline)
4391 ("=" org-verbatim verbatim)
4392 ("~" org-code verbatim)
4393 ("+" (:strike-through t)))
4394 "Alist of characters and faces to emphasize text.
4395 Text starting and ending with a special character will be emphasized,
4396 for example *bold*, _underlined_ and /italic/. This variable sets the
4397 marker characters and the face to be used by font-lock for highlighting
4398 in Org buffers.
4400 You need to reload Org or to restart Emacs after customizing this."
4401 :group 'org-appearance
4402 :set 'org-set-emph-re
4403 :version "24.4"
4404 :package-version '(Org . "8.0")
4405 :type '(repeat
4406 (list
4407 (string :tag "Marker character")
4408 (choice
4409 (face :tag "Font-lock-face")
4410 (plist :tag "Face property list"))
4411 (option (const verbatim)))))
4413 (defvar org-protecting-blocks '("src" "example" "export")
4414 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4415 This is needed for font-lock setup.")
4417 ;;; Functions and variables from their packages
4418 ;; Declared here to avoid compiler warnings
4419 (defvar mark-active)
4421 ;; Various packages
4422 (declare-function calc-eval "calc" (str &optional separator &rest args))
4423 (declare-function calendar-forward-day "cal-move" (arg))
4424 (declare-function calendar-goto-date "cal-move" (date))
4425 (declare-function calendar-goto-today "cal-move" ())
4426 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4427 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4428 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4429 (declare-function cdlatex-tab "ext:cdlatex" ())
4430 (declare-function dired-get-filename
4431 "dired"
4432 (&optional localp no-error-if-not-filep))
4433 (declare-function iswitchb-read-buffer
4434 "iswitchb"
4435 (prompt &optional
4436 default require-match _predicate start matches-set))
4437 (declare-function org-agenda-change-all-lines
4438 "org-agenda"
4439 (newhead hdmarker &optional fixface just-this))
4440 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4441 "org-agenda"
4442 (&optional end))
4443 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4444 (declare-function org-agenda-format-item
4445 "org-agenda"
4446 (extra txt &optional level category tags dotime
4447 remove-re habitp))
4448 (declare-function org-agenda-maybe-redo "org-agenda" ())
4449 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4450 (declare-function org-agenda-save-markers-for-cut-and-paste
4451 "org-agenda"
4452 (beg end))
4453 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4454 (declare-function org-agenda-skip "org-agenda" ())
4455 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4456 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4457 (declare-function org-indent-mode "org-indent" (&optional arg))
4458 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4459 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4460 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4461 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4462 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4463 (declare-function parse-time-string "parse-time" (string))
4464 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4466 (defvar align-mode-rules-list)
4467 (defvar calc-embedded-close-formula)
4468 (defvar calc-embedded-open-formula)
4469 (defvar calc-embedded-open-mode)
4470 (defvar font-lock-unfontify-region-function)
4471 (defvar iswitchb-temp-buflist)
4472 (defvar org-agenda-tags-todo-honor-ignore-options)
4473 (defvar remember-data-file)
4474 (defvar texmathp-why)
4476 ;;;###autoload
4477 (defun turn-on-orgtbl ()
4478 "Unconditionally turn on `orgtbl-mode'."
4479 (require 'org-table)
4480 (orgtbl-mode 1))
4482 (defun org-at-table-p (&optional table-type)
4483 "Non-nil if the cursor is inside an Org table.
4484 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4485 If `org-enable-table-editor' is nil, return nil unconditionally."
4486 (and
4487 org-enable-table-editor
4488 (save-excursion
4489 (beginning-of-line)
4490 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4491 (or (not (derived-mode-p 'org-mode))
4492 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4493 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4495 (defun org-at-table.el-p ()
4496 "Non-nil when point is at a table.el table."
4497 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4498 (let ((element (org-element-at-point)))
4499 (and (eq (org-element-type element) 'table)
4500 (eq (org-element-property :type element) 'table.el)))))
4502 (defun org-at-table-hline-p ()
4503 "Non-nil when point is inside a hline in a table.
4504 Assume point is already in a table. If `org-enable-table-editor'
4505 is nil, return nil unconditionally."
4506 (and org-enable-table-editor
4507 (save-excursion
4508 (beginning-of-line)
4509 (looking-at org-table-hline-regexp))))
4511 (defun org-table-map-tables (function &optional quietly)
4512 "Apply FUNCTION to the start of all tables in the buffer."
4513 (org-with-wide-buffer
4514 (goto-char (point-min))
4515 (while (re-search-forward org-table-any-line-regexp nil t)
4516 (unless quietly
4517 (message "Mapping tables: %d%%"
4518 (floor (* 100.0 (point)) (buffer-size))))
4519 (beginning-of-line 1)
4520 (when (and (looking-at org-table-line-regexp)
4521 ;; Exclude tables in src/example/verbatim/clocktable blocks
4522 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4523 (save-excursion (funcall function))
4524 (or (looking-at org-table-line-regexp)
4525 (forward-char 1)))
4526 (re-search-forward org-table-any-border-regexp nil 1)))
4527 (unless quietly (message "Mapping tables: done")))
4529 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4530 (declare-function org-clock-update-mode-line "org-clock" ())
4531 (declare-function org-resolve-clocks "org-clock"
4532 (&optional also-non-dangling-p prompt last-valid))
4534 (defun org-at-TBLFM-p (&optional pos)
4535 "Non-nil when point (or POS) is in #+TBLFM line."
4536 (save-excursion
4537 (goto-char (or pos (point)))
4538 (beginning-of-line)
4539 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4540 (eq (org-element-type (org-element-at-point)) 'table))))
4542 (defvar org-clock-start-time)
4543 (defvar org-clock-marker (make-marker)
4544 "Marker recording the last clock-in.")
4545 (defvar org-clock-hd-marker (make-marker)
4546 "Marker recording the last clock-in, but the headline position.")
4547 (defvar org-clock-heading ""
4548 "The heading of the current clock entry.")
4549 (defun org-clock-is-active ()
4550 "Return the buffer where the clock is currently running.
4551 Return nil if no clock is running."
4552 (marker-buffer org-clock-marker))
4554 (defun org-check-running-clock ()
4555 "Check if the current buffer contains the running clock.
4556 If yes, offer to stop it and to save the buffer with the changes."
4557 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4558 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4559 (buffer-name))))
4560 (org-clock-out)
4561 (when (y-or-n-p "Save changed buffer?")
4562 (save-buffer))))
4564 (defun org-clocktable-try-shift (dir n)
4565 "Check if this line starts a clock table, if yes, shift the time block."
4566 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4567 (org-clocktable-shift dir n)))
4569 ;;;###autoload
4570 (defun org-clock-persistence-insinuate ()
4571 "Set up hooks for clock persistence."
4572 (require 'org-clock)
4573 (add-hook 'org-mode-hook 'org-clock-load)
4574 (add-hook 'kill-emacs-hook 'org-clock-save))
4576 (defgroup org-archive nil
4577 "Options concerning archiving in Org mode."
4578 :tag "Org Archive"
4579 :group 'org-structure)
4581 (defcustom org-archive-location "%s_archive::"
4582 "The location where subtrees should be archived.
4584 The value of this variable is a string, consisting of two parts,
4585 separated by a double-colon. The first part is a filename and
4586 the second part is a headline.
4588 When the filename is omitted, archiving happens in the same file.
4589 %s in the filename will be replaced by the current file
4590 name (without the directory part). Archiving to a different file
4591 is useful to keep archived entries from contributing to the
4592 Org Agenda.
4594 The archived entries will be filed as subtrees of the specified
4595 headline. When the headline is omitted, the subtrees are simply
4596 filed away at the end of the file, as top-level entries. Also in
4597 the heading you can use %s to represent the file name, this can be
4598 useful when using the same archive for a number of different files.
4600 Here are a few examples:
4601 \"%s_archive::\"
4602 If the current file is Projects.org, archive in file
4603 Projects.org_archive, as top-level trees. This is the default.
4605 \"::* Archived Tasks\"
4606 Archive in the current file, under the top-level headline
4607 \"* Archived Tasks\".
4609 \"~/org/archive.org::\"
4610 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4612 \"~/org/archive.org::* From %s\"
4613 Archive in file ~/org/archive.org (absolute path), under headlines
4614 \"From FILENAME\" where file name is the current file name.
4616 \"~/org/datetree.org::datetree/* Finished Tasks\"
4617 The \"datetree/\" string is special, signifying to archive
4618 items to the datetree. Items are placed in either the CLOSED
4619 date of the item, or the current date if there is no CLOSED date.
4620 The heading will be a subentry to the current date. There doesn't
4621 need to be a heading, but there always needs to be a slash after
4622 datetree. For example, to store archived items directly in the
4623 datetree, use \"~/org/datetree.org::datetree/\".
4625 \"basement::** Finished Tasks\"
4626 Archive in file ./basement (relative path), as level 3 trees
4627 below the level 2 heading \"** Finished Tasks\".
4629 You may set this option on a per-file basis by adding to the buffer a
4630 line like
4632 #+ARCHIVE: basement::** Finished Tasks
4634 You may also define it locally for a subtree by setting an ARCHIVE property
4635 in the entry. If such a property is found in an entry, or anywhere up
4636 the hierarchy, it will be used."
4637 :group 'org-archive
4638 :type 'string)
4640 (defcustom org-agenda-skip-archived-trees t
4641 "Non-nil means the agenda will skip any items located in archived trees.
4642 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4643 variable is no longer recommended, you should leave it at the value t.
4644 Instead, use the key `v' to cycle the archives-mode in the agenda."
4645 :group 'org-archive
4646 :group 'org-agenda-skip
4647 :type 'boolean)
4649 (defcustom org-columns-skip-archived-trees t
4650 "Non-nil means ignore archived trees when creating column view."
4651 :group 'org-archive
4652 :group 'org-properties
4653 :type 'boolean)
4655 (defcustom org-cycle-open-archived-trees nil
4656 "Non-nil means `org-cycle' will open archived trees.
4657 An archived tree is a tree marked with the tag ARCHIVE.
4658 When nil, archived trees will stay folded. You can still open them with
4659 normal outline commands like `show-all', but not with the cycling commands."
4660 :group 'org-archive
4661 :group 'org-cycle
4662 :type 'boolean)
4664 (defcustom org-sparse-tree-open-archived-trees nil
4665 "Non-nil means sparse tree construction shows matches in archived trees.
4666 When nil, matches in these trees are highlighted, but the trees are kept in
4667 collapsed state."
4668 :group 'org-archive
4669 :group 'org-sparse-trees
4670 :type 'boolean)
4672 (defcustom org-sparse-tree-default-date-type nil
4673 "The default date type when building a sparse tree.
4674 When this is nil, a date is a scheduled or a deadline timestamp.
4675 Otherwise, these types are allowed:
4677 all: all timestamps
4678 active: only active timestamps (<...>)
4679 inactive: only inactive timestamps ([...])
4680 scheduled: only scheduled timestamps
4681 deadline: only deadline timestamps"
4682 :type '(choice (const :tag "Scheduled or deadline" nil)
4683 (const :tag "All timestamps" all)
4684 (const :tag "Only active timestamps" active)
4685 (const :tag "Only inactive timestamps" inactive)
4686 (const :tag "Only scheduled timestamps" scheduled)
4687 (const :tag "Only deadline timestamps" deadline)
4688 (const :tag "Only closed timestamps" closed))
4689 :version "26.1"
4690 :package-version '(Org . "8.3")
4691 :group 'org-sparse-trees)
4693 (defun org-cycle-hide-archived-subtrees (state)
4694 "Re-hide all archived subtrees after a visibility state change."
4695 (when (and (not org-cycle-open-archived-trees)
4696 (not (memq state '(overview folded))))
4697 (save-excursion
4698 (let* ((globalp (memq state '(contents all)))
4699 (beg (if globalp (point-min) (point)))
4700 (end (if globalp (point-max) (org-end-of-subtree t))))
4701 (org-hide-archived-subtrees beg end)
4702 (goto-char beg)
4703 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4704 (message "%s" (substitute-command-keys
4705 "Subtree is archived and stays closed. Use \
4706 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4708 (defun org-force-cycle-archived ()
4709 "Cycle subtree even if it is archived."
4710 (interactive)
4711 (setq this-command 'org-cycle)
4712 (let ((org-cycle-open-archived-trees t))
4713 (call-interactively 'org-cycle)))
4715 (defun org-hide-archived-subtrees (beg end)
4716 "Re-hide all archived subtrees after a visibility state change."
4717 (org-with-wide-buffer
4718 (let ((case-fold-search nil)
4719 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4720 (goto-char beg)
4721 ;; Include headline point is currently on.
4722 (beginning-of-line)
4723 (while (and (< (point) end) (re-search-forward re end t))
4724 (when (member org-archive-tag (org-get-tags))
4725 (org-flag-subtree t)
4726 (org-end-of-subtree t))))))
4728 (declare-function outline-end-of-heading "outline" ())
4729 (declare-function outline-flag-region "outline" (from to flag))
4730 (defun org-flag-subtree (flag)
4731 (save-excursion
4732 (org-back-to-heading t)
4733 (outline-end-of-heading)
4734 (outline-flag-region (point)
4735 (progn (org-end-of-subtree t) (point))
4736 flag)))
4738 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4740 ;; Declare Column View Code
4742 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4743 (declare-function org-columns-compute "org-colview" (property))
4745 ;; Declare ID code
4747 (declare-function org-id-store-link "org-id")
4748 (declare-function org-id-locations-load "org-id")
4749 (declare-function org-id-locations-save "org-id")
4750 (defvar org-id-track-globally)
4752 ;;; Variables for pre-computed regular expressions, all buffer local
4754 (defvar-local org-todo-regexp nil
4755 "Matches any of the TODO state keywords.
4756 Since TODO keywords are case-sensitive, `case-fold-search' is
4757 expected to be bound to nil when matching against this regexp.")
4759 (defvar-local org-not-done-regexp nil
4760 "Matches any of the TODO state keywords except the last one.
4761 Since TODO keywords are case-sensitive, `case-fold-search' is
4762 expected to be bound to nil when matching against this regexp.")
4764 (defvar-local org-not-done-heading-regexp nil
4765 "Matches a TODO headline that is not done.
4766 Since TODO keywords are case-sensitive, `case-fold-search' is
4767 expected to be bound to nil when matching against this regexp.")
4769 (defvar-local org-todo-line-regexp nil
4770 "Matches a headline and puts TODO state into group 2 if present.
4771 Since TODO keywords are case-sensitive, `case-fold-search' is
4772 expected to be bound to nil when matching against this regexp.")
4774 (defvar-local org-complex-heading-regexp nil
4775 "Matches a headline and puts everything into groups:
4777 group 1: Stars
4778 group 2: The TODO keyword, maybe
4779 group 3: Priority cookie
4780 group 4: True headline
4781 group 5: Tags
4783 Since TODO keywords are case-sensitive, `case-fold-search' is
4784 expected to be bound to nil when matching against this regexp.")
4786 (defvar-local org-complex-heading-regexp-format nil
4787 "Printf format to make regexp to match an exact headline.
4788 This regexp will match the headline of any node which has the
4789 exact headline text that is put into the format, but may have any
4790 TODO state, priority and tags.")
4792 (defvar-local org-todo-line-tags-regexp nil
4793 "Matches a headline and puts TODO state into group 2 if present.
4794 Also put tags into group 4 if tags are present.")
4796 (defconst org-plain-time-of-day-regexp
4797 (concat
4798 "\\(\\<[012]?[0-9]"
4799 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4800 "\\(--?"
4801 "\\(\\<[012]?[0-9]"
4802 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4803 "\\)?")
4804 "Regular expression to match a plain time or time range.
4805 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4806 groups carry important information:
4807 0 the full match
4808 1 the first time, range or not
4809 8 the second time, if it is a range.")
4811 (defconst org-plain-time-extension-regexp
4812 (concat
4813 "\\(\\<[012]?[0-9]"
4814 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4815 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4816 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4817 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4818 groups carry important information:
4819 0 the full match
4820 7 hours of duration
4821 9 minutes of duration")
4823 (defconst org-stamp-time-of-day-regexp
4824 (concat
4825 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4826 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4827 "\\(--?"
4828 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4829 "Regular expression to match a timestamp time or time range.
4830 After a match, the following groups carry important information:
4831 0 the full match
4832 1 date plus weekday, for back referencing to make sure both times are on the same day
4833 2 the first time, range or not
4834 4 the second time, if it is a range.")
4836 (defconst org-startup-options
4837 '(("fold" org-startup-folded t)
4838 ("overview" org-startup-folded t)
4839 ("nofold" org-startup-folded nil)
4840 ("showall" org-startup-folded nil)
4841 ("showeverything" org-startup-folded showeverything)
4842 ("content" org-startup-folded content)
4843 ("indent" org-startup-indented t)
4844 ("noindent" org-startup-indented nil)
4845 ("hidestars" org-hide-leading-stars t)
4846 ("showstars" org-hide-leading-stars nil)
4847 ("odd" org-odd-levels-only t)
4848 ("oddeven" org-odd-levels-only nil)
4849 ("align" org-startup-align-all-tables t)
4850 ("noalign" org-startup-align-all-tables nil)
4851 ("inlineimages" org-startup-with-inline-images t)
4852 ("noinlineimages" org-startup-with-inline-images nil)
4853 ("latexpreview" org-startup-with-latex-preview t)
4854 ("nolatexpreview" org-startup-with-latex-preview nil)
4855 ("customtime" org-display-custom-times t)
4856 ("logdone" org-log-done time)
4857 ("lognotedone" org-log-done note)
4858 ("nologdone" org-log-done nil)
4859 ("lognoteclock-out" org-log-note-clock-out t)
4860 ("nolognoteclock-out" org-log-note-clock-out nil)
4861 ("logrepeat" org-log-repeat state)
4862 ("lognoterepeat" org-log-repeat note)
4863 ("logdrawer" org-log-into-drawer t)
4864 ("nologdrawer" org-log-into-drawer nil)
4865 ("logstatesreversed" org-log-states-order-reversed t)
4866 ("nologstatesreversed" org-log-states-order-reversed nil)
4867 ("nologrepeat" org-log-repeat nil)
4868 ("logreschedule" org-log-reschedule time)
4869 ("lognotereschedule" org-log-reschedule note)
4870 ("nologreschedule" org-log-reschedule nil)
4871 ("logredeadline" org-log-redeadline time)
4872 ("lognoteredeadline" org-log-redeadline note)
4873 ("nologredeadline" org-log-redeadline nil)
4874 ("logrefile" org-log-refile time)
4875 ("lognoterefile" org-log-refile note)
4876 ("nologrefile" org-log-refile nil)
4877 ("fninline" org-footnote-define-inline t)
4878 ("nofninline" org-footnote-define-inline nil)
4879 ("fnlocal" org-footnote-section nil)
4880 ("fnauto" org-footnote-auto-label t)
4881 ("fnprompt" org-footnote-auto-label nil)
4882 ("fnconfirm" org-footnote-auto-label confirm)
4883 ("fnplain" org-footnote-auto-label plain)
4884 ("fnadjust" org-footnote-auto-adjust t)
4885 ("nofnadjust" org-footnote-auto-adjust nil)
4886 ("constcgs" constants-unit-system cgs)
4887 ("constSI" constants-unit-system SI)
4888 ("noptag" org-tag-persistent-alist nil)
4889 ("hideblocks" org-hide-block-startup t)
4890 ("nohideblocks" org-hide-block-startup nil)
4891 ("beamer" org-startup-with-beamer-mode t)
4892 ("entitiespretty" org-pretty-entities t)
4893 ("entitiesplain" org-pretty-entities nil))
4894 "Variable associated with STARTUP options for org-mode.
4895 Each element is a list of three items: the startup options (as written
4896 in the #+STARTUP line), the corresponding variable, and the value to set
4897 this variable to if the option is found. An optional forth element PUSH
4898 means to push this value onto the list in the variable.")
4900 (defcustom org-group-tags t
4901 "When non-nil (the default), use group tags.
4902 This can be turned on/off through `org-toggle-tags-groups'."
4903 :group 'org-tags
4904 :group 'org-startup
4905 :type 'boolean)
4907 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4909 (defun org-toggle-tags-groups ()
4910 "Toggle support for group tags.
4911 Support for group tags is controlled by the option
4912 `org-group-tags', which is non-nil by default."
4913 (interactive)
4914 (setq org-group-tags (not org-group-tags))
4915 (cond ((and (derived-mode-p 'org-agenda-mode)
4916 org-group-tags)
4917 (org-agenda-redo))
4918 ((derived-mode-p 'org-mode)
4919 (let ((org-inhibit-startup t)) (org-mode))))
4920 (message "Groups tags support has been turned %s"
4921 (if org-group-tags "on" "off")))
4923 (defun org-set-regexps-and-options (&optional tags-only)
4924 "Precompute regular expressions used in the current buffer.
4925 When optional argument TAGS-ONLY is non-nil, only compute tags
4926 related expressions."
4927 (when (derived-mode-p 'org-mode)
4928 (let ((alist (org--setup-collect-keywords
4929 (org-make-options-regexp
4930 (append '("FILETAGS" "TAGS" "SETUPFILE")
4931 (and (not tags-only)
4932 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4933 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4934 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4935 ;; Startup options. Get this early since it does change
4936 ;; behavior for other options (e.g., tags).
4937 (let ((startup (cdr (assq 'startup alist))))
4938 (dolist (option startup)
4939 (let ((entry (assoc-string option org-startup-options t)))
4940 (when entry
4941 (let ((var (nth 1 entry))
4942 (val (nth 2 entry)))
4943 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4944 (unless (listp (symbol-value var))
4945 (set (make-local-variable var) nil))
4946 (add-to-list var val)))))))
4947 (setq-local org-file-tags
4948 (mapcar #'org-add-prop-inherited
4949 (cdr (assq 'filetags alist))))
4950 (setq org-current-tag-alist
4951 (append org-tag-persistent-alist
4952 (let ((tags (cdr (assq 'tags alist))))
4953 (if tags (org-tag-string-to-alist tags)
4954 org-tag-alist))))
4955 (setq org-tag-groups-alist
4956 (org-tag-alist-to-groups org-current-tag-alist))
4957 (unless tags-only
4958 ;; File properties.
4959 (setq-local org-file-properties (cdr (assq 'property alist)))
4960 ;; Archive location.
4961 (let ((archive (cdr (assq 'archive alist))))
4962 (when archive (setq-local org-archive-location archive)))
4963 ;; Category.
4964 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4965 (when cat
4966 (setq-local org-category (intern cat))
4967 (setq-local org-file-properties
4968 (org--update-property-plist
4969 "CATEGORY" cat org-file-properties))))
4970 ;; Columns.
4971 (let ((column (cdr (assq 'columns alist))))
4972 (when column (setq-local org-columns-default-format column)))
4973 ;; Constants.
4974 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4975 ;; Link abbreviations.
4976 (let ((links (cdr (assq 'link alist))))
4977 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4978 ;; Priorities.
4979 (let ((priorities (cdr (assq 'priorities alist))))
4980 (when priorities
4981 (setq-local org-highest-priority (nth 0 priorities))
4982 (setq-local org-lowest-priority (nth 1 priorities))
4983 (setq-local org-default-priority (nth 2 priorities))))
4984 ;; Scripts.
4985 (let ((scripts (assq 'scripts alist)))
4986 (when scripts
4987 (setq-local org-use-sub-superscripts (cdr scripts))))
4988 ;; TODO keywords.
4989 (setq-local org-todo-kwd-alist nil)
4990 (setq-local org-todo-key-alist nil)
4991 (setq-local org-todo-key-trigger nil)
4992 (setq-local org-todo-keywords-1 nil)
4993 (setq-local org-done-keywords nil)
4994 (setq-local org-todo-heads nil)
4995 (setq-local org-todo-sets nil)
4996 (setq-local org-todo-log-states nil)
4997 (let ((todo-sequences
4998 (or (nreverse (cdr (assq 'todo alist)))
4999 (let ((d (default-value 'org-todo-keywords)))
5000 (if (not (stringp (car d))) d
5001 ;; XXX: Backward compatibility code.
5002 (list (cons org-todo-interpretation d)))))))
5003 (dolist (sequence todo-sequences)
5004 (let* ((sequence (or (run-hook-with-args-until-success
5005 'org-todo-setup-filter-hook sequence)
5006 sequence))
5007 (sequence-type (car sequence))
5008 (keywords (cdr sequence))
5009 (sep (member "|" keywords))
5010 names alist)
5011 (dolist (k (remove "|" keywords))
5012 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5014 (error "Invalid TODO keyword %s" k))
5015 (let ((name (match-string 1 k))
5016 (key (match-string 2 k))
5017 (log (org-extract-log-state-settings k)))
5018 (push name names)
5019 (push (cons name (and key (string-to-char key))) alist)
5020 (when log (push log org-todo-log-states))))
5021 (let* ((names (nreverse names))
5022 (done (if sep (org-remove-keyword-keys (cdr sep))
5023 (last names)))
5024 (head (car names))
5025 (tail (list sequence-type head (car done) (org-last done))))
5026 (add-to-list 'org-todo-heads head 'append)
5027 (push names org-todo-sets)
5028 (setq org-done-keywords (append org-done-keywords done nil))
5029 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5030 (setq org-todo-key-alist
5031 (append org-todo-key-alist
5032 (and alist
5033 (append '((:startgroup))
5034 (nreverse alist)
5035 '((:endgroup))))))
5036 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5037 (setq org-todo-sets (nreverse org-todo-sets)
5038 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5039 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5040 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5041 ;; Compute the regular expressions and other local variables.
5042 ;; Using `org-outline-regexp-bol' would complicate them much,
5043 ;; because of the fixed white space at the end of that string.
5044 (unless org-done-keywords
5045 (setq org-done-keywords
5046 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5047 (setq org-not-done-keywords
5048 (org-delete-all org-done-keywords
5049 (copy-sequence org-todo-keywords-1))
5050 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5051 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5052 org-not-done-heading-regexp
5053 (format org-heading-keyword-regexp-format org-not-done-regexp)
5054 org-todo-line-regexp
5055 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5056 org-complex-heading-regexp
5057 (concat "^\\(\\*+\\)"
5058 "\\(?: +" org-todo-regexp "\\)?"
5059 "\\(?: +\\(\\[#.\\]\\)\\)?"
5060 "\\(?: +\\(.*?\\)\\)??"
5061 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5062 "[ \t]*$")
5063 org-complex-heading-regexp-format
5064 (concat "^\\(\\*+\\)"
5065 "\\(?: +" org-todo-regexp "\\)?"
5066 "\\(?: +\\(\\[#.\\]\\)\\)?"
5067 "\\(?: +"
5068 ;; Stats cookies can be stuck to body.
5069 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5070 "\\(%s\\)"
5071 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5072 "\\)"
5073 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5074 "[ \t]*$")
5075 org-todo-line-tags-regexp
5076 (concat "^\\(\\*+\\)"
5077 "\\(?: +" org-todo-regexp "\\)?"
5078 "\\(?: +\\(.*?\\)\\)??"
5079 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5080 "[ \t]*$"))
5081 (org-compute-latex-and-related-regexp)))))
5083 (defun org--setup-collect-keywords (regexp &optional files alist)
5084 "Return setup keywords values as an alist.
5086 REGEXP matches a subset of setup keywords. FILES is a list of
5087 file names already visited. It is used to avoid circular setup
5088 files. ALIST, when non-nil, is the alist computed so far.
5090 Return value contains the following keys: `archive', `category',
5091 `columns', `constants', `filetags', `link', `priorities',
5092 `property', `scripts', `startup', `tags' and `todo'."
5093 (org-with-wide-buffer
5094 (goto-char (point-min))
5095 (let ((case-fold-search t))
5096 (while (re-search-forward regexp nil t)
5097 (let ((element (org-element-at-point)))
5098 (when (eq (org-element-type element) 'keyword)
5099 (let ((key (org-element-property :key element))
5100 (value (org-element-property :value element)))
5101 (cond
5102 ((equal key "ARCHIVE")
5103 (when (org-string-nw-p value)
5104 (push (cons 'archive value) alist)))
5105 ((equal key "CATEGORY") (push (cons 'category value) alist))
5106 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5107 ((equal key "CONSTANTS")
5108 (let* ((constants (assq 'constants alist))
5109 (store (cdr constants)))
5110 (dolist (pair (org-split-string value))
5111 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5112 pair)
5113 (let* ((name (match-string 1 pair))
5114 (value (match-string 2 pair))
5115 (old (assoc name store)))
5116 (if old (setcdr old value)
5117 (push (cons name value) store)))))
5118 (if constants (setcdr constants store)
5119 (push (cons 'constants store) alist))))
5120 ((equal key "FILETAGS")
5121 (when (org-string-nw-p value)
5122 (let ((old (assq 'filetags alist))
5123 (new (apply #'nconc
5124 (mapcar (lambda (x) (org-split-string x ":"))
5125 (org-split-string value)))))
5126 (if old (setcdr old (append new (cdr old)))
5127 (push (cons 'filetags new) alist)))))
5128 ((equal key "LINK")
5129 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5130 (let ((links (assq 'link alist))
5131 (pair (cons (match-string-no-properties 1 value)
5132 (match-string-no-properties 2 value))))
5133 (if links (push pair (cdr links))
5134 (push (list 'link pair) alist)))))
5135 ((equal key "OPTIONS")
5136 (when (and (org-string-nw-p value)
5137 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5138 (push (cons 'scripts (read (match-string 1 value))) alist)))
5139 ((equal key "PRIORITIES")
5140 (push (cons 'priorities
5141 (let ((prio (org-split-string value)))
5142 (if (< (length prio) 3) '(?A ?C ?B)
5143 (mapcar #'string-to-char prio))))
5144 alist))
5145 ((equal key "PROPERTY")
5146 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5147 (let* ((property (assq 'property alist))
5148 (value (org--update-property-plist
5149 (match-string-no-properties 1 value)
5150 (match-string-no-properties 2 value)
5151 (cdr property))))
5152 (if property (setcdr property value)
5153 (push (cons 'property value) alist)))))
5154 ((equal key "STARTUP")
5155 (let ((startup (assq 'startup alist)))
5156 (if startup
5157 (setcdr startup
5158 (append (cdr startup) (org-split-string value)))
5159 (push (cons 'startup (org-split-string value)) alist))))
5160 ((equal key "TAGS")
5161 (let ((tag-cell (assq 'tags alist)))
5162 (if tag-cell
5163 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5164 (push (cons 'tags value) alist))))
5165 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5166 (let ((todo (assq 'todo alist))
5167 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5168 (org-split-string value))))
5169 (if todo (push value (cdr todo))
5170 (push (list 'todo value) alist))))
5171 ((equal key "SETUPFILE")
5172 (unless buffer-read-only ; Do not check in Gnus messages.
5173 (let ((f (and (org-string-nw-p value)
5174 (expand-file-name
5175 (org-unbracket-string "\"" "\"" value)))))
5176 (when (and f (file-readable-p f) (not (member f files)))
5177 (with-temp-buffer
5178 (setq default-directory (file-name-directory f))
5179 (insert-file-contents f)
5180 (setq alist
5181 ;; Fake Org mode to benefit from cache
5182 ;; without recurring needlessly.
5183 (let ((major-mode 'org-mode))
5184 (org--setup-collect-keywords
5185 regexp (cons f files) alist)))))))))))))))
5186 alist)
5188 (defun org-tag-string-to-alist (s)
5189 "Return tag alist associated to string S.
5190 S is a value for TAGS keyword or produced with
5191 `org-tag-alist-to-string'. Return value is an alist suitable for
5192 `org-tag-alist' or `org-tag-persistent-alist'."
5193 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5194 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5195 "\\|{.+?}\\)" ; regular expression
5196 "\\(?:(\\(.\\))\\)?\\'"))
5197 alist group-flag)
5198 (dolist (tokens lines (cdr (nreverse alist)))
5199 (push '(:newline) alist)
5200 (while tokens
5201 (let ((token (pop tokens)))
5202 (pcase token
5203 ("{"
5204 (push '(:startgroup) alist)
5205 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5206 ("}"
5207 (push '(:endgroup) alist)
5208 (setq group-flag nil))
5209 ("["
5210 (push '(:startgrouptag) alist)
5211 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5212 ("]"
5213 (push '(:endgrouptag) alist)
5214 (setq group-flag nil))
5215 (":"
5216 (push '(:grouptags) alist))
5217 ((guard (string-match tag-re token))
5218 (let ((tag (match-string 1 token))
5219 (key (and (match-beginning 2)
5220 (string-to-char (match-string 2 token)))))
5221 ;; Push all tags in groups, no matter if they already
5222 ;; appear somewhere else in the list.
5223 (when (or group-flag (not (assoc tag alist)))
5224 (push (cons tag key) alist))))))))))
5226 (defun org-tag-alist-to-string (alist &optional skip-key)
5227 "Return tag string associated to ALIST.
5229 ALIST is an alist, as defined in `org-tag-alist' or
5230 `org-tag-persistent-alist', or produced with
5231 `org-tag-string-to-alist'.
5233 Return value is a string suitable as a value for \"TAGS\"
5234 keyword.
5236 When optional argument SKIP-KEY is non-nil, skip selection keys
5237 next to tags."
5238 (mapconcat (lambda (token)
5239 (pcase token
5240 (`(:startgroup) "{")
5241 (`(:endgroup) "}")
5242 (`(:startgrouptag) "[")
5243 (`(:endgrouptag) "]")
5244 (`(:grouptags) ":")
5245 (`(:newline) "\\n")
5246 ((and
5247 (guard (not skip-key))
5248 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5249 (format "%s(%c)" tag key))
5250 (`(,(and tag (pred stringp)) . ,_) tag)
5251 (_ (user-error "Invalid tag token: %S" token))))
5252 alist
5253 " "))
5255 (defun org-tag-alist-to-groups (alist)
5256 "Return group alist from tag ALIST.
5257 ALIST is an alist, as defined in `org-tag-alist' or
5258 `org-tag-persistent-alist', or produced with
5259 `org-tag-string-to-alist'. Return value is an alist following
5260 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5261 a string, summarizing TAGS, as a list of strings."
5262 (let (groups group-status current-group)
5263 (dolist (token alist (nreverse groups))
5264 (pcase token
5265 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5266 (`(,(or :endgroup :endgrouptag))
5267 (when (eq group-status 'append)
5268 (push (nreverse current-group) groups))
5269 (setq group-status nil))
5270 (`(:grouptags) (setq group-status 'append))
5271 ((and `(,tag . ,_) (guard group-status))
5272 (if (eq group-status 'append) (push tag current-group)
5273 (setq current-group (list tag))))
5274 (_ nil)))))
5276 (defun org-file-contents (file &optional noerror)
5277 "Return the contents of FILE, as a string."
5278 (if (and file (file-readable-p file))
5279 (with-temp-buffer
5280 (insert-file-contents file)
5281 (buffer-string))
5282 (funcall (if noerror 'message 'error)
5283 "Cannot read file \"%s\"%s"
5284 file
5285 (let ((from (buffer-file-name (buffer-base-buffer))))
5286 (if from (concat " (referenced in file \"" from "\")") "")))))
5288 (defun org-extract-log-state-settings (x)
5289 "Extract the log state setting from a TODO keyword string.
5290 This will extract info from a string like \"WAIT(w@/!)\"."
5291 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5292 (let ((kw (match-string 1 x))
5293 (log1 (and (match-end 3) (match-string 3 x)))
5294 (log2 (and (match-end 4) (match-string 4 x))))
5295 (and (or log1 log2)
5296 (list kw
5297 (and log1 (if (equal log1 "!") 'time 'note))
5298 (and log2 (if (equal log2 "!") 'time 'note)))))))
5300 (defun org-remove-keyword-keys (list)
5301 "Remove a pair of parenthesis at the end of each string in LIST."
5302 (mapcar (lambda (x)
5303 (if (string-match "(.*)$" x)
5304 (substring x 0 (match-beginning 0))
5306 list))
5308 (defun org-assign-fast-keys (alist)
5309 "Assign fast keys to a keyword-key alist.
5310 Respect keys that are already there."
5311 (let (new e (alt ?0))
5312 (while (setq e (pop alist))
5313 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5314 (cdr e)) ;; Key already assigned.
5315 (push e new)
5316 (let ((clist (string-to-list (downcase (car e))))
5317 (used (append new alist)))
5318 (when (= (car clist) ?@)
5319 (pop clist))
5320 (while (and clist (rassoc (car clist) used))
5321 (pop clist))
5322 (unless clist
5323 (while (rassoc alt used)
5324 (cl-incf alt)))
5325 (push (cons (car e) (or (car clist) alt)) new))))
5326 (nreverse new)))
5328 ;;; Some variables used in various places
5330 (defvar org-window-configuration nil
5331 "Used in various places to store a window configuration.")
5332 (defvar org-selected-window nil
5333 "Used in various places to store a window configuration.")
5334 (defvar org-finish-function nil
5335 "Function to be called when `C-c C-c' is used.
5336 This is for getting out of special buffers like capture.")
5337 (defvar org-last-state)
5339 ;; Defined somewhere in this file, but used before definition.
5340 (defvar org-entities) ;; defined in org-entities.el
5341 (defvar org-struct-menu)
5342 (defvar org-org-menu)
5343 (defvar org-tbl-menu)
5345 ;;;; Define the Org mode
5347 ;; We use a before-change function to check if a table might need
5348 ;; an update.
5349 (defvar org-table-may-need-update t
5350 "Indicates that a table might need an update.
5351 This variable is set by `org-before-change-function'.
5352 `org-table-align' sets it back to nil.")
5353 (defun org-before-change-function (_beg _end)
5354 "Every change indicates that a table might need an update."
5355 (setq org-table-may-need-update t))
5356 (defvar org-mode-map)
5357 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5358 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5359 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5360 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5361 (defvar org-table-buffer-is-an nil)
5363 (defvar bidi-paragraph-direction)
5364 (defvar buffer-face-mode-face)
5366 (require 'outline)
5368 ;; Other stuff we need.
5369 (require 'time-date)
5370 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5371 (require 'easymenu)
5372 (autoload 'easy-menu-add "easymenu")
5373 (require 'overlay)
5375 ;; (require 'org-macs) moved higher up in the file before it is first used
5376 (require 'org-entities)
5377 ;; (require 'org-compat) moved higher up in the file before it is first used
5378 (require 'org-faces)
5379 (require 'org-list)
5380 (require 'org-pcomplete)
5381 (require 'org-src)
5382 (require 'org-footnote)
5383 (require 'org-macro)
5385 ;; babel
5386 (require 'ob)
5388 ;;;###autoload
5389 (define-derived-mode org-mode outline-mode "Org"
5390 "Outline-based notes management and organizer, alias
5391 \"Carsten's outline-mode for keeping track of everything.\"
5393 Org mode develops organizational tasks around a NOTES file which
5394 contains information about projects as plain text. Org mode is
5395 implemented on top of Outline mode, which is ideal to keep the content
5396 of large files well structured. It supports ToDo items, deadlines and
5397 time stamps, which magically appear in the diary listing of the Emacs
5398 calendar. Tables are easily created with a built-in table editor.
5399 Plain text URL-like links connect to websites, emails (VM), Usenet
5400 messages (Gnus), BBDB entries, and any files related to the project.
5401 For printing and sharing of notes, an Org file (or a part of it)
5402 can be exported as a structured ASCII or HTML file.
5404 The following commands are available:
5406 \\{org-mode-map}"
5408 ;; Get rid of Outline menus, they are not needed
5409 ;; Need to do this here because define-derived-mode sets up
5410 ;; the keymap so late. Still, it is a waste to call this each time
5411 ;; we switch another buffer into Org mode.
5412 (define-key org-mode-map [menu-bar headings] 'undefined)
5413 (define-key org-mode-map [menu-bar hide] 'undefined)
5414 (define-key org-mode-map [menu-bar show] 'undefined)
5416 (org-load-modules-maybe)
5417 (org-install-agenda-files-menu)
5418 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5419 (add-to-invisibility-spec '(org-cwidth))
5420 (add-to-invisibility-spec '(org-hide-block . t))
5421 (setq-local outline-regexp org-outline-regexp)
5422 (setq-local outline-level 'org-outline-level)
5423 (setq bidi-paragraph-direction 'left-to-right)
5424 (when (and org-ellipsis
5425 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5426 (fboundp 'make-glyph-code))
5427 (unless org-display-table
5428 (setq org-display-table (make-display-table)))
5429 (set-display-table-slot
5430 org-display-table 4
5431 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5432 (if (stringp org-ellipsis) org-ellipsis "..."))))
5433 (setq buffer-display-table org-display-table))
5434 (org-set-regexps-and-options)
5435 (org-set-font-lock-defaults)
5436 (when (and org-tag-faces (not org-tags-special-faces-re))
5437 ;; tag faces set outside customize.... force initialization.
5438 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5439 ;; Calc embedded
5440 (setq-local calc-embedded-open-mode "# ")
5441 ;; Modify a few syntax entries
5442 (modify-syntax-entry ?@ "w")
5443 (modify-syntax-entry ?\" "\"")
5444 (modify-syntax-entry ?\\ "_")
5445 (modify-syntax-entry ?~ "_")
5446 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5447 ;; Activate before-change-function
5448 (setq-local org-table-may-need-update t)
5449 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5450 ;; Check for running clock before killing a buffer
5451 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5452 ;; Initialize macros templates.
5453 (org-macro-initialize-templates)
5454 ;; Initialize radio targets.
5455 (org-update-radio-target-regexp)
5456 ;; Indentation.
5457 (setq-local indent-line-function 'org-indent-line)
5458 (setq-local indent-region-function 'org-indent-region)
5459 ;; Filling and auto-filling.
5460 (org-setup-filling)
5461 ;; Comments.
5462 (org-setup-comments-handling)
5463 ;; Initialize cache.
5464 (org-element-cache-reset)
5465 ;; Beginning/end of defun
5466 (setq-local beginning-of-defun-function 'org-backward-element)
5467 (setq-local end-of-defun-function
5468 (lambda ()
5469 (if (not (org-at-heading-p))
5470 (org-forward-element)
5471 (org-forward-element)
5472 (forward-char -1))))
5473 ;; Next error for sparse trees
5474 (setq-local next-error-function 'org-occur-next-match)
5475 ;; Make sure dependence stuff works reliably, even for users who set it
5476 ;; too late :-(
5477 (if org-enforce-todo-dependencies
5478 (add-hook 'org-blocker-hook
5479 'org-block-todo-from-children-or-siblings-or-parent)
5480 (remove-hook 'org-blocker-hook
5481 'org-block-todo-from-children-or-siblings-or-parent))
5482 (if org-enforce-todo-checkbox-dependencies
5483 (add-hook 'org-blocker-hook
5484 'org-block-todo-from-checkboxes)
5485 (remove-hook 'org-blocker-hook
5486 'org-block-todo-from-checkboxes))
5488 ;; Align options lines
5489 (setq-local
5490 align-mode-rules-list
5491 '((org-in-buffer-settings
5492 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5493 (modes . '(org-mode)))))
5495 ;; Imenu
5496 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5498 ;; Make isearch reveal context
5499 (setq-local outline-isearch-open-invisible-function
5500 (lambda (&rest _) (org-show-context 'isearch)))
5502 ;; Setup the pcomplete hooks
5503 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5504 (setq-local pcomplete-command-name-function 'org-command-at-point)
5505 (setq-local pcomplete-default-completion-function 'ignore)
5506 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5507 (setq-local pcomplete-termination-string "")
5508 (setq-local buffer-face-mode-face 'org-default)
5510 ;; If empty file that did not turn on Org mode automatically, make
5511 ;; it to.
5512 (when (and org-insert-mode-line-in-empty-file
5513 (called-interactively-p 'any)
5514 (= (point-min) (point-max)))
5515 (insert "# -*- mode: org -*-\n\n"))
5516 (unless org-inhibit-startup
5517 (org-unmodified
5518 (when org-startup-with-beamer-mode (org-beamer-mode))
5519 (when org-startup-align-all-tables
5520 (org-table-map-tables #'org-table-align t))
5521 (when org-startup-with-inline-images (org-display-inline-images))
5522 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5523 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5524 (when org-startup-truncated (setq truncate-lines t))
5525 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5526 (org-refresh-effort-properties)))
5527 ;; Try to set `org-hide' face correctly.
5528 (let ((foreground (org-find-invisible-foreground)))
5529 (when foreground
5530 (set-face-foreground 'org-hide foreground))))
5532 ;; Update `customize-package-emacs-version-alist'
5533 (add-to-list 'customize-package-emacs-version-alist
5534 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5535 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5536 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5537 ("9.0" . "26.1")))
5539 (defvar org-mode-transpose-word-syntax-table
5540 (let ((st (make-syntax-table text-mode-syntax-table)))
5541 (dolist (c org-emphasis-alist st)
5542 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5544 (when (fboundp 'abbrev-table-put)
5545 (abbrev-table-put org-mode-abbrev-table
5546 :parents (list text-mode-abbrev-table)))
5548 (defun org-find-invisible-foreground ()
5549 (let ((candidates (remove
5550 "unspecified-bg"
5551 (nconc
5552 (list (face-background 'default)
5553 (face-background 'org-default))
5554 (mapcar
5555 (lambda (alist)
5556 (when (boundp alist)
5557 (cdr (assq 'background-color (symbol-value alist)))))
5558 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5559 (list (face-foreground 'org-hide))))))
5560 (car (remove nil candidates))))
5562 (defun org-current-time (&optional rounding-minutes past)
5563 "Current time, possibly rounded to ROUNDING-MINUTES.
5564 When ROUNDING-MINUTES is not an integer, fall back on the car of
5565 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5566 the rounding returns a past time."
5567 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5568 (car org-time-stamp-rounding-minutes)))
5569 (time (decode-time)) res)
5570 (if (< r 1)
5571 (current-time)
5572 (setq res
5573 (apply 'encode-time
5574 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5575 (nthcdr 2 time))))
5576 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5577 (seconds-to-time (- (float-time res) (* r 60)))
5578 res))))
5580 (defun org-today ()
5581 "Return today date, considering `org-extend-today-until'."
5582 (time-to-days
5583 (time-subtract (current-time)
5584 (list 0 (* 3600 org-extend-today-until) 0))))
5586 ;;;; Font-Lock stuff, including the activators
5588 (defvar org-mouse-map (make-sparse-keymap))
5589 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5590 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5591 (when org-mouse-1-follows-link
5592 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5593 (when org-tab-follows-link
5594 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5595 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5597 (require 'font-lock)
5599 (defconst org-non-link-chars "]\t\n\r<>")
5600 (defvar org-link-types-re nil
5601 "Matches a link that has a url-like prefix like \"http:\"")
5602 (defvar org-link-re-with-space nil
5603 "Matches a link with spaces, optional angular brackets around it.")
5604 (defvar org-link-re-with-space2 nil
5605 "Matches a link with spaces, optional angular brackets around it.")
5606 (defvar org-link-re-with-space3 nil
5607 "Matches a link with spaces, only for internal part in bracket links.")
5608 (defvar org-angle-link-re nil
5609 "Matches link with angular brackets, spaces are allowed.")
5610 (defvar org-plain-link-re nil
5611 "Matches plain link, without spaces.")
5612 (defvar org-bracket-link-regexp nil
5613 "Matches a link in double brackets.")
5614 (defvar org-bracket-link-analytic-regexp nil
5615 "Regular expression used to analyze links.
5616 Here is what the match groups contain after a match:
5617 1: http:
5618 2: http
5619 3: path
5620 4: [desc]
5621 5: desc")
5622 (defvar org-bracket-link-analytic-regexp++ nil
5623 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5624 (defvar org-any-link-re nil
5625 "Regular expression matching any link.")
5627 (defconst org-match-sexp-depth 3
5628 "Number of stacked braces for sub/superscript matching.")
5630 (defun org-create-multibrace-regexp (left right n)
5631 "Create a regular expression which will match a balanced sexp.
5632 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5633 as single character strings.
5634 The regexp returned will match the entire expression including the
5635 delimiters. It will also define a single group which contains the
5636 match except for the outermost delimiters. The maximum depth of
5637 stacked delimiters is N. Escaping delimiters is not possible."
5638 (let* ((nothing (concat "[^" left right "]*?"))
5639 (or "\\|")
5640 (re nothing)
5641 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5642 (while (> n 1)
5643 (setq n (1- n)
5644 re (concat re or next)
5645 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5646 (concat left "\\(" re "\\)" right)))
5648 (defconst org-match-substring-regexp
5649 (concat
5650 "\\(\\S-\\)\\([_^]\\)\\("
5651 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5652 "\\|"
5653 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5654 "\\|"
5655 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5656 "The regular expression matching a sub- or superscript.")
5658 (defconst org-match-substring-with-braces-regexp
5659 (concat
5660 "\\(\\S-\\)\\([_^]\\)"
5661 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5662 "The regular expression matching a sub- or superscript, forcing braces.")
5664 (defun org-make-link-regexps ()
5665 "Update the link regular expressions.
5666 This should be called after the variable `org-link-parameters' has changed."
5667 (let ((types-re (regexp-opt (org-link-types) t)))
5668 (setq org-link-types-re
5669 (concat "\\`" types-re ":")
5670 org-link-re-with-space
5671 (concat "<?" types-re ":"
5672 "\\([^" org-non-link-chars " ]"
5673 "[^" org-non-link-chars "]*"
5674 "[^" org-non-link-chars " ]\\)>?")
5675 org-link-re-with-space2
5676 (concat "<?" types-re ":"
5677 "\\([^" org-non-link-chars " ]"
5678 "[^\t\n\r]*"
5679 "[^" org-non-link-chars " ]\\)>?")
5680 org-link-re-with-space3
5681 (concat "<?" types-re ":"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^\t\n\r]*\\)")
5684 org-angle-link-re
5685 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5686 types-re)
5687 org-plain-link-re
5688 (concat
5689 "\\<" types-re ":"
5690 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5691 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5692 org-bracket-link-regexp
5693 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5694 org-bracket-link-analytic-regexp
5695 (concat
5696 "\\[\\["
5697 "\\(" types-re ":\\)?"
5698 "\\([^]]+\\)"
5699 "\\]"
5700 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5701 "\\]")
5702 org-bracket-link-analytic-regexp++
5703 (concat
5704 "\\[\\["
5705 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5706 "\\([^]]+\\)"
5707 "\\]"
5708 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5709 "\\]")
5710 org-any-link-re
5711 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5712 org-angle-link-re "\\)\\|\\("
5713 org-plain-link-re "\\)"))))
5715 (org-make-link-regexps)
5717 (defvar org-emph-face nil)
5719 (defun org-do-emphasis-faces (limit)
5720 "Run through the buffer and emphasize strings."
5721 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5722 (car org-emphasis-regexp-components))))
5723 (catch :exit
5724 (while (re-search-forward quick-re limit t)
5725 (let* ((marker (match-string 2))
5726 (verbatim? (member marker '("~" "="))))
5727 (when (save-excursion
5728 (goto-char (match-beginning 0))
5729 ;; Do not match headline stars. Do not consider
5730 ;; stars of a headline as closing marker for bold
5731 ;; markup either.
5732 (and (not (looking-at-p org-outline-regexp-bol))
5733 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5734 (not (string-match-p
5735 (concat org-outline-regexp-bol "\\'")
5736 (match-string 0)))))
5737 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5738 (font-lock-prepend-text-property
5739 (match-beginning 2) (match-end 2) 'face face)
5740 (when verbatim?
5741 (org-remove-flyspell-overlays-in
5742 (match-beginning 0) (match-end 0)))
5743 (add-text-properties (match-beginning 2) (match-end 2)
5744 '(font-lock-multiline t org-emphasis t))
5745 (when org-hide-emphasis-markers
5746 (add-text-properties (match-end 4) (match-beginning 5)
5747 '(invisible org-link))
5748 (add-text-properties (match-beginning 3) (match-end 3)
5749 '(invisible org-link)))
5750 (throw :exit t))))))))
5752 (defun org-emphasize (&optional char)
5753 "Insert or change an emphasis, i.e. a font like bold or italic.
5754 If there is an active region, change that region to a new emphasis.
5755 If there is no region, just insert the marker characters and position
5756 the cursor between them.
5757 CHAR should be the marker character. If it is a space, it means to
5758 remove the emphasis of the selected region.
5759 If CHAR is not given (for example in an interactive call) it will be
5760 prompted for."
5761 (interactive)
5762 (let ((erc org-emphasis-regexp-components)
5763 (string "") beg end move s)
5764 (if (org-region-active-p)
5765 (setq beg (region-beginning)
5766 end (region-end)
5767 string (buffer-substring beg end))
5768 (setq move t))
5770 (unless char
5771 (message "Emphasis marker or tag: [%s]"
5772 (mapconcat #'car org-emphasis-alist ""))
5773 (setq char (read-char-exclusive)))
5774 (if (equal char ?\s)
5775 (setq s ""
5776 move nil)
5777 (unless (assoc (char-to-string char) org-emphasis-alist)
5778 (user-error "No such emphasis marker: \"%c\"" char))
5779 (setq s (char-to-string char)))
5780 (while (and (> (length string) 1)
5781 (equal (substring string 0 1) (substring string -1))
5782 (assoc (substring string 0 1) org-emphasis-alist))
5783 (setq string (substring string 1 -1)))
5784 (setq string (concat s string s))
5785 (when beg (delete-region beg end))
5786 (unless (or (bolp)
5787 (string-match (concat "[" (nth 0 erc) "\n]")
5788 (char-to-string (char-before (point)))))
5789 (insert " "))
5790 (unless (or (eobp)
5791 (string-match (concat "[" (nth 1 erc) "\n]")
5792 (char-to-string (char-after (point)))))
5793 (insert " ") (backward-char 1))
5794 (insert string)
5795 (and move (backward-char 1))))
5797 (defconst org-nonsticky-props
5798 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5800 (defsubst org-rear-nonsticky-at (pos)
5801 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5803 (defun org-activate-plain-links (limit)
5804 "Add link properties for plain links."
5805 (when (and (re-search-forward org-plain-link-re limit t)
5806 (not (org-in-src-block-p)))
5808 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5809 'face))
5810 (link (match-string-no-properties 0))
5811 (type (match-string-no-properties 1))
5812 (path (match-string-no-properties 2))
5813 (link-start (match-beginning 0))
5814 (link-end (match-end 0))
5815 (link-face (org-link-get-parameter type :face))
5816 (help-echo (org-link-get-parameter type :help-echo))
5817 (htmlize-link (org-link-get-parameter type :htmlize-link))
5818 (activate-func (org-link-get-parameter type :activate-func)))
5819 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5820 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5821 (add-text-properties (match-beginning 0) (match-end 0)
5822 (list
5823 'mouse-face (or (org-link-get-parameter type :mouse-face)
5824 'highlight)
5825 'face (cond
5826 ;; A function that returns a face
5827 ((functionp link-face)
5828 (funcall link-face path))
5829 ;; a face
5830 ((facep link-face)
5831 link-face)
5832 ;; An anonymous face
5833 ((consp link-face)
5834 link-face)
5835 ;; default
5837 'org-link))
5838 'help-echo (cond
5839 ((stringp help-echo)
5840 help-echo)
5841 ((functionp help-echo)
5842 help-echo)
5844 (concat "LINK: "
5845 (save-match-data
5846 (org-link-unescape link)))))
5847 'htmlize-link (cond
5848 ((functionp htmlize-link)
5849 (funcall htmlize-link path))
5851 `(:uri ,link)))
5852 'keymap (or (org-link-get-parameter type :keymap)
5853 org-mouse-map)
5854 'org-link-start (match-beginning 0)))
5855 (org-rear-nonsticky-at (match-end 0))
5856 (when activate-func
5857 (funcall activate-func link-start link-end path nil))
5858 t))))
5860 (defun org-activate-code (limit)
5861 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5862 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5863 (remove-text-properties (match-beginning 0) (match-end 0)
5864 '(display t invisible t intangible t))
5867 (defcustom org-src-fontify-natively t
5868 "When non-nil, fontify code in code blocks.
5869 See also the `org-block' face."
5870 :type 'boolean
5871 :version "24.4"
5872 :package-version '(Org . "8.3")
5873 :group 'org-appearance
5874 :group 'org-babel)
5876 (defcustom org-allow-promoting-top-level-subtree nil
5877 "When non-nil, allow promoting a top level subtree.
5878 The leading star of the top level headline will be replaced
5879 by a #."
5880 :type 'boolean
5881 :version "24.1"
5882 :group 'org-appearance)
5884 (defun org-fontify-meta-lines-and-blocks (limit)
5885 (condition-case nil
5886 (org-fontify-meta-lines-and-blocks-1 limit)
5887 (error (message "org-mode fontification error in %S at %d"
5888 (current-buffer)
5889 (line-number-at-pos)))))
5891 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5892 "Fontify #+ lines and blocks."
5893 (let ((case-fold-search t))
5894 (when (re-search-forward
5895 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5896 limit t)
5897 (let ((beg (match-beginning 0))
5898 (block-start (match-end 0))
5899 (block-end nil)
5900 (lang (match-string 7))
5901 (beg1 (line-beginning-position 2))
5902 (dc1 (downcase (match-string 2)))
5903 (dc3 (downcase (match-string 3)))
5904 end end1 quoting block-type)
5905 (cond
5906 ((and (match-end 4) (equal dc3 "+begin"))
5907 ;; Truly a block
5908 (setq block-type (downcase (match-string 5))
5909 quoting (member block-type org-protecting-blocks))
5910 (when (re-search-forward
5911 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5912 nil t) ;; on purpose, we look further than LIMIT
5913 (setq end (min (point-max) (match-end 0))
5914 end1 (min (point-max) (1- (match-beginning 0))))
5915 (setq block-end (match-beginning 0))
5916 (when quoting
5917 (org-remove-flyspell-overlays-in beg1 end1)
5918 (remove-text-properties beg end
5919 '(display t invisible t intangible t)))
5920 (add-text-properties
5921 beg end '(font-lock-fontified t font-lock-multiline t))
5922 (add-text-properties beg beg1 '(face org-meta-line))
5923 (org-remove-flyspell-overlays-in beg beg1)
5924 (add-text-properties ; For end_src
5925 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5926 (org-remove-flyspell-overlays-in end1 end)
5927 (cond
5928 ((and lang (not (string= lang "")) org-src-fontify-natively)
5929 (org-src-font-lock-fontify-block lang block-start block-end)
5930 (add-text-properties beg1 block-end '(src-block t)))
5931 (quoting
5932 (add-text-properties beg1 (min (point-max) (1+ end1))
5933 (list 'face
5934 (list :inherit
5935 (let ((face-name
5936 (intern (format "org-block-%s" lang))))
5937 (append (and (facep face-name) (list face-name))
5938 '(org-block))))))) ; end of source block
5939 ((not org-fontify-quote-and-verse-blocks))
5940 ((string= block-type "quote")
5941 (add-face-text-property
5942 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5943 ((string= block-type "verse")
5944 (add-face-text-property
5945 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5946 (add-text-properties beg beg1 '(face org-block-begin-line))
5947 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5948 '(face org-block-end-line))
5950 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5951 (org-remove-flyspell-overlays-in
5952 (match-beginning 0)
5953 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5954 (add-text-properties
5955 beg (match-end 3)
5956 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5957 '(font-lock-fontified t invisible t)
5958 '(font-lock-fontified t face org-document-info-keyword)))
5959 (add-text-properties
5960 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5961 (if (string-equal dc1 "+title:")
5962 '(font-lock-fontified t face org-document-title)
5963 '(font-lock-fontified t face org-document-info))))
5964 ((string-prefix-p "+caption" dc1)
5965 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5966 (remove-text-properties (match-beginning 0) (match-end 0)
5967 '(display t invisible t intangible t))
5968 ;; Handle short captions.
5969 (save-excursion
5970 (beginning-of-line)
5971 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5972 (add-text-properties (line-beginning-position) (match-end 1)
5973 '(font-lock-fontified t face org-meta-line))
5974 (add-text-properties (match-end 0) (line-end-position)
5975 '(font-lock-fontified t face org-block))
5977 ((member dc3 '(" " ""))
5978 (org-remove-flyspell-overlays-in beg (match-end 0))
5979 (add-text-properties
5980 beg (match-end 0)
5981 '(font-lock-fontified t face font-lock-comment-face)))
5982 (t ;; just any other in-buffer setting, but not indented
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (remove-text-properties (match-beginning 0) (match-end 0)
5985 '(display t invisible t intangible t))
5986 (add-text-properties beg (match-end 0)
5987 '(font-lock-fontified t face org-meta-line))
5988 t))))))
5990 (defun org-fontify-drawers (limit)
5991 "Fontify drawers."
5992 (when (re-search-forward org-drawer-regexp limit t)
5993 (add-text-properties
5994 (match-beginning 0) (match-end 0)
5995 '(font-lock-fontified t face org-special-keyword))
5996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5999 (defun org-fontify-macros (limit)
6000 "Fontify macros."
6001 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6002 (add-text-properties
6003 (match-beginning 0) (match-end 0)
6004 '(font-lock-fontified t face org-macro))
6005 (when org-hide-macro-markers
6006 (add-text-properties (match-end 2) (match-beginning 2)
6007 '(invisible t))
6008 (add-text-properties (match-beginning 1) (match-end 1)
6009 '(invisible t)))
6010 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6013 (defun org-activate-angle-links (limit)
6014 "Add text properties for angle links."
6015 (when (and (re-search-forward org-angle-link-re limit t)
6016 (not (org-in-src-block-p)))
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6018 (add-text-properties (match-beginning 0) (match-end 0)
6019 (list 'mouse-face 'highlight
6020 'keymap org-mouse-map
6021 'font-lock-multiline t))
6022 (org-rear-nonsticky-at (match-end 0))
6025 (defun org-activate-footnote-links (limit)
6026 "Add text properties for footnotes."
6027 (let ((fn (org-footnote-next-reference-or-definition limit)))
6028 (when fn
6029 (let* ((beg (nth 1 fn))
6030 (end (nth 2 fn))
6031 (label (car fn))
6032 (referencep (/= (line-beginning-position) beg)))
6033 (when (and referencep (nth 3 fn))
6034 (save-excursion
6035 (goto-char beg)
6036 (search-forward (or label "fn:"))
6037 (org-remove-flyspell-overlays-in beg (match-end 0))))
6038 (add-text-properties beg end
6039 (list 'mouse-face 'highlight
6040 'keymap org-mouse-map
6041 'help-echo
6042 (if referencep "Footnote reference"
6043 "Footnote definition")
6044 'font-lock-fontified t
6045 'font-lock-multiline t
6046 'face 'org-footnote))))))
6048 (defun org-activate-bracket-links (limit)
6049 "Add text properties for bracketed links."
6050 (when (and (re-search-forward org-bracket-link-regexp limit t)
6051 (not (org-in-src-block-p)))
6052 (let* ((hl (save-match-data
6053 (org-link-expand-abbrev (match-string-no-properties 1))))
6054 (type (save-match-data
6055 (and (string-match org-plain-link-re hl)
6056 (match-string-no-properties 1 hl))))
6057 (path (save-match-data
6058 (and (string-match org-plain-link-re hl)
6059 (match-string-no-properties 2 hl))))
6060 (link-start (match-beginning 0))
6061 (link-end (match-end 0))
6062 (bracketp t)
6063 (help-echo (org-link-get-parameter type :help-echo))
6064 (help (cond
6065 ((stringp help-echo)
6066 help-echo)
6067 ((functionp help-echo)
6068 help-echo)
6070 (concat "LINK: "
6071 (save-match-data
6072 (org-link-unescape hl))))))
6073 (link-face (org-link-get-parameter type :face))
6074 (face (cond
6075 ;; A function that returns a face
6076 ((functionp link-face)
6077 (funcall link-face path))
6078 ;; a face
6079 ((facep link-face)
6080 link-face)
6081 ;; An anonymous face
6082 ((consp link-face)
6083 link-face)
6084 ;; default
6086 'org-link)))
6087 (keymap (or (org-link-get-parameter type :keymap)
6088 org-mouse-map))
6089 (mouse-face (or (org-link-get-parameter type :mouse-face)
6090 'highlight))
6091 (htmlize (org-link-get-parameter type :htmlize-link))
6092 (htmlize-link (cond
6093 ((functionp htmlize)
6094 (funcall htmlize))
6096 `(:uri ,(format "%s:%s" type path)))))
6097 (activate-func (org-link-get-parameter type :activate-func))
6098 ;; invisible part
6099 (ip (list 'invisible (or
6100 (org-link-get-parameter type :display)
6101 'org-link)
6102 'face face
6103 'keymap keymap
6104 'mouse-face mouse-face
6105 'font-lock-multiline t
6106 'help-echo help
6107 'htmlize-link htmlize-link))
6108 ;; visible part
6109 (vp (list 'keymap keymap
6110 'face face
6111 'mouse-face mouse-face
6112 'font-lock-multiline t
6113 'help-echo help
6114 'htmlize-link htmlize-link)))
6115 ;; We need to remove the invisible property here. Table narrowing
6116 ;; may have made some of this invisible.
6117 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6118 (remove-text-properties (match-beginning 0) (match-end 0)
6119 '(invisible nil))
6120 (if (match-end 3)
6121 (progn
6122 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6123 (org-rear-nonsticky-at (match-beginning 3))
6124 (add-text-properties (match-beginning 3) (match-end 3) vp)
6125 (org-rear-nonsticky-at (match-end 3))
6126 (add-text-properties (match-end 3) (match-end 0) ip)
6127 (org-rear-nonsticky-at (match-end 0)))
6128 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6129 (org-rear-nonsticky-at (match-beginning 1))
6130 (add-text-properties (match-beginning 1) (match-end 1) vp)
6131 (org-rear-nonsticky-at (match-end 1))
6132 (add-text-properties (match-end 1) (match-end 0) ip)
6133 (org-rear-nonsticky-at (match-end 0)))
6134 (when activate-func
6135 (funcall activate-func link-start link-end path bracketp))
6136 t)))
6138 (defun org-activate-dates (limit)
6139 "Add text properties for dates."
6140 (when (and (re-search-forward org-tsr-regexp-both limit t)
6141 (not (equal (char-before (match-beginning 0)) 91)))
6142 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6143 (add-text-properties (match-beginning 0) (match-end 0)
6144 (list 'mouse-face 'highlight
6145 'keymap org-mouse-map))
6146 (org-rear-nonsticky-at (match-end 0))
6147 (when org-display-custom-times
6148 (if (match-end 3)
6149 (org-display-custom-time (match-beginning 3) (match-end 3))
6150 (org-display-custom-time (match-beginning 1) (match-end 1))))
6153 (defvar-local org-target-link-regexp nil
6154 "Regular expression matching radio targets in plain text.")
6156 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6157 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6158 border border border))
6159 "Regular expression matching a link target.")
6161 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6162 "Regular expression matching a radio target.")
6164 (defconst org-any-target-regexp
6165 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6166 "Regular expression matching any target.")
6168 (defun org-activate-target-links (limit)
6169 "Add text properties for target matches."
6170 (when org-target-link-regexp
6171 (let ((case-fold-search t))
6172 (when (re-search-forward org-target-link-regexp limit t)
6173 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6174 (add-text-properties (match-beginning 1) (match-end 1)
6175 (list 'mouse-face 'highlight
6176 'keymap org-mouse-map
6177 'help-echo "Radio target link"
6178 'org-linked-text t))
6179 (org-rear-nonsticky-at (match-end 1))
6180 t))))
6182 (defun org-update-radio-target-regexp ()
6183 "Find all radio targets in this file and update the regular expression.
6184 Also refresh fontification if needed."
6185 (interactive)
6186 (let ((old-regexp org-target-link-regexp)
6187 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6188 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6189 (targets
6190 (org-with-wide-buffer
6191 (goto-char (point-min))
6192 (let (rtn)
6193 (while (re-search-forward org-radio-target-regexp nil t)
6194 ;; Make sure point is really within the object.
6195 (backward-char)
6196 (let ((obj (org-element-context)))
6197 (when (eq (org-element-type obj) 'radio-target)
6198 (cl-pushnew (org-element-property :value obj) rtn
6199 :test #'equal))))
6200 rtn))))
6201 (setq org-target-link-regexp
6202 (and targets
6203 (concat before-re
6204 (mapconcat
6205 (lambda (x)
6206 (replace-regexp-in-string
6207 " +" "\\s-+" (regexp-quote x) t t))
6208 targets
6209 "\\|")
6210 after-re)))
6211 (unless (equal old-regexp org-target-link-regexp)
6212 ;; Clean-up cache.
6213 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6214 ((not org-target-link-regexp) old-regexp)
6216 (concat before-re
6217 (mapconcat
6218 (lambda (re)
6219 (substring re (length before-re)
6220 (- (length after-re))))
6221 (list old-regexp org-target-link-regexp)
6222 "\\|")
6223 after-re)))))
6224 (org-with-wide-buffer
6225 (goto-char (point-min))
6226 (while (re-search-forward regexp nil t)
6227 (org-element-cache-refresh (match-beginning 1)))))
6228 ;; Re fontify buffer.
6229 (when (memq 'radio org-highlight-links)
6230 (org-restart-font-lock)))))
6232 (defun org-hide-wide-columns (limit)
6233 (let (s e)
6234 (setq s (text-property-any (point) (or limit (point-max))
6235 'org-cwidth t))
6236 (when s
6237 (setq e (next-single-property-change s 'org-cwidth))
6238 (add-text-properties s e '(invisible org-cwidth))
6239 (goto-char e)
6240 t)))
6242 (defvar org-latex-and-related-regexp nil
6243 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6245 (defun org-compute-latex-and-related-regexp ()
6246 "Compute regular expression for LaTeX, entities and sub/superscript.
6247 Result depends on variable `org-highlight-latex-and-related'."
6248 (setq-local
6249 org-latex-and-related-regexp
6250 (let* ((re-sub
6251 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6252 ((eq org-use-sub-superscripts '{})
6253 (list org-match-substring-with-braces-regexp))
6254 (org-use-sub-superscripts (list org-match-substring-regexp))))
6255 (re-latex
6256 (when (memq 'latex org-highlight-latex-and-related)
6257 (let ((matchers (plist-get org-format-latex-options :matchers)))
6258 (delq nil
6259 (mapcar (lambda (x)
6260 (and (member (car x) matchers) (nth 1 x)))
6261 org-latex-regexps)))))
6262 (re-entities
6263 (when (memq 'entities org-highlight-latex-and-related)
6264 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6265 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6267 (defun org-do-latex-and-related (limit)
6268 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6269 LIMIT bounds the search for syntax to highlight. Stop at first
6270 highlighted object, if any. Return t if some highlighting was
6271 done, nil otherwise."
6272 (when (org-string-nw-p org-latex-and-related-regexp)
6273 (catch 'found
6274 (while (re-search-forward org-latex-and-related-regexp limit t)
6275 (unless
6276 (cl-some
6277 (lambda (f)
6278 (memq f '(org-code org-verbatim underline org-special-keyword)))
6279 (save-excursion
6280 (goto-char (1+ (match-beginning 0)))
6281 (face-at-point nil t)))
6282 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6283 '(?_ ?^))
6285 0)))
6286 (font-lock-prepend-text-property
6287 (+ offset (match-beginning 0)) (match-end 0)
6288 'face 'org-latex-and-related)
6289 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6290 '(font-lock-multiline t)))
6291 (throw 'found t)))
6292 nil)))
6294 (defun org-restart-font-lock ()
6295 "Restart `font-lock-mode', to force refontification."
6296 (when (and (boundp 'font-lock-mode) font-lock-mode)
6297 (font-lock-mode -1)
6298 (font-lock-mode 1)))
6300 (defun org-activate-tags (limit)
6301 (when (re-search-forward
6302 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6303 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6304 (add-text-properties (match-beginning 1) (match-end 1)
6305 (list 'mouse-face 'highlight
6306 'keymap org-mouse-map))
6307 (org-rear-nonsticky-at (match-end 1))
6310 (defun org-outline-level ()
6311 "Compute the outline level of the heading at point.
6313 If this is called at a normal headline, the level is the number
6314 of stars. Use `org-reduced-level' to remove the effect of
6315 `org-odd-levels'. Unlike to `org-current-level', this function
6316 takes into consideration inlinetasks."
6317 (org-with-wide-buffer
6318 (end-of-line)
6319 (if (re-search-backward org-outline-regexp-bol nil t)
6320 (1- (- (match-end 0) (match-beginning 0)))
6321 0)))
6323 (defvar org-font-lock-keywords nil)
6325 (defsubst org-re-property (property &optional literal allow-null value)
6326 "Return a regexp matching a PROPERTY line.
6328 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6329 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6330 non-nil, match properties even without a value.
6332 Match group 3 is set to the value when it exists. If there is no
6333 value and ALLOW-NULL is non-nil, it is set to the empty string.
6335 With optional argument VALUE, match only property lines with
6336 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6337 unless LITERAL is non-nil."
6338 (concat
6339 "^\\(?4:[ \t]*\\)"
6340 (format "\\(?1::\\(?2:%s\\):\\)"
6341 (if literal property (regexp-quote property)))
6342 (cond (value
6343 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6344 (if literal value (regexp-quote value))))
6345 (allow-null
6346 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6348 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6350 (defconst org-property-re
6351 (org-re-property "\\S-+" 'literal t)
6352 "Regular expression matching a property line.
6353 There are four matching groups:
6354 1: :PROPKEY: including the leading and trailing colon,
6355 2: PROPKEY without the leading and trailing colon,
6356 3: PROPVAL without leading or trailing spaces,
6357 4: the indentation of the current line,
6358 5: trailing whitespace.")
6360 (defvar org-font-lock-hook nil
6361 "Functions to be called for special font lock stuff.")
6363 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6365 (defvar org-font-lock-set-keywords-hook nil
6366 "Functions that can manipulate `org-font-lock-extra-keywords'.
6367 This is called after `org-font-lock-extra-keywords' is defined, but before
6368 it is installed to be used by font lock. This can be useful if something
6369 needs to be inserted at a specific position in the font-lock sequence.")
6371 (defun org-font-lock-hook (limit)
6372 "Run `org-font-lock-hook' within LIMIT."
6373 (run-hook-with-args 'org-font-lock-hook limit))
6375 (defun org-set-font-lock-defaults ()
6376 "Set font lock defaults for the current buffer."
6377 (let* ((em org-fontify-emphasized-text)
6378 (lk org-highlight-links)
6379 (org-font-lock-extra-keywords
6380 (list
6381 ;; Call the hook
6382 '(org-font-lock-hook)
6383 ;; Headlines
6384 `(,(if org-fontify-whole-heading-line
6385 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6386 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6387 (1 (org-get-level-face 1))
6388 (2 (org-get-level-face 2))
6389 (3 (org-get-level-face 3)))
6390 ;; Table lines
6391 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6392 (1 'org-table t))
6393 ;; Table internals
6394 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6395 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6396 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6397 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6398 ;; Drawers
6399 '(org-fontify-drawers)
6400 ;; Properties
6401 (list org-property-re
6402 '(1 'org-special-keyword t)
6403 '(3 'org-property-value t))
6404 ;; Links
6405 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6406 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6407 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6408 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6409 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6410 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6411 (when (memq 'footnote lk) '(org-activate-footnote-links))
6412 ;; Targets.
6413 (list org-any-target-regexp '(0 'org-target t))
6414 ;; Diary sexps.
6415 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6416 ;; Macro
6417 '(org-fontify-macros)
6418 '(org-hide-wide-columns (0 nil append))
6419 ;; TODO keyword
6420 (list (format org-heading-keyword-regexp-format
6421 org-todo-regexp)
6422 '(2 (org-get-todo-face 2) t))
6423 ;; DONE
6424 (if org-fontify-done-headline
6425 (list (format org-heading-keyword-regexp-format
6426 (concat
6427 "\\(?:"
6428 (mapconcat 'regexp-quote org-done-keywords "\\|")
6429 "\\)"))
6430 '(2 'org-headline-done t))
6431 nil)
6432 ;; Priorities
6433 '(org-font-lock-add-priority-faces)
6434 ;; Tags
6435 '(org-font-lock-add-tag-faces)
6436 ;; Tags groups
6437 (when (and org-group-tags org-tag-groups-alist)
6438 (list (concat org-outline-regexp-bol ".+\\(:"
6439 (regexp-opt (mapcar 'car org-tag-groups-alist))
6440 ":\\).*$")
6441 '(1 'org-tag-group prepend)))
6442 ;; Special keywords
6443 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6444 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6445 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6446 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6447 ;; Emphasis
6448 (when em '(org-do-emphasis-faces))
6449 ;; Checkboxes
6450 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6451 1 'org-checkbox prepend)
6452 (when (cdr (assq 'checkbox org-list-automatic-rules))
6453 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6454 (0 (org-get-checkbox-statistics-face) t)))
6455 ;; Description list items
6456 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6457 1 'org-list-dt prepend)
6458 ;; ARCHIVEd headings
6459 (list (concat
6460 org-outline-regexp-bol
6461 "\\(.*:" org-archive-tag ":.*\\)")
6462 '(1 'org-archived prepend))
6463 ;; Specials
6464 '(org-do-latex-and-related)
6465 '(org-fontify-entities)
6466 '(org-raise-scripts)
6467 ;; Code
6468 '(org-activate-code (1 'org-code t))
6469 ;; COMMENT
6470 (list (format
6471 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6472 org-todo-regexp
6473 org-comment-string)
6474 '(9 'org-special-keyword t))
6475 ;; Blocks and meta lines
6476 '(org-fontify-meta-lines-and-blocks))))
6477 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6478 (run-hooks 'org-font-lock-set-keywords-hook)
6479 ;; Now set the full font-lock-keywords
6480 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6481 (setq-local font-lock-defaults
6482 '(org-font-lock-keywords t nil nil backward-paragraph))
6483 (kill-local-variable 'font-lock-keywords)
6484 nil))
6486 (defun org-toggle-pretty-entities ()
6487 "Toggle the composition display of entities as UTF8 characters."
6488 (interactive)
6489 (setq-local org-pretty-entities (not org-pretty-entities))
6490 (org-restart-font-lock)
6491 (if org-pretty-entities
6492 (message "Entities are now displayed as UTF8 characters")
6493 (save-restriction
6494 (widen)
6495 (decompose-region (point-min) (point-max))
6496 (message "Entities are now displayed as plain text"))))
6498 (defvar-local org-custom-properties-overlays nil
6499 "List of overlays used for custom properties.")
6501 (defun org-toggle-custom-properties-visibility ()
6502 "Display or hide properties in `org-custom-properties'."
6503 (interactive)
6504 (if org-custom-properties-overlays
6505 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6506 (setq org-custom-properties-overlays nil))
6507 (when org-custom-properties
6508 (org-with-wide-buffer
6509 (goto-char (point-min))
6510 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6511 (while (re-search-forward regexp nil t)
6512 (let ((end (cdr (save-match-data (org-get-property-block)))))
6513 (when (and end (< (point) end))
6514 ;; Hide first custom property in current drawer.
6515 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6516 (overlay-put o 'invisible t)
6517 (overlay-put o 'org-custom-property t)
6518 (push o org-custom-properties-overlays))
6519 ;; Hide additional custom properties in the same drawer.
6520 (while (re-search-forward regexp end t)
6521 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6522 (overlay-put o 'invisible t)
6523 (overlay-put o 'org-custom-property t)
6524 (push o org-custom-properties-overlays)))))
6525 ;; Each entry is limited to a single property drawer.
6526 (outline-next-heading)))))))
6528 (defun org-fontify-entities (limit)
6529 "Find an entity to fontify."
6530 (let (ee)
6531 (when org-pretty-entities
6532 (catch 'match
6533 ;; "\_ "-family is left out on purpose. Only the first one,
6534 ;; i.e., "\_ ", could be fontified anyway, and it would be
6535 ;; confusing when adding a second white space character.
6536 (while (re-search-forward
6537 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6538 limit t)
6539 (when (and (not (org-at-comment-p))
6540 (setq ee (org-entity-get (match-string 1)))
6541 (= (length (nth 6 ee)) 1))
6542 (let* ((end (if (equal (match-string 2) "{}")
6543 (match-end 2)
6544 (match-end 1))))
6545 (add-text-properties
6546 (match-beginning 0) end
6547 (list 'font-lock-fontified t))
6548 (compose-region (match-beginning 0) end
6549 (nth 6 ee) nil)
6550 (backward-char 1)
6551 (throw 'match t))))
6552 nil))))
6554 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6555 "Fontify string S like in Org mode."
6556 (with-temp-buffer
6557 (insert s)
6558 (let ((org-odd-levels-only odd-levels))
6559 (org-mode)
6560 (org-font-lock-ensure)
6561 (buffer-string))))
6563 (defvar org-m nil)
6564 (defvar org-l nil)
6565 (defvar org-f nil)
6566 (defun org-get-level-face (n)
6567 "Get the right face for match N in font-lock matching of headlines."
6568 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6569 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6570 (if org-cycle-level-faces
6571 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6572 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6573 (cond
6574 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6575 ((eq n 2) org-f)
6576 (t (unless org-level-color-stars-only org-f))))
6578 (defun org-face-from-face-or-color (context inherit face-or-color)
6579 "Create a face list that inherits INHERIT, but sets the foreground color.
6580 When FACE-OR-COLOR is not a string, just return it."
6581 (if (stringp face-or-color)
6582 (list :inherit inherit
6583 (cdr (assoc context org-faces-easy-properties))
6584 face-or-color)
6585 face-or-color))
6587 (defun org-get-todo-face (kwd)
6588 "Get the right face for a TODO keyword KWD.
6589 If KWD is a number, get the corresponding match group."
6590 (when (numberp kwd) (setq kwd (match-string kwd)))
6591 (or (org-face-from-face-or-color
6592 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6593 (and (member kwd org-done-keywords) 'org-done)
6594 'org-todo))
6596 (defun org-get-priority-face (priority)
6597 "Get the right face for PRIORITY.
6598 PRIORITY is a character."
6599 (or (org-face-from-face-or-color
6600 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6601 'org-priority))
6603 (defun org-get-tag-face (tag)
6604 "Get the right face for TAG.
6605 If TAG is a number, get the corresponding match group."
6606 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6607 (or (org-face-from-face-or-color
6608 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6609 'org-tag)))
6611 (defun org-font-lock-add-priority-faces (limit)
6612 "Add the special priority faces."
6613 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6614 (add-text-properties
6615 (match-beginning 1) (match-end 1)
6616 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6617 'font-lock-fontified t))))
6619 (defun org-font-lock-add-tag-faces (limit)
6620 "Add the special tag faces."
6621 (when (and org-tag-faces org-tags-special-faces-re)
6622 (while (re-search-forward org-tags-special-faces-re limit t)
6623 (add-text-properties (match-beginning 1) (match-end 1)
6624 (list 'face (org-get-tag-face 1)
6625 'font-lock-fontified t))
6626 (backward-char 1))))
6628 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6629 "Remove fontification and activation overlays from links."
6630 (font-lock-default-unfontify-region beg end)
6631 (let* ((buffer-undo-list t)
6632 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6633 (inhibit-modification-hooks t)
6634 deactivate-mark buffer-file-name buffer-file-truename)
6635 (decompose-region beg end)
6636 (remove-text-properties beg end
6637 '(mouse-face t keymap t org-linked-text t
6638 invisible t intangible t
6639 org-emphasis t))
6640 (org-remove-font-lock-display-properties beg end)))
6642 (defconst org-script-display '(((raise -0.3) (height 0.7))
6643 ((raise 0.3) (height 0.7))
6644 ((raise -0.5))
6645 ((raise 0.5)))
6646 "Display properties for showing superscripts and subscripts.")
6648 (defun org-remove-font-lock-display-properties (beg end)
6649 "Remove specific display properties that have been added by font lock.
6650 The will remove the raise properties that are used to show superscripts
6651 and subscripts."
6652 (let (next prop)
6653 (while (< beg end)
6654 (setq next (next-single-property-change beg 'display nil end)
6655 prop (get-text-property beg 'display))
6656 (when (member prop org-script-display)
6657 (put-text-property beg next 'display nil))
6658 (setq beg next))))
6660 (defun org-raise-scripts (limit)
6661 "Add raise properties to sub/superscripts."
6662 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6663 (re-search-forward
6664 (if (eq org-use-sub-superscripts t)
6665 org-match-substring-regexp
6666 org-match-substring-with-braces-regexp)
6667 limit t))
6668 (let* ((pos (point)) table-p comment-p
6669 (mpos (match-beginning 3))
6670 (emph-p (get-text-property mpos 'org-emphasis))
6671 (link-p (get-text-property mpos 'mouse-face))
6672 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6673 (goto-char (point-at-bol))
6674 (setq table-p (looking-at-p org-table-dataline-regexp)
6675 comment-p (looking-at-p "^[ \t]*#[ +]"))
6676 (goto-char pos)
6677 ;; Handle a_b^c
6678 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6679 (unless (or comment-p emph-p link-p keyw-p)
6680 (put-text-property (match-beginning 3) (match-end 0)
6681 'display
6682 (if (equal (char-after (match-beginning 2)) ?^)
6683 (nth (if table-p 3 1) org-script-display)
6684 (nth (if table-p 2 0) org-script-display)))
6685 (add-text-properties (match-beginning 2) (match-end 2)
6686 (list 'invisible t
6687 'org-dwidth t 'org-dwidth-n 1))
6688 (if (and (eq (char-after (match-beginning 3)) ?{)
6689 (eq (char-before (match-end 3)) ?}))
6690 (progn
6691 (add-text-properties
6692 (match-beginning 3) (1+ (match-beginning 3))
6693 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6694 (add-text-properties
6695 (1- (match-end 3)) (match-end 3)
6696 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6697 t)))
6699 ;;;; Visibility cycling, including org-goto and indirect buffer
6701 ;;; Cycling
6703 (defvar-local org-cycle-global-status nil)
6704 (put 'org-cycle-global-status 'org-state t)
6705 (defvar-local org-cycle-subtree-status nil)
6706 (put 'org-cycle-subtree-status 'org-state t)
6708 (defvar org-inlinetask-min-level)
6710 (defun org-unlogged-message (&rest args)
6711 "Display a message, but avoid logging it in the *Messages* buffer."
6712 (let ((message-log-max nil))
6713 (apply 'message args)))
6715 ;;;###autoload
6716 (defun org-cycle (&optional arg)
6717 "TAB-action and visibility cycling for Org mode.
6719 This is the command invoked in Org mode by the `TAB' key. Its main
6720 purpose is outline visibility cycling, but it also invokes other actions
6721 in special contexts.
6723 When this function is called with a `\\[universal-argument]' prefix, rotate \
6724 the entire
6725 buffer through 3 states (global cycling)
6726 1. OVERVIEW: Show only top-level headlines.
6727 2. CONTENTS: Show all headlines of all levels, but no body text.
6728 3. SHOW ALL: Show everything.
6730 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6731 switch to the startup visibility,
6732 determined by the variable `org-startup-folded', and by any VISIBILITY
6733 properties in the buffer.
6735 With a `\\[universal-argument] \\[universal-argument] \
6736 \\[universal-argument]' prefix argument, show the entire buffer, including
6737 any drawers.
6739 When inside a table, re-align the table and move to the next field.
6741 When point is at the beginning of a headline, rotate the subtree started
6742 by this line through 3 different states (local cycling)
6743 1. FOLDED: Only the main headline is shown.
6744 2. CHILDREN: The main headline and the direct children are shown.
6745 From this state, you can move to one of the children
6746 and zoom in further.
6747 3. SUBTREE: Show the entire subtree, including body text.
6748 If there is no subtree, switch directly from CHILDREN to FOLDED.
6750 When point is at the beginning of an empty headline and the variable
6751 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6752 of the headline by demoting and promoting it to likely levels. This
6753 speeds up creation document structure by pressing `TAB' once or several
6754 times right after creating a new headline.
6756 When there is a numeric prefix, go up to a heading with level ARG, do
6757 a `show-subtree' and return to the previous cursor position. If ARG
6758 is negative, go up that many levels.
6760 When point is not at the beginning of a headline, execute the global
6761 binding for `TAB', which is re-indenting the line. See the option
6762 `org-cycle-emulate-tab' for details.
6764 As a special case, if point is at the beginning of the buffer and there is
6765 no headline in line 1, this function will act as if called with prefix arg
6766 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6767 prefix arg, but only
6768 if the variable `org-cycle-global-at-bob' is t."
6769 (interactive "P")
6770 (org-load-modules-maybe)
6771 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6772 (and org-cycle-level-after-item/entry-creation
6773 (or (org-cycle-level)
6774 (org-cycle-item-indentation))))
6775 (let* ((limit-level
6776 (or org-cycle-max-level
6777 (and (boundp 'org-inlinetask-min-level)
6778 org-inlinetask-min-level
6779 (1- org-inlinetask-min-level))))
6780 (nstars (and limit-level
6781 (if org-odd-levels-only
6782 (and limit-level (1- (* limit-level 2)))
6783 limit-level)))
6784 (org-outline-regexp
6785 (if (not (derived-mode-p 'org-mode))
6786 outline-regexp
6787 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6788 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6789 (not (looking-at org-outline-regexp))))
6790 (org-cycle-hook
6791 (if bob-special
6792 (delq 'org-optimize-window-after-visibility-change
6793 (copy-sequence org-cycle-hook))
6794 org-cycle-hook))
6795 (pos (point)))
6797 (cond
6799 ((equal arg '(16))
6800 (setq last-command 'dummy)
6801 (org-set-startup-visibility)
6802 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6804 ((equal arg '(64))
6805 (outline-show-all)
6806 (org-unlogged-message "Entire buffer visible, including drawers"))
6808 ((equal arg '(4)) (org-cycle-internal-global))
6810 ;; Try hiding block at point.
6811 ((org-hide-block-toggle-maybe))
6813 ;; Try cdlatex TAB completion
6814 ((org-try-cdlatex-tab))
6816 ;; Table: enter it or move to the next field.
6817 ((org-at-table-p 'any)
6818 (if (org-at-table.el-p)
6819 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6820 Use `\\[org-edit-special]' to edit table.el tables"))
6821 (if arg (org-table-edit-field t)
6822 (org-table-justify-field-maybe)
6823 (call-interactively 'org-table-next-field))))
6825 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6827 ;; Global cycling: delegate to `org-cycle-internal-global'.
6828 (bob-special (org-cycle-internal-global))
6830 ;; Drawers: delegate to `org-flag-drawer'.
6831 ((save-excursion
6832 (beginning-of-line 1)
6833 (looking-at org-drawer-regexp))
6834 (org-flag-drawer ; toggle block visibility
6835 (not (get-char-property (match-end 0) 'invisible))))
6837 ;; Show-subtree, ARG levels up from here.
6838 ((integerp arg)
6839 (save-excursion
6840 (org-back-to-heading)
6841 (outline-up-heading (if (< arg 0) (- arg)
6842 (- (funcall outline-level) arg)))
6843 (org-show-subtree)))
6845 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6846 ((and (featurep 'org-inlinetask)
6847 (org-inlinetask-at-task-p)
6848 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6849 (org-inlinetask-toggle-visibility))
6851 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6852 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6853 (save-excursion (move-beginning-of-line 1)
6854 (looking-at org-outline-regexp)))
6855 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6856 (org-cycle-internal-local))
6858 ;; From there: TAB emulation and template completion.
6859 (buffer-read-only (org-back-to-heading))
6861 ((run-hook-with-args-until-success
6862 'org-tab-after-check-for-cycling-hook))
6864 ((org-try-structure-completion))
6866 ((run-hook-with-args-until-success
6867 'org-tab-before-tab-emulation-hook))
6869 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6870 (or (not (bolp))
6871 (not (looking-at org-outline-regexp))))
6872 (call-interactively (global-key-binding "\t")))
6874 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6875 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6876 (or (and (eq org-cycle-emulate-tab 'white)
6877 (= (match-end 0) (point-at-eol)))
6878 (and (eq org-cycle-emulate-tab 'whitestart)
6879 (>= (match-end 0) pos))))
6881 (eq org-cycle-emulate-tab t))
6882 (call-interactively (global-key-binding "\t")))
6884 (t (save-excursion
6885 (org-back-to-heading)
6886 (org-cycle)))))))
6888 (defun org-cycle-internal-global ()
6889 "Do the global cycling action."
6890 ;; Hack to avoid display of messages for .org attachments in Gnus
6891 (let ((ga (string-match "\\*fontification" (buffer-name))))
6892 (cond
6893 ((and (eq last-command this-command)
6894 (eq org-cycle-global-status 'overview))
6895 ;; We just created the overview - now do table of contents
6896 ;; This can be slow in very large buffers, so indicate action
6897 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6898 (unless ga (org-unlogged-message "CONTENTS..."))
6899 (org-content)
6900 (unless ga (org-unlogged-message "CONTENTS...done"))
6901 (setq org-cycle-global-status 'contents)
6902 (run-hook-with-args 'org-cycle-hook 'contents))
6904 ((and (eq last-command this-command)
6905 (eq org-cycle-global-status 'contents))
6906 ;; We just showed the table of contents - now show everything
6907 (run-hook-with-args 'org-pre-cycle-hook 'all)
6908 (outline-show-all)
6909 (unless ga (org-unlogged-message "SHOW ALL"))
6910 (setq org-cycle-global-status 'all)
6911 (run-hook-with-args 'org-cycle-hook 'all))
6914 ;; Default action: go to overview
6915 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6916 (org-overview)
6917 (unless ga (org-unlogged-message "OVERVIEW"))
6918 (setq org-cycle-global-status 'overview)
6919 (run-hook-with-args 'org-cycle-hook 'overview)))))
6921 (defvar org-called-with-limited-levels nil
6922 "Non-nil when `org-with-limited-levels' is currently active.")
6924 (defun org-cycle-internal-local ()
6925 "Do the local cycling action."
6926 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6927 ;; First, determine end of headline (EOH), end of subtree or item
6928 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6929 (save-excursion
6930 (if (org-at-item-p)
6931 (progn
6932 (beginning-of-line)
6933 (setq struct (org-list-struct))
6934 (setq eoh (point-at-eol))
6935 (setq eos (org-list-get-item-end-before-blank (point) struct))
6936 (setq has-children (org-list-has-child-p (point) struct)))
6937 (org-back-to-heading)
6938 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6939 (setq eos (save-excursion (org-end-of-subtree t t)
6940 (when (bolp) (backward-char)) (point)))
6941 (setq has-children
6942 (or (save-excursion
6943 (let ((level (funcall outline-level)))
6944 (outline-next-heading)
6945 (and (org-at-heading-p t)
6946 (> (funcall outline-level) level))))
6947 (save-excursion
6948 (org-list-search-forward (org-item-beginning-re) eos t)))))
6949 ;; Determine end invisible part of buffer (EOL)
6950 (beginning-of-line 2)
6951 (while (and (not (eobp)) ;This is like `next-line'.
6952 (get-char-property (1- (point)) 'invisible))
6953 (goto-char (next-single-char-property-change (point) 'invisible))
6954 (and (eolp) (beginning-of-line 2)))
6955 (setq eol (point)))
6956 ;; Find out what to do next and set `this-command'
6957 (cond
6958 ((= eos eoh)
6959 ;; Nothing is hidden behind this heading
6960 (unless (org-before-first-heading-p)
6961 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6962 (org-unlogged-message "EMPTY ENTRY")
6963 (setq org-cycle-subtree-status nil)
6964 (save-excursion
6965 (goto-char eos)
6966 (outline-next-heading)
6967 (when (outline-invisible-p) (org-flag-heading nil))))
6968 ((and (or (>= eol eos)
6969 (not (string-match "\\S-" (buffer-substring eol eos))))
6970 (or has-children
6971 (not (setq children-skipped
6972 org-cycle-skip-children-state-if-no-children))))
6973 ;; Entire subtree is hidden in one line: children view
6974 (unless (org-before-first-heading-p)
6975 (run-hook-with-args 'org-pre-cycle-hook 'children))
6976 (if (org-at-item-p)
6977 (org-list-set-item-visibility (point-at-bol) struct 'children)
6978 (org-show-entry)
6979 (org-with-limited-levels (org-show-children))
6980 ;; FIXME: This slows down the func way too much.
6981 ;; How keep drawers hidden in subtree anyway?
6982 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6983 ;; (org-cycle-hide-drawers 'subtree))
6985 ;; Fold every list in subtree to top-level items.
6986 (when (eq org-cycle-include-plain-lists 'integrate)
6987 (save-excursion
6988 (org-back-to-heading)
6989 (while (org-list-search-forward (org-item-beginning-re) eos t)
6990 (beginning-of-line 1)
6991 (let* ((struct (org-list-struct))
6992 (prevs (org-list-prevs-alist struct))
6993 (end (org-list-get-bottom-point struct)))
6994 (dolist (e (org-list-get-all-items (point) struct prevs))
6995 (org-list-set-item-visibility e struct 'folded))
6996 (goto-char (if (< end eos) end eos)))))))
6997 (org-unlogged-message "CHILDREN")
6998 (save-excursion
6999 (goto-char eos)
7000 (outline-next-heading)
7001 (when (outline-invisible-p) (org-flag-heading nil)))
7002 (setq org-cycle-subtree-status 'children)
7003 (unless (org-before-first-heading-p)
7004 (run-hook-with-args 'org-cycle-hook 'children)))
7005 ((or children-skipped
7006 (and (eq last-command this-command)
7007 (eq org-cycle-subtree-status 'children)))
7008 ;; We just showed the children, or no children are there,
7009 ;; now show everything.
7010 (unless (org-before-first-heading-p)
7011 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7012 (outline-flag-region eoh eos nil)
7013 (org-unlogged-message
7014 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7015 (setq org-cycle-subtree-status 'subtree)
7016 (unless (org-before-first-heading-p)
7017 (run-hook-with-args 'org-cycle-hook 'subtree)))
7019 ;; Default action: hide the subtree.
7020 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7021 (outline-flag-region eoh eos t)
7022 (org-unlogged-message "FOLDED")
7023 (setq org-cycle-subtree-status 'folded)
7024 (unless (org-before-first-heading-p)
7025 (run-hook-with-args 'org-cycle-hook 'folded))))))
7027 ;;;###autoload
7028 (defun org-global-cycle (&optional arg)
7029 "Cycle the global visibility. For details see `org-cycle'.
7030 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7031 With a numeric prefix, show all headlines up to that level."
7032 (interactive "P")
7033 (let ((org-cycle-include-plain-lists
7034 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7035 (cond
7036 ((integerp arg)
7037 (outline-show-all)
7038 (outline-hide-sublevels arg)
7039 (setq org-cycle-global-status 'contents))
7040 ((equal arg '(4))
7041 (org-set-startup-visibility)
7042 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7044 (org-cycle '(4))))))
7046 (defun org-set-startup-visibility ()
7047 "Set the visibility required by startup options and properties."
7048 (cond
7049 ((eq org-startup-folded t)
7050 (org-overview))
7051 ((eq org-startup-folded 'content)
7052 (org-content))
7053 ((or (eq org-startup-folded 'showeverything)
7054 (eq org-startup-folded nil))
7055 (outline-show-all)))
7056 (unless (eq org-startup-folded 'showeverything)
7057 (when org-hide-block-startup (org-hide-block-all))
7058 (org-set-visibility-according-to-property 'no-cleanup)
7059 (org-cycle-hide-archived-subtrees 'all)
7060 (org-cycle-hide-drawers 'all)
7061 (org-cycle-show-empty-lines t)))
7063 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7064 "Switch subtree visibilities according to :VISIBILITY: property."
7065 (interactive)
7066 (org-with-wide-buffer
7067 (goto-char (point-min))
7068 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7069 (if (not (org-at-property-p)) (outline-next-heading)
7070 (let ((state (match-string 3)))
7071 (save-excursion
7072 (org-back-to-heading t)
7073 (outline-hide-subtree)
7074 (org-reveal)
7075 (cond
7076 ((equal state "folded")
7077 (outline-hide-subtree))
7078 ((equal state "children")
7079 (org-show-hidden-entry)
7080 (org-show-children))
7081 ((equal state "content")
7082 (save-excursion
7083 (save-restriction
7084 (org-narrow-to-subtree)
7085 (org-content))))
7086 ((member state '("all" "showall"))
7087 (outline-show-subtree)))))))
7088 (unless no-cleanup
7089 (org-cycle-hide-archived-subtrees 'all)
7090 (org-cycle-hide-drawers 'all)
7091 (org-cycle-show-empty-lines 'all))))
7093 ;; This function uses outline-regexp instead of the more fundamental
7094 ;; org-outline-regexp so that org-cycle-global works outside of Org
7095 ;; buffers, where outline-regexp is needed.
7096 (defun org-overview ()
7097 "Switch to overview mode, showing only top-level headlines.
7098 This shows all headlines with a level equal or greater than the level
7099 of the first headline in the buffer. This is important, because if the
7100 first headline is not level one, then (hide-sublevels 1) gives confusing
7101 results."
7102 (interactive)
7103 (save-excursion
7104 (let ((level
7105 (save-excursion
7106 (goto-char (point-min))
7107 (when (re-search-forward (concat "^" outline-regexp) nil t)
7108 (goto-char (match-beginning 0))
7109 (funcall outline-level)))))
7110 (and level (outline-hide-sublevels level)))))
7112 (defun org-content (&optional arg)
7113 "Show all headlines in the buffer, like a table of contents.
7114 With numerical argument N, show content up to level N."
7115 (interactive "P")
7116 (org-overview)
7117 (save-excursion
7118 ;; Visit all headings and show their offspring
7119 (and (integerp arg) (org-overview))
7120 (goto-char (point-max))
7121 (catch 'exit
7122 (while (and (progn (condition-case nil
7123 (outline-previous-visible-heading 1)
7124 (error (goto-char (point-min))))
7126 (looking-at org-outline-regexp))
7127 (if (integerp arg)
7128 (org-show-children (1- arg))
7129 (outline-show-branches))
7130 (when (bobp) (throw 'exit nil))))))
7132 (defun org-optimize-window-after-visibility-change (state)
7133 "Adjust the window after a change in outline visibility.
7134 This function is the default value of the hook `org-cycle-hook'."
7135 (when (get-buffer-window (current-buffer))
7136 (cond
7137 ((eq state 'content) nil)
7138 ((eq state 'all) nil)
7139 ((eq state 'folded) nil)
7140 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7141 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7143 (defun org-remove-empty-overlays-at (pos)
7144 "Remove outline overlays that do not contain non-white stuff."
7145 (dolist (o (overlays-at pos))
7146 (and (eq 'outline (overlay-get o 'invisible))
7147 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7148 (overlay-end o))))
7149 (delete-overlay o))))
7151 (defun org-clean-visibility-after-subtree-move ()
7152 "Fix visibility issues after moving a subtree."
7153 ;; First, find a reasonable region to look at:
7154 ;; Start two siblings above, end three below
7155 (let* ((beg (save-excursion
7156 (and (org-get-last-sibling)
7157 (org-get-last-sibling))
7158 (point)))
7159 (end (save-excursion
7160 (and (org-get-next-sibling)
7161 (org-get-next-sibling)
7162 (org-get-next-sibling))
7163 (if (org-at-heading-p)
7164 (point-at-eol)
7165 (point))))
7166 (level (looking-at "\\*+"))
7167 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7168 (save-excursion
7169 (save-restriction
7170 (narrow-to-region beg end)
7171 (when re
7172 ;; Properly fold already folded siblings
7173 (goto-char (point-min))
7174 (while (re-search-forward re nil t)
7175 (when (and (not (outline-invisible-p))
7176 (save-excursion
7177 (goto-char (point-at-eol)) (outline-invisible-p)))
7178 (outline-hide-entry))))
7179 (org-cycle-show-empty-lines 'overview)
7180 (org-cycle-hide-drawers 'overview)))))
7182 (defun org-cycle-show-empty-lines (state)
7183 "Show empty lines above all visible headlines.
7184 The region to be covered depends on STATE when called through
7185 `org-cycle-hook'. Lisp program can use t for STATE to get the
7186 entire buffer covered. Note that an empty line is only shown if there
7187 are at least `org-cycle-separator-lines' empty lines before the headline."
7188 (when (/= org-cycle-separator-lines 0)
7189 (save-excursion
7190 (let* ((n (abs org-cycle-separator-lines))
7191 (re (cond
7192 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7193 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7194 (t (let ((ns (number-to-string (- n 2))))
7195 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7196 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7197 beg end)
7198 (cond
7199 ((memq state '(overview contents t))
7200 (setq beg (point-min) end (point-max)))
7201 ((memq state '(children folded))
7202 (setq beg (point)
7203 end (progn (org-end-of-subtree t t)
7204 (line-beginning-position 2)))))
7205 (when beg
7206 (goto-char beg)
7207 (while (re-search-forward re end t)
7208 (unless (get-char-property (match-end 1) 'invisible)
7209 (let ((e (match-end 1))
7210 (b (if (>= org-cycle-separator-lines 0)
7211 (match-beginning 1)
7212 (save-excursion
7213 (goto-char (match-beginning 0))
7214 (skip-chars-backward " \t\n")
7215 (line-end-position)))))
7216 (outline-flag-region b e nil))))))))
7217 ;; Never hide empty lines at the end of the file.
7218 (save-excursion
7219 (goto-char (point-max))
7220 (outline-previous-heading)
7221 (outline-end-of-heading)
7222 (when (and (looking-at "[ \t\n]+")
7223 (= (match-end 0) (point-max)))
7224 (outline-flag-region (point) (match-end 0) nil))))
7226 (defun org-show-empty-lines-in-parent ()
7227 "Move to the parent and re-show empty lines before visible headlines."
7228 (save-excursion
7229 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7230 (org-cycle-show-empty-lines context))))
7232 (defun org-files-list ()
7233 "Return `org-agenda-files' list, plus all open Org files.
7234 This is useful for operations that need to scan all of a user's
7235 open and agenda-wise Org files."
7236 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7237 (dolist (buf (buffer-list))
7238 (with-current-buffer buf
7239 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7240 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7241 files))
7243 (defsubst org-entry-beginning-position ()
7244 "Return the beginning position of the current entry."
7245 (save-excursion (org-back-to-heading t) (point)))
7247 (defsubst org-entry-end-position ()
7248 "Return the end position of the current entry."
7249 (save-excursion (outline-next-heading) (point)))
7251 (defun org-cycle-hide-drawers (state &optional exceptions)
7252 "Re-hide all drawers after a visibility state change.
7253 When non-nil, optional argument EXCEPTIONS is a list of strings
7254 specifying which drawers should not be hidden."
7255 (when (and (derived-mode-p 'org-mode)
7256 (not (memq state '(overview folded contents))))
7257 (save-excursion
7258 (let* ((globalp (memq state '(contents all)))
7259 (beg (if globalp (point-min) (point)))
7260 (end (if globalp (point-max)
7261 (if (eq state 'children)
7262 (save-excursion (outline-next-heading) (point))
7263 (org-end-of-subtree t)))))
7264 (goto-char beg)
7265 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7266 (unless (member-ignore-case (match-string 1) exceptions)
7267 (let ((drawer (org-element-at-point)))
7268 (when (memq (org-element-type drawer) '(drawer property-drawer))
7269 (org-flag-drawer t drawer)
7270 ;; Make sure to skip drawer entirely or we might flag
7271 ;; it another time when matching its ending line with
7272 ;; `org-drawer-regexp'.
7273 (goto-char (org-element-property :end drawer))))))))))
7275 (defun org-flag-drawer (flag &optional element)
7276 "When FLAG is non-nil, hide the drawer we are at.
7277 Otherwise make it visible. When optional argument ELEMENT is
7278 a parsed drawer, as returned by `org-element-at-point', hide or
7279 show that drawer instead."
7280 (let ((drawer (or element
7281 (and (save-excursion
7282 (beginning-of-line)
7283 (looking-at-p org-drawer-regexp))
7284 (org-element-at-point)))))
7285 (when (memq (org-element-type drawer) '(drawer property-drawer))
7286 (let ((post (org-element-property :post-affiliated drawer)))
7287 (save-excursion
7288 (outline-flag-region
7289 (progn (goto-char post) (line-end-position))
7290 (progn (goto-char (org-element-property :end drawer))
7291 (skip-chars-backward " \r\t\n")
7292 (line-end-position))
7293 flag))
7294 ;; When the drawer is hidden away, make sure point lies in
7295 ;; a visible part of the buffer.
7296 (when (and flag (> (line-beginning-position) post))
7297 (goto-char post))))))
7299 (defun org-subtree-end-visible-p ()
7300 "Is the end of the current subtree visible?"
7301 (pos-visible-in-window-p
7302 (save-excursion (org-end-of-subtree t) (point))))
7304 (defun org-first-headline-recenter ()
7305 "Move cursor to the first headline and recenter the headline."
7306 (let ((window (get-buffer-window)))
7307 (when window
7308 (goto-char (point-min))
7309 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7310 (set-window-start window (line-beginning-position))))))
7312 ;;; Saving and restoring visibility
7314 (defun org-outline-overlay-data (&optional use-markers)
7315 "Return a list of the locations of all outline overlays.
7316 These are overlays with the `invisible' property value `outline'.
7317 The return value is a list of cons cells, with start and stop
7318 positions for each overlay.
7319 If USE-MARKERS is set, return the positions as markers."
7320 (let (beg end)
7321 (org-with-wide-buffer
7322 (delq nil
7323 (mapcar (lambda (o)
7324 (when (eq (overlay-get o 'invisible) 'outline)
7325 (setq beg (overlay-start o)
7326 end (overlay-end o))
7327 (and beg end (> end beg)
7328 (if use-markers
7329 (cons (copy-marker beg)
7330 (copy-marker end t))
7331 (cons beg end)))))
7332 (overlays-in (point-min) (point-max)))))))
7334 (defun org-set-outline-overlay-data (data)
7335 "Create visibility overlays for all positions in DATA.
7336 DATA should have been made by `org-outline-overlay-data'."
7337 (org-with-wide-buffer
7338 (outline-show-all)
7339 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7341 ;;; Folding of blocks
7343 (defvar-local org-hide-block-overlays nil
7344 "Overlays hiding blocks.")
7346 (defun org-block-map (function &optional start end)
7347 "Call FUNCTION at the head of all source blocks in the current buffer.
7348 Optional arguments START and END can be used to limit the range."
7349 (let ((start (or start (point-min)))
7350 (end (or end (point-max))))
7351 (save-excursion
7352 (goto-char start)
7353 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7354 (save-excursion
7355 (save-match-data
7356 (goto-char (match-beginning 0))
7357 (funcall function)))))))
7359 (defun org-hide-block-toggle-all ()
7360 "Toggle the visibility of all blocks in the current buffer."
7361 (org-block-map 'org-hide-block-toggle))
7363 (defun org-hide-block-all ()
7364 "Fold all blocks in the current buffer."
7365 (interactive)
7366 (org-show-block-all)
7367 (org-block-map 'org-hide-block-toggle-maybe))
7369 (defun org-show-block-all ()
7370 "Unfold all blocks in the current buffer."
7371 (interactive)
7372 (mapc #'delete-overlay org-hide-block-overlays)
7373 (setq org-hide-block-overlays nil))
7375 (defun org-hide-block-toggle-maybe ()
7376 "Toggle visibility of block at point.
7377 Unlike to `org-hide-block-toggle', this function does not throw
7378 an error. Return a non-nil value when toggling is successful."
7379 (interactive)
7380 (ignore-errors (org-hide-block-toggle)))
7382 (defun org-hide-block-toggle (&optional force)
7383 "Toggle the visibility of the current block.
7384 When optional argument FORCE is `off', make block visible. If it
7385 is non-nil, hide it unconditionally. Throw an error when not at
7386 a block. Return a non-nil value when toggling is successful."
7387 (interactive)
7388 (let ((element (org-element-at-point)))
7389 (unless (memq (org-element-type element)
7390 '(center-block comment-block dynamic-block example-block
7391 export-block quote-block special-block
7392 src-block verse-block))
7393 (user-error "Not at a block"))
7394 (let* ((start (save-excursion
7395 (goto-char (org-element-property :post-affiliated element))
7396 (line-end-position)))
7397 (end (save-excursion
7398 (goto-char (org-element-property :end element))
7399 (skip-chars-backward " \r\t\n")
7400 (line-end-position)))
7401 (overlays (overlays-at start)))
7402 (cond
7403 ;; Do nothing when not before or at the block opening line or
7404 ;; at the block closing line.
7405 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7406 ((and (not (eq force 'off))
7407 (not (memq t (mapcar
7408 (lambda (o)
7409 (eq (overlay-get o 'invisible) 'org-hide-block))
7410 overlays))))
7411 (let ((ov (make-overlay start end)))
7412 (overlay-put ov 'invisible 'org-hide-block)
7413 ;; Make the block accessible to `isearch'.
7414 (overlay-put
7415 ov 'isearch-open-invisible
7416 (lambda (ov)
7417 (when (memq ov org-hide-block-overlays)
7418 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7419 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7420 (delete-overlay ov))))
7421 (push ov org-hide-block-overlays)
7422 ;; When the block is hidden away, make sure point is left in
7423 ;; a visible part of the buffer.
7424 (when (> (line-beginning-position) start)
7425 (goto-char start)
7426 (beginning-of-line))
7427 ;; Signal successful toggling.
7429 ((or (not force) (eq force 'off))
7430 (dolist (ov overlays t)
7431 (when (memq ov org-hide-block-overlays)
7432 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7433 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7434 (delete-overlay ov))))))))
7436 ;; Remove overlays when changing major mode
7437 (add-hook 'org-mode-hook
7438 (lambda () (add-hook 'change-major-mode-hook
7439 'org-show-block-all 'append 'local)))
7441 ;;; Org-goto
7443 (defvar org-goto-window-configuration nil)
7444 (defvar org-goto-marker nil)
7445 (defvar org-goto-map)
7446 (defun org-goto-map ()
7447 "Set the keymap `org-goto'."
7448 (setq org-goto-map
7449 (let ((map (make-sparse-keymap)))
7450 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7451 mouse-drag-region universal-argument org-occur)))
7452 (dolist (cmd cmds)
7453 (substitute-key-definition cmd cmd map global-map)))
7454 (suppress-keymap map)
7455 (org-defkey map "\C-m" 'org-goto-ret)
7456 (org-defkey map [(return)] 'org-goto-ret)
7457 (org-defkey map [(left)] 'org-goto-left)
7458 (org-defkey map [(right)] 'org-goto-right)
7459 (org-defkey map [(control ?g)] 'org-goto-quit)
7460 (org-defkey map "\C-i" 'org-cycle)
7461 (org-defkey map [(tab)] 'org-cycle)
7462 (org-defkey map [(down)] 'outline-next-visible-heading)
7463 (org-defkey map [(up)] 'outline-previous-visible-heading)
7464 (if org-goto-auto-isearch
7465 (if (fboundp 'define-key-after)
7466 (define-key-after map [t] 'org-goto-local-auto-isearch)
7467 nil)
7468 (org-defkey map "q" 'org-goto-quit)
7469 (org-defkey map "n" 'outline-next-visible-heading)
7470 (org-defkey map "p" 'outline-previous-visible-heading)
7471 (org-defkey map "f" 'outline-forward-same-level)
7472 (org-defkey map "b" 'outline-backward-same-level)
7473 (org-defkey map "u" 'outline-up-heading))
7474 (org-defkey map "/" 'org-occur)
7475 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7476 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7477 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7478 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7479 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7480 map)))
7482 (defconst org-goto-help
7483 "Browse buffer copy, to find location or copy text.%s
7484 RET=jump to location C-g=quit and return to previous location
7485 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7487 (defvar org-goto-start-pos) ; dynamically scoped parameter
7489 (defun org-goto (&optional alternative-interface)
7490 "Look up a different location in the current file, keeping current visibility.
7492 When you want look-up or go to a different location in a
7493 document, the fastest way is often to fold the entire buffer and
7494 then dive into the tree. This method has the disadvantage, that
7495 the previous location will be folded, which may not be what you
7496 want.
7498 This command works around this by showing a copy of the current
7499 buffer in an indirect buffer, in overview mode. You can dive
7500 into the tree in that copy, use org-occur and incremental search
7501 to find a location. When pressing RET or `Q', the command
7502 returns to the original buffer in which the visibility is still
7503 unchanged. After RET it will also jump to the location selected
7504 in the indirect buffer and expose the headline hierarchy above.
7506 With a prefix argument, use the alternative interface: e.g., if
7507 `org-goto-interface' is `outline' use `outline-path-completion'."
7508 (interactive "P")
7509 (org-goto-map)
7510 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7511 (org-refile-use-outline-path t)
7512 (org-refile-target-verify-function nil)
7513 (interface
7514 (if (not alternative-interface)
7515 org-goto-interface
7516 (if (eq org-goto-interface 'outline)
7517 'outline-path-completion
7518 'outline)))
7519 (org-goto-start-pos (point))
7520 (selected-point
7521 (if (eq interface 'outline)
7522 (car (org-get-location (current-buffer) org-goto-help))
7523 (let ((pa (org-refile-get-location "Goto")))
7524 (org-refile-check-position pa)
7525 (nth 3 pa)))))
7526 (if selected-point
7527 (progn
7528 (org-mark-ring-push org-goto-start-pos)
7529 (goto-char selected-point)
7530 (when (or (outline-invisible-p) (org-invisible-p2))
7531 (org-show-context 'org-goto)))
7532 (message "Quit"))))
7534 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7535 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7536 (defvar org-goto-local-auto-isearch-map) ; defined below
7538 (defun org-get-location (_buf help)
7539 "Let the user select a location in current buffer.
7540 This function uses a recursive edit. It returns the selected position
7541 or nil."
7542 (org-no-popups
7543 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7544 (isearch-hide-immediately nil)
7545 (isearch-search-fun-function
7546 (lambda () 'org-goto-local-search-headings))
7547 (org-goto-selected-point org-goto-exit-command))
7548 (save-excursion
7549 (save-window-excursion
7550 (delete-other-windows)
7551 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7552 (pop-to-buffer-same-window
7553 (condition-case nil
7554 (make-indirect-buffer (current-buffer) "*org-goto*")
7555 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7556 (with-output-to-temp-buffer "*Org Help*"
7557 (princ (format help (if org-goto-auto-isearch
7558 " Just type for auto-isearch."
7559 " n/p/f/b/u to navigate, q to quit."))))
7560 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7561 (setq buffer-read-only nil)
7562 (let ((org-startup-truncated t)
7563 (org-startup-folded nil)
7564 (org-startup-align-all-tables nil))
7565 (org-mode)
7566 (org-overview))
7567 (setq buffer-read-only t)
7568 (if (and (boundp 'org-goto-start-pos)
7569 (integer-or-marker-p org-goto-start-pos))
7570 (progn (goto-char org-goto-start-pos)
7571 (when (outline-invisible-p)
7572 (org-show-set-visibility 'lineage)))
7573 (goto-char (point-min)))
7574 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7575 (message "Select location and press RET")
7576 (use-local-map org-goto-map)
7577 (recursive-edit)))
7578 (kill-buffer "*org-goto*")
7579 (cons org-goto-selected-point org-goto-exit-command))))
7581 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7582 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7583 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7584 (if (fboundp 'isearch-other-control-char)
7585 (progn
7586 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7587 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7588 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7589 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7590 (define-key org-goto-local-auto-isearch-map [return] nil))
7592 (defun org-goto-local-search-headings (string bound noerror)
7593 "Search and make sure that any matches are in headlines."
7594 (catch 'return
7595 (while (if isearch-forward
7596 (search-forward string bound noerror)
7597 (search-backward string bound noerror))
7598 (when (save-match-data
7599 (and (save-excursion
7600 (beginning-of-line)
7601 (looking-at org-complex-heading-regexp))
7602 (or (not (match-beginning 5))
7603 (< (point) (match-beginning 5)))))
7604 (throw 'return (point))))))
7606 (defun org-goto-local-auto-isearch ()
7607 "Start isearch."
7608 (interactive)
7609 (goto-char (point-min))
7610 (let ((keys (this-command-keys)))
7611 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7612 (isearch-mode t)
7613 (isearch-process-search-char (string-to-char keys)))))
7615 (defun org-goto-ret (&optional _arg)
7616 "Finish `org-goto' by going to the new location."
7617 (interactive "P")
7618 (setq org-goto-selected-point (point))
7619 (setq org-goto-exit-command 'return)
7620 (throw 'exit nil))
7622 (defun org-goto-left ()
7623 "Finish `org-goto' by going to the new location."
7624 (interactive)
7625 (if (org-at-heading-p)
7626 (progn
7627 (beginning-of-line 1)
7628 (setq org-goto-selected-point (point)
7629 org-goto-exit-command 'left)
7630 (throw 'exit nil))
7631 (user-error "Not on a heading")))
7633 (defun org-goto-right ()
7634 "Finish `org-goto' by going to the new location."
7635 (interactive)
7636 (if (org-at-heading-p)
7637 (progn
7638 (setq org-goto-selected-point (point)
7639 org-goto-exit-command 'right)
7640 (throw 'exit nil))
7641 (user-error "Not on a heading")))
7643 (defun org-goto-quit ()
7644 "Finish `org-goto' without cursor motion."
7645 (interactive)
7646 (setq org-goto-selected-point nil)
7647 (setq org-goto-exit-command 'quit)
7648 (throw 'exit nil))
7650 ;;; Indirect buffer display of subtrees
7652 (defvar org-indirect-dedicated-frame nil
7653 "This is the frame being used for indirect tree display.")
7654 (defvar org-last-indirect-buffer nil)
7656 (defun org-tree-to-indirect-buffer (&optional arg)
7657 "Create indirect buffer and narrow it to current subtree.
7659 With a numerical prefix ARG, go up to this level and then take that tree.
7660 If ARG is negative, go up that many levels.
7662 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7663 indirect buffer previously made with this command, to avoid proliferation of
7664 indirect buffers. However, when you call the command with a \
7665 `\\[universal-argument]' prefix, or
7666 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7667 so that you can work with several indirect buffers at the same time. If
7668 `org-indirect-buffer-display' is `dedicated-frame', the \
7669 `\\[universal-argument]' prefix also
7670 requests that a new frame be made for the new buffer, so that the dedicated
7671 frame is not changed."
7672 (interactive "P")
7673 (let ((cbuf (current-buffer))
7674 (cwin (selected-window))
7675 (pos (point))
7676 beg end level heading ibuf)
7677 (save-excursion
7678 (org-back-to-heading t)
7679 (when (numberp arg)
7680 (setq level (org-outline-level))
7681 (when (< arg 0) (setq arg (+ level arg)))
7682 (while (> (setq level (org-outline-level)) arg)
7683 (org-up-heading-safe)))
7684 (setq beg (point)
7685 heading (org-get-heading 'no-tags))
7686 (org-end-of-subtree t t)
7687 (when (org-at-heading-p) (backward-char 1))
7688 (setq end (point)))
7689 (when (and (buffer-live-p org-last-indirect-buffer)
7690 (not (eq org-indirect-buffer-display 'new-frame))
7691 (not arg))
7692 (kill-buffer org-last-indirect-buffer))
7693 (setq ibuf (org-get-indirect-buffer cbuf heading)
7694 org-last-indirect-buffer ibuf)
7695 (cond
7696 ((or (eq org-indirect-buffer-display 'new-frame)
7697 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7698 (select-frame (make-frame))
7699 (delete-other-windows)
7700 (pop-to-buffer-same-window ibuf)
7701 (org-set-frame-title heading))
7702 ((eq org-indirect-buffer-display 'dedicated-frame)
7703 (raise-frame
7704 (select-frame (or (and org-indirect-dedicated-frame
7705 (frame-live-p org-indirect-dedicated-frame)
7706 org-indirect-dedicated-frame)
7707 (setq org-indirect-dedicated-frame (make-frame)))))
7708 (delete-other-windows)
7709 (pop-to-buffer-same-window ibuf)
7710 (org-set-frame-title (concat "Indirect: " heading)))
7711 ((eq org-indirect-buffer-display 'current-window)
7712 (pop-to-buffer-same-window ibuf))
7713 ((eq org-indirect-buffer-display 'other-window)
7714 (pop-to-buffer ibuf))
7715 (t (error "Invalid value")))
7716 (narrow-to-region beg end)
7717 (outline-show-all)
7718 (goto-char pos)
7719 (run-hook-with-args 'org-cycle-hook 'all)
7720 (and (window-live-p cwin) (select-window cwin))))
7722 (defun org-get-indirect-buffer (&optional buffer heading)
7723 (setq buffer (or buffer (current-buffer)))
7724 (let ((n 1) (base (buffer-name buffer)) bname)
7725 (while (buffer-live-p
7726 (get-buffer
7727 (setq bname
7728 (concat base "-"
7729 (if heading (concat heading "-" (number-to-string n))
7730 (number-to-string n))))))
7731 (setq n (1+ n)))
7732 (condition-case nil
7733 (make-indirect-buffer buffer bname 'clone)
7734 (error (make-indirect-buffer buffer bname)))))
7736 (defun org-set-frame-title (title)
7737 "Set the title of the current frame to the string TITLE."
7738 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7740 ;;;; Structure editing
7742 ;;; Inserting headlines
7744 (defun org--line-empty-p (n)
7745 "Is the Nth next line empty?
7747 Counts the current line as N = 1 and the previous line as N = 0;
7748 see `beginning-of-line'."
7749 (save-excursion
7750 (and (not (bobp))
7751 (or (beginning-of-line n) t)
7752 (save-match-data
7753 (looking-at "[ \t]*$")))))
7755 (defun org-previous-line-empty-p ()
7756 "Is the previous line a blank line?
7757 When NEXT is non-nil, check the next line instead."
7758 (org--line-empty-p 0))
7760 (defun org-next-line-empty-p ()
7761 "Is the previous line a blank line?
7762 When NEXT is non-nil, check the next line instead."
7763 (org--line-empty-p 2))
7765 (defun org--blank-before-heading-p (&optional parent)
7766 "Non-nil when an empty line should precede a new heading here.
7767 When optional argument PARENT is non-nil, consider parent
7768 headline instead of current one."
7769 (pcase (assq 'heading org-blank-before-new-entry)
7770 (`(heading . auto)
7771 (save-excursion
7772 (org-with-limited-levels
7773 (unless (and (org-before-first-heading-p)
7774 (not (outline-next-heading)))
7775 (org-back-to-heading t)
7776 (when parent (org-up-heading-safe))
7777 (cond ((not (bobp))
7778 (org-previous-line-empty-p))
7779 ((outline-next-heading)
7780 (org-previous-line-empty-p))
7781 ;; Ignore trailing spaces on last buffer line.
7782 ((progn (skip-chars-backward " \t") (bolp))
7783 (org-previous-line-empty-p))
7784 (t nil))))))
7785 (`(heading . ,value) value)
7786 (_ nil)))
7788 (defun org-insert-heading (&optional arg invisible-ok top)
7789 "Insert a new heading or an item with the same depth at point.
7791 If point is at the beginning of a heading, insert a new heading
7792 or a new headline above the current one. When at the beginning
7793 of a regular line of text, turn it into a heading.
7795 If point is in the middle of a line, split it and create a new
7796 headline with the text in the current line after point (see
7797 `org-M-RET-may-split-line' on how to modify this behavior). As
7798 a special case, on a headline, splitting can only happen on the
7799 title itself. E.g., this excludes breaking stars or tags.
7801 With a `\\[universal-argument]' prefix, set \
7802 `org-insert-heading-respect-content' to
7803 a non-nil value for the duration of the command. This forces the
7804 insertion of a heading after the current subtree, independently
7805 on the location of point.
7807 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7808 insert the heading at the end of the tree
7809 above the current heading. For example, if point is within a
7810 2nd-level heading, then it will insert a 2nd-level heading at
7811 the end of the 1st-level parent subtree.
7813 When INVISIBLE-OK is set, stop at invisible headlines when going
7814 back. This is important for non-interactive uses of the
7815 command.
7817 When optional argument TOP is non-nil, insert a level 1 heading,
7818 unconditionally."
7819 (interactive "P")
7820 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7821 (level (org-current-level))
7822 (stars (make-string (if (and level (not top)) level 1) ?*)))
7823 (cond
7824 ((or org-insert-heading-respect-content
7825 (member arg '((4) (16)))
7826 (and (not invisible-ok)
7827 (invisible-p (max (1- (point)) (point-min)))))
7828 ;; Position point at the location of insertion.
7829 (if (not level) ;before first headline
7830 (org-with-limited-levels (outline-next-heading))
7831 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7832 ;; is nil.
7833 (org-with-limited-levels (org-back-to-heading invisible-ok))
7834 (cond ((equal arg '(16))
7835 (org-up-heading-safe)
7836 (org-end-of-subtree t t))
7838 (org-end-of-subtree t t))))
7839 (unless (bolp) (insert "\n")) ;ensure final newline
7840 (unless (and blank? (org-previous-line-empty-p))
7841 (org-N-empty-lines-before-current (if blank? 1 0)))
7842 (insert stars " \n")
7843 (forward-char -1))
7844 ;; At a headline...
7845 ((org-at-heading-p)
7846 (cond ((bolp)
7847 (when blank? (save-excursion (insert "\n")))
7848 (save-excursion (insert stars " \n"))
7849 (unless (and blank? (org-previous-line-empty-p))
7850 (org-N-empty-lines-before-current (if blank? 1 0)))
7851 (end-of-line))
7852 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7853 (org-match-line org-complex-heading-regexp)
7854 (org-pos-in-match-range (point) 4))
7855 ;; Grab the text that should moved to the new headline.
7856 ;; Preserve tags.
7857 (let ((split (delete-and-extract-region (point) (match-end 4))))
7858 (if (looking-at "[ \t]*$") (replace-match "")
7859 (org-set-tags nil t))
7860 (end-of-line)
7861 (when blank? (insert "\n"))
7862 (insert "\n" stars " ")
7863 (when (org-string-nw-p split) (insert split))
7864 (when (eobp) (save-excursion (insert "\n")))))
7866 (end-of-line)
7867 (when blank? (insert "\n"))
7868 (insert "\n" stars " ")
7869 (when (eobp) (save-excursion (insert "\n"))))))
7870 ;; On regular text, turn line into a headline or split, if
7871 ;; appropriate.
7872 ((bolp)
7873 (insert stars " ")
7874 (unless (and blank? (org-previous-line-empty-p))
7875 (org-N-empty-lines-before-current (if blank? 1 0))))
7877 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7878 (end-of-line))
7879 (insert "\n" stars " ")
7880 (unless (and blank? (org-previous-line-empty-p))
7881 (org-N-empty-lines-before-current (if blank? 1 0))))))
7882 (run-hooks 'org-insert-heading-hook))
7884 (defun org-N-empty-lines-before-current (n)
7885 "Make the number of empty lines before current exactly N.
7886 So this will delete or add empty lines."
7887 (let ((column (current-column)))
7888 (beginning-of-line)
7889 (unless (bobp)
7890 (let ((start (save-excursion
7891 (skip-chars-backward " \r\t\n")
7892 (line-end-position))))
7893 (delete-region start (line-end-position 0))))
7894 (insert (make-string n ?\n))
7895 (move-to-column column)))
7897 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7898 "Return the heading of the current entry, without the stars.
7899 When NO-TAGS is non-nil, don't include tags.
7900 When NO-TODO is non-nil, don't include TODO keywords.
7901 When NO-PRIORITY is non-nil, don't include priority cookie.
7902 When NO-COMMENT is non-nil, don't include COMMENT string."
7903 (save-excursion
7904 (org-back-to-heading t)
7905 (let ((case-fold-search nil))
7906 (looking-at org-complex-heading-regexp)
7907 (let ((todo (and (not no-todo) (match-string 2)))
7908 (priority (and (not no-priority) (match-string 3)))
7909 (headline (pcase (match-string 4)
7910 (`nil "")
7911 ((and (guard no-comment) h)
7912 (replace-regexp-in-string
7913 (eval-when-compile
7914 (format "\\`%s[ \t]+" org-comment-string))
7915 "" h))
7916 (h h)))
7917 (tags (and (not no-tags) (match-string 5))))
7918 (mapconcat #'identity
7919 (delq nil (list todo priority headline tags))
7920 " ")))))
7922 (defvar orgstruct-mode) ; defined below
7924 (defun org-heading-components ()
7925 "Return the components of the current heading.
7926 This is a list with the following elements:
7927 - the level as an integer
7928 - the reduced level, different if `org-odd-levels-only' is set.
7929 - the TODO keyword, or nil
7930 - the priority character, like ?A, or nil if no priority is given
7931 - the headline text itself, or the tags string if no headline text
7932 - the tags string, or nil."
7933 (save-excursion
7934 (org-back-to-heading t)
7935 (when (let (case-fold-search)
7936 (looking-at
7937 (if orgstruct-mode
7938 org-heading-regexp
7939 org-complex-heading-regexp)))
7940 (if orgstruct-mode
7941 (list (length (match-string 1))
7942 (org-reduced-level (length (match-string 1)))
7945 (match-string 2)
7946 nil)
7947 (list (length (match-string 1))
7948 (org-reduced-level (length (match-string 1)))
7949 (match-string-no-properties 2)
7950 (and (match-end 3) (aref (match-string 3) 2))
7951 (match-string-no-properties 4)
7952 (match-string-no-properties 5))))))
7954 (defun org-get-entry ()
7955 "Get the entry text, after heading, entire subtree."
7956 (save-excursion
7957 (org-back-to-heading t)
7958 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7960 (defun org-edit-headline (&optional heading)
7961 "Edit the current headline.
7962 Set it to HEADING when provided."
7963 (interactive)
7964 (org-with-wide-buffer
7965 (org-back-to-heading t)
7966 (let ((case-fold-search nil))
7967 (when (looking-at org-complex-heading-regexp)
7968 (let* ((old (match-string-no-properties 4))
7969 (new (save-match-data
7970 (org-trim (or heading (read-string "Edit: " old))))))
7971 (unless (equal old new)
7972 (if old (replace-match new t t nil 4)
7973 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7974 (insert " " new))
7975 (org-set-tags nil t)
7976 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7978 (defun org-insert-heading-after-current ()
7979 "Insert a new heading with same level as current, after current subtree."
7980 (interactive)
7981 (org-back-to-heading)
7982 (org-insert-heading)
7983 (org-move-subtree-down)
7984 (end-of-line 1))
7986 (defun org-insert-heading-respect-content (&optional invisible-ok)
7987 "Insert heading with `org-insert-heading-respect-content' set to t."
7988 (interactive)
7989 (org-insert-heading '(4) invisible-ok))
7991 (defun org-insert-todo-heading-respect-content (&optional force-state)
7992 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7993 (interactive)
7994 (org-insert-todo-heading force-state '(4)))
7996 (defun org-insert-todo-heading (arg &optional force-heading)
7997 "Insert a new heading with the same level and TODO state as current heading.
7999 If the heading has no TODO state, or if the state is DONE, use
8000 the first state (TODO by default). Also with one prefix arg,
8001 force first state. With two prefix args, force inserting at the
8002 end of the parent subtree.
8004 When called at a plain list item, insert a new item with an
8005 unchecked check box."
8006 (interactive "P")
8007 (when (or force-heading (not (org-insert-item 'checkbox)))
8008 (org-insert-heading (or (and (equal arg '(16)) '(16))
8009 force-heading))
8010 (save-excursion
8011 (org-back-to-heading)
8012 (outline-previous-heading)
8013 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8014 (let* ((new-mark-x
8015 (if (or (equal arg '(4))
8016 (not (match-beginning 2))
8017 (member (match-string 2) org-done-keywords))
8018 (car org-todo-keywords-1)
8019 (match-string 2)))
8020 (new-mark
8022 (run-hook-with-args-until-success
8023 'org-todo-get-default-hook new-mark-x nil)
8024 new-mark-x)))
8025 (beginning-of-line 1)
8026 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8027 (if org-treat-insert-todo-heading-as-state-change
8028 (org-todo new-mark)
8029 (insert new-mark " "))))
8030 (when org-provide-todo-statistics
8031 (org-update-parent-todo-statistics))))
8033 (defun org-insert-subheading (arg)
8034 "Insert a new subheading and demote it.
8035 Works for outline headings and for plain lists alike."
8036 (interactive "P")
8037 (org-insert-heading arg)
8038 (cond
8039 ((org-at-heading-p) (org-do-demote))
8040 ((org-at-item-p) (org-indent-item))))
8042 (defun org-insert-todo-subheading (arg)
8043 "Insert a new subheading with TODO keyword or checkbox and demote it.
8044 Works for outline headings and for plain lists alike."
8045 (interactive "P")
8046 (org-insert-todo-heading arg)
8047 (cond
8048 ((org-at-heading-p) (org-do-demote))
8049 ((org-at-item-p) (org-indent-item))))
8051 ;;; Promotion and Demotion
8053 (defvar org-after-demote-entry-hook nil
8054 "Hook run after an entry has been demoted.
8055 The cursor will be at the beginning of the entry.
8056 When a subtree is being demoted, the hook will be called for each node.")
8058 (defvar org-after-promote-entry-hook nil
8059 "Hook run after an entry has been promoted.
8060 The cursor will be at the beginning of the entry.
8061 When a subtree is being promoted, the hook will be called for each node.")
8063 (defun org-promote-subtree ()
8064 "Promote the entire subtree.
8065 See also `org-promote'."
8066 (interactive)
8067 (save-excursion
8068 (org-with-limited-levels (org-map-tree 'org-promote)))
8069 (org-fix-position-after-promote))
8071 (defun org-demote-subtree ()
8072 "Demote the entire subtree.
8073 See `org-demote' and `org-promote'."
8074 (interactive)
8075 (save-excursion
8076 (org-with-limited-levels (org-map-tree 'org-demote)))
8077 (org-fix-position-after-promote))
8079 (defun org-do-promote ()
8080 "Promote the current heading higher up the tree.
8081 If the region is active in `transient-mark-mode', promote all
8082 headings in the region."
8083 (interactive)
8084 (save-excursion
8085 (if (org-region-active-p)
8086 (org-map-region 'org-promote (region-beginning) (region-end))
8087 (org-promote)))
8088 (org-fix-position-after-promote))
8090 (defun org-do-demote ()
8091 "Demote the current heading lower down the tree.
8092 If the region is active in `transient-mark-mode', demote all
8093 headings in the region."
8094 (interactive)
8095 (save-excursion
8096 (if (org-region-active-p)
8097 (org-map-region 'org-demote (region-beginning) (region-end))
8098 (org-demote)))
8099 (org-fix-position-after-promote))
8101 (defun org-fix-position-after-promote ()
8102 "Fix cursor position and indentation after demoting/promoting."
8103 (let ((pos (point)))
8104 (when (save-excursion
8105 (beginning-of-line)
8106 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8107 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8108 (cond ((eobp) (insert " "))
8109 ((eolp) (insert " "))
8110 ((equal (char-after) ?\s) (forward-char 1))))))
8112 (defun org-current-level ()
8113 "Return the level of the current entry, or nil if before the first headline.
8114 The level is the number of stars at the beginning of the
8115 headline. Use `org-reduced-level' to remove the effect of
8116 `org-odd-levels'. Unlike to `org-outline-level', this function
8117 ignores inlinetasks."
8118 (let ((level (org-with-limited-levels (org-outline-level))))
8119 (and (> level 0) level)))
8121 (defun org-get-previous-line-level ()
8122 "Return the outline depth of the last headline before the current line.
8123 Returns 0 for the first headline in the buffer, and nil if before the
8124 first headline."
8125 (and (org-current-level)
8126 (or (and (/= (line-beginning-position) (point-min))
8127 (save-excursion (beginning-of-line 0) (org-current-level)))
8128 0)))
8130 (defun org-reduced-level (l)
8131 "Compute the effective level of a heading.
8132 This takes into account the setting of `org-odd-levels-only'."
8133 (cond
8134 ((zerop l) 0)
8135 (org-odd-levels-only (1+ (floor (/ l 2))))
8136 (t l)))
8138 (defun org-level-increment ()
8139 "Return the number of stars that will be added or removed at a
8140 time to headlines when structure editing, based on the value of
8141 `org-odd-levels-only'."
8142 (if org-odd-levels-only 2 1))
8144 (defun org-get-valid-level (level &optional change)
8145 "Rectify a level change under the influence of `org-odd-levels-only'.
8146 LEVEL is a current level, CHANGE is by how much the level should
8147 be modified. Even if CHANGE is nil, LEVEL may be returned
8148 modified because even level numbers will become the next higher
8149 odd number. Returns values greater than 0."
8150 (if org-odd-levels-only
8151 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8152 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8153 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8154 (max 1 (+ level (or change 0)))))
8156 (defun org-promote ()
8157 "Promote the current heading higher up the tree."
8158 (org-with-wide-buffer
8159 (org-back-to-heading t)
8160 (let* ((after-change-functions (remq 'flyspell-after-change-function
8161 after-change-functions))
8162 (level (save-match-data (funcall outline-level)))
8163 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8164 (diff (abs (- level (length up-head) -1))))
8165 (cond
8166 ((and (= level 1) org-allow-promoting-top-level-subtree)
8167 (replace-match "# " nil t))
8168 ((= level 1)
8169 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8170 (t (replace-match up-head nil t)))
8171 (unless (= level 1)
8172 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8173 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8174 (run-hooks 'org-after-promote-entry-hook))))
8176 (defun org-demote ()
8177 "Demote the current heading lower down the tree."
8178 (org-with-wide-buffer
8179 (org-back-to-heading t)
8180 (let* ((after-change-functions (remq 'flyspell-after-change-function
8181 after-change-functions))
8182 (level (save-match-data (funcall outline-level)))
8183 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8184 (diff (abs (- level (length down-head) -1))))
8185 (replace-match down-head nil t)
8186 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8187 (when org-adapt-indentation (org-fixup-indentation diff))
8188 (run-hooks 'org-after-demote-entry-hook))))
8190 (defun org-cycle-level ()
8191 "Cycle the level of an empty headline through possible states.
8192 This goes first to child, then to parent, level, then up the hierarchy.
8193 After top level, it switches back to sibling level."
8194 (interactive)
8195 (let ((org-adapt-indentation nil))
8196 (when (org-point-at-end-of-empty-headline)
8197 (setq this-command 'org-cycle-level) ; Only needed for caching
8198 (let ((cur-level (org-current-level))
8199 (prev-level (org-get-previous-line-level)))
8200 (cond
8201 ;; If first headline in file, promote to top-level.
8202 ((= prev-level 0)
8203 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8204 do (org-do-promote)))
8205 ;; If same level as prev, demote one.
8206 ((= prev-level cur-level)
8207 (org-do-demote))
8208 ;; If parent is top-level, promote to top level if not already.
8209 ((= prev-level 1)
8210 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8211 do (org-do-promote)))
8212 ;; If top-level, return to prev-level.
8213 ((= cur-level 1)
8214 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8215 do (org-do-demote)))
8216 ;; If less than prev-level, promote one.
8217 ((< cur-level prev-level)
8218 (org-do-promote))
8219 ;; If deeper than prev-level, promote until higher than
8220 ;; prev-level.
8221 ((> cur-level prev-level)
8222 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8223 do (org-do-promote))))
8224 t))))
8226 (defun org-map-tree (fun)
8227 "Call FUN for every heading underneath the current one."
8228 (org-back-to-heading t)
8229 (let ((level (funcall outline-level)))
8230 (save-excursion
8231 (funcall fun)
8232 (while (and (progn
8233 (outline-next-heading)
8234 (> (funcall outline-level) level))
8235 (not (eobp)))
8236 (funcall fun)))))
8238 (defun org-map-region (fun beg end)
8239 "Call FUN for every heading between BEG and END."
8240 (let ((org-ignore-region t))
8241 (save-excursion
8242 (setq end (copy-marker end))
8243 (goto-char beg)
8244 (when (and (re-search-forward org-outline-regexp-bol nil t)
8245 (< (point) end))
8246 (funcall fun))
8247 (while (and (progn
8248 (outline-next-heading)
8249 (< (point) end))
8250 (not (eobp)))
8251 (funcall fun)))))
8253 (defun org-fixup-indentation (diff)
8254 "Change the indentation in the current entry by DIFF.
8256 DIFF is an integer. Indentation is done according to the
8257 following rules:
8259 - Planning information and property drawers are always indented
8260 according to the new level of the headline;
8262 - Footnote definitions and their contents are ignored;
8264 - Inlinetasks' boundaries are not shifted;
8266 - Empty lines are ignored;
8268 - Other lines' indentation are shifted by DIFF columns, unless
8269 it would introduce a structural change in the document, in
8270 which case no shifting is done at all.
8272 Assume point is at a heading or an inlinetask beginning."
8273 (org-with-wide-buffer
8274 (narrow-to-region (line-beginning-position)
8275 (save-excursion
8276 (if (org-with-limited-levels (org-at-heading-p))
8277 (org-with-limited-levels (outline-next-heading))
8278 (org-inlinetask-goto-end))
8279 (point)))
8280 (forward-line)
8281 ;; Indent properly planning info and property drawer.
8282 (when (looking-at-p org-planning-line-re)
8283 (org-indent-line)
8284 (forward-line))
8285 (when (looking-at org-property-drawer-re)
8286 (goto-char (match-end 0))
8287 (forward-line)
8288 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8289 (catch 'no-shift
8290 (when (zerop diff) (throw 'no-shift nil))
8291 ;; If DIFF is negative, first check if a shift is possible at all
8292 ;; (e.g., it doesn't break structure). This can only happen if
8293 ;; some contents are not properly indented.
8294 (let ((case-fold-search t))
8295 (when (< diff 0)
8296 (let ((diff (- diff))
8297 (forbidden-re (concat org-outline-regexp
8298 "\\|"
8299 (substring org-footnote-definition-re 1))))
8300 (save-excursion
8301 (while (not (eobp))
8302 (cond
8303 ((looking-at-p "[ \t]*$") (forward-line))
8304 ((and (looking-at-p org-footnote-definition-re)
8305 (let ((e (org-element-at-point)))
8306 (and (eq (org-element-type e) 'footnote-definition)
8307 (goto-char (org-element-property :end e))))))
8308 ((looking-at-p org-outline-regexp) (forward-line))
8309 ;; Give up if shifting would move before column 0 or
8310 ;; if it would introduce a headline or a footnote
8311 ;; definition.
8313 (skip-chars-forward " \t")
8314 (let ((ind (current-column)))
8315 (when (or (< ind diff)
8316 (and (= ind diff) (looking-at-p forbidden-re)))
8317 (throw 'no-shift nil)))
8318 ;; Ignore contents of example blocks and source
8319 ;; blocks if their indentation is meant to be
8320 ;; preserved. Jump to block's closing line.
8321 (beginning-of-line)
8322 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8323 (let ((e (org-element-at-point)))
8324 (and (memq (org-element-type e)
8325 '(example-block src-block))
8326 (or org-src-preserve-indentation
8327 (org-element-property :preserve-indent e))
8328 (goto-char (org-element-property :end e))
8329 (progn (skip-chars-backward " \r\t\n")
8330 (beginning-of-line)
8331 t))))
8332 (forward-line))))))))
8333 ;; Shift lines but footnote definitions, inlinetasks boundaries
8334 ;; by DIFF. Also skip contents of source or example blocks
8335 ;; when indentation is meant to be preserved.
8336 (while (not (eobp))
8337 (cond
8338 ((and (looking-at-p org-footnote-definition-re)
8339 (let ((e (org-element-at-point)))
8340 (and (eq (org-element-type e) 'footnote-definition)
8341 (goto-char (org-element-property :end e))))))
8342 ((looking-at-p org-outline-regexp) (forward-line))
8343 ((looking-at-p "[ \t]*$") (forward-line))
8345 (indent-line-to (+ (org-get-indentation) diff))
8346 (beginning-of-line)
8347 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8348 (let ((e (org-element-at-point)))
8349 (and (memq (org-element-type e)
8350 '(example-block src-block))
8351 (or org-src-preserve-indentation
8352 (org-element-property :preserve-indent e))
8353 (goto-char (org-element-property :end e))
8354 (progn (skip-chars-backward " \r\t\n")
8355 (beginning-of-line)
8356 t))))
8357 (forward-line)))))))))
8359 (defun org-convert-to-odd-levels ()
8360 "Convert an Org file with all levels allowed to one with odd levels.
8361 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8362 level 5 etc."
8363 (interactive)
8364 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8365 (let ((outline-level 'org-outline-level)
8366 (org-odd-levels-only nil) n)
8367 (save-excursion
8368 (goto-char (point-min))
8369 (while (re-search-forward "^\\*\\*+ " nil t)
8370 (setq n (- (length (match-string 0)) 2))
8371 (while (>= (setq n (1- n)) 0)
8372 (org-demote))
8373 (end-of-line 1))))))
8375 (defun org-convert-to-oddeven-levels ()
8376 "Convert an Org file with only odd levels to one with odd/even levels.
8377 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8378 file contains a section with an even level, conversion would
8379 destroy the structure of the file. An error is signaled in this
8380 case."
8381 (interactive)
8382 (goto-char (point-min))
8383 ;; First check if there are no even levels
8384 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8385 (org-show-set-visibility 'canonical)
8386 (error "Not all levels are odd in this file. Conversion not possible"))
8387 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8388 (let ((outline-regexp org-outline-regexp)
8389 (outline-level 'org-outline-level)
8390 (org-odd-levels-only nil) n)
8391 (save-excursion
8392 (goto-char (point-min))
8393 (while (re-search-forward "^\\*\\*+ " nil t)
8394 (setq n (/ (1- (length (match-string 0))) 2))
8395 (while (>= (setq n (1- n)) 0)
8396 (org-promote))
8397 (end-of-line 1))))))
8399 (defun org-tr-level (n)
8400 "Make N odd if required."
8401 (if org-odd-levels-only (1+ (/ n 2)) n))
8403 ;;; Vertical tree motion, cutting and pasting of subtrees
8405 (defun org-move-subtree-up (&optional arg)
8406 "Move the current subtree up past ARG headlines of the same level."
8407 (interactive "p")
8408 (org-move-subtree-down (- (prefix-numeric-value arg))))
8410 (defun org-move-subtree-down (&optional arg)
8411 "Move the current subtree down past ARG headlines of the same level."
8412 (interactive "p")
8413 (setq arg (prefix-numeric-value arg))
8414 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8415 'org-get-last-sibling))
8416 (ins-point (make-marker))
8417 (cnt (abs arg))
8418 (col (current-column))
8419 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8420 ;; Select the tree
8421 (org-back-to-heading)
8422 (setq beg0 (point))
8423 (save-excursion
8424 (setq ne-beg (org-back-over-empty-lines))
8425 (setq beg (point)))
8426 (save-match-data
8427 (save-excursion (outline-end-of-heading)
8428 (setq folded (outline-invisible-p)))
8429 (progn (org-end-of-subtree nil t)
8430 (unless (eobp) (backward-char))))
8431 (outline-next-heading)
8432 (setq ne-end (org-back-over-empty-lines))
8433 (setq end (point))
8434 (goto-char beg0)
8435 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8436 ;; include less whitespace
8437 (save-excursion
8438 (goto-char beg)
8439 (forward-line (- ne-beg ne-end))
8440 (setq beg (point))))
8441 ;; Find insertion point, with error handling
8442 (while (> cnt 0)
8443 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8444 (progn (goto-char beg0)
8445 (user-error "Cannot move past superior level or buffer limit")))
8446 (setq cnt (1- cnt)))
8447 (when (> arg 0)
8448 ;; Moving forward - still need to move over subtree
8449 (org-end-of-subtree t t)
8450 (save-excursion
8451 (org-back-over-empty-lines)
8452 (or (bolp) (newline))))
8453 (setq ne-ins (org-back-over-empty-lines))
8454 (move-marker ins-point (point))
8455 (setq txt (buffer-substring beg end))
8456 (org-save-markers-in-region beg end)
8457 (delete-region beg end)
8458 (org-remove-empty-overlays-at beg)
8459 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8460 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8461 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8462 (let ((bbb (point)))
8463 (insert-before-markers txt)
8464 (org-reinstall-markers-in-region bbb)
8465 (move-marker ins-point bbb))
8466 (or (bolp) (insert "\n"))
8467 (setq ins-end (point))
8468 (goto-char ins-point)
8469 (org-skip-whitespace)
8470 (when (and (< arg 0)
8471 (org-first-sibling-p)
8472 (> ne-ins ne-beg))
8473 ;; Move whitespace back to beginning
8474 (save-excursion
8475 (goto-char ins-end)
8476 (let ((kill-whole-line t))
8477 (kill-line (- ne-ins ne-beg)) (point)))
8478 (insert (make-string (- ne-ins ne-beg) ?\n)))
8479 (move-marker ins-point nil)
8480 (if folded
8481 (outline-hide-subtree)
8482 (org-show-entry)
8483 (org-show-children)
8484 (org-cycle-hide-drawers 'children))
8485 (org-clean-visibility-after-subtree-move)
8486 ;; move back to the initial column we were at
8487 (move-to-column col)))
8489 (defvar org-subtree-clip ""
8490 "Clipboard for cut and paste of subtrees.
8491 This is actually only a copy of the kill, because we use the normal kill
8492 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8494 (defvar org-subtree-clip-folded nil
8495 "Was the last copied subtree folded?
8496 This is used to fold the tree back after pasting.")
8498 (defun org-cut-subtree (&optional n)
8499 "Cut the current subtree into the clipboard.
8500 With prefix arg N, cut this many sequential subtrees.
8501 This is a short-hand for marking the subtree and then cutting it."
8502 (interactive "p")
8503 (org-copy-subtree n 'cut))
8505 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8506 "Copy the current subtree it in the clipboard.
8507 With prefix arg N, copy this many sequential subtrees.
8508 This is a short-hand for marking the subtree and then copying it.
8509 If CUT is non-nil, actually cut the subtree.
8510 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8511 of some markers in the region, even if CUT is non-nil. This is
8512 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8513 (interactive "p")
8514 (let (beg end folded (beg0 (point)))
8515 (if (called-interactively-p 'any)
8516 (org-back-to-heading nil) ; take what looks like a subtree
8517 (org-back-to-heading t)) ; take what is really there
8518 (setq beg (point))
8519 (skip-chars-forward " \t\r\n")
8520 (save-match-data
8521 (if nosubtrees
8522 (outline-next-heading)
8523 (save-excursion (outline-end-of-heading)
8524 (setq folded (outline-invisible-p)))
8525 (ignore-errors (org-forward-heading-same-level (1- n) t))
8526 (org-end-of-subtree t t)))
8527 ;; Include the end of an inlinetask
8528 (when (and (featurep 'org-inlinetask)
8529 (looking-at-p (concat (org-inlinetask-outline-regexp)
8530 "END[ \t]*$")))
8531 (end-of-line))
8532 (setq end (point))
8533 (goto-char beg0)
8534 (when (> end beg)
8535 (setq org-subtree-clip-folded folded)
8536 (when (or cut force-store-markers)
8537 (org-save-markers-in-region beg end))
8538 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8539 (setq org-subtree-clip (current-kill 0))
8540 (message "%s: Subtree(s) with %d characters"
8541 (if cut "Cut" "Copied")
8542 (length org-subtree-clip)))))
8544 (defun org-paste-subtree (&optional level tree for-yank remove)
8545 "Paste the clipboard as a subtree, with modification of headline level.
8546 The entire subtree is promoted or demoted in order to match a new headline
8547 level.
8549 If the cursor is at the beginning of a headline, the same level as
8550 that headline is used to paste the tree.
8552 If not, the new level is derived from the *visible* headings
8553 before and after the insertion point, and taken to be the inferior headline
8554 level of the two. So if the previous visible heading is level 3 and the
8555 next is level 4 (or vice versa), level 4 will be used for insertion.
8556 This makes sure that the subtree remains an independent subtree and does
8557 not swallow low level entries.
8559 You can also force a different level, either by using a numeric prefix
8560 argument, or by inserting the heading marker by hand. For example, if the
8561 cursor is after \"*****\", then the tree will be shifted to level 5.
8563 If optional TREE is given, use this text instead of the kill ring.
8565 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8566 move back over whitespace before inserting, and move point to the end of
8567 the inserted text when done.
8569 When REMOVE is non-nil, remove the subtree from the clipboard."
8570 (interactive "P")
8571 (setq tree (or tree (and kill-ring (current-kill 0))))
8572 (unless (org-kill-is-subtree-p tree)
8573 (user-error "%s"
8574 (substitute-command-keys
8575 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8576 (org-with-limited-levels
8577 (let* ((visp (not (outline-invisible-p)))
8578 (txt tree)
8579 (^re_ "\\(\\*+\\)[ \t]*")
8580 (old-level (if (string-match org-outline-regexp-bol txt)
8581 (- (match-end 0) (match-beginning 0) 1)
8582 -1))
8583 (force-level (cond (level (prefix-numeric-value level))
8584 ((and (looking-at "[ \t]*$")
8585 (string-match
8586 "^\\*+$" (buffer-substring
8587 (point-at-bol) (point))))
8588 (- (match-end 0) (match-beginning 0)))
8589 ((and (bolp)
8590 (looking-at org-outline-regexp))
8591 (- (match-end 0) (point) 1))))
8592 (previous-level (save-excursion
8593 (condition-case nil
8594 (progn
8595 (outline-previous-visible-heading 1)
8596 (if (looking-at ^re_)
8597 (- (match-end 0) (match-beginning 0) 1)
8599 (error 1))))
8600 (next-level (save-excursion
8601 (condition-case nil
8602 (progn
8603 (or (looking-at org-outline-regexp)
8604 (outline-next-visible-heading 1))
8605 (if (looking-at ^re_)
8606 (- (match-end 0) (match-beginning 0) 1)
8608 (error 1))))
8609 (new-level (or force-level (max previous-level next-level)))
8610 (shift (if (or (= old-level -1)
8611 (= new-level -1)
8612 (= old-level new-level))
8614 (- new-level old-level)))
8615 (delta (if (> shift 0) -1 1))
8616 (func (if (> shift 0) 'org-demote 'org-promote))
8617 (org-odd-levels-only nil)
8618 beg end newend)
8619 ;; Remove the forced level indicator
8620 (when force-level
8621 (delete-region (point-at-bol) (point)))
8622 ;; Paste
8623 (beginning-of-line (if (bolp) 1 2))
8624 (setq beg (point))
8625 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8626 (insert-before-markers txt)
8627 (unless (string-suffix-p "\n" txt) (insert "\n"))
8628 (setq newend (point))
8629 (org-reinstall-markers-in-region beg)
8630 (setq end (point))
8631 (goto-char beg)
8632 (skip-chars-forward " \t\n\r")
8633 (setq beg (point))
8634 (when (and (outline-invisible-p) visp)
8635 (save-excursion (outline-show-heading)))
8636 ;; Shift if necessary
8637 (unless (= shift 0)
8638 (save-restriction
8639 (narrow-to-region beg end)
8640 (while (not (= shift 0))
8641 (org-map-region func (point-min) (point-max))
8642 (setq shift (+ delta shift)))
8643 (goto-char (point-min))
8644 (setq newend (point-max))))
8645 (when (or (called-interactively-p 'interactive) for-yank)
8646 (message "Clipboard pasted as level %d subtree" new-level))
8647 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8648 kill-ring
8649 (eq org-subtree-clip (current-kill 0))
8650 org-subtree-clip-folded)
8651 ;; The tree was folded before it was killed/copied
8652 (outline-hide-subtree))
8653 (and for-yank (goto-char newend))
8654 (and remove (setq kill-ring (cdr kill-ring))))))
8656 (defun org-kill-is-subtree-p (&optional txt)
8657 "Check if the current kill is an outline subtree, or a set of trees.
8658 Returns nil if kill does not start with a headline, or if the first
8659 headline level is not the largest headline level in the tree.
8660 So this will actually accept several entries of equal levels as well,
8661 which is OK for `org-paste-subtree'.
8662 If optional TXT is given, check this string instead of the current kill."
8663 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8664 (re (org-get-limited-outline-regexp))
8665 (^re (concat "^" re))
8666 (start-level (and kill
8667 (string-match
8668 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8669 kill)
8670 (- (match-end 2) (match-beginning 2) 1)))
8671 (start (1+ (or (match-beginning 2) -1))))
8672 (if (not start-level)
8673 (progn
8674 nil) ;; does not even start with a heading
8675 (catch 'exit
8676 (while (setq start (string-match ^re kill (1+ start)))
8677 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8678 (throw 'exit nil)))
8679 t))))
8681 (defvar org-markers-to-move nil
8682 "Markers that should be moved with a cut-and-paste operation.
8683 Those markers are stored together with their positions relative to
8684 the start of the region.")
8686 (defun org-save-markers-in-region (beg end)
8687 "Check markers in region.
8688 If these markers are between BEG and END, record their position relative
8689 to BEG, so that after moving the block of text, we can put the markers back
8690 into place.
8691 This function gets called just before an entry or tree gets cut from the
8692 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8693 called immediately, to move the markers with the entries."
8694 (setq org-markers-to-move nil)
8695 (when (featurep 'org-clock)
8696 (org-clock-save-markers-for-cut-and-paste beg end))
8697 (when (featurep 'org-agenda)
8698 (org-agenda-save-markers-for-cut-and-paste beg end)))
8700 (defun org-check-and-save-marker (marker beg end)
8701 "Check if MARKER is between BEG and END.
8702 If yes, remember the marker and the distance to BEG."
8703 (when (and (marker-buffer marker)
8704 (equal (marker-buffer marker) (current-buffer))
8705 (>= marker beg) (< marker end))
8706 (push (cons marker (- marker beg)) org-markers-to-move)))
8708 (defun org-reinstall-markers-in-region (beg)
8709 "Move all remembered markers to their position relative to BEG."
8710 (dolist (x org-markers-to-move)
8711 (move-marker (car x) (+ beg (cdr x))))
8712 (setq org-markers-to-move nil))
8714 (defun org-narrow-to-subtree ()
8715 "Narrow buffer to the current subtree."
8716 (interactive)
8717 (save-excursion
8718 (save-match-data
8719 (org-with-limited-levels
8720 (narrow-to-region
8721 (progn (org-back-to-heading t) (point))
8722 (progn (org-end-of-subtree t t)
8723 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8724 (point)))))))
8726 (defun org-narrow-to-block ()
8727 "Narrow buffer to the current block."
8728 (interactive)
8729 (let* ((case-fold-search t)
8730 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8731 "^[ \t]*#\\+end_.*")))
8732 (if blockp
8733 (narrow-to-region (car blockp) (cdr blockp))
8734 (user-error "Not in a block"))))
8736 (defun org-clone-subtree-with-time-shift (n &optional shift)
8737 "Clone the task (subtree) at point N times.
8738 The clones will be inserted as siblings.
8740 In interactive use, the user will be prompted for the number of
8741 clones to be produced. If the entry has a timestamp, the user
8742 will also be prompted for a time shift, which may be a repeater
8743 as used in time stamps, for example `+3d'. To disable this,
8744 you can call the function with a universal prefix argument.
8746 When a valid repeater is given and the entry contains any time
8747 stamps, the clones will become a sequence in time, with time
8748 stamps in the subtree shifted for each clone produced. If SHIFT
8749 is nil or the empty string, time stamps will be left alone. The
8750 ID property of the original subtree is removed.
8752 In each clone, all the CLOCK entries will be removed. This
8753 prevents Org from considering that the clocked times overlap.
8755 If the original subtree did contain time stamps with a repeater,
8756 the following will happen:
8757 - the repeater will be removed in each clone
8758 - an additional clone will be produced, with the current, unshifted
8759 date(s) in the entry.
8760 - the original entry will be placed *after* all the clones, with
8761 repeater intact.
8762 - the start days in the repeater in the original entry will be shifted
8763 to past the last clone.
8764 In this way you can spell out a number of instances of a repeating task,
8765 and still retain the repeater to cover future instances of the task.
8767 As described above, N+1 clones are produced when the original
8768 subtree has a repeater. Setting N to 0, then, can be used to
8769 remove the repeater from a subtree and create a shifted clone
8770 with the original repeater."
8771 (interactive "nNumber of clones to produce: ")
8772 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8773 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8774 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8775 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8776 (shift
8777 (or shift
8778 (if (and (not (equal current-prefix-arg '(4)))
8779 (save-excursion
8780 (goto-char beg)
8781 (re-search-forward org-ts-regexp-both end-of-tree t)))
8782 (read-from-minibuffer
8783 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8784 ""))) ;No time shift
8785 (doshift
8786 (and (org-string-nw-p shift)
8787 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8788 shift)
8789 (user-error "Invalid shift specification %s" shift)))))
8790 (goto-char end-of-tree)
8791 (unless (bolp) (insert "\n"))
8792 (let* ((end (point))
8793 (template (buffer-substring beg end))
8794 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8795 (shift-what (pcase (and doshift (match-string 2 shift))
8796 (`nil nil)
8797 ("d" 'day)
8798 ("w" (setq shift-n (* 7 shift-n)) 'day)
8799 ("m" 'month)
8800 ("y" 'year)
8801 (_ (error "Unsupported time unit"))))
8802 (nmin 1)
8803 (nmax n)
8804 (n-no-remove -1)
8805 (idprop (org-entry-get nil "ID")))
8806 (when (and doshift
8807 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8808 template))
8809 (delete-region beg end)
8810 (setq end beg)
8811 (setq nmin 0)
8812 (setq nmax (1+ nmax))
8813 (setq n-no-remove nmax))
8814 (goto-char end)
8815 (cl-loop for n from nmin to nmax do
8816 (insert
8817 ;; Prepare clone.
8818 (with-temp-buffer
8819 (insert template)
8820 (org-mode)
8821 (goto-char (point-min))
8822 (org-show-subtree)
8823 (and idprop (if org-clone-delete-id
8824 (org-entry-delete nil "ID")
8825 (org-id-get-create t)))
8826 (unless (= n 0)
8827 (while (re-search-forward org-clock-line-re nil t)
8828 (delete-region (line-beginning-position)
8829 (line-beginning-position 2)))
8830 (goto-char (point-min))
8831 (while (re-search-forward org-drawer-regexp nil t)
8832 (org-remove-empty-drawer-at (point))))
8833 (goto-char (point-min))
8834 (when doshift
8835 (while (re-search-forward org-ts-regexp-both nil t)
8836 (org-timestamp-change (* n shift-n) shift-what))
8837 (unless (= n n-no-remove)
8838 (goto-char (point-min))
8839 (while (re-search-forward org-ts-regexp nil t)
8840 (save-excursion
8841 (goto-char (match-beginning 0))
8842 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8843 (delete-region (match-beginning 1) (match-end 1)))))))
8844 (buffer-string)))))
8845 (goto-char beg)))
8847 ;;; Outline Sorting
8849 (defun org-sort (&optional with-case)
8850 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8851 Optional argument WITH-CASE means sort case-sensitively."
8852 (interactive "P")
8853 (org-call-with-arg
8854 (cond ((org-at-table-p) #'org-table-sort-lines)
8855 ((org-at-item-p) #'org-sort-list)
8856 (t #'org-sort-entries))
8857 with-case))
8859 (defun org-sort-remove-invisible (s)
8860 "Remove invisible part of links and emphasis markers from string S."
8861 (remove-text-properties 0 (length s) org-rm-props s)
8862 (replace-regexp-in-string
8863 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8864 (replace-regexp-in-string
8865 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8866 (org-link-display-format s)
8867 t t) t t))
8869 (defvar org-priority-regexp) ; defined later in the file
8871 (defvar org-after-sorting-entries-or-items-hook nil
8872 "Hook that is run after a bunch of entries or items have been sorted.
8873 When children are sorted, the cursor is in the parent line when this
8874 hook gets called. When a region or a plain list is sorted, the cursor
8875 will be in the first entry of the sorted region/list.")
8877 (defun org-sort-entries
8878 (&optional with-case sorting-type getkey-func compare-func property)
8879 "Sort entries on a certain level of an outline tree.
8880 If there is an active region, the entries in the region are sorted.
8881 Else, if the cursor is before the first entry, sort the top-level items.
8882 Else, the children of the entry at point are sorted.
8884 Sorting can be alphabetically, numerically, by date/time as given by
8885 a time stamp, by a property, by priority order, or by a custom function.
8887 The command prompts for the sorting type unless it has been given to the
8888 function through the SORTING-TYPE argument, which needs to be a character,
8889 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8890 the precise meaning of each character:
8892 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8893 c By creation time, which is assumed to be the first inactive time stamp
8894 at the beginning of a line.
8895 d By deadline date/time.
8896 k By clocking time.
8897 n Numerically, by converting the beginning of the entry/item to a number.
8898 o By order of TODO keywords.
8899 p By priority according to the cookie.
8900 r By the value of a property.
8901 s By scheduled date/time.
8902 t By date/time, either the first active time stamp in the entry, or, if
8903 none exist, by the first inactive one.
8905 Capital letters will reverse the sort order.
8907 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8908 called with point at the beginning of the record. It must return either
8909 a string or a number that should serve as the sorting key for that record.
8911 Comparing entries ignores case by default. However, with an optional argument
8912 WITH-CASE, the sorting considers case as well.
8914 Sorting is done against the visible part of the headlines, it ignores hidden
8915 links.
8917 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8918 (interactive "P")
8919 (let ((case-func (if with-case 'identity 'downcase))
8920 (cmstr
8921 ;; The clock marker is lost when using `sort-subr', let's
8922 ;; store the clocking string.
8923 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8924 (save-excursion
8925 (goto-char org-clock-marker)
8926 (buffer-substring-no-properties (line-beginning-position)
8927 (point)))))
8928 start beg end stars re re2
8929 txt what tmp)
8930 ;; Find beginning and end of region to sort
8931 (cond
8932 ((org-region-active-p)
8933 ;; we will sort the region
8934 (setq end (region-end)
8935 what "region")
8936 (goto-char (region-beginning))
8937 (unless (org-at-heading-p) (outline-next-heading))
8938 (setq start (point)))
8939 ((or (org-at-heading-p)
8940 (ignore-errors (progn (org-back-to-heading) t)))
8941 ;; we will sort the children of the current headline
8942 (org-back-to-heading)
8943 (setq start (point)
8944 end (progn (org-end-of-subtree t t)
8945 (or (bolp) (insert "\n"))
8946 (when (>= (org-back-over-empty-lines) 1)
8947 (forward-line 1))
8948 (point))
8949 what "children")
8950 (goto-char start)
8951 (outline-show-subtree)
8952 (outline-next-heading))
8954 ;; we will sort the top-level entries in this file
8955 (goto-char (point-min))
8956 (or (org-at-heading-p) (outline-next-heading))
8957 (setq start (point))
8958 (goto-char (point-max))
8959 (beginning-of-line 1)
8960 (when (looking-at ".*?\\S-")
8961 ;; File ends in a non-white line
8962 (end-of-line 1)
8963 (insert "\n"))
8964 (setq end (point-max))
8965 (setq what "top-level")
8966 (goto-char start)
8967 (outline-show-all)))
8969 (setq beg (point))
8970 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8972 (looking-at "\\(\\*+\\)")
8973 (setq stars (match-string 1)
8974 re (concat "^" (regexp-quote stars) " +")
8975 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8976 txt (buffer-substring beg end))
8977 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8978 (when (and (not (equal stars "*")) (string-match re2 txt))
8979 (user-error "Region to sort contains a level above the first entry"))
8981 (unless sorting-type
8982 (message
8983 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8984 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8985 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8986 what)
8987 (setq sorting-type (read-char-exclusive))
8989 (unless getkey-func
8990 (and (= (downcase sorting-type) ?f)
8991 (setq getkey-func
8992 (completing-read "Sort using function: "
8993 obarray 'fboundp t nil nil))
8994 (setq getkey-func (intern getkey-func))))
8996 (and (= (downcase sorting-type) ?r)
8997 (not property)
8998 (setq property
8999 (completing-read "Property: "
9000 (mapcar #'list (org-buffer-property-keys t))
9001 nil t))))
9003 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9004 (message "Sorting entries...")
9006 (save-restriction
9007 (narrow-to-region start end)
9008 (let ((dcst (downcase sorting-type))
9009 (case-fold-search nil)
9010 (now (current-time)))
9011 (sort-subr
9012 (/= dcst sorting-type)
9013 ;; This function moves to the beginning character of the "record" to
9014 ;; be sorted.
9015 (lambda nil
9016 (if (re-search-forward re nil t)
9017 (goto-char (match-beginning 0))
9018 (goto-char (point-max))))
9019 ;; This function moves to the last character of the "record" being
9020 ;; sorted.
9021 (lambda nil
9022 (save-match-data
9023 (condition-case nil
9024 (outline-forward-same-level 1)
9025 (error
9026 (goto-char (point-max))))))
9027 ;; This function returns the value that gets sorted against.
9028 (lambda nil
9029 (cond
9030 ((= dcst ?n)
9031 (if (looking-at org-complex-heading-regexp)
9032 (string-to-number (org-sort-remove-invisible (match-string 4)))
9033 nil))
9034 ((= dcst ?a)
9035 (if (looking-at org-complex-heading-regexp)
9036 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9037 nil))
9038 ((= dcst ?k)
9039 (or (get-text-property (point) :org-clock-minutes) 0))
9040 ((= dcst ?t)
9041 (let ((end (save-excursion (outline-next-heading) (point))))
9042 (if (or (re-search-forward org-ts-regexp end t)
9043 (re-search-forward org-ts-regexp-both end t))
9044 (org-time-string-to-seconds (match-string 0))
9045 (float-time now))))
9046 ((= dcst ?c)
9047 (let ((end (save-excursion (outline-next-heading) (point))))
9048 (if (re-search-forward
9049 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9050 end t)
9051 (org-time-string-to-seconds (match-string 0))
9052 (float-time now))))
9053 ((= dcst ?s)
9054 (let ((end (save-excursion (outline-next-heading) (point))))
9055 (if (re-search-forward org-scheduled-time-regexp end t)
9056 (org-time-string-to-seconds (match-string 1))
9057 (float-time now))))
9058 ((= dcst ?d)
9059 (let ((end (save-excursion (outline-next-heading) (point))))
9060 (if (re-search-forward org-deadline-time-regexp end t)
9061 (org-time-string-to-seconds (match-string 1))
9062 (float-time now))))
9063 ((= dcst ?p)
9064 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9065 (string-to-char (match-string 2))
9066 org-default-priority))
9067 ((= dcst ?r)
9068 (or (org-entry-get nil property) ""))
9069 ((= dcst ?o)
9070 (when (looking-at org-complex-heading-regexp)
9071 (let* ((m (match-string 2))
9072 (s (if (member m org-done-keywords) '- '+)))
9073 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9074 ((= dcst ?f)
9075 (if getkey-func
9076 (progn
9077 (setq tmp (funcall getkey-func))
9078 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9079 tmp)
9080 (error "Invalid key function `%s'" getkey-func)))
9081 (t (error "Invalid sorting type `%c'" sorting-type))))
9083 (cond
9084 ((= dcst ?a) 'string<)
9085 ((= dcst ?f) compare-func)
9086 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9087 (run-hooks 'org-after-sorting-entries-or-items-hook)
9088 ;; Reset the clock marker if needed
9089 (when cmstr
9090 (save-excursion
9091 (goto-char start)
9092 (search-forward cmstr nil t)
9093 (move-marker org-clock-marker (point))))
9094 (message "Sorting entries...done")))
9096 ;;; The orgstruct minor mode
9098 ;; Define a minor mode which can be used in other modes in order to
9099 ;; integrate the Org mode structure editing commands.
9101 ;; This is really a hack, because the Org mode structure commands use
9102 ;; keys which normally belong to the major mode. Here is how it
9103 ;; works: The minor mode defines all the keys necessary to operate the
9104 ;; structure commands, but wraps the commands into a function which
9105 ;; tests if the cursor is currently at a headline or a plain list
9106 ;; item. If that is the case, the structure command is used,
9107 ;; temporarily setting many Org mode variables like regular
9108 ;; expressions for filling etc. However, when any of those keys is
9109 ;; used at a different location, function uses `key-binding' to look
9110 ;; up if the key has an associated command in another currently active
9111 ;; keymap (minor modes, major mode, global), and executes that
9112 ;; command. There might be problems if any of the keys is otherwise
9113 ;; used as a prefix key.
9115 (defcustom orgstruct-heading-prefix-regexp ""
9116 "Regexp that matches the custom prefix of Org headlines in
9117 orgstruct(++)-mode."
9118 :group 'org
9119 :version "24.4"
9120 :package-version '(Org . "8.3")
9121 :type 'regexp)
9122 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9124 (defcustom orgstruct-setup-hook nil
9125 "Hook run after orgstruct-mode-map is filled."
9126 :group 'org
9127 :version "24.4"
9128 :package-version '(Org . "8.0")
9129 :type 'hook)
9131 (defvar orgstruct-initialized nil)
9133 (defvar org-local-vars nil
9134 "List of local variables, for use by `orgstruct-mode'.")
9136 ;;;###autoload
9137 (define-minor-mode orgstruct-mode
9138 "Toggle the minor mode `orgstruct-mode'.
9139 This mode is for using Org mode structure commands in other
9140 modes. The following keys behave as if Org mode were active, if
9141 the cursor is on a headline, or on a plain list item (both as
9142 defined by Org mode)."
9143 nil " OrgStruct" (make-sparse-keymap)
9144 (funcall (if orgstruct-mode
9145 'add-to-invisibility-spec
9146 'remove-from-invisibility-spec)
9147 '(outline . t))
9148 (when orgstruct-mode
9149 (org-load-modules-maybe)
9150 (unless orgstruct-initialized
9151 (orgstruct-setup)
9152 (setq orgstruct-initialized t))))
9154 ;;;###autoload
9155 (defun turn-on-orgstruct ()
9156 "Unconditionally turn on `orgstruct-mode'."
9157 (orgstruct-mode 1))
9159 (defvar-local orgstruct-is-++ nil
9160 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9161 (defvar-local org-fb-vars nil)
9162 (defun orgstruct++-mode (&optional arg)
9163 "Toggle `orgstruct-mode', the enhanced version of it.
9164 In addition to setting orgstruct-mode, this also exports all
9165 indentation and autofilling variables from Org mode into the
9166 buffer. It will also recognize item context in multiline items."
9167 (interactive "P")
9168 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9169 (if (< arg 1)
9170 (progn (orgstruct-mode -1)
9171 (dolist (v org-fb-vars)
9172 (set (make-local-variable (car v))
9173 (if (eq (car-safe (cadr v)) 'quote)
9174 (cl-cadadr v)
9175 (nth 1 v)))))
9176 (orgstruct-mode 1)
9177 (setq org-fb-vars nil)
9178 (unless org-local-vars
9179 (setq org-local-vars (org-get-local-variables)))
9180 (let (var val)
9181 (dolist (x org-local-vars)
9182 (when (string-match
9183 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9184 \\|fill-prefix\\|indent-\\)"
9185 (symbol-name (car x)))
9186 (setq var (car x) val (nth 1 x))
9187 (push (list var `(quote ,(eval var))) org-fb-vars)
9188 (set (make-local-variable var)
9189 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9190 (setq-local orgstruct-is-++ t))))
9192 ;;;###autoload
9193 (defun turn-on-orgstruct++ ()
9194 "Unconditionally turn on `orgstruct++-mode'."
9195 (orgstruct++-mode 1))
9197 (defun orgstruct-error ()
9198 "Error when there is no default binding for a structure key."
9199 (interactive)
9200 (funcall (if (fboundp 'user-error)
9201 'user-error
9202 'error)
9203 "This key has no function outside structure elements"))
9205 (defun orgstruct-setup ()
9206 "Setup orgstruct keymap."
9207 (dolist (cell '((org-demote . t)
9208 (org-metaleft . t)
9209 (org-metaright . t)
9210 (org-promote . t)
9211 (org-shiftmetaleft . t)
9212 (org-shiftmetaright . t)
9213 org-backward-element
9214 org-backward-heading-same-level
9215 org-ctrl-c-ret
9216 org-ctrl-c-minus
9217 org-ctrl-c-star
9218 org-cycle
9219 org-force-cycle-archived
9220 org-forward-heading-same-level
9221 org-insert-heading
9222 org-insert-heading-respect-content
9223 org-kill-note-or-show-branches
9224 org-mark-subtree
9225 org-meta-return
9226 org-metadown
9227 org-metaup
9228 org-narrow-to-subtree
9229 org-promote-subtree
9230 org-reveal
9231 org-shiftdown
9232 org-shiftleft
9233 org-shiftmetadown
9234 org-shiftmetaup
9235 org-shiftright
9236 org-shifttab
9237 org-shifttab
9238 org-shiftup
9239 org-show-children
9240 org-show-subtree
9241 org-sort
9242 org-up-element
9243 outline-demote
9244 outline-next-visible-heading
9245 outline-previous-visible-heading
9246 outline-promote
9247 outline-up-heading))
9248 (let ((f (or (car-safe cell) cell))
9249 (disable-when-heading-prefix (cdr-safe cell)))
9250 (when (fboundp f)
9251 (let ((new-bindings))
9252 (dolist (binding (nconc (where-is-internal f org-mode-map)
9253 (where-is-internal f outline-mode-map)))
9254 (push binding new-bindings)
9255 ;; TODO use local-function-key-map
9256 (dolist (rep '(("<tab>" . "TAB")
9257 ("<return>" . "RET")
9258 ("<escape>" . "ESC")
9259 ("<delete>" . "DEL")))
9260 (setq binding (read-kbd-macro
9261 (let ((case-fold-search))
9262 (replace-regexp-in-string
9263 (regexp-quote (cdr rep))
9264 (car rep)
9265 (key-description binding)))))
9266 (cl-pushnew binding new-bindings :test 'equal)))
9267 (dolist (binding new-bindings)
9268 (let ((key (lookup-key orgstruct-mode-map binding)))
9269 (when (or (not key) (numberp key))
9270 (ignore-errors
9271 (org-defkey orgstruct-mode-map
9272 binding
9273 (orgstruct-make-binding
9274 f binding disable-when-heading-prefix))))))))))
9275 (run-hooks 'orgstruct-setup-hook))
9277 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9278 "Create a function for binding in the structure minor mode.
9279 FUN is the command to call inside a table. KEY is the key that
9280 should be checked in for a command to execute outside of tables.
9281 Non-nil `disable-when-heading-prefix' means to disable the command
9282 if `orgstruct-heading-prefix-regexp' is not empty."
9283 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9284 (let ((nname name)
9285 (i 0))
9286 (while (fboundp (intern nname))
9287 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9288 (setq name (intern nname)))
9289 (eval
9290 (let ((bindings '((org-heading-regexp
9291 (concat "^"
9292 orgstruct-heading-prefix-regexp
9293 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9294 (org-outline-regexp
9295 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9296 (org-outline-regexp-bol
9297 (concat "^" org-outline-regexp))
9298 (outline-regexp org-outline-regexp)
9299 (outline-heading-end-regexp "\n")
9300 (outline-level 'org-outline-level)
9301 (outline-heading-alist))))
9302 `(defun ,name (arg)
9303 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9304 "Outside of structure, run the binding of `"
9305 (key-description key) "'."
9306 (when disable-when-heading-prefix
9307 (concat
9308 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9309 "back to the default binding due to limitations of Org's implementation of\n"
9310 "`" (symbol-name fun) "'.")))
9311 (interactive "p")
9312 (let* ((disable
9313 ,(and disable-when-heading-prefix
9314 '(not (string= orgstruct-heading-prefix-regexp ""))))
9315 (fallback
9316 (or disable
9317 (not
9318 (let* ,bindings
9319 (org-context-p 'headline 'item
9320 ,(when (memq fun
9321 '(org-insert-heading
9322 org-insert-heading-respect-content
9323 org-meta-return))
9324 '(when orgstruct-is-++
9325 'item-body))))))))
9326 (if fallback
9327 (let* ((orgstruct-mode)
9328 (binding
9329 (let ((key ,key))
9330 (catch 'exit
9331 (dolist
9332 (rep
9333 '(nil
9334 ("<\\([^>]*\\)tab>" . "\\1TAB")
9335 ("<\\([^>]*\\)return>" . "\\1RET")
9336 ("<\\([^>]*\\)escape>" . "\\1ESC")
9337 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9338 nil)
9339 (when rep
9340 (setq key (read-kbd-macro
9341 (let ((case-fold-search))
9342 (replace-regexp-in-string
9343 (car rep)
9344 (cdr rep)
9345 (key-description key))))))
9346 (when (key-binding key)
9347 (throw 'exit (key-binding key))))))))
9348 (if (keymapp binding)
9349 (org-set-transient-map binding)
9350 (let ((func (or binding
9351 (unless disable
9352 'orgstruct-error))))
9353 (when func
9354 (call-interactively func)))))
9355 (org-run-like-in-org-mode
9356 (lambda ()
9357 (interactive)
9358 (let* ,bindings
9359 (call-interactively ',fun)))))))))
9360 name))
9362 (defun org-contextualize-keys (alist contexts)
9363 "Return valid elements in ALIST depending on CONTEXTS.
9365 `org-agenda-custom-commands' or `org-capture-templates' are the
9366 values used for ALIST, and `org-agenda-custom-commands-contexts'
9367 or `org-capture-templates-contexts' are the associated contexts
9368 definitions."
9369 (let ((contexts
9370 ;; normalize contexts
9371 (mapcar
9372 (lambda(c) (cond ((listp (cadr c))
9373 (list (car c) (car c) (nth 1 c)))
9374 ((string= "" (cadr c))
9375 (list (car c) (car c) (nth 2 c)))
9376 (t c)))
9377 contexts))
9378 (a alist) r s)
9379 ;; loop over all commands or templates
9380 (dolist (c a)
9381 (let (vrules repl)
9382 (cond
9383 ((not (assoc (car c) contexts))
9384 (push c r))
9385 ((and (assoc (car c) contexts)
9386 (setq vrules (org-contextualize-validate-key
9387 (car c) contexts)))
9388 (mapc (lambda (vr)
9389 (unless (equal (car vr) (cadr vr))
9390 (setq repl vr)))
9391 vrules)
9392 (if (not repl) (push c r)
9393 (push (cadr repl) s)
9394 (push
9395 (cons (car c)
9396 (cdr (or (assoc (cadr repl) alist)
9397 (error "Undefined key `%s' as contextual replacement for `%s'"
9398 (cadr repl) (car c)))))
9399 r))))))
9400 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9401 (delq
9403 (delete-dups
9404 (mapcar (lambda (x)
9405 (let ((tpl (car x)))
9406 (unless (delq
9408 (mapcar (lambda (y)
9409 (equal y tpl))
9411 x)))
9412 (reverse r))))))
9414 (defun org-contextualize-validate-key (key contexts)
9415 "Check CONTEXTS for agenda or capture KEY."
9416 (let (res)
9417 (dolist (r contexts)
9418 (dolist (rr (car (last r)))
9419 (when
9420 (and (equal key (car r))
9421 (if (functionp rr) (funcall rr)
9422 (or (and (eq (car rr) 'in-file)
9423 (buffer-file-name)
9424 (string-match (cdr rr) (buffer-file-name)))
9425 (and (eq (car rr) 'in-mode)
9426 (string-match (cdr rr) (symbol-name major-mode)))
9427 (and (eq (car rr) 'in-buffer)
9428 (string-match (cdr rr) (buffer-name)))
9429 (when (and (eq (car rr) 'not-in-file)
9430 (buffer-file-name))
9431 (not (string-match (cdr rr) (buffer-file-name))))
9432 (when (eq (car rr) 'not-in-mode)
9433 (not (string-match (cdr rr) (symbol-name major-mode))))
9434 (when (eq (car rr) 'not-in-buffer)
9435 (not (string-match (cdr rr) (buffer-name)))))))
9436 (push r res))))
9437 (delete-dups (delq nil res))))
9439 (defun org-context-p (&rest contexts)
9440 "Check if local context is any of CONTEXTS.
9441 Possible values in the list of contexts are `table', `headline', and `item'."
9442 (let ((pos (point)))
9443 (goto-char (point-at-bol))
9444 (prog1 (or (and (memq 'table contexts)
9445 (looking-at "[ \t]*|"))
9446 (and (memq 'headline contexts)
9447 (looking-at org-outline-regexp))
9448 (and (memq 'item contexts)
9449 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9450 (and (memq 'item-body contexts)
9451 (org-in-item-p)))
9452 (goto-char pos))))
9454 (defconst org-unique-local-variables
9455 '(org-element--cache
9456 org-element--cache-objects
9457 org-element--cache-sync-keys
9458 org-element--cache-sync-requests
9459 org-element--cache-sync-timer)
9460 "List of local variables that cannot be transferred to another buffer.")
9462 (defun org-get-local-variables ()
9463 "Return a list of all local variables in an Org mode buffer."
9464 (delq nil
9465 (mapcar
9466 (lambda (x)
9467 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9468 (name (car binding)))
9469 (and (not (get name 'org-state))
9470 (not (memq name org-unique-local-variables))
9471 (string-match-p
9472 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9473 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9474 (symbol-name name))
9475 binding)))
9476 (with-temp-buffer
9477 (org-mode)
9478 (buffer-local-variables)))))
9480 (defun org-clone-local-variables (from-buffer &optional regexp)
9481 "Clone local variables from FROM-BUFFER.
9482 Optional argument REGEXP selects variables to clone."
9483 (dolist (pair (buffer-local-variables from-buffer))
9484 (let ((name (car pair)))
9485 (when (and (symbolp name)
9486 (not (memq name org-unique-local-variables))
9487 (or (null regexp) (string-match regexp (symbol-name name))))
9488 (set (make-local-variable name) (cdr pair))))))
9490 ;;;###autoload
9491 (defun org-run-like-in-org-mode (cmd)
9492 "Run a command, pretending that the current buffer is in Org mode.
9493 This will temporarily bind local variables that are typically bound in
9494 Org mode to the values they have in Org mode, and then interactively
9495 call CMD."
9496 (org-load-modules-maybe)
9497 (unless org-local-vars
9498 (setq org-local-vars (org-get-local-variables)))
9499 (let (binds)
9500 (dolist (var org-local-vars)
9501 (when (or (not (boundp (car var)))
9502 (eq (symbol-value (car var))
9503 (default-value (car var))))
9504 (push (list (car var) `(quote ,(cadr var))) binds)))
9505 (eval `(let ,binds
9506 (call-interactively (quote ,cmd))))))
9508 (defun org-get-category (&optional pos force-refresh)
9509 "Get the category applying to position POS."
9510 (save-match-data
9511 (when force-refresh (org-refresh-category-properties))
9512 (let ((pos (or pos (point))))
9513 (or (get-text-property pos 'org-category)
9514 (progn (org-refresh-category-properties)
9515 (get-text-property pos 'org-category))))))
9517 ;;; Refresh properties
9519 (defun org-refresh-properties (dprop tprop)
9520 "Refresh buffer text properties.
9521 DPROP is the drawer property and TPROP is either the
9522 corresponding text property to set, or an alist with each element
9523 being a text property (as a symbol) and a function to apply to
9524 the value of the drawer property."
9525 (let* ((case-fold-search t)
9526 (inhibit-read-only t)
9527 (inherit? (org-property-inherit-p dprop))
9528 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9529 (global (and inherit? (org--property-global-value dprop nil))))
9530 (org-with-silent-modifications
9531 (org-with-point-at 1
9532 ;; Set global values (e.g., values defined through
9533 ;; "#+PROPERTY:" keywords) to the whole buffer.
9534 (when global (put-text-property (point-min) (point-max) tprop global))
9535 ;; Set local values.
9536 (while (re-search-forward property-re nil t)
9537 (when (org-at-property-p)
9538 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9539 (outline-next-heading))))))
9541 (defun org-refresh-property (tprop p &optional inherit)
9542 "Refresh the buffer text property TPROP from the drawer property P.
9543 The refresh happens only for the current headline, or the whole
9544 sub-tree if optional argument INHERIT is non-nil."
9545 (unless (org-before-first-heading-p)
9546 (save-excursion
9547 (org-back-to-heading t)
9548 (let ((start (point))
9549 (end (save-excursion
9550 (if inherit (org-end-of-subtree t t)
9551 (or (outline-next-heading) (point-max))))))
9552 (if (symbolp tprop)
9553 ;; TPROP is a text property symbol.
9554 (put-text-property start end tprop p)
9555 ;; TPROP is an alist with (property . function) elements.
9556 (pcase-dolist (`(,prop . ,f) tprop)
9557 (put-text-property start end prop (funcall f p))))))))
9559 (defun org-refresh-category-properties ()
9560 "Refresh category text properties in the buffer."
9561 (let ((case-fold-search t)
9562 (inhibit-read-only t)
9563 (default-category
9564 (cond ((null org-category)
9565 (if buffer-file-name
9566 (file-name-sans-extension
9567 (file-name-nondirectory buffer-file-name))
9568 "???"))
9569 ((symbolp org-category) (symbol-name org-category))
9570 (t org-category))))
9571 (org-with-silent-modifications
9572 (org-with-wide-buffer
9573 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9574 ;; This is the default category for the buffer. If none is
9575 ;; found, fall-back to `org-category' or buffer file name.
9576 (put-text-property
9577 (point-min) (point-max)
9578 'org-category
9579 (catch 'buffer-category
9580 (goto-char (point-max))
9581 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9582 (let ((element (org-element-at-point)))
9583 (when (eq (org-element-type element) 'keyword)
9584 (throw 'buffer-category
9585 (org-element-property :value element)))))
9586 default-category))
9587 ;; Set sub-tree specific categories.
9588 (goto-char (point-min))
9589 (let ((regexp (org-re-property "CATEGORY")))
9590 (while (re-search-forward regexp nil t)
9591 (let ((value (match-string-no-properties 3)))
9592 (when (org-at-property-p)
9593 (put-text-property
9594 (save-excursion (org-back-to-heading t) (point))
9595 (save-excursion (org-end-of-subtree t t) (point))
9596 'org-category
9597 value)))))))))
9599 (defun org-refresh-stats-properties ()
9600 "Refresh stats text properties in the buffer."
9601 (let (stats)
9602 (org-with-silent-modifications
9603 (org-with-wide-buffer
9604 (goto-char (point-min))
9605 (while (re-search-forward
9606 (concat org-outline-regexp-bol ".*"
9607 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9608 nil t)
9609 (setq stats (cond ((equal (match-string 3) "0") 0)
9610 ((match-string 2)
9611 (/ (* (string-to-number (match-string 2)) 100)
9612 (string-to-number (match-string 3))))
9613 (t (string-to-number (match-string 1)))))
9614 (org-back-to-heading t)
9615 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9616 'org-stats stats))))))
9618 (defun org-refresh-effort-properties ()
9619 "Refresh effort properties"
9620 (org-refresh-properties
9621 org-effort-property
9622 '((effort . identity)
9623 (effort-minutes . org-duration-to-minutes))))
9625 ;;;; Link Stuff
9627 ;;; Link abbreviations
9629 (defun org-link-expand-abbrev (link)
9630 "Apply replacements as defined in `org-link-abbrev-alist'."
9631 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9632 (let* ((key (match-string 1 link))
9633 (as (or (assoc key org-link-abbrev-alist-local)
9634 (assoc key org-link-abbrev-alist)))
9635 (tag (and (match-end 2) (match-string 3 link)))
9636 rpl)
9637 (if (not as)
9638 link
9639 (setq rpl (cdr as))
9640 (cond
9641 ((symbolp rpl) (funcall rpl tag))
9642 ((string-match "%(\\([^)]+\\))" rpl)
9643 (replace-match
9644 (save-match-data
9645 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9646 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9647 ((string-match "%h" rpl)
9648 (replace-match (url-hexify-string (or tag "")) t t rpl))
9649 (t (concat rpl tag)))))
9650 link))
9652 ;;; Storing and inserting links
9654 (defvar org-insert-link-history nil
9655 "Minibuffer history for links inserted with `org-insert-link'.")
9657 (defvar org-stored-links nil
9658 "Contains the links stored with `org-store-link'.")
9660 (defvar org-store-link-plist nil
9661 "Plist with info about the most recently link created with `org-store-link'.")
9663 (defun org-store-link-functions ()
9664 "Return a list of functions that are called to create and store a link.
9665 The functions defined in the :store property of
9666 `org-link-parameters'.
9668 Each function will be called in turn until one returns a non-nil
9669 value. Each function should check if it is responsible for
9670 creating this link (for example by looking at the major mode).
9671 If not, it must exit and return nil. If yes, it should return
9672 a non-nil value after calling `org-store-link-props' with a list
9673 of properties and values. Special properties are:
9675 :type The link prefix, like \"http\". This must be given.
9676 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9677 This is obligatory as well.
9678 :description Optional default description for the second pair
9679 of brackets in an Org mode link. The user can still change
9680 this when inserting this link into an Org mode buffer.
9682 In addition to these, any additional properties can be specified
9683 and then used in capture templates."
9684 (cl-loop for link in org-link-parameters
9685 with store-func
9686 do (setq store-func (org-link-get-parameter (car link) :store))
9687 if store-func
9688 collect store-func))
9690 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9691 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9693 ;;;###autoload
9694 (defun org-store-link (arg)
9695 "Store an org-link to the current location.
9696 \\<org-mode-map>
9697 This link is added to `org-stored-links' and can later be inserted
9698 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9700 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9701 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9702 For file links, ARG negates `org-context-in-file-links'.
9704 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9705 skipping storing functions that are not
9706 part of Org core.
9708 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9709 prefix ARG forces storing a link for each line in the
9710 active region."
9711 (interactive "P")
9712 (org-load-modules-maybe)
9713 (if (and (equal arg '(64)) (org-region-active-p))
9714 (save-excursion
9715 (let ((end (region-end)))
9716 (goto-char (region-beginning))
9717 (set-mark (point))
9718 (while (< (point-at-eol) end)
9719 (move-end-of-line 1) (activate-mark)
9720 (let (current-prefix-arg)
9721 (call-interactively 'org-store-link))
9722 (move-beginning-of-line 2)
9723 (set-mark (point)))))
9724 (setq org-store-link-plist nil)
9725 (let (link cpltxt desc description search
9726 txt custom-id agenda-link sfuns sfunsn)
9727 (cond
9729 ;; Store a link using an external link type
9730 ((and (not (equal arg '(16)))
9731 (setq sfuns
9732 (delq
9733 nil (mapcar (lambda (f)
9734 (let (fs) (if (funcall f) (push f fs))))
9735 (org-store-link-functions)))
9736 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9737 (or (and (cdr sfuns)
9738 (funcall (intern
9739 (completing-read
9740 "Which function for creating the link? "
9741 sfunsn nil t (car sfunsn)))))
9742 (funcall (caar sfuns)))
9743 (setq link (plist-get org-store-link-plist :link)
9744 desc (or (plist-get org-store-link-plist
9745 :description)
9746 link))))
9748 ;; Store a link from a source code buffer.
9749 ((org-src-edit-buffer-p)
9750 (let ((coderef-format (org-src-coderef-format)))
9751 (cond ((save-excursion
9752 (beginning-of-line)
9753 (looking-at (org-src-coderef-regexp coderef-format)))
9754 (setq link (format "(%s)" (match-string-no-properties 3))))
9755 ((called-interactively-p 'any)
9756 (let ((label (read-string "Code line label: ")))
9757 (end-of-line)
9758 (setq link (format coderef-format label))
9759 (let ((gc (- 79 (length link))))
9760 (if (< (current-column) gc)
9761 (org-move-to-column gc t)
9762 (insert " ")))
9763 (insert link)
9764 (setq link (concat "(" label ")"))
9765 (setq desc nil)))
9766 (t (setq link nil)))))
9768 ;; We are in the agenda, link to referenced location
9769 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9770 (let ((m (or (get-text-property (point) 'org-hd-marker)
9771 (get-text-property (point) 'org-marker))))
9772 (when m
9773 (org-with-point-at m
9774 (setq agenda-link
9775 (if (called-interactively-p 'any)
9776 (call-interactively 'org-store-link)
9777 (org-store-link nil)))))))
9779 ((eq major-mode 'calendar-mode)
9780 (let ((cd (calendar-cursor-to-date)))
9781 (setq link
9782 (format-time-string
9783 (car org-time-stamp-formats)
9784 (apply 'encode-time
9785 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9786 nil nil nil))))
9787 (org-store-link-props :type "calendar" :date cd)))
9789 ((eq major-mode 'help-mode)
9790 (setq link (concat "help:" (save-excursion
9791 (goto-char (point-min))
9792 (looking-at "^[^ ]+")
9793 (match-string 0))))
9794 (org-store-link-props :type "help"))
9796 ((eq major-mode 'w3-mode)
9797 (setq cpltxt (if (and (buffer-name)
9798 (not (string-match "Untitled" (buffer-name))))
9799 (buffer-name)
9800 (url-view-url t))
9801 link (url-view-url t))
9802 (org-store-link-props :type "w3" :url (url-view-url t)))
9804 ((eq major-mode 'image-mode)
9805 (setq cpltxt (concat "file:"
9806 (abbreviate-file-name buffer-file-name))
9807 link cpltxt)
9808 (org-store-link-props :type "image" :file buffer-file-name))
9810 ;; In dired, store a link to the file of the current line
9811 ((derived-mode-p 'dired-mode)
9812 (let ((file (dired-get-filename nil t)))
9813 (setq file (if file
9814 (abbreviate-file-name
9815 (expand-file-name (dired-get-filename nil t)))
9816 ;; otherwise, no file so use current directory.
9817 default-directory))
9818 (setq cpltxt (concat "file:" file)
9819 link cpltxt)))
9821 ((setq search (run-hook-with-args-until-success
9822 'org-create-file-search-functions))
9823 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9824 "::" search))
9825 (setq cpltxt (or description link)))
9827 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9828 (org-with-limited-levels
9829 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9830 (cond
9831 ;; Store a link using the target at point
9832 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9833 (setq cpltxt
9834 (concat "file:"
9835 (abbreviate-file-name
9836 (buffer-file-name (buffer-base-buffer)))
9837 "::" (match-string 1))
9838 link cpltxt))
9839 ((and (featurep 'org-id)
9840 (or (eq org-id-link-to-org-use-id t)
9841 (and (called-interactively-p 'any)
9842 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9843 (and (eq org-id-link-to-org-use-id
9844 'create-if-interactive-and-no-custom-id)
9845 (not custom-id))))
9846 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9847 ;; Store a link using the ID at point
9848 (setq link (condition-case nil
9849 (prog1 (org-id-store-link)
9850 (setq desc (or (plist-get org-store-link-plist
9851 :description)
9852 "")))
9853 (error
9854 ;; Probably before first headline, link only to file
9855 (concat "file:"
9856 (abbreviate-file-name
9857 (buffer-file-name (buffer-base-buffer))))))))
9859 ;; Just link to current headline
9860 (setq cpltxt (concat "file:"
9861 (abbreviate-file-name
9862 (buffer-file-name (buffer-base-buffer)))))
9863 ;; Add a context search string
9864 (when (org-xor org-context-in-file-links arg)
9865 (let* ((element (org-element-at-point))
9866 (name (org-element-property :name element)))
9867 (setq txt (cond
9868 ((org-at-heading-p) nil)
9869 (name)
9870 ((org-region-active-p)
9871 (buffer-substring (region-beginning) (region-end)))))
9872 (when (or (null txt) (string-match "\\S-" txt))
9873 (setq cpltxt
9874 (concat cpltxt "::"
9875 (condition-case nil
9876 (org-make-org-heading-search-string txt)
9877 (error "")))
9878 desc (or name
9879 (nth 4 (ignore-errors (org-heading-components)))
9880 "NONE")))))
9881 (when (string-match "::\\'" cpltxt)
9882 (setq cpltxt (substring cpltxt 0 -2)))
9883 (setq link cpltxt)))))
9885 ((buffer-file-name (buffer-base-buffer))
9886 ;; Just link to this file here.
9887 (setq cpltxt (concat "file:"
9888 (abbreviate-file-name
9889 (buffer-file-name (buffer-base-buffer)))))
9890 ;; Add a context string.
9891 (when (org-xor org-context-in-file-links arg)
9892 (setq txt (if (org-region-active-p)
9893 (buffer-substring (region-beginning) (region-end))
9894 (buffer-substring (point-at-bol) (point-at-eol))))
9895 ;; Only use search option if there is some text.
9896 (when (string-match "\\S-" txt)
9897 (setq cpltxt
9898 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9899 desc "NONE")))
9900 (setq link cpltxt))
9902 ((called-interactively-p 'interactive)
9903 (user-error "No method for storing a link from this buffer"))
9905 (t (setq link nil)))
9907 ;; We're done setting link and desc, clean up
9908 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9909 (setq link (or link cpltxt)
9910 desc (or desc cpltxt))
9911 (cond ((not desc))
9912 ((equal desc "NONE") (setq desc nil))
9913 (t (setq desc
9914 (replace-regexp-in-string
9915 org-bracket-link-analytic-regexp
9916 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9917 desc))))
9918 ;; Return the link
9919 (if (not (and (or (called-interactively-p 'any)
9920 executing-kbd-macro)
9921 link))
9922 (or agenda-link (and link (org-make-link-string link desc)))
9923 (push (list link desc) org-stored-links)
9924 (message "Stored: %s" (or desc link))
9925 (when custom-id
9926 (setq link (concat "file:" (abbreviate-file-name
9927 (buffer-file-name)) "::#" custom-id))
9928 (push (list link desc) org-stored-links))
9929 (car org-stored-links)))))
9931 (defun org-store-link-props (&rest plist)
9932 "Store link properties, extract names, addresses and dates."
9933 (let ((x (plist-get plist :from)))
9934 (when x
9935 (let ((adr (mail-extract-address-components x)))
9936 (setq plist (plist-put plist :fromname (car adr)))
9937 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9938 (let ((x (plist-get plist :to)))
9939 (when x
9940 (let ((adr (mail-extract-address-components x)))
9941 (setq plist (plist-put plist :toname (car adr)))
9942 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9943 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9944 (when x
9945 (setq plist (plist-put plist :date-timestamp
9946 (format-time-string
9947 (org-time-stamp-format t) x)))
9948 (setq plist (plist-put plist :date-timestamp-inactive
9949 (format-time-string
9950 (org-time-stamp-format t t) x)))))
9951 (let ((from (plist-get plist :from))
9952 (to (plist-get plist :to)))
9953 (when (and from to org-from-is-user-regexp)
9954 (setq plist
9955 (plist-put plist :fromto
9956 (if (string-match org-from-is-user-regexp from)
9957 (concat "to %t")
9958 (concat "from %f"))))))
9959 (setq org-store-link-plist plist))
9961 (defun org-add-link-props (&rest plist)
9962 "Add these properties to the link property list."
9963 (let (key value)
9964 (while plist
9965 (setq key (pop plist) value (pop plist))
9966 (setq org-store-link-plist
9967 (plist-put org-store-link-plist key value)))))
9969 (defun org-email-link-description (&optional fmt)
9970 "Return the description part of an email link.
9971 This takes information from `org-store-link-plist' and formats it
9972 according to FMT (default from `org-email-link-description-format')."
9973 (setq fmt (or fmt org-email-link-description-format))
9974 (let* ((p org-store-link-plist)
9975 (to (plist-get p :toaddress))
9976 (from (plist-get p :fromaddress))
9977 (table
9978 (list
9979 (cons "%c" (plist-get p :fromto))
9980 (cons "%F" (plist-get p :from))
9981 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9982 (cons "%T" (plist-get p :to))
9983 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9984 (cons "%s" (plist-get p :subject))
9985 (cons "%d" (plist-get p :date))
9986 (cons "%m" (plist-get p :message-id)))))
9987 (when (string-match "%c" fmt)
9988 ;; Check if the user wrote this message
9989 (if (and org-from-is-user-regexp from to
9990 (save-match-data (string-match org-from-is-user-regexp from)))
9991 (setq fmt (replace-match "to %t" t t fmt))
9992 (setq fmt (replace-match "from %f" t t fmt))))
9993 (org-replace-escapes fmt table)))
9995 (defun org-make-org-heading-search-string (&optional string)
9996 "Make search string for the current headline or STRING."
9997 (let ((s (or string
9998 (and (derived-mode-p 'org-mode)
9999 (save-excursion
10000 (org-back-to-heading t)
10001 (org-element-property :raw-value (org-element-at-point))))))
10002 (lines org-context-in-file-links))
10003 (or string (setq s (concat "*" s))) ; Add * for headlines
10004 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10005 (when (and string (integerp lines) (> lines 0))
10006 (let ((slines (org-split-string s "\n")))
10007 (when (< lines (length slines))
10008 (setq s (mapconcat
10009 'identity
10010 (reverse (nthcdr (- (length slines) lines)
10011 (reverse slines))) "\n")))))
10012 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10014 (defun org-make-link-string (link &optional description)
10015 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10016 (unless (org-string-nw-p link) (error "Empty link"))
10017 (let ((uri (cond ((string-match org-link-types-re link)
10018 (concat (match-string 1 link)
10019 (org-link-escape (substring link (match-end 1)))))
10020 ;; For readability, url-encode internal links only
10021 ;; when absolutely needed (i.e, when they contain
10022 ;; square brackets). File links however, are
10023 ;; encoded since, e.g., spaces are significant.
10024 ((or (file-name-absolute-p link)
10025 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10026 (org-link-escape link))
10027 (t link)))
10028 (description
10029 (and (org-string-nw-p description)
10030 ;; Remove brackets from description, as they are fatal.
10031 (replace-regexp-in-string
10032 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10033 (org-trim description)))))
10034 (format "[[%s]%s]"
10036 (if description (format "[%s]" description) ""))))
10038 (defconst org-link-escape-chars
10039 ;;%20 %5B %5D %25
10040 '(?\s ?\[ ?\] ?%)
10041 "List of characters that should be escaped in a link when stored to Org.
10042 This is the list that is used for internal purposes.")
10044 (defun org-link-escape (text &optional table merge)
10045 "Return percent escaped representation of TEXT.
10046 TEXT is a string with the text to escape.
10047 Optional argument TABLE is a list with characters that should be
10048 escaped. When nil, `org-link-escape-chars' is used.
10049 If optional argument MERGE is set, merge TABLE into
10050 `org-link-escape-chars'."
10051 (let ((characters-to-encode
10052 (cond ((null table) org-link-escape-chars)
10053 (merge (append org-link-escape-chars table))
10054 (t table))))
10055 (mapconcat
10056 (lambda (c)
10057 (if (or (memq c characters-to-encode)
10058 (and org-url-hexify-p (or (< c 32) (> c 126))))
10059 (mapconcat (lambda (e) (format "%%%.2X" e))
10060 (or (encode-coding-char c 'utf-8)
10061 (error "Unable to percent escape character: %c" c))
10063 (char-to-string c)))
10064 text "")))
10066 (defun org-link-unescape (str)
10067 "Unhex hexified Unicode parts in string STR.
10068 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10069 reciprocal of `org-link-escape', which see."
10070 (if (org-string-nw-p str)
10071 (replace-regexp-in-string
10072 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10073 str))
10075 (defun org-link-unescape-compound (hex)
10076 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10077 Note: this function also decodes single byte encodings like
10078 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10079 (save-match-data
10080 (let* ((bytes (cdr (split-string hex "%")))
10081 (ret "")
10082 (eat 0)
10083 (sum 0))
10084 (while bytes
10085 (let* ((val (string-to-number (pop bytes) 16))
10086 (shift-xor
10087 (if (= 0 eat)
10088 (cond
10089 ((>= val 252) (cons 6 252))
10090 ((>= val 248) (cons 5 248))
10091 ((>= val 240) (cons 4 240))
10092 ((>= val 224) (cons 3 224))
10093 ((>= val 192) (cons 2 192))
10094 (t (cons 0 0)))
10095 (cons 6 128))))
10096 (when (>= val 192) (setq eat (car shift-xor)))
10097 (setq val (logxor val (cdr shift-xor)))
10098 (setq sum (+ (lsh sum (car shift-xor)) val))
10099 (when (> eat 0) (setq eat (- eat 1)))
10100 (cond
10101 ((= 0 eat) ;multi byte
10102 (setq ret (concat ret (char-to-string sum)))
10103 (setq sum 0))
10104 ((not bytes) ; single byte(s)
10105 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10106 ret)))
10108 (defun org-link-unescape-single-byte-sequence (hex)
10109 "Unhexify hex-encoded single byte character sequences."
10110 (mapconcat (lambda (byte)
10111 (char-to-string (string-to-number byte 16)))
10112 (cdr (split-string hex "%")) ""))
10114 (defun org-xor (a b)
10115 "Exclusive or."
10116 (if a (not b) b))
10118 (defun org-fixup-message-id-for-http (s)
10119 "Replace special characters in a message id, so it can be used in an http query."
10120 (when (string-match "%" s)
10121 (setq s (mapconcat (lambda (c)
10122 (if (eq c ?%)
10123 "%25"
10124 (char-to-string c)))
10125 s "")))
10126 (while (string-match "<" s)
10127 (setq s (replace-match "%3C" t t s)))
10128 (while (string-match ">" s)
10129 (setq s (replace-match "%3E" t t s)))
10130 (while (string-match "@" s)
10131 (setq s (replace-match "%40" t t s)))
10134 (defun org-link-prettify (link)
10135 "Return a human-readable representation of LINK.
10136 The car of LINK must be a raw link.
10137 The cdr of LINK must be either a link description or nil."
10138 (let ((desc (or (cadr link) "<no description>")))
10139 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10140 "<" (car link) ">")))
10142 ;;;###autoload
10143 (defun org-insert-link-global ()
10144 "Insert a link like Org mode does.
10145 This command can be called in any mode to insert a link in Org syntax."
10146 (interactive)
10147 (org-load-modules-maybe)
10148 (org-run-like-in-org-mode 'org-insert-link))
10150 (defun org-insert-all-links (arg &optional pre post)
10151 "Insert all links in `org-stored-links'.
10152 When a universal prefix, do not delete the links from `org-stored-links'.
10153 When `ARG' is a number, insert the last N link(s).
10154 `PRE' and `POST' are optional arguments to define a string to
10155 prepend or to append."
10156 (interactive "P")
10157 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10158 (links (copy-sequence org-stored-links))
10159 (pr (or pre "- "))
10160 (po (or post "\n"))
10161 (cnt 1) l)
10162 (if (null org-stored-links)
10163 (message "No link to insert")
10164 (while (and (or (listp arg) (>= arg cnt))
10165 (setq l (if (listp arg)
10166 (pop links)
10167 (pop org-stored-links))))
10168 (setq cnt (1+ cnt))
10169 (insert pr)
10170 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10171 (insert po)))))
10173 (defun org-insert-last-stored-link (arg)
10174 "Insert the last link stored in `org-stored-links'."
10175 (interactive "p")
10176 (org-insert-all-links arg "" "\n"))
10178 (defun org-link-fontify-links-to-this-file ()
10179 "Fontify links to the current file in `org-stored-links'."
10180 (let ((f (buffer-file-name)) a b)
10181 (setq a (mapcar (lambda(l)
10182 (let ((ll (car l)))
10183 (when (and (string-match "^file:\\(.+\\)::" ll)
10184 (equal f (expand-file-name (match-string 1 ll))))
10185 ll)))
10186 org-stored-links))
10187 (when (featurep 'org-id)
10188 (setq b (mapcar (lambda(l)
10189 (let ((ll (car l)))
10190 (when (and (string-match "^id:\\(.+\\)$" ll)
10191 (equal f (expand-file-name
10192 (or (org-id-find-id-file
10193 (match-string 1 ll)) ""))))
10194 ll)))
10195 org-stored-links)))
10196 (mapcar (lambda(l)
10197 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10198 (delq nil (append a b)))))
10200 (defvar org--links-history nil)
10201 (defun org-insert-link (&optional complete-file link-location default-description)
10202 "Insert a link. At the prompt, enter the link.
10204 Completion can be used to insert any of the link protocol prefixes in use.
10206 The history can be used to select a link previously stored with
10207 `org-store-link'. When the empty string is entered (i.e. if you just
10208 press `RET' at the prompt), the link defaults to the most recently
10209 stored link. As `SPC' triggers completion in the minibuffer, you need to
10210 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10212 You will also be prompted for a description, and if one is given, it will
10213 be displayed in the buffer instead of the link.
10215 If there is already a link at point, this command will allow you to edit
10216 link and description parts.
10218 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10219 file name can be
10220 selected using completion. The path to the file will be relative to the
10221 current directory if the file is in the current directory or a subdirectory.
10222 Otherwise, the link will be the absolute path as completed in the minibuffer
10223 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10224 option `org-link-file-path-type'.
10226 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10227 absolute path even if the file is in
10228 the current directory or below.
10230 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10231 prefix negates `org-keep-stored-link-after-insertion'.
10233 If `org-make-link-description-function' is non-nil, this function will be
10234 called with the link target, and the result will be the default
10235 link description.
10237 If the LINK-LOCATION parameter is non-nil, this value will be used as
10238 the link location instead of reading one interactively.
10240 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10241 as the default description."
10242 (interactive "P")
10243 (let* ((wcf (current-window-configuration))
10244 (origbuf (current-buffer))
10245 (region (when (org-region-active-p)
10246 (buffer-substring (region-beginning) (region-end))))
10247 (remove (and region (list (region-beginning) (region-end))))
10248 (desc region)
10249 (link link-location)
10250 (abbrevs org-link-abbrev-alist-local)
10251 entry all-prefixes auto-desc)
10252 (cond
10253 (link-location) ; specified by arg, just use it.
10254 ((org-in-regexp org-bracket-link-regexp 1)
10255 ;; We do have a link at point, and we are going to edit it.
10256 (setq remove (list (match-beginning 0) (match-end 0)))
10257 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10258 (setq link (read-string "Link: "
10259 (org-link-unescape
10260 (match-string-no-properties 1)))))
10261 ((or (org-in-regexp org-angle-link-re)
10262 (org-in-regexp org-plain-link-re))
10263 ;; Convert to bracket link
10264 (setq remove (list (match-beginning 0) (match-end 0))
10265 link (read-string "Link: "
10266 (org-unbracket-string "<" ">" (match-string 0)))))
10267 ((member complete-file '((4) (16)))
10268 ;; Completing read for file names.
10269 (setq link (org-file-complete-link complete-file)))
10271 ;; Read link, with completion for stored links.
10272 (org-link-fontify-links-to-this-file)
10273 (org-switch-to-buffer-other-window "*Org Links*")
10274 (with-current-buffer "*Org Links*"
10275 (erase-buffer)
10276 (insert "Insert a link.
10277 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10278 (when org-stored-links
10279 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10280 (insert (mapconcat 'org-link-prettify
10281 (reverse org-stored-links) "\n")))
10282 (goto-char (point-min)))
10283 (let ((cw (selected-window)))
10284 (select-window (get-buffer-window "*Org Links*" 'visible))
10285 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10286 (unless (pos-visible-in-window-p (point-max))
10287 (org-fit-window-to-buffer))
10288 (and (window-live-p cw) (select-window cw)))
10289 (setq all-prefixes (append (mapcar 'car abbrevs)
10290 (mapcar 'car org-link-abbrev-alist)
10291 (org-link-types)))
10292 (unwind-protect
10293 ;; Fake a link history, containing the stored links.
10294 (let ((org--links-history
10295 (append (mapcar #'car org-stored-links)
10296 org-insert-link-history)))
10297 (setq link
10298 (org-completing-read
10299 "Link: "
10300 (append
10301 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10302 (mapcar #'car org-stored-links))
10303 nil nil nil
10304 'org--links-history
10305 (caar org-stored-links)))
10306 (unless (org-string-nw-p link) (user-error "No link selected"))
10307 (dolist (l org-stored-links)
10308 (when (equal link (cadr l))
10309 (setq link (car l))
10310 (setq auto-desc t)))
10311 (when (or (member link all-prefixes)
10312 (and (equal ":" (substring link -1))
10313 (member (substring link 0 -1) all-prefixes)
10314 (setq link (substring link 0 -1))))
10315 (setq link (with-current-buffer origbuf
10316 (org-link-try-special-completion link)))))
10317 (set-window-configuration wcf)
10318 (kill-buffer "*Org Links*"))
10319 (setq entry (assoc link org-stored-links))
10320 (or entry (push link org-insert-link-history))
10321 (setq desc (or desc (nth 1 entry)))))
10323 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10324 (not org-keep-stored-link-after-insertion))
10325 (setq org-stored-links (delq (assoc link org-stored-links)
10326 org-stored-links)))
10328 (when (and (string-match org-plain-link-re link)
10329 (not (string-match org-ts-regexp link)))
10330 ;; URL-like link, normalize the use of angular brackets.
10331 (setq link (org-unbracket-string "<" ">" link)))
10333 ;; Check if we are linking to the current file with a search
10334 ;; option If yes, simplify the link by using only the search
10335 ;; option.
10336 (when (and buffer-file-name
10337 (let ((case-fold-search nil))
10338 (string-match "\\`file:\\(.+?\\)::" link)))
10339 (let ((path (match-string-no-properties 1 link))
10340 (search (substring-no-properties link (match-end 0))))
10341 (save-match-data
10342 (when (equal (file-truename buffer-file-name) (file-truename path))
10343 ;; We are linking to this same file, with a search option
10344 (setq link search)))))
10346 ;; Check if we can/should use a relative path. If yes, simplify the link
10347 (let ((case-fold-search nil))
10348 (when (string-match "\\`\\(file\\|docview\\):" link)
10349 (let* ((type (match-string-no-properties 0 link))
10350 (path (substring-no-properties link (match-end 0)))
10351 (origpath path))
10352 (cond
10353 ((or (eq org-link-file-path-type 'absolute)
10354 (equal complete-file '(16)))
10355 (setq path (abbreviate-file-name (expand-file-name path))))
10356 ((eq org-link-file-path-type 'noabbrev)
10357 (setq path (expand-file-name path)))
10358 ((eq org-link-file-path-type 'relative)
10359 (setq path (file-relative-name path)))
10361 (save-match-data
10362 (if (string-match (concat "^" (regexp-quote
10363 (expand-file-name
10364 (file-name-as-directory
10365 default-directory))))
10366 (expand-file-name path))
10367 ;; We are linking a file with relative path name.
10368 (setq path (substring (expand-file-name path)
10369 (match-end 0)))
10370 (setq path (abbreviate-file-name (expand-file-name path)))))))
10371 (setq link (concat type path))
10372 (when (equal desc origpath)
10373 (setq desc path)))))
10375 (if org-make-link-description-function
10376 (setq desc
10377 (or (condition-case nil
10378 (funcall org-make-link-description-function link desc)
10379 (error (progn (message "Can't get link description from `%s'"
10380 (symbol-name org-make-link-description-function))
10381 (sit-for 2) nil)))
10382 (read-string "Description: " default-description)))
10383 (if default-description (setq desc default-description)
10384 (setq desc (or (and auto-desc desc)
10385 (read-string "Description: " desc)))))
10387 (unless (string-match "\\S-" desc) (setq desc nil))
10388 (when remove (apply 'delete-region remove))
10389 (insert (org-make-link-string link desc))
10390 ;; Redisplay so as the new link has proper invisible characters.
10391 (sit-for 0)))
10393 (defun org-link-try-special-completion (type)
10394 "If there is completion support for link type TYPE, offer it."
10395 (let ((fun (org-link-get-parameter type :complete)))
10396 (if (functionp fun)
10397 (funcall fun)
10398 (read-string "Link (no completion support): " (concat type ":")))))
10400 (defun org-file-complete-link (&optional arg)
10401 "Create a file link using completion."
10402 (let ((file (read-file-name "File: "))
10403 (pwd (file-name-as-directory (expand-file-name ".")))
10404 (pwd1 (file-name-as-directory (abbreviate-file-name
10405 (expand-file-name ".")))))
10406 (cond ((equal arg '(16))
10407 (concat "file:"
10408 (abbreviate-file-name (expand-file-name file))))
10409 ((string-match
10410 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10411 (concat "file:" (match-string 1 file)))
10412 ((string-match
10413 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10414 (expand-file-name file))
10415 (concat "file:"
10416 (match-string 1 (expand-file-name file))))
10417 (t (concat "file:" file)))))
10419 (defun org-completing-read (&rest args)
10420 "Completing-read with SPACE being a normal character."
10421 (let ((enable-recursive-minibuffers t)
10422 (minibuffer-local-completion-map
10423 (copy-keymap minibuffer-local-completion-map)))
10424 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10425 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10426 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10427 'org-time-stamp-inactive)
10428 (apply #'completing-read args)))
10430 ;;; Opening/following a link
10432 (defvar org-link-search-failed nil)
10434 (defvar org-open-link-functions nil
10435 "Hook for functions finding a plain text link.
10436 These functions must take a single argument, the link content.
10437 They will be called for links that look like [[link text][description]]
10438 when LINK TEXT does not have a protocol like \"http:\" and does not look
10439 like a filename (e.g. \"./blue.png\").
10441 These functions will be called *before* Org attempts to resolve the
10442 link by doing text searches in the current buffer - so if you want a
10443 link \"[[target]]\" to still find \"<<target>>\", your function should
10444 handle this as a special case.
10446 When the function does handle the link, it must return a non-nil value.
10447 If it decides that it is not responsible for this link, it must return
10448 nil to indicate that that Org can continue with other options like
10449 exact and fuzzy text search.")
10451 (defun org-next-link (&optional search-backward)
10452 "Move forward to the next link.
10453 If the link is in hidden text, expose it."
10454 (interactive "P")
10455 (when (and org-link-search-failed (eq this-command last-command))
10456 (goto-char (point-min))
10457 (message "Link search wrapped back to beginning of buffer"))
10458 (setq org-link-search-failed nil)
10459 (let* ((pos (point))
10460 (ct (org-context))
10461 (a (assq :link ct))
10462 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10463 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10464 ((looking-at org-any-link-re)
10465 ;; Don't stay stuck at link without an org-link face
10466 (forward-char (if search-backward -1 1))))
10467 (if (funcall srch-fun org-any-link-re nil t)
10468 (progn
10469 (goto-char (match-beginning 0))
10470 (when (outline-invisible-p) (org-show-context)))
10471 (goto-char pos)
10472 (setq org-link-search-failed t)
10473 (message "No further link found"))))
10475 (defun org-previous-link ()
10476 "Move backward to the previous link.
10477 If the link is in hidden text, expose it."
10478 (interactive)
10479 (funcall 'org-next-link t))
10481 (defun org-translate-link (s)
10482 "Translate a link string if a translation function has been defined."
10483 (with-temp-buffer
10484 (insert (org-trim s))
10485 (org-trim (org-element-interpret-data (org-element-context)))))
10487 (defun org-translate-link-from-planner (type path)
10488 "Translate a link from Emacs Planner syntax so that Org can follow it.
10489 This is still an experimental function, your mileage may vary."
10490 (cond
10491 ((member type '("http" "https" "news" "ftp"))
10492 ;; standard Internet links are the same.
10493 nil)
10494 ((and (equal type "irc") (string-match "^//" path))
10495 ;; Planner has two / at the beginning of an irc link, we have 1.
10496 ;; We should have zero, actually....
10497 (setq path (substring path 1)))
10498 ((and (equal type "lisp") (string-match "^/" path))
10499 ;; Planner has a slash, we do not.
10500 (setq type "elisp" path (substring path 1)))
10501 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10502 ;; A typical message link. Planner has the id after the final slash,
10503 ;; we separate it with a hash mark
10504 (setq path (concat (match-string 1 path) "#"
10505 (org-unbracket-string "<" ">" (match-string 2 path))))))
10506 (cons type path))
10508 (defun org-find-file-at-mouse (ev)
10509 "Open file link or URL at mouse."
10510 (interactive "e")
10511 (mouse-set-point ev)
10512 (org-open-at-point 'in-emacs))
10514 (defun org-open-at-mouse (ev)
10515 "Open file link or URL at mouse.
10516 See the docstring of `org-open-file' for details."
10517 (interactive "e")
10518 (mouse-set-point ev)
10519 (when (eq major-mode 'org-agenda-mode)
10520 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10521 (org-open-at-point))
10523 (defvar org-window-config-before-follow-link nil
10524 "The window configuration before following a link.
10525 This is saved in case the need arises to restore it.")
10527 ;;;###autoload
10528 (defun org-open-at-point-global ()
10529 "Follow a link or time-stamp like Org mode does.
10530 This command can be called in any mode to follow an external link
10531 or a time-stamp that has Org mode syntax. Its behavior is
10532 undefined when called on internal links (e.g., fuzzy links).
10533 Raise an error when there is nothing to follow. "
10534 (interactive)
10535 (cond ((org-in-regexp org-any-link-re)
10536 (org-open-link-from-string (match-string-no-properties 0)))
10537 ((or (org-in-regexp org-ts-regexp-both nil t)
10538 (org-in-regexp org-tsr-regexp-both nil t))
10539 (org-follow-timestamp-link))
10540 (t (user-error "No link found"))))
10542 ;;;###autoload
10543 (defun org-open-link-from-string (s &optional arg reference-buffer)
10544 "Open a link in the string S, as if it was in Org mode."
10545 (interactive "sLink: \nP")
10546 (let ((reference-buffer (or reference-buffer (current-buffer))))
10547 (with-temp-buffer
10548 (let ((org-inhibit-startup (not reference-buffer)))
10549 (org-mode)
10550 (insert s)
10551 (goto-char (point-min))
10552 (when reference-buffer
10553 (setq org-link-abbrev-alist-local
10554 (with-current-buffer reference-buffer
10555 org-link-abbrev-alist-local)))
10556 (org-open-at-point arg reference-buffer)))))
10558 (defvar org-open-at-point-functions nil
10559 "Hook that is run when following a link at point.
10561 Functions in this hook must return t if they identify and follow
10562 a link at point. If they don't find anything interesting at point,
10563 they must return nil.")
10565 (defvar org-link-search-inhibit-query nil)
10566 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10567 (defun org--open-doi-link (path)
10568 "Open a \"doi\" type link.
10569 PATH is a the path to search for, as a string."
10570 (browse-url (url-encode-url (concat org-doi-server-url path))))
10572 (defun org--open-elisp-link (path)
10573 "Open a \"elisp\" type link.
10574 PATH is the sexp to evaluate, as a string."
10575 (let ((cmd path))
10576 (if (or (and (org-string-nw-p
10577 org-confirm-elisp-link-not-regexp)
10578 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10579 (not org-confirm-elisp-link-function)
10580 (funcall org-confirm-elisp-link-function
10581 (format "Execute \"%s\" as elisp? "
10582 (org-add-props cmd nil 'face 'org-warning))))
10583 (message "%s => %s" cmd
10584 (if (eq (string-to-char cmd) ?\()
10585 (eval (read cmd))
10586 (call-interactively (read cmd))))
10587 (user-error "Abort"))))
10589 (defun org--open-help-link (path)
10590 "Open a \"help\" type link.
10591 PATH is a symbol name, as a string."
10592 (pcase (intern path)
10593 ((and (pred fboundp) variable) (describe-function variable))
10594 ((and (pred boundp) function) (describe-variable function))
10595 (name (user-error "Unknown function or variable: %s" name))))
10597 (defun org--open-shell-link (path)
10598 "Open a \"shell\" type link.
10599 PATH is the command to execute, as a string."
10600 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10601 (cmd path))
10602 (if (or (and (org-string-nw-p
10603 org-confirm-shell-link-not-regexp)
10604 (string-match
10605 org-confirm-shell-link-not-regexp cmd))
10606 (not org-confirm-shell-link-function)
10607 (funcall org-confirm-shell-link-function
10608 (format "Execute \"%s\" in shell? "
10609 (org-add-props cmd nil
10610 'face 'org-warning))))
10611 (progn
10612 (message "Executing %s" cmd)
10613 (shell-command cmd buf)
10614 (when (featurep 'midnight)
10615 (setq clean-buffer-list-kill-buffer-names
10616 (cons (buffer-name buf)
10617 clean-buffer-list-kill-buffer-names))))
10618 (user-error "Abort"))))
10620 (defun org-open-at-point (&optional arg reference-buffer)
10621 "Open link, timestamp, footnote or tags at point.
10623 When point is on a link, follow it. Normally, files will be
10624 opened by an appropriate application. If the optional prefix
10625 argument ARG is non-nil, Emacs will visit the file. With
10626 a double prefix argument, try to open outside of Emacs, in the
10627 application the system uses for this file type.
10629 When point is on a timestamp, open the agenda at the day
10630 specified.
10632 When point is a footnote definition, move to the first reference
10633 found. If it is on a reference, move to the associated
10634 definition.
10636 When point is on a headline, display a list of every link in the
10637 entry, so it is possible to pick one, or all, of them. If point
10638 is on a tag, call `org-tags-view' instead.
10640 When optional argument REFERENCE-BUFFER is non-nil, it should
10641 specify a buffer from where the link search should happen. This
10642 is used internally by `org-open-link-from-string'.
10644 On top of syntactically correct links, this function will open
10645 the link at point in comments or comment blocks and the first
10646 link in a property drawer line."
10647 (interactive "P")
10648 ;; On a code block, open block's results.
10649 (unless (call-interactively 'org-babel-open-src-block-result)
10650 (org-load-modules-maybe)
10651 (setq org-window-config-before-follow-link (current-window-configuration))
10652 (org-remove-occur-highlights nil nil t)
10653 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10654 (let* ((context
10655 ;; Only consider supported types, even if they are not
10656 ;; the closest one.
10657 (org-element-lineage
10658 (org-element-context)
10659 '(clock comment comment-block footnote-definition
10660 footnote-reference headline inlinetask keyword link
10661 node-property timestamp)
10663 (type (org-element-type context))
10664 (value (org-element-property :value context)))
10665 (cond
10666 ((not context) (user-error "No link found"))
10667 ;; Exception: open timestamps and links in properties
10668 ;; drawers, keywords and comments.
10669 ((memq type '(comment comment-block keyword node-property))
10670 (call-interactively #'org-open-at-point-global))
10671 ;; On a headline or an inlinetask, but not on a timestamp,
10672 ;; a link, a footnote reference or on tags.
10673 ((and (memq type '(headline inlinetask))
10674 ;; Not on tags.
10675 (let ((case-fold-search nil))
10676 (save-excursion
10677 (beginning-of-line)
10678 (looking-at org-complex-heading-regexp))
10679 (or (not (match-beginning 5))
10680 (< (point) (match-beginning 5)))))
10681 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10682 (links (car data))
10683 (links-end (cdr data)))
10684 (if links
10685 (dolist (link (if (stringp links) (list links) links))
10686 (search-forward link nil links-end)
10687 (goto-char (match-beginning 0))
10688 (org-open-at-point))
10689 (require 'org-attach)
10690 (org-attach-reveal 'if-exists))))
10691 ;; On a clock line, make sure point is on the timestamp
10692 ;; before opening it.
10693 ((and (eq type 'clock)
10694 value
10695 (>= (point) (org-element-property :begin value))
10696 (<= (point) (org-element-property :end value)))
10697 (org-follow-timestamp-link))
10698 ;; Do nothing on white spaces after an object.
10699 ((>= (point)
10700 (save-excursion
10701 (goto-char (org-element-property :end context))
10702 (skip-chars-backward " \t")
10703 (point)))
10704 (user-error "No link found"))
10705 ((eq type 'timestamp) (org-follow-timestamp-link))
10706 ;; On tags within a headline or an inlinetask.
10707 ((and (memq type '(headline inlinetask))
10708 (let ((case-fold-search nil))
10709 (save-excursion (beginning-of-line)
10710 (looking-at org-complex-heading-regexp))
10711 (and (match-beginning 5)
10712 (>= (point) (match-beginning 5)))))
10713 (org-tags-view arg (substring (match-string 5) 0 -1)))
10714 ((eq type 'link)
10715 (let ((type (org-element-property :type context))
10716 (path (org-link-unescape (org-element-property :path context))))
10717 ;; Switch back to REFERENCE-BUFFER needed when called in
10718 ;; a temporary buffer through `org-open-link-from-string'.
10719 (with-current-buffer (or reference-buffer (current-buffer))
10720 (cond
10721 ((equal type "file")
10722 (if (string-match "[*?{]" (file-name-nondirectory path))
10723 (dired path)
10724 ;; Look into `org-link-parameters' in order to find
10725 ;; a DEDICATED-FUNCTION to open file. The function
10726 ;; will be applied on raw link instead of parsed
10727 ;; link due to the limitation in `org-add-link-type'
10728 ;; ("open" function called with a single argument).
10729 ;; If no such function is found, fallback to
10730 ;; `org-open-file'.
10731 (let* ((option (org-element-property :search-option context))
10732 (app (org-element-property :application context))
10733 (dedicated-function
10734 (org-link-get-parameter
10735 (if app (concat type "+" app) type)
10736 :follow)))
10737 (if dedicated-function
10738 (funcall dedicated-function
10739 (concat path
10740 (and option (concat "::" option))))
10741 (apply #'org-open-file
10742 path
10743 (cond (arg)
10744 ((equal app "emacs") 'emacs)
10745 ((equal app "sys") 'system))
10746 (cond ((not option) nil)
10747 ((string-match-p "\\`[0-9]+\\'" option)
10748 (list (string-to-number option)))
10749 (t (list nil
10750 (org-link-unescape option)))))))))
10751 ((functionp (org-link-get-parameter type :follow))
10752 (funcall (org-link-get-parameter type :follow) path))
10753 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10754 (unless (run-hook-with-args-until-success
10755 'org-open-link-functions path)
10756 (if (not arg) (org-mark-ring-push)
10757 (switch-to-buffer-other-window
10758 (org-get-buffer-for-internal-link (current-buffer))))
10759 (let ((destination
10760 (org-with-wide-buffer
10761 (if (equal type "radio")
10762 (org-search-radio-target
10763 (org-element-property :path context))
10764 (org-link-search
10765 (if (member type '("custom-id" "coderef"))
10766 (org-element-property :raw-link context)
10767 path)
10768 ;; Prevent fuzzy links from matching
10769 ;; themselves.
10770 (and (equal type "fuzzy")
10771 (+ 2 (org-element-property :begin context)))))
10772 (point))))
10773 (unless (and (<= (point-min) destination)
10774 (>= (point-max) destination))
10775 (widen))
10776 (goto-char destination))))
10777 (t (browse-url-at-point))))))
10778 ;; On a footnote reference or at a footnote definition's label.
10779 ((or (eq type 'footnote-reference)
10780 (and (eq type 'footnote-definition)
10781 (save-excursion
10782 ;; Do not validate action when point is on the
10783 ;; spaces right after the footnote label, in
10784 ;; order to be on par with behaviour on links.
10785 (skip-chars-forward " \t")
10786 (let ((begin
10787 (org-element-property :contents-begin context)))
10788 (if begin (< (point) begin)
10789 (= (org-element-property :post-affiliated context)
10790 (line-beginning-position)))))))
10791 (org-footnote-action))
10792 (t (user-error "No link found")))))
10793 (run-hook-with-args 'org-follow-link-hook)))
10795 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10796 "Offer links in the current entry and return the selected link.
10797 If there is only one link, return it.
10798 If NTH is an integer, return the NTH link found.
10799 If ZERO is a string, check also this string for a link, and if
10800 there is one, return it."
10801 (with-current-buffer buffer
10802 (org-with-wide-buffer
10803 (goto-char marker)
10804 (let ((cnt ?0)
10805 have-zero end links link c)
10806 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10807 (push (match-string 0 zero) links)
10808 (setq cnt (1- cnt) have-zero t))
10809 (save-excursion
10810 (org-back-to-heading t)
10811 (setq end (save-excursion (outline-next-heading) (point)))
10812 (while (re-search-forward org-any-link-re end t)
10813 (push (match-string 0) links))
10814 (setq links (org-uniquify (reverse links))))
10815 (cond
10816 ((null links)
10817 (message "No links"))
10818 ((equal (length links) 1)
10819 (setq link (car links)))
10820 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10821 (setq link (nth (if have-zero nth (1- nth)) links)))
10822 (t ; we have to select a link
10823 (save-excursion
10824 (save-window-excursion
10825 (delete-other-windows)
10826 (with-output-to-temp-buffer "*Select Link*"
10827 (dolist (l links)
10828 (cond
10829 ((not (string-match org-bracket-link-regexp l))
10830 (princ (format "[%c] %s\n" (cl-incf cnt)
10831 (org-unbracket-string "<" ">" l))))
10832 ((match-end 3)
10833 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10834 (match-string 3 l) (match-string 1 l))))
10835 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10836 (match-string 1 l)))))))
10837 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10838 (message "Select link to open, RET to open all:")
10839 (setq c (read-char-exclusive))
10840 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10841 (when (equal c ?q) (user-error "Abort"))
10842 (if (equal c ?\C-m)
10843 (setq link links)
10844 (setq nth (- c ?0))
10845 (when have-zero (setq nth (1+ nth)))
10846 (unless (and (integerp nth) (>= (length links) nth))
10847 (user-error "Invalid link selection"))
10848 (setq link (nth (1- nth) links)))))
10849 (cons link end)))))
10851 ;; TODO: These functions are deprecated since `org-open-at-point'
10852 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10853 (defun org-open-file-with-system (path)
10854 "Open file at PATH using the system way of opening it."
10855 (org-open-file path 'system))
10856 (defun org-open-file-with-emacs (path)
10857 "Open file at PATH in Emacs."
10858 (org-open-file path 'emacs))
10861 ;;; File search
10863 (defvar org-create-file-search-functions nil
10864 "List of functions to construct the right search string for a file link.
10865 These functions are called in turn with point at the location to
10866 which the link should point.
10868 A function in the hook should first test if it would like to
10869 handle this file type, for example by checking the `major-mode'
10870 or the file extension. If it decides not to handle this file, it
10871 should just return nil to give other functions a chance. If it
10872 does handle the file, it must return the search string to be used
10873 when following the link. The search string will be part of the
10874 file link, given after a double colon, and `org-open-at-point'
10875 will automatically search for it. If special measures must be
10876 taken to make the search successful, another function should be
10877 added to the companion hook `org-execute-file-search-functions',
10878 which see.
10880 A function in this hook may also use `setq' to set the variable
10881 `description' to provide a suggestion for the descriptive text to
10882 be used for this link when it gets inserted into an Org buffer
10883 with \\[org-insert-link].")
10885 (defvar org-execute-file-search-functions nil
10886 "List of functions to execute a file search triggered by a link.
10888 Functions added to this hook must accept a single argument, the
10889 search string that was part of the file link, the part after the
10890 double colon. The function must first check if it would like to
10891 handle this search, for example by checking the `major-mode' or
10892 the file extension. If it decides not to handle this search, it
10893 should just return nil to give other functions a chance. If it
10894 does handle the search, it must return a non-nil value to keep
10895 other functions from trying.
10897 Each function can access the current prefix argument through the
10898 variable `current-prefix-arg'. Note that a single prefix is used
10899 to force opening a link in Emacs, so it may be good to only use a
10900 numeric or double prefix to guide the search function.
10902 In case this is needed, a function in this hook can also restore
10903 the window configuration before `org-open-at-point' was called using:
10905 (set-window-configuration org-window-config-before-follow-link)")
10907 (defun org-search-radio-target (target)
10908 "Search a radio target matching TARGET in current buffer.
10909 White spaces are not significant."
10910 (let ((re (format "<<<%s>>>"
10911 (mapconcat #'regexp-quote
10912 (org-split-string target "[ \t\n]+")
10913 "[ \t]+\\(?:\n[ \t]*\\)?")))
10914 (origin (point)))
10915 (goto-char (point-min))
10916 (catch :radio-match
10917 (while (re-search-forward re nil t)
10918 (backward-char)
10919 (let ((object (org-element-context)))
10920 (when (eq (org-element-type object) 'radio-target)
10921 (goto-char (org-element-property :begin object))
10922 (org-show-context 'link-search)
10923 (throw :radio-match nil))))
10924 (goto-char origin)
10925 (user-error "No match for radio target: %s" target))))
10927 (defun org-link-search (s &optional avoid-pos stealth)
10928 "Search for a search string S.
10930 If S starts with \"#\", it triggers a custom ID search.
10932 If S is enclosed within parenthesis, it initiates a coderef
10933 search.
10935 If S is surrounded by forward slashes, it is interpreted as
10936 a regular expression. In Org mode files, this will create an
10937 `org-occur' sparse tree. In ordinary files, `occur' will be used
10938 to list matches. If the current buffer is in `dired-mode', grep
10939 will be used to search in all files.
10941 When AVOID-POS is given, ignore matches near that position.
10943 When optional argument STEALTH is non-nil, do not modify
10944 visibility around point, thus ignoring `org-show-context-detail'
10945 variable.
10947 Search is case-insensitive and ignores white spaces. Return type
10948 of matched result, which is either `dedicated' or `fuzzy'."
10949 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10950 (let* ((case-fold-search t)
10951 (origin (point))
10952 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10953 (starred (eq (string-to-char normalized) ?*))
10954 (words (split-string (if starred (substring s 1) s)))
10955 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10956 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10957 type)
10958 (cond
10959 ;; Check if there are any special search functions.
10960 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10961 ((eq (string-to-char s) ?#)
10962 ;; Look for a custom ID S if S starts with "#".
10963 (let* ((id (substring normalized 1))
10964 (match (org-find-property "CUSTOM_ID" id)))
10965 (if match (progn (goto-char match) (setf type 'dedicated))
10966 (error "No match for custom ID: %s" id))))
10967 ((string-match "\\`(\\(.*\\))\\'" normalized)
10968 ;; Look for coderef targets if S is enclosed within parenthesis.
10969 (let ((coderef (match-string-no-properties 1 normalized))
10970 (re (substring s-single-re 1 -1)))
10971 (goto-char (point-min))
10972 (catch :coderef-match
10973 (while (re-search-forward re nil t)
10974 (let ((element (org-element-at-point)))
10975 (when (and (memq (org-element-type element)
10976 '(example-block src-block))
10977 ;; Build proper regexp according to current
10978 ;; block's label format.
10979 (let ((label-fmt
10980 (regexp-quote
10981 (or (org-element-property :label-fmt element)
10982 org-coderef-label-format))))
10983 (save-excursion
10984 (beginning-of-line)
10985 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10986 (format label-fmt coderef))))))
10987 (setq type 'dedicated)
10988 (goto-char (match-beginning 1))
10989 (throw :coderef-match nil))))
10990 (goto-char origin)
10991 (error "No match for coderef: %s" coderef))))
10992 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10993 ;; Look for a regular expression.
10994 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10995 (match-string 1 s)))
10996 ;; From here, we handle fuzzy links.
10998 ;; Look for targets, only if not in a headline search.
10999 ((and (not starred)
11000 (let ((target (format "<<%s>>" s-multi-re)))
11001 (catch :target-match
11002 (goto-char (point-min))
11003 (while (re-search-forward target nil t)
11004 (backward-char)
11005 (let ((context (org-element-context)))
11006 (when (eq (org-element-type context) 'target)
11007 (setq type 'dedicated)
11008 (goto-char (org-element-property :begin context))
11009 (throw :target-match t))))
11010 nil))))
11011 ;; Look for elements named after S, only if not in a headline
11012 ;; search.
11013 ((and (not starred)
11014 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11015 (catch :name-match
11016 (goto-char (point-min))
11017 (while (re-search-forward name nil t)
11018 (let ((element (org-element-at-point)))
11019 (when (equal words
11020 (split-string
11021 (org-element-property :name element)))
11022 (setq type 'dedicated)
11023 (beginning-of-line)
11024 (throw :name-match t))))
11025 nil))))
11026 ;; Regular text search. Prefer headlines in Org mode buffers.
11027 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11028 ;; statistics cookies and tags.
11029 ((and (derived-mode-p 'org-mode)
11030 (let ((title-re
11031 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11032 org-outline-regexp-bol
11033 org-comment-string
11034 (mapconcat #'regexp-quote words ".+")))
11035 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11036 (comment-re (eval-when-compile
11037 (format "\\`%s[ \t]+" org-comment-string))))
11038 (goto-char (point-min))
11039 (catch :found
11040 (while (re-search-forward title-re nil t)
11041 (when (equal words
11042 (split-string
11043 (replace-regexp-in-string
11044 cookie-re ""
11045 (replace-regexp-in-string
11046 comment-re "" (org-get-heading t t t)))))
11047 (throw :found t)))
11048 nil)))
11049 (beginning-of-line)
11050 (setq type 'dedicated))
11051 ;; Offer to create non-existent headline depending on
11052 ;; `org-link-search-must-match-exact-headline'.
11053 ((and (derived-mode-p 'org-mode)
11054 (not org-link-search-inhibit-query)
11055 (eq org-link-search-must-match-exact-headline 'query-to-create)
11056 (yes-or-no-p "No match - create this as a new heading? "))
11057 (goto-char (point-max))
11058 (unless (bolp) (newline))
11059 (org-insert-heading nil t t)
11060 (insert s "\n")
11061 (beginning-of-line 0))
11062 ;; Only headlines are looked after. No need to process
11063 ;; further: throw an error.
11064 ((and (derived-mode-p 'org-mode)
11065 (or starred org-link-search-must-match-exact-headline))
11066 (goto-char origin)
11067 (error "No match for fuzzy expression: %s" normalized))
11068 ;; Regular text search.
11069 ((catch :fuzzy-match
11070 (goto-char (point-min))
11071 (while (re-search-forward s-multi-re nil t)
11072 ;; Skip match if it contains AVOID-POS or it is included in
11073 ;; a link with a description but outside the description.
11074 (unless (or (and avoid-pos
11075 (<= (match-beginning 0) avoid-pos)
11076 (> (match-end 0) avoid-pos))
11077 (and (save-match-data
11078 (org-in-regexp org-bracket-link-regexp))
11079 (match-beginning 3)
11080 (or (> (match-beginning 3) (point))
11081 (<= (match-end 3) (point)))
11082 (org-element-lineage
11083 (save-match-data (org-element-context))
11084 '(link) t)))
11085 (goto-char (match-beginning 0))
11086 (setq type 'fuzzy)
11087 (throw :fuzzy-match t)))
11088 nil))
11089 ;; All failed. Throw an error.
11090 (t (goto-char origin)
11091 (error "No match for fuzzy expression: %s" normalized)))
11092 ;; Disclose surroundings of match, if appropriate.
11093 (when (and (derived-mode-p 'org-mode) (not stealth))
11094 (org-show-context 'link-search))
11095 type))
11097 (defun org-get-buffer-for-internal-link (buffer)
11098 "Return a buffer to be used for displaying the link target of internal links."
11099 (cond
11100 ((not org-display-internal-link-with-indirect-buffer)
11101 buffer)
11102 ((string-suffix-p "(Clone)" (buffer-name buffer))
11103 (message "Buffer is already a clone, not making another one")
11104 ;; we also do not modify visibility in this case
11105 buffer)
11106 (t ; make a new indirect buffer for displaying the link
11107 (let* ((bn (buffer-name buffer))
11108 (ibn (concat bn "(Clone)"))
11109 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11110 (with-current-buffer ib (org-overview))
11111 ib))))
11113 (defun org-do-occur (regexp &optional cleanup)
11114 "Call the Emacs command `occur'.
11115 If CLEANUP is non-nil, remove the printout of the regular expression
11116 in the *Occur* buffer. This is useful if the regex is long and not useful
11117 to read."
11118 (occur regexp)
11119 (when cleanup
11120 (let ((cwin (selected-window)) win beg end)
11121 (when (setq win (get-buffer-window "*Occur*"))
11122 (select-window win))
11123 (goto-char (point-min))
11124 (when (re-search-forward "match[a-z]+" nil t)
11125 (setq beg (match-end 0))
11126 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11127 (setq end (1- (match-beginning 0)))))
11128 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11129 (goto-char (point-min))
11130 (select-window cwin))))
11132 ;;; The mark ring for links jumps
11134 (defvar org-mark-ring nil
11135 "Mark ring for positions before jumps in Org mode.")
11136 (defvar org-mark-ring-last-goto nil
11137 "Last position in the mark ring used to go back.")
11138 ;; Fill and close the ring
11139 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11140 (dotimes (_ org-mark-ring-length)
11141 (push (make-marker) org-mark-ring))
11142 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11143 org-mark-ring)
11145 (defun org-mark-ring-push (&optional pos buffer)
11146 "Put the current position or POS into the mark ring and rotate it."
11147 (interactive)
11148 (setq pos (or pos (point)))
11149 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11150 (move-marker (car org-mark-ring)
11151 (or pos (point))
11152 (or buffer (current-buffer)))
11153 (message "%s"
11154 (substitute-command-keys
11155 "Position saved to mark ring, go back with \
11156 `\\[org-mark-ring-goto]'.")))
11158 (defun org-mark-ring-goto (&optional n)
11159 "Jump to the previous position in the mark ring.
11160 With prefix arg N, jump back that many stored positions. When
11161 called several times in succession, walk through the entire ring.
11162 Org mode commands jumping to a different position in the current file,
11163 or to another Org file, automatically push the old position onto the ring."
11164 (interactive "p")
11165 (let (p m)
11166 (if (eq last-command this-command)
11167 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11168 (setq p org-mark-ring))
11169 (setq org-mark-ring-last-goto p)
11170 (setq m (car p))
11171 (pop-to-buffer-same-window (marker-buffer m))
11172 (goto-char m)
11173 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11175 (defun org-add-angle-brackets (s)
11176 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11177 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11180 ;;; Following specific links
11182 (defvar org-agenda-buffer-tmp-name)
11183 (defvar org-agenda-start-on-weekday)
11184 (defun org-follow-timestamp-link ()
11185 "Open an agenda view for the time-stamp date/range at point."
11186 (cond
11187 ((org-at-date-range-p t)
11188 (let ((org-agenda-start-on-weekday)
11189 (t1 (match-string 1))
11190 (t2 (match-string 2)) tt1 tt2)
11191 (setq tt1 (time-to-days (org-time-string-to-time t1))
11192 tt2 (time-to-days (org-time-string-to-time t2)))
11193 (let ((org-agenda-buffer-tmp-name
11194 (format "*Org Agenda(a:%s)"
11195 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11196 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11197 ((org-at-timestamp-p t)
11198 (let ((org-agenda-buffer-tmp-name
11199 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11200 (org-agenda-list nil (time-to-days (org-time-string-to-time
11201 (substring (match-string 1) 0 10)))
11202 1)))
11203 (t (error "This should not happen"))))
11206 ;;; Following file links
11207 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11208 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11209 (declare-function mailcap-mime-info
11210 "mailcap" (string &optional request no-decode))
11211 (defvar org-wait nil)
11212 (defun org-open-file (path &optional in-emacs line search)
11213 "Open the file at PATH.
11214 First, this expands any special file name abbreviations. Then the
11215 configuration variable `org-file-apps' is checked if it contains an
11216 entry for this file type, and if yes, the corresponding command is launched.
11218 If no application is found, Emacs simply visits the file.
11220 With optional prefix argument IN-EMACS, Emacs will visit the file.
11221 With a double \\[universal-argument] \\[universal-argument] \
11222 prefix arg, Org tries to avoid opening in Emacs
11223 and to use an external application to visit the file.
11225 Optional LINE specifies a line to go to, optional SEARCH a string
11226 to search for. If LINE or SEARCH is given, the file will be
11227 opened in Emacs, unless an entry from org-file-apps that makes
11228 use of groups in a regexp matches.
11230 If you want to change the way frames are used when following a
11231 link, please customize `org-link-frame-setup'.
11233 If the file does not exist, an error is thrown."
11234 (let* ((file (if (equal path "")
11235 buffer-file-name
11236 (substitute-in-file-name (expand-file-name path))))
11237 (file-apps (append org-file-apps (org-default-apps)))
11238 (apps (cl-remove-if
11239 'org-file-apps-entry-match-against-dlink-p file-apps))
11240 (apps-dlink (cl-remove-if-not
11241 'org-file-apps-entry-match-against-dlink-p file-apps))
11242 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11243 (dirp (unless remp (file-directory-p file)))
11244 (file (if (and dirp org-open-directory-means-index-dot-org)
11245 (concat (file-name-as-directory file) "index.org")
11246 file))
11247 (a-m-a-p (assq 'auto-mode apps))
11248 (dfile (downcase file))
11249 ;; Reconstruct the original link from the PATH, LINE and
11250 ;; SEARCH args.
11251 (link (cond (line (concat file "::" (number-to-string line)))
11252 (search (concat file "::" search))
11253 (t file)))
11254 (dlink (downcase link))
11255 (ext
11256 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11257 (match-string 1 dfile)))
11258 (save-position-maybe
11259 (let ((old-buffer (current-buffer))
11260 (old-pos (point))
11261 (old-mode major-mode))
11262 (lambda ()
11263 (and (derived-mode-p 'org-mode)
11264 (eq old-mode 'org-mode)
11265 (or (not (eq old-buffer (current-buffer)))
11266 (not (eq old-pos (point))))
11267 (org-mark-ring-push old-pos old-buffer)))))
11268 cmd link-match-data)
11269 (cond
11270 ((member in-emacs '((16) system))
11271 (setq cmd (cdr (assq 'system apps))))
11272 (in-emacs (setq cmd 'emacs))
11274 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11275 (and dirp (cdr (assq 'directory apps)))
11276 ;; First, try matching against apps-dlink if we
11277 ;; get a match here, store the match data for
11278 ;; later.
11279 (let ((match (assoc-default dlink apps-dlink
11280 'string-match)))
11281 (if match
11282 (progn (setq link-match-data (match-data))
11283 match)
11284 (progn (setq in-emacs (or in-emacs line search))
11285 nil))) ; if we have no match in apps-dlink,
11286 ; always open the file in emacs if line or search
11287 ; is given (for backwards compatibility)
11288 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11289 'string-match)
11290 (cdr (assoc ext apps))
11291 (cdr (assq t apps))))))
11292 (when (eq cmd 'system)
11293 (setq cmd (cdr (assq 'system apps))))
11294 (when (eq cmd 'default)
11295 (setq cmd (cdr (assoc t apps))))
11296 (when (eq cmd 'mailcap)
11297 (require 'mailcap)
11298 (mailcap-parse-mailcaps)
11299 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11300 (command (mailcap-mime-info mime-type)))
11301 (if (stringp command)
11302 (setq cmd command)
11303 (setq cmd 'emacs))))
11304 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11305 (not (file-exists-p file))
11306 (not org-open-non-existing-files))
11307 (user-error "No such file: %s" file))
11308 (cond
11309 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11310 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11311 (while (string-match "['\"]%s['\"]" cmd)
11312 (setq cmd (replace-match "%s" t t cmd)))
11313 (setq cmd (replace-regexp-in-string
11314 "%s"
11315 (shell-quote-argument (convert-standard-filename file))
11317 nil t))
11319 ;; Replace "%1", "%2" etc. in command with group matches from regex
11320 (save-match-data
11321 (let ((match-index 1)
11322 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11323 (set-match-data link-match-data)
11324 (while (<= match-index number-of-groups)
11325 (let ((regex (concat "%" (number-to-string match-index)))
11326 (replace-with (match-string match-index dlink)))
11327 (while (string-match regex cmd)
11328 (setq cmd (replace-match replace-with t t cmd))))
11329 (setq match-index (+ match-index 1)))))
11331 (save-window-excursion
11332 (message "Running %s...done" cmd)
11333 (start-process-shell-command cmd nil cmd)
11334 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11335 ((or (stringp cmd)
11336 (eq cmd 'emacs))
11337 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11338 (widen)
11339 (cond (line (org-goto-line line)
11340 (when (derived-mode-p 'org-mode) (org-reveal)))
11341 (search (condition-case err
11342 (org-link-search search)
11343 ;; Save position before error-ing out so user
11344 ;; can easily move back to the original buffer.
11345 (error (funcall save-position-maybe)
11346 (error (nth 1 err)))))))
11347 ((functionp cmd)
11348 (save-match-data
11349 (set-match-data link-match-data)
11350 (condition-case nil
11351 (funcall cmd file link)
11352 ;; FIXME: Remove this check when most default installations
11353 ;; of Emacs have at least Org 9.0.
11354 ((debug wrong-number-of-arguments wrong-type-argument
11355 invalid-function)
11356 (user-error "Please see Org News for version 9.0 about \
11357 `org-file-apps'--Lisp error: %S" cmd)))))
11358 ((consp cmd)
11359 ;; FIXME: Remove this check when most default installations of
11360 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11361 ;; fall back to `org-link-frame-setup' for an old usage of
11362 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11363 (user-error "Please see Org News for version 9.0 about \
11364 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11365 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11366 (funcall save-position-maybe)))
11368 (defun org-file-apps-entry-match-against-dlink-p (entry)
11369 "This function returns non-nil if `entry' uses a regular
11370 expression which should be matched against the whole link by
11371 org-open-file.
11373 It assumes that is the case when the entry uses a regular
11374 expression which has at least one grouping construct and the
11375 action is either a lisp form or a command string containing
11376 `%1', i.e. using at least one subexpression match as a
11377 parameter."
11378 (let ((selector (car entry))
11379 (action (cdr entry)))
11380 (if (stringp selector)
11381 (and (> (regexp-opt-depth selector) 0)
11382 (or (and (stringp action)
11383 (string-match "%[0-9]" action))
11384 (consp action)))
11385 nil)))
11387 (defun org-default-apps ()
11388 "Return the default applications for this operating system."
11389 (cond
11390 ((eq system-type 'darwin)
11391 org-file-apps-defaults-macosx)
11392 ((eq system-type 'windows-nt)
11393 org-file-apps-defaults-windowsnt)
11394 (t org-file-apps-defaults-gnu)))
11396 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11397 "Convert extensions to regular expressions in the cars of LIST.
11398 Also, weed out any non-string entries, because the return value is used
11399 only for regexp matching.
11400 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11401 point to the symbol `emacs', indicating that the file should
11402 be opened in Emacs."
11403 (append
11404 (delq nil
11405 (mapcar (lambda (x)
11406 (unless (not (stringp (car x)))
11407 (if (string-match "\\W" (car x))
11409 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11410 list))
11411 (when add-auto-mode
11412 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11414 (defvar ange-ftp-name-format)
11415 (defun org-file-remote-p (file)
11416 "Test whether FILE specifies a location on a remote system.
11417 Return non-nil if the location is indeed remote.
11419 For example, the filename \"/user@host:/foo\" specifies a location
11420 on the system \"/user@host:\"."
11421 (cond ((fboundp 'file-remote-p)
11422 (file-remote-p file))
11423 ((fboundp 'tramp-handle-file-remote-p)
11424 (tramp-handle-file-remote-p file))
11425 ((and (boundp 'ange-ftp-name-format)
11426 (string-match (car ange-ftp-name-format) file))
11427 t)))
11430 ;;;; Refiling
11432 (defun org-get-org-file ()
11433 "Read a filename, with default directory `org-directory'."
11434 (let ((default (or org-default-notes-file remember-data-file)))
11435 (read-file-name (format "File name [%s]: " default)
11436 (file-name-as-directory org-directory)
11437 default)))
11439 (defun org-notes-order-reversed-p ()
11440 "Check if the current file should receive notes in reversed order."
11441 (cond
11442 ((not org-reverse-note-order) nil)
11443 ((eq t org-reverse-note-order) t)
11444 ((not (listp org-reverse-note-order)) nil)
11445 (t (catch 'exit
11446 (dolist (entry org-reverse-note-order)
11447 (when (string-match (car entry) buffer-file-name)
11448 (throw 'exit (cdr entry))))))))
11450 (defvar org-refile-target-table nil
11451 "The list of refile targets, created by `org-refile'.")
11453 (defvar org-agenda-new-buffers nil
11454 "Buffers created to visit agenda files.")
11456 (defvar org-refile-cache nil
11457 "Cache for refile targets.")
11459 (defvar org-refile-markers nil
11460 "All the markers used for caching refile locations.")
11462 (defun org-refile-marker (pos)
11463 "Get a new refile marker, but only if caching is in use."
11464 (if (not org-refile-use-cache)
11466 (let ((m (make-marker)))
11467 (move-marker m pos)
11468 (push m org-refile-markers)
11469 m)))
11471 (defun org-refile-cache-clear ()
11472 "Clear the refile cache and disable all the markers."
11473 (dolist (m org-refile-markers) (move-marker m nil))
11474 (setq org-refile-markers nil)
11475 (setq org-refile-cache nil)
11476 (message "Refile cache has been cleared"))
11478 (defun org-refile-cache-check-set (set)
11479 "Check if all the markers in the cache still have live buffers."
11480 (let (marker)
11481 (catch 'exit
11482 (while (and set (setq marker (nth 3 (pop set))))
11483 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11484 (when (and marker (null (marker-buffer marker)))
11485 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11486 (sit-for 3)
11487 (throw 'exit nil)))
11488 t)))
11490 (defun org-refile-cache-put (set &rest identifiers)
11491 "Push the refile targets SET into the cache, under IDENTIFIERS."
11492 (let* ((key (sha1 (prin1-to-string identifiers)))
11493 (entry (assoc key org-refile-cache)))
11494 (if entry
11495 (setcdr entry set)
11496 (push (cons key set) org-refile-cache))))
11498 (defun org-refile-cache-get (&rest identifiers)
11499 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11500 (cond
11501 ((not org-refile-cache) nil)
11502 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11504 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11505 org-refile-cache))))
11506 (and set (org-refile-cache-check-set set) set)))))
11508 (defvar org-outline-path-cache nil
11509 "Alist between buffer positions and outline paths.
11510 It value is an alist (POSITION . PATH) where POSITION is the
11511 buffer position at the beginning of an entry and PATH is a list
11512 of strings describing the outline path for that entry, in reverse
11513 order.")
11515 (defun org-refile-get-targets (&optional default-buffer)
11516 "Produce a table with refile targets."
11517 (let ((case-fold-search nil)
11518 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11519 (entries (or org-refile-targets '((nil . (:level . 1)))))
11520 targets tgs files desc descre)
11521 (message "Getting targets...")
11522 (with-current-buffer (or default-buffer (current-buffer))
11523 (dolist (entry entries)
11524 (setq files (car entry) desc (cdr entry))
11525 (cond
11526 ((null files) (setq files (list (current-buffer))))
11527 ((eq files 'org-agenda-files)
11528 (setq files (org-agenda-files 'unrestricted)))
11529 ((and (symbolp files) (fboundp files))
11530 (setq files (funcall files)))
11531 ((and (symbolp files) (boundp files))
11532 (setq files (symbol-value files))))
11533 (when (stringp files) (setq files (list files)))
11534 (cond
11535 ((eq (car desc) :tag)
11536 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11537 ((eq (car desc) :todo)
11538 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11539 ((eq (car desc) :regexp)
11540 (setq descre (cdr desc)))
11541 ((eq (car desc) :level)
11542 (setq descre (concat "^\\*\\{" (number-to-string
11543 (if org-odd-levels-only
11544 (1- (* 2 (cdr desc)))
11545 (cdr desc)))
11546 "\\}[ \t]")))
11547 ((eq (car desc) :maxlevel)
11548 (setq descre (concat "^\\*\\{1," (number-to-string
11549 (if org-odd-levels-only
11550 (1- (* 2 (cdr desc)))
11551 (cdr desc)))
11552 "\\}[ \t]")))
11553 (t (error "Bad refiling target description %s" desc)))
11554 (dolist (f files)
11555 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11557 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11558 (progn
11559 (when (bufferp f)
11560 (setq f (buffer-file-name (buffer-base-buffer f))))
11561 (setq f (and f (expand-file-name f)))
11562 (when (eq org-refile-use-outline-path 'file)
11563 (push (list (file-name-nondirectory f) f nil nil) tgs))
11564 (when (eq org-refile-use-outline-path 'buffer-name)
11565 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11566 (org-with-wide-buffer
11567 (goto-char (point-min))
11568 (setq org-outline-path-cache nil)
11569 (while (re-search-forward descre nil t)
11570 (beginning-of-line)
11571 (let ((case-fold-search nil))
11572 (looking-at org-complex-heading-regexp))
11573 (let ((begin (point))
11574 (heading (match-string-no-properties 4)))
11575 (unless (or (and
11576 org-refile-target-verify-function
11577 (not
11578 (funcall org-refile-target-verify-function)))
11579 (not heading))
11580 (let ((re (format org-complex-heading-regexp-format
11581 (regexp-quote heading)))
11582 (target
11583 (if (not org-refile-use-outline-path) heading
11584 (mapconcat
11585 #'identity
11586 (append
11587 (pcase org-refile-use-outline-path
11588 (`file (list (file-name-nondirectory
11589 (buffer-file-name
11590 (buffer-base-buffer)))))
11591 (`full-file-path
11592 (list (buffer-file-name
11593 (buffer-base-buffer))))
11594 (`buffer-name
11595 (list (buffer-name
11596 (buffer-base-buffer))))
11597 (_ nil))
11598 (mapcar #'org-protect-slash
11599 (org-get-outline-path t t)))
11600 "/"))))
11601 (push (list target f re (org-refile-marker (point)))
11602 tgs)))
11603 (when (= (point) begin)
11604 ;; Verification function has not moved point.
11605 (end-of-line)))))))
11606 (when org-refile-use-cache
11607 (org-refile-cache-put tgs (buffer-file-name) descre))
11608 (setq targets (append tgs targets))))))
11609 (message "Getting targets...done")
11610 (nreverse targets)))
11612 (defun org-protect-slash (s)
11613 (replace-regexp-in-string "/" "\\/" s nil t))
11615 (defun org--get-outline-path-1 (&optional use-cache)
11616 "Return outline path to current headline.
11618 Outline path is a list of strings, in reverse order. When
11619 optional argument USE-CACHE is non-nil, make use of a cache. See
11620 `org-get-outline-path' for details.
11622 Assume buffer is widened and point is on a headline."
11623 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11624 (let ((p (point))
11625 (heading (let ((case-fold-search nil))
11626 (looking-at org-complex-heading-regexp)
11627 (if (not (match-end 4)) ""
11628 ;; Remove statistics cookies.
11629 (org-trim
11630 (org-link-display-format
11631 (replace-regexp-in-string
11632 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11633 (match-string-no-properties 4))))))))
11634 (if (org-up-heading-safe)
11635 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11636 (when use-cache
11637 (push (cons p path) org-outline-path-cache))
11638 path)
11639 ;; This is a new root node. Since we assume we are moving
11640 ;; forward, we can drop previous cache so as to limit number
11641 ;; of associations there.
11642 (let ((path (list heading)))
11643 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11644 path)))))
11646 (defun org-get-outline-path (&optional with-self use-cache)
11647 "Return the outline path to the current entry.
11649 An outline path is a list of ancestors for current headline, as
11650 a list of strings. Statistics cookies are removed and links are
11651 replaced with their description, if any, or their path otherwise.
11653 When optional argument WITH-SELF is non-nil, the path also
11654 includes the current headline.
11656 When optional argument USE-CACHE is non-nil, cache outline paths
11657 between calls to this function so as to avoid backtracking. This
11658 argument is useful when planning to find more than one outline
11659 path in the same document. In that case, there are two
11660 conditions to satisfy:
11661 - `org-outline-path-cache' is set to nil before starting the
11662 process;
11663 - outline paths are computed by increasing buffer positions."
11664 (org-with-wide-buffer
11665 (and (or (and with-self (org-back-to-heading t))
11666 (org-up-heading-safe))
11667 (reverse (org--get-outline-path-1 use-cache)))))
11669 (defun org-format-outline-path (path &optional width prefix separator)
11670 "Format the outline path PATH for display.
11671 WIDTH is the maximum number of characters that is available.
11672 PREFIX is a prefix to be included in the returned string,
11673 such as the file name.
11674 SEPARATOR is inserted between the different parts of the path,
11675 the default is \"/\"."
11676 (setq width (or width 79))
11677 (setq path (delq nil path))
11678 (unless (> width 0)
11679 (user-error "Argument `width' must be positive"))
11680 (setq separator (or separator "/"))
11681 (let* ((org-odd-levels-only nil)
11682 (fpath (concat
11683 prefix (and prefix path separator)
11684 (mapconcat
11685 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11686 (cl-loop for head in path
11687 for n from 0
11688 collect (org-add-props
11689 head nil 'face
11690 (nth (% n org-n-level-faces) org-level-faces)))
11691 separator))))
11692 (when (> (length fpath) width)
11693 (if (< width 7)
11694 ;; It's unlikely that `width' will be this small, but don't
11695 ;; waste characters by adding ".." if it is.
11696 (setq fpath (substring fpath 0 width))
11697 (setf (substring fpath (- width 2)) "..")))
11698 fpath))
11700 (defun org-display-outline-path (&optional file current separator just-return-string)
11701 "Display the current outline path in the echo area.
11703 If FILE is non-nil, prepend the output with the file name.
11704 If CURRENT is non-nil, append the current heading to the output.
11705 SEPARATOR is passed through to `org-format-outline-path'. It separates
11706 the different parts of the path and defaults to \"/\".
11707 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11708 (interactive "P")
11709 (let* (case-fold-search
11710 (bfn (buffer-file-name (buffer-base-buffer)))
11711 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11712 res)
11713 (when current (setq path (append path
11714 (save-excursion
11715 (org-back-to-heading t)
11716 (when (looking-at org-complex-heading-regexp)
11717 (list (match-string 4)))))))
11718 (setq res
11719 (org-format-outline-path
11720 path
11721 (1- (frame-width))
11722 (and file bfn (concat (file-name-nondirectory bfn) separator))
11723 separator))
11724 (if just-return-string
11725 (org-no-properties res)
11726 (org-unlogged-message "%s" res))))
11728 (defvar org-refile-history nil
11729 "History for refiling operations.")
11731 (defvar org-after-refile-insert-hook nil
11732 "Hook run after `org-refile' has inserted its stuff at the new location.
11733 Note that this is still *before* the stuff will be removed from
11734 the *old* location.")
11736 (defvar org-capture-last-stored-marker)
11737 (defvar org-refile-keep nil
11738 "Non-nil means `org-refile' will copy instead of refile.")
11740 (defun org-copy ()
11741 "Like `org-refile', but copy."
11742 (interactive)
11743 (let ((org-refile-keep t))
11744 (funcall 'org-refile nil nil nil "Copy")))
11746 (defun org-refile (&optional arg default-buffer rfloc msg)
11747 "Move the entry or entries at point to another heading.
11749 The list of target headings is compiled using the information in
11750 `org-refile-targets', which see.
11752 At the target location, the entry is filed as a subitem of the
11753 target heading. Depending on `org-reverse-note-order', the new
11754 subitem will either be the first or the last subitem.
11756 If there is an active region, all entries in that region will be
11757 refiled. However, the region must fulfill the requirement that
11758 the first heading sets the top-level of the moved text.
11760 With a `\\[universal-argument]' ARG, the command will only visit the target \
11761 location
11762 and not actually move anything.
11764 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11765 location where the last
11766 refiling operation has put the subtree.
11768 With a numeric prefix argument of `2', refile to the running clock.
11770 With a numeric prefix argument of `3', emulate `org-refile-keep'
11771 being set to t and copy to the target location, don't move it.
11772 Beware that keeping refiled entries may result in duplicated ID
11773 properties.
11775 RFLOC can be a refile location obtained in a different way.
11777 MSG is a string to replace \"Refile\" in the default prompt with
11778 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11780 See also `org-refile-use-outline-path'.
11782 If you are using target caching (see `org-refile-use-cache'), you
11783 have to clear the target cache in order to find new targets.
11784 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11785 prefix argument (`C-u C-u C-u C-c C-w')."
11786 (interactive "P")
11787 (if (member arg '(0 (64)))
11788 (org-refile-cache-clear)
11789 (let* ((actionmsg (cond (msg msg)
11790 ((equal arg 3) "Refile (and keep)")
11791 (t "Refile")))
11792 (regionp (org-region-active-p))
11793 (region-start (and regionp (region-beginning)))
11794 (region-end (and regionp (region-end)))
11795 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11796 pos it nbuf file level reversed)
11797 (setq last-command nil)
11798 (when regionp
11799 (goto-char region-start)
11800 (or (bolp) (goto-char (point-at-bol)))
11801 (setq region-start (point))
11802 (unless (or (org-kill-is-subtree-p
11803 (buffer-substring region-start region-end))
11804 (prog1 org-refile-active-region-within-subtree
11805 (let ((s (point-at-eol)))
11806 (org-toggle-heading)
11807 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11808 (user-error "The region is not a (sequence of) subtree(s)")))
11809 (if (equal arg '(16))
11810 (org-refile-goto-last-stored)
11811 (when (or
11812 (and (equal arg 2)
11813 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11814 (prog1
11815 (setq it (list (or org-clock-heading "running clock")
11816 (buffer-file-name
11817 (marker-buffer org-clock-hd-marker))
11819 (marker-position org-clock-hd-marker)))
11820 (setq arg nil)))
11821 (setq it
11822 (or rfloc
11823 (let (heading-text)
11824 (save-excursion
11825 (unless (and arg (listp arg))
11826 (org-back-to-heading t)
11827 (setq heading-text
11828 (replace-regexp-in-string
11829 org-bracket-link-regexp
11830 "\\3"
11831 (or (nth 4 (org-heading-components))
11832 ""))))
11833 (org-refile-get-location
11834 (cond ((and arg (listp arg)) "Goto")
11835 (regionp (concat actionmsg " region to"))
11836 (t (concat actionmsg " subtree \""
11837 heading-text "\" to")))
11838 default-buffer
11839 (and (not (equal '(4) arg))
11840 org-refile-allow-creating-parent-nodes)))))))
11841 (setq file (nth 1 it)
11842 pos (nth 3 it))
11843 (when (and (not arg)
11845 (equal (buffer-file-name) file)
11846 (if regionp
11847 (and (>= pos region-start)
11848 (<= pos region-end))
11849 (and (>= pos (point))
11850 (< pos (save-excursion
11851 (org-end-of-subtree t t))))))
11852 (error "Cannot refile to position inside the tree or region"))
11853 (setq nbuf (or (find-buffer-visiting file)
11854 (find-file-noselect file)))
11855 (if (and arg (not (equal arg 3)))
11856 (progn
11857 (pop-to-buffer-same-window nbuf)
11858 (goto-char pos)
11859 (org-show-context 'org-goto))
11860 (if regionp
11861 (progn
11862 (org-kill-new (buffer-substring region-start region-end))
11863 (org-save-markers-in-region region-start region-end))
11864 (org-copy-subtree 1 nil t))
11865 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11866 (find-file-noselect file)))
11867 (setq reversed (org-notes-order-reversed-p))
11868 (org-with-wide-buffer
11869 (if pos
11870 (progn
11871 (goto-char pos)
11872 (setq level (org-get-valid-level (funcall outline-level) 1))
11873 (goto-char
11874 (if reversed
11875 (or (outline-next-heading) (point-max))
11876 (or (save-excursion (org-get-next-sibling))
11877 (org-end-of-subtree t t)
11878 (point-max)))))
11879 (setq level 1)
11880 (if (not reversed)
11881 (goto-char (point-max))
11882 (goto-char (point-min))
11883 (or (outline-next-heading) (goto-char (point-max)))))
11884 (unless (bolp) (newline))
11885 (org-paste-subtree level nil nil t)
11886 (when org-log-refile
11887 (org-add-log-setup 'refile nil nil org-log-refile)
11888 (unless (eq org-log-refile 'note)
11889 (save-excursion (org-add-log-note))))
11890 (and org-auto-align-tags
11891 (let ((org-loop-over-headlines-in-active-region nil))
11892 (org-set-tags nil t)))
11893 (let ((bookmark-name (plist-get org-bookmark-names-plist
11894 :last-refile)))
11895 (when bookmark-name
11896 (with-demoted-errors
11897 (bookmark-set bookmark-name))))
11898 ;; If we are refiling for capture, make sure that the
11899 ;; last-capture pointers point here
11900 (when (bound-and-true-p org-capture-is-refiling)
11901 (let ((bookmark-name (plist-get org-bookmark-names-plist
11902 :last-capture-marker)))
11903 (when bookmark-name
11904 (with-demoted-errors
11905 (bookmark-set bookmark-name))))
11906 (move-marker org-capture-last-stored-marker (point)))
11907 (when (fboundp 'deactivate-mark) (deactivate-mark))
11908 (run-hooks 'org-after-refile-insert-hook)))
11909 (unless org-refile-keep
11910 (if regionp
11911 (delete-region (point) (+ (point) (- region-end region-start)))
11912 (delete-region
11913 (and (org-back-to-heading t) (point))
11914 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11915 (when (featurep 'org-inlinetask)
11916 (org-inlinetask-remove-END-maybe))
11917 (setq org-markers-to-move nil)
11918 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11920 (defun org-refile-goto-last-stored ()
11921 "Go to the location where the last refile was stored."
11922 (interactive)
11923 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11924 (message "This is the location of the last refile"))
11926 (defun org-refile--get-location (refloc tbl)
11927 "When user refile to REFLOC, find the associated target in TBL.
11928 Also check `org-refile-target-table'."
11929 (car (delq
11931 (mapcar
11932 (lambda (r) (or (assoc r tbl)
11933 (assoc r org-refile-target-table)))
11934 (list (replace-regexp-in-string "/$" "" refloc)
11935 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11937 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11938 "Prompt the user for a refile location, using PROMPT.
11939 PROMPT should not be suffixed with a colon and a space, because
11940 this function appends the default value from
11941 `org-refile-history' automatically, if that is not empty."
11942 (let ((org-refile-targets org-refile-targets)
11943 (org-refile-use-outline-path org-refile-use-outline-path))
11944 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11945 (unless org-refile-target-table
11946 (user-error "No refile targets"))
11947 (let* ((cbuf (current-buffer))
11948 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11949 (cfunc (if (and org-refile-use-outline-path
11950 org-outline-path-complete-in-steps)
11951 #'org-olpath-completing-read
11952 #'completing-read))
11953 (extra (if org-refile-use-outline-path "/" ""))
11954 (cbnex (concat (buffer-name) extra))
11955 (filename (and cfn (expand-file-name cfn)))
11956 (tbl (mapcar
11957 (lambda (x)
11958 (if (and (not (member org-refile-use-outline-path
11959 '(file full-file-path)))
11960 (not (equal filename (nth 1 x))))
11961 (cons (concat (car x) extra " ("
11962 (file-name-nondirectory (nth 1 x)) ")")
11963 (cdr x))
11964 (cons (concat (car x) extra) (cdr x))))
11965 org-refile-target-table))
11966 (completion-ignore-case t)
11967 cdef
11968 (prompt (concat prompt
11969 (or (and (car org-refile-history)
11970 (concat " (default " (car org-refile-history) ")"))
11971 (and (assoc cbnex tbl) (setq cdef cbnex)
11972 (concat " (default " cbnex ")"))) ": "))
11973 pa answ parent-target child parent old-hist)
11974 (setq old-hist org-refile-history)
11975 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11976 nil 'org-refile-history (or cdef (car org-refile-history))))
11977 (if (setq pa (org-refile--get-location answ tbl))
11978 (progn
11979 (org-refile-check-position pa)
11980 (when (or (not org-refile-history)
11981 (not (eq old-hist org-refile-history))
11982 (not (equal (car pa) (car org-refile-history))))
11983 (setq org-refile-history
11984 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11985 org-refile-history
11986 (cdr org-refile-history))))
11987 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11988 (pop org-refile-history)))
11990 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11991 (progn
11992 (setq parent (match-string 1 answ)
11993 child (match-string 2 answ))
11994 (setq parent-target (org-refile--get-location parent tbl))
11995 (when (and parent-target
11996 (or (eq new-nodes t)
11997 (and (eq new-nodes 'confirm)
11998 (y-or-n-p (format "Create new node \"%s\"? "
11999 child)))))
12000 (org-refile-new-child parent-target child)))
12001 (user-error "Invalid target location")))))
12003 (declare-function org-string-nw-p "org-macs" (s))
12004 (defun org-refile-check-position (refile-pointer)
12005 "Check if the refile pointer matches the headline to which it points."
12006 (let* ((file (nth 1 refile-pointer))
12007 (re (nth 2 refile-pointer))
12008 (pos (nth 3 refile-pointer))
12009 buffer)
12010 (if (and (not (markerp pos)) (not file))
12011 (user-error "Please indicate a target file in the refile path")
12012 (when (org-string-nw-p re)
12013 (setq buffer (if (markerp pos)
12014 (marker-buffer pos)
12015 (or (find-buffer-visiting file)
12016 (find-file-noselect file))))
12017 (with-current-buffer buffer
12018 (org-with-wide-buffer
12019 (goto-char pos)
12020 (beginning-of-line 1)
12021 (unless (looking-at-p re)
12022 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12024 (defun org-refile-new-child (parent-target child)
12025 "Use refile target PARENT-TARGET to add new CHILD below it."
12026 (unless parent-target
12027 (error "Cannot find parent for new node"))
12028 (let ((file (nth 1 parent-target))
12029 (pos (nth 3 parent-target))
12030 level)
12031 (with-current-buffer (or (find-buffer-visiting file)
12032 (find-file-noselect file))
12033 (org-with-wide-buffer
12034 (if pos
12035 (goto-char pos)
12036 (goto-char (point-max))
12037 (unless (bolp) (newline)))
12038 (when (looking-at org-outline-regexp)
12039 (setq level (funcall outline-level))
12040 (org-end-of-subtree t t))
12041 (org-back-over-empty-lines)
12042 (insert "\n" (make-string
12043 (if pos (org-get-valid-level level 1) 1) ?*)
12044 " " child "\n")
12045 (beginning-of-line 0)
12046 (list (concat (car parent-target) "/" child) file "" (point))))))
12048 (defun org-olpath-completing-read (prompt collection &rest args)
12049 "Read an outline path like a file name."
12050 (let ((thetable collection))
12051 (apply #'completing-read
12052 prompt
12053 (lambda (string predicate &optional flag)
12054 (cond
12055 ((eq flag nil) (try-completion string thetable))
12056 ((eq flag t)
12057 (let ((l (length string)))
12058 (mapcar (lambda (x)
12059 (let ((r (substring x l))
12060 (f (if (string-match " ([^)]*)$" x)
12061 (match-string 0 x)
12062 "")))
12063 (if (string-match "/" r)
12064 (concat string (substring r 0 (match-end 0)) f)
12065 x)))
12066 (all-completions string thetable predicate))))
12067 ;; Exact match?
12068 ((eq flag 'lambda) (assoc string thetable))))
12069 args)))
12071 ;;;; Dynamic blocks
12073 (defun org-find-dblock (name)
12074 "Find the first dynamic block with name NAME in the buffer.
12075 If not found, stay at current position and return nil."
12076 (let ((case-fold-search t) pos)
12077 (save-excursion
12078 (goto-char (point-min))
12079 (setq pos (and (re-search-forward
12080 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12081 (match-beginning 0))))
12082 (when pos (goto-char pos))
12083 pos))
12085 (defun org-create-dblock (plist)
12086 "Create a dynamic block section, with parameters taken from PLIST.
12087 PLIST must contain a :name entry which is used as the name of the block."
12088 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12089 (end-of-line 1)
12090 (newline))
12091 (let ((col (current-column))
12092 (name (plist-get plist :name)))
12093 (insert "#+BEGIN: " name)
12094 (while plist
12095 (if (eq (car plist) :name)
12096 (setq plist (cddr plist))
12097 (insert " " (prin1-to-string (pop plist)))))
12098 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12099 (beginning-of-line -2)))
12101 (defun org-prepare-dblock ()
12102 "Prepare dynamic block for refresh.
12103 This empties the block, puts the cursor at the insert position and returns
12104 the property list including an extra property :name with the block name."
12105 (unless (looking-at org-dblock-start-re)
12106 (user-error "Not at a dynamic block"))
12107 (let* ((begdel (1+ (match-end 0)))
12108 (name (org-no-properties (match-string 1)))
12109 (params (append (list :name name)
12110 (read (concat "(" (match-string 3) ")")))))
12111 (save-excursion
12112 (beginning-of-line 1)
12113 (skip-chars-forward " \t")
12114 (setq params (plist-put params :indentation-column (current-column))))
12115 (unless (re-search-forward org-dblock-end-re nil t)
12116 (error "Dynamic block not terminated"))
12117 (setq params
12118 (append params
12119 (list :content (buffer-substring
12120 begdel (match-beginning 0)))))
12121 (delete-region begdel (match-beginning 0))
12122 (goto-char begdel)
12123 (open-line 1)
12124 params))
12126 (defun org-map-dblocks (&optional command)
12127 "Apply COMMAND to all dynamic blocks in the current buffer.
12128 If COMMAND is not given, use `org-update-dblock'."
12129 (let ((cmd (or command 'org-update-dblock)))
12130 (save-excursion
12131 (goto-char (point-min))
12132 (while (re-search-forward org-dblock-start-re nil t)
12133 (goto-char (match-beginning 0))
12134 (save-excursion
12135 (condition-case nil
12136 (funcall cmd)
12137 (error (message "Error during update of dynamic block"))))
12138 (unless (re-search-forward org-dblock-end-re nil t)
12139 (error "Dynamic block not terminated"))))))
12141 (defun org-dblock-update (&optional arg)
12142 "User command for updating dynamic blocks.
12143 Update the dynamic block at point. With prefix ARG, update all dynamic
12144 blocks in the buffer."
12145 (interactive "P")
12146 (if arg
12147 (org-update-all-dblocks)
12148 (or (looking-at org-dblock-start-re)
12149 (org-beginning-of-dblock))
12150 (org-update-dblock)))
12152 (defun org-update-dblock ()
12153 "Update the dynamic block at point.
12154 This means to empty the block, parse for parameters and then call
12155 the correct writing function."
12156 (interactive)
12157 (save-excursion
12158 (let* ((win (selected-window))
12159 (pos (point))
12160 (line (org-current-line))
12161 (params (org-prepare-dblock))
12162 (name (plist-get params :name))
12163 (indent (plist-get params :indentation-column))
12164 (cmd (intern (concat "org-dblock-write:" name))))
12165 (message "Updating dynamic block `%s' at line %d..." name line)
12166 (funcall cmd params)
12167 (message "Updating dynamic block `%s' at line %d...done" name line)
12168 (goto-char pos)
12169 (when (and indent (> indent 0))
12170 (setq indent (make-string indent ?\ ))
12171 (save-excursion
12172 (select-window win)
12173 (org-beginning-of-dblock)
12174 (forward-line 1)
12175 (while (not (looking-at org-dblock-end-re))
12176 (insert indent)
12177 (beginning-of-line 2))
12178 (when (looking-at org-dblock-end-re)
12179 (and (looking-at "[ \t]+")
12180 (replace-match ""))
12181 (insert indent)))))))
12183 (defun org-beginning-of-dblock ()
12184 "Find the beginning of the dynamic block at point.
12185 Error if there is no such block at point."
12186 (let ((pos (point))
12187 beg)
12188 (end-of-line 1)
12189 (if (and (re-search-backward org-dblock-start-re nil t)
12190 (setq beg (match-beginning 0))
12191 (re-search-forward org-dblock-end-re nil t)
12192 (> (match-end 0) pos))
12193 (goto-char beg)
12194 (goto-char pos)
12195 (error "Not in a dynamic block"))))
12197 (defun org-update-all-dblocks ()
12198 "Update all dynamic blocks in the buffer.
12199 This function can be used in a hook."
12200 (interactive)
12201 (when (derived-mode-p 'org-mode)
12202 (org-map-dblocks 'org-update-dblock)))
12205 ;;;; Completion
12207 (declare-function org-export-backend-options "ox" (cl-x) t)
12208 (defun org-get-export-keywords ()
12209 "Return a list of all currently understood export keywords.
12210 Export keywords include options, block names, attributes and
12211 keywords relative to each registered export back-end."
12212 (let (keywords)
12213 (dolist (backend
12214 (bound-and-true-p org-export-registered-backends)
12215 (delq nil keywords))
12216 ;; Back-end name (for keywords, like #+LATEX:)
12217 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12218 (dolist (option-entry (org-export-backend-options backend))
12219 ;; Back-end options.
12220 (push (nth 1 option-entry) keywords)))))
12222 (defconst org-options-keywords
12223 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12224 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12225 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12226 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12227 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12229 (defcustom org-structure-template-alist
12230 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12231 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12232 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12233 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12234 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12235 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12236 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12237 ("L" "#+LaTeX: ")
12238 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12239 ("H" "#+HTML: ")
12240 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12241 ("A" "#+ASCII: ")
12242 ("i" "#+INDEX: ?")
12243 ("I" "#+INCLUDE: %file ?"))
12244 "Structure completion elements.
12245 This is a list of abbreviation keys and values. The value gets inserted
12246 if you type `<' followed by the key and then press the completion key,
12247 usually `TAB'. %file will be replaced by a file name after prompting
12248 for the file using completion. The cursor will be placed at the position
12249 of the `?' in the template.
12250 There are two templates for each key, the first uses the original Org syntax,
12251 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12252 the default when the /org-mtags.el/ module has been loaded. See also the
12253 variable `org-mtags-prefer-muse-templates'."
12254 :group 'org-completion
12255 :type '(repeat
12256 (list
12257 (string :tag "Key")
12258 (string :tag "Template")))
12259 :version "26.1"
12260 :package-version '(Org . "8.3"))
12262 (defun org-try-structure-completion ()
12263 "Try to complete a structure template before point.
12264 This looks for strings like \"<e\" on an otherwise empty line and
12265 expands them."
12266 (let ((l (buffer-substring (point-at-bol) (point)))
12268 (when (and (looking-at "[ \t]*$")
12269 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12270 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12271 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12272 (match-beginning 1)) a)
12273 t)))
12275 (defun org-complete-expand-structure-template (start cell)
12276 "Expand a structure template."
12277 (let ((rpl (nth 1 cell))
12278 (ind ""))
12279 (delete-region start (point))
12280 (when (string-match "\\`[ \t]*#\\+" rpl)
12281 (cond
12282 ((bolp))
12283 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12284 (setq ind (buffer-substring (point-at-bol) (point))))
12285 (t (newline))))
12286 (setq start (point))
12287 (when (string-match "%file" rpl)
12288 (setq rpl (replace-match
12289 (concat
12290 "\""
12291 (save-match-data
12292 (abbreviate-file-name (read-file-name "Include file: ")))
12293 "\"")
12294 t t rpl)))
12295 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12296 (concat "\n" ind)))
12297 (insert rpl)
12298 (when (re-search-backward "\\?" start t) (delete-char 1))))
12300 ;;;; TODO, DEADLINE, Comments
12302 (defun org-toggle-comment ()
12303 "Change the COMMENT state of an entry."
12304 (interactive)
12305 (save-excursion
12306 (org-back-to-heading)
12307 (let ((case-fold-search nil))
12308 (looking-at org-complex-heading-regexp))
12309 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12310 (skip-chars-forward " \t")
12311 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12312 (if (org-in-commented-heading-p t)
12313 (delete-region (point)
12314 (progn (search-forward " " (line-end-position) 'move)
12315 (skip-chars-forward " \t")
12316 (point)))
12317 (insert org-comment-string)
12318 (unless (eolp) (insert " ")))))
12320 (defvar org-last-todo-state-is-todo nil
12321 "This is non-nil when the last TODO state change led to a TODO state.
12322 If the last change removed the TODO tag or switched to DONE, then
12323 this is nil.")
12325 (defvar org-setting-tags nil) ; dynamically skipped
12327 (defvar org-todo-setup-filter-hook nil
12328 "Hook for functions that pre-filter todo specs.
12329 Each function takes a todo spec and returns either nil or the spec
12330 transformed into canonical form." )
12332 (defvar org-todo-get-default-hook nil
12333 "Hook for functions that get a default item for todo.
12334 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12335 nil or a string to be used for the todo mark." )
12337 (defvar org-agenda-headline-snapshot-before-repeat)
12339 (defun org-current-effective-time ()
12340 "Return current time adjusted for `org-extend-today-until' variable."
12341 (let* ((ct (org-current-time))
12342 (dct (decode-time ct))
12343 (ct1
12344 (cond
12345 (org-use-last-clock-out-time-as-effective-time
12346 (or (org-clock-get-last-clock-out-time) ct))
12347 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12348 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12349 (t ct))))
12350 ct1))
12352 (defun org-todo-yesterday (&optional arg)
12353 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12354 (interactive "P")
12355 (if (eq major-mode 'org-agenda-mode)
12356 (apply 'org-agenda-todo-yesterday arg)
12357 (let* ((org-use-effective-time t)
12358 (hour (nth 2 (decode-time (org-current-time))))
12359 (org-extend-today-until (1+ hour)))
12360 (org-todo arg))))
12362 (defvar org-block-entry-blocking ""
12363 "First entry preventing the TODO state change.")
12365 (defun org-cancel-repeater ()
12366 "Cancel a repeater by setting its numeric value to zero."
12367 (interactive)
12368 (save-excursion
12369 (org-back-to-heading t)
12370 (let ((bound1 (point))
12371 (bound0 (save-excursion (outline-next-heading) (point))))
12372 (when (and (re-search-forward
12373 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12374 org-deadline-time-regexp "\\)\\|\\("
12375 org-ts-regexp "\\)")
12376 bound0 t)
12377 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12378 bound1 t))
12379 (replace-match "0" t nil nil 1)))))
12381 (defvar org-state)
12382 (defvar org-blocked-by-checkboxes)
12383 (defun org-todo (&optional arg)
12384 "Change the TODO state of an item.
12386 The state of an item is given by a keyword at the start of the heading,
12387 like
12388 *** TODO Write paper
12389 *** DONE Call mom
12391 The different keywords are specified in the variable `org-todo-keywords'.
12392 By default the available states are \"TODO\" and \"DONE\". So, for this
12393 example: when the item starts with TODO, it is changed to DONE.
12394 When it starts with DONE, the DONE is removed. And when neither TODO nor
12395 DONE are present, add TODO at the beginning of the heading.
12397 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12398 state.
12399 With numeric prefix ARG, switch to that state.
12400 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12401 next set of TODO \
12402 keywords (nextset).
12403 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12404 prefix, circumvent any state blocking.
12405 With a numeric prefix arg of 0, inhibit note taking for the change.
12406 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12408 When called through ELisp, arg is also interpreted in the following way:
12409 `none' -> empty state
12410 \"\" -> switch to empty state
12411 `done' -> switch to DONE
12412 `nextset' -> switch to the next set of keywords
12413 `previousset' -> switch to the previous set of keywords
12414 \"WAITING\" -> switch to the specified keyword, but only if it
12415 really is a member of `org-todo-keywords'."
12416 (interactive "P")
12417 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12418 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12419 'region-start-level 'region))
12420 org-loop-over-headlines-in-active-region)
12421 (org-map-entries
12422 `(org-todo ,arg)
12423 org-loop-over-headlines-in-active-region
12424 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12425 (when (equal arg '(16)) (setq arg 'nextset))
12426 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12427 (let ((org-blocker-hook org-blocker-hook)
12428 commentp
12429 case-fold-search)
12430 (when (equal arg '(64))
12431 (setq arg nil org-blocker-hook nil))
12432 (when (and org-blocker-hook
12433 (or org-inhibit-blocking
12434 (org-entry-get nil "NOBLOCKING")))
12435 (setq org-blocker-hook nil))
12436 (save-excursion
12437 (catch 'exit
12438 (org-back-to-heading t)
12439 (when (org-in-commented-heading-p t)
12440 (org-toggle-comment)
12441 (setq commentp t))
12442 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12443 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12444 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12445 (let* ((match-data (match-data))
12446 (startpos (point-at-bol))
12447 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12448 (org-log-done org-log-done)
12449 (org-log-repeat org-log-repeat)
12450 (org-todo-log-states org-todo-log-states)
12451 (org-inhibit-logging
12452 (if (equal arg 0)
12453 (progn (setq arg nil) 'note) org-inhibit-logging))
12454 (this (match-string 1))
12455 (hl-pos (match-beginning 0))
12456 (head (org-get-todo-sequence-head this))
12457 (ass (assoc head org-todo-kwd-alist))
12458 (interpret (nth 1 ass))
12459 (done-word (nth 3 ass))
12460 (final-done-word (nth 4 ass))
12461 (org-last-state (or this ""))
12462 (completion-ignore-case t)
12463 (member (member this org-todo-keywords-1))
12464 (tail (cdr member))
12465 (org-state (cond
12466 ((and org-todo-key-trigger
12467 (or (and (equal arg '(4))
12468 (eq org-use-fast-todo-selection 'prefix))
12469 (and (not arg) org-use-fast-todo-selection
12470 (not (eq org-use-fast-todo-selection
12471 'prefix)))))
12472 ;; Use fast selection.
12473 (org-fast-todo-selection))
12474 ((and (equal arg '(4))
12475 (or (not org-use-fast-todo-selection)
12476 (not org-todo-key-trigger)))
12477 ;; Read a state with completion.
12478 (completing-read
12479 "State: " (mapcar #'list org-todo-keywords-1)
12480 nil t))
12481 ((eq arg 'right)
12482 (if this
12483 (if tail (car tail) nil)
12484 (car org-todo-keywords-1)))
12485 ((eq arg 'left)
12486 (unless (equal member org-todo-keywords-1)
12487 (if this
12488 (nth (- (length org-todo-keywords-1)
12489 (length tail) 2)
12490 org-todo-keywords-1)
12491 (org-last org-todo-keywords-1))))
12492 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12493 (setq arg nil))) ;hack to fall back to cycling
12494 (arg
12495 ;; User or caller requests a specific state.
12496 (cond
12497 ((equal arg "") nil)
12498 ((eq arg 'none) nil)
12499 ((eq arg 'done) (or done-word (car org-done-keywords)))
12500 ((eq arg 'nextset)
12501 (or (car (cdr (member head org-todo-heads)))
12502 (car org-todo-heads)))
12503 ((eq arg 'previousset)
12504 (let ((org-todo-heads (reverse org-todo-heads)))
12505 (or (car (cdr (member head org-todo-heads)))
12506 (car org-todo-heads))))
12507 ((car (member arg org-todo-keywords-1)))
12508 ((stringp arg)
12509 (user-error "State `%s' not valid in this file" arg))
12510 ((nth (1- (prefix-numeric-value arg))
12511 org-todo-keywords-1))))
12512 ((null member) (or head (car org-todo-keywords-1)))
12513 ((equal this final-done-word) nil) ;-> make empty
12514 ((null tail) nil) ;-> first entry
12515 ((memq interpret '(type priority))
12516 (if (eq this-command last-command)
12517 (car tail)
12518 (if (> (length tail) 0)
12519 (or done-word (car org-done-keywords))
12520 nil)))
12522 (car tail))))
12523 (org-state (or
12524 (run-hook-with-args-until-success
12525 'org-todo-get-default-hook org-state org-last-state)
12526 org-state))
12527 (next (if org-state (concat " " org-state " ") " "))
12528 (change-plist (list :type 'todo-state-change :from this :to org-state
12529 :position startpos))
12530 dolog now-done-p)
12531 (when org-blocker-hook
12532 (let (org-blocked-by-checkboxes block-reason)
12533 (setq org-last-todo-state-is-todo
12534 (not (member this org-done-keywords)))
12535 (unless (save-excursion
12536 (save-match-data
12537 (org-with-wide-buffer
12538 (run-hook-with-args-until-failure
12539 'org-blocker-hook change-plist))))
12540 (setq block-reason (if org-blocked-by-checkboxes
12541 "contained checkboxes"
12542 (format "\"%s\"" org-block-entry-blocking)))
12543 (if (called-interactively-p 'interactive)
12544 (user-error "TODO state change from %s to %s blocked (by %s)"
12545 this org-state block-reason)
12546 ;; Fail silently.
12547 (message "TODO state change from %s to %s blocked (by %s)"
12548 this org-state block-reason)
12549 (throw 'exit nil)))))
12550 (store-match-data match-data)
12551 (replace-match next t t)
12552 (cond ((equal this org-state)
12553 (message "TODO state was already %s" (org-trim next)))
12554 ((pos-visible-in-window-p hl-pos)
12555 (message "TODO state changed to %s" (org-trim next))))
12556 (unless head
12557 (setq head (org-get-todo-sequence-head org-state)
12558 ass (assoc head org-todo-kwd-alist)
12559 interpret (nth 1 ass)
12560 done-word (nth 3 ass)
12561 final-done-word (nth 4 ass)))
12562 (when (memq arg '(nextset previousset))
12563 (message "Keyword-Set %d/%d: %s"
12564 (- (length org-todo-sets) -1
12565 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12566 (length org-todo-sets)
12567 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12568 (setq org-last-todo-state-is-todo
12569 (not (member org-state org-done-keywords)))
12570 (setq now-done-p (and (member org-state org-done-keywords)
12571 (not (member this org-done-keywords))))
12572 (and logging (org-local-logging logging))
12573 (when (and (or org-todo-log-states org-log-done)
12574 (not (eq org-inhibit-logging t))
12575 (not (memq arg '(nextset previousset))))
12576 ;; We need to look at recording a time and note.
12577 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12578 (nth 2 (assoc this org-todo-log-states))))
12579 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12580 (setq dolog 'time))
12581 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12582 (and org-state
12583 (member org-state org-not-done-keywords)
12584 (not (member this org-not-done-keywords))))
12585 ;; This is now a todo state and was not one before
12586 ;; If there was a CLOSED time stamp, get rid of it.
12587 (org-add-planning-info nil nil 'closed))
12588 (when (and now-done-p org-log-done)
12589 ;; It is now done, and it was not done before.
12590 (org-add-planning-info 'closed (org-current-effective-time))
12591 (when (and (not dolog) (eq 'note org-log-done))
12592 (org-add-log-setup 'done org-state this 'note)))
12593 (when (and org-state dolog)
12594 ;; This is a non-nil state, and we need to log it.
12595 (org-add-log-setup 'state org-state this dolog)))
12596 ;; Fixup tag positioning.
12597 (org-todo-trigger-tag-changes org-state)
12598 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12599 (when org-provide-todo-statistics
12600 (org-update-parent-todo-statistics))
12601 (run-hooks 'org-after-todo-state-change-hook)
12602 (when (and arg (not (member org-state org-done-keywords)))
12603 (setq head (org-get-todo-sequence-head org-state)))
12604 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12605 ;; Do we need to trigger a repeat?
12606 (when now-done-p
12607 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12608 ;; This is for the agenda, take a snapshot of the headline.
12609 (save-match-data
12610 (setq org-agenda-headline-snapshot-before-repeat
12611 (org-get-heading))))
12612 (org-auto-repeat-maybe org-state))
12613 ;; Fixup cursor location if close to the keyword.
12614 (when (and (outline-on-heading-p)
12615 (not (bolp))
12616 (save-excursion (beginning-of-line 1)
12617 (looking-at org-todo-line-regexp))
12618 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12619 (goto-char (or (match-end 2) (match-end 1)))
12620 (and (looking-at " ") (just-one-space)))
12621 (when org-trigger-hook
12622 (save-excursion
12623 (run-hook-with-args 'org-trigger-hook change-plist)))
12624 (when commentp (org-toggle-comment))))))))
12626 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12627 "Block turning an entry into a TODO, using the hierarchy.
12628 This checks whether the current task should be blocked from state
12629 changes. Such blocking occurs when:
12631 1. The task has children which are not all in a completed state.
12633 2. A task has a parent with the property :ORDERED:, and there
12634 are siblings prior to the current task with incomplete
12635 status.
12637 3. The parent of the task is blocked because it has siblings that should
12638 be done first, or is child of a block grandparent TODO entry."
12640 (if (not org-enforce-todo-dependencies)
12641 t ; if locally turned off don't block
12642 (catch 'dont-block
12643 ;; If this is not a todo state change, or if this entry is already DONE,
12644 ;; do not block
12645 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12646 (member (plist-get change-plist :from)
12647 (cons 'done org-done-keywords))
12648 (member (plist-get change-plist :to)
12649 (cons 'todo org-not-done-keywords))
12650 (not (plist-get change-plist :to)))
12651 (throw 'dont-block t))
12652 ;; If this task has children, and any are undone, it's blocked
12653 (save-excursion
12654 (org-back-to-heading t)
12655 (let ((this-level (funcall outline-level)))
12656 (outline-next-heading)
12657 (let ((child-level (funcall outline-level)))
12658 (while (and (not (eobp))
12659 (> child-level this-level))
12660 ;; this todo has children, check whether they are all
12661 ;; completed
12662 (when (and (not (org-entry-is-done-p))
12663 (org-entry-is-todo-p))
12664 (setq org-block-entry-blocking (org-get-heading))
12665 (throw 'dont-block nil))
12666 (outline-next-heading)
12667 (setq child-level (funcall outline-level))))))
12668 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12669 ;; any previous siblings are undone, it's blocked
12670 (save-excursion
12671 (org-back-to-heading t)
12672 (let* ((pos (point))
12673 (parent-pos (and (org-up-heading-safe) (point)))
12674 (case-fold-search nil))
12675 (unless parent-pos (throw 'dont-block t)) ; no parent
12676 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12677 (forward-line 1)
12678 (re-search-forward org-not-done-heading-regexp pos t))
12679 (setq org-block-entry-blocking (match-string 0))
12680 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12681 ;; Search further up the hierarchy, to see if an ancestor is blocked
12682 (while t
12683 (goto-char parent-pos)
12684 (unless (looking-at org-not-done-heading-regexp)
12685 (throw 'dont-block t)) ; do not block, parent is not a TODO
12686 (setq pos (point))
12687 (setq parent-pos (and (org-up-heading-safe) (point)))
12688 (unless parent-pos (throw 'dont-block t)) ; no parent
12689 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12690 (forward-line 1)
12691 (re-search-forward org-not-done-heading-regexp pos t)
12692 (setq org-block-entry-blocking (org-get-heading)))
12693 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12695 (defcustom org-track-ordered-property-with-tag nil
12696 "Should the ORDERED property also be shown as a tag?
12697 The ORDERED property decides if an entry should require subtasks to be
12698 completed in sequence. Since a property is not very visible, setting
12699 this option means that toggling the ORDERED property with the command
12700 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12701 not relevant for the behavior, but it makes things more visible.
12703 Note that toggling the tag with tags commands will not change the property
12704 and therefore not influence behavior!
12706 This can be t, meaning the tag ORDERED should be used, It can also be a
12707 string to select a different tag for this task."
12708 :group 'org-todo
12709 :type '(choice
12710 (const :tag "No tracking" nil)
12711 (const :tag "Track with ORDERED tag" t)
12712 (string :tag "Use other tag")))
12714 (defun org-toggle-ordered-property ()
12715 "Toggle the ORDERED property of the current entry.
12716 For better visibility, you can track the value of this property with a tag.
12717 See variable `org-track-ordered-property-with-tag'."
12718 (interactive)
12719 (let* ((t1 org-track-ordered-property-with-tag)
12720 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12721 (save-excursion
12722 (org-back-to-heading)
12723 (if (org-entry-get nil "ORDERED")
12724 (progn
12725 (org-delete-property "ORDERED")
12726 (and tag (org-toggle-tag tag 'off))
12727 (message "Subtasks can be completed in arbitrary order"))
12728 (org-entry-put nil "ORDERED" "t")
12729 (and tag (org-toggle-tag tag 'on))
12730 (message "Subtasks must be completed in sequence")))))
12732 (defun org-block-todo-from-checkboxes (change-plist)
12733 "Block turning an entry into a TODO, using checkboxes.
12734 This checks whether the current task should be blocked from state
12735 changes because there are unchecked boxes in this entry."
12736 (if (not org-enforce-todo-checkbox-dependencies)
12737 t ; if locally turned off don't block
12738 (catch 'dont-block
12739 ;; If this is not a todo state change, or if this entry is already DONE,
12740 ;; do not block
12741 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12742 (member (plist-get change-plist :from)
12743 (cons 'done org-done-keywords))
12744 (member (plist-get change-plist :to)
12745 (cons 'todo org-not-done-keywords))
12746 (not (plist-get change-plist :to)))
12747 (throw 'dont-block t))
12748 ;; If this task has checkboxes that are not checked, it's blocked
12749 (save-excursion
12750 (org-back-to-heading t)
12751 (let ((beg (point)) end)
12752 (outline-next-heading)
12753 (setq end (point))
12754 (goto-char beg)
12755 (when (org-list-search-forward
12756 (concat (org-item-beginning-re)
12757 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12758 "\\[[- ]\\]")
12759 end t)
12760 (when (boundp 'org-blocked-by-checkboxes)
12761 (setq org-blocked-by-checkboxes t))
12762 (throw 'dont-block nil))))
12763 t))) ; do not block
12765 (defun org-entry-blocked-p ()
12766 "Non-nil if entry at point is blocked."
12767 (and (not (org-entry-get nil "NOBLOCKING"))
12768 (member (org-entry-get nil "TODO") org-not-done-keywords)
12769 (not (run-hook-with-args-until-failure
12770 'org-blocker-hook
12771 (list :type 'todo-state-change
12772 :position (point)
12773 :from 'todo
12774 :to 'done)))))
12776 (defun org-update-statistics-cookies (all)
12777 "Update the statistics cookie, either from TODO or from checkboxes.
12778 This should be called with the cursor in a line with a statistics
12779 cookie. When called with a \\[universal-argument] prefix, update
12780 all statistics cookies in the buffer."
12781 (interactive "P")
12782 (if all
12783 (progn
12784 (org-update-checkbox-count 'all)
12785 (org-map-entries 'org-update-parent-todo-statistics))
12786 (if (not (org-at-heading-p))
12787 (org-update-checkbox-count)
12788 (let ((pos (point-marker))
12789 end l1 l2)
12790 (ignore-errors (org-back-to-heading t))
12791 (if (not (org-at-heading-p))
12792 (org-update-checkbox-count)
12793 (setq l1 (org-outline-level))
12794 (setq end (save-excursion
12795 (outline-next-heading)
12796 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12797 (point)))
12798 (if (and (save-excursion
12799 (re-search-forward
12800 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12801 (not (save-excursion (re-search-forward
12802 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12803 (org-update-checkbox-count)
12804 (if (and l2 (> l2 l1))
12805 (progn
12806 (goto-char end)
12807 (org-update-parent-todo-statistics))
12808 (goto-char pos)
12809 (beginning-of-line 1)
12810 (while (re-search-forward
12811 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12812 (point-at-eol) t)
12813 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12814 (goto-char pos)
12815 (move-marker pos nil)))))
12817 (defvar org-entry-property-inherited-from) ;; defined below
12818 (defun org-update-parent-todo-statistics ()
12819 "Update any statistics cookie in the parent of the current headline.
12820 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12821 the entire subtree and this will travel up the hierarchy and update
12822 statistics everywhere."
12823 (let* ((prop (save-excursion (org-up-heading-safe)
12824 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12825 (recursive (or (not org-hierarchical-todo-statistics)
12826 (and prop (string-match "\\<recursive\\>" prop))))
12827 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12829 (first t)
12830 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12831 level ltoggle l1 new ndel
12832 (cnt-all 0) (cnt-done 0) is-percent kwd
12833 checkbox-beg cookie-present)
12834 (catch 'exit
12835 (save-excursion
12836 (beginning-of-line 1)
12837 (setq ltoggle (funcall outline-level))
12838 ;; Three situations are to consider:
12840 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12841 ;; to the top-level ancestor on the headline;
12843 ;; 2. If parent has "recursive" property, repeat up to the
12844 ;; headline setting that property, taking inheritance into
12845 ;; account;
12847 ;; 3. Else, move up to direct parent and proceed only once.
12848 (while (and (setq level (org-up-heading-safe))
12849 (or recursive first)
12850 (>= (point) lim))
12851 (setq first nil cookie-present nil)
12852 (unless (and level
12853 (not (string-match
12854 "\\<checkbox\\>"
12855 (downcase (or (org-entry-get nil "COOKIE_DATA")
12856 "")))))
12857 (throw 'exit nil))
12858 (while (re-search-forward box-re (point-at-eol) t)
12859 (setq cnt-all 0 cnt-done 0 cookie-present t)
12860 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12861 (save-match-data
12862 (unless (outline-next-heading) (throw 'exit nil))
12863 (while (and (looking-at org-complex-heading-regexp)
12864 (> (setq l1 (length (match-string 1))) level))
12865 (setq kwd (and (or recursive (= l1 ltoggle))
12866 (match-string 2)))
12867 (if (or (eq org-provide-todo-statistics 'all-headlines)
12868 (and (eq org-provide-todo-statistics t)
12869 (or (member kwd org-done-keywords)))
12870 (and (listp org-provide-todo-statistics)
12871 (stringp (car org-provide-todo-statistics))
12872 (or (member kwd org-provide-todo-statistics)
12873 (member kwd org-done-keywords)))
12874 (and (listp org-provide-todo-statistics)
12875 (listp (car org-provide-todo-statistics))
12876 (or (member kwd (car org-provide-todo-statistics))
12877 (and (member kwd org-done-keywords)
12878 (member kwd (cadr org-provide-todo-statistics))))))
12879 (setq cnt-all (1+ cnt-all))
12880 (and (eq org-provide-todo-statistics t)
12882 (setq cnt-all (1+ cnt-all))))
12883 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12884 (member kwd org-done-keywords))
12885 (and (listp org-provide-todo-statistics)
12886 (listp (car org-provide-todo-statistics))
12887 (member kwd org-done-keywords)
12888 (member kwd (cadr org-provide-todo-statistics)))
12889 (and (listp org-provide-todo-statistics)
12890 (stringp (car org-provide-todo-statistics))
12891 (member kwd org-done-keywords)))
12892 (setq cnt-done (1+ cnt-done)))
12893 (outline-next-heading)))
12894 (setq new
12895 (if is-percent
12896 (format "[%d%%]" (floor (* 100.0 cnt-done)
12897 (max 1 cnt-all)))
12898 (format "[%d/%d]" cnt-done cnt-all))
12899 ndel (- (match-end 0) checkbox-beg))
12900 (goto-char checkbox-beg)
12901 (insert new)
12902 (delete-region (point) (+ (point) ndel))
12903 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12904 (when cookie-present
12905 (run-hook-with-args 'org-after-todo-statistics-hook
12906 cnt-done (- cnt-all cnt-done))))))
12907 (run-hooks 'org-todo-statistics-hook)))
12909 (defvar org-after-todo-statistics-hook nil
12910 "Hook that is called after a TODO statistics cookie has been updated.
12911 Each function is called with two arguments: the number of not-done entries
12912 and the number of done entries.
12914 For example, the following function, when added to this hook, will switch
12915 an entry to DONE when all children are done, and back to TODO when new
12916 entries are set to a TODO status. Note that this hook is only called
12917 when there is a statistics cookie in the headline!
12919 (defun org-summary-todo (n-done n-not-done)
12920 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12921 (let (org-log-done org-log-states) ; turn off logging
12922 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12925 (defvar org-todo-statistics-hook nil
12926 "Hook that is run whenever Org thinks TODO statistics should be updated.
12927 This hook runs even if there is no statistics cookie present, in which case
12928 `org-after-todo-statistics-hook' would not run.")
12930 (defun org-todo-trigger-tag-changes (state)
12931 "Apply the changes defined in `org-todo-state-tags-triggers'."
12932 (let ((l org-todo-state-tags-triggers)
12933 changes)
12934 (when (or (not state) (equal state ""))
12935 (setq changes (append changes (cdr (assoc "" l)))))
12936 (when (and (stringp state) (> (length state) 0))
12937 (setq changes (append changes (cdr (assoc state l)))))
12938 (when (member state org-not-done-keywords)
12939 (setq changes (append changes (cdr (assq 'todo l)))))
12940 (when (member state org-done-keywords)
12941 (setq changes (append changes (cdr (assq 'done l)))))
12942 (dolist (c changes)
12943 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12945 (defun org-local-logging (value)
12946 "Get logging settings from a property VALUE."
12947 ;; Directly set the variables, they are already local.
12948 (setq org-log-done nil
12949 org-log-repeat nil
12950 org-todo-log-states nil)
12951 (dolist (w (org-split-string value))
12952 (let (a)
12953 (cond
12954 ((setq a (assoc w org-startup-options))
12955 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12956 (set (nth 1 a) (nth 2 a))))
12957 ((setq a (org-extract-log-state-settings w))
12958 (and (member (car a) org-todo-keywords-1)
12959 (push a org-todo-log-states)))))))
12961 (defun org-get-todo-sequence-head (kwd)
12962 "Return the head of the TODO sequence to which KWD belongs.
12963 If KWD is not set, check if there is a text property remembering the
12964 right sequence."
12965 (let (p)
12966 (cond
12967 ((not kwd)
12968 (or (get-text-property (point-at-bol) 'org-todo-head)
12969 (progn
12970 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12971 nil (point-at-eol)))
12972 (get-text-property p 'org-todo-head))))
12973 ((not (member kwd org-todo-keywords-1))
12974 (car org-todo-keywords-1))
12975 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12977 (defun org-fast-todo-selection ()
12978 "Fast TODO keyword selection with single keys.
12979 Returns the new TODO keyword, or nil if no state change should occur."
12980 (let* ((fulltable org-todo-key-alist)
12981 (done-keywords org-done-keywords) ;; needed for the faces.
12982 (maxlen (apply 'max (mapcar
12983 (lambda (x)
12984 (if (stringp (car x)) (string-width (car x)) 0))
12985 fulltable)))
12986 (expert nil)
12987 (fwidth (+ maxlen 3 1 3))
12988 (ncol (/ (- (window-width) 4) fwidth))
12989 tg cnt e c tbl
12990 groups ingroup)
12991 (save-excursion
12992 (save-window-excursion
12993 (if expert
12994 (set-buffer (get-buffer-create " *Org todo*"))
12995 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12996 (erase-buffer)
12997 (setq-local org-done-keywords done-keywords)
12998 (setq tbl fulltable cnt 0)
12999 (while (setq e (pop tbl))
13000 (cond
13001 ((equal e '(:startgroup))
13002 (push '() groups) (setq ingroup t)
13003 (unless (= cnt 0)
13004 (setq cnt 0)
13005 (insert "\n"))
13006 (insert "{ "))
13007 ((equal e '(:endgroup))
13008 (setq ingroup nil cnt 0)
13009 (insert "}\n"))
13010 ((equal e '(:newline))
13011 (unless (= cnt 0)
13012 (setq cnt 0)
13013 (insert "\n")
13014 (setq e (car tbl))
13015 (while (equal (car tbl) '(:newline))
13016 (insert "\n")
13017 (setq tbl (cdr tbl)))))
13019 (setq tg (car e) c (cdr e))
13020 (when ingroup (push tg (car groups)))
13021 (setq tg (org-add-props tg nil 'face
13022 (org-get-todo-face tg)))
13023 (when (and (= cnt 0) (not ingroup)) (insert " "))
13024 (insert "[" c "] " tg (make-string
13025 (- fwidth 4 (length tg)) ?\ ))
13026 (when (= (setq cnt (1+ cnt)) ncol)
13027 (insert "\n")
13028 (when ingroup (insert " "))
13029 (setq cnt 0)))))
13030 (insert "\n")
13031 (goto-char (point-min))
13032 (unless expert (org-fit-window-to-buffer))
13033 (message "[a-z..]:Set [SPC]:clear")
13034 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13035 (cond
13036 ((or (= c ?\C-g)
13037 (and (= c ?q) (not (rassoc c fulltable))))
13038 (setq quit-flag t))
13039 ((= c ?\ ) nil)
13040 ((setq e (rassoc c fulltable) tg (car e))
13042 (t (setq quit-flag t)))))))
13044 (defun org-entry-is-todo-p ()
13045 (member (org-get-todo-state) org-not-done-keywords))
13047 (defun org-entry-is-done-p ()
13048 (member (org-get-todo-state) org-done-keywords))
13050 (defun org-get-todo-state ()
13051 "Return the TODO keyword of the current subtree."
13052 (save-excursion
13053 (org-back-to-heading t)
13054 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13055 (match-end 2)
13056 (match-string 2))))
13058 (defun org-at-date-range-p (&optional inactive-ok)
13059 "Non-nil if point is inside a date range.
13061 When optional argument INACTIVE-OK is non-nil, also consider
13062 inactive time ranges.
13064 When this function returns a non-nil value, match data is set
13065 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13066 on INACTIVE-OK."
13067 (interactive)
13068 (save-excursion
13069 (catch 'exit
13070 (let ((pos (point)))
13071 (skip-chars-backward "^[<\r\n")
13072 (skip-chars-backward "<[")
13073 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13074 (>= (match-end 0) pos)
13075 (throw 'exit t))
13076 (skip-chars-backward "^<[\r\n")
13077 (skip-chars-backward "<[")
13078 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13079 (>= (match-end 0) pos)
13080 (throw 'exit t)))
13081 nil)))
13083 (defun org-get-repeat (&optional timestamp)
13084 "Check if there is a time-stamp with repeater in this entry.
13086 Return the repeater, as a string, or nil. Also return nil when
13087 this function is called before first heading.
13089 When optional argument TIMESTAMP is a string, extract the
13090 repeater from there instead."
13091 (save-match-data
13092 (cond (timestamp
13093 (and (string-match org-repeat-re timestamp)
13094 (match-string-no-properties 1 timestamp)))
13095 ((org-before-first-heading-p) nil)
13097 (save-excursion
13098 (org-back-to-heading t)
13099 (let ((end (org-entry-end-position)))
13100 (catch :repeat
13101 (while (re-search-forward org-repeat-re end t)
13102 (when (save-match-data (org-at-timestamp-p))
13103 (throw :repeat (match-string-no-properties 1)))))))))))
13105 (defvar org-last-changed-timestamp)
13106 (defvar org-last-inserted-timestamp)
13107 (defvar org-log-post-message)
13108 (defvar org-log-note-purpose)
13109 (defvar org-log-note-how nil)
13110 (defvar org-log-note-extra)
13111 (defun org-auto-repeat-maybe (done-word)
13112 "Check if the current headline contains a repeated time-stamp.
13114 If yes, set TODO state back to what it was and change the base date
13115 of repeating deadline/scheduled time stamps to new date.
13117 This function is run automatically after each state change to a DONE state."
13118 (let* ((repeat (org-get-repeat))
13119 (aa (assoc org-last-state org-todo-kwd-alist))
13120 (interpret (nth 1 aa))
13121 (head (nth 2 aa))
13122 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13123 (msg "Entry repeats: ")
13124 (org-log-done nil)
13125 (org-todo-log-states nil)
13126 (end (copy-marker (org-entry-end-position))))
13127 (unwind-protect
13128 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13129 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13130 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13131 org-todo-repeat-to-state)))
13132 (org-todo (cond
13133 ((and to-state (member to-state org-todo-keywords-1))
13134 to-state)
13135 ((eq interpret 'type) org-last-state)
13136 (head)
13137 (t 'none))))
13138 (org-back-to-heading t)
13139 (org-add-planning-info nil nil 'closed)
13140 ;; When `org-log-repeat' is non-nil or entry contains
13141 ;; a clock, set LAST_REPEAT property.
13142 (when (or org-log-repeat
13143 (catch :clock
13144 (while (re-search-forward org-clock-line-re end t)
13145 (when (org-at-clock-log-p) (throw :clock t)))))
13146 (org-entry-put nil "LAST_REPEAT" (format-time-string
13147 (org-time-stamp-format t t)
13148 (current-time))))
13149 (when org-log-repeat
13150 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13151 (memq 'org-add-log-note post-command-hook))
13152 ;; We are already setup for some record.
13153 (when (eq org-log-repeat 'note)
13154 ;; Make sure we take a note, not only a time stamp.
13155 (setq org-log-note-how 'note))
13156 ;; Set up for taking a record.
13157 (org-add-log-setup 'state
13158 (or done-word (car org-done-keywords))
13159 org-last-state
13160 org-log-repeat)))
13161 (let ((planning-re (regexp-opt
13162 (list org-scheduled-string org-deadline-string))))
13163 (while (re-search-forward org-ts-regexp end t)
13164 (let* ((ts (match-string 0))
13165 (planning? (org-at-planning-p))
13166 (type (if (not planning?) "Plain:"
13167 (save-excursion
13168 (re-search-backward
13169 planning-re (line-beginning-position) t)
13170 (match-string 0)))))
13171 (cond
13172 ;; Ignore fake time-stamps (e.g., within comments).
13173 ((not (org-at-timestamp-p t)))
13174 ;; Time-stamps without a repeater are usually
13175 ;; skipped. However, a SCHEDULED time-stamp without
13176 ;; one is removed, as they are no longer relevant.
13177 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13178 ts))
13179 (when (equal type org-scheduled-string)
13180 (org-remove-timestamp-with-keyword type)))
13182 (let ((n (string-to-number (match-string 2 ts)))
13183 (what (match-string 3 ts)))
13184 (when (equal what "w") (setq n (* n 7) what "d"))
13185 (when (and (equal what "h")
13186 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13187 ts)))
13188 (user-error
13189 "Cannot repeat in Repeat in %d hour(s) because no hour \
13190 has been set"
13192 ;; Preparation, see if we need to modify the start
13193 ;; date for the change.
13194 (when (match-end 1)
13195 (let ((time (save-match-data
13196 (org-time-string-to-time ts))))
13197 (cond
13198 ((equal (match-string 1 ts) ".")
13199 ;; Shift starting date to today
13200 (org-timestamp-change
13201 (- (org-today) (time-to-days time))
13202 'day))
13203 ((equal (match-string 1 ts) "+")
13204 (let ((nshiftmax 10)
13205 (nshift 0))
13206 (while (or (= nshift 0)
13207 (not (time-less-p (current-time) time)))
13208 (when (= (cl-incf nshift) nshiftmax)
13209 (or (y-or-n-p
13210 (format "%d repeater intervals were not \
13211 enough to shift date past today. Continue? "
13212 nshift))
13213 (user-error "Abort")))
13214 (org-timestamp-change n (cdr (assoc what whata)))
13215 (org-in-regexp org-ts-regexp3)
13216 (setq ts (match-string 1))
13217 (setq time
13218 (save-match-data
13219 (org-time-string-to-time ts)))))
13220 (org-timestamp-change (- n) (cdr (assoc what whata)))
13221 ;; Rematch, so that we have everything in place
13222 ;; for the real shift.
13223 (org-in-regexp org-ts-regexp3)
13224 (setq ts (match-string 1))
13225 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13226 ts)))))
13227 (save-excursion
13228 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13229 (setq msg
13230 (concat
13231 msg type " " org-last-changed-timestamp " "))))))))
13232 (setq org-log-post-message msg)
13233 (message "%s" msg))
13234 (set-marker end nil))))
13236 (defun org-show-todo-tree (arg)
13237 "Make a compact tree which shows all headlines marked with TODO.
13238 The tree will show the lines where the regexp matches, and all higher
13239 headlines above the match.
13240 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13241 With a numeric prefix N, construct a sparse tree for the Nth element
13242 of `org-todo-keywords-1'."
13243 (interactive "P")
13244 (let ((case-fold-search nil)
13245 (kwd-re
13246 (cond ((null arg) org-not-done-regexp)
13247 ((equal arg '(4))
13248 (let ((kwd
13249 (completing-read "Keyword (or KWD1|KWD2|...): "
13250 (mapcar #'list org-todo-keywords-1))))
13251 (concat "\\("
13252 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13253 "\\)\\>")))
13254 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13255 (regexp-quote (nth (1- (prefix-numeric-value arg))
13256 org-todo-keywords-1)))
13257 (t (user-error "Invalid prefix argument: %s" arg)))))
13258 (message "%d TODO entries found"
13259 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13261 (defun org--deadline-or-schedule (arg type time)
13262 "Insert DEADLINE or SCHEDULE information in current entry.
13263 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13264 `org-schedule' for information about ARG and TIME arguments."
13265 (let* ((deadline? (eq type 'deadline))
13266 (keyword (if deadline? org-deadline-string org-scheduled-string))
13267 (log (if deadline? org-log-redeadline org-log-reschedule))
13268 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13269 (old-date-time (and old-date (org-time-string-to-time old-date)))
13270 ;; Save repeater cookie from either TIME or current scheduled
13271 ;; time stamp. We are going to insert it back at the end of
13272 ;; the process.
13273 (repeater (or (and (org-string-nw-p time)
13274 ;; We use `org-repeat-re' because we need
13275 ;; to tell the difference between a real
13276 ;; repeater and a time delta, e.g. "+2d".
13277 (string-match org-repeat-re time)
13278 (match-string 1 time))
13279 (and (org-string-nw-p old-date)
13280 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13281 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13282 old-date)
13283 (match-string 1 old-date)))))
13284 (pcase arg
13285 (`(4)
13286 (when (and old-date log)
13287 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13288 nil old-date log))
13289 (org-remove-timestamp-with-keyword keyword)
13290 (message (if deadline? "Item no longer has a deadline."
13291 "Item is no longer scheduled.")))
13292 (`(16)
13293 (save-excursion
13294 (org-back-to-heading t)
13295 (let ((regexp (if deadline? org-deadline-time-regexp
13296 org-scheduled-time-regexp)))
13297 (if (not (re-search-forward regexp (line-end-position 2) t))
13298 (user-error (if deadline? "No deadline information to update"
13299 "No scheduled information to update"))
13300 (let* ((rpl0 (match-string 1))
13301 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13302 (msg (if deadline? "Warn starting from" "Delay until")))
13303 (replace-match
13304 (concat keyword
13305 " <" rpl
13306 (format " -%dd"
13307 (abs (- (time-to-days
13308 (save-match-data
13309 (org-read-date
13310 nil t nil msg old-date-time)))
13311 (time-to-days old-date-time))))
13312 ">") t t))))))
13314 (org-add-planning-info type time 'closed)
13315 (when (and old-date
13317 (not (equal old-date org-last-inserted-timestamp)))
13318 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13319 org-last-inserted-timestamp
13320 old-date
13321 log))
13322 (when repeater
13323 (save-excursion
13324 (org-back-to-heading t)
13325 (when (re-search-forward
13326 (concat keyword " " org-last-inserted-timestamp)
13327 (line-end-position 2)
13329 (goto-char (1- (match-end 0)))
13330 (insert " " repeater)
13331 (setq org-last-inserted-timestamp
13332 (concat (substring org-last-inserted-timestamp 0 -1)
13333 " " repeater
13334 (substring org-last-inserted-timestamp -1))))))
13335 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13336 org-last-inserted-timestamp)))))
13338 (defun org-deadline (arg &optional time)
13339 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13340 With one universal prefix argument, remove any deadline from the item.
13341 With two universal prefix arguments, prompt for a warning delay.
13342 With argument TIME, set the deadline at the corresponding date. TIME
13343 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13344 (interactive "P")
13345 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13346 (org-map-entries
13347 (lambda () (org--deadline-or-schedule arg 'deadline time))
13349 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13350 'region-start-level
13351 'region)
13352 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13353 (org--deadline-or-schedule arg 'deadline time)))
13355 (defun org-schedule (arg &optional time)
13356 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13357 With one universal prefix argument, remove any scheduling date from the item.
13358 With two universal prefix arguments, prompt for a delay cookie.
13359 With argument TIME, scheduled at the corresponding date. TIME can
13360 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13361 (interactive "P")
13362 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13363 (org-map-entries
13364 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13366 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13367 'region-start-level
13368 'region)
13369 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13370 (org--deadline-or-schedule arg 'scheduled time)))
13372 (defun org-get-scheduled-time (pom &optional inherit)
13373 "Get the scheduled time as a time tuple, of a format suitable
13374 for calling org-schedule with, or if there is no scheduling,
13375 returns nil."
13376 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13377 (when time
13378 (apply 'encode-time (org-parse-time-string time)))))
13380 (defun org-get-deadline-time (pom &optional inherit)
13381 "Get the deadline as a time tuple, of a format suitable for
13382 calling org-deadline with, or if there is no scheduling, returns
13383 nil."
13384 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13385 (when time
13386 (apply 'encode-time (org-parse-time-string time)))))
13388 (defun org-remove-timestamp-with-keyword (keyword)
13389 "Remove all time stamps with KEYWORD in the current entry."
13390 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13391 beg)
13392 (save-excursion
13393 (org-back-to-heading t)
13394 (setq beg (point))
13395 (outline-next-heading)
13396 (while (re-search-backward re beg t)
13397 (replace-match "")
13398 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13399 (equal (char-before) ?\ ))
13400 (backward-delete-char 1)
13401 (when (string-match "^[ \t]*$" (buffer-substring
13402 (point-at-bol) (point-at-eol)))
13403 (delete-region (point-at-bol)
13404 (min (point-max) (1+ (point-at-eol))))))))))
13406 (defvar org-time-was-given) ; dynamically scoped parameter
13407 (defvar org-end-time-was-given) ; dynamically scoped parameter
13409 (defun org-at-planning-p ()
13410 "Non-nil when point is on a planning info line."
13411 ;; This is as accurate and faster than `org-element-at-point' since
13412 ;; planning info location is fixed in the section.
13413 (org-with-wide-buffer
13414 (beginning-of-line)
13415 (and (looking-at-p org-planning-line-re)
13416 (eq (point)
13417 (ignore-errors
13418 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13419 (org-back-to-heading t)
13420 (org-with-limited-levels (org-back-to-heading t)))
13421 (line-beginning-position 2))))))
13423 (defun org-add-planning-info (what &optional time &rest remove)
13424 "Insert new timestamp with keyword in the planning line.
13425 WHAT indicates what kind of time stamp to add. It is a symbol
13426 among `closed', `deadline', `scheduled' and nil. TIME indicates
13427 the time to use. If none is given, the user is prompted for
13428 a date. REMOVE indicates what kind of entries to remove. An old
13429 WHAT entry will also be removed."
13430 (let (org-time-was-given org-end-time-was-given default-time default-input)
13431 (catch 'exit
13432 (when (and (memq what '(scheduled deadline))
13433 (or (not time)
13434 (and (stringp time)
13435 (string-match "^[-+]+[0-9]" time))))
13436 ;; Try to get a default date/time from existing timestamp
13437 (save-excursion
13438 (org-back-to-heading t)
13439 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13440 (when (re-search-forward (if (eq what 'scheduled)
13441 org-scheduled-time-regexp
13442 org-deadline-time-regexp)
13443 end t)
13444 (setq ts (match-string 1)
13445 default-time (apply 'encode-time (org-parse-time-string ts))
13446 default-input (and ts (org-get-compact-tod ts)))))))
13447 (when what
13448 (setq time
13449 (if (stringp time)
13450 ;; This is a string (relative or absolute), set
13451 ;; proper date.
13452 (apply #'encode-time
13453 (org-read-date-analyze
13454 time default-time (decode-time default-time)))
13455 ;; If necessary, get the time from the user
13456 (or time (org-read-date nil 'to-time nil nil
13457 default-time default-input)))))
13459 (org-with-wide-buffer
13460 (org-back-to-heading t)
13461 (forward-line)
13462 (unless (bolp) (insert "\n"))
13463 (cond ((looking-at-p org-planning-line-re)
13464 ;; Move to current indentation.
13465 (skip-chars-forward " \t")
13466 ;; Check if we have to remove something.
13467 (dolist (type (if what (cons what remove) remove))
13468 (save-excursion
13469 (when (re-search-forward
13470 (cl-case type
13471 (closed org-closed-time-regexp)
13472 (deadline org-deadline-time-regexp)
13473 (scheduled org-scheduled-time-regexp)
13474 (otherwise
13475 (error "Invalid planning type: %s" type)))
13476 (line-end-position) t)
13477 ;; Delete until next keyword or end of line.
13478 (delete-region
13479 (match-beginning 0)
13480 (if (re-search-forward org-keyword-time-not-clock-regexp
13481 (line-end-position)
13483 (match-beginning 0)
13484 (line-end-position))))))
13485 ;; If there is nothing more to add and no more keyword
13486 ;; is left, remove the line completely.
13487 (if (and (looking-at-p "[ \t]*$") (not what))
13488 (delete-region (line-beginning-position)
13489 (line-beginning-position 2))
13490 ;; If we removed last keyword, do not leave trailing
13491 ;; white space at the end of line.
13492 (let ((p (point)))
13493 (save-excursion
13494 (end-of-line)
13495 (unless (= (skip-chars-backward " \t" p) 0)
13496 (delete-region (point) (line-end-position)))))))
13497 ((not what) (throw 'exit nil)) ; Nothing to do.
13498 (t (insert-before-markers "\n")
13499 (backward-char 1)
13500 (when org-adapt-indentation
13501 (indent-to-column (1+ (org-outline-level))))))
13502 (when what
13503 ;; Insert planning keyword.
13504 (insert (cl-case what
13505 (closed org-closed-string)
13506 (deadline org-deadline-string)
13507 (scheduled org-scheduled-string)
13508 (otherwise (error "Invalid planning type: %s" what)))
13509 " ")
13510 ;; Insert associated timestamp.
13511 (let ((ts (org-insert-time-stamp
13512 time
13513 (or org-time-was-given
13514 (and (eq what 'closed) org-log-done-with-time))
13515 (eq what 'closed)
13516 nil nil (list org-end-time-was-given))))
13517 (unless (eolp) (insert " "))
13518 ts))))))
13520 (defvar org-log-note-marker (make-marker)
13521 "Marker pointing at the entry where the note is to be inserted.")
13522 (defvar org-log-note-purpose nil)
13523 (defvar org-log-note-state nil)
13524 (defvar org-log-note-previous-state nil)
13525 (defvar org-log-note-extra nil)
13526 (defvar org-log-note-window-configuration nil)
13527 (defvar org-log-note-return-to (make-marker))
13528 (defvar org-log-note-effective-time nil
13529 "Remembered current time so that dynamically scoped
13530 `org-extend-today-until' affects timestamps in state change log")
13532 (defvar org-log-post-message nil
13533 "Message to be displayed after a log note has been stored.
13534 The auto-repeater uses this.")
13536 (defun org-add-note ()
13537 "Add a note to the current entry.
13538 This is done in the same way as adding a state change note."
13539 (interactive)
13540 (org-add-log-setup 'note))
13542 (defun org-log-beginning (&optional create)
13543 "Return expected start of log notes in current entry.
13544 When optional argument CREATE is non-nil, the function creates
13545 a drawer to store notes, if necessary. Returned position ignores
13546 narrowing."
13547 (org-with-wide-buffer
13548 (let ((drawer (org-log-into-drawer)))
13549 (cond
13550 (drawer
13551 (org-end-of-meta-data)
13552 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13553 (end (if (org-at-heading-p) (point)
13554 (save-excursion (outline-next-heading) (point))))
13555 (case-fold-search t))
13556 (catch 'exit
13557 ;; Try to find existing drawer.
13558 (while (re-search-forward regexp end t)
13559 (let ((element (org-element-at-point)))
13560 (when (eq (org-element-type element) 'drawer)
13561 (let ((cend (org-element-property :contents-end element)))
13562 (when (and (not org-log-states-order-reversed) cend)
13563 (goto-char cend)))
13564 (throw 'exit nil))))
13565 ;; No drawer found. Create one, if permitted.
13566 (when create
13567 (unless (bolp) (insert "\n"))
13568 (let ((beg (point)))
13569 (insert ":" drawer ":\n:END:\n")
13570 (org-indent-region beg (point)))
13571 (end-of-line -1)))))
13573 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13574 (skip-chars-forward " \t\n")
13575 (beginning-of-line)
13576 (unless org-log-states-order-reversed
13577 (org-skip-over-state-notes)
13578 (skip-chars-backward " \t\n")
13579 (forward-line)))))
13580 (if (bolp) (point) (line-beginning-position 2))))
13582 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13583 "Set up the post command hook to take a note.
13584 If this is about to TODO state change, the new state is expected in STATE.
13585 HOW is an indicator what kind of note should be created.
13586 EXTRA is additional text that will be inserted into the notes buffer."
13587 (move-marker org-log-note-marker (point))
13588 (setq org-log-note-purpose purpose
13589 org-log-note-state state
13590 org-log-note-previous-state prev-state
13591 org-log-note-how how
13592 org-log-note-extra extra
13593 org-log-note-effective-time (org-current-effective-time))
13594 (add-hook 'post-command-hook 'org-add-log-note 'append))
13596 (defun org-skip-over-state-notes ()
13597 "Skip past the list of State notes in an entry."
13598 (when (ignore-errors (goto-char (org-in-item-p)))
13599 (let* ((struct (org-list-struct))
13600 (prevs (org-list-prevs-alist struct))
13601 (regexp
13602 (concat "[ \t]*- +"
13603 (replace-regexp-in-string
13604 " +" " +"
13605 (org-replace-escapes
13606 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13607 `(("%d" . ,org-ts-regexp-inactive)
13608 ("%D" . ,org-ts-regexp)
13609 ("%s" . "\"\\S-+\"")
13610 ("%S" . "\"\\S-+\"")
13611 ("%t" . ,org-ts-regexp-inactive)
13612 ("%T" . ,org-ts-regexp)
13613 ("%u" . ".*?")
13614 ("%U" . ".*?")))))))
13615 (while (looking-at-p regexp)
13616 (goto-char (or (org-list-get-next-item (point) struct prevs)
13617 (org-list-get-item-end (point) struct)))))))
13619 (defun org-add-log-note (&optional _purpose)
13620 "Pop up a window for taking a note, and add this note later."
13621 (remove-hook 'post-command-hook 'org-add-log-note)
13622 (setq org-log-note-window-configuration (current-window-configuration))
13623 (delete-other-windows)
13624 (move-marker org-log-note-return-to (point))
13625 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13626 (goto-char org-log-note-marker)
13627 (org-switch-to-buffer-other-window "*Org Note*")
13628 (erase-buffer)
13629 (if (memq org-log-note-how '(time state))
13630 (let (current-prefix-arg) (org-store-log-note))
13631 (let ((org-inhibit-startup t)) (org-mode))
13632 (insert (format "# Insert note for %s.
13633 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13634 (cond
13635 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13636 ((eq org-log-note-purpose 'done) "closed todo item")
13637 ((eq org-log-note-purpose 'state)
13638 (format "state change from \"%s\" to \"%s\""
13639 (or org-log-note-previous-state "")
13640 (or org-log-note-state "")))
13641 ((eq org-log-note-purpose 'reschedule)
13642 "rescheduling")
13643 ((eq org-log-note-purpose 'delschedule)
13644 "no longer scheduled")
13645 ((eq org-log-note-purpose 'redeadline)
13646 "changing deadline")
13647 ((eq org-log-note-purpose 'deldeadline)
13648 "removing deadline")
13649 ((eq org-log-note-purpose 'refile)
13650 "refiling")
13651 ((eq org-log-note-purpose 'note)
13652 "this entry")
13653 (t (error "This should not happen")))))
13654 (when org-log-note-extra (insert org-log-note-extra))
13655 (setq-local org-finish-function 'org-store-log-note)
13656 (run-hooks 'org-log-buffer-setup-hook)))
13658 (defvar org-note-abort nil) ; dynamically scoped
13659 (defun org-store-log-note ()
13660 "Finish taking a log note, and insert it to where it belongs."
13661 (let ((txt (prog1 (buffer-string)
13662 (kill-buffer)))
13663 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13664 lines)
13665 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13666 (setq txt (replace-match "" t t txt)))
13667 (when (string-match "\\s-+\\'" txt)
13668 (setq txt (replace-match "" t t txt)))
13669 (setq lines (org-split-string txt "\n"))
13670 (when (org-string-nw-p note)
13671 (setq note
13672 (org-replace-escapes
13673 note
13674 (list (cons "%u" (user-login-name))
13675 (cons "%U" user-full-name)
13676 (cons "%t" (format-time-string
13677 (org-time-stamp-format 'long 'inactive)
13678 org-log-note-effective-time))
13679 (cons "%T" (format-time-string
13680 (org-time-stamp-format 'long nil)
13681 org-log-note-effective-time))
13682 (cons "%d" (format-time-string
13683 (org-time-stamp-format nil 'inactive)
13684 org-log-note-effective-time))
13685 (cons "%D" (format-time-string
13686 (org-time-stamp-format nil nil)
13687 org-log-note-effective-time))
13688 (cons "%s" (cond
13689 ((not org-log-note-state) "")
13690 ((string-match-p org-ts-regexp
13691 org-log-note-state)
13692 (format "\"[%s]\""
13693 (substring org-log-note-state 1 -1)))
13694 (t (format "\"%s\"" org-log-note-state))))
13695 (cons "%S"
13696 (cond
13697 ((not org-log-note-previous-state) "")
13698 ((string-match-p org-ts-regexp
13699 org-log-note-previous-state)
13700 (format "\"[%s]\""
13701 (substring
13702 org-log-note-previous-state 1 -1)))
13703 (t (format "\"%s\""
13704 org-log-note-previous-state)))))))
13705 (when lines (setq note (concat note " \\\\")))
13706 (push note lines))
13707 (when (and lines (not (or current-prefix-arg org-note-abort)))
13708 (with-current-buffer (marker-buffer org-log-note-marker)
13709 (org-with-wide-buffer
13710 ;; Find location for the new note.
13711 (goto-char org-log-note-marker)
13712 (set-marker org-log-note-marker nil)
13713 ;; Note associated to a clock is to be located right after
13714 ;; the clock. Do not move point.
13715 (unless (eq org-log-note-purpose 'clock-out)
13716 (goto-char (org-log-beginning t)))
13717 ;; Make sure point is at the beginning of an empty line.
13718 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13719 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13720 ;; In an existing list, add a new item at the top level.
13721 ;; Otherwise, indent line like a regular one.
13722 (let ((itemp (org-in-item-p)))
13723 (if itemp
13724 (indent-line-to
13725 (let ((struct (save-excursion
13726 (goto-char itemp) (org-list-struct))))
13727 (org-list-get-ind (org-list-get-top-point struct) struct)))
13728 (org-indent-line)))
13729 (insert (org-list-bullet-string "-") (pop lines))
13730 (let ((ind (org-list-item-body-column (line-beginning-position))))
13731 (dolist (line lines)
13732 (insert "\n")
13733 (indent-line-to ind)
13734 (insert line)))
13735 (message "Note stored")
13736 (org-back-to-heading t)
13737 (org-cycle-hide-drawers 'children))
13738 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13739 ;; from within `org-add-log-note' because `buffer-undo-list'
13740 ;; is then modified outside of `org-with-remote-undo'.
13741 (when (eq this-command 'org-agenda-todo)
13742 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13743 ;; Don't add undo information when called from `org-agenda-todo'.
13744 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13745 (set-window-configuration org-log-note-window-configuration)
13746 (with-current-buffer (marker-buffer org-log-note-return-to)
13747 (goto-char org-log-note-return-to))
13748 (move-marker org-log-note-return-to nil)
13749 (when org-log-post-message (message "%s" org-log-post-message))))
13751 (defun org-remove-empty-drawer-at (pos)
13752 "Remove an empty drawer at position POS.
13753 POS may also be a marker."
13754 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13755 (org-with-wide-buffer
13756 (goto-char pos)
13757 (let ((drawer (org-element-at-point)))
13758 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13759 (not (org-element-property :contents-begin drawer)))
13760 (delete-region (org-element-property :begin drawer)
13761 (progn (goto-char (org-element-property :end drawer))
13762 (skip-chars-backward " \r\t\n")
13763 (forward-line)
13764 (point))))))))
13766 (defvar org-ts-type nil)
13767 (defun org-sparse-tree (&optional arg type)
13768 "Create a sparse tree, prompt for the details.
13769 This command can create sparse trees. You first need to select the type
13770 of match used to create the tree:
13772 t Show all TODO entries.
13773 T Show entries with a specific TODO keyword.
13774 m Show entries selected by a tags/property match.
13775 p Enter a property name and its value (both with completion on existing
13776 names/values) and show entries with that property.
13777 r Show entries matching a regular expression (`/' can be used as well).
13778 b Show deadlines and scheduled items before a date.
13779 a Show deadlines and scheduled items after a date.
13780 d Show deadlines due within `org-deadline-warning-days'.
13781 D Show deadlines and scheduled items between a date range."
13782 (interactive "P")
13783 (setq type (or type org-sparse-tree-default-date-type))
13784 (setq org-ts-type type)
13785 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13786 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13787 \[c]ycle through date types: %s"
13788 (cl-case type
13789 (all "all timestamps")
13790 (scheduled "only scheduled")
13791 (deadline "only deadline")
13792 (active "only active timestamps")
13793 (inactive "only inactive timestamps")
13794 (closed "with a closed time-stamp")
13795 (otherwise "scheduled/deadline")))
13796 (let ((answer (read-char-exclusive)))
13797 (cl-case answer
13799 (org-sparse-tree
13801 (cadr
13802 (memq type '(nil all scheduled deadline active inactive closed)))))
13803 (?d (call-interactively 'org-check-deadlines))
13804 (?b (call-interactively 'org-check-before-date))
13805 (?a (call-interactively 'org-check-after-date))
13806 (?D (call-interactively 'org-check-dates-range))
13807 (?t (call-interactively 'org-show-todo-tree))
13808 (?T (org-show-todo-tree '(4)))
13809 (?m (call-interactively 'org-match-sparse-tree))
13810 ((?p ?P)
13811 (let* ((kwd (completing-read
13812 "Property: " (mapcar #'list (org-buffer-property-keys))))
13813 (value (completing-read
13814 "Value: " (mapcar #'list (org-property-values kwd)))))
13815 (unless (string-match "\\`{.*}\\'" value)
13816 (setq value (concat "\"" value "\"")))
13817 (org-match-sparse-tree arg (concat kwd "=" value))))
13818 ((?r ?R ?/) (call-interactively 'org-occur))
13819 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13821 (defvar-local org-occur-highlights nil
13822 "List of overlays used for occur matches.")
13823 (defvar-local org-occur-parameters nil
13824 "Parameters of the active org-occur calls.
13825 This is a list, each call to org-occur pushes as cons cell,
13826 containing the regular expression and the callback, onto the list.
13827 The list can contain several entries if `org-occur' has been called
13828 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13829 will only contain one set of parameters. When the highlights are
13830 removed (for example with `C-c C-c', or with the next edit (depending
13831 on `org-remove-highlights-with-change'), this variable is emptied
13832 as well.")
13834 (defun org-occur (regexp &optional keep-previous callback)
13835 "Make a compact tree which shows all matches of REGEXP.
13837 The tree will show the lines where the regexp matches, and any other context
13838 defined in `org-show-context-detail', which see.
13840 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13841 done by a previous call to `org-occur' will be kept, to allow stacking of
13842 calls to this command.
13844 Optional argument CALLBACK can be a function of no argument. In this case,
13845 it is called with point at the end of the match, match data being set
13846 accordingly. Current match is shown only if the return value is non-nil.
13847 The function must neither move point nor alter narrowing."
13848 (interactive "sRegexp: \nP")
13849 (when (equal regexp "")
13850 (user-error "Regexp cannot be empty"))
13851 (unless keep-previous
13852 (org-remove-occur-highlights nil nil t))
13853 (push (cons regexp callback) org-occur-parameters)
13854 (let ((cnt 0))
13855 (save-excursion
13856 (goto-char (point-min))
13857 (when (or (not keep-previous) ; do not want to keep
13858 (not org-occur-highlights)) ; no previous matches
13859 ;; hide everything
13860 (org-overview))
13861 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13862 (isearch-no-upper-case-p regexp t)
13863 org-occur-case-fold-search)))
13864 (while (re-search-forward regexp nil t)
13865 (when (or (not callback)
13866 (save-match-data (funcall callback)))
13867 (setq cnt (1+ cnt))
13868 (when org-highlight-sparse-tree-matches
13869 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13870 (org-show-context 'occur-tree)))))
13871 (when org-remove-highlights-with-change
13872 (add-hook 'before-change-functions 'org-remove-occur-highlights
13873 nil 'local))
13874 (unless org-sparse-tree-open-archived-trees
13875 (org-hide-archived-subtrees (point-min) (point-max)))
13876 (run-hooks 'org-occur-hook)
13877 (when (called-interactively-p 'interactive)
13878 (message "%d match(es) for regexp %s" cnt regexp))
13879 cnt))
13881 (defun org-occur-next-match (&optional n _reset)
13882 "Function for `next-error-function' to find sparse tree matches.
13883 N is the number of matches to move, when negative move backwards.
13884 This function always goes back to the starting point when no
13885 match is found."
13886 (let* ((limit (if (< n 0) (point-min) (point-max)))
13887 (search-func (if (< n 0)
13888 'previous-single-char-property-change
13889 'next-single-char-property-change))
13890 (n (abs n))
13891 (pos (point))
13893 (catch 'exit
13894 (while (setq p1 (funcall search-func (point) 'org-type))
13895 (when (equal p1 limit)
13896 (goto-char pos)
13897 (user-error "No more matches"))
13898 (when (equal (get-char-property p1 'org-type) 'org-occur)
13899 (setq n (1- n))
13900 (when (= n 0)
13901 (goto-char p1)
13902 (throw 'exit (point))))
13903 (goto-char p1))
13904 (goto-char p1)
13905 (user-error "No more matches"))))
13907 (defun org-show-context (&optional key)
13908 "Make sure point and context are visible.
13909 Optional argument KEY, when non-nil, is a symbol. See
13910 `org-show-context-detail' for allowed values and how much is to
13911 be shown."
13912 (org-show-set-visibility
13913 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13914 ((cdr (assq key org-show-context-detail)))
13915 (t (cdr (assq 'default org-show-context-detail))))))
13917 (defun org-show-set-visibility (detail)
13918 "Set visibility around point according to DETAIL.
13919 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13920 `tree', `canonical' or t. See `org-show-context-detail' for more
13921 information."
13922 ;; Show current heading and possibly its entry, following headline
13923 ;; or all children.
13924 (if (and (org-at-heading-p) (not (eq detail 'local)))
13925 (org-flag-heading nil)
13926 (org-show-entry)
13927 ;; If point is hidden within a drawer or a block, make sure to
13928 ;; expose it.
13929 (dolist (o (overlays-at (point)))
13930 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13931 (delete-overlay o)))
13932 (unless (org-before-first-heading-p)
13933 (org-with-limited-levels
13934 (cl-case detail
13935 ((tree canonical t) (org-show-children))
13936 ((nil minimal ancestors))
13937 (t (save-excursion
13938 (outline-next-heading)
13939 (org-flag-heading nil)))))))
13940 ;; Show all siblings.
13941 (when (eq detail 'lineage) (org-show-siblings))
13942 ;; Show ancestors, possibly with their children.
13943 (when (memq detail '(ancestors lineage tree canonical t))
13944 (save-excursion
13945 (while (org-up-heading-safe)
13946 (org-flag-heading nil)
13947 (when (memq detail '(canonical t)) (org-show-entry))
13948 (when (memq detail '(tree canonical t)) (org-show-children))))))
13950 (defvar org-reveal-start-hook nil
13951 "Hook run before revealing a location.")
13953 (defun org-reveal (&optional siblings)
13954 "Show current entry, hierarchy above it, and the following headline.
13956 This can be used to show a consistent set of context around
13957 locations exposed with `org-show-context'.
13959 With optional argument SIBLINGS, on each level of the hierarchy all
13960 siblings are shown. This repairs the tree structure to what it would
13961 look like when opened with hierarchical calls to `org-cycle'.
13963 With a \\[universal-argument] \\[universal-argument] prefix, \
13964 go to the parent and show the entire tree."
13965 (interactive "P")
13966 (run-hooks 'org-reveal-start-hook)
13967 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13968 ((equal siblings '(16))
13969 (save-excursion
13970 (when (org-up-heading-safe)
13971 (org-show-subtree)
13972 (run-hook-with-args 'org-cycle-hook 'subtree))))
13973 (t (org-show-set-visibility 'lineage))))
13975 (defun org-highlight-new-match (beg end)
13976 "Highlight from BEG to END and mark the highlight is an occur headline."
13977 (let ((ov (make-overlay beg end)))
13978 (overlay-put ov 'face 'secondary-selection)
13979 (overlay-put ov 'org-type 'org-occur)
13980 (push ov org-occur-highlights)))
13982 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13983 "Remove the occur highlights from the buffer.
13984 BEG and END are ignored. If NOREMOVE is nil, remove this function
13985 from the `before-change-functions' in the current buffer."
13986 (interactive)
13987 (unless org-inhibit-highlight-removal
13988 (mapc #'delete-overlay org-occur-highlights)
13989 (setq org-occur-highlights nil)
13990 (setq org-occur-parameters nil)
13991 (unless noremove
13992 (remove-hook 'before-change-functions
13993 'org-remove-occur-highlights 'local))))
13995 ;;;; Priorities
13997 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13998 "Regular expression matching the priority indicator.")
14000 (defvar org-remove-priority-next-time nil)
14002 (defun org-priority-up ()
14003 "Increase the priority of the current item."
14004 (interactive)
14005 (org-priority 'up))
14007 (defun org-priority-down ()
14008 "Decrease the priority of the current item."
14009 (interactive)
14010 (org-priority 'down))
14012 (defun org-priority (&optional action _show)
14013 "Change the priority of an item.
14014 ACTION can be `set', `up', `down', or a character."
14015 (interactive "P")
14016 (if (equal action '(4))
14017 (org-show-priority)
14018 (unless org-enable-priority-commands
14019 (user-error "Priority commands are disabled"))
14020 (setq action (or action 'set))
14021 (let (current new news have remove)
14022 (save-excursion
14023 (org-back-to-heading t)
14024 (when (looking-at org-priority-regexp)
14025 (setq current (string-to-char (match-string 2))
14026 have t))
14027 (cond
14028 ((eq action 'remove)
14029 (setq remove t new ?\ ))
14030 ((or (eq action 'set)
14031 (integerp action))
14032 (if (not (eq action 'set))
14033 (setq new action)
14034 (message "Priority %c-%c, SPC to remove: "
14035 org-highest-priority org-lowest-priority)
14036 (save-match-data
14037 (setq new (read-char-exclusive))))
14038 (when (and (= (upcase org-highest-priority) org-highest-priority)
14039 (= (upcase org-lowest-priority) org-lowest-priority))
14040 (setq new (upcase new)))
14041 (cond ((equal new ?\ ) (setq remove t))
14042 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14043 (user-error "Priority must be between `%c' and `%c'"
14044 org-highest-priority org-lowest-priority))))
14045 ((eq action 'up)
14046 (setq new (if have
14047 (1- current) ; normal cycling
14048 ;; last priority was empty
14049 (if (eq last-command this-command)
14050 org-lowest-priority ; wrap around empty to lowest
14051 ;; default
14052 (if org-priority-start-cycle-with-default
14053 org-default-priority
14054 (1- org-default-priority))))))
14055 ((eq action 'down)
14056 (setq new (if have
14057 (1+ current) ; normal cycling
14058 ;; last priority was empty
14059 (if (eq last-command this-command)
14060 org-highest-priority ; wrap around empty to highest
14061 ;; default
14062 (if org-priority-start-cycle-with-default
14063 org-default-priority
14064 (1+ org-default-priority))))))
14065 (t (user-error "Invalid action")))
14066 (when (or (< (upcase new) org-highest-priority)
14067 (> (upcase new) org-lowest-priority))
14068 (if (and (memq action '(up down))
14069 (not have) (not (eq last-command this-command)))
14070 ;; `new' is from default priority
14071 (error
14072 "The default can not be set, see `org-default-priority' why")
14073 ;; normal cycling: `new' is beyond highest/lowest priority
14074 ;; and is wrapped around to the empty priority
14075 (setq remove t)))
14076 (setq news (format "%c" new))
14077 (if have
14078 (if remove
14079 (replace-match "" t t nil 1)
14080 (replace-match news t t nil 2))
14081 (if remove
14082 (user-error "No priority cookie found in line")
14083 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14084 (if (match-end 2)
14085 (progn
14086 (goto-char (match-end 2))
14087 (insert " [#" news "]"))
14088 (goto-char (match-beginning 3))
14089 (insert "[#" news "] "))))
14090 (org-set-tags nil 'align))
14091 (if remove
14092 (message "Priority removed")
14093 (message "Priority of current item set to %s" news)))))
14095 (defun org-show-priority ()
14096 "Show the priority of the current item.
14097 This priority is composed of the main priority given with the [#A] cookies,
14098 and by additional input from the age of a schedules or deadline entry."
14099 (interactive)
14100 (let ((pri (if (eq major-mode 'org-agenda-mode)
14101 (org-get-at-bol 'priority)
14102 (save-excursion
14103 (save-match-data
14104 (beginning-of-line)
14105 (and (looking-at org-heading-regexp)
14106 (org-get-priority (match-string 0))))))))
14107 (message "Priority is %d" (if pri pri -1000))))
14109 (defun org-get-priority (s)
14110 "Find priority cookie and return priority."
14111 (save-match-data
14112 (if (functionp org-get-priority-function)
14113 (funcall org-get-priority-function)
14114 (if (not (string-match org-priority-regexp s))
14115 (* 1000 (- org-lowest-priority org-default-priority))
14116 (* 1000 (- org-lowest-priority
14117 (string-to-char (match-string 2 s))))))))
14119 ;;;; Tags
14121 (defvar org-agenda-archives-mode)
14122 (defvar org-map-continue-from nil
14123 "Position from where mapping should continue.
14124 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14126 (defvar org-scanner-tags nil
14127 "The current tag list while the tags scanner is running.")
14129 (defvar org-trust-scanner-tags nil
14130 "Should `org-get-tags-at' use the tags for the scanner.
14131 This is for internal dynamical scoping only.
14132 When this is non-nil, the function `org-get-tags-at' will return the value
14133 of `org-scanner-tags' instead of building the list by itself. This
14134 can lead to large speed-ups when the tags scanner is used in a file with
14135 many entries, and when the list of tags is retrieved, for example to
14136 obtain a list of properties. Building the tags list for each entry in such
14137 a file becomes an N^2 operation - but with this variable set, it scales
14138 as N.")
14140 (defvar org--matcher-tags-todo-only nil)
14142 (defun org-scan-tags (action matcher todo-only &optional start-level)
14143 "Scan headline tags with inheritance and produce output ACTION.
14145 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14146 or `agenda' to produce an entry list for an agenda view. It can also be
14147 a Lisp form or a function that should be called at each matched headline, in
14148 this case the return value is a list of all return values from these calls.
14150 MATCHER is a function accepting three arguments, returning
14151 a non-nil value whenever a given set of tags qualifies a headline
14152 for inclusion. See `org-make-tags-matcher' for more information.
14153 As a special case, it can also be set to t (respectively nil) in
14154 order to match all (respectively none) headline.
14156 When TODO-ONLY is non-nil, only lines with a not-done TODO
14157 keyword are included in the output.
14159 START-LEVEL can be a string with asterisks, reducing the scope to
14160 headlines matching this string."
14161 (require 'org-agenda)
14162 (let* ((re (concat "^"
14163 (if start-level
14164 ;; Get the correct level to match
14165 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14166 org-outline-regexp)
14167 " *\\(\\<\\("
14168 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14169 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14170 (props (list 'face 'default
14171 'done-face 'org-agenda-done
14172 'undone-face 'default
14173 'mouse-face 'highlight
14174 'org-not-done-regexp org-not-done-regexp
14175 'org-todo-regexp org-todo-regexp
14176 'org-complex-heading-regexp org-complex-heading-regexp
14177 'help-echo
14178 (format "mouse-2 or RET jump to org file %s"
14179 (abbreviate-file-name
14180 (or (buffer-file-name (buffer-base-buffer))
14181 (buffer-name (buffer-base-buffer)))))))
14182 (org-map-continue-from nil)
14183 lspos tags tags-list
14184 (tags-alist (list (cons 0 org-file-tags)))
14185 (llast 0) rtn rtn1 level category i txt
14186 todo marker entry priority
14187 ts-date ts-date-type ts-date-pair)
14188 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14189 (setq action (list 'lambda nil action)))
14190 (save-excursion
14191 (goto-char (point-min))
14192 (when (eq action 'sparse-tree)
14193 (org-overview)
14194 (org-remove-occur-highlights))
14195 (while (let (case-fold-search)
14196 (re-search-forward re nil t))
14197 (setq org-map-continue-from nil)
14198 (catch :skip
14199 (setq todo
14200 ;; TODO: is the 1-2 difference a bug?
14201 (when (match-end 1) (match-string-no-properties 2))
14202 tags (when (match-end 4) (match-string-no-properties 4)))
14203 (goto-char (setq lspos (match-beginning 0)))
14204 (setq level (org-reduced-level (org-outline-level))
14205 category (org-get-category))
14206 (when (eq action 'agenda)
14207 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14208 ts-date (car ts-date-pair)
14209 ts-date-type (cdr ts-date-pair)))
14210 (setq i llast llast level)
14211 ;; remove tag lists from same and sublevels
14212 (while (>= i level)
14213 (when (setq entry (assoc i tags-alist))
14214 (setq tags-alist (delete entry tags-alist)))
14215 (setq i (1- i)))
14216 ;; add the next tags
14217 (when tags
14218 (setq tags (org-split-string tags ":")
14219 tags-alist
14220 (cons (cons level tags) tags-alist)))
14221 ;; compile tags for current headline
14222 (setq tags-list
14223 (if org-use-tag-inheritance
14224 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14225 tags)
14226 org-scanner-tags tags-list)
14227 (when org-use-tag-inheritance
14228 (setcdr (car tags-alist)
14229 (mapcar (lambda (x)
14230 (setq x (copy-sequence x))
14231 (org-add-prop-inherited x))
14232 (cdar tags-alist))))
14233 (when (and tags org-use-tag-inheritance
14234 (or (not (eq t org-use-tag-inheritance))
14235 org-tags-exclude-from-inheritance))
14236 ;; Selective inheritance, remove uninherited ones.
14237 (setcdr (car tags-alist)
14238 (org-remove-uninherited-tags (cdar tags-alist))))
14239 (when (and
14241 ;; eval matcher only when the todo condition is OK
14242 (and (or (not todo-only) (member todo org-not-done-keywords))
14243 (if (functionp matcher)
14244 (let ((case-fold-search t) (org-trust-scanner-tags t))
14245 (funcall matcher todo tags-list level))
14246 matcher))
14248 ;; Call the skipper, but return t if it does not
14249 ;; skip, so that the `and' form continues evaluating.
14250 (progn
14251 (unless (eq action 'sparse-tree) (org-agenda-skip))
14254 ;; Check if timestamps are deselecting this entry
14255 (or (not todo-only)
14256 (and (member todo org-not-done-keywords)
14257 (or (not org-agenda-tags-todo-honor-ignore-options)
14258 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14260 ;; select this headline
14261 (cond
14262 ((eq action 'sparse-tree)
14263 (and org-highlight-sparse-tree-matches
14264 (org-get-heading) (match-end 0)
14265 (org-highlight-new-match
14266 (match-beginning 1) (match-end 1)))
14267 (org-show-context 'tags-tree))
14268 ((eq action 'agenda)
14269 (setq txt (org-agenda-format-item
14271 (concat
14272 (if (eq org-tags-match-list-sublevels 'indented)
14273 (make-string (1- level) ?.) "")
14274 (org-get-heading))
14275 (make-string level ?\s)
14276 category
14277 tags-list)
14278 priority (org-get-priority txt))
14279 (goto-char lspos)
14280 (setq marker (org-agenda-new-marker))
14281 (org-add-props txt props
14282 'org-marker marker 'org-hd-marker marker 'org-category category
14283 'todo-state todo
14284 'ts-date ts-date
14285 'priority priority
14286 'type (concat "tagsmatch" ts-date-type))
14287 (push txt rtn))
14288 ((functionp action)
14289 (setq org-map-continue-from nil)
14290 (save-excursion
14291 (setq rtn1 (funcall action))
14292 (push rtn1 rtn)))
14293 (t (user-error "Invalid action")))
14295 ;; if we are to skip sublevels, jump to end of subtree
14296 (unless org-tags-match-list-sublevels
14297 (org-end-of-subtree t)
14298 (backward-char 1))))
14299 ;; Get the correct position from where to continue
14300 (if org-map-continue-from
14301 (goto-char org-map-continue-from)
14302 (and (= (point) lspos) (end-of-line 1)))))
14303 (when (and (eq action 'sparse-tree)
14304 (not org-sparse-tree-open-archived-trees))
14305 (org-hide-archived-subtrees (point-min) (point-max)))
14306 (nreverse rtn)))
14308 (defun org-remove-uninherited-tags (tags)
14309 "Remove all tags that are not inherited from the list TAGS."
14310 (cond
14311 ((eq org-use-tag-inheritance t)
14312 (if org-tags-exclude-from-inheritance
14313 (org-delete-all org-tags-exclude-from-inheritance tags)
14314 tags))
14315 ((not org-use-tag-inheritance) nil)
14316 ((stringp org-use-tag-inheritance)
14317 (delq nil (mapcar
14318 (lambda (x)
14319 (if (and (string-match org-use-tag-inheritance x)
14320 (not (member x org-tags-exclude-from-inheritance)))
14321 x nil))
14322 tags)))
14323 ((listp org-use-tag-inheritance)
14324 (delq nil (mapcar
14325 (lambda (x)
14326 (if (member x org-use-tag-inheritance) x nil))
14327 tags)))))
14329 (defun org-match-sparse-tree (&optional todo-only match)
14330 "Create a sparse tree according to tags string MATCH.
14332 MATCH is a string with match syntax. It can contain a selection
14333 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14334 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14335 those. See the manual for details.
14337 If optional argument TODO-ONLY is non-nil, only select lines that
14338 are also TODO tasks."
14339 (interactive "P")
14340 (org-agenda-prepare-buffers (list (current-buffer)))
14341 (let ((org--matcher-tags-todo-only todo-only))
14342 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14343 org--matcher-tags-todo-only)))
14345 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14347 (defvar org-cached-props nil)
14348 (defun org-cached-entry-get (pom property)
14349 (if (or (eq t org-use-property-inheritance)
14350 (and (stringp org-use-property-inheritance)
14351 (let ((case-fold-search t))
14352 (string-match-p org-use-property-inheritance property)))
14353 (and (listp org-use-property-inheritance)
14354 (member-ignore-case property org-use-property-inheritance)))
14355 ;; Caching is not possible, check it directly.
14356 (org-entry-get pom property 'inherit)
14357 ;; Get all properties, so we can do complicated checks easily.
14358 (cdr (assoc-string property
14359 (or org-cached-props
14360 (setq org-cached-props (org-entry-properties pom)))
14361 t))))
14363 (defun org-global-tags-completion-table (&optional files)
14364 "Return the list of all tags in all agenda buffer/files.
14365 Optional FILES argument is a list of files which can be used
14366 instead of the agenda files."
14367 (save-excursion
14368 (org-uniquify
14369 (delq nil
14370 (apply #'append
14371 (mapcar
14372 (lambda (file)
14373 (set-buffer (find-file-noselect file))
14374 (mapcar (lambda (x)
14375 (and (stringp (car-safe x))
14376 (list (car-safe x))))
14377 (or org-current-tag-alist (org-get-buffer-tags))))
14378 (if (car-safe files) files
14379 (org-agenda-files))))))))
14381 (defun org-make-tags-matcher (match)
14382 "Create the TAGS/TODO matcher form for the selection string MATCH.
14384 Returns a cons of the selection string MATCH and a function
14385 implementing the matcher.
14387 The matcher is to be called at an Org entry, with point on the
14388 headline, and returns non-nil if the entry matches the selection
14389 string MATCH. It must be called with three arguments: the TODO
14390 keyword at the entry (or nil if none), the list of all tags at
14391 the entry including inherited ones and the reduced level of the
14392 headline. Additionally, the category of the entry, if any, must
14393 be specified as the text property `org-category' on the headline.
14395 This function sets the variable `org--matcher-tags-todo-only' to
14396 a non-nil value if the matcher restricts matching to TODO
14397 entries, otherwise it is not touched.
14399 See also `org-scan-tags'."
14400 (unless match
14401 ;; Get a new match request, with completion against the global
14402 ;; tags table and the local tags in current buffer.
14403 (let ((org-last-tags-completion-table
14404 (org-uniquify
14405 (delq nil (append (org-get-buffer-tags)
14406 (org-global-tags-completion-table))))))
14407 (setq match
14408 (completing-read
14409 "Match: "
14410 'org-tags-completion-function nil nil nil 'org-tags-history))))
14412 (let ((match0 match)
14413 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14414 (start 0)
14415 tagsmatch todomatch tagsmatcher todomatcher)
14417 ;; Expand group tags.
14418 (setq match (org-tags-expand match))
14420 ;; Check if there is a TODO part of this match, which would be the
14421 ;; part after a "/". To make sure that this slash is not part of
14422 ;; a property value to be matched against, we also check that
14423 ;; there is no / after that slash. First, find the last slash.
14424 (let ((s 0))
14425 (while (string-match "/+" match s)
14426 (setq start (match-beginning 0))
14427 (setq s (match-end 0))))
14428 (if (and (string-match "/+" match start)
14429 (not (string-match-p "\"" match start)))
14430 ;; Match contains also a TODO-matching request.
14431 (progn
14432 (setq tagsmatch (substring match 0 (match-beginning 0)))
14433 (setq todomatch (substring match (match-end 0)))
14434 (when (string-prefix-p "!" todomatch)
14435 (setq org--matcher-tags-todo-only t)
14436 (setq todomatch (substring todomatch 1)))
14437 (when (string-match "\\`\\s-*\\'" todomatch)
14438 (setq todomatch nil)))
14439 ;; Only matching tags.
14440 (setq tagsmatch match)
14441 (setq todomatch nil))
14443 ;; Make the tags matcher.
14444 (when (org-string-nw-p tagsmatch)
14445 (let ((orlist nil)
14446 (orterms (org-split-string tagsmatch "|"))
14447 term)
14448 (while (setq term (pop orterms))
14449 (while (and (equal (substring term -1) "\\") orterms)
14450 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14451 (while (string-match re term)
14452 (let* ((rest (substring term (match-end 0)))
14453 (minus (and (match-end 1)
14454 (equal (match-string 1 term) "-")))
14455 (tag (save-match-data
14456 (replace-regexp-in-string
14457 "\\\\-" "-" (match-string 2 term))))
14458 (regexp (eq (string-to-char tag) ?{))
14459 (levelp (match-end 4))
14460 (propp (match-end 5))
14462 (cond
14463 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14464 (levelp
14465 `(,(org-op-to-function (match-string 3 term))
14466 level
14467 ,(string-to-number (match-string 4 term))))
14468 (propp
14469 (let* ((gv (pcase (upcase (match-string 5 term))
14470 ("CATEGORY"
14471 '(get-text-property (point) 'org-category))
14472 ("TODO" 'todo)
14473 (p `(org-cached-entry-get nil ,p))))
14474 (pv (match-string 7 term))
14475 (regexp (eq (string-to-char pv) ?{))
14476 (strp (eq (string-to-char pv) ?\"))
14477 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14478 (po (org-op-to-function (match-string 6 term)
14479 (if timep 'time strp))))
14480 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14481 (when timep (setq pv (org-matcher-time pv)))
14482 (cond ((and regexp (eq po 'org<>))
14483 `(not (string-match ,pv (or ,gv ""))))
14484 (regexp `(string-match ,pv (or ,gv "")))
14485 (strp `(,po (or ,gv "") ,pv))
14487 `(,po
14488 (string-to-number (or ,gv ""))
14489 ,(string-to-number pv))))))
14490 (t `(member ,tag tags-list)))))
14491 (push (if minus `(not ,mm) mm) tagsmatcher)
14492 (setq term rest)))
14493 (push `(and ,@tagsmatcher) orlist)
14494 (setq tagsmatcher nil))
14495 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14497 ;; Make the TODO matcher.
14498 (when (org-string-nw-p todomatch)
14499 (let ((orlist nil))
14500 (dolist (term (org-split-string todomatch "|"))
14501 (while (string-match re term)
14502 (let* ((minus (and (match-end 1)
14503 (equal (match-string 1 term) "-")))
14504 (kwd (match-string 2 term))
14505 (regexp (eq (string-to-char kwd) ?{))
14506 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14507 `(equal todo ,kwd))))
14508 (push (if minus `(not ,mm) mm) todomatcher))
14509 (setq term (substring term (match-end 0))))
14510 (push (if (> (length todomatcher) 1)
14511 (cons 'and todomatcher)
14512 (car todomatcher))
14513 orlist)
14514 (setq todomatcher nil))
14515 (setq todomatcher (cons 'or orlist))))
14517 ;; Return the string and function of the matcher. If no
14518 ;; tags-specific or todo-specific matcher exists, match
14519 ;; everything.
14520 (let ((matcher (if (and tagsmatcher todomatcher)
14521 `(and ,tagsmatcher ,todomatcher)
14522 (or tagsmatcher todomatcher t))))
14523 (when org--matcher-tags-todo-only
14524 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14525 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14527 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14528 "Expand group tags in MATCH.
14530 This replaces every group tag in MATCH with a regexp tag search.
14531 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14532 will be replaced like this:
14534 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14535 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14536 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14538 Replacing by a regexp preserves the structure of the match.
14539 E.g., this expansion
14541 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14543 will match anything tagged with \"Lab\" and \"Home\", or tagged
14544 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14546 A group tag in MATCH can contain regular expressions of its own.
14547 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14548 will be replaced like this:
14550 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14552 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14553 assumed to be a single group tag, and the function will return
14554 the list of tags in this group.
14556 When DOWNCASE is non-nil, expand downcased TAGS."
14557 (if org-group-tags
14558 (let* ((case-fold-search t)
14559 (stable org-mode-syntax-table)
14560 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14561 (taggroups (if downcased
14562 (mapcar (lambda (tg) (mapcar #'downcase tg))
14563 taggroups)
14564 taggroups))
14565 (taggroups-keys (mapcar #'car taggroups))
14566 (return-match (if downcased (downcase match) match))
14567 (count 0)
14568 (work-already-expanded tags-already-expanded)
14569 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14570 ;; @ and _ are allowed as word-components in tags.
14571 (modify-syntax-entry ?@ "w" stable)
14572 (modify-syntax-entry ?_ "w" stable)
14573 ;; Temporarily replace regexp-expressions in the match-expression.
14574 (while (string-match "{.+?}" return-match)
14575 (cl-incf count)
14576 (push (match-string 0 return-match) regexps-in-match)
14577 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14578 (while (and taggroups-keys
14579 (with-syntax-table stable
14580 (string-match
14581 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14582 (regexp-opt taggroups-keys) "\\>\\)")
14583 return-match)))
14584 (let* ((dir (match-string 1 return-match))
14585 (tag (match-string 2 return-match))
14586 (tag (if downcased (downcase tag) tag)))
14587 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14588 (member tag work-already-expanded))
14589 (setq tags-in-group (assoc tag taggroups))
14590 (push tag work-already-expanded)
14591 ;; Recursively expand each tag in the group, if the tag hasn't
14592 ;; already been expanded. Restore the match-data after all recursive calls.
14593 (save-match-data
14594 (let (tags-expanded)
14595 (dolist (x (cdr tags-in-group))
14596 (if (and (member x taggroups-keys)
14597 (not (member x work-already-expanded)))
14598 (setq tags-expanded
14599 (delete-dups
14600 (append
14601 (org-tags-expand x t downcased
14602 work-already-expanded)
14603 tags-expanded)))
14604 (setq tags-expanded
14605 (append (list x) tags-expanded)))
14606 (setq work-already-expanded
14607 (delete-dups
14608 (append tags-expanded
14609 work-already-expanded))))
14610 (setq tags-in-group
14611 (delete-dups (cons (car tags-in-group)
14612 tags-expanded)))))
14613 ;; Filter tag-regexps from tags.
14614 (setq regexp-in-group-escaped
14615 (delq nil (mapcar (lambda (x)
14616 (if (stringp x)
14617 (and (equal "{" (substring x 0 1))
14618 (equal "}" (substring x -1))
14621 tags-in-group))
14622 regexp-in-group
14623 (mapcar (lambda (x)
14624 (substring x 1 -1))
14625 regexp-in-group-escaped)
14626 tags-in-group
14627 (delq nil (mapcar (lambda (x)
14628 (if (stringp x)
14629 (and (not (equal "{" (substring x 0 1)))
14630 (not (equal "}" (substring x -1)))
14633 tags-in-group)))
14634 ;; If single-as-list, do no more in the while-loop.
14635 (if (not single-as-list)
14636 (progn
14637 (when regexp-in-group
14638 (setq regexp-in-group
14639 (concat "\\|"
14640 (mapconcat 'identity regexp-in-group
14641 "\\|"))))
14642 (setq tags-in-group
14643 (concat dir
14644 "{\\<"
14645 (regexp-opt tags-in-group)
14646 "\\>"
14647 regexp-in-group
14648 "}"))
14649 (when (stringp tags-in-group)
14650 (org-add-props tags-in-group '(grouptag t)))
14651 (setq return-match
14652 (replace-match tags-in-group t t return-match)))
14653 (setq tags-in-group
14654 (append regexp-in-group-escaped tags-in-group))))
14655 (setq taggroups-keys (delete tag taggroups-keys))))
14656 ;; Add the regular expressions back into the match-expression again.
14657 (while regexps-in-match
14658 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14659 (pop regexps-in-match)
14660 return-match t t))
14661 (cl-decf count))
14662 (if single-as-list
14663 (if tags-in-group tags-in-group (list return-match))
14664 return-match))
14665 (if single-as-list
14666 (list (if downcased (downcase match) match))
14667 match)))
14669 (defun org-op-to-function (op &optional stringp)
14670 "Turn an operator into the appropriate function."
14671 (setq op
14672 (cond
14673 ((equal op "<" ) '(< string< org-time<))
14674 ((equal op ">" ) '(> org-string> org-time>))
14675 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14676 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14677 ((member op '("=" "==")) '(= string= org-time=))
14678 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14679 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14681 (defun org<> (a b) (not (= a b)))
14682 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14683 (defun org-string>= (a b) (not (string< a b)))
14684 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14685 (defun org-string<> (a b) (not (string= a b)))
14686 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14687 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14688 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14689 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14690 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14691 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14692 (defun org-2ft (s)
14693 "Convert S to a floating point time.
14694 If S is already a number, just return it. If it is a string, parse
14695 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14696 (cond
14697 ((numberp s) s)
14698 ((stringp s)
14699 (condition-case nil
14700 (float-time (apply 'encode-time (org-parse-time-string s)))
14701 (error 0.)))
14702 (t 0.)))
14704 (defun org-time-today ()
14705 "Time in seconds today at 0:00.
14706 Returns the float number of seconds since the beginning of the
14707 epoch to the beginning of today (00:00)."
14708 (float-time (apply 'encode-time
14709 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14711 (defun org-matcher-time (s)
14712 "Interpret a time comparison value."
14713 (save-match-data
14714 (cond
14715 ((string= s "<now>") (float-time))
14716 ((string= s "<today>") (org-time-today))
14717 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14718 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14719 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14720 (+ (org-time-today)
14721 (* (string-to-number (match-string 1 s))
14722 (cdr (assoc (match-string 2 s)
14723 '(("d" . 86400.0) ("w" . 604800.0)
14724 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14725 (t (org-2ft s)))))
14727 (defun org-match-any-p (re list)
14728 "Does re match any element of list?"
14729 (setq list (mapcar (lambda (x) (string-match re x)) list))
14730 (delq nil list))
14732 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14733 (defvar org-tags-overlay (make-overlay 1 1))
14734 (delete-overlay org-tags-overlay)
14736 (defun org-get-local-tags-at (&optional pos)
14737 "Get a list of tags defined in the current headline."
14738 (org-get-tags-at pos 'local))
14740 (defun org-get-local-tags ()
14741 "Get a list of tags defined in the current headline."
14742 (org-get-tags-at nil 'local))
14744 (defun org-get-tags-at (&optional pos local)
14745 "Get a list of all headline tags applicable at POS.
14746 POS defaults to point. If tags are inherited, the list contains
14747 the targets in the same sequence as the headlines appear, i.e.
14748 the tags of the current headline come last.
14749 When LOCAL is non-nil, only return tags from the current headline,
14750 ignore inherited ones."
14751 (interactive)
14752 (if (and org-trust-scanner-tags
14753 (or (not pos) (equal pos (point)))
14754 (not local))
14755 org-scanner-tags
14756 (let (tags ltags lastpos parent)
14757 (save-excursion
14758 (save-restriction
14759 (widen)
14760 (goto-char (or pos (point)))
14761 (save-match-data
14762 (catch 'done
14763 (condition-case nil
14764 (progn
14765 (org-back-to-heading t)
14766 (while (not (equal lastpos (point)))
14767 (setq lastpos (point))
14768 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14769 (setq ltags (org-split-string
14770 (match-string-no-properties 1) ":"))
14771 (when parent
14772 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14773 (setq tags (append
14774 (if parent
14775 (org-remove-uninherited-tags ltags)
14776 ltags)
14777 tags)))
14778 (or org-use-tag-inheritance (throw 'done t))
14779 (when local (throw 'done t))
14780 (or (org-up-heading-safe) (error nil))
14781 (setq parent t)))
14782 (error nil)))))
14783 (if local
14784 tags
14785 (reverse (delete-dups
14786 (reverse (append
14787 (org-remove-uninherited-tags
14788 org-file-tags)
14789 tags)))))))))
14791 (defun org-add-prop-inherited (s)
14792 (add-text-properties 0 (length s) '(inherited t) s)
14795 (defun org-toggle-tag (tag &optional onoff)
14796 "Toggle the tag TAG for the current line.
14797 If ONOFF is `on' or `off', don't toggle but set to this state."
14798 (let (res current)
14799 (save-excursion
14800 (org-back-to-heading t)
14801 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14802 (point-at-eol) t)
14803 (progn
14804 (setq current (match-string 1))
14805 (replace-match ""))
14806 (setq current ""))
14807 (setq current (nreverse (org-split-string current ":")))
14808 (cond
14809 ((eq onoff 'on)
14810 (setq res t)
14811 (or (member tag current) (push tag current)))
14812 ((eq onoff 'off)
14813 (or (not (member tag current)) (setq current (delete tag current))))
14814 (t (if (member tag current)
14815 (setq current (delete tag current))
14816 (setq res t)
14817 (push tag current))))
14818 (end-of-line 1)
14819 (if current
14820 (progn
14821 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14822 (org-set-tags nil t))
14823 (delete-horizontal-space))
14824 (run-hooks 'org-after-tags-change-hook))
14825 res))
14827 (defun org--align-tags-here (to-col)
14828 "Align tags on the current headline to TO-COL.
14829 Assume point is on a headline."
14830 (let ((pos (point)))
14831 (beginning-of-line)
14832 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14833 (>= pos (match-beginning 2)))
14834 ;; No tags or point within tags: do not align.
14835 (goto-char pos)
14836 (goto-char (match-beginning 1))
14837 (let ((shift (max (- (if (>= to-col 0) to-col
14838 (- (abs to-col) (string-width (match-string 2))))
14839 (current-column))
14840 1)))
14841 (replace-match (make-string shift ?\s) nil nil nil 1)
14842 ;; Preserve initial position, if possible. In any case, stop
14843 ;; before tags.
14844 (when (< pos (point)) (goto-char pos))))))
14846 (defun org-set-tags-command (&optional arg just-align)
14847 "Call the set-tags command for the current entry."
14848 (interactive "P")
14849 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14850 (org-set-tags arg just-align)
14851 (save-excursion
14852 (unless (and (org-region-active-p)
14853 org-loop-over-headlines-in-active-region)
14854 (org-back-to-heading t))
14855 (org-set-tags arg just-align))))
14857 (defun org-set-tags-to (data)
14858 "Set the tags of the current entry to DATA, replacing the current tags.
14859 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14860 If DATA is nil or the empty string, any tags will be removed."
14861 (interactive "sTags: ")
14862 (setq data
14863 (cond
14864 ((eq data nil) "")
14865 ((equal data "") "")
14866 ((stringp data)
14867 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14868 ":"))
14869 ((listp data)
14870 (concat ":" (mapconcat 'identity data ":") ":"))))
14871 (when data
14872 (save-excursion
14873 (org-back-to-heading t)
14874 (when (let ((case-fold-search nil))
14875 (looking-at org-complex-heading-regexp))
14876 (if (match-end 5)
14877 (progn
14878 (goto-char (match-beginning 5))
14879 (insert data)
14880 (delete-region (point) (point-at-eol))
14881 (org-set-tags nil 'align))
14882 (goto-char (point-at-eol))
14883 (insert " " data)
14884 (org-set-tags nil 'align)))
14885 (beginning-of-line 1)
14886 (when (looking-at ".*?\\([ \t]+\\)$")
14887 (delete-region (match-beginning 1) (match-end 1))))))
14889 (defun org-align-all-tags ()
14890 "Align the tags in all headings."
14891 (interactive)
14892 (save-excursion
14893 (or (ignore-errors (org-back-to-heading t))
14894 (outline-next-heading))
14895 (if (org-at-heading-p)
14896 (org-set-tags t)
14897 (message "No headings"))))
14899 (defvar org-indent-indentation-per-level)
14900 (defun org-set-tags (&optional arg just-align)
14901 "Set the tags for the current headline.
14902 With prefix ARG, realign all tags in headings in the current buffer.
14903 When JUST-ALIGN is non-nil, only align tags."
14904 (interactive "P")
14905 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14906 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14907 'region-start-level
14908 'region))
14909 org-loop-over-headlines-in-active-region)
14910 (org-map-entries
14911 ;; We don't use ARG and JUST-ALIGN here because these args
14912 ;; are not useful when looping over headlines.
14913 #'org-set-tags
14914 org-loop-over-headlines-in-active-region
14916 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14917 (let ((org-setting-tags t))
14918 (if arg
14919 (save-excursion
14920 (goto-char (point-min))
14921 (while (re-search-forward org-outline-regexp-bol nil t)
14922 (org-set-tags nil t)
14923 (end-of-line))
14924 (message "All tags realigned to column %d" org-tags-column))
14925 (let* ((current (org-get-tags-string))
14926 (tags
14927 (if just-align current
14928 ;; Get a new set of tags from the user.
14929 (save-excursion
14930 (let* ((seen)
14931 (table
14932 (setq
14933 org-last-tags-completion-table
14934 ;; Uniquify tags in alists, yet preserve
14935 ;; structure (i.e., keywords).
14936 (delq nil
14937 (mapcar
14938 (lambda (pair)
14939 (let ((head (car pair)))
14940 (cond ((symbolp head) pair)
14941 ((member head seen) nil)
14942 (t (push head seen)
14943 pair))))
14944 (append
14945 (or org-current-tag-alist
14946 (org-get-buffer-tags))
14947 (and
14948 org-complete-tags-always-offer-all-agenda-tags
14949 (org-global-tags-completion-table
14950 (org-agenda-files))))))))
14951 (current-tags (org-split-string current ":"))
14952 (inherited-tags
14953 (nreverse (nthcdr (length current-tags)
14954 (nreverse (org-get-tags-at))))))
14955 (replace-regexp-in-string
14956 "\\([-+&]+\\|,\\)"
14958 (if (or (eq t org-use-fast-tag-selection)
14959 (and org-use-fast-tag-selection
14960 (delq nil (mapcar #'cdr table))))
14961 (org-fast-tag-selection
14962 current-tags inherited-tags table
14963 (and org-fast-tag-selection-include-todo
14964 org-todo-key-alist))
14965 (let ((org-add-colon-after-tag-completion
14966 (< 1 (length table))))
14967 (org-trim
14968 (completing-read
14969 "Tags: "
14970 #'org-tags-completion-function
14971 nil nil current 'org-tags-history))))))))))
14973 (when org-tags-sort-function
14974 (setq tags
14975 (mapconcat
14976 #'identity
14977 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14978 org-tags-sort-function)
14979 ":")))
14981 (if (or (string= ":" tags)
14982 (string= "::" tags))
14983 (setq tags ""))
14984 (if (not (org-string-nw-p tags)) (setq tags "")
14985 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14986 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14988 ;; Insert new tags at the correct column.
14989 (unless (equal current tags)
14990 (save-excursion
14991 (beginning-of-line)
14992 (let ((case-fold-search nil))
14993 (looking-at org-complex-heading-regexp))
14994 ;; Remove current tags, if any.
14995 (when (match-end 5) (replace-match "" nil nil nil 5))
14996 ;; Insert new tags, if any. Otherwise, remove trailing
14997 ;; white spaces.
14998 (end-of-line)
14999 (if (not (equal tags ""))
15000 ;; When text is being inserted on an invisible
15001 ;; region boundary, it can be inadvertently sucked
15002 ;; into invisibility.
15003 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15004 (skip-chars-backward " \t")
15005 (delete-region (point) (line-end-position)))))
15006 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15007 ;; is on.
15008 (unless (equal tags "")
15009 (let* ((level (save-excursion
15010 (beginning-of-line)
15011 (skip-chars-forward "\\*")))
15012 (offset (if (bound-and-true-p org-indent-mode)
15013 (* (1- org-indent-indentation-per-level)
15014 (1- level))
15016 (tags-column
15017 (+ org-tags-column
15018 (if (> org-tags-column 0) (- offset) offset))))
15019 (org--align-tags-here tags-column))))
15020 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15022 (defun org-change-tag-in-region (beg end tag off)
15023 "Add or remove TAG for each entry in the region.
15024 This works in the agenda, and also in an Org buffer."
15025 (interactive
15026 (list (region-beginning) (region-end)
15027 (let ((org-last-tags-completion-table
15028 (if (derived-mode-p 'org-mode)
15029 (org-uniquify
15030 (delq nil (append (org-get-buffer-tags)
15031 (org-global-tags-completion-table))))
15032 (org-global-tags-completion-table))))
15033 (completing-read
15034 "Tag: " 'org-tags-completion-function nil nil nil
15035 'org-tags-history))
15036 (progn
15037 (message "[s]et or [r]emove? ")
15038 (equal (read-char-exclusive) ?r))))
15039 (when (fboundp 'deactivate-mark) (deactivate-mark))
15040 (let ((agendap (equal major-mode 'org-agenda-mode))
15041 l1 l2 m buf pos newhead (cnt 0))
15042 (goto-char end)
15043 (setq l2 (1- (org-current-line)))
15044 (goto-char beg)
15045 (setq l1 (org-current-line))
15046 (cl-loop for l from l1 to l2 do
15047 (org-goto-line l)
15048 (setq m (get-text-property (point) 'org-hd-marker))
15049 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15050 (and agendap m))
15051 (setq buf (if agendap (marker-buffer m) (current-buffer))
15052 pos (if agendap m (point)))
15053 (with-current-buffer buf
15054 (save-excursion
15055 (save-restriction
15056 (goto-char pos)
15057 (setq cnt (1+ cnt))
15058 (org-toggle-tag tag (if off 'off 'on))
15059 (setq newhead (org-get-heading)))))
15060 (and agendap (org-agenda-change-all-lines newhead m))))
15061 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15063 (defun org-tags-completion-function (string _predicate &optional flag)
15064 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15065 (confirm (lambda (x) (stringp (car x)))))
15066 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15067 (setq s1 (match-string 1 string)
15068 s2 (match-string 2 string))
15069 (setq s1 "" s2 string))
15070 (cond
15071 ((eq flag nil)
15072 ;; try completion
15073 (setq rtn (try-completion s2 ctable confirm))
15074 (when (stringp rtn)
15075 (setq rtn
15076 (concat s1 s2 (substring rtn (length s2))
15077 (if (and org-add-colon-after-tag-completion
15078 (assoc rtn ctable))
15079 ":" ""))))
15080 rtn)
15081 ((eq flag t)
15082 ;; all-completions
15083 (all-completions s2 ctable confirm))
15084 ((eq flag 'lambda)
15085 ;; exact match?
15086 (assoc s2 ctable)))))
15088 (defun org-fast-tag-insert (kwd tags face &optional end)
15089 "Insert KDW, and the TAGS, the latter with face FACE.
15090 Also insert END."
15091 (insert (format "%-12s" (concat kwd ":"))
15092 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15093 (or end "")))
15095 (defun org-fast-tag-show-exit (flag)
15096 (save-excursion
15097 (org-goto-line 3)
15098 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15099 (replace-match ""))
15100 (when flag
15101 (end-of-line 1)
15102 (org-move-to-column (- (window-width) 19) t)
15103 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15105 (defun org-set-current-tags-overlay (current prefix)
15106 "Add an overlay to CURRENT tag with PREFIX."
15107 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15108 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15109 (org-overlay-display org-tags-overlay (concat prefix s))))
15111 (defvar org-last-tag-selection-key nil)
15112 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15113 "Fast tag selection with single keys.
15114 CURRENT is the current list of tags in the headline, INHERITED is the
15115 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15116 possibly with grouping information. TODO-TABLE is a similar table with
15117 TODO keywords, should these have keys assigned to them.
15118 If the keys are nil, a-z are automatically assigned.
15119 Returns the new tags string, or nil to not change the current settings."
15120 (let* ((fulltable (append table todo-table))
15121 (maxlen (apply 'max (mapcar
15122 (lambda (x)
15123 (if (stringp (car x)) (string-width (car x)) 0))
15124 fulltable)))
15125 (buf (current-buffer))
15126 (expert (eq org-fast-tag-selection-single-key 'expert))
15127 (buffer-tags nil)
15128 (fwidth (+ maxlen 3 1 3))
15129 (ncol (/ (- (window-width) 4) fwidth))
15130 (i-face 'org-done)
15131 (c-face 'org-todo)
15132 tg cnt e c char c1 c2 ntable tbl rtn
15133 ov-start ov-end ov-prefix
15134 (exit-after-next org-fast-tag-selection-single-key)
15135 (done-keywords org-done-keywords)
15136 groups ingroup intaggroup)
15137 (save-excursion
15138 (beginning-of-line 1)
15139 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15140 (setq ov-start (match-beginning 1)
15141 ov-end (match-end 1)
15142 ov-prefix "")
15143 (setq ov-start (1- (point-at-eol))
15144 ov-end (1+ ov-start))
15145 (skip-chars-forward "^\n\r")
15146 (setq ov-prefix
15147 (concat
15148 (buffer-substring (1- (point)) (point))
15149 (if (> (current-column) org-tags-column)
15151 (make-string (- org-tags-column (current-column)) ?\ ))))))
15152 (move-overlay org-tags-overlay ov-start ov-end)
15153 (save-window-excursion
15154 (if expert
15155 (set-buffer (get-buffer-create " *Org tags*"))
15156 (delete-other-windows)
15157 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15158 (org-switch-to-buffer-other-window " *Org tags*"))
15159 (erase-buffer)
15160 (setq-local org-done-keywords done-keywords)
15161 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15162 (org-fast-tag-insert "Current" current c-face "\n\n")
15163 (org-fast-tag-show-exit exit-after-next)
15164 (org-set-current-tags-overlay current ov-prefix)
15165 (setq tbl fulltable char ?a cnt 0)
15166 (while (setq e (pop tbl))
15167 (cond
15168 ((eq (car e) :startgroup)
15169 (push '() groups) (setq ingroup t)
15170 (unless (zerop cnt)
15171 (setq cnt 0)
15172 (insert "\n"))
15173 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15174 ((eq (car e) :endgroup)
15175 (setq ingroup nil cnt 0)
15176 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15177 ((eq (car e) :startgrouptag)
15178 (setq intaggroup t)
15179 (unless (zerop cnt)
15180 (setq cnt 0)
15181 (insert "\n"))
15182 (insert "[ "))
15183 ((eq (car e) :endgrouptag)
15184 (setq intaggroup nil cnt 0)
15185 (insert "]\n"))
15186 ((equal e '(:newline))
15187 (unless (zerop cnt)
15188 (setq cnt 0)
15189 (insert "\n")
15190 (setq e (car tbl))
15191 (while (equal (car tbl) '(:newline))
15192 (insert "\n")
15193 (setq tbl (cdr tbl)))))
15194 ((equal e '(:grouptags)) (insert " : "))
15196 (setq tg (copy-sequence (car e)) c2 nil)
15197 (if (cdr e)
15198 (setq c (cdr e))
15199 ;; automatically assign a character.
15200 (setq c1 (string-to-char
15201 (downcase (substring
15202 tg (if (= (string-to-char tg) ?@) 1 0)))))
15203 (if (or (rassoc c1 ntable) (rassoc c1 table))
15204 (while (or (rassoc char ntable) (rassoc char table))
15205 (setq char (1+ char)))
15206 (setq c2 c1))
15207 (setq c (or c2 char)))
15208 (when ingroup (push tg (car groups)))
15209 (setq tg (org-add-props tg nil 'face
15210 (cond
15211 ((not (assoc tg table))
15212 (org-get-todo-face tg))
15213 ((member tg current) c-face)
15214 ((member tg inherited) i-face))))
15215 (when (equal (caar tbl) :grouptags)
15216 (org-add-props tg nil 'face 'org-tag-group))
15217 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15218 (insert "[" c "] " tg (make-string
15219 (- fwidth 4 (length tg)) ?\ ))
15220 (push (cons tg c) ntable)
15221 (when (= (cl-incf cnt) ncol)
15222 (insert "\n")
15223 (when (or ingroup intaggroup) (insert " "))
15224 (setq cnt 0)))))
15225 (setq ntable (nreverse ntable))
15226 (insert "\n")
15227 (goto-char (point-min))
15228 (unless expert (org-fit-window-to-buffer))
15229 (setq rtn
15230 (catch 'exit
15231 (while t
15232 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15233 (if (not groups) "no " "")
15234 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15235 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15236 (setq org-last-tag-selection-key c)
15237 (cond
15238 ((= c ?\r) (throw 'exit t))
15239 ((= c ?!)
15240 (setq groups (not groups))
15241 (goto-char (point-min))
15242 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15243 ((= c ?\C-c)
15244 (if (not expert)
15245 (org-fast-tag-show-exit
15246 (setq exit-after-next (not exit-after-next)))
15247 (setq expert nil)
15248 (delete-other-windows)
15249 (set-window-buffer (split-window-vertically) " *Org tags*")
15250 (org-switch-to-buffer-other-window " *Org tags*")
15251 (org-fit-window-to-buffer)))
15252 ((or (= c ?\C-g)
15253 (and (= c ?q) (not (rassoc c ntable))))
15254 (delete-overlay org-tags-overlay)
15255 (setq quit-flag t))
15256 ((= c ?\ )
15257 (setq current nil)
15258 (when exit-after-next (setq exit-after-next 'now)))
15259 ((= c ?\t)
15260 (condition-case nil
15261 (setq tg (completing-read
15262 "Tag: "
15263 (or buffer-tags
15264 (with-current-buffer buf
15265 (setq buffer-tags
15266 (org-get-buffer-tags))))))
15267 (quit (setq tg "")))
15268 (when (string-match "\\S-" tg)
15269 (cl-pushnew (list tg) buffer-tags :test #'equal)
15270 (if (member tg current)
15271 (setq current (delete tg current))
15272 (push tg current)))
15273 (when exit-after-next (setq exit-after-next 'now)))
15274 ((setq e (rassoc c todo-table) tg (car e))
15275 (with-current-buffer buf
15276 (save-excursion (org-todo tg)))
15277 (when exit-after-next (setq exit-after-next 'now)))
15278 ((setq e (rassoc c ntable) tg (car e))
15279 (if (member tg current)
15280 (setq current (delete tg current))
15281 (cl-loop for g in groups do
15282 (when (member tg g)
15283 (dolist (x g) (setq current (delete x current)))))
15284 (push tg current))
15285 (when exit-after-next (setq exit-after-next 'now))))
15287 ;; Create a sorted list
15288 (setq current
15289 (sort current
15290 (lambda (a b)
15291 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15292 (when (eq exit-after-next 'now) (throw 'exit t))
15293 (goto-char (point-min))
15294 (beginning-of-line 2)
15295 (delete-region (point) (point-at-eol))
15296 (org-fast-tag-insert "Current" current c-face)
15297 (org-set-current-tags-overlay current ov-prefix)
15298 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15299 (setq tg (match-string 1))
15300 (add-text-properties
15301 (match-beginning 1) (match-end 1)
15302 (list 'face
15303 (cond
15304 ((member tg current) c-face)
15305 ((member tg inherited) i-face)
15306 (t (get-text-property (match-beginning 1) 'face))))))
15307 (goto-char (point-min)))))
15308 (delete-overlay org-tags-overlay)
15309 (if rtn
15310 (mapconcat 'identity current ":")
15311 nil))))
15313 (defun org-get-tags-string ()
15314 "Get the TAGS string in the current headline."
15315 (unless (org-at-heading-p t)
15316 (user-error "Not on a heading"))
15317 (save-excursion
15318 (beginning-of-line 1)
15319 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15320 (match-string-no-properties 1)
15321 "")))
15323 (defun org-get-tags ()
15324 "Get the list of tags specified in the current headline."
15325 (org-split-string (org-get-tags-string) ":"))
15327 (defun org-get-buffer-tags ()
15328 "Get a table of all tags used in the buffer, for completion."
15329 (org-with-wide-buffer
15330 (goto-char (point-min))
15331 (let ((tag-re (concat org-outline-regexp-bol
15332 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15333 tags)
15334 (while (re-search-forward tag-re nil t)
15335 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15336 (push tag tags)))
15337 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15339 ;;;; The mapping API
15341 (defvar org-agenda-skip-comment-trees)
15342 (defvar org-agenda-skip-function)
15343 (defun org-map-entries (func &optional match scope &rest skip)
15344 "Call FUNC at each headline selected by MATCH in SCOPE.
15346 FUNC is a function or a lisp form. The function will be called without
15347 arguments, with the cursor positioned at the beginning of the headline.
15348 The return values of all calls to the function will be collected and
15349 returned as a list.
15351 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15352 does not need to preserve point. After evaluation, the cursor will be
15353 moved to the end of the line (presumably of the headline of the
15354 processed entry) and search continues from there. Under some
15355 circumstances, this may not produce the wanted results. For example,
15356 if you have removed (e.g. archived) the current (sub)tree it could
15357 mean that the next entry will be skipped entirely. In such cases, you
15358 can specify the position from where search should continue by making
15359 FUNC set the variable `org-map-continue-from' to the desired buffer
15360 position.
15362 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15363 Only headlines that are matched by this query will be considered during
15364 the iteration. When MATCH is nil or t, all headlines will be
15365 visited by the iteration.
15367 SCOPE determines the scope of this command. It can be any of:
15369 nil The current buffer, respecting the restriction if any
15370 tree The subtree started with the entry at point
15371 region The entries within the active region, if any
15372 region-start-level
15373 The entries within the active region, but only those at
15374 the same level than the first one.
15375 file The current buffer, without restriction
15376 file-with-archives
15377 The current buffer, and any archives associated with it
15378 agenda All agenda files
15379 agenda-with-archives
15380 All agenda files with any archive files associated with them
15381 \(file1 file2 ...)
15382 If this is a list, all files in the list will be scanned
15384 The remaining args are treated as settings for the skipping facilities of
15385 the scanner. The following items can be given here:
15387 archive skip trees with the archive tag
15388 comment skip trees with the COMMENT keyword
15389 function or Emacs Lisp form:
15390 will be used as value for `org-agenda-skip-function', so
15391 whenever the function returns a position, FUNC will not be
15392 called for that entry and search will continue from the
15393 position returned
15395 If your function needs to retrieve the tags including inherited tags
15396 at the *current* entry, you can use the value of the variable
15397 `org-scanner-tags' which will be much faster than getting the value
15398 with `org-get-tags-at'. If your function gets properties with
15399 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15400 to t around the call to `org-entry-properties' to get the same speedup.
15401 Note that if your function moves around to retrieve tags and properties at
15402 a *different* entry, you cannot use these techniques."
15403 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15404 (not (org-region-active-p)))
15405 (let* ((org-agenda-archives-mode nil) ; just to make sure
15406 (org-agenda-skip-archived-trees (memq 'archive skip))
15407 (org-agenda-skip-comment-trees (memq 'comment skip))
15408 (org-agenda-skip-function
15409 (car (org-delete-all '(comment archive) skip)))
15410 (org-tags-match-list-sublevels t)
15411 (start-level (eq scope 'region-start-level))
15412 matcher res
15413 org-todo-keywords-for-agenda
15414 org-done-keywords-for-agenda
15415 org-todo-keyword-alist-for-agenda
15416 org-tag-alist-for-agenda
15417 org--matcher-tags-todo-only)
15419 (cond
15420 ((eq match t) (setq matcher t))
15421 ((eq match nil) (setq matcher t))
15422 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15424 (save-excursion
15425 (save-restriction
15426 (cond ((eq scope 'tree)
15427 (org-back-to-heading t)
15428 (org-narrow-to-subtree)
15429 (setq scope nil))
15430 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15431 (org-region-active-p))
15432 ;; If needed, set start-level to a string like "2"
15433 (when start-level
15434 (save-excursion
15435 (goto-char (region-beginning))
15436 (unless (org-at-heading-p) (outline-next-heading))
15437 (setq start-level (org-current-level))))
15438 (narrow-to-region (region-beginning)
15439 (save-excursion
15440 (goto-char (region-end))
15441 (unless (and (bolp) (org-at-heading-p))
15442 (outline-next-heading))
15443 (point)))
15444 (setq scope nil)))
15446 (if (not scope)
15447 (progn
15448 (org-agenda-prepare-buffers
15449 (and buffer-file-name (list buffer-file-name)))
15450 (setq res
15451 (org-scan-tags
15452 func matcher org--matcher-tags-todo-only start-level)))
15453 ;; Get the right scope
15454 (cond
15455 ((and scope (listp scope) (symbolp (car scope)))
15456 (setq scope (eval scope)))
15457 ((eq scope 'agenda)
15458 (setq scope (org-agenda-files t)))
15459 ((eq scope 'agenda-with-archives)
15460 (setq scope (org-agenda-files t))
15461 (setq scope (org-add-archive-files scope)))
15462 ((eq scope 'file)
15463 (setq scope (and buffer-file-name (list buffer-file-name))))
15464 ((eq scope 'file-with-archives)
15465 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15466 (org-agenda-prepare-buffers scope)
15467 (dolist (file scope)
15468 (with-current-buffer (org-find-base-buffer-visiting file)
15469 (org-with-wide-buffer
15470 (goto-char (point-min))
15471 (setq res
15472 (append
15474 (org-scan-tags
15475 func matcher org--matcher-tags-todo-only)))))))))
15476 res)))
15478 ;;; Properties API
15480 (defconst org-special-properties
15481 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15482 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15483 "The special properties valid in Org mode.
15484 These are properties that are not defined in the property drawer,
15485 but in some other way.")
15487 (defconst org-default-properties
15488 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15489 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15490 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15491 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15492 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15493 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15494 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15495 "Some properties that are used by Org mode for various purposes.
15496 Being in this list makes sure that they are offered for completion.")
15498 (defun org--valid-property-p (property)
15499 "Non nil when string PROPERTY is a valid property name."
15500 (not
15501 (or (equal property "")
15502 (string-match-p "\\s-" property))))
15504 (defun org--update-property-plist (key val props)
15505 "Associate KEY to VAL in alist PROPS.
15506 Modifications are made by side-effect. Return new alist."
15507 (let* ((appending (string= (substring key -1) "+"))
15508 (key (if appending (substring key 0 -1) key))
15509 (old (assoc-string key props t)))
15510 (if (not old) (cons (cons key val) props)
15511 (setcdr old (if appending (concat (cdr old) " " val) val))
15512 props)))
15514 (defun org-get-property-block (&optional beg force)
15515 "Return the (beg . end) range of the body of the property drawer.
15516 BEG is the beginning of the current subtree, or of the part
15517 before the first headline. If it is not given, it will be found.
15518 If the drawer does not exist, create it if FORCE is non-nil, or
15519 return nil."
15520 (org-with-wide-buffer
15521 (when beg (goto-char beg))
15522 (unless (org-before-first-heading-p)
15523 (let ((beg (cond (beg)
15524 ((or (not (featurep 'org-inlinetask))
15525 (org-inlinetask-in-task-p))
15526 (org-back-to-heading t))
15527 (t (org-with-limited-levels (org-back-to-heading t))))))
15528 (forward-line)
15529 (when (looking-at-p org-planning-line-re) (forward-line))
15530 (cond ((looking-at org-property-drawer-re)
15531 (forward-line)
15532 (cons (point) (progn (goto-char (match-end 0))
15533 (line-beginning-position))))
15534 (force
15535 (goto-char beg)
15536 (org-insert-property-drawer)
15537 (let ((pos (save-excursion (search-forward ":END:")
15538 (line-beginning-position))))
15539 (cons pos pos))))))))
15541 (defun org-at-property-p ()
15542 "Non-nil when point is inside a property drawer.
15543 See `org-property-re' for match data, if applicable."
15544 (save-excursion
15545 (beginning-of-line)
15546 (and (looking-at org-property-re)
15547 (let ((property-drawer (save-match-data (org-get-property-block))))
15548 (and property-drawer
15549 (>= (point) (car property-drawer))
15550 (< (point) (cdr property-drawer)))))))
15552 (defun org-property-action ()
15553 "Do an action on properties."
15554 (interactive)
15555 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15556 (let ((c (read-char-exclusive)))
15557 (cl-case c
15558 (?s (call-interactively #'org-set-property))
15559 (?d (call-interactively #'org-delete-property))
15560 (?D (call-interactively #'org-delete-property-globally))
15561 (?c (call-interactively #'org-compute-property-at-point))
15562 (otherwise (user-error "No such property action %c" c)))))
15564 (defun org-inc-effort ()
15565 "Increment the value of the effort property in the current entry."
15566 (interactive)
15567 (org-set-effort nil t))
15569 (defvar org-clock-effort) ; Defined in org-clock.el.
15570 (defvar org-clock-current-task) ; Defined in org-clock.el.
15571 (defun org-set-effort (&optional value increment)
15572 "Set the effort property of the current entry.
15573 With numerical prefix arg, use the nth allowed value, 0 stands for the
15574 10th allowed value.
15576 When INCREMENT is non-nil, set the property to the next allowed value."
15577 (interactive "P")
15578 (when (equal value 0) (setq value 10))
15579 (let* ((completion-ignore-case t)
15580 (prop org-effort-property)
15581 (cur (org-entry-get nil prop))
15582 (allowed (org-property-get-allowed-values nil prop 'table))
15583 (existing (mapcar 'list (org-property-values prop)))
15584 (heading (nth 4 (org-heading-components)))
15586 (val (cond
15587 ((stringp value) value)
15588 ((and allowed (integerp value))
15589 (or (car (nth (1- value) allowed))
15590 (car (org-last allowed))))
15591 ((and allowed increment)
15592 (or (cl-caadr (member (list cur) allowed))
15593 (user-error "Allowed effort values are not set")))
15594 (allowed
15595 (message "Select 1-9,0, [RET%s]: %s"
15596 (if cur (concat "=" cur) "")
15597 (mapconcat 'car allowed " "))
15598 (setq rpl (read-char-exclusive))
15599 (if (equal rpl ?\r)
15601 (setq rpl (- rpl ?0))
15602 (when (equal rpl 0) (setq rpl 10))
15603 (if (and (> rpl 0) (<= rpl (length allowed)))
15604 (car (nth (1- rpl) allowed))
15605 (org-completing-read "Effort: " allowed nil))))
15607 (org-completing-read
15608 (concat "Effort" (and cur (string-match "\\S-" cur)
15609 (concat " [" cur "]"))
15610 ": ")
15611 existing nil nil "" nil cur)))))
15612 (unless (equal (org-entry-get nil prop) val)
15613 (org-entry-put nil prop val))
15614 (org-refresh-property
15615 '((effort . identity)
15616 (effort-minutes . org-duration-to-minutes))
15617 val)
15618 (when (equal heading (bound-and-true-p org-clock-current-task))
15619 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15620 (org-clock-update-mode-line))
15621 (message "%s is now %s" prop val)))
15623 (defun org-entry-properties (&optional pom which)
15624 "Get all properties of the current entry.
15626 When POM is a buffer position, get all properties from the entry
15627 there instead.
15629 This includes the TODO keyword, the tags, time strings for
15630 deadline, scheduled, and clocking, and any additional properties
15631 defined in the entry.
15633 If WHICH is nil or `all', get all properties. If WHICH is
15634 `special' or `standard', only get that subclass. If WHICH is
15635 a string, only get that property.
15637 Return value is an alist. Keys are properties, as upcased
15638 strings."
15639 (org-with-point-at pom
15640 (when (and (derived-mode-p 'org-mode)
15641 (ignore-errors (org-back-to-heading t)))
15642 (catch 'exit
15643 (let* ((beg (point))
15644 (specific (and (stringp which) (upcase which)))
15645 (which (cond ((not specific) which)
15646 ((member specific org-special-properties) 'special)
15647 (t 'standard)))
15648 props)
15649 ;; Get the special properties, like TODO and TAGS.
15650 (when (memq which '(nil all special))
15651 (when (or (not specific) (string= specific "CLOCKSUM"))
15652 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15653 (when clocksum
15654 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15655 props)))
15656 (when specific (throw 'exit props)))
15657 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15658 (let ((clocksumt (get-text-property (point)
15659 :org-clock-minutes-today)))
15660 (when clocksumt
15661 (push (cons "CLOCKSUM_T"
15662 (org-duration-from-minutes clocksumt))
15663 props)))
15664 (when specific (throw 'exit props)))
15665 (when (or (not specific) (string= specific "ITEM"))
15666 (let ((case-fold-search nil))
15667 (when (looking-at org-complex-heading-regexp)
15668 (push (cons "ITEM"
15669 (let ((title (match-string-no-properties 4)))
15670 (if (org-string-nw-p title)
15671 (org-remove-tabs title)
15672 "")))
15673 props)))
15674 (when specific (throw 'exit props)))
15675 (when (or (not specific) (string= specific "TODO"))
15676 (let ((case-fold-search nil))
15677 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15678 (push (cons "TODO" (match-string-no-properties 2)) props)))
15679 (when specific (throw 'exit props)))
15680 (when (or (not specific) (string= specific "PRIORITY"))
15681 (push (cons "PRIORITY"
15682 (if (looking-at org-priority-regexp)
15683 (match-string-no-properties 2)
15684 (char-to-string org-default-priority)))
15685 props)
15686 (when specific (throw 'exit props)))
15687 (when (or (not specific) (string= specific "FILE"))
15688 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15689 props)
15690 (when specific (throw 'exit props)))
15691 (when (or (not specific) (string= specific "TAGS"))
15692 (let ((value (org-string-nw-p (org-get-tags-string))))
15693 (when value (push (cons "TAGS" value) props)))
15694 (when specific (throw 'exit props)))
15695 (when (or (not specific) (string= specific "ALLTAGS"))
15696 (let ((value (org-get-tags-at)))
15697 (when value
15698 (push (cons "ALLTAGS"
15699 (format ":%s:" (mapconcat #'identity value ":")))
15700 props)))
15701 (when specific (throw 'exit props)))
15702 (when (or (not specific) (string= specific "BLOCKED"))
15703 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15704 (when specific (throw 'exit props)))
15705 (when (or (not specific)
15706 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15707 (forward-line)
15708 (when (looking-at-p org-planning-line-re)
15709 (end-of-line)
15710 (let ((bol (line-beginning-position))
15711 ;; Backward compatibility: time keywords used to
15712 ;; be configurable (before 8.3). Make sure we
15713 ;; get the correct keyword.
15714 (key-assoc `(("CLOSED" . ,org-closed-string)
15715 ("DEADLINE" . ,org-deadline-string)
15716 ("SCHEDULED" . ,org-scheduled-string))))
15717 (dolist (pair (if specific (list (assoc specific key-assoc))
15718 key-assoc))
15719 (save-excursion
15720 (when (search-backward (cdr pair) bol t)
15721 (goto-char (match-end 0))
15722 (skip-chars-forward " \t")
15723 (and (looking-at org-ts-regexp-both)
15724 (push (cons (car pair)
15725 (match-string-no-properties 0))
15726 props)))))))
15727 (when specific (throw 'exit props)))
15728 (when (or (not specific)
15729 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15730 (let ((find-ts
15731 (lambda (end ts)
15732 ;; Fix next time-stamp before END. TS is the
15733 ;; list of time-stamps found so far.
15734 (let ((ts ts)
15735 (regexp (cond
15736 ((string= specific "TIMESTAMP")
15737 org-ts-regexp)
15738 ((string= specific "TIMESTAMP_IA")
15739 org-ts-regexp-inactive)
15740 ((assoc "TIMESTAMP_IA" ts)
15741 org-ts-regexp)
15742 ((assoc "TIMESTAMP" ts)
15743 org-ts-regexp-inactive)
15744 (t org-ts-regexp-both))))
15745 (catch 'next
15746 (while (re-search-forward regexp end t)
15747 (backward-char)
15748 (let ((object (org-element-context)))
15749 ;; Accept to match timestamps in node
15750 ;; properties, too.
15751 (when (memq (org-element-type object)
15752 '(node-property timestamp))
15753 (let ((type
15754 (org-element-property :type object)))
15755 (cond
15756 ((and (memq type '(active active-range))
15757 (not (equal specific "TIMESTAMP_IA")))
15758 (unless (assoc "TIMESTAMP" ts)
15759 (push (cons "TIMESTAMP"
15760 (org-element-property
15761 :raw-value object))
15763 (when specific (throw 'exit ts))))
15764 ((and (memq type '(inactive inactive-range))
15765 (not (string= specific "TIMESTAMP")))
15766 (unless (assoc "TIMESTAMP_IA" ts)
15767 (push (cons "TIMESTAMP_IA"
15768 (org-element-property
15769 :raw-value object))
15771 (when specific (throw 'exit ts))))))
15772 ;; Both timestamp types are found,
15773 ;; move to next part.
15774 (when (= (length ts) 2) (throw 'next ts)))))
15775 ts)))))
15776 (goto-char beg)
15777 ;; First look for timestamps within headline.
15778 (let ((ts (funcall find-ts (line-end-position) nil)))
15779 (if (= (length ts) 2) (setq props (nconc ts props))
15780 ;; Then find timestamps in the section, skipping
15781 ;; planning line.
15782 (let ((end (save-excursion (outline-next-heading))))
15783 (forward-line)
15784 (when (looking-at-p org-planning-line-re) (forward-line))
15785 (setq props (nconc (funcall find-ts end ts) props))))))))
15786 ;; Get the standard properties, like :PROP:.
15787 (when (memq which '(nil all standard))
15788 ;; If we are looking after a specific property, delegate
15789 ;; to `org-entry-get', which is faster. However, make an
15790 ;; exception for "CATEGORY", since it can be also set
15791 ;; through keywords (i.e. #+CATEGORY).
15792 (if (and specific (not (equal specific "CATEGORY")))
15793 (let ((value (org-entry-get beg specific nil t)))
15794 (throw 'exit (and value (list (cons specific value)))))
15795 (let ((range (org-get-property-block beg)))
15796 (when range
15797 (let ((end (cdr range)) seen-base)
15798 (goto-char (car range))
15799 ;; Unlike to `org--update-property-plist', we
15800 ;; handle the case where base values is found
15801 ;; after its extension. We also forbid standard
15802 ;; properties to be named as special properties.
15803 (while (re-search-forward org-property-re end t)
15804 (let* ((key (upcase (match-string-no-properties 2)))
15805 (extendp (string-match-p "\\+\\'" key))
15806 (key-base (if extendp (substring key 0 -1) key))
15807 (value (match-string-no-properties 3)))
15808 (cond
15809 ((member-ignore-case key-base org-special-properties))
15810 (extendp
15811 (setq props
15812 (org--update-property-plist key value props)))
15813 ((member key seen-base))
15814 (t (push key seen-base)
15815 (let ((p (assoc-string key props t)))
15816 (if p (setcdr p (concat value " " (cdr p)))
15817 (push (cons key value) props))))))))))))
15818 (unless (assoc "CATEGORY" props)
15819 (push (cons "CATEGORY" (org-get-category beg)) props)
15820 (when (string= specific "CATEGORY") (throw 'exit props)))
15821 ;; Return value.
15822 props)))))
15824 (defun org--property-local-values (property literal-nil)
15825 "Return value for PROPERTY in current entry.
15826 Value is a list whose car is the base value for PROPERTY and cdr
15827 a list of accumulated values. Return nil if neither is found in
15828 the entry. Also return nil when PROPERTY is set to \"nil\",
15829 unless LITERAL-NIL is non-nil."
15830 (let ((range (org-get-property-block)))
15831 (when range
15832 (goto-char (car range))
15833 (let* ((case-fold-search t)
15834 (end (cdr range))
15835 (value
15836 ;; Base value.
15837 (save-excursion
15838 (let ((v (and (re-search-forward
15839 (org-re-property property nil t) end t)
15840 (match-string-no-properties 3))))
15841 (list (if literal-nil v (org-not-nil v)))))))
15842 ;; Find additional values.
15843 (let* ((property+ (org-re-property (concat property "+") nil t)))
15844 (while (re-search-forward property+ end t)
15845 (push (match-string-no-properties 3) value)))
15846 ;; Return final values.
15847 (and (not (equal value '(nil))) (nreverse value))))))
15849 (defun org--property-global-value (property literal-nil)
15850 "Return value for PROPERTY in current buffer.
15851 Return value is a string. Return nil if property is not set
15852 globally. Also return nil when PROPERTY is set to \"nil\",
15853 unless LITERAL-NIL is non-nil."
15854 (let ((global
15855 (cdr (or (assoc-string property org-file-properties t)
15856 (assoc-string property org-global-properties t)
15857 (assoc-string property org-global-properties-fixed t)))))
15858 (if literal-nil global (org-not-nil global))))
15860 (defun org-entry-get (pom property &optional inherit literal-nil)
15861 "Get value of PROPERTY for entry or content at point-or-marker POM.
15863 If INHERIT is non-nil and the entry does not have the property,
15864 then also check higher levels of the hierarchy. If INHERIT is
15865 the symbol `selective', use inheritance only if the setting in
15866 `org-use-property-inheritance' selects PROPERTY for inheritance.
15868 If the property is present but empty, the return value is the
15869 empty string. If the property is not present at all, nil is
15870 returned. In any other case, return the value as a string.
15871 Search is case-insensitive.
15873 If LITERAL-NIL is set, return the string value \"nil\" as
15874 a string, do not interpret it as the list atom nil. This is used
15875 for inheritance when a \"nil\" value can supersede a non-nil
15876 value higher up the hierarchy."
15877 (org-with-point-at pom
15878 (cond
15879 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15880 ;; We need a special property. Use `org-entry-properties' to
15881 ;; retrieve it, but specify the wanted property.
15882 (cdr (assoc-string property (org-entry-properties nil property))))
15883 ((and inherit
15884 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15885 (org-entry-get-with-inheritance property literal-nil))
15887 (let* ((local (org--property-local-values property literal-nil))
15888 (value (and local (mapconcat #'identity (delq nil local) " "))))
15889 (if literal-nil value (org-not-nil value)))))))
15891 (defun org-property-or-variable-value (var &optional inherit)
15892 "Check if there is a property fixing the value of VAR.
15893 If yes, return this value. If not, return the current value of the variable."
15894 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15895 (if (and prop (stringp prop) (string-match "\\S-" prop))
15896 (read prop)
15897 (symbol-value var))))
15899 (defun org-entry-delete (pom property)
15900 "Delete PROPERTY from entry at point-or-marker POM.
15901 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15902 non-nil when a property was removed."
15903 (org-with-point-at pom
15904 (pcase (org-get-property-block)
15905 (`(,begin . ,origin)
15906 (let* ((end (copy-marker origin))
15907 (re (org-re-property
15908 (concat (regexp-quote property) "\\+?") t t)))
15909 (goto-char begin)
15910 (while (re-search-forward re end t)
15911 (delete-region (match-beginning 0) (line-beginning-position 2)))
15912 ;; If drawer is empty, remove it altogether.
15913 (when (= begin end)
15914 (delete-region (line-beginning-position 0)
15915 (line-beginning-position 2)))
15916 ;; Return non-nil if some property was removed.
15917 (prog1 (/= end origin) (set-marker end nil))))
15918 (_ nil))))
15920 ;; Multi-values properties are properties that contain multiple values
15921 ;; These values are assumed to be single words, separated by whitespace.
15922 (defun org-entry-add-to-multivalued-property (pom property value)
15923 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15924 (let* ((old (org-entry-get pom property))
15925 (values (and old (org-split-string old "[ \t]"))))
15926 (setq value (org-entry-protect-space value))
15927 (unless (member value values)
15928 (setq values (append values (list value)))
15929 (org-entry-put pom property
15930 (mapconcat 'identity values " ")))))
15932 (defun org-entry-remove-from-multivalued-property (pom property value)
15933 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15934 (let* ((old (org-entry-get pom property))
15935 (values (and old (org-split-string old "[ \t]"))))
15936 (setq value (org-entry-protect-space value))
15937 (when (member value values)
15938 (setq values (delete value values))
15939 (org-entry-put pom property
15940 (mapconcat 'identity values " ")))))
15942 (defun org-entry-member-in-multivalued-property (pom property value)
15943 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15944 (let* ((old (org-entry-get pom property))
15945 (values (and old (org-split-string old "[ \t]"))))
15946 (setq value (org-entry-protect-space value))
15947 (member value values)))
15949 (defun org-entry-get-multivalued-property (pom property)
15950 "Return a list of values in a multivalued property."
15951 (let* ((value (org-entry-get pom property))
15952 (values (and value (org-split-string value "[ \t]"))))
15953 (mapcar 'org-entry-restore-space values)))
15955 (defun org-entry-put-multivalued-property (pom property &rest values)
15956 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15957 VALUES should be a list of strings. Spaces will be protected."
15958 (org-entry-put pom property
15959 (mapconcat 'org-entry-protect-space values " "))
15960 (let* ((value (org-entry-get pom property))
15961 (values (and value (org-split-string value "[ \t]"))))
15962 (mapcar 'org-entry-restore-space values)))
15964 (defun org-entry-protect-space (s)
15965 "Protect spaces and newline in string S."
15966 (while (string-match " " s)
15967 (setq s (replace-match "%20" t t s)))
15968 (while (string-match "\n" s)
15969 (setq s (replace-match "%0A" t t s)))
15972 (defun org-entry-restore-space (s)
15973 "Restore spaces and newline in string S."
15974 (while (string-match "%20" s)
15975 (setq s (replace-match " " t t s)))
15976 (while (string-match "%0A" s)
15977 (setq s (replace-match "\n" t t s)))
15980 (defvar org-entry-property-inherited-from (make-marker)
15981 "Marker pointing to the entry from where a property was inherited.
15982 Each call to `org-entry-get-with-inheritance' will set this marker to the
15983 location of the entry where the inheritance search matched. If there was
15984 no match, the marker will point nowhere.
15985 Note that also `org-entry-get' calls this function, if the INHERIT flag
15986 is set.")
15988 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15989 "Get PROPERTY of entry or content at point, search higher levels if needed.
15990 The search will stop at the first ancestor which has the property defined.
15991 If the value found is \"nil\", return nil to show that the property
15992 should be considered as undefined (this is the meaning of nil here).
15993 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15994 (move-marker org-entry-property-inherited-from nil)
15995 (org-with-wide-buffer
15996 (let (value)
15997 (catch 'exit
15998 (while t
15999 (let ((v (org--property-local-values property literal-nil)))
16000 (when v
16001 (setq value
16002 (concat (mapconcat #'identity (delq nil v) " ")
16003 (and value " ")
16004 value)))
16005 (cond
16006 ((car v)
16007 (org-back-to-heading t)
16008 (move-marker org-entry-property-inherited-from (point))
16009 (throw 'exit nil))
16010 ((org-up-heading-safe))
16012 (let ((global (org--property-global-value property literal-nil)))
16013 (cond ((not global))
16014 (value (setq value (concat global " " value)))
16015 (t (setq value global))))
16016 (throw 'exit nil))))))
16017 (if literal-nil value (org-not-nil value)))))
16019 (defvar org-property-changed-functions nil
16020 "Hook called when the value of a property has changed.
16021 Each hook function should accept two arguments, the name of the property
16022 and the new value.")
16024 (defun org-entry-put (pom property value)
16025 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16027 If the value is nil, it is converted to the empty string. If it
16028 is not a string, an error is raised. Also raise an error on
16029 invalid property names.
16031 PROPERTY can be any regular property (see
16032 `org-special-properties'). It can also be \"TODO\",
16033 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16035 For the last two properties, VALUE may have any of the special
16036 values \"earlier\" and \"later\". The function then increases or
16037 decreases scheduled or deadline date by one day."
16038 (cond ((null value) (setq value ""))
16039 ((not (stringp value)) (error "Properties values should be strings"))
16040 ((not (org--valid-property-p property))
16041 (user-error "Invalid property name: \"%s\"" property)))
16042 (org-with-point-at pom
16043 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16044 (org-back-to-heading t)
16045 (org-with-limited-levels (org-back-to-heading t)))
16046 (let ((beg (point)))
16047 (cond
16048 ((equal property "TODO")
16049 (cond ((not (org-string-nw-p value)) (setq value 'none))
16050 ((not (member value org-todo-keywords-1))
16051 (user-error "\"%s\" is not a valid TODO state" value)))
16052 (org-todo value)
16053 (org-set-tags nil 'align))
16054 ((equal property "PRIORITY")
16055 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16056 (org-set-tags nil 'align))
16057 ((equal property "SCHEDULED")
16058 (forward-line)
16059 (if (and (looking-at-p org-planning-line-re)
16060 (re-search-forward
16061 org-scheduled-time-regexp (line-end-position) t))
16062 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16063 ((string= value "later") (org-timestamp-change 1 'day))
16064 ((string= value "") (org-schedule '(4)))
16065 (t (org-schedule nil value)))
16066 (if (member value '("earlier" "later" ""))
16067 (call-interactively #'org-schedule)
16068 (org-schedule nil value))))
16069 ((equal property "DEADLINE")
16070 (forward-line)
16071 (if (and (looking-at-p org-planning-line-re)
16072 (re-search-forward
16073 org-deadline-time-regexp (line-end-position) t))
16074 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16075 ((string= value "later") (org-timestamp-change 1 'day))
16076 ((string= value "") (org-deadline '(4)))
16077 (t (org-deadline nil value)))
16078 (if (member value '("earlier" "later" ""))
16079 (call-interactively #'org-deadline)
16080 (org-deadline nil value))))
16081 ((member property org-special-properties)
16082 (error "The %s property cannot be set with `org-entry-put'" property))
16084 (let* ((range (org-get-property-block beg 'force))
16085 (end (cdr range))
16086 (case-fold-search t))
16087 (goto-char (car range))
16088 (if (re-search-forward (org-re-property property nil t) end t)
16089 (progn (delete-region (match-beginning 0) (match-end 0))
16090 (goto-char (match-beginning 0)))
16091 (goto-char end)
16092 (insert "\n")
16093 (backward-char))
16094 (insert ":" property ":")
16095 (when value (insert " " value))
16096 (org-indent-line)))))
16097 (run-hook-with-args 'org-property-changed-functions property value)))
16099 (defun org-buffer-property-keys
16100 (&optional specials defaults columns ignore-malformed)
16101 "Get all property keys in the current buffer.
16103 When SPECIALS is non-nil, also list the special properties that
16104 reflect things like tags and TODO state.
16106 When DEFAULTS is non-nil, also include properties that has
16107 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16108 DESCRIPTION, LOCATION, and LOGGING and others.
16110 When COLUMNS in non-nil, also include property names given in
16111 COLUMN formats in the current buffer.
16113 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16114 automatically performed, such drawers will be silently ignored."
16115 (let ((case-fold-search t)
16116 (props (append
16117 (and specials org-special-properties)
16118 (and defaults (cons org-effort-property org-default-properties))
16119 nil)))
16120 (org-with-wide-buffer
16121 (goto-char (point-min))
16122 (while (re-search-forward org-property-start-re nil t)
16123 (let ((range (org-get-property-block)))
16124 (catch 'skip
16125 (unless range
16126 (when (and (not ignore-malformed)
16127 (not (org-before-first-heading-p))
16128 (y-or-n-p (format "Malformed drawer at %d, repair?"
16129 (line-beginning-position))))
16130 (org-get-property-block nil t))
16131 (throw 'skip nil))
16132 (goto-char (car range))
16133 (let ((begin (car range))
16134 (end (cdr range)))
16135 ;; Make sure that found property block is not located
16136 ;; before current point, as it would generate an infloop.
16137 ;; It can happen, for example, in the following
16138 ;; situation:
16140 ;; * Headline
16141 ;; :PROPERTIES:
16142 ;; ...
16143 ;; :END:
16144 ;; *************** Inlinetask
16145 ;; #+BEGIN_EXAMPLE
16146 ;; :PROPERTIES:
16147 ;; #+END_EXAMPLE
16149 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16150 (while (< (point) end)
16151 (let ((p (progn (looking-at org-property-re)
16152 (match-string-no-properties 2))))
16153 ;; Only add true property name, not extension symbol.
16154 (push (if (not (string-match-p "\\+\\'" p)) p
16155 (substring p 0 -1))
16156 props))
16157 (forward-line))))
16158 (outline-next-heading)))
16159 (when columns
16160 (goto-char (point-min))
16161 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16162 (let ((element (org-element-at-point)))
16163 (when (memq (org-element-type element) '(keyword node-property))
16164 (let ((value (org-element-property :value element))
16165 (start 0))
16166 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16167 (setq start (match-end 0))
16168 (let ((p (match-string-no-properties 1 value)))
16169 (unless (member-ignore-case p org-special-properties)
16170 (push p props))))))))))
16171 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16173 (defun org-property-values (key)
16174 "List all non-nil values of property KEY in current buffer."
16175 (org-with-wide-buffer
16176 (goto-char (point-min))
16177 (let ((case-fold-search t)
16178 (re (org-re-property key))
16179 values)
16180 (while (re-search-forward re nil t)
16181 (push (org-entry-get (point) key) values))
16182 (delete-dups values))))
16184 (defun org-insert-property-drawer ()
16185 "Insert a property drawer into the current entry."
16186 (org-with-wide-buffer
16187 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16188 (org-back-to-heading t)
16189 (org-with-limited-levels (org-back-to-heading t)))
16190 (forward-line)
16191 (when (looking-at-p org-planning-line-re) (forward-line))
16192 (unless (looking-at-p org-property-drawer-re)
16193 ;; Make sure we start editing a line from current entry, not from
16194 ;; next one. It prevents extending text properties or overlays
16195 ;; belonging to the latter.
16196 (when (bolp) (backward-char))
16197 (let ((begin (1+ (point)))
16198 (inhibit-read-only t))
16199 (insert "\n:PROPERTIES:\n:END:")
16200 (when (eobp) (insert "\n"))
16201 (org-indent-region begin (point))))))
16203 (defun org-insert-drawer (&optional arg drawer)
16204 "Insert a drawer at point.
16206 When optional argument ARG is non-nil, insert a property drawer.
16208 Optional argument DRAWER, when non-nil, is a string representing
16209 drawer's name. Otherwise, the user is prompted for a name.
16211 If a region is active, insert the drawer around that region
16212 instead.
16214 Point is left between drawer's boundaries."
16215 (interactive "P")
16216 (let* ((drawer (if arg "PROPERTIES"
16217 (or drawer (read-from-minibuffer "Drawer: ")))))
16218 (cond
16219 ;; With C-u, fall back on `org-insert-property-drawer'
16220 (arg (org-insert-property-drawer))
16221 ;; Check validity of suggested drawer's name.
16222 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16223 (user-error "Invalid drawer name"))
16224 ;; With an active region, insert a drawer at point.
16225 ((not (org-region-active-p))
16226 (progn
16227 (unless (bolp) (insert "\n"))
16228 (insert (format ":%s:\n\n:END:\n" drawer))
16229 (forward-line -2)))
16230 ;; Otherwise, insert the drawer at point
16232 (let ((rbeg (region-beginning))
16233 (rend (copy-marker (region-end))))
16234 (unwind-protect
16235 (progn
16236 (goto-char rbeg)
16237 (beginning-of-line)
16238 (when (save-excursion
16239 (re-search-forward org-outline-regexp-bol rend t))
16240 (user-error "Drawers cannot contain headlines"))
16241 ;; Position point at the beginning of the first
16242 ;; non-blank line in region. Insert drawer's opening
16243 ;; there, then indent it.
16244 (org-skip-whitespace)
16245 (beginning-of-line)
16246 (insert ":" drawer ":\n")
16247 (forward-line -1)
16248 (indent-for-tab-command)
16249 ;; Move point to the beginning of the first blank line
16250 ;; after the last non-blank line in region. Insert
16251 ;; drawer's closing, then indent it.
16252 (goto-char rend)
16253 (skip-chars-backward " \r\t\n")
16254 (insert "\n:END:")
16255 (deactivate-mark t)
16256 (indent-for-tab-command)
16257 (unless (eolp) (insert "\n")))
16258 ;; Clear marker, whatever the outcome of insertion is.
16259 (set-marker rend nil)))))))
16261 (defvar org-property-set-functions-alist nil
16262 "Property set function alist.
16263 Each entry should have the following format:
16265 (PROPERTY . READ-FUNCTION)
16267 The read function will be called with the same argument as
16268 `org-completing-read'.")
16270 (defun org-set-property-function (property)
16271 "Get the function that should be used to set PROPERTY.
16272 This is computed according to `org-property-set-functions-alist'."
16273 (or (cdr (assoc property org-property-set-functions-alist))
16274 'org-completing-read))
16276 (defun org-read-property-value (property)
16277 "Read PROPERTY value from user."
16278 (let* ((completion-ignore-case t)
16279 (allowed (org-property-get-allowed-values nil property 'table))
16280 (cur (org-entry-get nil property))
16281 (prompt (concat property " value"
16282 (if (and cur (string-match "\\S-" cur))
16283 (concat " [" cur "]") "") ": "))
16284 (set-function (org-set-property-function property))
16285 (val (if allowed
16286 (funcall set-function prompt allowed nil
16287 (not (get-text-property 0 'org-unrestricted
16288 (caar allowed))))
16289 (funcall set-function prompt
16290 (mapcar 'list (org-property-values property))
16291 nil nil "" nil cur))))
16292 (org-trim val)))
16294 (defvar org-last-set-property nil)
16295 (defvar org-last-set-property-value nil)
16296 (defun org-read-property-name ()
16297 "Read a property name."
16298 (let ((completion-ignore-case t)
16299 (default-prop (or (and (org-at-property-p)
16300 (match-string-no-properties 2))
16301 org-last-set-property)))
16302 (org-completing-read
16303 (concat "Property"
16304 (if default-prop (concat " [" default-prop "]") "")
16305 ": ")
16306 (mapcar #'list (org-buffer-property-keys nil t t))
16307 nil nil nil nil default-prop)))
16309 (defun org-set-property-and-value (use-last)
16310 "Allow to set [PROPERTY]: [value] direction from prompt.
16311 When use-default, don't even ask, just use the last
16312 \"[PROPERTY]: [value]\" string from the history."
16313 (interactive "P")
16314 (let* ((completion-ignore-case t)
16315 (pv (or (and use-last org-last-set-property-value)
16316 (org-completing-read
16317 "Enter a \"[Property]: [value]\" pair: "
16318 nil nil nil nil nil
16319 org-last-set-property-value)))
16320 prop val)
16321 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16322 (setq prop (match-string 1 pv)
16323 val (match-string 2 pv))
16324 (org-set-property prop val))))
16326 (defun org-set-property (property value)
16327 "In the current entry, set PROPERTY to VALUE.
16329 When called interactively, this will prompt for a property name, offering
16330 completion on existing and default properties. And then it will prompt
16331 for a value, offering completion either on allowed values (via an inherited
16332 xxx_ALL property) or on existing values in other instances of this property
16333 in the current file.
16335 Throw an error when trying to set a property with an invalid name."
16336 (interactive (list nil nil))
16337 (let ((property (or property (org-read-property-name))))
16338 ;; `org-entry-put' also makes the following check, but this one
16339 ;; avoids polluting `org-last-set-property' and
16340 ;; `org-last-set-property-value' needlessly.
16341 (unless (org--valid-property-p property)
16342 (user-error "Invalid property name: \"%s\"" property))
16343 (let ((value (or value (org-read-property-value property)))
16344 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16345 (setq org-last-set-property property)
16346 (setq org-last-set-property-value (concat property ": " value))
16347 ;; Possibly postprocess the inserted value:
16348 (when fn (setq value (funcall fn value)))
16349 (unless (equal (org-entry-get nil property) value)
16350 (org-entry-put nil property value)))))
16352 (defun org-find-property (property &optional value)
16353 "Find first entry in buffer that sets PROPERTY.
16355 When optional argument VALUE is non-nil, only consider an entry
16356 if it contains PROPERTY set to this value. If PROPERTY should be
16357 explicitly set to nil, use string \"nil\" for VALUE.
16359 Return position where the entry begins, or nil if there is no
16360 such entry. If narrowing is in effect, only search the visible
16361 part of the buffer."
16362 (save-excursion
16363 (goto-char (point-min))
16364 (let ((case-fold-search t)
16365 (re (org-re-property property nil (not value) value)))
16366 (catch 'exit
16367 (while (re-search-forward re nil t)
16368 (when (if value (org-at-property-p)
16369 (org-entry-get (point) property nil t))
16370 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16372 (defun org-delete-property (property)
16373 "In the current entry, delete PROPERTY."
16374 (interactive
16375 (let* ((completion-ignore-case t)
16376 (cat (org-entry-get (point) "CATEGORY"))
16377 (props0 (org-entry-properties nil 'standard))
16378 (props (if cat props0
16379 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16380 (prop (if (< 1 (length props))
16381 (completing-read "Property: " props nil t)
16382 (caar props))))
16383 (list prop)))
16384 (if (not property)
16385 (message "No property to delete in this entry")
16386 (org-entry-delete nil property)
16387 (message "Property \"%s\" deleted" property)))
16389 (defun org-delete-property-globally (property)
16390 "Remove PROPERTY globally, from all entries.
16391 This function ignores narrowing, if any."
16392 (interactive
16393 (let* ((completion-ignore-case t)
16394 (prop (completing-read
16395 "Globally remove property: "
16396 (mapcar #'list (org-buffer-property-keys)))))
16397 (list prop)))
16398 (org-with-wide-buffer
16399 (goto-char (point-min))
16400 (let ((count 0)
16401 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16402 (while (re-search-forward re nil t)
16403 (when (org-entry-delete (point) property) (cl-incf count)))
16404 (message "Property \"%s\" removed from %d entries" property count))))
16406 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16408 (defun org-compute-property-at-point ()
16409 "Compute the property at point.
16410 This looks for an enclosing column format, extracts the operator and
16411 then applies it to the property in the column format's scope."
16412 (interactive)
16413 (unless (org-at-property-p)
16414 (user-error "Not at a property"))
16415 (let ((prop (match-string-no-properties 2)))
16416 (org-columns-get-format-and-top-level)
16417 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16418 (user-error "No operator defined for property %s" prop))
16419 (org-columns-compute prop)))
16421 (defvar org-property-allowed-value-functions nil
16422 "Hook for functions supplying allowed values for a specific property.
16423 The functions must take a single argument, the name of the property, and
16424 return a flat list of allowed values. If \":ETC\" is one of
16425 the values, this means that these values are intended as defaults for
16426 completion, but that other values should be allowed too.
16427 The functions must return nil if they are not responsible for this
16428 property.")
16430 (defun org-property-get-allowed-values (pom property &optional table)
16431 "Get allowed values for the property PROPERTY.
16432 When TABLE is non-nil, return an alist that can directly be used for
16433 completion."
16434 (let (vals)
16435 (cond
16436 ((equal property "TODO")
16437 (setq vals (org-with-point-at pom
16438 (append org-todo-keywords-1 '("")))))
16439 ((equal property "PRIORITY")
16440 (let ((n org-lowest-priority))
16441 (while (>= n org-highest-priority)
16442 (push (char-to-string n) vals)
16443 (setq n (1- n)))))
16444 ((equal property "CATEGORY"))
16445 ((member property org-special-properties))
16446 ((setq vals (run-hook-with-args-until-success
16447 'org-property-allowed-value-functions property)))
16449 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16450 (when (and vals (string-match "\\S-" vals))
16451 (setq vals (car (read-from-string (concat "(" vals ")"))))
16452 (setq vals (mapcar (lambda (x)
16453 (cond ((stringp x) x)
16454 ((numberp x) (number-to-string x))
16455 ((symbolp x) (symbol-name x))
16456 (t "???")))
16457 vals)))))
16458 (when (member ":ETC" vals)
16459 (setq vals (remove ":ETC" vals))
16460 (org-add-props (car vals) '(org-unrestricted t)))
16461 (if table (mapcar 'list vals) vals)))
16463 (defun org-property-previous-allowed-value (&optional _previous)
16464 "Switch to the next allowed value for this property."
16465 (interactive)
16466 (org-property-next-allowed-value t))
16468 (defun org-property-next-allowed-value (&optional previous)
16469 "Switch to the next allowed value for this property."
16470 (interactive)
16471 (unless (org-at-property-p)
16472 (user-error "Not at a property"))
16473 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16474 (key (match-string 2))
16475 (value (match-string 3))
16476 (allowed (or (org-property-get-allowed-values (point) key)
16477 (and (member value '("[ ]" "[-]" "[X]"))
16478 '("[ ]" "[X]"))))
16479 (heading (save-match-data (nth 4 (org-heading-components))))
16480 nval)
16481 (unless allowed
16482 (user-error "Allowed values for this property have not been defined"))
16483 (when previous (setq allowed (reverse allowed)))
16484 (when (member value allowed)
16485 (setq nval (car (cdr (member value allowed)))))
16486 (setq nval (or nval (car allowed)))
16487 (when (equal nval value)
16488 (user-error "Only one allowed value for this property"))
16489 (org-at-property-p)
16490 (replace-match (concat " :" key ": " nval) t t)
16491 (org-indent-line)
16492 (beginning-of-line 1)
16493 (skip-chars-forward " \t")
16494 (when (equal prop org-effort-property)
16495 (org-refresh-property
16496 '((effort . identity)
16497 (effort-minutes . org-duration-to-minutes))
16498 nval)
16499 (when (string= org-clock-current-task heading)
16500 (setq org-clock-effort nval)
16501 (org-clock-update-mode-line)))
16502 (run-hook-with-args 'org-property-changed-functions key nval)))
16504 (defun org-find-olp (path &optional this-buffer)
16505 "Return a marker pointing to the entry at outline path OLP.
16506 If anything goes wrong, throw an error.
16507 You can wrap this call to catch the error like this:
16509 (condition-case msg
16510 (org-mobile-locate-entry (match-string 4))
16511 (error (nth 1 msg)))
16513 The return value will then be either a string with the error message,
16514 or a marker if everything is OK.
16516 If THIS-BUFFER is set, the outline path does not contain a file,
16517 only headings."
16518 (let* ((file (if this-buffer buffer-file-name (pop path)))
16519 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16520 (level 1)
16521 (lmin 1)
16522 (lmax 1)
16523 end found flevel)
16524 (unless buffer (error "File not found :%s" file))
16525 (with-current-buffer buffer
16526 (unless (derived-mode-p 'org-mode)
16527 (error "Buffer %s needs to be in Org mode" buffer))
16528 (org-with-wide-buffer
16529 (goto-char (point-min))
16530 (dolist (heading path)
16531 (let ((re (format org-complex-heading-regexp-format
16532 (regexp-quote heading)))
16533 (cnt 0))
16534 (while (re-search-forward re end t)
16535 (setq level (- (match-end 1) (match-beginning 1)))
16536 (when (and (>= level lmin) (<= level lmax))
16537 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16538 (when (= cnt 0)
16539 (error "Heading not found on level %d: %s" lmax heading))
16540 (when (> cnt 1)
16541 (error "Heading not unique on level %d: %s" lmax heading))
16542 (goto-char found)
16543 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16544 (setq end (save-excursion (org-end-of-subtree t t)))))
16545 (when (org-at-heading-p)
16546 (point-marker))))))
16548 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16549 "Find node HEADING in BUFFER.
16550 Return a marker to the heading if it was found, or nil if not.
16551 If POS-ONLY is set, return just the position instead of a marker.
16553 The heading text must match exact, but it may have a TODO keyword,
16554 a priority cookie and tags in the standard locations."
16555 (with-current-buffer (or buffer (current-buffer))
16556 (org-with-wide-buffer
16557 (goto-char (point-min))
16558 (let (case-fold-search)
16559 (when (re-search-forward
16560 (format org-complex-heading-regexp-format
16561 (regexp-quote heading)) nil t)
16562 (if pos-only
16563 (match-beginning 0)
16564 (move-marker (make-marker) (match-beginning 0))))))))
16566 (defun org-find-exact-heading-in-directory (heading &optional dir)
16567 "Find Org node headline HEADING in all .org files in directory DIR.
16568 When the target headline is found, return a marker to this location."
16569 (let ((files (directory-files (or dir default-directory)
16570 t "\\`[^.#].*\\.org\\'"))
16571 visiting m buffer)
16572 (catch 'found
16573 (dolist (file files)
16574 (message "trying %s" file)
16575 (setq visiting (org-find-base-buffer-visiting file))
16576 (setq buffer (or visiting (find-file-noselect file)))
16577 (setq m (org-find-exact-headline-in-buffer
16578 heading buffer))
16579 (when (and (not m) (not visiting)) (kill-buffer buffer))
16580 (and m (throw 'found m))))))
16582 (defun org-find-entry-with-id (ident)
16583 "Locate the entry that contains the ID property with exact value IDENT.
16584 IDENT can be a string, a symbol or a number, this function will search for
16585 the string representation of it.
16586 Return the position where this entry starts, or nil if there is no such entry."
16587 (interactive "sID: ")
16588 (let ((id (cond
16589 ((stringp ident) ident)
16590 ((symbolp ident) (symbol-name ident))
16591 ((numberp ident) (number-to-string ident))
16592 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16593 (org-with-wide-buffer (org-find-property "ID" id))))
16595 ;;;; Timestamps
16597 (defvar org-last-changed-timestamp nil)
16598 (defvar org-last-inserted-timestamp nil
16599 "The last time stamp inserted with `org-insert-time-stamp'.")
16601 (defun org-time-stamp (arg &optional inactive)
16602 "Prompt for a date/time and insert a time stamp.
16604 If the user specifies a time like HH:MM or if this command is
16605 called with at least one prefix argument, the time stamp contains
16606 the date and the time. Otherwise, only the date is included.
16608 All parts of a date not specified by the user are filled in from
16609 the timestamp at point, if any, or the current date/time
16610 otherwise.
16612 If there is already a timestamp at the cursor, it is replaced.
16614 With two universal prefix arguments, insert an active timestamp
16615 with the current time without prompting the user.
16617 When called from lisp, the timestamp is inactive if INACTIVE is
16618 non-nil."
16619 (interactive "P")
16620 (let* ((ts (cond
16621 ((org-at-date-range-p t)
16622 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16623 ((org-at-timestamp-p t) (match-string 0))))
16624 ;; Default time is either the timestamp at point or today.
16625 ;; When entering a range, only the range start is considered.
16626 (default-time (if (not ts) (current-time)
16627 (apply #'encode-time (org-parse-time-string ts))))
16628 (default-input (and ts (org-get-compact-tod ts)))
16629 (repeater (and ts
16630 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16631 (match-string 0 ts)))
16632 org-time-was-given
16633 org-end-time-was-given
16634 (time
16635 (and (if (equal arg '(16)) (current-time)
16636 ;; Preserve `this-command' and `last-command'.
16637 (let ((this-command this-command)
16638 (last-command last-command))
16639 (org-read-date
16640 arg 'totime nil nil default-time default-input
16641 inactive))))))
16642 (cond
16643 ((and ts
16644 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16645 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16646 (insert "--")
16647 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16649 ;; Make sure we're on a timestamp. When in the middle of a date
16650 ;; range, move arbitrarily to range end.
16651 (unless (org-at-timestamp-p t)
16652 (skip-chars-forward "-")
16653 (org-at-timestamp-p t))
16654 (replace-match "")
16655 (setq org-last-changed-timestamp
16656 (org-insert-time-stamp
16657 time (or org-time-was-given arg)
16658 inactive nil nil (list org-end-time-was-given)))
16659 (when repeater
16660 (backward-char)
16661 (insert " " repeater)
16662 (setq org-last-changed-timestamp
16663 (concat (substring org-last-inserted-timestamp 0 -1)
16664 " " repeater ">")))
16665 (message "Timestamp updated"))
16666 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16667 (t (org-insert-time-stamp
16668 time (or org-time-was-given arg) inactive nil nil
16669 (list org-end-time-was-given))))))
16671 ;; FIXME: can we use this for something else, like computing time differences?
16672 (defun org-get-compact-tod (s)
16673 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16674 (let* ((t1 (match-string 1 s))
16675 (h1 (string-to-number (match-string 2 s)))
16676 (m1 (string-to-number (match-string 3 s)))
16677 (t2 (and (match-end 4) (match-string 5 s)))
16678 (h2 (and t2 (string-to-number (match-string 6 s))))
16679 (m2 (and t2 (string-to-number (match-string 7 s))))
16680 dh dm)
16681 (if (not t2)
16683 (setq dh (- h2 h1) dm (- m2 m1))
16684 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16685 (concat t1 "+" (number-to-string dh)
16686 (and (/= 0 dm) (format ":%02d" dm)))))))
16688 (defun org-time-stamp-inactive (&optional arg)
16689 "Insert an inactive time stamp.
16690 An inactive time stamp is enclosed in square brackets instead of angle
16691 brackets. It is inactive in the sense that it does not trigger agenda entries,
16692 does not link to the calendar and cannot be changed with the S-cursor keys.
16693 So these are more for recording a certain time/date."
16694 (interactive "P")
16695 (org-time-stamp arg 'inactive))
16697 (defvar org-date-ovl (make-overlay 1 1))
16698 (overlay-put org-date-ovl 'face 'org-date-selected)
16699 (delete-overlay org-date-ovl)
16701 (defvar org-ans1) ; dynamically scoped parameter
16702 (defvar org-ans2) ; dynamically scoped parameter
16704 (defvar org-plain-time-of-day-regexp) ; defined below
16706 (defvar org-overriding-default-time nil) ; dynamically scoped
16707 (defvar org-read-date-overlay nil)
16708 (defvar org-dcst nil) ; dynamically scoped
16709 (defvar org-read-date-history nil)
16710 (defvar org-read-date-final-answer nil)
16711 (defvar org-read-date-analyze-futurep nil)
16712 (defvar org-read-date-analyze-forced-year nil)
16713 (defvar org-read-date-inactive)
16715 (defvar org-read-date-minibuffer-local-map
16716 (let* ((map (make-sparse-keymap)))
16717 (set-keymap-parent map minibuffer-local-map)
16718 (org-defkey map (kbd ".")
16719 (lambda () (interactive)
16720 ;; Are we at the beginning of the prompt?
16721 (if (looking-back "^[^:]+: "
16722 (let ((inhibit-field-text-motion t))
16723 (line-beginning-position)))
16724 (org-eval-in-calendar '(calendar-goto-today))
16725 (insert "."))))
16726 (org-defkey map (kbd "C-.")
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-goto-today))))
16729 (org-defkey map [(meta shift left)]
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(calendar-backward-month 1))))
16732 (org-defkey map [(meta shift right)]
16733 (lambda () (interactive)
16734 (org-eval-in-calendar '(calendar-forward-month 1))))
16735 (org-defkey map [(meta shift up)]
16736 (lambda () (interactive)
16737 (org-eval-in-calendar '(calendar-backward-year 1))))
16738 (org-defkey map [(meta shift down)]
16739 (lambda () (interactive)
16740 (org-eval-in-calendar '(calendar-forward-year 1))))
16741 (org-defkey map [?\e (shift left)]
16742 (lambda () (interactive)
16743 (org-eval-in-calendar '(calendar-backward-month 1))))
16744 (org-defkey map [?\e (shift right)]
16745 (lambda () (interactive)
16746 (org-eval-in-calendar '(calendar-forward-month 1))))
16747 (org-defkey map [?\e (shift up)]
16748 (lambda () (interactive)
16749 (org-eval-in-calendar '(calendar-backward-year 1))))
16750 (org-defkey map [?\e (shift down)]
16751 (lambda () (interactive)
16752 (org-eval-in-calendar '(calendar-forward-year 1))))
16753 (org-defkey map [(shift up)]
16754 (lambda () (interactive)
16755 (org-eval-in-calendar '(calendar-backward-week 1))))
16756 (org-defkey map [(shift down)]
16757 (lambda () (interactive)
16758 (org-eval-in-calendar '(calendar-forward-week 1))))
16759 (org-defkey map [(shift left)]
16760 (lambda () (interactive)
16761 (org-eval-in-calendar '(calendar-backward-day 1))))
16762 (org-defkey map [(shift right)]
16763 (lambda () (interactive)
16764 (org-eval-in-calendar '(calendar-forward-day 1))))
16765 (org-defkey map "!"
16766 (lambda () (interactive)
16767 (org-eval-in-calendar '(diary-view-entries))
16768 (message "")))
16769 (org-defkey map ">"
16770 (lambda () (interactive)
16771 (org-eval-in-calendar '(calendar-scroll-left 1))))
16772 (org-defkey map "<"
16773 (lambda () (interactive)
16774 (org-eval-in-calendar '(calendar-scroll-right 1))))
16775 (org-defkey map "\C-v"
16776 (lambda () (interactive)
16777 (org-eval-in-calendar
16778 '(calendar-scroll-left-three-months 1))))
16779 (org-defkey map "\M-v"
16780 (lambda () (interactive)
16781 (org-eval-in-calendar
16782 '(calendar-scroll-right-three-months 1))))
16783 map)
16784 "Keymap for minibuffer commands when using `org-read-date'.")
16786 (defvar org-def)
16787 (defvar org-defdecode)
16788 (defvar org-with-time)
16790 (defvar calendar-setup) ; Dynamically scoped.
16791 (defun org-read-date (&optional with-time to-time from-string prompt
16792 default-time default-input inactive)
16793 "Read a date, possibly a time, and make things smooth for the user.
16794 The prompt will suggest to enter an ISO date, but you can also enter anything
16795 which will at least partially be understood by `parse-time-string'.
16796 Unrecognized parts of the date will default to the current day, month, year,
16797 hour and minute. If this command is called to replace a timestamp at point,
16798 or to enter the second timestamp of a range, the default time is taken
16799 from the existing stamp. Furthermore, the command prefers the future,
16800 so if you are giving a date where the year is not given, and the day-month
16801 combination is already past in the current year, it will assume you
16802 mean next year. For details, see the manual. A few examples:
16804 3-2-5 --> 2003-02-05
16805 feb 15 --> currentyear-02-15
16806 2/15 --> currentyear-02-15
16807 sep 12 9 --> 2009-09-12
16808 12:45 --> today 12:45
16809 22 sept 0:34 --> currentyear-09-22 0:34
16810 12 --> currentyear-currentmonth-12
16811 Fri --> nearest Friday after today
16812 -Tue --> last Tuesday
16813 etc.
16815 Furthermore you can specify a relative date by giving, as the *first* thing
16816 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16817 change in days weeks, months, years.
16818 With a single plus or minus, the date is relative to today. With a double
16819 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16820 +4d --> four days from today
16821 +4 --> same as above
16822 +2w --> two weeks from today
16823 ++5 --> five days from default date
16825 The function understands only English month and weekday abbreviations.
16827 While prompting, a calendar is popped up - you can also select the
16828 date with the mouse (button 1). The calendar shows a period of three
16829 months. To scroll it to other months, use the keys `>' and `<'.
16830 If you don't like the calendar, turn it off with
16831 (setq org-read-date-popup-calendar nil)
16833 With optional argument TO-TIME, the date will immediately be converted
16834 to an internal time.
16835 With an optional argument WITH-TIME, the prompt will suggest to
16836 also insert a time. Note that when WITH-TIME is not set, you can
16837 still enter a time, and this function will inform the calling routine
16838 about this change. The calling routine may then choose to change the
16839 format used to insert the time stamp into the buffer to include the time.
16840 With optional argument FROM-STRING, read from this string instead from
16841 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16842 the time/date that is used for everything that is not specified by the
16843 user."
16844 (require 'parse-time)
16845 (let* ((org-with-time with-time)
16846 (org-time-stamp-rounding-minutes
16847 (if (equal org-with-time '(16))
16848 '(0 0)
16849 org-time-stamp-rounding-minutes))
16850 (org-dcst org-display-custom-times)
16851 (ct (org-current-time))
16852 (org-def (or org-overriding-default-time default-time ct))
16853 (org-defdecode (decode-time org-def))
16854 (cur-frame (selected-frame))
16855 (mouse-autoselect-window nil) ; Don't let the mouse jump
16856 (calendar-setup
16857 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16858 (calendar-move-hook nil)
16859 (calendar-view-diary-initially-flag nil)
16860 (calendar-view-holidays-initially-flag nil)
16861 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16862 ;; Rationalize `org-def' and `org-defdecode', if required.
16863 (when (< (nth 2 org-defdecode) org-extend-today-until)
16864 (setf (nth 2 org-defdecode) -1)
16865 (setf (nth 1 org-defdecode) 59)
16866 (setq org-def (apply #'encode-time org-defdecode))
16867 (setq org-defdecode (decode-time org-def)))
16868 (let* ((timestr (format-time-string
16869 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16870 org-def))
16871 (prompt (concat (if prompt (concat prompt " ") "")
16872 (format "Date+time [%s]: " timestr))))
16873 (cond
16874 (from-string (setq ans from-string))
16875 (org-read-date-popup-calendar
16876 (save-excursion
16877 (save-window-excursion
16878 (calendar)
16879 (when (eq calendar-setup 'calendar-only)
16880 (setq cal-frame
16881 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16882 (select-frame cal-frame))
16883 (org-eval-in-calendar '(setq cursor-type nil) t)
16884 (unwind-protect
16885 (progn
16886 (calendar-forward-day (- (time-to-days org-def)
16887 (calendar-absolute-from-gregorian
16888 (calendar-current-date))))
16889 (org-eval-in-calendar nil t)
16890 (let* ((old-map (current-local-map))
16891 (map (copy-keymap calendar-mode-map))
16892 (minibuffer-local-map
16893 (copy-keymap org-read-date-minibuffer-local-map)))
16894 (org-defkey map (kbd "RET") 'org-calendar-select)
16895 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16896 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16897 (unwind-protect
16898 (progn
16899 (use-local-map map)
16900 (setq org-read-date-inactive inactive)
16901 (add-hook 'post-command-hook 'org-read-date-display)
16902 (setq org-ans0
16903 (read-string prompt
16904 default-input
16905 'org-read-date-history
16906 nil))
16907 ;; org-ans0: from prompt
16908 ;; org-ans1: from mouse click
16909 ;; org-ans2: from calendar motion
16910 (setq ans
16911 (concat org-ans0 " " (or org-ans1 org-ans2))))
16912 (remove-hook 'post-command-hook 'org-read-date-display)
16913 (use-local-map old-map)
16914 (when org-read-date-overlay
16915 (delete-overlay org-read-date-overlay)
16916 (setq org-read-date-overlay nil)))))
16917 (bury-buffer "*Calendar*")
16918 (when cal-frame
16919 (delete-frame cal-frame)
16920 (select-frame-set-input-focus cur-frame))))))
16922 (t ; Naked prompt only
16923 (unwind-protect
16924 (setq ans (read-string prompt default-input
16925 'org-read-date-history timestr))
16926 (when org-read-date-overlay
16927 (delete-overlay org-read-date-overlay)
16928 (setq org-read-date-overlay nil))))))
16930 (setq final (org-read-date-analyze ans org-def org-defdecode))
16932 (when org-read-date-analyze-forced-year
16933 (message "Year was forced into %s"
16934 (if org-read-date-force-compatible-dates
16935 "compatible range (1970-2037)"
16936 "range representable on this machine"))
16937 (ding))
16939 ;; One round trip to get rid of 34th of August and stuff like that....
16940 (setq final (decode-time (apply 'encode-time final)))
16942 (setq org-read-date-final-answer ans)
16944 (if to-time
16945 (apply 'encode-time final)
16946 (if (and (boundp 'org-time-was-given) org-time-was-given)
16947 (format "%04d-%02d-%02d %02d:%02d"
16948 (nth 5 final) (nth 4 final) (nth 3 final)
16949 (nth 2 final) (nth 1 final))
16950 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16952 (defun org-read-date-display ()
16953 "Display the current date prompt interpretation in the minibuffer."
16954 (when org-read-date-display-live
16955 (when org-read-date-overlay
16956 (delete-overlay org-read-date-overlay))
16957 (when (minibufferp (current-buffer))
16958 (save-excursion
16959 (end-of-line 1)
16960 (while (not (equal (buffer-substring
16961 (max (point-min) (- (point) 4)) (point))
16962 " "))
16963 (insert " ")))
16964 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16965 " " (or org-ans1 org-ans2)))
16966 (org-end-time-was-given nil)
16967 (f (org-read-date-analyze ans org-def org-defdecode))
16968 (fmts (if org-dcst
16969 org-time-stamp-custom-formats
16970 org-time-stamp-formats))
16971 (fmt (if (or org-with-time
16972 (and (boundp 'org-time-was-given) org-time-was-given))
16973 (cdr fmts)
16974 (car fmts)))
16975 (txt (format-time-string fmt (apply 'encode-time f)))
16976 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16977 (txt (concat "=> " txt)))
16978 (when (and org-end-time-was-given
16979 (string-match org-plain-time-of-day-regexp txt))
16980 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16981 org-end-time-was-given
16982 (substring txt (match-end 0)))))
16983 (when org-read-date-analyze-futurep
16984 (setq txt (concat txt " (=>F)")))
16985 (setq org-read-date-overlay
16986 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16987 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16989 (defun org-read-date-analyze (ans def defdecode)
16990 "Analyze the combined answer of the date prompt."
16991 ;; FIXME: cleanup and comment
16992 ;; Pass `current-time' result to `decode-time' (instead of calling
16993 ;; without arguments) so that only `current-time' has to be
16994 ;; overriden in tests.
16995 (let ((org-def def)
16996 (org-defdecode defdecode)
16997 (nowdecode (decode-time (current-time)))
16998 delta deltan deltaw deltadef year month day
16999 hour minute second wday pm h2 m2 tl wday1
17000 iso-year iso-weekday iso-week iso-date futurep kill-year)
17001 (setq org-read-date-analyze-futurep nil
17002 org-read-date-analyze-forced-year nil)
17003 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17004 (setq ans "+0"))
17006 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17007 (setq ans (replace-match "" t t ans)
17008 deltan (car delta)
17009 deltaw (nth 1 delta)
17010 deltadef (nth 2 delta)))
17012 ;; Check if there is an iso week date in there. If yes, store the
17013 ;; info and postpone interpreting it until the rest of the parsing
17014 ;; is done.
17015 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17016 (setq iso-year (when (match-end 1)
17017 (org-small-year-to-year
17018 (string-to-number (match-string 1 ans))))
17019 iso-weekday (when (match-end 3)
17020 (string-to-number (match-string 3 ans)))
17021 iso-week (string-to-number (match-string 2 ans)))
17022 (setq ans (replace-match "" t t ans)))
17024 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17025 (when (string-match
17026 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17027 (setq year (if (match-end 2)
17028 (string-to-number (match-string 2 ans))
17029 (progn (setq kill-year t)
17030 (string-to-number (format-time-string "%Y"))))
17031 month (string-to-number (match-string 3 ans))
17032 day (string-to-number (match-string 4 ans)))
17033 (setq year (org-small-year-to-year year))
17034 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17035 t nil ans)))
17037 ;; Help matching dotted european dates
17038 (when (string-match
17039 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17040 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17041 (setq kill-year t)
17042 (string-to-number (format-time-string "%Y")))
17043 day (string-to-number (match-string 1 ans))
17044 month (string-to-number (match-string 2 ans))
17045 ans (replace-match (format "%04d-%02d-%02d" year month day)
17046 t nil ans)))
17048 ;; Help matching american dates, like 5/30 or 5/30/7
17049 (when (string-match
17050 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17051 (setq year (if (match-end 4)
17052 (string-to-number (match-string 4 ans))
17053 (progn (setq kill-year t)
17054 (string-to-number (format-time-string "%Y"))))
17055 month (string-to-number (match-string 1 ans))
17056 day (string-to-number (match-string 2 ans)))
17057 (setq year (org-small-year-to-year year))
17058 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17059 t nil ans)))
17060 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17061 ;; If there is a time with am/pm, and *no* time without it, we convert
17062 ;; so that matching will be successful.
17063 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17064 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17065 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17066 (setq hour (string-to-number (match-string 1 ans))
17067 minute (if (match-end 3)
17068 (string-to-number (match-string 3 ans))
17070 pm (equal ?p
17071 (string-to-char (downcase (match-string 4 ans)))))
17072 (if (and (= hour 12) (not pm))
17073 (setq hour 0)
17074 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17075 (setq ans (replace-match (format "%02d:%02d" hour minute)
17076 t t ans))))
17078 ;; Check if a time range is given as a duration
17079 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17080 (setq hour (string-to-number (match-string 1 ans))
17081 h2 (+ hour (string-to-number (match-string 3 ans)))
17082 minute (string-to-number (match-string 2 ans))
17083 m2 (+ minute (if (match-end 5) (string-to-number
17084 (match-string 5 ans))0)))
17085 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17086 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17087 t t ans)))
17089 ;; Check if there is a time range
17090 (when (boundp 'org-end-time-was-given)
17091 (setq org-time-was-given nil)
17092 (when (and (string-match org-plain-time-of-day-regexp ans)
17093 (match-end 8))
17094 (setq org-end-time-was-given (match-string 8 ans))
17095 (setq ans (concat (substring ans 0 (match-beginning 7))
17096 (substring ans (match-end 7))))))
17098 (setq tl (parse-time-string ans)
17099 day (or (nth 3 tl) (nth 3 org-defdecode))
17100 month
17101 (cond ((nth 4 tl))
17102 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17103 ;; Day was specified. Make sure DAY+MONTH
17104 ;; combination happens in the future.
17105 ((nth 3 tl)
17106 (setq futurep t)
17107 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17108 (nth 4 nowdecode)))
17109 (t (nth 4 org-defdecode)))
17110 year
17111 (cond ((and (not kill-year) (nth 5 tl)))
17112 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17113 ;; Month was guessed in the future and is at least
17114 ;; equal to NOWDECODE's. Fix year accordingly.
17115 (futurep
17116 (if (or (> month (nth 4 nowdecode))
17117 (>= day (nth 3 nowdecode)))
17118 (nth 5 nowdecode)
17119 (1+ (nth 5 nowdecode))))
17120 ;; Month was specified. Make sure MONTH+YEAR
17121 ;; combination happens in the future.
17122 ((nth 4 tl)
17123 (setq futurep t)
17124 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17125 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17126 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17127 (t (nth 5 nowdecode))))
17128 (t (nth 5 org-defdecode)))
17129 hour (or (nth 2 tl) (nth 2 org-defdecode))
17130 minute (or (nth 1 tl) (nth 1 org-defdecode))
17131 second (or (nth 0 tl) 0)
17132 wday (nth 6 tl))
17134 (when (and (eq org-read-date-prefer-future 'time)
17135 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17136 (equal day (nth 3 nowdecode))
17137 (equal month (nth 4 nowdecode))
17138 (equal year (nth 5 nowdecode))
17139 (nth 2 tl)
17140 (or (< (nth 2 tl) (nth 2 nowdecode))
17141 (and (= (nth 2 tl) (nth 2 nowdecode))
17142 (nth 1 tl)
17143 (< (nth 1 tl) (nth 1 nowdecode)))))
17144 (setq day (1+ day)
17145 futurep t))
17147 ;; Special date definitions below
17148 (cond
17149 (iso-week
17150 ;; There was an iso week
17151 (require 'cal-iso)
17152 (setq futurep nil)
17153 (setq year (or iso-year year)
17154 day (or iso-weekday wday 1)
17155 wday nil ; to make sure that the trigger below does not match
17156 iso-date (calendar-gregorian-from-absolute
17157 (calendar-iso-to-absolute
17158 (list iso-week day year))))
17159 ; FIXME: Should we also push ISO weeks into the future?
17160 ; (when (and org-read-date-prefer-future
17161 ; (not iso-year)
17162 ; (< (calendar-absolute-from-gregorian iso-date)
17163 ; (time-to-days (current-time))))
17164 ; (setq year (1+ year)
17165 ; iso-date (calendar-gregorian-from-absolute
17166 ; (calendar-iso-to-absolute
17167 ; (list iso-week day year)))))
17168 (setq month (car iso-date)
17169 year (nth 2 iso-date)
17170 day (nth 1 iso-date)))
17171 (deltan
17172 (setq futurep nil)
17173 (unless deltadef
17174 ;; Pass `current-time' result to `decode-time' (instead of
17175 ;; calling without arguments) so that only `current-time' has
17176 ;; to be overriden in tests.
17177 (let ((now (decode-time (current-time))))
17178 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17179 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17180 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17181 ((equal deltaw "m") (setq month (+ month deltan)))
17182 ((equal deltaw "y") (setq year (+ year deltan)))))
17183 ((and wday (not (nth 3 tl)))
17184 ;; Weekday was given, but no day, so pick that day in the week
17185 ;; on or after the derived date.
17186 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17187 (unless (equal wday wday1)
17188 (setq day (+ day (% (- wday wday1 -7) 7))))))
17189 (when (and (boundp 'org-time-was-given)
17190 (nth 2 tl))
17191 (setq org-time-was-given t))
17192 (when (< year 100) (setq year (+ 2000 year)))
17193 ;; Check of the date is representable
17194 (if org-read-date-force-compatible-dates
17195 (progn
17196 (when (< year 1970)
17197 (setq year 1970 org-read-date-analyze-forced-year t))
17198 (when (> year 2037)
17199 (setq year 2037 org-read-date-analyze-forced-year t)))
17200 (condition-case nil
17201 (ignore (encode-time second minute hour day month year))
17202 (error
17203 (setq year (nth 5 org-defdecode))
17204 (setq org-read-date-analyze-forced-year t))))
17205 (setq org-read-date-analyze-futurep futurep)
17206 (list second minute hour day month year)))
17208 (defvar parse-time-weekdays)
17209 (defun org-read-date-get-relative (s today default)
17210 "Check string S for special relative date string.
17211 TODAY and DEFAULT are internal times, for today and for a default.
17212 Return shift list (N what def-flag)
17213 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17214 N is the number of WHATs to shift.
17215 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17216 the DEFAULT date rather than TODAY."
17217 (require 'parse-time)
17218 (when (and
17219 (string-match
17220 (concat
17221 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17222 "\\([0-9]+\\)?"
17223 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17224 "\\([ \t]\\|$\\)") s)
17225 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17226 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17227 (string-to-char (substring (match-string 1 s) -1))
17228 ?+))
17229 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17230 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17231 (what (if (match-end 3) (match-string 3 s) "d"))
17232 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17233 (date (if rel default today))
17234 (wday (nth 6 (decode-time date)))
17235 delta)
17236 (if wday1
17237 (progn
17238 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17239 (when (= delta 0) (setq delta 7))
17240 (when (= dir ?-)
17241 (setq delta (- delta 7))
17242 (when (= delta 0) (setq delta -7)))
17243 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17244 (list delta "d" rel))
17245 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17247 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17248 "Turn a user-specified date into the internal representation.
17249 The internal representation needed by the calendar is (month day year).
17250 This is a wrapper to handle the brain-dead convention in calendar that
17251 user function argument order change dependent on argument order."
17252 (pcase calendar-date-style
17253 (`american (list arg1 arg2 arg3))
17254 (`european (list arg2 arg1 arg3))
17255 (`iso (list arg2 arg3 arg1))))
17257 (defun org-eval-in-calendar (form &optional keepdate)
17258 "Eval FORM in the calendar window and return to current window.
17259 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17260 (let ((sf (selected-frame))
17261 (sw (selected-window)))
17262 (select-window (get-buffer-window "*Calendar*" t))
17263 (eval form)
17264 (when (and (not keepdate) (calendar-cursor-to-date))
17265 (let* ((date (calendar-cursor-to-date))
17266 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17267 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17268 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17269 (select-window sw)
17270 (select-frame-set-input-focus sf)))
17272 (defun org-calendar-select ()
17273 "Return to `org-read-date' with the date currently selected.
17274 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17275 (interactive)
17276 (when (calendar-cursor-to-date)
17277 (let* ((date (calendar-cursor-to-date))
17278 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17279 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17280 (when (active-minibuffer-window) (exit-minibuffer))))
17282 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17283 "Insert a date stamp for the date given by the internal TIME.
17284 See `format-time-string' for the format of TIME.
17285 WITH-HM means use the stamp format that includes the time of the day.
17286 INACTIVE means use square brackets instead of angular ones, so that the
17287 stamp will not contribute to the agenda.
17288 PRE and POST are optional strings to be inserted before and after the
17289 stamp.
17290 The command returns the inserted time stamp."
17291 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17292 stamp)
17293 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17294 (insert-before-markers (or pre ""))
17295 (when (listp extra)
17296 (setq extra (car extra))
17297 (if (and (stringp extra)
17298 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17299 (setq extra (format "-%02d:%02d"
17300 (string-to-number (match-string 1 extra))
17301 (string-to-number (match-string 2 extra))))
17302 (setq extra nil)))
17303 (when extra
17304 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17305 (insert-before-markers (setq stamp (format-time-string fmt time)))
17306 (insert-before-markers (or post ""))
17307 (setq org-last-inserted-timestamp stamp)))
17309 (defun org-toggle-time-stamp-overlays ()
17310 "Toggle the use of custom time stamp formats."
17311 (interactive)
17312 (setq org-display-custom-times (not org-display-custom-times))
17313 (unless org-display-custom-times
17314 (let ((p (point-min)) (bmp (buffer-modified-p)))
17315 (while (setq p (next-single-property-change p 'display))
17316 (when (and (get-text-property p 'display)
17317 (eq (get-text-property p 'face) 'org-date))
17318 (remove-text-properties
17319 p (setq p (next-single-property-change p 'display))
17320 '(display t))))
17321 (set-buffer-modified-p bmp)))
17322 (org-restart-font-lock)
17323 (setq org-table-may-need-update t)
17324 (if org-display-custom-times
17325 (message "Time stamps are overlaid with custom format")
17326 (message "Time stamp overlays removed")))
17328 (defun org-display-custom-time (beg end)
17329 "Overlay modified time stamp format over timestamp between BEG and END."
17330 (let* ((ts (buffer-substring beg end))
17331 t1 w1 with-hm tf time str w2 (off 0))
17332 (save-match-data
17333 (setq t1 (org-parse-time-string ts t))
17334 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17335 (setq off (- (match-end 0) (match-beginning 0)))))
17336 (setq end (- end off))
17337 (setq w1 (- end beg)
17338 with-hm (and (nth 1 t1) (nth 2 t1))
17339 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17340 time (org-fix-decoded-time t1)
17341 str (org-add-props
17342 (format-time-string
17343 (substring tf 1 -1) (apply 'encode-time time))
17344 nil 'mouse-face 'highlight)
17345 w2 (length str))
17346 (unless (= w2 w1)
17347 (add-text-properties (1+ beg) (+ 2 beg)
17348 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17349 (put-text-property beg end 'display str)))
17351 (defun org-fix-decoded-time (time)
17352 "Set 0 instead of nil for the first 6 elements of time.
17353 Don't touch the rest."
17354 (let ((n 0))
17355 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17357 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17358 "Difference between TIMESTAMP-STRING and now in days.
17359 If SECONDS is non-nil, return the difference in seconds."
17360 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17361 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17362 (funcall fdiff (current-time)))))
17364 (defun org-deadline-close-p (timestamp-string &optional ndays)
17365 "Is the time in TIMESTAMP-STRING close to the current date?"
17366 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17367 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17368 (not (org-entry-is-done-p))))
17370 (defun org-get-wdays (ts &optional delay zero-delay)
17371 "Get the deadline lead time appropriate for timestring TS.
17372 When DELAY is non-nil, get the delay time for scheduled items
17373 instead of the deadline lead time. When ZERO-DELAY is non-nil
17374 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17375 don't try to find the delay cookie in the scheduled timestamp."
17376 (let ((tv (if delay org-scheduled-delay-days
17377 org-deadline-warning-days)))
17378 (cond
17379 ((or (and delay (< tv 0))
17380 (and delay zero-delay (<= tv 0))
17381 (and (not delay) (<= tv 0)))
17382 ;; Enforce this value no matter what
17383 (- tv))
17384 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17385 ;; lead time is specified.
17386 (floor (* (string-to-number (match-string 1 ts))
17387 (cdr (assoc (match-string 2 ts)
17388 '(("d" . 1) ("w" . 7)
17389 ("m" . 30.4) ("y" . 365.25)
17390 ("h" . 0.041667)))))))
17391 ;; go for the default.
17392 (t tv))))
17394 (defun org-calendar-select-mouse (ev)
17395 "Return to `org-read-date' with the date currently selected.
17396 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17397 (interactive "e")
17398 (mouse-set-point ev)
17399 (when (calendar-cursor-to-date)
17400 (let* ((date (calendar-cursor-to-date))
17401 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17402 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17403 (when (active-minibuffer-window) (exit-minibuffer))))
17405 (defun org-check-deadlines (ndays)
17406 "Check if there are any deadlines due or past due.
17407 A deadline is considered due if it happens within `org-deadline-warning-days'
17408 days from today's date. If the deadline appears in an entry marked DONE,
17409 it is not shown. A numeric prefix argument NDAYS can be used to test that
17410 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17411 are shown."
17412 (interactive "P")
17413 (let* ((org-warn-days
17414 (cond
17415 ((equal ndays '(4)) 100000)
17416 (ndays (prefix-numeric-value ndays))
17417 (t (abs org-deadline-warning-days))))
17418 (case-fold-search nil)
17419 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17420 (callback
17421 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17422 (message "%d deadlines past-due or due within %d days"
17423 (org-occur regexp nil callback)
17424 org-warn-days)))
17426 (defsubst org-re-timestamp (type)
17427 "Return a regexp for timestamp TYPE.
17428 Allowed values for TYPE are:
17430 all: all timestamps
17431 active: only active timestamps (<...>)
17432 inactive: only inactive timestamps ([...])
17433 scheduled: only scheduled timestamps
17434 deadline: only deadline timestamps
17435 closed: only closed time-stamps
17437 When TYPE is nil, fall back on returning a regexp that matches
17438 both scheduled and deadline timestamps."
17439 (cl-case type
17440 (all org-ts-regexp-both)
17441 (active org-ts-regexp)
17442 (inactive org-ts-regexp-inactive)
17443 (scheduled org-scheduled-time-regexp)
17444 (deadline org-deadline-time-regexp)
17445 (closed org-closed-time-regexp)
17446 (otherwise
17447 (concat "\\<"
17448 (regexp-opt (list org-deadline-string org-scheduled-string))
17449 " *<\\([^>]+\\)>"))))
17451 (defun org-check-before-date (d)
17452 "Check if there are deadlines or scheduled entries before date D."
17453 (interactive (list (org-read-date)))
17454 (let* ((case-fold-search nil)
17455 (regexp (org-re-timestamp org-ts-type))
17456 (ts-type org-ts-type)
17457 (callback
17458 (lambda ()
17459 (let ((match (match-string 1)))
17460 (and (if (memq ts-type '(active inactive all))
17461 (eq (org-element-type (save-excursion
17462 (backward-char)
17463 (org-element-context)))
17464 'timestamp)
17465 (org-at-planning-p))
17466 (time-less-p
17467 (org-time-string-to-time match)
17468 (org-time-string-to-time d)))))))
17469 (message "%d entries before %s"
17470 (org-occur regexp nil callback)
17471 d)))
17473 (defun org-check-after-date (d)
17474 "Check if there are deadlines or scheduled entries after date D."
17475 (interactive (list (org-read-date)))
17476 (let* ((case-fold-search nil)
17477 (regexp (org-re-timestamp org-ts-type))
17478 (ts-type org-ts-type)
17479 (callback
17480 (lambda ()
17481 (let ((match (match-string 1)))
17482 (and (if (memq ts-type '(active inactive all))
17483 (eq (org-element-type (save-excursion
17484 (backward-char)
17485 (org-element-context)))
17486 'timestamp)
17487 (org-at-planning-p))
17488 (not (time-less-p
17489 (org-time-string-to-time match)
17490 (org-time-string-to-time d))))))))
17491 (message "%d entries after %s"
17492 (org-occur regexp nil callback)
17493 d)))
17495 (defun org-check-dates-range (start-date end-date)
17496 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17497 (interactive (list (org-read-date nil nil nil "Range starts")
17498 (org-read-date nil nil nil "Range end")))
17499 (let ((case-fold-search nil)
17500 (regexp (org-re-timestamp org-ts-type))
17501 (callback
17502 (let ((type org-ts-type))
17503 (lambda ()
17504 (let ((match (match-string 1)))
17505 (and
17506 (if (memq type '(active inactive all))
17507 (eq (org-element-type (save-excursion
17508 (backward-char)
17509 (org-element-context)))
17510 'timestamp)
17511 (org-at-planning-p))
17512 (not (time-less-p
17513 (org-time-string-to-time match)
17514 (org-time-string-to-time start-date)))
17515 (time-less-p
17516 (org-time-string-to-time match)
17517 (org-time-string-to-time end-date))))))))
17518 (message "%d entries between %s and %s"
17519 (org-occur regexp nil callback) start-date end-date)))
17521 (defun org-evaluate-time-range (&optional to-buffer)
17522 "Evaluate a time range by computing the difference between start and end.
17523 Normally the result is just printed in the echo area, but with prefix arg
17524 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17525 If the time range is actually in a table, the result is inserted into the
17526 next column.
17527 For time difference computation, a year is assumed to be exactly 365
17528 days in order to avoid rounding problems."
17529 (interactive "P")
17531 (org-clock-update-time-maybe)
17532 (save-excursion
17533 (unless (org-at-date-range-p t)
17534 (goto-char (point-at-bol))
17535 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17536 (unless (org-at-date-range-p t)
17537 (user-error "Not at a time-stamp range, and none found in current line")))
17538 (let* ((ts1 (match-string 1))
17539 (ts2 (match-string 2))
17540 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17541 (match-end (match-end 0))
17542 (time1 (org-time-string-to-time ts1))
17543 (time2 (org-time-string-to-time ts2))
17544 (t1 (float-time time1))
17545 (t2 (float-time time2))
17546 (diff (abs (- t2 t1)))
17547 (negative (< (- t2 t1) 0))
17548 ;; (ys (floor (* 365 24 60 60)))
17549 (ds (* 24 60 60))
17550 (hs (* 60 60))
17551 (fy "%dy %dd %02d:%02d")
17552 (fy1 "%dy %dd")
17553 (fd "%dd %02d:%02d")
17554 (fd1 "%dd")
17555 (fh "%02d:%02d")
17556 y d h m align)
17557 (if havetime
17558 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17560 d (floor (/ diff ds)) diff (mod diff ds)
17561 h (floor (/ diff hs)) diff (mod diff hs)
17562 m (floor (/ diff 60)))
17563 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17565 d (floor (+ (/ diff ds) 0.5))
17566 h 0 m 0))
17567 (if (not to-buffer)
17568 (message "%s" (org-make-tdiff-string y d h m))
17569 (if (org-at-table-p)
17570 (progn
17571 (goto-char match-end)
17572 (setq align t)
17573 (and (looking-at " *|") (goto-char (match-end 0))))
17574 (goto-char match-end))
17575 (when (looking-at
17576 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17577 (replace-match ""))
17578 (when negative (insert " -"))
17579 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17580 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17581 (insert " " (format fh h m))))
17582 (when align (org-table-align))
17583 (message "Time difference inserted")))))
17585 (defun org-make-tdiff-string (y d h m)
17586 (let ((fmt "")
17587 (l nil))
17588 (when (> y 0)
17589 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17590 (push y l))
17591 (when (> d 0)
17592 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17593 (push d l))
17594 (when (> h 0)
17595 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17596 (push h l))
17597 (when (> m 0)
17598 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17599 (push m l))
17600 (apply 'format fmt (nreverse l))))
17602 (defun org-time-string-to-time (s &optional buffer pos)
17603 "Convert a timestamp string into internal time."
17604 (condition-case errdata
17605 (apply 'encode-time (org-parse-time-string s))
17606 (error (error "Bad timestamp `%s'%s\nError was: %s"
17607 s (if (not (and buffer pos))
17609 (format-message " at %d in buffer `%s'" pos buffer))
17610 (cdr errdata)))))
17612 (defun org-time-string-to-seconds (s)
17613 "Convert a timestamp string to a number of seconds."
17614 (float-time (org-time-string-to-time s)))
17616 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17618 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17619 "Convert time stamp S to an absolute day number.
17621 If DAYNR in non-nil, and there is a specifier for a cyclic time
17622 stamp, get the closest date to DAYNR. If PREFER is
17623 `past' (respectively `future') return a date past (respectively
17624 after) or equal to DAYNR.
17626 POS is the location of time stamp S, as a buffer position in
17627 BUFFER.
17629 Diary sexp timestamps are matched against DAYNR, when non-nil.
17630 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17631 signalled."
17632 (cond
17633 ((string-match "\\`%%\\((.*)\\)" s)
17634 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17635 ;; only able to match individual dates. If it fails, raise an
17636 ;; error.
17637 (if (and daynr
17638 (org-diary-sexp-entry
17639 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17640 daynr
17641 (signal 'org-diary-sexp-no-match (list s))))
17642 (daynr (org-closest-date s daynr prefer))
17643 (t (time-to-days
17644 (condition-case errdata
17645 (apply #'encode-time (org-parse-time-string s))
17646 (error (error "Bad timestamp `%s'%s\nError was: %s"
17648 (if (not (and buffer pos)) ""
17649 (format-message " at %d in buffer `%s'" pos buffer))
17650 (cdr errdata))))))))
17652 (defun org-days-to-iso-week (days)
17653 "Return the iso week number."
17654 (require 'cal-iso)
17655 (car (calendar-iso-from-absolute days)))
17657 (defun org-small-year-to-year (year)
17658 "Convert 2-digit years into 4-digit years.
17659 YEAR is expanded into one of the 30 next years, if possible, or
17660 into a past one. Any year larger than 99 is returned unchanged."
17661 (if (>= year 100) year
17662 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17663 (century (/ current 100))
17664 (offset (- year (% current 100))))
17665 (cond ((> offset 30) (+ (* (1- century) 100) year))
17666 ((> offset -70) (+ (* century 100) year))
17667 (t (+ (* (1+ century) 100) year))))))
17669 (defun org-time-from-absolute (d)
17670 "Return the time corresponding to date D.
17671 D may be an absolute day number, or a calendar-type list (month day year)."
17672 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17673 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17675 (defvar org-agenda-current-date)
17676 (defun org-calendar-holiday ()
17677 "List of holidays, for Diary display in Org mode."
17678 (require 'holidays)
17679 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17680 (and hl (mapconcat #'identity hl "; "))))
17682 (defun org-diary-sexp-entry (sexp entry d)
17683 "Process a SEXP diary ENTRY for date D."
17684 (require 'diary-lib)
17685 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17686 ;; dynamically.
17687 (let* ((sexp `(let ((entry ,entry)
17688 (date ',d))
17689 ,(car (read-from-string sexp))))
17690 (result (if calendar-debug-sexp (eval sexp)
17691 (condition-case nil
17692 (eval sexp)
17693 (error
17694 (beep)
17695 (message "Bad sexp at line %d in %s: %s"
17696 (org-current-line)
17697 (buffer-file-name) sexp)
17698 (sleep-for 2))))))
17699 (cond ((stringp result) (split-string result "; "))
17700 ((and (consp result)
17701 (not (consp (cdr result)))
17702 (stringp (cdr result))) (cdr result))
17703 ((and (consp result)
17704 (stringp (car result))) result)
17705 (result entry))))
17707 (defun org-diary-to-ical-string (frombuf)
17708 "Get iCalendar entries from diary entries in buffer FROMBUF.
17709 This uses the icalendar.el library."
17710 (let* ((tmpdir temporary-file-directory)
17711 (tmpfile (make-temp-name
17712 (expand-file-name "orgics" tmpdir)))
17713 buf rtn b e)
17714 (with-current-buffer frombuf
17715 (icalendar-export-region (point-min) (point-max) tmpfile)
17716 (setq buf (find-buffer-visiting tmpfile))
17717 (set-buffer buf)
17718 (goto-char (point-min))
17719 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17720 (setq b (match-beginning 0)))
17721 (goto-char (point-max))
17722 (when (re-search-backward "^END:VEVENT" nil t)
17723 (setq e (match-end 0)))
17724 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17725 (kill-buffer buf)
17726 (delete-file tmpfile)
17727 rtn))
17729 (defun org-closest-date (start current prefer)
17730 "Return closest date to CURRENT starting from START.
17732 CURRENT and START are both time stamps.
17734 When PREFER is `past', return a date that is either CURRENT or
17735 past. When PREFER is `future', return a date that is either
17736 CURRENT or future.
17738 Only time stamps with a repeater are modified. Any other time
17739 stamp stay unchanged. In any case, return value is an absolute
17740 day number."
17741 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17742 ;; No repeater. Do not shift time stamp.
17743 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17744 (let ((value (string-to-number (match-string 1 start)))
17745 (type (match-string 2 start)))
17746 (if (= 0 value)
17747 ;; Repeater with a 0-value is considered as void.
17748 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17749 (let* ((base (org-date-to-gregorian start))
17750 (target (org-date-to-gregorian current))
17751 (sday (calendar-absolute-from-gregorian base))
17752 (cday (calendar-absolute-from-gregorian target))
17753 n1 n2)
17754 ;; If START is already past CURRENT, just return START.
17755 (if (<= cday sday) sday
17756 ;; Compute closest date before (N1) and closest date past
17757 ;; (N2) CURRENT.
17758 (pcase type
17759 ("h"
17760 (let ((missing-hours
17761 (mod (+ (- (* 24 (- cday sday))
17762 (nth 2 (org-parse-time-string start)))
17763 org-extend-today-until)
17764 value)))
17765 (setf n1 (if (= missing-hours 0) cday
17766 (- cday (1+ (/ missing-hours 24)))))
17767 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17768 ((or "d" "w")
17769 (let ((value (if (equal type "w") (* 7 value) value)))
17770 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17771 (setf n2 (+ n1 value))))
17772 ("m"
17773 (let* ((add-months
17774 (lambda (d n)
17775 ;; Add N months to gregorian date D, i.e.,
17776 ;; a list (MONTH DAY YEAR). Return a valid
17777 ;; gregorian date.
17778 (let ((m (+ (nth 0 d) n)))
17779 (list (mod m 12)
17780 (nth 1 d)
17781 (+ (/ m 12) (nth 2 d))))))
17782 (months ; Complete months to TARGET.
17783 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17784 (- (nth 0 target) (nth 0 base))
17785 ;; If START's day is greater than
17786 ;; TARGET's, remove incomplete month.
17787 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17788 value)
17789 value))
17790 (before (funcall add-months base months)))
17791 (setf n1 (calendar-absolute-from-gregorian before))
17792 (setf n2
17793 (calendar-absolute-from-gregorian
17794 (funcall add-months before value)))))
17796 (let* ((d (nth 1 base))
17797 (m (nth 0 base))
17798 (y (nth 2 base))
17799 (years ; Complete years to TARGET.
17800 (* (/ (- (nth 2 target)
17802 ;; If START's month and day are
17803 ;; greater than TARGET's, remove
17804 ;; incomplete year.
17805 (if (or (> (nth 0 target) m)
17806 (and (= (nth 0 target) m)
17807 (> (nth 1 target) d)))
17810 value)
17811 value))
17812 (before (list m d (+ y years))))
17813 (setf n1 (calendar-absolute-from-gregorian before))
17814 (setf n2 (calendar-absolute-from-gregorian
17815 (list m d (+ (nth 2 before) value)))))))
17816 ;; Handle PREFER parameter, if any.
17817 (cond
17818 ((eq prefer 'past) (if (= cday n2) n2 n1))
17819 ((eq prefer 'future) (if (= cday n1) n1 n2))
17820 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17822 (defun org-date-to-gregorian (d)
17823 "Turn any specification of date D into a Gregorian date for the calendar."
17824 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17825 ((and (listp d) (= (length d) 3)) d)
17826 ((stringp d)
17827 (let ((d (org-parse-time-string d)))
17828 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17829 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17831 (defun org-parse-time-string (s &optional nodefault)
17832 "Parse the standard Org time string.
17833 This should be a lot faster than the normal `parse-time-string'.
17834 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17835 hour and minute fields will be nil if not given."
17836 (cond ((string-match org-ts-regexp0 s)
17837 (list 0
17838 (when (or (match-beginning 8) (not nodefault))
17839 (string-to-number (or (match-string 8 s) "0")))
17840 (when (or (match-beginning 7) (not nodefault))
17841 (string-to-number (or (match-string 7 s) "0")))
17842 (string-to-number (match-string 4 s))
17843 (string-to-number (match-string 3 s))
17844 (string-to-number (match-string 2 s))
17845 nil nil nil))
17846 ((string-match "^<[^>]+>$" s)
17847 (decode-time (seconds-to-time (org-matcher-time s))))
17848 (t (error "Not a standard Org time string: %s" s))))
17850 (defun org-timestamp-up (&optional arg)
17851 "Increase the date item at the cursor by one.
17852 If the cursor is on the year, change the year. If it is on the month,
17853 the day or the time, change that.
17854 With prefix ARG, change by that many units."
17855 (interactive "p")
17856 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17858 (defun org-timestamp-down (&optional arg)
17859 "Decrease the date item at the cursor by one.
17860 If the cursor is on the year, change the year. If it is on the month,
17861 the day or the time, change that.
17862 With prefix ARG, change by that many units."
17863 (interactive "p")
17864 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17866 (defun org-timestamp-up-day (&optional arg)
17867 "Increase the date in the time stamp by one day.
17868 With prefix ARG, change that many days."
17869 (interactive "p")
17870 (if (and (not (org-at-timestamp-p t))
17871 (org-at-heading-p))
17872 (org-todo 'up)
17873 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17875 (defun org-timestamp-down-day (&optional arg)
17876 "Decrease the date in the time stamp by one day.
17877 With prefix ARG, change that many days."
17878 (interactive "p")
17879 (if (and (not (org-at-timestamp-p t))
17880 (org-at-heading-p))
17881 (org-todo 'down)
17882 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17884 (defun org-at-timestamp-p (&optional inactive-ok)
17885 "Non-nil if point is inside a timestamp.
17887 When optional argument INACTIVE-OK is non-nil, also consider
17888 inactive timestamps.
17890 When this function returns a non-nil value, match data is set
17891 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17892 INACTIVE-OK.
17894 Return the position of the point as a symbol among `bracket',
17895 `after', `year', `month', `hour', `minute', `day' or a number of
17896 character from the last know part of the time stamp.
17898 This function checks context and only return non-nil for valid
17899 time stamps. If you need to match anything looking like a time
17900 stamp, or if you are sure about the context, consider using
17901 `org-in-regexp', e.g.,
17903 (org-in-regexp org-ts-regexp)
17905 Unlike to `org-element-context', the function recognizes time
17906 stamps in properties drawers, planning lines and clocks."
17907 (interactive)
17908 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17909 (pos (point))
17910 (match
17911 (let ((boundaries (org-in-regexp tsr)))
17912 (save-match-data
17913 (cond ((null boundaries) nil)
17914 ((org-at-planning-p))
17915 ((org-at-property-p))
17916 ;; CLOCK lines only contain inactive time-stamps.
17917 ((and inactive-ok (org-at-clock-log-p)))
17919 (eq 'timestamp
17920 (save-excursion
17921 (when (= pos (cdr boundaries)) (forward-char -1))
17922 (org-element-type (org-element-context))))))))))
17923 (cond
17924 ((not match) nil)
17925 ((= pos (match-beginning 0)) 'bracket)
17926 ;; Distinguish location right before the closing bracket from
17927 ;; right after it.
17928 ((= pos (1- (match-end 0))) 'bracket)
17929 ((= pos (match-end 0)) 'after)
17930 ((org-pos-in-match-range pos 2) 'year)
17931 ((org-pos-in-match-range pos 3) 'month)
17932 ((org-pos-in-match-range pos 7) 'hour)
17933 ((org-pos-in-match-range pos 8) 'minute)
17934 ((or (org-pos-in-match-range pos 4)
17935 (org-pos-in-match-range pos 5)) 'day)
17936 ((and (> pos (or (match-end 8) (match-end 5)))
17937 (< pos (match-end 0)))
17938 (- pos (or (match-end 8) (match-end 5))))
17939 (t 'day))))
17941 (defun org-toggle-timestamp-type ()
17942 "Toggle the type (<active> or [inactive]) of a time stamp."
17943 (interactive)
17944 (when (org-at-timestamp-p t)
17945 (let ((beg (match-beginning 0)) (end (match-end 0))
17946 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17947 (save-excursion
17948 (goto-char beg)
17949 (while (re-search-forward "[][<>]" end t)
17950 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17951 t t)))
17952 (message "Timestamp is now %sactive"
17953 (if (equal (char-after beg) ?<) "" "in")))))
17955 (defun org-at-clock-log-p ()
17956 "Non-nil if point is on a clock log line."
17957 (and (org-match-line org-clock-line-re)
17958 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17960 (defvar org-clock-history) ; defined in org-clock.el
17961 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17962 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17963 "Change the date in the time stamp at point.
17964 The date will be changed by N times WHAT. WHAT can be `day', `month',
17965 `year', `minute', `second'. If WHAT is not given, the cursor position
17966 in the timestamp determines what will be changed.
17967 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17968 (let ((origin (point))
17969 (timestamp? (org-at-timestamp-p t))
17970 origin-cat
17971 with-hm inactive
17972 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17973 extra rem
17974 ts time time0 fixnext clrgx)
17975 (unless timestamp? (user-error "Not at a timestamp"))
17976 (if (and (not what) (eq timestamp? 'bracket))
17977 (org-toggle-timestamp-type)
17978 ;; Point isn't on brackets. Remember the part of the time-stamp
17979 ;; the point was in. Indeed, size of time-stamps may change,
17980 ;; but point must be kept in the same category nonetheless.
17981 (setq origin-cat timestamp?)
17982 (when (and (not what) (not (eq timestamp? 'day))
17983 org-display-custom-times
17984 (get-text-property (point) 'display)
17985 (not (get-text-property (1- (point)) 'display)))
17986 (setq timestamp? 'day))
17987 (setq timestamp? (or what timestamp?)
17988 inactive (= (char-after (match-beginning 0)) ?\[)
17989 ts (match-string 0))
17990 (replace-match "")
17991 (when (string-match
17992 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17994 (setq extra (match-string 1 ts))
17995 (when suppress-tmp-delay
17996 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17997 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17998 (setq with-hm t))
17999 (setq time0 (org-parse-time-string ts))
18000 (when (and updown
18001 (eq timestamp? 'minute)
18002 (not current-prefix-arg))
18003 ;; This looks like s-up and s-down. Change by one rounding step.
18004 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18005 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18006 (setcar (cdr time0) (+ (nth 1 time0)
18007 (if (> n 0) (- rem) (- dm rem))))))
18008 (setq time
18009 (apply #'encode-time
18010 (or (car time0) 0)
18011 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18012 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18013 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18014 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18015 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18016 (nthcdr 6 time0)))
18017 (when (and (memq timestamp? '(hour minute))
18018 extra
18019 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18020 (setq extra (org-modify-ts-extra
18021 extra
18022 (if (eq timestamp? 'hour) 2 5)
18023 n dm)))
18024 (when (integerp timestamp?)
18025 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18026 (when (eq what 'calendar)
18027 (let ((cal-date (org-get-date-from-calendar)))
18028 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18029 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18030 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18031 (setcar time0 (or (car time0) 0))
18032 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18033 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18034 (setq time (apply 'encode-time time0))))
18035 ;; Insert the new time-stamp, and ensure point stays in the same
18036 ;; category as before (i.e. not after the last position in that
18037 ;; category).
18038 (let ((pos (point)))
18039 ;; Stay before inserted string. `save-excursion' is of no use.
18040 (setq org-last-changed-timestamp
18041 (org-insert-time-stamp time with-hm inactive nil nil extra))
18042 (goto-char pos))
18043 (save-match-data
18044 (looking-at org-ts-regexp3)
18045 (goto-char
18046 (pcase origin-cat
18047 ;; `day' category ends before `hour' if any, or at the end
18048 ;; of the day name.
18049 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18050 (`hour (min (match-end 7) origin))
18051 (`minute (min (1- (match-end 8)) origin))
18052 ((pred integerp) (min (1- (match-end 0)) origin))
18053 ;; Point was right after the time-stamp. However, the
18054 ;; time-stamp length might have changed, so refer to
18055 ;; (match-end 0) instead.
18056 (`after (match-end 0))
18057 ;; `year' and `month' have both fixed size: point couldn't
18058 ;; have moved into another part.
18059 (_ origin))))
18060 ;; Update clock if on a CLOCK line.
18061 (org-clock-update-time-maybe)
18062 ;; Maybe adjust the closest clock in `org-clock-history'
18063 (when org-clock-adjust-closest
18064 (if (not (and (org-at-clock-log-p)
18065 (< 1 (length (delq nil (mapcar 'marker-position
18066 org-clock-history))))))
18067 (message "No clock to adjust")
18068 (cond ((save-excursion ; fix previous clock?
18069 (re-search-backward org-ts-regexp0 nil t)
18070 (looking-back (concat org-clock-string " \\[")
18071 (line-beginning-position)))
18072 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18073 ((save-excursion ; fix next clock?
18074 (re-search-backward org-ts-regexp0 nil t)
18075 (looking-at (concat org-ts-regexp0 "\\] =>")))
18076 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18077 (save-window-excursion
18078 ;; Find closest clock to point, adjust the previous/next one in history
18079 (let* ((p (save-excursion (org-back-to-heading t)))
18080 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18081 (clfixnth
18082 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18083 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18084 (if (not clfixpos)
18085 (message "No clock to adjust")
18086 (save-excursion
18087 (org-goto-marker-or-bmk clfixpos)
18088 (org-show-subtree)
18089 (when (re-search-forward clrgx nil t)
18090 (goto-char (match-beginning 1))
18091 (let (org-clock-adjust-closest)
18092 (org-timestamp-change n timestamp? updown))
18093 (message "Clock adjusted in %s for heading: %s"
18094 (file-name-nondirectory (buffer-file-name))
18095 (org-get-heading t t)))))))))
18096 ;; Try to recenter the calendar window, if any.
18097 (when (and org-calendar-follow-timestamp-change
18098 (get-buffer-window "*Calendar*" t)
18099 (memq timestamp? '(day month year)))
18100 (org-recenter-calendar (time-to-days time))))))
18102 (defun org-modify-ts-extra (s pos n dm)
18103 "Change the different parts of the lead-time and repeat fields in timestamp."
18104 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18105 ng h m new rem)
18106 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18107 (cond
18108 ((or (org-pos-in-match-range pos 2)
18109 (org-pos-in-match-range pos 3))
18110 (setq m (string-to-number (match-string 3 s))
18111 h (string-to-number (match-string 2 s)))
18112 (if (org-pos-in-match-range pos 2)
18113 (setq h (+ h n))
18114 (setq n (* dm (with-no-warnings (signum n))))
18115 (unless (= 0 (setq rem (% m dm)))
18116 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18117 (setq m (+ m n)))
18118 (when (< m 0) (setq m (+ m 60) h (1- h)))
18119 (when (> m 59) (setq m (- m 60) h (1+ h)))
18120 (setq h (mod h 24))
18121 (setq ng 1 new (format "-%02d:%02d" h m)))
18122 ((org-pos-in-match-range pos 6)
18123 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18124 ((org-pos-in-match-range pos 5)
18125 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18127 ((org-pos-in-match-range pos 9)
18128 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18129 ((org-pos-in-match-range pos 8)
18130 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18132 (when ng
18133 (setq s (concat
18134 (substring s 0 (match-beginning ng))
18136 (substring s (match-end ng))))))
18139 (defun org-recenter-calendar (d)
18140 "If the calendar is visible, recenter it to date D."
18141 (let ((cwin (get-buffer-window "*Calendar*" t)))
18142 (when cwin
18143 (let ((calendar-move-hook nil))
18144 (with-selected-window cwin
18145 (calendar-goto-date
18146 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18148 (defun org-goto-calendar (&optional arg)
18149 "Go to the Emacs calendar at the current date.
18150 If there is a time stamp in the current line, go to that date.
18151 A prefix ARG can be used to force the current date."
18152 (interactive "P")
18153 (let ((tsr org-ts-regexp) diff
18154 (calendar-move-hook nil)
18155 (calendar-view-holidays-initially-flag nil)
18156 (calendar-view-diary-initially-flag nil))
18157 (when (or (org-at-timestamp-p)
18158 (save-excursion
18159 (beginning-of-line 1)
18160 (looking-at (concat ".*" tsr))))
18161 (let ((d1 (time-to-days (current-time)))
18162 (d2 (time-to-days
18163 (org-time-string-to-time (match-string 1)))))
18164 (setq diff (- d2 d1))))
18165 (calendar)
18166 (calendar-goto-today)
18167 (when (and diff (not arg)) (calendar-forward-day diff))))
18169 (defun org-get-date-from-calendar ()
18170 "Return a list (month day year) of date at point in calendar."
18171 (with-current-buffer "*Calendar*"
18172 (save-match-data
18173 (calendar-cursor-to-date))))
18175 (defun org-date-from-calendar ()
18176 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18177 If there is already a time stamp at the cursor position, update it."
18178 (interactive)
18179 (if (org-at-timestamp-p t)
18180 (org-timestamp-change 0 'calendar)
18181 (let ((cal-date (org-get-date-from-calendar)))
18182 (org-insert-time-stamp
18183 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18185 (defcustom org-effort-durations
18186 `(("min" . 1)
18187 ("h" . 60)
18188 ("d" . ,(* 60 8))
18189 ("w" . ,(* 60 8 5))
18190 ("m" . ,(* 60 8 5 4))
18191 ("y" . ,(* 60 8 5 40)))
18192 "Conversion factor to minutes for an effort modifier.
18194 Each entry has the form (MODIFIER . MINUTES).
18196 In an effort string, a number followed by MODIFIER is multiplied
18197 by the specified number of MINUTES to obtain an effort in
18198 minutes.
18200 For example, if the value of this variable is ((\"hours\" . 60)), then an
18201 effort string \"2hours\" is equivalent to 120 minutes."
18202 :group 'org-agenda
18203 :version "26.1"
18204 :package-version '(Org . "8.3")
18205 :type '(alist :key-type (string :tag "Modifier")
18206 :value-type (number :tag "Minutes")))
18208 (defcustom org-image-actual-width t
18209 "Should we use the actual width of images when inlining them?
18211 When set to t, always use the image width.
18213 When set to a number, use imagemagick (when available) to set
18214 the image's width to this value.
18216 When set to a number in a list, try to get the width from any
18217 #+ATTR.* keyword if it matches a width specification like
18219 #+ATTR_HTML: :width 300px
18221 and fall back on that number if none is found.
18223 When set to nil, try to get the width from an #+ATTR.* keyword
18224 and fall back on the original width if none is found.
18226 This requires Emacs >= 24.1, build with imagemagick support."
18227 :group 'org-appearance
18228 :version "24.4"
18229 :package-version '(Org . "8.0")
18230 :type '(choice
18231 (const :tag "Use the image width" t)
18232 (integer :tag "Use a number of pixels")
18233 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18234 (const :tag "Use #+ATTR* or don't resize" nil)))
18236 (defcustom org-agenda-inhibit-startup nil
18237 "Inhibit startup when preparing agenda buffers.
18238 When this variable is t, the initialization of the Org agenda
18239 buffers is inhibited: e.g. the visibility state is not set, the
18240 tables are not re-aligned, etc."
18241 :type 'boolean
18242 :version "24.3"
18243 :group 'org-agenda)
18245 (defcustom org-agenda-ignore-properties nil
18246 "Avoid updating text properties when building the agenda.
18247 Properties are used to prepare buffers for effort estimates,
18248 appointments, statistics and subtree-local categories.
18249 If you don't use these in the agenda, you can add them to this
18250 list and agenda building will be a bit faster.
18251 The value is a list, with zero or more of the symbols `effort', `appt',
18252 `stats' or `category'."
18253 :type '(set :greedy t
18254 (const effort)
18255 (const appt)
18256 (const stats)
18257 (const category))
18258 :version "26.1"
18259 :package-version '(Org . "8.3")
18260 :group 'org-agenda)
18262 ;;;; Files
18264 (defun org-save-all-org-buffers ()
18265 "Save all Org buffers without user confirmation."
18266 (interactive)
18267 (message "Saving all Org buffers...")
18268 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18269 (when (featurep 'org-id) (org-id-locations-save))
18270 (message "Saving all Org buffers... done"))
18272 (defun org-revert-all-org-buffers ()
18273 "Revert all Org buffers.
18274 Prompt for confirmation when there are unsaved changes.
18275 Be sure you know what you are doing before letting this function
18276 overwrite your changes.
18278 This function is useful in a setup where one tracks org files
18279 with a version control system, to revert on one machine after pulling
18280 changes from another. I believe the procedure must be like this:
18282 1. M-x org-save-all-org-buffers
18283 2. Pull changes from the other machine, resolve conflicts
18284 3. M-x org-revert-all-org-buffers"
18285 (interactive)
18286 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18287 (user-error "Abort"))
18288 (save-excursion
18289 (save-window-excursion
18290 (dolist (b (buffer-list))
18291 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18292 (with-current-buffer b buffer-file-name))
18293 (pop-to-buffer-same-window b)
18294 (revert-buffer t 'no-confirm)))
18295 (when (and (featurep 'org-id) org-id-track-globally)
18296 (org-id-locations-load)))))
18298 ;;;; Agenda files
18300 ;;;###autoload
18301 (defun org-switchb (&optional arg)
18302 "Switch between Org buffers.
18304 With `\\[universal-argument]' prefix, restrict available buffers to files.
18306 With `\\[universal-argument] \\[universal-argument]' \
18307 prefix, restrict available buffers to agenda files."
18308 (interactive "P")
18309 (let ((blist (org-buffer-list
18310 (cond ((equal arg '(4)) 'files)
18311 ((equal arg '(16)) 'agenda)))))
18312 (pop-to-buffer-same-window
18313 (completing-read "Org buffer: "
18314 (mapcar #'list (mapcar #'buffer-name blist))
18315 nil t))))
18317 (defun org-buffer-list (&optional predicate exclude-tmp)
18318 "Return a list of Org buffers.
18319 PREDICATE can be `export', `files' or `agenda'.
18321 export restrict the list to Export buffers.
18322 files restrict the list to buffers visiting Org files.
18323 agenda restrict the list to buffers visiting agenda files.
18325 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18326 (let* ((bfn nil)
18327 (agenda-files (and (eq predicate 'agenda)
18328 (mapcar 'file-truename (org-agenda-files t))))
18329 (filter
18330 (cond
18331 ((eq predicate 'files)
18332 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18333 ((eq predicate 'export)
18334 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18335 ((eq predicate 'agenda)
18336 (lambda (b)
18337 (with-current-buffer b
18338 (and (derived-mode-p 'org-mode)
18339 (setq bfn (buffer-file-name b))
18340 (member (file-truename bfn) agenda-files)))))
18341 (t (lambda (b) (with-current-buffer b
18342 (or (derived-mode-p 'org-mode)
18343 (string-match "\\*Org .*Export"
18344 (buffer-name b)))))))))
18345 (delq nil
18346 (mapcar
18347 (lambda(b)
18348 (if (and (funcall filter b)
18349 (or (not exclude-tmp)
18350 (not (string-match "tmp" (buffer-name b)))))
18352 nil))
18353 (buffer-list)))))
18355 (defun org-agenda-files (&optional unrestricted archives)
18356 "Get the list of agenda files.
18357 Optional UNRESTRICTED means return the full list even if a restriction
18358 is currently in place.
18359 When ARCHIVES is t, include all archive files that are really being
18360 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18361 `org-agenda-archives-mode' is t."
18362 (let ((files
18363 (cond
18364 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18365 ((stringp org-agenda-files) (org-read-agenda-file-list))
18366 ((listp org-agenda-files) org-agenda-files)
18367 (t (error "Invalid value of `org-agenda-files'")))))
18368 (setq files (apply 'append
18369 (mapcar (lambda (f)
18370 (if (file-directory-p f)
18371 (directory-files
18372 f t org-agenda-file-regexp)
18373 (list f)))
18374 files)))
18375 (when org-agenda-skip-unavailable-files
18376 (setq files (delq nil
18377 (mapcar (function
18378 (lambda (file)
18379 (and (file-readable-p file) file)))
18380 files))))
18381 (when (or (eq archives t)
18382 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18383 (setq files (org-add-archive-files files)))
18384 files))
18386 (defun org-agenda-file-p (&optional file)
18387 "Return non-nil, if FILE is an agenda file.
18388 If FILE is omitted, use the file associated with the current
18389 buffer."
18390 (let ((fname (or file (buffer-file-name))))
18391 (and fname
18392 (member (file-truename fname)
18393 (mapcar #'file-truename (org-agenda-files t))))))
18395 (defun org-edit-agenda-file-list ()
18396 "Edit the list of agenda files.
18397 Depending on setup, this either uses customize to edit the variable
18398 `org-agenda-files', or it visits the file that is holding the list. In the
18399 latter case, the buffer is set up in a way that saving it automatically kills
18400 the buffer and restores the previous window configuration."
18401 (interactive)
18402 (if (stringp org-agenda-files)
18403 (let ((cw (current-window-configuration)))
18404 (find-file org-agenda-files)
18405 (setq-local org-window-configuration cw)
18406 (add-hook 'after-save-hook
18407 (lambda ()
18408 (set-window-configuration
18409 (prog1 org-window-configuration
18410 (kill-buffer (current-buffer))))
18411 (org-install-agenda-files-menu)
18412 (message "New agenda file list installed"))
18413 nil 'local)
18414 (message "%s" (substitute-command-keys
18415 "Edit list and finish with \\[save-buffer]")))
18416 (customize-variable 'org-agenda-files)))
18418 (defun org-store-new-agenda-file-list (list)
18419 "Set new value for the agenda file list and save it correctly."
18420 (if (stringp org-agenda-files)
18421 (let ((fe (org-read-agenda-file-list t)) b u)
18422 (while (setq b (find-buffer-visiting org-agenda-files))
18423 (kill-buffer b))
18424 (with-temp-file org-agenda-files
18425 (insert
18426 (mapconcat
18427 (lambda (f) ;; Keep un-expanded entries.
18428 (if (setq u (assoc f fe))
18429 (cdr u)
18431 list "\n")
18432 "\n")))
18433 (let ((org-mode-hook nil) (org-inhibit-startup t)
18434 (org-insert-mode-line-in-empty-file nil))
18435 (setq org-agenda-files list)
18436 (customize-save-variable 'org-agenda-files org-agenda-files))))
18438 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18439 "Read the list of agenda files from a file.
18440 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18441 filenames, used by `org-store-new-agenda-file-list' to write back
18442 un-expanded file names."
18443 (when (file-directory-p org-agenda-files)
18444 (error "`org-agenda-files' cannot be a single directory"))
18445 (when (stringp org-agenda-files)
18446 (with-temp-buffer
18447 (insert-file-contents org-agenda-files)
18448 (mapcar
18449 (lambda (f)
18450 (let ((e (expand-file-name (substitute-in-file-name f)
18451 org-directory)))
18452 (if pair-with-expansion
18453 (cons e f)
18454 e)))
18455 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18457 ;;;###autoload
18458 (defun org-cycle-agenda-files ()
18459 "Cycle through the files in `org-agenda-files'.
18460 If the current buffer visits an agenda file, find the next one in the list.
18461 If the current buffer does not, find the first agenda file."
18462 (interactive)
18463 (let* ((fs (or (org-agenda-files t)
18464 (user-error "No agenda files")))
18465 (files (copy-sequence fs))
18466 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18467 file)
18468 (when tcf
18469 (while (and (setq file (pop files))
18470 (not (equal (file-truename file) tcf)))))
18471 (find-file (car (or files fs)))
18472 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18474 (defun org-agenda-file-to-front (&optional to-end)
18475 "Move/add the current file to the top of the agenda file list.
18476 If the file is not present in the list, it is added to the front. If it is
18477 present, it is moved there. With optional argument TO-END, add/move to the
18478 end of the list."
18479 (interactive "P")
18480 (let ((org-agenda-skip-unavailable-files nil)
18481 (file-alist (mapcar (lambda (x)
18482 (cons (file-truename x) x))
18483 (org-agenda-files t)))
18484 (ctf (file-truename
18485 (or buffer-file-name
18486 (user-error "Please save the current buffer to a file"))))
18487 x had)
18488 (setq x (assoc ctf file-alist) had x)
18490 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18491 (if to-end
18492 (setq file-alist (append (delq x file-alist) (list x)))
18493 (setq file-alist (cons x (delq x file-alist))))
18494 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18495 (org-install-agenda-files-menu)
18496 (message "File %s to %s of agenda file list"
18497 (if had "moved" "added") (if to-end "end" "front"))))
18499 (defun org-remove-file (&optional file)
18500 "Remove current file from the list of files in variable `org-agenda-files'.
18501 These are the files which are being checked for agenda entries.
18502 Optional argument FILE means use this file instead of the current."
18503 (interactive)
18504 (let* ((org-agenda-skip-unavailable-files nil)
18505 (file (or file buffer-file-name
18506 (user-error "Current buffer does not visit a file")))
18507 (true-file (file-truename file))
18508 (afile (abbreviate-file-name file))
18509 (files (delq nil (mapcar
18510 (lambda (x)
18511 (unless (equal true-file
18512 (file-truename x))
18514 (org-agenda-files t)))))
18515 (if (not (= (length files) (length (org-agenda-files t))))
18516 (progn
18517 (org-store-new-agenda-file-list files)
18518 (org-install-agenda-files-menu)
18519 (message "Removed from Org Agenda list: %s" afile))
18520 (message "File was not in list: %s (not removed)" afile))))
18522 (defun org-file-menu-entry (file)
18523 (vector file (list 'find-file file) t))
18525 (defun org-check-agenda-file (file)
18526 "Make sure FILE exists. If not, ask user what to do."
18527 (unless (file-exists-p file)
18528 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18529 (abbreviate-file-name file))
18530 (let ((r (downcase (read-char-exclusive))))
18531 (cond
18532 ((equal r ?r)
18533 (org-remove-file file)
18534 (throw 'nextfile t))
18535 (t (user-error "Abort"))))))
18537 (defun org-get-agenda-file-buffer (file)
18538 "Get an agenda buffer visiting FILE.
18539 If the buffer needs to be created, add it to the list of buffers
18540 which might be released later."
18541 (let ((buf (org-find-base-buffer-visiting file)))
18542 (if buf
18543 buf ; just return it
18544 ;; Make a new buffer and remember it
18545 (setq buf (find-file-noselect file))
18546 (when buf (push buf org-agenda-new-buffers))
18547 buf)))
18549 (defun org-release-buffers (blist)
18550 "Release all buffers in list, asking the user for confirmation when needed.
18551 When a buffer is unmodified, it is just killed. When modified, it is saved
18552 \(if the user agrees) and then killed."
18553 (let (file)
18554 (dolist (buf blist)
18555 (setq file (buffer-file-name buf))
18556 (when (and (buffer-modified-p buf)
18557 file
18558 (y-or-n-p (format "Save file %s? " file)))
18559 (with-current-buffer buf (save-buffer)))
18560 (kill-buffer buf))))
18562 (defun org-agenda-prepare-buffers (files)
18563 "Create buffers for all agenda files, protect archived trees and comments."
18564 (interactive)
18565 (let ((pa '(:org-archived t))
18566 (pc '(:org-comment t))
18567 (pall '(:org-archived t :org-comment t))
18568 (inhibit-read-only t)
18569 (org-inhibit-startup org-agenda-inhibit-startup)
18570 (rea (concat ":" org-archive-tag ":"))
18571 re pos)
18572 (setq org-tag-alist-for-agenda nil
18573 org-tag-groups-alist-for-agenda nil)
18574 (save-excursion
18575 (save-restriction
18576 (dolist (file files)
18577 (catch 'nextfile
18578 (if (bufferp file)
18579 (set-buffer file)
18580 (org-check-agenda-file file)
18581 (set-buffer (org-get-agenda-file-buffer file)))
18582 (widen)
18583 (org-set-regexps-and-options 'tags-only)
18584 (setq pos (point))
18585 (or (memq 'category org-agenda-ignore-properties)
18586 (org-refresh-category-properties))
18587 (or (memq 'stats org-agenda-ignore-properties)
18588 (org-refresh-stats-properties))
18589 (or (memq 'effort org-agenda-ignore-properties)
18590 (org-refresh-effort-properties))
18591 (or (memq 'appt org-agenda-ignore-properties)
18592 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18593 (setq org-todo-keywords-for-agenda
18594 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18595 (setq org-done-keywords-for-agenda
18596 (append org-done-keywords-for-agenda org-done-keywords))
18597 (setq org-todo-keyword-alist-for-agenda
18598 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18599 (setq org-tag-alist-for-agenda
18600 (org-uniquify
18601 (append org-tag-alist-for-agenda
18602 org-current-tag-alist)))
18603 ;; Merge current file's tag groups into global
18604 ;; `org-tag-groups-alist-for-agenda'.
18605 (when org-group-tags
18606 (dolist (alist org-tag-groups-alist)
18607 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18608 (if old
18609 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18610 (push alist org-tag-groups-alist-for-agenda)))))
18611 (org-with-silent-modifications
18612 (save-excursion
18613 (remove-text-properties (point-min) (point-max) pall)
18614 (when org-agenda-skip-archived-trees
18615 (goto-char (point-min))
18616 (while (re-search-forward rea nil t)
18617 (when (org-at-heading-p t)
18618 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18619 (goto-char (point-min))
18620 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18621 (while (re-search-forward re nil t)
18622 (when (save-match-data (org-in-commented-heading-p t))
18623 (add-text-properties
18624 (match-beginning 0) (org-end-of-subtree t) pc)))))
18625 (goto-char pos)))))
18626 (setq org-todo-keywords-for-agenda
18627 (org-uniquify org-todo-keywords-for-agenda))
18628 (setq org-todo-keyword-alist-for-agenda
18629 (org-uniquify org-todo-keyword-alist-for-agenda))))
18632 ;;;; CDLaTeX minor mode
18634 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18635 "Keymap for the minor `org-cdlatex-mode'.")
18637 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18638 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18639 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18640 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18641 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18643 (defvar org-cdlatex-texmathp-advice-is-done nil
18644 "Flag remembering if we have applied the advice to texmathp already.")
18646 (define-minor-mode org-cdlatex-mode
18647 "Toggle the minor `org-cdlatex-mode'.
18648 This mode supports entering LaTeX environment and math in LaTeX fragments
18649 in Org mode.
18650 \\{org-cdlatex-mode-map}"
18651 nil " OCDL" nil
18652 (when org-cdlatex-mode
18653 (require 'cdlatex)
18654 (run-hooks 'cdlatex-mode-hook)
18655 (cdlatex-compute-tables))
18656 (unless org-cdlatex-texmathp-advice-is-done
18657 (setq org-cdlatex-texmathp-advice-is-done t)
18658 (defadvice texmathp (around org-math-always-on activate)
18659 "Always return t in Org buffers.
18660 This is because we want to insert math symbols without dollars even outside
18661 the LaTeX math segments. If Org mode thinks that point is actually inside
18662 an embedded LaTeX fragment, let `texmathp' do its job.
18663 `\\[org-cdlatex-mode-map]'"
18664 (interactive)
18665 (let (p)
18666 (cond
18667 ((not (derived-mode-p 'org-mode)) ad-do-it)
18668 ((eq this-command 'cdlatex-math-symbol)
18669 (setq ad-return-value t
18670 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18672 (let ((p (org-inside-LaTeX-fragment-p)))
18673 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18674 (setq ad-return-value t
18675 texmathp-why '("Org mode embedded math" . 0))
18676 (when p ad-do-it)))))))))
18678 (defun turn-on-org-cdlatex ()
18679 "Unconditionally turn on `org-cdlatex-mode'."
18680 (org-cdlatex-mode 1))
18682 (defun org-try-cdlatex-tab ()
18683 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18684 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18685 - inside a LaTeX fragment, or
18686 - after the first word in a line, where an abbreviation expansion could
18687 insert a LaTeX environment."
18688 (when org-cdlatex-mode
18689 (cond
18690 ;; Before any word on the line: No expansion possible.
18691 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18692 ;; Just after first word on the line: Expand it. Make sure it
18693 ;; cannot happen on headlines, though.
18694 ((save-excursion
18695 (skip-chars-backward "a-zA-Z0-9*")
18696 (skip-chars-backward " \t")
18697 (and (bolp) (not (org-at-heading-p))))
18698 (cdlatex-tab) t)
18699 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18701 (defun org-cdlatex-underscore-caret (&optional _arg)
18702 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18703 Revert to the normal definition outside of these fragments."
18704 (interactive "P")
18705 (if (org-inside-LaTeX-fragment-p)
18706 (call-interactively 'cdlatex-sub-superscript)
18707 (let (org-cdlatex-mode)
18708 (call-interactively (key-binding (vector last-input-event))))))
18710 (defun org-cdlatex-math-modify (&optional _arg)
18711 "Execute `cdlatex-math-modify' in LaTeX fragments.
18712 Revert to the normal definition outside of these fragments."
18713 (interactive "P")
18714 (if (org-inside-LaTeX-fragment-p)
18715 (call-interactively 'cdlatex-math-modify)
18716 (let (org-cdlatex-mode)
18717 (call-interactively (key-binding (vector last-input-event))))))
18719 (defun org-cdlatex-environment-indent (&optional environment item)
18720 "Execute `cdlatex-environment' and indent the inserted environment.
18722 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18724 The inserted environment is indented to current indentation
18725 unless point is at the beginning of the line, in which the
18726 environment remains unintended."
18727 (interactive)
18728 ;; cdlatex-environment always return nil. Therefore, capture output
18729 ;; first and determine if an environment was selected.
18730 (let* ((beg (point-marker))
18731 (end (copy-marker (point) t))
18732 (inserted (progn
18733 (ignore-errors (cdlatex-environment environment item))
18734 (< beg end)))
18735 ;; Figure out how many lines to move forward after the
18736 ;; environment has been inserted.
18737 (lines (when inserted
18738 (save-excursion
18739 (- (cl-loop while (< beg (point))
18740 with x = 0
18741 do (forward-line -1)
18742 (cl-incf x)
18743 finally return x)
18744 (if (progn (goto-char beg)
18745 (and (progn (skip-chars-forward " \t") (eolp))
18746 (progn (skip-chars-backward " \t") (bolp))))
18747 1 0)))))
18748 (env (org-trim (delete-and-extract-region beg end))))
18749 (when inserted
18750 ;; Get indentation of next line unless at column 0.
18751 (let ((ind (if (bolp) 0
18752 (save-excursion
18753 (org-return-indent)
18754 (prog1 (org-get-indentation)
18755 (when (progn (skip-chars-forward " \t") (eolp))
18756 (delete-region beg (point)))))))
18757 (bol (progn (skip-chars-backward " \t") (bolp))))
18758 ;; Insert a newline before environment unless at column zero
18759 ;; to "escape" the current line. Insert a newline if
18760 ;; something is one the same line as \end{ENVIRONMENT}.
18761 (insert
18762 (concat (unless bol "\n") env
18763 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18764 (unless (zerop ind)
18765 (save-excursion
18766 (goto-char beg)
18767 (while (< (point) end)
18768 (unless (eolp) (indent-line-to ind))
18769 (forward-line))))
18770 (goto-char beg)
18771 (forward-line lines)
18772 (indent-line-to ind)))
18773 (set-marker beg nil)
18774 (set-marker end nil)))
18777 ;;;; LaTeX fragments
18779 (defun org-inside-LaTeX-fragment-p ()
18780 "Test if point is inside a LaTeX fragment.
18781 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18782 sequence appearing also before point.
18783 Even though the matchers for math are configurable, this function assumes
18784 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18785 delimiters are skipped when they have been removed by customization.
18786 The return value is nil, or a cons cell with the delimiter and the
18787 position of this delimiter.
18789 This function does a reasonably good job, but can locally be fooled by
18790 for example currency specifications. For example it will assume being in
18791 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18792 fragments that are properly closed, but during editing, we have to live
18793 with the uncertainty caused by missing closing delimiters. This function
18794 looks only before point, not after."
18795 (catch 'exit
18796 (let ((pos (point))
18797 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18798 (lim (progn
18799 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18800 (point)))
18801 dd-on str (start 0) m re)
18802 (goto-char pos)
18803 (when dodollar
18804 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18805 re (nth 1 (assoc "$" org-latex-regexps)))
18806 (while (string-match re str start)
18807 (cond
18808 ((= (match-end 0) (length str))
18809 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18810 ((= (match-end 0) (- (length str) 5))
18811 (throw 'exit nil))
18812 (t (setq start (match-end 0))))))
18813 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18814 (goto-char pos)
18815 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18816 (and (match-beginning 2) (throw 'exit nil))
18817 ;; count $$
18818 (while (re-search-backward "\\$\\$" lim t)
18819 (setq dd-on (not dd-on)))
18820 (goto-char pos)
18821 (when dd-on (cons "$$" m))))))
18823 (defun org-inside-latex-macro-p ()
18824 "Is point inside a LaTeX macro or its arguments?"
18825 (save-match-data
18826 (org-in-regexp
18827 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18829 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18830 "Build an overlay between BEG and END using IMAGE file.
18831 Argument IMAGETYPE is the extension of the displayed image,
18832 as a string. It defaults to \"png\"."
18833 (let ((ov (make-overlay beg end))
18834 (imagetype (or (intern imagetype) 'png)))
18835 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18836 (overlay-put ov 'evaporate t)
18837 (overlay-put ov
18838 'modification-hooks
18839 (list (lambda (o _flag _beg _end &optional _l)
18840 (delete-overlay o))))
18841 (overlay-put ov
18842 'display
18843 (list 'image :type imagetype :file image :ascent 'center))))
18845 (defun org--list-latex-overlays (&optional beg end)
18846 "List all Org LaTeX overlays in current buffer.
18847 Limit to overlays between BEG and END when those are provided."
18848 (cl-remove-if-not
18849 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18850 (overlays-in (or beg (point-min)) (or end (point-max)))))
18852 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18853 "Remove all overlays with LaTeX fragment images in current buffer.
18854 When optional arguments BEG and END are non-nil, remove all
18855 overlays between them instead. Return a non-nil value when some
18856 overlays were removed, nil otherwise."
18857 (let ((overlays (org--list-latex-overlays beg end)))
18858 (mapc #'delete-overlay overlays)
18859 overlays))
18861 (defun org-toggle-latex-fragment (&optional arg)
18862 "Preview the LaTeX fragment at point, or all locally or globally.
18864 If the cursor is on a LaTeX fragment, create the image and overlay
18865 it over the source code, if there is none. Remove it otherwise.
18866 If there is no fragment at point, display all fragments in the
18867 current section.
18869 With prefix ARG, preview or clear image for all fragments in the
18870 current subtree or in the whole buffer when used before the first
18871 headline. With a prefix ARG `\\[universal-argument] \
18872 \\[universal-argument]' preview or clear images
18873 for all fragments in the buffer."
18874 (interactive "P")
18875 (when (display-graphic-p)
18876 (catch 'exit
18877 (save-excursion
18878 (let (beg end msg)
18879 (cond
18880 ((or (equal arg '(16))
18881 (and (equal arg '(4))
18882 (org-with-limited-levels (org-before-first-heading-p))))
18883 (if (org-remove-latex-fragment-image-overlays)
18884 (progn (message "LaTeX fragments images removed from buffer")
18885 (throw 'exit nil))
18886 (setq msg "Creating images for buffer...")))
18887 ((equal arg '(4))
18888 (org-with-limited-levels (org-back-to-heading t))
18889 (setq beg (point))
18890 (setq end (progn (org-end-of-subtree t) (point)))
18891 (if (org-remove-latex-fragment-image-overlays beg end)
18892 (progn
18893 (message "LaTeX fragment images removed from subtree")
18894 (throw 'exit nil))
18895 (setq msg "Creating images for subtree...")))
18896 ((let ((datum (org-element-context)))
18897 (when (memq (org-element-type datum)
18898 '(latex-environment latex-fragment))
18899 (setq beg (org-element-property :begin datum))
18900 (setq end (org-element-property :end datum))
18901 (if (org-remove-latex-fragment-image-overlays beg end)
18902 (progn (message "LaTeX fragment image removed")
18903 (throw 'exit nil))
18904 (setq msg "Creating image...")))))
18906 (org-with-limited-levels
18907 (setq beg (if (org-at-heading-p) (line-beginning-position)
18908 (outline-previous-heading)
18909 (point)))
18910 (setq end (progn (outline-next-heading) (point)))
18911 (if (org-remove-latex-fragment-image-overlays beg end)
18912 (progn
18913 (message "LaTeX fragment images removed from section")
18914 (throw 'exit nil))
18915 (setq msg "Creating images for section...")))))
18916 (let ((file (buffer-file-name (buffer-base-buffer))))
18917 (org-format-latex
18918 (concat org-preview-latex-image-directory "org-ltximg")
18919 beg end
18920 ;; Emacs cannot overlay images from remote hosts. Create
18921 ;; it in `temporary-file-directory' instead.
18922 (if (or (not file) (file-remote-p file))
18923 temporary-file-directory
18924 default-directory)
18925 'overlays msg 'forbuffer org-preview-latex-default-process))
18926 (message (concat msg "done")))))))
18928 (defun org-format-latex
18929 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18930 "Replace LaTeX fragments with links to an image.
18932 The function takes care of creating the replacement image.
18934 Only consider fragments between BEG and END when those are
18935 provided.
18937 When optional argument OVERLAYS is non-nil, display the image on
18938 top of the fragment instead of replacing it.
18940 PROCESSING-TYPE is the conversion method to use, as a symbol.
18942 Some of the options can be changed using the variable
18943 `org-format-latex-options', which see."
18944 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18945 (unless (eq processing-type 'verbatim)
18946 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18947 (cnt 0)
18948 checkdir-flag)
18949 (goto-char (or beg (point-min)))
18950 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18951 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18952 (overlay-recenter (or end (point-max))))
18953 (while (re-search-forward math-regexp end t)
18954 (unless (and overlays
18955 (eq (get-char-property (point) 'org-overlay-type)
18956 'org-latex-overlay))
18957 (let* ((context (org-element-context))
18958 (type (org-element-type context)))
18959 (when (memq type '(latex-environment latex-fragment))
18960 (let ((block-type (eq type 'latex-environment))
18961 (value (org-element-property :value context))
18962 (beg (org-element-property :begin context))
18963 (end (save-excursion
18964 (goto-char (org-element-property :end context))
18965 (skip-chars-backward " \r\t\n")
18966 (point))))
18967 (cond
18968 ((eq processing-type 'mathjax)
18969 ;; Prepare for MathJax processing.
18970 (if (not (string-match "\\`\\$\\$?" value))
18971 (goto-char end)
18972 (delete-region beg end)
18973 (if (string= (match-string 0 value) "$$")
18974 (insert "\\[" (substring value 2 -2) "\\]")
18975 (insert "\\(" (substring value 1 -1) "\\)"))))
18976 ((assq processing-type org-preview-latex-process-alist)
18977 ;; Process to an image.
18978 (cl-incf cnt)
18979 (goto-char beg)
18980 (let* ((processing-info
18981 (cdr (assq processing-type org-preview-latex-process-alist)))
18982 (face (face-at-point))
18983 ;; Get the colors from the face at point.
18985 (let ((color (plist-get org-format-latex-options
18986 :foreground)))
18987 (if (and forbuffer (eq color 'auto))
18988 (face-attribute face :foreground nil 'default)
18989 color)))
18991 (let ((color (plist-get org-format-latex-options
18992 :background)))
18993 (if (and forbuffer (eq color 'auto))
18994 (face-attribute face :background nil 'default)
18995 color)))
18996 (hash (sha1 (prin1-to-string
18997 (list org-format-latex-header
18998 org-latex-default-packages-alist
18999 org-latex-packages-alist
19000 org-format-latex-options
19001 forbuffer value fg bg))))
19002 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19003 (absprefix (expand-file-name prefix dir))
19004 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19005 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19006 (sep (and block-type "\n\n"))
19007 (link (concat sep "[[file:" linkfile "]]" sep))
19008 (options
19009 (org-combine-plists
19010 org-format-latex-options
19011 `(:foreground ,fg :background ,bg))))
19012 (when msg (message msg cnt))
19013 (unless checkdir-flag ; Ensure the directory exists.
19014 (setq checkdir-flag t)
19015 (let ((todir (file-name-directory absprefix)))
19016 (unless (file-directory-p todir)
19017 (make-directory todir t))))
19018 (unless (file-exists-p movefile)
19019 (org-create-formula-image
19020 value movefile options forbuffer processing-type))
19021 (if overlays
19022 (progn
19023 (dolist (o (overlays-in beg end))
19024 (when (eq (overlay-get o 'org-overlay-type)
19025 'org-latex-overlay)
19026 (delete-overlay o)))
19027 (org--format-latex-make-overlay beg end movefile imagetype)
19028 (goto-char end))
19029 (delete-region beg end)
19030 (insert
19031 (org-add-props link
19032 (list 'org-latex-src
19033 (replace-regexp-in-string "\"" "" value)
19034 'org-latex-src-embed-type
19035 (if block-type 'paragraph 'character)))))))
19036 ((eq processing-type 'mathml)
19037 ;; Process to MathML.
19038 (unless (org-format-latex-mathml-available-p)
19039 (user-error "LaTeX to MathML converter not configured"))
19040 (cl-incf cnt)
19041 (when msg (message msg cnt))
19042 (goto-char beg)
19043 (delete-region beg end)
19044 (insert (org-format-latex-as-mathml
19045 value block-type prefix dir)))
19047 (error "Unknown conversion process %s for LaTeX fragments"
19048 processing-type)))))))))))
19050 (defun org-create-math-formula (latex-frag &optional mathml-file)
19051 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19052 Use `org-latex-to-mathml-convert-command'. If the conversion is
19053 sucessful, return the portion between \"<math...> </math>\"
19054 elements otherwise return nil. When MATHML-FILE is specified,
19055 write the results in to that file. When invoked as an
19056 interactive command, prompt for LATEX-FRAG, with initial value
19057 set to the current active region and echo the results for user
19058 inspection."
19059 (interactive (list (let ((frag (when (org-region-active-p)
19060 (buffer-substring-no-properties
19061 (region-beginning) (region-end)))))
19062 (read-string "LaTeX Fragment: " frag nil frag))))
19063 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19064 (let* ((tmp-in-file
19065 (let ((file (file-relative-name
19066 (make-temp-name (expand-file-name "ltxmathml-in")))))
19067 (write-region latex-frag nil file)
19068 file))
19069 (tmp-out-file (file-relative-name
19070 (make-temp-name (expand-file-name "ltxmathml-out"))))
19071 (cmd (format-spec
19072 org-latex-to-mathml-convert-command
19073 `((?j . ,(and org-latex-to-mathml-jar-file
19074 (shell-quote-argument
19075 (expand-file-name
19076 org-latex-to-mathml-jar-file))))
19077 (?I . ,(shell-quote-argument tmp-in-file))
19078 (?i . ,latex-frag)
19079 (?o . ,(shell-quote-argument tmp-out-file)))))
19080 mathml shell-command-output)
19081 (when (called-interactively-p 'any)
19082 (unless (org-format-latex-mathml-available-p)
19083 (user-error "LaTeX to MathML converter not configured")))
19084 (message "Running %s" cmd)
19085 (setq shell-command-output (shell-command-to-string cmd))
19086 (setq mathml
19087 (when (file-readable-p tmp-out-file)
19088 (with-current-buffer (find-file-noselect tmp-out-file t)
19089 (goto-char (point-min))
19090 (when (re-search-forward
19091 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19092 (regexp-quote
19093 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19094 nil t)
19095 (prog1 (match-string 0) (kill-buffer))))))
19096 (cond
19097 (mathml
19098 (setq mathml
19099 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19100 (when mathml-file
19101 (write-region mathml nil mathml-file))
19102 (when (called-interactively-p 'any)
19103 (message mathml)))
19104 ((message "LaTeX to MathML conversion failed")
19105 (message shell-command-output)))
19106 (delete-file tmp-in-file)
19107 (when (file-exists-p tmp-out-file)
19108 (delete-file tmp-out-file))
19109 mathml))
19111 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19112 prefix &optional dir)
19113 "Use `org-create-math-formula' but check local cache first."
19114 (let* ((absprefix (expand-file-name prefix dir))
19115 (print-length nil) (print-level nil)
19116 (formula-id (concat
19117 "formula-"
19118 (sha1
19119 (prin1-to-string
19120 (list latex-frag
19121 org-latex-to-mathml-convert-command)))))
19122 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19123 (formula-cache-dir (file-name-directory formula-cache)))
19125 (unless (file-directory-p formula-cache-dir)
19126 (make-directory formula-cache-dir t))
19128 (unless (file-exists-p formula-cache)
19129 (org-create-math-formula latex-frag formula-cache))
19131 (if (file-exists-p formula-cache)
19132 ;; Successful conversion. Return the link to MathML file.
19133 (org-add-props
19134 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19135 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19136 'org-latex-src-embed-type (if latex-frag-type
19137 'paragraph 'character)))
19138 ;; Failed conversion. Return the LaTeX fragment verbatim
19139 latex-frag)))
19141 (defun org--get-display-dpi ()
19142 "Get the DPI of the display.
19143 The function assumes that the display has the same pixel width in
19144 the horizontal and vertical directions."
19145 (if (display-graphic-p)
19146 (round (/ (display-pixel-height)
19147 (/ (display-mm-height) 25.4)))
19148 (error "Attempt to calculate the dpi of a non-graphic display")))
19150 (defun org-create-formula-image
19151 (string tofile options buffer &optional processing-type)
19152 "Create an image from LaTeX source using external processes.
19154 The LaTeX STRING is saved to a temporary LaTeX file, then
19155 converted to an image file by process PROCESSING-TYPE defined in
19156 `org-preview-latex-process-alist'. A nil value defaults to
19157 `org-preview-latex-default-process'.
19159 The generated image file is eventually moved to TOFILE.
19161 The OPTIONS argument controls the size, foreground color and
19162 background color of the generated image.
19164 When BUFFER non-nil, this function is used for LaTeX previewing.
19165 Otherwise, it is used to deal with LaTeX snippets showed in
19166 a HTML file."
19167 (let* ((processing-type (or processing-type
19168 org-preview-latex-default-process))
19169 (processing-info
19170 (cdr (assq processing-type org-preview-latex-process-alist)))
19171 (programs (plist-get processing-info :programs))
19172 (error-message (or (plist-get processing-info :message) ""))
19173 (use-xcolor (plist-get processing-info :use-xcolor))
19174 (image-input-type (plist-get processing-info :image-input-type))
19175 (image-output-type (plist-get processing-info :image-output-type))
19176 (post-clean (or (plist-get processing-info :post-clean)
19177 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19178 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19179 (latex-header
19180 (or (plist-get processing-info :latex-header)
19181 (org-latex-make-preamble
19182 (org-export-get-environment (org-export-get-backend 'latex))
19183 org-format-latex-header
19184 'snippet)))
19185 (latex-compiler (plist-get processing-info :latex-compiler))
19186 (image-converter (plist-get processing-info :image-converter))
19187 (tmpdir temporary-file-directory)
19188 (texfilebase (make-temp-name
19189 (expand-file-name "orgtex" tmpdir)))
19190 (texfile (concat texfilebase ".tex"))
19191 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19192 '(1.0 . 1.0)))
19193 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19194 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19195 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19196 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19197 "Black"))
19198 (bg (or (plist-get options (if buffer :background :html-background))
19199 "Transparent"))
19200 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19201 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19202 (dolist (program programs)
19203 (org-check-external-command program error-message))
19204 (if use-xcolor
19205 (progn (if (eq fg 'default)
19206 (setq fg (org-latex-color :foreground))
19207 (setq fg (org-latex-color-format fg)))
19208 (if (eq bg 'default)
19209 (setq bg (org-latex-color :background))
19210 (setq bg (org-latex-color-format
19211 (if (string= bg "Transparent") "white" bg))))
19212 (with-temp-file texfile
19213 (insert latex-header)
19214 (insert "\n\\begin{document}\n"
19215 "\\definecolor{fg}{rgb}{" fg "}\n"
19216 "\\definecolor{bg}{rgb}{" bg "}\n"
19217 "\n\\pagecolor{bg}\n"
19218 "\n{\\color{fg}\n"
19219 string
19220 "\n}\n"
19221 "\n\\end{document}\n")))
19222 (if (eq fg 'default)
19223 (setq fg (org-dvipng-color :foreground))
19224 (unless (string= fg "Transparent")
19225 (setq fg (org-dvipng-color-format fg))))
19226 (if (eq bg 'default)
19227 (setq bg (org-dvipng-color :background))
19228 (unless (string= bg "Transparent")
19229 (setq bg (org-dvipng-color-format bg))))
19230 (with-temp-file texfile
19231 (insert latex-header)
19232 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19234 (let* ((err-msg (format "Please adjust '%s' part of \
19235 `org-preview-latex-process-alist'."
19236 processing-type))
19237 (image-input-file
19238 (org-compile-file
19239 texfile latex-compiler image-input-type err-msg log-buf))
19240 (image-output-file
19241 (org-compile-file
19242 image-input-file image-converter image-output-type err-msg log-buf
19243 `((?F . ,(shell-quote-argument fg))
19244 (?B . ,(shell-quote-argument bg))
19245 (?D . ,(shell-quote-argument (format "%s" dpi)))
19246 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19247 (copy-file image-output-file tofile 'replace)
19248 (dolist (e post-clean)
19249 (when (file-exists-p (concat texfilebase e))
19250 (delete-file (concat texfilebase e))))
19251 image-output-file)))
19253 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19254 "Fill a LaTeX header template TPL.
19255 In the template, the following place holders will be recognized:
19257 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19258 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19259 [PACKAGES] \\usepackage statements for PKG
19260 [NO-PACKAGES] do not include PKG
19261 [EXTRA] the string EXTRA
19262 [NO-EXTRA] do not include EXTRA
19264 For backward compatibility, if both the positive and the negative place
19265 holder is missing, the positive one (without the \"NO-\") will be
19266 assumed to be present at the end of the template.
19267 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19268 EXTRA is a string.
19269 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19270 (let (rpl (end ""))
19271 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19272 (setq rpl (if (or (match-end 1) (not def-pkg))
19273 "" (org-latex-packages-to-string def-pkg snippets-p t))
19274 tpl (replace-match rpl t t tpl))
19275 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19277 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19278 (setq rpl (if (or (match-end 1) (not pkg))
19279 "" (org-latex-packages-to-string pkg snippets-p t))
19280 tpl (replace-match rpl t t tpl))
19281 (when pkg (setq end
19282 (concat end "\n"
19283 (org-latex-packages-to-string pkg snippets-p)))))
19285 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19286 (setq rpl (if (or (match-end 1) (not extra))
19287 "" (concat extra "\n"))
19288 tpl (replace-match rpl t t tpl))
19289 (when (and extra (string-match "\\S-" extra))
19290 (setq end (concat end "\n" extra))))
19292 (if (string-match "\\S-" end)
19293 (concat tpl "\n" end)
19294 tpl)))
19296 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19297 "Turn an alist of packages into a string with the \\usepackage macros."
19298 (setq pkg (mapconcat (lambda(p)
19299 (cond
19300 ((stringp p) p)
19301 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19302 (format "%% Package %s omitted" (cadr p)))
19303 ((equal "" (car p))
19304 (format "\\usepackage{%s}" (cadr p)))
19306 (format "\\usepackage[%s]{%s}"
19307 (car p) (cadr p)))))
19309 "\n"))
19310 (if newline (concat pkg "\n") pkg))
19312 (defun org-dvipng-color (attr)
19313 "Return a RGB color specification for dvipng."
19314 (org-dvipng-color-format (face-attribute 'default attr nil)))
19316 (defun org-dvipng-color-format (color-name)
19317 "Convert COLOR-NAME to a RGB color value for dvipng."
19318 (apply #'format "rgb %s %s %s"
19319 (mapcar 'org-normalize-color
19320 (color-values color-name))))
19322 (defun org-latex-color (attr)
19323 "Return a RGB color for the LaTeX color package."
19324 (org-latex-color-format (face-attribute 'default attr nil)))
19326 (defun org-latex-color-format (color-name)
19327 "Convert COLOR-NAME to a RGB color value."
19328 (apply #'format "%s,%s,%s"
19329 (mapcar 'org-normalize-color
19330 (color-values color-name))))
19332 (defun org-normalize-color (value)
19333 "Return string to be used as color value for an RGB component."
19334 (format "%g" (/ value 65535.0)))
19338 ;; Image display
19340 (defvar-local org-inline-image-overlays nil)
19342 (defun org-toggle-inline-images (&optional include-linked)
19343 "Toggle the display of inline images.
19344 INCLUDE-LINKED is passed to `org-display-inline-images'."
19345 (interactive "P")
19346 (if org-inline-image-overlays
19347 (progn
19348 (org-remove-inline-images)
19349 (when (called-interactively-p 'interactive)
19350 (message "Inline image display turned off")))
19351 (org-display-inline-images include-linked)
19352 (when (called-interactively-p 'interactive)
19353 (message (if org-inline-image-overlays
19354 (format "%d images displayed inline"
19355 (length org-inline-image-overlays))
19356 "No images to display inline")))))
19358 (defun org-redisplay-inline-images ()
19359 "Refresh the display of inline images."
19360 (interactive)
19361 (if (not org-inline-image-overlays)
19362 (org-toggle-inline-images)
19363 (org-toggle-inline-images)
19364 (org-toggle-inline-images)))
19366 (defun org-display-inline-images (&optional include-linked refresh beg end)
19367 "Display inline images.
19369 An inline image is a link which follows either of these
19370 conventions:
19372 1. Its path is a file with an extension matching return value
19373 from `image-file-name-regexp' and it has no contents.
19375 2. Its description consists in a single link of the previous
19376 type.
19378 When optional argument INCLUDE-LINKED is non-nil, also links with
19379 a text description part will be inlined. This can be nice for
19380 a quick look at those images, but it does not reflect what
19381 exported files will look like.
19383 When optional argument REFRESH is non-nil, refresh existing
19384 images between BEG and END. This will create new image displays
19385 only if necessary. BEG and END default to the buffer
19386 boundaries."
19387 (interactive "P")
19388 (when (display-graphic-p)
19389 (unless refresh
19390 (org-remove-inline-images)
19391 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19392 (org-with-wide-buffer
19393 (goto-char (or beg (point-min)))
19394 (let ((case-fold-search t)
19395 (file-extension-re (image-file-name-regexp)))
19396 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19397 (let ((link (save-match-data (org-element-context))))
19398 ;; Check if we're at an inline image.
19399 (when (and (equal (org-element-property :type link) "file")
19400 (or include-linked
19401 (not (org-element-property :contents-begin link)))
19402 (let ((parent (org-element-property :parent link)))
19403 (or (not (eq (org-element-type parent) 'link))
19404 (not (cdr (org-element-contents parent)))))
19405 (string-match-p file-extension-re
19406 (org-element-property :path link)))
19407 (let ((file (expand-file-name
19408 (org-link-unescape
19409 (org-element-property :path link)))))
19410 (when (file-exists-p file)
19411 (let ((width
19412 ;; Apply `org-image-actual-width' specifications.
19413 (cond
19414 ((not (image-type-available-p 'imagemagick)) nil)
19415 ((eq org-image-actual-width t) nil)
19416 ((listp org-image-actual-width)
19418 ;; First try to find a width among
19419 ;; attributes associated to the paragraph
19420 ;; containing link.
19421 (let ((paragraph
19422 (let ((e link))
19423 (while (and (setq e (org-element-property
19424 :parent e))
19425 (not (eq (org-element-type e)
19426 'paragraph))))
19427 e)))
19428 (when paragraph
19429 (save-excursion
19430 (goto-char (org-element-property :begin paragraph))
19431 (when
19432 (re-search-forward
19433 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19434 (org-element-property
19435 :post-affiliated paragraph)
19437 (string-to-number (match-string 1))))))
19438 ;; Otherwise, fall-back to provided number.
19439 (car org-image-actual-width)))
19440 ((numberp org-image-actual-width)
19441 org-image-actual-width)))
19442 (old (get-char-property-and-overlay
19443 (org-element-property :begin link)
19444 'org-image-overlay)))
19445 (if (and (car-safe old) refresh)
19446 (image-refresh (overlay-get (cdr old) 'display))
19447 (let ((image (create-image file
19448 (and width 'imagemagick)
19450 :width width)))
19451 (when image
19452 (let* ((link
19453 ;; If inline image is the description
19454 ;; of another link, be sure to
19455 ;; consider the latter as the one to
19456 ;; apply the overlay on.
19457 (let ((parent
19458 (org-element-property :parent link)))
19459 (if (eq (org-element-type parent) 'link)
19460 parent
19461 link)))
19462 (ov (make-overlay
19463 (org-element-property :begin link)
19464 (progn
19465 (goto-char
19466 (org-element-property :end link))
19467 (skip-chars-backward " \t")
19468 (point)))))
19469 (overlay-put ov 'display image)
19470 (overlay-put ov 'face 'default)
19471 (overlay-put ov 'org-image-overlay t)
19472 (overlay-put
19473 ov 'modification-hooks
19474 (list 'org-display-inline-remove-overlay))
19475 (push ov org-inline-image-overlays)))))))))))))))
19477 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19478 "Remove inline-display overlay if a corresponding region is modified."
19479 (let ((inhibit-modification-hooks t))
19480 (when (and ov after)
19481 (delete ov org-inline-image-overlays)
19482 (delete-overlay ov))))
19484 (defun org-remove-inline-images ()
19485 "Remove inline display of images."
19486 (interactive)
19487 (mapc #'delete-overlay org-inline-image-overlays)
19488 (setq org-inline-image-overlays nil))
19490 ;;;; Key bindings
19492 ;; Outline functions from `outline-mode-prefix-map'
19493 ;; that can be remapped in Org:
19494 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19495 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19496 (define-key org-mode-map [remap outline-forward-same-level]
19497 'org-forward-heading-same-level)
19498 (define-key org-mode-map [remap outline-backward-same-level]
19499 'org-backward-heading-same-level)
19500 (define-key org-mode-map [remap outline-show-branches]
19501 'org-kill-note-or-show-branches)
19502 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19503 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19504 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19505 (define-key org-mode-map [remap outline-next-visible-heading]
19506 'org-next-visible-heading)
19507 (define-key org-mode-map [remap outline-previous-visible-heading]
19508 'org-previous-visible-heading)
19509 (define-key org-mode-map [remap show-children] 'org-show-children)
19511 ;; Outline functions from `outline-mode-prefix-map' that can not
19512 ;; be remapped in Org:
19514 ;; - the column "key binding" shows whether the Outline function is still
19515 ;; available in Org mode on the same key that it has been bound to in
19516 ;; Outline mode:
19517 ;; - "overridden": key used for a different functionality in Org mode
19518 ;; - else: key still bound to the same Outline function in Org mode
19520 ;; | Outline function | key binding | Org replacement |
19521 ;; |------------------------------------+-------------+--------------------------|
19522 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19523 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19524 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19525 ;; | `show-entry' | overridden | no replacement |
19526 ;; | `show-branches' | `C-c C-k' | still same function |
19527 ;; | `show-subtree' | overridden | visibility cycling |
19528 ;; | `show-all' | overridden | no replacement |
19529 ;; | `hide-subtree' | overridden | visibility cycling |
19530 ;; | `hide-body' | overridden | no replacement |
19531 ;; | `hide-entry' | overridden | visibility cycling |
19532 ;; | `hide-leaves' | overridden | no replacement |
19533 ;; | `hide-sublevels' | overridden | no replacement |
19534 ;; | `hide-other' | overridden | no replacement |
19536 ;; Make `C-c C-x' a prefix key
19537 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19539 ;; TAB key with modifiers
19540 (org-defkey org-mode-map "\C-i" 'org-cycle)
19541 (org-defkey org-mode-map [(tab)] 'org-cycle)
19542 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19543 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19544 ;; The following line is necessary under Suse GNU/Linux
19545 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19546 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19547 (define-key org-mode-map [backtab] 'org-shifttab)
19549 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19550 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19551 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19553 ;; Cursor keys with modifiers
19554 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19555 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19556 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19557 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19559 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19560 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19561 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19562 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19563 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19564 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19566 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19567 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19568 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19569 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19571 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19572 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19573 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19574 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19576 ;; Babel keys
19577 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19578 (dolist (pair org-babel-key-bindings)
19579 (define-key org-babel-map (car pair) (cdr pair)))
19581 ;;; Extra keys for tty access.
19582 ;; We only set them when really needed because otherwise the
19583 ;; menus don't show the simple keys
19585 (when (or org-use-extra-keys (not window-system))
19586 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19587 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19588 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19589 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19590 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19591 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19592 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19593 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19594 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19595 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19596 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19597 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19598 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19599 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19600 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19601 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19602 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19603 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19604 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19605 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19606 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19607 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19608 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19609 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19610 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19611 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19612 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19613 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19615 ;; All the other keys
19617 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19618 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19619 (if (boundp 'narrow-map)
19620 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19621 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19622 (if (boundp 'narrow-map)
19623 (org-defkey narrow-map "b" 'org-narrow-to-block)
19624 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19625 (if (boundp 'narrow-map)
19626 (org-defkey narrow-map "e" 'org-narrow-to-element)
19627 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19628 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19629 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19630 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19631 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19632 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19633 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19634 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19635 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19636 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19637 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19638 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19639 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19640 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19641 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19642 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19643 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19644 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19645 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19646 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19647 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19648 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19649 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19650 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19651 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19652 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19653 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19654 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19655 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19656 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19657 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19658 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19659 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19660 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19661 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19662 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19663 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19664 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19665 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19666 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19667 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19668 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19669 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19670 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19671 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19672 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19673 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19674 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19675 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19676 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19677 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19678 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19679 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19680 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19681 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19682 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19683 (org-defkey org-mode-map "\C-c^" 'org-sort)
19684 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19685 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19686 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19687 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19688 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19689 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19690 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19691 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19692 (org-defkey org-mode-map "\C-m" 'org-return)
19693 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19694 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19695 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19696 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19697 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19698 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19699 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19700 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19701 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19702 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19703 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19704 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19705 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19706 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19707 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19708 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19709 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19710 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19711 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19712 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19713 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19714 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19715 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19716 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19717 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19719 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19720 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19721 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19723 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19724 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19725 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19726 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19727 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19728 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19729 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19730 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19731 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19732 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19733 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19734 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19735 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19736 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19737 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19738 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19739 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19740 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19741 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19742 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19743 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19744 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19746 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19747 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19748 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19749 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19750 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19752 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19754 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19756 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19757 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19759 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19762 (defconst org-speed-commands-default
19764 ("Outline Navigation")
19765 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19766 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19767 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19768 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19769 ("F" . org-next-block)
19770 ("B" . org-previous-block)
19771 ("u" . (org-speed-move-safe 'outline-up-heading))
19772 ("j" . org-goto)
19773 ("g" . (org-refile t))
19774 ("Outline Visibility")
19775 ("c" . org-cycle)
19776 ("C" . org-shifttab)
19777 (" " . org-display-outline-path)
19778 ("s" . org-narrow-to-subtree)
19779 ("=" . org-columns)
19780 ("Outline Structure Editing")
19781 ("U" . org-metaup)
19782 ("D" . org-metadown)
19783 ("r" . org-metaright)
19784 ("l" . org-metaleft)
19785 ("R" . org-shiftmetaright)
19786 ("L" . org-shiftmetaleft)
19787 ("i" . (progn (forward-char 1) (call-interactively
19788 'org-insert-heading-respect-content)))
19789 ("^" . org-sort)
19790 ("w" . org-refile)
19791 ("a" . org-archive-subtree-default-with-confirmation)
19792 ("@" . org-mark-subtree)
19793 ("#" . org-toggle-comment)
19794 ("Clock Commands")
19795 ("I" . org-clock-in)
19796 ("O" . org-clock-out)
19797 ("Meta Data Editing")
19798 ("t" . org-todo)
19799 ("," . (org-priority))
19800 ("0" . (org-priority ?\ ))
19801 ("1" . (org-priority ?A))
19802 ("2" . (org-priority ?B))
19803 ("3" . (org-priority ?C))
19804 (":" . org-set-tags-command)
19805 ("e" . org-set-effort)
19806 ("E" . org-inc-effort)
19807 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19808 (org-entry-put (point) "APPT_WARNTIME" m)))
19809 ("Agenda Views etc")
19810 ("v" . org-agenda)
19811 ("/" . org-sparse-tree)
19812 ("Misc")
19813 ("o" . org-open-at-point)
19814 ("?" . org-speed-command-help)
19815 ("<" . (org-agenda-set-restriction-lock 'subtree))
19816 (">" . (org-agenda-remove-restriction-lock))
19818 "The default speed commands.")
19820 (defun org-print-speed-command (e)
19821 (if (> (length (car e)) 1)
19822 (progn
19823 (princ "\n")
19824 (princ (car e))
19825 (princ "\n")
19826 (princ (make-string (length (car e)) ?-))
19827 (princ "\n"))
19828 (princ (car e))
19829 (princ " ")
19830 (if (symbolp (cdr e))
19831 (princ (symbol-name (cdr e)))
19832 (prin1 (cdr e)))
19833 (princ "\n")))
19835 (defun org-speed-command-help ()
19836 "Show the available speed commands."
19837 (interactive)
19838 (if (not org-use-speed-commands)
19839 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19840 (with-output-to-temp-buffer "*Help*"
19841 (princ "User-defined Speed commands\n===========================\n")
19842 (mapc #'org-print-speed-command org-speed-commands-user)
19843 (princ "\n")
19844 (princ "Built-in Speed commands\n=======================\n")
19845 (mapc #'org-print-speed-command org-speed-commands-default))
19846 (with-current-buffer "*Help*"
19847 (setq truncate-lines t))))
19849 (defun org-speed-move-safe (cmd)
19850 "Execute CMD, but make sure that the cursor always ends up in a headline.
19851 If not, return to the original position and throw an error."
19852 (interactive)
19853 (let ((pos (point)))
19854 (call-interactively cmd)
19855 (unless (and (bolp) (org-at-heading-p))
19856 (goto-char pos)
19857 (error "Boundary reached while executing %s" cmd))))
19859 (defvar org-self-insert-command-undo-counter 0)
19861 (defvar org-table-auto-blank-field) ; defined in org-table.el
19862 (defvar org-speed-command nil)
19864 (defun org-speed-command-activate (keys)
19865 "Hook for activating single-letter speed commands.
19866 `org-speed-commands-default' specifies a minimal command set.
19867 Use `org-speed-commands-user' for further customization."
19868 (when (or (and (bolp) (looking-at org-outline-regexp))
19869 (and (functionp org-use-speed-commands)
19870 (funcall org-use-speed-commands)))
19871 (cdr (assoc keys (append org-speed-commands-user
19872 org-speed-commands-default)))))
19874 (defun org-babel-speed-command-activate (keys)
19875 "Hook for activating single-letter code block commands."
19876 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19877 (cdr (assoc keys org-babel-key-bindings))))
19879 (defcustom org-speed-command-hook
19880 '(org-speed-command-activate org-babel-speed-command-activate)
19881 "Hook for activating speed commands at strategic locations.
19882 Hook functions are called in sequence until a valid handler is
19883 found.
19885 Each hook takes a single argument, a user-pressed command key
19886 which is also a `self-insert-command' from the global map.
19888 Within the hook, examine the cursor position and the command key
19889 and return nil or a valid handler as appropriate. Handler could
19890 be one of an interactive command, a function, or a form.
19892 Set `org-use-speed-commands' to non-nil value to enable this
19893 hook. The default setting is `org-speed-command-activate'."
19894 :group 'org-structure
19895 :version "24.1"
19896 :type 'hook)
19898 (defun org-self-insert-command (N)
19899 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19900 If the cursor is in a table looking at whitespace, the whitespace is
19901 overwritten, and the table is not marked as requiring realignment."
19902 (interactive "p")
19903 (org-check-before-invisible-edit 'insert)
19904 (cond
19905 ((and org-use-speed-commands
19906 (let ((kv (this-command-keys-vector)))
19907 (setq org-speed-command
19908 (run-hook-with-args-until-success
19909 'org-speed-command-hook
19910 (make-string 1 (aref kv (1- (length kv))))))))
19911 (cond
19912 ((commandp org-speed-command)
19913 (setq this-command org-speed-command)
19914 (call-interactively org-speed-command))
19915 ((functionp org-speed-command)
19916 (funcall org-speed-command))
19917 ((and org-speed-command (listp org-speed-command))
19918 (eval org-speed-command))
19919 (t (let (org-use-speed-commands)
19920 (call-interactively 'org-self-insert-command)))))
19921 ((and
19922 (org-at-table-p)
19923 (progn
19924 ;; Check if we blank the field, and if that triggers align.
19925 (and (featurep 'org-table) org-table-auto-blank-field
19926 (memq last-command
19927 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19928 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19929 ;; Got extra space, this field does not determine
19930 ;; column width.
19931 (let (org-table-may-need-update) (org-table-blank-field))
19932 ;; No extra space, this field may determine column
19933 ;; width.
19934 (org-table-blank-field)))
19936 (eq N 1)
19937 (looking-at "[^|\n]* \\( \\)|"))
19938 ;; There is room for insertion without re-aligning the table.
19939 (delete-region (match-beginning 1) (match-end 1))
19940 (self-insert-command N))
19942 (setq org-table-may-need-update t)
19943 (self-insert-command N)
19944 (org-fix-tags-on-the-fly)
19945 (when org-self-insert-cluster-for-undo
19946 (if (not (eq last-command 'org-self-insert-command))
19947 (setq org-self-insert-command-undo-counter 1)
19948 (if (>= org-self-insert-command-undo-counter 20)
19949 (setq org-self-insert-command-undo-counter 1)
19950 (and (> org-self-insert-command-undo-counter 0)
19951 buffer-undo-list (listp buffer-undo-list)
19952 (not (cadr buffer-undo-list)) ; remove nil entry
19953 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19954 (setq org-self-insert-command-undo-counter
19955 (1+ org-self-insert-command-undo-counter))))))))
19957 (defun org-check-before-invisible-edit (kind)
19958 "Check is editing if kind KIND would be dangerous with invisible text around.
19959 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19960 ;; First, try to get out of here as quickly as possible, to reduce overhead
19961 (when (and org-catch-invisible-edits
19962 (or (not (boundp 'visible-mode)) (not visible-mode))
19963 (or (get-char-property (point) 'invisible)
19964 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19965 ;; OK, we need to take a closer look
19966 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19967 (invisible-before-point (unless (bobp) (get-char-property
19968 (1- (point)) 'invisible)))
19969 (border-and-ok-direction
19971 ;; Check if we are acting predictably before invisible text
19972 (and invisible-at-point (not invisible-before-point)
19973 (memq kind '(insert delete-backward)))
19974 ;; Check if we are acting predictably after invisible text
19975 ;; This works not well, and I have turned it off. It seems
19976 ;; better to always show and stop after invisible text.
19977 ;; (and (not invisible-at-point) invisible-before-point
19978 ;; (memq kind '(insert delete)))
19980 (when (or (memq invisible-at-point '(outline org-hide-block t))
19981 (memq invisible-before-point '(outline org-hide-block t)))
19982 (when (eq org-catch-invisible-edits 'error)
19983 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19984 (if (and org-custom-properties-overlays
19985 (y-or-n-p "Display invisible properties in this buffer? "))
19986 (org-toggle-custom-properties-visibility)
19987 ;; Make the area visible
19988 (save-excursion
19989 (when invisible-before-point
19990 (goto-char (previous-single-char-property-change
19991 (point) 'invisible)))
19992 (outline-show-subtree))
19993 (cond
19994 ((eq org-catch-invisible-edits 'show)
19995 ;; That's it, we do the edit after showing
19996 (message
19997 "Unfolding invisible region around point before editing")
19998 (sit-for 1))
19999 ((and (eq org-catch-invisible-edits 'smart)
20000 border-and-ok-direction)
20001 (message "Unfolding invisible region around point before editing"))
20003 ;; Don't do the edit, make the user repeat it in full visibility
20004 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20006 (defun org-fix-tags-on-the-fly ()
20007 "Align tags in headline at point.
20008 Unlike to `org-set-tags', it ignores region and sorting."
20009 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20010 (org-at-heading-p))
20011 (let ((org-ignore-region t)
20012 (org-tags-sort-function nil))
20013 (org-set-tags nil t))))
20015 (defun org-delete-backward-char (N)
20016 "Like `delete-backward-char', insert whitespace at field end in tables.
20017 When deleting backwards, in tables this function will insert whitespace in
20018 front of the next \"|\" separator, to keep the table aligned. The table will
20019 still be marked for re-alignment if the field did fill the entire column,
20020 because, in this case the deletion might narrow the column."
20021 (interactive "p")
20022 (save-match-data
20023 (org-check-before-invisible-edit 'delete-backward)
20024 (if (and (org-at-table-p)
20025 (eq N 1)
20026 (string-match "|" (buffer-substring (point-at-bol) (point)))
20027 (looking-at ".*?|"))
20028 (let ((pos (point))
20029 (noalign (looking-at "[^|\n\r]* |"))
20030 (c org-table-may-need-update))
20031 (backward-delete-char N)
20032 (unless overwrite-mode
20033 (skip-chars-forward "^|")
20034 (insert " ")
20035 (goto-char (1- pos)))
20036 ;; noalign: if there were two spaces at the end, this field
20037 ;; does not determine the width of the column.
20038 (when noalign (setq org-table-may-need-update c)))
20039 (backward-delete-char N)
20040 (org-fix-tags-on-the-fly))))
20042 (defun org-delete-char (N)
20043 "Like `delete-char', but insert whitespace at field end in tables.
20044 When deleting characters, in tables this function will insert whitespace in
20045 front of the next \"|\" separator, to keep the table aligned. The table will
20046 still be marked for re-alignment if the field did fill the entire column,
20047 because, in this case the deletion might narrow the column."
20048 (interactive "p")
20049 (save-match-data
20050 (org-check-before-invisible-edit 'delete)
20051 (if (and (org-at-table-p)
20052 (not (bolp))
20053 (not (= (char-after) ?|))
20054 (eq N 1))
20055 (if (looking-at ".*?|")
20056 (let ((pos (point))
20057 (noalign (looking-at "[^|\n\r]* |"))
20058 (c org-table-may-need-update))
20059 (replace-match
20060 (concat (substring (match-string 0) 1 -1) " |") nil t)
20061 (goto-char pos)
20062 ;; noalign: if there were two spaces at the end, this field
20063 ;; does not determine the width of the column.
20064 (when noalign (setq org-table-may-need-update c)))
20065 (delete-char N))
20066 (delete-char N)
20067 (org-fix-tags-on-the-fly))))
20069 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20070 (put 'org-self-insert-command 'delete-selection
20071 (lambda ()
20072 (not (run-hook-with-args-until-success
20073 'self-insert-uses-region-functions))))
20074 (put 'orgtbl-self-insert-command 'delete-selection
20075 (lambda ()
20076 (not (run-hook-with-args-until-success
20077 'self-insert-uses-region-functions))))
20078 (put 'org-delete-char 'delete-selection 'supersede)
20079 (put 'org-delete-backward-char 'delete-selection 'supersede)
20080 (put 'org-yank 'delete-selection 'yank)
20082 ;; Make `flyspell-mode' delay after some commands
20083 (put 'org-self-insert-command 'flyspell-delayed t)
20084 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20085 (put 'org-delete-char 'flyspell-delayed t)
20086 (put 'org-delete-backward-char 'flyspell-delayed t)
20088 ;; Make pabbrev-mode expand after Org mode commands
20089 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20090 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20092 (defun org-remap (map &rest commands)
20093 "In MAP, remap the functions given in COMMANDS.
20094 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20095 (let (new old)
20096 (while commands
20097 (setq old (pop commands) new (pop commands))
20098 (org-defkey map (vector 'remap old) new))))
20100 (defun org-transpose-words ()
20101 "Transpose words for Org.
20102 This uses the `org-mode-transpose-word-syntax-table' syntax
20103 table, which interprets characters in `org-emphasis-alist' as
20104 word constituents."
20105 (interactive)
20106 (with-syntax-table org-mode-transpose-word-syntax-table
20107 (call-interactively 'transpose-words)))
20108 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20110 (when (eq org-enable-table-editor 'optimized)
20111 ;; If the user wants maximum table support, we need to hijack
20112 ;; some standard editing functions
20113 (org-remap org-mode-map
20114 'self-insert-command 'org-self-insert-command
20115 'delete-char 'org-delete-char
20116 'delete-backward-char 'org-delete-backward-char)
20117 (org-defkey org-mode-map "|" 'org-force-self-insert))
20119 (defvar org-ctrl-c-ctrl-c-hook nil
20120 "Hook for functions attaching themselves to `C-c C-c'.
20122 This can be used to add additional functionality to the C-c C-c
20123 key which executes context-dependent commands. This hook is run
20124 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20125 run after the last test.
20127 Each function will be called with no arguments. The function
20128 must check if the context is appropriate for it to act. If yes,
20129 it should do its thing and then return a non-nil value. If the
20130 context is wrong, just do nothing and return nil.")
20132 (defvar org-ctrl-c-ctrl-c-final-hook nil
20133 "Hook for functions attaching themselves to `C-c C-c'.
20135 This can be used to add additional functionality to the C-c C-c
20136 key which executes context-dependent commands. This hook is run
20137 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20138 before the first test.
20140 Each function will be called with no arguments. The function
20141 must check if the context is appropriate for it to act. If yes,
20142 it should do its thing and then return a non-nil value. If the
20143 context is wrong, just do nothing and return nil.")
20145 (defvar org-tab-first-hook nil
20146 "Hook for functions to attach themselves to TAB.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.
20148 This hook runs as the first action when TAB is pressed, even before
20149 `org-cycle' messes around with the `outline-regexp' to cater for
20150 inline tasks and plain list item folding.
20151 If any function in this hook returns t, any other actions that
20152 would have been caused by TAB (such as table field motion or visibility
20153 cycling) will not occur.")
20155 (defvar org-tab-after-check-for-table-hook nil
20156 "Hook for functions to attach themselves to TAB.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.
20158 This hook runs after it has been established that the cursor is not in a
20159 table, but before checking if the cursor is in a headline or if global cycling
20160 should be done.
20161 If any function in this hook returns t, not other actions like visibility
20162 cycling will be done.")
20164 (defvar org-tab-after-check-for-cycling-hook nil
20165 "Hook for functions to attach themselves to TAB.
20166 See `org-ctrl-c-ctrl-c-hook' for more information.
20167 This hook runs after it has been established that not table field motion and
20168 not visibility should be done because of current context. This is probably
20169 the place where a package like yasnippets can hook in.")
20171 (defvar org-tab-before-tab-emulation-hook nil
20172 "Hook for functions to attach themselves to TAB.
20173 See `org-ctrl-c-ctrl-c-hook' for more information.
20174 This hook runs after every other options for TAB have been exhausted, but
20175 before indentation and \t insertion takes place.")
20177 (defvar org-metaleft-hook nil
20178 "Hook for functions attaching themselves to `M-left'.
20179 See `org-ctrl-c-ctrl-c-hook' for more information.")
20180 (defvar org-metaright-hook nil
20181 "Hook for functions attaching themselves to `M-right'.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-metaup-hook nil
20184 "Hook for functions attaching themselves to `M-up'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-metadown-hook nil
20187 "Hook for functions attaching themselves to `M-down'.
20188 See `org-ctrl-c-ctrl-c-hook' for more information.")
20189 (defvar org-shiftmetaleft-hook nil
20190 "Hook for functions attaching themselves to `M-S-left'.
20191 See `org-ctrl-c-ctrl-c-hook' for more information.")
20192 (defvar org-shiftmetaright-hook nil
20193 "Hook for functions attaching themselves to `M-S-right'.
20194 See `org-ctrl-c-ctrl-c-hook' for more information.")
20195 (defvar org-shiftmetaup-hook nil
20196 "Hook for functions attaching themselves to `M-S-up'.
20197 See `org-ctrl-c-ctrl-c-hook' for more information.")
20198 (defvar org-shiftmetadown-hook nil
20199 "Hook for functions attaching themselves to `M-S-down'.
20200 See `org-ctrl-c-ctrl-c-hook' for more information.")
20201 (defvar org-metareturn-hook nil
20202 "Hook for functions attaching themselves to `M-RET'.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20204 (defvar org-shiftup-hook nil
20205 "Hook for functions attaching themselves to `S-up'.
20206 See `org-ctrl-c-ctrl-c-hook' for more information.")
20207 (defvar org-shiftup-final-hook nil
20208 "Hook for functions attaching themselves to `S-up'.
20209 This one runs after all other options except shift-select have been excluded.
20210 See `org-ctrl-c-ctrl-c-hook' for more information.")
20211 (defvar org-shiftdown-hook nil
20212 "Hook for functions attaching themselves to `S-down'.
20213 See `org-ctrl-c-ctrl-c-hook' for more information.")
20214 (defvar org-shiftdown-final-hook nil
20215 "Hook for functions attaching themselves to `S-down'.
20216 This one runs after all other options except shift-select have been excluded.
20217 See `org-ctrl-c-ctrl-c-hook' for more information.")
20218 (defvar org-shiftleft-hook nil
20219 "Hook for functions attaching themselves to `S-left'.
20220 See `org-ctrl-c-ctrl-c-hook' for more information.")
20221 (defvar org-shiftleft-final-hook nil
20222 "Hook for functions attaching themselves to `S-left'.
20223 This one runs after all other options except shift-select have been excluded.
20224 See `org-ctrl-c-ctrl-c-hook' for more information.")
20225 (defvar org-shiftright-hook nil
20226 "Hook for functions attaching themselves to `S-right'.
20227 See `org-ctrl-c-ctrl-c-hook' for more information.")
20228 (defvar org-shiftright-final-hook nil
20229 "Hook for functions attaching themselves to `S-right'.
20230 This one runs after all other options except shift-select have been excluded.
20231 See `org-ctrl-c-ctrl-c-hook' for more information.")
20233 (defun org-modifier-cursor-error ()
20234 "Throw an error, a modified cursor command was applied in wrong context."
20235 (user-error "This command is active in special context like tables, headlines or items"))
20237 (defun org-shiftselect-error ()
20238 "Throw an error because Shift-Cursor command was applied in wrong context."
20239 (if (and (boundp 'shift-select-mode) shift-select-mode)
20240 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20241 (user-error "This command works only in special context like headlines or timestamps")))
20243 (defun org-call-for-shift-select (cmd)
20244 (let ((this-command-keys-shift-translated t))
20245 (call-interactively cmd)))
20247 (defun org-shifttab (&optional arg)
20248 "Global visibility cycling or move to previous table field.
20249 Call `org-table-previous-field' within a table.
20250 When ARG is nil, cycle globally through visibility states.
20251 When ARG is a numeric prefix, show contents of this level."
20252 (interactive "P")
20253 (cond
20254 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20255 ((integerp arg)
20256 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20257 (message "Content view to level: %d" arg)
20258 (org-content (prefix-numeric-value arg2))
20259 (org-cycle-show-empty-lines t)
20260 (setq org-cycle-global-status 'overview)))
20261 (t (call-interactively 'org-global-cycle))))
20263 (defun org-shiftmetaleft ()
20264 "Promote subtree or delete table column.
20265 Calls `org-promote-subtree', `org-outdent-item-tree', or
20266 `org-table-delete-column', depending on context. See the
20267 individual commands for more information."
20268 (interactive)
20269 (cond
20270 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20271 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20272 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20273 ((if (not (org-region-active-p)) (org-at-item-p)
20274 (save-excursion (goto-char (region-beginning))
20275 (org-at-item-p)))
20276 (call-interactively 'org-outdent-item-tree))
20277 (t (org-modifier-cursor-error))))
20279 (defun org-shiftmetaright ()
20280 "Demote subtree or insert table column.
20281 Calls `org-demote-subtree', `org-indent-item-tree', or
20282 `org-table-insert-column', depending on context. See the
20283 individual commands for more information."
20284 (interactive)
20285 (cond
20286 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20287 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20288 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20289 ((if (not (org-region-active-p)) (org-at-item-p)
20290 (save-excursion (goto-char (region-beginning))
20291 (org-at-item-p)))
20292 (call-interactively 'org-indent-item-tree))
20293 (t (org-modifier-cursor-error))))
20295 (defun org-shiftmetaup (&optional _arg)
20296 "Drag the line at point up.
20297 In a table, kill the current row.
20298 On a clock timestamp, update the value of the timestamp like `S-<up>'
20299 but also adjust the previous clocked item in the clock history.
20300 Everywhere else, drag the line at point up."
20301 (interactive "P")
20302 (cond
20303 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20304 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20305 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20306 (call-interactively 'org-timestamp-up)))
20307 (t (call-interactively 'org-drag-line-backward))))
20309 (defun org-shiftmetadown (&optional _arg)
20310 "Drag the line at point down.
20311 In a table, insert an empty row at the current line.
20312 On a clock timestamp, update the value of the timestamp like `S-<down>'
20313 but also adjust the previous clocked item in the clock history.
20314 Everywhere else, drag the line at point down."
20315 (interactive "P")
20316 (cond
20317 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20318 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20319 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20320 (call-interactively 'org-timestamp-down)))
20321 (t (call-interactively 'org-drag-line-forward))))
20323 (defsubst org-hidden-tree-error ()
20324 (user-error
20325 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20327 (defun org-metaleft (&optional _arg)
20328 "Promote heading, list item at point or move table column left.
20330 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20331 depending on context. With no specific context, calls the Emacs
20332 default `backward-word'. See the individual commands for more
20333 information.
20335 This function runs the hook `org-metaleft-hook' as a first step,
20336 and returns at first non-nil value."
20337 (interactive "P")
20338 (cond
20339 ((run-hook-with-args-until-success 'org-metaleft-hook))
20340 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20341 ((org-with-limited-levels
20342 (or (org-at-heading-p)
20343 (and (org-region-active-p)
20344 (save-excursion
20345 (goto-char (region-beginning))
20346 (org-at-heading-p)))))
20347 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20348 (call-interactively 'org-do-promote))
20349 ;; At an inline task.
20350 ((org-at-heading-p)
20351 (call-interactively 'org-inlinetask-promote))
20352 ((or (org-at-item-p)
20353 (and (org-region-active-p)
20354 (save-excursion
20355 (goto-char (region-beginning))
20356 (org-at-item-p))))
20357 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20358 (call-interactively 'org-outdent-item))
20359 (t (call-interactively 'backward-word))))
20361 (defun org-metaright (&optional _arg)
20362 "Demote heading, list item at point or move table column right.
20364 In front of a drawer or a block keyword, indent it correctly.
20366 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20367 `org-indent-drawer' or `org-indent-block' depending on context.
20368 With no specific context, calls the Emacs default `forward-word'.
20369 See the individual commands for more information.
20371 This function runs the hook `org-metaright-hook' as a first step,
20372 and returns at first non-nil value."
20373 (interactive "P")
20374 (cond
20375 ((run-hook-with-args-until-success 'org-metaright-hook))
20376 ((org-at-table-p) (call-interactively 'org-table-move-column))
20377 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20378 ((org-at-block-p) (call-interactively 'org-indent-block))
20379 ((org-with-limited-levels
20380 (or (org-at-heading-p)
20381 (and (org-region-active-p)
20382 (save-excursion
20383 (goto-char (region-beginning))
20384 (org-at-heading-p)))))
20385 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20386 (call-interactively 'org-do-demote))
20387 ;; At an inline task.
20388 ((org-at-heading-p)
20389 (call-interactively 'org-inlinetask-demote))
20390 ((or (org-at-item-p)
20391 (and (org-region-active-p)
20392 (save-excursion
20393 (goto-char (region-beginning))
20394 (org-at-item-p))))
20395 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20396 (call-interactively 'org-indent-item))
20397 (t (call-interactively 'forward-word))))
20399 (defun org-check-for-hidden (what)
20400 "Check if there are hidden headlines/items in the current visual line.
20401 WHAT can be either `headlines' or `items'. If the current line is
20402 an outline or item heading and it has a folded subtree below it,
20403 this function returns t, nil otherwise."
20404 (let ((re (cond
20405 ((eq what 'headlines) org-outline-regexp-bol)
20406 ((eq what 'items) (org-item-beginning-re))
20407 (t (error "This should not happen"))))
20408 beg end)
20409 (save-excursion
20410 (catch 'exit
20411 (unless (org-region-active-p)
20412 (setq beg (point-at-bol))
20413 (beginning-of-line 2)
20414 (while (and (not (eobp)) ;; this is like `next-line'
20415 (get-char-property (1- (point)) 'invisible))
20416 (beginning-of-line 2))
20417 (setq end (point))
20418 (goto-char beg)
20419 (goto-char (point-at-eol))
20420 (setq end (max end (point)))
20421 (while (re-search-forward re end t)
20422 (when (get-char-property (match-beginning 0) 'invisible)
20423 (throw 'exit t))))
20424 nil))))
20426 (defun org-metaup (&optional _arg)
20427 "Move subtree up or move table row up.
20428 Calls `org-move-subtree-up' or `org-table-move-row' or
20429 `org-move-item-up', depending on context. See the individual commands
20430 for more information."
20431 (interactive "P")
20432 (cond
20433 ((run-hook-with-args-until-success 'org-metaup-hook))
20434 ((org-region-active-p)
20435 (let* ((a (min (region-beginning) (region-end)))
20436 (b (1- (max (region-beginning) (region-end))))
20437 (c (save-excursion (goto-char a)
20438 (move-beginning-of-line 0)))
20439 (d (save-excursion (goto-char a)
20440 (move-end-of-line 0) (point))))
20441 (transpose-regions a b c d)
20442 (goto-char c)))
20443 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20444 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20445 ((org-at-item-p) (call-interactively 'org-move-item-up))
20446 (t (org-drag-element-backward))))
20448 (defun org-metadown (&optional _arg)
20449 "Move subtree down or move table row down.
20450 Calls `org-move-subtree-down' or `org-table-move-row' or
20451 `org-move-item-down', depending on context. See the individual
20452 commands for more information."
20453 (interactive "P")
20454 (cond
20455 ((run-hook-with-args-until-success 'org-metadown-hook))
20456 ((org-region-active-p)
20457 (let* ((a (min (region-beginning) (region-end)))
20458 (b (max (region-beginning) (region-end)))
20459 (c (save-excursion (goto-char b)
20460 (move-beginning-of-line 1)))
20461 (d (save-excursion (goto-char b)
20462 (move-end-of-line 1) (1+ (point)))))
20463 (transpose-regions a b c d)
20464 (goto-char d)))
20465 ((org-at-table-p) (call-interactively 'org-table-move-row))
20466 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20467 ((org-at-item-p) (call-interactively 'org-move-item-down))
20468 (t (org-drag-element-forward))))
20470 (defun org-shiftup (&optional arg)
20471 "Increase item in timestamp or increase priority of current headline.
20472 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20473 depending on context. See the individual commands for more information."
20474 (interactive "P")
20475 (cond
20476 ((run-hook-with-args-until-success 'org-shiftup-hook))
20477 ((and org-support-shift-select (org-region-active-p))
20478 (org-call-for-shift-select 'previous-line))
20479 ((org-at-timestamp-p t)
20480 (call-interactively (if org-edit-timestamp-down-means-later
20481 'org-timestamp-down 'org-timestamp-up)))
20482 ((and (not (eq org-support-shift-select 'always))
20483 org-enable-priority-commands
20484 (org-at-heading-p))
20485 (call-interactively 'org-priority-up))
20486 ((and (not org-support-shift-select) (org-at-item-p))
20487 (call-interactively 'org-previous-item))
20488 ((org-clocktable-try-shift 'up arg))
20489 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20490 (org-support-shift-select
20491 (org-call-for-shift-select 'previous-line))
20492 (t (org-shiftselect-error))))
20494 (defun org-shiftdown (&optional arg)
20495 "Decrease item in timestamp or decrease priority of current headline.
20496 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20497 depending on context. See the individual commands for more information."
20498 (interactive "P")
20499 (cond
20500 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20501 ((and org-support-shift-select (org-region-active-p))
20502 (org-call-for-shift-select 'next-line))
20503 ((org-at-timestamp-p t)
20504 (call-interactively (if org-edit-timestamp-down-means-later
20505 'org-timestamp-up 'org-timestamp-down)))
20506 ((and (not (eq org-support-shift-select 'always))
20507 org-enable-priority-commands
20508 (org-at-heading-p))
20509 (call-interactively 'org-priority-down))
20510 ((and (not org-support-shift-select) (org-at-item-p))
20511 (call-interactively 'org-next-item))
20512 ((org-clocktable-try-shift 'down arg))
20513 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20514 (org-support-shift-select
20515 (org-call-for-shift-select 'next-line))
20516 (t (org-shiftselect-error))))
20518 (defun org-shiftright (&optional arg)
20519 "Cycle the thing at point or in the current line, depending on context.
20520 Depending on context, this does one of the following:
20522 - switch a timestamp at point one day into the future
20523 - on a headline, switch to the next TODO keyword.
20524 - on an item, switch entire list to the next bullet type
20525 - on a property line, switch to the next allowed value
20526 - on a clocktable definition line, move time block into the future"
20527 (interactive "P")
20528 (cond
20529 ((run-hook-with-args-until-success 'org-shiftright-hook))
20530 ((and org-support-shift-select (org-region-active-p))
20531 (org-call-for-shift-select 'forward-char))
20532 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20533 ((and (not (eq org-support-shift-select 'always))
20534 (org-at-heading-p))
20535 (let ((org-inhibit-logging
20536 (not org-treat-S-cursor-todo-selection-as-state-change))
20537 (org-inhibit-blocking
20538 (not org-treat-S-cursor-todo-selection-as-state-change)))
20539 (org-call-with-arg 'org-todo 'right)))
20540 ((or (and org-support-shift-select
20541 (not (eq org-support-shift-select 'always))
20542 (org-at-item-bullet-p))
20543 (and (not org-support-shift-select) (org-at-item-p)))
20544 (org-call-with-arg 'org-cycle-list-bullet nil))
20545 ((and (not (eq org-support-shift-select 'always))
20546 (org-at-property-p))
20547 (call-interactively 'org-property-next-allowed-value))
20548 ((org-clocktable-try-shift 'right arg))
20549 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20550 (org-support-shift-select
20551 (org-call-for-shift-select 'forward-char))
20552 (t (org-shiftselect-error))))
20554 (defun org-shiftleft (&optional arg)
20555 "Cycle the thing at point or in the current line, depending on context.
20556 Depending on context, this does one of the following:
20558 - switch a timestamp at point one day into the past
20559 - on a headline, switch to the previous TODO keyword.
20560 - on an item, switch entire list to the previous bullet type
20561 - on a property line, switch to the previous allowed value
20562 - on a clocktable definition line, move time block into the past"
20563 (interactive "P")
20564 (cond
20565 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20566 ((and org-support-shift-select (org-region-active-p))
20567 (org-call-for-shift-select 'backward-char))
20568 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20569 ((and (not (eq org-support-shift-select 'always))
20570 (org-at-heading-p))
20571 (let ((org-inhibit-logging
20572 (not org-treat-S-cursor-todo-selection-as-state-change))
20573 (org-inhibit-blocking
20574 (not org-treat-S-cursor-todo-selection-as-state-change)))
20575 (org-call-with-arg 'org-todo 'left)))
20576 ((or (and org-support-shift-select
20577 (not (eq org-support-shift-select 'always))
20578 (org-at-item-bullet-p))
20579 (and (not org-support-shift-select) (org-at-item-p)))
20580 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20581 ((and (not (eq org-support-shift-select 'always))
20582 (org-at-property-p))
20583 (call-interactively 'org-property-previous-allowed-value))
20584 ((org-clocktable-try-shift 'left arg))
20585 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20586 (org-support-shift-select
20587 (org-call-for-shift-select 'backward-char))
20588 (t (org-shiftselect-error))))
20590 (defun org-shiftcontrolright ()
20591 "Switch to next TODO set."
20592 (interactive)
20593 (cond
20594 ((and org-support-shift-select (org-region-active-p))
20595 (org-call-for-shift-select 'forward-word))
20596 ((and (not (eq org-support-shift-select 'always))
20597 (org-at-heading-p))
20598 (org-call-with-arg 'org-todo 'nextset))
20599 (org-support-shift-select
20600 (org-call-for-shift-select 'forward-word))
20601 (t (org-shiftselect-error))))
20603 (defun org-shiftcontrolleft ()
20604 "Switch to previous TODO set."
20605 (interactive)
20606 (cond
20607 ((and org-support-shift-select (org-region-active-p))
20608 (org-call-for-shift-select 'backward-word))
20609 ((and (not (eq org-support-shift-select 'always))
20610 (org-at-heading-p))
20611 (org-call-with-arg 'org-todo 'previousset))
20612 (org-support-shift-select
20613 (org-call-for-shift-select 'backward-word))
20614 (t (org-shiftselect-error))))
20616 (defun org-shiftcontrolup (&optional n)
20617 "Change timestamps synchronously up in CLOCK log lines.
20618 Optional argument N tells to change by that many units."
20619 (interactive "P")
20620 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20621 (let (org-support-shift-select)
20622 (org-clock-timestamps-up n))
20623 (user-error "Not at a clock log")))
20625 (defun org-shiftcontroldown (&optional n)
20626 "Change timestamps synchronously down in CLOCK log lines.
20627 Optional argument N tells to change by that many units."
20628 (interactive "P")
20629 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20630 (let (org-support-shift-select)
20631 (org-clock-timestamps-down n))
20632 (user-error "Not at a clock log")))
20634 (defun org-increase-number-at-point (&optional inc)
20635 "Increment the number at point.
20636 With an optional prefix numeric argument INC, increment using
20637 this numeric value."
20638 (interactive "p")
20639 (if (not (number-at-point))
20640 (user-error "Not on a number")
20641 (unless inc (setq inc 1))
20642 (let ((pos (point))
20643 (beg (skip-chars-backward "-+^/*0-9eE."))
20644 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20645 (setq nap (buffer-substring-no-properties
20646 (+ pos beg) (+ pos beg end)))
20647 (delete-region (+ pos beg) (+ pos beg end))
20648 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20649 (when (org-at-table-p)
20650 (org-table-align)
20651 (org-table-end-of-field 1))))
20653 (defun org-decrease-number-at-point (&optional inc)
20654 "Decrement the number at point.
20655 With an optional prefix numeric argument INC, decrement using
20656 this numeric value."
20657 (interactive "p")
20658 (org-increase-number-at-point (- (or inc 1))))
20660 (defun org-ctrl-c-ret ()
20661 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20662 (interactive)
20663 (cond
20664 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20665 (t (call-interactively 'org-insert-heading))))
20667 (defun org-find-visible ()
20668 (let ((s (point)))
20669 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20670 (get-char-property s 'invisible)))
20672 (defun org-find-invisible ()
20673 (let ((s (point)))
20674 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20675 (not (get-char-property s 'invisible))))
20678 (defun org-copy-visible (beg end)
20679 "Copy the visible parts of the region."
20680 (interactive "r")
20681 (let (snippets s)
20682 (save-excursion
20683 (save-restriction
20684 (narrow-to-region beg end)
20685 (setq s (goto-char (point-min)))
20686 (while (not (= (point) (point-max)))
20687 (goto-char (org-find-invisible))
20688 (push (buffer-substring s (point)) snippets)
20689 (setq s (goto-char (org-find-visible))))))
20690 (kill-new (apply 'concat (nreverse snippets)))))
20692 (defun org-copy-special ()
20693 "Copy region in table or copy current subtree.
20694 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20695 context. See the individual commands for more information."
20696 (interactive)
20697 (call-interactively
20698 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20700 (defun org-cut-special ()
20701 "Cut region in table or cut current subtree.
20702 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20703 context. See the individual commands for more information."
20704 (interactive)
20705 (call-interactively
20706 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20708 (defun org-paste-special (arg)
20709 "Paste rectangular region into table, or past subtree relative to level.
20710 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20711 See the individual commands for more information."
20712 (interactive "P")
20713 (if (org-at-table-p)
20714 (org-table-paste-rectangle)
20715 (org-paste-subtree arg)))
20717 (defun org-edit-special (&optional arg)
20718 "Call a special editor for the element at point.
20719 When at a table, call the formula editor with `org-table-edit-formulas'.
20720 When in a source code block, call `org-edit-src-code'.
20721 When in a fixed-width region, call `org-edit-fixed-width-region'.
20722 When in an export block, call `org-edit-export-block'.
20723 When in a LaTeX environment, call `org-edit-latex-environment'.
20724 When at an #+INCLUDE keyword, visit the included file.
20725 When at a footnote reference, call `org-edit-footnote-reference'
20726 On a link, call `ffap' to visit the link at point.
20727 Otherwise, return a user error."
20728 (interactive "P")
20729 (let ((element (org-element-at-point)))
20730 (barf-if-buffer-read-only)
20731 (pcase (org-element-type element)
20732 (`src-block
20733 (if (not arg) (org-edit-src-code)
20734 (let* ((info (org-babel-get-src-block-info))
20735 (lang (nth 0 info))
20736 (params (nth 2 info))
20737 (session (cdr (assq :session params))))
20738 (if (not session) (org-edit-src-code)
20739 ;; At a src-block with a session and function called with
20740 ;; an ARG: switch to the buffer related to the inferior
20741 ;; process.
20742 (switch-to-buffer
20743 (funcall (intern (concat "org-babel-prep-session:" lang))
20744 session params))))))
20745 (`keyword
20746 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20747 (org-open-link-from-string
20748 (format "[[%s]]"
20749 (expand-file-name
20750 (let ((value (org-element-property :value element)))
20751 (cond ((not (org-string-nw-p value))
20752 (user-error "No file to edit"))
20753 ((string-match "\\`\"\\(.*?\\)\"" value)
20754 (match-string 1 value))
20755 ((string-match "\\`[^ \t\"]\\S-*" value)
20756 (match-string 0 value))
20757 (t (user-error "No valid file specified")))))))
20758 (user-error "No special environment to edit here")))
20759 (`table
20760 (if (eq (org-element-property :type element) 'table.el)
20761 (org-edit-table.el)
20762 (call-interactively 'org-table-edit-formulas)))
20763 ;; Only Org tables contain `table-row' type elements.
20764 (`table-row (call-interactively 'org-table-edit-formulas))
20765 (`example-block (org-edit-src-code))
20766 (`export-block (org-edit-export-block))
20767 (`fixed-width (org-edit-fixed-width-region))
20768 (`latex-environment (org-edit-latex-environment))
20770 ;; No notable element at point. Though, we may be at a link or
20771 ;; a footnote reference, which are objects. Thus, scan deeper.
20772 (let ((context (org-element-context element)))
20773 (pcase (org-element-type context)
20774 (`footnote-reference (org-edit-footnote-reference))
20775 (`inline-src-block (org-edit-inline-src-code))
20776 (`link (call-interactively #'ffap))
20777 (_ (user-error "No special environment to edit here"))))))))
20779 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20780 (defun org-ctrl-c-ctrl-c (&optional arg)
20781 "Set tags in headline, or update according to changed information at point.
20783 This command does many different things, depending on context:
20785 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20786 this is what we do.
20788 - If the cursor is on a statistics cookie, update it.
20790 - If the cursor is in a headline, prompt for tags and insert them
20791 into the current line, aligned to `org-tags-column'. When called
20792 with prefix arg, realign all tags in the current buffer.
20794 - If the cursor is in one of the special #+KEYWORD lines, this
20795 triggers scanning the buffer for these lines and updating the
20796 information.
20798 - If the cursor is inside a table, realign the table. This command
20799 works even if the automatic table editor has been turned off.
20801 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20802 the entire table.
20804 - If the cursor is at a footnote reference or definition, jump to
20805 the corresponding definition or references, respectively.
20807 - If the cursor is a the beginning of a dynamic block, update it.
20809 - If the current buffer is a capture buffer, close note and file it.
20811 - If the cursor is on a <<<target>>>, update radio targets and
20812 corresponding links in this buffer.
20814 - If the cursor is on a numbered item in a plain list, renumber the
20815 ordered list.
20817 - If the cursor is on a checkbox, toggle it.
20819 - If the cursor is on a code block, evaluate it. The variable
20820 `org-confirm-babel-evaluate' can be used to control prompting
20821 before code block evaluation, by default every code block
20822 evaluation requires confirmation. Code block evaluation can be
20823 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20824 (interactive "P")
20825 (cond
20826 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20827 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20828 (org-remove-occur-highlights)
20829 (message "Temporary highlights/overlays removed from current buffer"))
20830 ((and (local-variable-p 'org-finish-function)
20831 (fboundp org-finish-function))
20832 (funcall org-finish-function))
20833 ((org-babel-hash-at-point))
20834 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20836 (let* ((context
20837 (org-element-lineage
20838 (org-element-context)
20839 ;; Limit to supported contexts.
20840 '(babel-call clock dynamic-block footnote-definition
20841 footnote-reference inline-babel-call inline-src-block
20842 inlinetask item keyword node-property paragraph
20843 plain-list property-drawer radio-target src-block
20844 statistics-cookie table table-cell table-row
20845 timestamp)
20847 (type (org-element-type context)))
20848 ;; For convenience: at the first line of a paragraph on the same
20849 ;; line as an item, apply function on that item instead.
20850 (when (eq type 'paragraph)
20851 (let ((parent (org-element-property :parent context)))
20852 (when (and (eq (org-element-type parent) 'item)
20853 (= (line-beginning-position)
20854 (org-element-property :begin parent)))
20855 (setq context parent)
20856 (setq type 'item))))
20857 ;; Act according to type of element or object at point.
20859 ;; Do nothing on a blank line, except if it is contained in
20860 ;; a src block. Hence, we first check if point is in such
20861 ;; a block and then if it is at a blank line.
20862 (pcase type
20863 ((or `inline-src-block `src-block)
20864 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20865 (org-babel-eval-wipe-error-buffer)
20866 (org-babel-execute-src-block
20867 current-prefix-arg (org-babel-get-src-block-info nil context))))
20868 ((guard (org-match-line "[ \t]*$"))
20869 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20870 (user-error
20871 (substitute-command-keys
20872 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20873 ((or `babel-call `inline-babel-call)
20874 (let ((info (org-babel-lob-get-info context)))
20875 (when info (org-babel-execute-src-block nil info))))
20876 (`clock (org-clock-update-time-maybe))
20877 (`dynamic-block
20878 (save-excursion
20879 (goto-char (org-element-property :post-affiliated context))
20880 (org-update-dblock)))
20881 (`footnote-definition
20882 (goto-char (org-element-property :post-affiliated context))
20883 (call-interactively 'org-footnote-action))
20884 (`footnote-reference (call-interactively #'org-footnote-action))
20885 ((or `headline `inlinetask)
20886 (save-excursion (goto-char (org-element-property :begin context))
20887 (call-interactively #'org-set-tags)))
20888 (`item
20889 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20890 ;; unconditionally, whereas `C-u' will toggle its presence.
20891 ;; Without a universal argument, if the item has a checkbox,
20892 ;; toggle it. Otherwise repair the list.
20893 (let* ((box (org-element-property :checkbox context))
20894 (struct (org-element-property :structure context))
20895 (old-struct (copy-tree struct))
20896 (parents (org-list-parents-alist struct))
20897 (prevs (org-list-prevs-alist struct))
20898 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20899 (org-list-set-checkbox
20900 (org-element-property :begin context) struct
20901 (cond ((equal arg '(16)) "[-]")
20902 ((and (not box) (equal arg '(4))) "[ ]")
20903 ((or (not box) (equal arg '(4))) nil)
20904 ((eq box 'on) "[ ]")
20905 (t "[X]")))
20906 ;; Mimic `org-list-write-struct' but with grabbing a return
20907 ;; value from `org-list-struct-fix-box'.
20908 (org-list-struct-fix-ind struct parents 2)
20909 (org-list-struct-fix-item-end struct)
20910 (org-list-struct-fix-bul struct prevs)
20911 (org-list-struct-fix-ind struct parents)
20912 (let ((block-item
20913 (org-list-struct-fix-box struct parents prevs orderedp)))
20914 (if (and box (equal struct old-struct))
20915 (if (equal arg '(16))
20916 (message "Checkboxes already reset")
20917 (user-error "Cannot toggle this checkbox: %s"
20918 (if (eq box 'on)
20919 "all subitems checked"
20920 "unchecked subitems")))
20921 (org-list-struct-apply-struct struct old-struct)
20922 (org-update-checkbox-count-maybe))
20923 (when block-item
20924 (message "Checkboxes were removed due to empty box at line %d"
20925 (org-current-line block-item))))))
20926 (`keyword
20927 (let ((org-inhibit-startup-visibility-stuff t)
20928 (org-startup-align-all-tables nil))
20929 (when (boundp 'org-table-coordinate-overlays)
20930 (mapc #'delete-overlay org-table-coordinate-overlays)
20931 (setq org-table-coordinate-overlays nil))
20932 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20933 (message "Local setup has been refreshed"))
20934 (`plain-list
20935 ;; At a plain list, with a double C-u argument, set
20936 ;; checkboxes of each item to "[-]", whereas a single one
20937 ;; will toggle their presence according to the state of the
20938 ;; first item in the list. Without an argument, repair the
20939 ;; list.
20940 (let* ((begin (org-element-property :contents-begin context))
20941 (beginm (move-marker (make-marker) begin))
20942 (struct (org-element-property :structure context))
20943 (old-struct (copy-tree struct))
20944 (first-box (save-excursion
20945 (goto-char begin)
20946 (looking-at org-list-full-item-re)
20947 (match-string-no-properties 3)))
20948 (new-box (cond ((equal arg '(16)) "[-]")
20949 ((equal arg '(4)) (unless first-box "[ ]"))
20950 ((equal first-box "[X]") "[ ]")
20951 (t "[X]"))))
20952 (cond
20953 (arg
20954 (dolist (pos
20955 (org-list-get-all-items
20956 begin struct (org-list-prevs-alist struct)))
20957 (org-list-set-checkbox pos struct new-box)))
20958 ((and first-box (eq (point) begin))
20959 ;; For convenience, when point is at bol on the first
20960 ;; item of the list and no argument is provided, simply
20961 ;; toggle checkbox of that item, if any.
20962 (org-list-set-checkbox begin struct new-box)))
20963 (org-list-write-struct
20964 struct (org-list-parents-alist struct) old-struct)
20965 (org-update-checkbox-count-maybe)
20966 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20967 ((or `property-drawer `node-property)
20968 (call-interactively #'org-property-action))
20969 (`radio-target
20970 (call-interactively #'org-update-radio-target-regexp))
20971 (`statistics-cookie
20972 (call-interactively #'org-update-statistics-cookies))
20973 ((or `table `table-cell `table-row)
20974 ;; At a table, recalculate every field and align it. Also
20975 ;; send the table if necessary. If the table has
20976 ;; a `table.el' type, just give up. At a table row or cell,
20977 ;; maybe recalculate line but always align table.
20978 (if (eq (org-element-property :type context) 'table.el)
20979 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20980 Use `\\[org-edit-special]' to edit table.el tables"))
20981 (let ((org-enable-table-editor t))
20982 (if (or (eq type 'table)
20983 ;; Check if point is at a TBLFM line.
20984 (and (eq type 'table-row)
20985 (= (point) (org-element-property :end context))))
20986 (save-excursion
20987 (if (org-at-TBLFM-p)
20988 (progn (require 'org-table)
20989 (org-table-calc-current-TBLFM))
20990 (goto-char (org-element-property :contents-begin context))
20991 (org-call-with-arg 'org-table-recalculate (or arg t))
20992 (orgtbl-send-table 'maybe)))
20993 (org-table-maybe-eval-formula)
20994 (cond (arg (call-interactively #'org-table-recalculate))
20995 ((org-table-maybe-recalculate-line))
20996 (t (org-table-align)))))))
20997 (`timestamp (org-timestamp-change 0 'day))
20998 ((and `nil (guard (org-at-heading-p)))
20999 ;; When point is on an unsupported object type, we can miss
21000 ;; the fact that it also is at a heading. Handle it here.
21001 (call-interactively #'org-set-tags))
21002 ((guard
21003 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21005 (user-error
21006 (substitute-command-keys
21007 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21009 (defun org-mode-restart ()
21010 (interactive)
21011 (let ((indent-status (bound-and-true-p org-indent-mode)))
21012 (funcall major-mode)
21013 (hack-local-variables)
21014 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21015 (org-indent-mode -1)))
21016 (message "%s restarted" major-mode))
21018 (defun org-kill-note-or-show-branches ()
21019 "Abort storing current note, or call `outline-show-branches'."
21020 (interactive)
21021 (if (not org-finish-function)
21022 (progn
21023 (outline-hide-subtree)
21024 (call-interactively 'outline-show-branches))
21025 (let ((org-note-abort t))
21026 (funcall org-finish-function))))
21028 (defun org-delete-indentation (&optional arg)
21029 "Join current line to previous and fix whitespace at join.
21031 If previous line is a headline add to headline title. Otherwise
21032 the function calls `delete-indentation'.
21034 With a non-nil optional argument, join it to the following one."
21035 (interactive "*P")
21036 (if (save-excursion
21037 (beginning-of-line (if arg 1 0))
21038 (let ((case-fold-search nil))
21039 (looking-at org-complex-heading-regexp)))
21040 ;; At headline.
21041 (let ((tags-column (when (match-beginning 5)
21042 (save-excursion (goto-char (match-beginning 5))
21043 (current-column))))
21044 (string (concat " " (progn (when arg (forward-line 1))
21045 (org-trim (delete-and-extract-region
21046 (line-beginning-position)
21047 (line-end-position)))))))
21048 (unless (bobp) (delete-region (point) (1- (point))))
21049 (goto-char (or (match-end 4)
21050 (match-beginning 5)
21051 (match-end 0)))
21052 (skip-chars-backward " \t")
21053 (save-excursion (insert string))
21054 ;; Adjust alignment of tags.
21055 (cond
21056 ((not tags-column)) ;no tags
21057 (org-auto-align-tags (org-set-tags nil t))
21058 (t (org--align-tags-here tags-column)))) ;preserve tags column
21059 (delete-indentation arg)))
21061 (defun org-open-line (n)
21062 "Insert a new row in tables, call `open-line' elsewhere.
21063 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21064 As a special case, when a document starts with a table, allow to
21065 call `open-line' on the very first character."
21066 (interactive "*p")
21067 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21068 (org-table-insert-row)
21069 (open-line n)))
21071 (defun org-return (&optional indent)
21072 "Goto next table row or insert a newline.
21074 Calls `org-table-next-row' or `newline', depending on context.
21076 When optional INDENT argument is non-nil, call
21077 `newline-and-indent' instead of `newline'.
21079 When `org-return-follows-link' is non-nil and point is on
21080 a timestamp or a link, call `org-open-at-point'. However, it
21081 will not happen if point is in a table or on a \"dead\"
21082 object (e.g., within a comment). In these case, you need to use
21083 `org-open-at-point' directly."
21084 (interactive)
21085 (let ((context (if org-return-follows-link (org-element-context)
21086 (org-element-at-point))))
21087 (cond
21088 ;; In a table, call `org-table-next-row'.
21089 ((or (and (eq (org-element-type context) 'table)
21090 (>= (point) (org-element-property :contents-begin context))
21091 (< (point) (org-element-property :contents-end context)))
21092 (org-element-lineage context '(table-row table-cell) t))
21093 (org-table-justify-field-maybe)
21094 (call-interactively #'org-table-next-row))
21095 ;; On a link or a timestamp, call `org-open-at-point' if
21096 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21097 ;; locations, e.g., in a comment, as `org-open-at-point'.
21098 ((and org-return-follows-link
21099 (or (org-in-regexp org-ts-regexp-both nil t)
21100 (org-in-regexp org-tsr-regexp-both nil t)
21101 (org-in-regexp org-any-link-re nil t)))
21102 (call-interactively #'org-open-at-point))
21103 ;; Insert newline in heading, but preserve tags.
21104 ((and (not (bolp))
21105 (save-excursion (beginning-of-line)
21106 (let ((case-fold-search nil))
21107 (looking-at org-complex-heading-regexp))))
21108 ;; At headline. Split line. However, if point is on keyword,
21109 ;; priority cookie or tags, do not break any of them: add
21110 ;; a newline after the headline instead.
21111 (let ((tags-column (and (match-beginning 5)
21112 (save-excursion (goto-char (match-beginning 5))
21113 (current-column))))
21114 (string
21115 (when (and (match-end 4) (org-point-in-group (point) 4))
21116 (delete-and-extract-region (point) (match-end 4)))))
21117 ;; Adjust tag alignment.
21118 (cond
21119 ((not (and tags-column string)))
21120 (org-auto-align-tags (org-set-tags nil t))
21121 (t (org--align-tags-here tags-column))) ;preserve tags column
21122 (end-of-line)
21123 (org-show-entry)
21124 (if indent (newline-and-indent) (newline))
21125 (when string (save-excursion (insert (org-trim string))))))
21126 ;; In a list, make sure indenting keeps trailing text within.
21127 ((and indent
21128 (not (eolp))
21129 (org-element-lineage context '(item)))
21130 (let ((trailing-data
21131 (delete-and-extract-region (point) (line-end-position))))
21132 (newline-and-indent)
21133 (save-excursion (insert trailing-data))))
21134 (t (if indent (newline-and-indent) (newline))))))
21136 (defun org-return-indent ()
21137 "Goto next table row or insert a newline and indent.
21138 Calls `org-table-next-row' or `newline-and-indent', depending on
21139 context. See the individual commands for more information."
21140 (interactive)
21141 (org-return t))
21143 (defun org-ctrl-c-star ()
21144 "Compute table, or change heading status of lines.
21145 Calls `org-table-recalculate' or `org-toggle-heading',
21146 depending on context."
21147 (interactive)
21148 (cond
21149 ((org-at-table-p)
21150 (call-interactively 'org-table-recalculate))
21152 ;; Convert all lines in region to list items
21153 (call-interactively 'org-toggle-heading))))
21155 (defun org-ctrl-c-minus ()
21156 "Insert separator line in table or modify bullet status of line.
21157 Also turns a plain line or a region of lines into list items.
21158 Calls `org-table-insert-hline', `org-toggle-item', or
21159 `org-cycle-list-bullet', depending on context."
21160 (interactive)
21161 (cond
21162 ((org-at-table-p)
21163 (call-interactively 'org-table-insert-hline))
21164 ((org-region-active-p)
21165 (call-interactively 'org-toggle-item))
21166 ((org-in-item-p)
21167 (call-interactively 'org-cycle-list-bullet))
21169 (call-interactively 'org-toggle-item))))
21171 (defun org-toggle-heading (&optional nstars)
21172 "Convert headings to normal text, or items or text to headings.
21173 If there is no active region, only convert the current line.
21175 With a `\\[universal-argument]' prefix, convert the whole list at
21176 point into heading.
21178 In a region:
21180 - If the first non blank line is a headline, remove the stars
21181 from all headlines in the region.
21183 - If it is a normal line, turn each and every normal line (i.e.,
21184 not an heading or an item) in the region into headings. If you
21185 want to convert only the first line of this region, use one
21186 universal prefix argument.
21188 - If it is a plain list item, turn all plain list items into headings.
21190 When converting a line into a heading, the number of stars is chosen
21191 such that the lines become children of the current entry. However,
21192 when a numeric prefix argument is given, its value determines the
21193 number of stars to add."
21194 (interactive "P")
21195 (let ((skip-blanks
21196 (function
21197 ;; Return beginning of first non-blank line, starting from
21198 ;; line at POS.
21199 (lambda (pos)
21200 (save-excursion
21201 (goto-char pos)
21202 (while (org-at-comment-p) (forward-line))
21203 (skip-chars-forward " \r\t\n")
21204 (point-at-bol)))))
21205 beg end toggled)
21206 ;; Determine boundaries of changes. If a universal prefix has
21207 ;; been given, put the list in a region. If region ends at a bol,
21208 ;; do not consider the last line to be in the region.
21210 (when (and current-prefix-arg (org-at-item-p))
21211 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21212 (org-mark-element))
21214 (if (org-region-active-p)
21215 (setq beg (funcall skip-blanks (region-beginning))
21216 end (copy-marker (save-excursion
21217 (goto-char (region-end))
21218 (if (bolp) (point) (point-at-eol)))))
21219 (setq beg (funcall skip-blanks (point-at-bol))
21220 end (copy-marker (point-at-eol))))
21221 ;; Ensure inline tasks don't count as headings.
21222 (org-with-limited-levels
21223 (save-excursion
21224 (goto-char beg)
21225 (cond
21226 ;; Case 1. Started at an heading: de-star headings.
21227 ((org-at-heading-p)
21228 (while (< (point) end)
21229 (when (org-at-heading-p t)
21230 (looking-at org-outline-regexp) (replace-match "")
21231 (setq toggled t))
21232 (forward-line)))
21233 ;; Case 2. Started at an item: change items into headlines.
21234 ;; One star will be added by `org-list-to-subtree'.
21235 ((org-at-item-p)
21236 (while (< (point) end)
21237 (when (org-at-item-p)
21238 ;; Pay attention to cases when region ends before list.
21239 (let* ((struct (org-list-struct))
21240 (list-end
21241 (min (org-list-get-bottom-point struct) (1+ end))))
21242 (save-restriction
21243 (narrow-to-region (point) list-end)
21244 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21245 (setq toggled t))
21246 (forward-line)))
21247 ;; Case 3. Started at normal text: make every line an heading,
21248 ;; skipping headlines and items.
21249 (t (let* ((stars
21250 (make-string
21251 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21252 (add-stars
21253 (cond (nstars "") ; stars from prefix only
21254 ((equal stars "") "*") ; before first heading
21255 (org-odd-levels-only "**") ; inside heading, odd
21256 (t "*"))) ; inside heading, oddeven
21257 (rpl (concat stars add-stars " "))
21258 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21259 (while (< (point) (if (equal nstars '(4)) lend end))
21260 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21261 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21262 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21263 (forward-line)))))))
21264 (unless toggled (message "Cannot toggle heading from here"))))
21266 (defun org-meta-return (&optional arg)
21267 "Insert a new heading or wrap a region in a table.
21268 Calls `org-insert-heading', `org-insert-item' or
21269 `org-table-wrap-region', depending on context. When called with
21270 an argument, unconditionally call `org-insert-heading'."
21271 (interactive "P")
21272 (org-check-before-invisible-edit 'insert)
21273 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21274 (call-interactively (cond (arg #'org-insert-heading)
21275 ((org-at-table-p) #'org-table-wrap-region)
21276 ((org-in-item-p) #'org-insert-item)
21277 (t #'org-insert-heading)))))
21279 ;;; Menu entries
21281 (defsubst org-in-subtree-not-table-p ()
21282 "Are we in a subtree and not in a table?"
21283 (and (not (org-before-first-heading-p))
21284 (not (org-at-table-p))))
21286 ;; Define the Org mode menus
21287 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21288 '("Tbl"
21289 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21290 ["Next Field" org-cycle (org-at-table-p)]
21291 ["Previous Field" org-shifttab (org-at-table-p)]
21292 ["Next Row" org-return (org-at-table-p)]
21293 "--"
21294 ["Blank Field" org-table-blank-field (org-at-table-p)]
21295 ["Edit Field" org-table-edit-field (org-at-table-p)]
21296 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21297 "--"
21298 ("Column"
21299 ["Move Column Left" org-metaleft (org-at-table-p)]
21300 ["Move Column Right" org-metaright (org-at-table-p)]
21301 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21302 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21303 ("Row"
21304 ["Move Row Up" org-metaup (org-at-table-p)]
21305 ["Move Row Down" org-metadown (org-at-table-p)]
21306 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21307 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21308 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21309 "--"
21310 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21311 ("Rectangle"
21312 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21313 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21314 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21315 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21316 "--"
21317 ("Calculate"
21318 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21319 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21320 ["Edit Formulas" org-edit-special (org-at-table-p)]
21321 "--"
21322 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21323 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21324 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21325 "--"
21326 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21327 "--"
21328 ["Sum Column/Rectangle" org-table-sum
21329 (or (org-at-table-p) (org-region-active-p))]
21330 ["Which Column?" org-table-current-column (org-at-table-p)])
21331 ["Debug Formulas"
21332 org-table-toggle-formula-debugger
21333 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21334 ["Show Col/Row Numbers"
21335 org-table-toggle-coordinate-overlays
21336 :style toggle
21337 :selected (bound-and-true-p org-table-overlay-coordinates)]
21338 "--"
21339 ["Create" org-table-create (and (not (org-at-table-p))
21340 org-enable-table-editor)]
21341 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21342 ["Import from File" org-table-import (not (org-at-table-p))]
21343 ["Export to File" org-table-export (org-at-table-p)]
21344 "--"
21345 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21346 "--"
21347 ("Plot"
21348 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21349 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21351 (easy-menu-define org-org-menu org-mode-map "Org menu"
21352 '("Org"
21353 ("Show/Hide"
21354 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21355 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21356 ["Sparse Tree..." org-sparse-tree t]
21357 ["Reveal Context" org-reveal t]
21358 ["Show All" outline-show-all t]
21359 "--"
21360 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21361 "--"
21362 ["New Heading" org-insert-heading t]
21363 ("Navigate Headings"
21364 ["Up" outline-up-heading t]
21365 ["Next" outline-next-visible-heading t]
21366 ["Previous" outline-previous-visible-heading t]
21367 ["Next Same Level" outline-forward-same-level t]
21368 ["Previous Same Level" outline-backward-same-level t]
21369 "--"
21370 ["Jump" org-goto t])
21371 ("Edit Structure"
21372 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21373 "--"
21374 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21375 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21376 "--"
21377 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21378 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21379 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21380 "--"
21381 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21382 "--"
21383 ["Copy visible text" org-copy-visible t]
21384 "--"
21385 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21386 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21387 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21388 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21389 "--"
21390 ["Sort Region/Children" org-sort t]
21391 "--"
21392 ["Convert to odd levels" org-convert-to-odd-levels t]
21393 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21394 ("Editing"
21395 ["Emphasis..." org-emphasize t]
21396 ["Edit Source Example" org-edit-special t]
21397 "--"
21398 ["Footnote new/jump" org-footnote-action t]
21399 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21400 ("Archive"
21401 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21402 "--"
21403 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21404 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21405 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21407 "--"
21408 ("Hyperlinks"
21409 ["Store Link (Global)" org-store-link t]
21410 ["Find existing link to here" org-occur-link-in-agenda-files t]
21411 ["Insert Link" org-insert-link t]
21412 ["Follow Link" org-open-at-point t]
21413 "--"
21414 ["Next link" org-next-link t]
21415 ["Previous link" org-previous-link t]
21416 "--"
21417 ["Descriptive Links"
21418 org-toggle-link-display
21419 :style radio
21420 :selected org-descriptive-links
21422 ["Literal Links"
21423 org-toggle-link-display
21424 :style radio
21425 :selected (not org-descriptive-links)])
21426 "--"
21427 ("TODO Lists"
21428 ["TODO/DONE/-" org-todo t]
21429 ("Select keyword"
21430 ["Next keyword" org-shiftright (org-at-heading-p)]
21431 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21432 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21433 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21434 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21435 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21436 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21437 "--"
21438 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21439 :selected org-enforce-todo-dependencies :style toggle :active t]
21440 "Settings for tree at point"
21441 ["Do Children sequentially" org-toggle-ordered-property :style radio
21442 :selected (org-entry-get nil "ORDERED")
21443 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21444 ["Do Children parallel" org-toggle-ordered-property :style radio
21445 :selected (not (org-entry-get nil "ORDERED"))
21446 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21447 "--"
21448 ["Set Priority" org-priority t]
21449 ["Priority Up" org-shiftup t]
21450 ["Priority Down" org-shiftdown t]
21451 "--"
21452 ["Get news from all feeds" org-feed-update-all t]
21453 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21454 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21455 ("TAGS and Properties"
21456 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21457 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21458 "--"
21459 ["Set property" org-set-property (not (org-before-first-heading-p))]
21460 ["Column view of properties" org-columns t]
21461 ["Insert Column View DBlock" org-columns-insert-dblock t])
21462 ("Dates and Scheduling"
21463 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21464 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21465 ("Change Date"
21466 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21467 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21468 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21469 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21470 ["Compute Time Range" org-evaluate-time-range t]
21471 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21472 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21473 "--"
21474 ["Custom time format" org-toggle-time-stamp-overlays
21475 :style radio :selected org-display-custom-times]
21476 "--"
21477 ["Goto Calendar" org-goto-calendar t]
21478 ["Date from Calendar" org-date-from-calendar t]
21479 "--"
21480 ["Start/Restart Timer" org-timer-start t]
21481 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21482 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21483 ["Insert Timer String" org-timer t]
21484 ["Insert Timer Item" org-timer-item t])
21485 ("Logging work"
21486 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21487 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21488 ["Clock out" org-clock-out t]
21489 ["Clock cancel" org-clock-cancel t]
21490 "--"
21491 ["Mark as default task" org-clock-mark-default-task t]
21492 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21493 ["Goto running clock" org-clock-goto t]
21494 "--"
21495 ["Display times" org-clock-display t]
21496 ["Create clock table" org-clock-report t]
21497 "--"
21498 ["Record DONE time"
21499 (progn (setq org-log-done (not org-log-done))
21500 (message "Switching to %s will %s record a timestamp"
21501 (car org-done-keywords)
21502 (if org-log-done "automatically" "not")))
21503 :style toggle :selected org-log-done])
21504 "--"
21505 ["Agenda Command..." org-agenda t]
21506 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21507 ("File List for Agenda")
21508 ("Special views current file"
21509 ["TODO Tree" org-show-todo-tree t]
21510 ["Check Deadlines" org-check-deadlines t]
21511 ["Tags/Property tree" org-match-sparse-tree t])
21512 "--"
21513 ["Export/Publish..." org-export-dispatch t]
21514 ("LaTeX"
21515 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21516 :selected org-cdlatex-mode]
21517 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21518 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21519 ["Modify math symbol" org-cdlatex-math-modify
21520 (org-inside-LaTeX-fragment-p)]
21521 ["Insert citation" org-reftex-citation t])
21522 "--"
21523 ("MobileOrg"
21524 ["Push Files and Views" org-mobile-push t]
21525 ["Get Captured and Flagged" org-mobile-pull t]
21526 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21527 "--"
21528 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21529 "--"
21530 ("Documentation"
21531 ["Show Version" org-version t]
21532 ["Info Documentation" org-info t])
21533 ("Customize"
21534 ["Browse Org Group" org-customize t]
21535 "--"
21536 ["Expand This Menu" org-create-customize-menu
21537 (fboundp 'customize-menu-create)])
21538 ["Send bug report" org-submit-bug-report t]
21539 "--"
21540 ("Refresh/Reload"
21541 ["Refresh setup current buffer" org-mode-restart t]
21542 ["Reload Org (after update)" org-reload t]
21543 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21546 (defun org-info (&optional node)
21547 "Read documentation for Org in the info system.
21548 With optional NODE, go directly to that node."
21549 (interactive)
21550 (info (format "(org)%s" (or node ""))))
21552 ;;;###autoload
21553 (defun org-submit-bug-report ()
21554 "Submit a bug report on Org via mail.
21556 Don't hesitate to report any problems or inaccurate documentation.
21558 If you don't have setup sending mail from (X)Emacs, please copy the
21559 output buffer into your mail program, as it gives us important
21560 information about your Org version and configuration."
21561 (interactive)
21562 (require 'reporter)
21563 (defvar reporter-prompt-for-summary-p)
21564 (org-load-modules-maybe)
21565 (org-require-autoloaded-modules)
21566 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21567 (reporter-submit-bug-report
21568 "emacs-orgmode@gnu.org"
21569 (org-version nil 'full)
21570 (let (list)
21571 (save-window-excursion
21572 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21573 (delete-other-windows)
21574 (erase-buffer)
21575 (insert "You are about to submit a bug report to the Org mailing list.
21577 We would like to add your full Org and Outline configuration to the
21578 bug report. This greatly simplifies the work of the maintainer and
21579 other experts on the mailing list.
21581 HOWEVER, some variables you have customized may contain private
21582 information. The names of customers, colleagues, or friends, might
21583 appear in the form of file names, tags, todo states, or search strings.
21584 If you answer yes to the prompt, you might want to check and remove
21585 such private information before sending the email.")
21586 (add-text-properties (point-min) (point-max) '(face org-warning))
21587 (when (yes-or-no-p "Include your Org configuration ")
21588 (mapatoms
21589 (lambda (v)
21590 (and (boundp v)
21591 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21592 (or (and (symbol-value v)
21593 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21594 (and
21595 (get v 'custom-type) (get v 'standard-value)
21596 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21597 (push v list)))))
21598 (kill-buffer (get-buffer "*Warn about privacy*"))
21599 list))
21600 nil nil
21601 "Remember to cover the basics, that is, what you expected to happen and
21602 what in fact did happen. You don't know how to make a good report? See
21604 http://orgmode.org/manual/Feedback.html#Feedback
21606 Your bug report will be posted to the Org mailing list.
21607 ------------------------------------------------------------------------")
21608 (save-excursion
21609 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21610 (replace-match "\\1Bug: \\3 [\\2]")))))
21613 (defun org-install-agenda-files-menu ()
21614 (let ((bl (buffer-list)))
21615 (save-excursion
21616 (while bl
21617 (set-buffer (pop bl))
21618 (when (derived-mode-p 'org-mode) (setq bl nil)))
21619 (when (derived-mode-p 'org-mode)
21620 (easy-menu-change
21621 '("Org") "File List for Agenda"
21622 (append
21623 (list
21624 ["Edit File List" (org-edit-agenda-file-list) t]
21625 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21626 ["Remove Current File from List" org-remove-file t]
21627 ["Cycle through agenda files" org-cycle-agenda-files t]
21628 ["Occur in all agenda files" org-occur-in-agenda-files t]
21629 "--")
21630 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21632 ;;;; Documentation
21634 (defun org-require-autoloaded-modules ()
21635 (interactive)
21636 (mapc #'require
21637 '(org-agenda org-archive org-attach org-clock org-colview org-id
21638 org-table org-timer)))
21640 ;;;###autoload
21641 (defun org-reload (&optional uncompiled)
21642 "Reload all org lisp files.
21643 With prefix arg UNCOMPILED, load the uncompiled versions."
21644 (interactive "P")
21645 (require 'loadhist)
21646 (let* ((org-dir (org-find-library-dir "org"))
21647 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21648 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21649 (remove-re (format "\\`%s\\'"
21650 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21651 (feats (delete-dups
21652 (mapcar 'file-name-sans-extension
21653 (mapcar 'file-name-nondirectory
21654 (delq nil
21655 (mapcar 'feature-file
21656 features))))))
21657 (lfeat (append
21658 (sort
21659 (setq feats
21660 (delq nil (mapcar
21661 (lambda (f)
21662 (if (and (string-match feature-re f)
21663 (not (string-match remove-re f)))
21664 f nil))
21665 feats)))
21666 'string-lessp)
21667 (list "org-version" "org")))
21668 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21669 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21670 load-uncore load-misses)
21671 (setq load-misses
21672 (delq 't
21673 (mapcar (lambda (f)
21674 (or (org-load-noerror-mustsuffix (concat org-dir f))
21675 (and (string= org-dir contrib-dir)
21676 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21677 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21678 (add-to-list 'load-uncore f 'append)
21681 lfeat)))
21682 (when load-uncore
21683 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21684 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21685 (if load-misses
21686 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21687 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21688 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21690 ;;;###autoload
21691 (defun org-customize ()
21692 "Call the customize function with org as argument."
21693 (interactive)
21694 (org-load-modules-maybe)
21695 (org-require-autoloaded-modules)
21696 (customize-browse 'org))
21698 (defun org-create-customize-menu ()
21699 "Create a full customization menu for Org mode, insert it into the menu."
21700 (interactive)
21701 (org-load-modules-maybe)
21702 (org-require-autoloaded-modules)
21703 (if (fboundp 'customize-menu-create)
21704 (progn
21705 (easy-menu-change
21706 '("Org") "Customize"
21707 `(["Browse Org group" org-customize t]
21708 "--"
21709 ,(customize-menu-create 'org)
21710 ["Set" Custom-set t]
21711 ["Save" Custom-save t]
21712 ["Reset to Current" Custom-reset-current t]
21713 ["Reset to Saved" Custom-reset-saved t]
21714 ["Reset to Standard Settings" Custom-reset-standard t]))
21715 (message "\"Org\"-menu now contains full customization menu"))
21716 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21718 ;;;; Miscellaneous stuff
21720 ;;; Generally useful functions
21722 (defun org-get-at-eol (property n)
21723 "Get text property PROPERTY at the end of line less N characters."
21724 (get-text-property (- (point-at-eol) n) property))
21726 (defun org-find-text-property-in-string (prop s)
21727 "Return the first non-nil value of property PROP in string S."
21728 (or (get-text-property 0 prop s)
21729 (get-text-property (or (next-single-property-change 0 prop s) 0)
21730 prop s)))
21732 (defun org-display-warning (message)
21733 "Display the given MESSAGE as a warning."
21734 (display-warning 'org message :warning))
21736 (defun org-eval (form)
21737 "Eval FORM and return result."
21738 (condition-case error
21739 (eval form)
21740 (error (format "%%![Error: %s]" error))))
21742 (defun org-in-clocktable-p ()
21743 "Check if the cursor is in a clocktable."
21744 (let ((pos (point)) start)
21745 (save-excursion
21746 (end-of-line 1)
21747 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21748 (setq start (match-beginning 0))
21749 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21750 (>= (match-end 0) pos)
21751 start))))
21753 (defun org-in-verbatim-emphasis ()
21754 (save-match-data
21755 (and (org-in-regexp org-verbatim-re 2)
21756 (>= (point) (match-beginning 3))
21757 (<= (point) (match-end 4)))))
21759 (defun org-overlay-display (ovl text &optional face evap)
21760 "Make overlay OVL display TEXT with face FACE."
21761 (overlay-put ovl 'display text)
21762 (if face (overlay-put ovl 'face face))
21763 (if evap (overlay-put ovl 'evaporate t)))
21765 (defun org-overlay-before-string (ovl text &optional face evap)
21766 "Make overlay OVL display TEXT with face FACE."
21767 (if face (org-add-props text nil 'face face))
21768 (overlay-put ovl 'before-string text)
21769 (if evap (overlay-put ovl 'evaporate t)))
21771 (defun org-find-overlays (prop &optional pos delete)
21772 "Find all overlays specifying PROP at POS or point.
21773 If DELETE is non-nil, delete all those overlays."
21774 (let (found)
21775 (dolist (ov (overlays-at (or pos (point))) found)
21776 (cond ((not (overlay-get ov prop)))
21777 (delete (delete-overlay ov))
21778 (t (push ov found))))))
21780 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21781 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21782 (if (and marker (marker-buffer marker)
21783 (buffer-live-p (marker-buffer marker)))
21784 (progn
21785 (pop-to-buffer-same-window (marker-buffer marker))
21786 (when (or (> marker (point-max)) (< marker (point-min)))
21787 (widen))
21788 (goto-char marker)
21789 (org-show-context 'org-goto))
21790 (if bookmark
21791 (bookmark-jump bookmark)
21792 (error "Cannot find location"))))
21794 (defun org-quote-csv-field (s)
21795 "Quote field for inclusion in CSV material."
21796 (if (string-match "[\",]" s)
21797 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21800 (defun org-force-self-insert (N)
21801 "Needed to enforce self-insert under remapping."
21802 (interactive "p")
21803 (self-insert-command N))
21805 (defun org-string-width (s)
21806 "Compute width of string, ignoring invisible characters.
21807 This ignores character with invisibility property `org-link', and also
21808 characters with property `org-cwidth', because these will become invisible
21809 upon the next fontification round."
21810 (let (b l)
21811 (when (or (eq t buffer-invisibility-spec)
21812 (assq 'org-link buffer-invisibility-spec))
21813 (while (setq b (text-property-any 0 (length s)
21814 'invisible 'org-link s))
21815 (setq s (concat (substring s 0 b)
21816 (substring s (or (next-single-property-change
21817 b 'invisible s)
21818 (length s)))))))
21819 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21820 (setq s (concat (substring s 0 b)
21821 (substring s (or (next-single-property-change
21822 b 'org-cwidth s)
21823 (length s))))))
21824 (setq l (string-width s) b -1)
21825 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21826 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21829 (defun org-shorten-string (s maxlength)
21830 "Shorten string S so that it is no longer than MAXLENGTH characters.
21831 If the string is shorter or has length MAXLENGTH, just return the
21832 original string. If it is longer, the functions finds a space in the
21833 string, breaks this string off at that locations and adds three dots
21834 as ellipsis. Including the ellipsis, the string will not be longer
21835 than MAXLENGTH. If finding a good breaking point in the string does
21836 not work, the string is just chopped off in the middle of a word
21837 if necessary."
21838 (if (<= (length s) maxlength)
21840 (let* ((n (max (- maxlength 4) 1))
21841 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21842 (if (string-match re s)
21843 (concat (match-string 1 s) "...")
21844 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21846 (defun org-get-indentation (&optional line)
21847 "Get the indentation of the current line, interpreting tabs.
21848 When LINE is given, assume it represents a line and compute its indentation."
21849 (if line
21850 (when (string-match "^ *" (org-remove-tabs line))
21851 (match-end 0))
21852 (save-excursion
21853 (beginning-of-line 1)
21854 (skip-chars-forward " \t")
21855 (current-column))))
21857 (defun org-get-string-indentation (s)
21858 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21859 (let ((n -1) (i 0) (w tab-width) c)
21860 (catch 'exit
21861 (while (< (setq n (1+ n)) (length s))
21862 (setq c (aref s n))
21863 (cond ((= c ?\ ) (setq i (1+ i)))
21864 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21865 (t (throw 'exit t)))))
21868 (defun org-remove-tabs (s &optional width)
21869 "Replace tabulators in S with spaces.
21870 Assumes that s is a single line, starting in column 0."
21871 (setq width (or width tab-width))
21872 (while (string-match "\t" s)
21873 (setq s (replace-match
21874 (make-string
21875 (- (* width (/ (+ (match-beginning 0) width) width))
21876 (match-beginning 0)) ?\ )
21877 t t s)))
21880 (defun org-fix-indentation (line ind)
21881 "Fix indentation in LINE.
21882 IND is a cons cell with target and minimum indentation.
21883 If the current indentation in LINE is smaller than the minimum,
21884 leave it alone. If it is larger than ind, set it to the target."
21885 (let* ((l (org-remove-tabs line))
21886 (i (org-get-indentation l))
21887 (i1 (car ind)) (i2 (cdr ind)))
21888 (when (>= i i2) (setq l (substring line i2)))
21889 (if (> i1 0)
21890 (concat (make-string i1 ?\ ) l)
21891 l)))
21893 (defun org-remove-indentation (code &optional n)
21894 "Remove maximum common indentation in string CODE and return it.
21895 N may optionally be the number of columns to remove. Return CODE
21896 as-is if removal failed."
21897 (with-temp-buffer
21898 (insert code)
21899 (if (org-do-remove-indentation n) (buffer-string) code)))
21901 (defun org-do-remove-indentation (&optional n)
21902 "Remove the maximum common indentation from the buffer.
21903 When optional argument N is a positive integer, remove exactly
21904 that much characters from indentation, if possible. Return nil
21905 if it fails."
21906 (catch :exit
21907 (goto-char (point-min))
21908 ;; Find maximum common indentation, if not specified.
21909 (let ((n (or n
21910 (let ((min-ind (point-max)))
21911 (save-excursion
21912 (while (re-search-forward "^[ \t]*\\S-" nil t)
21913 (let ((ind (1- (current-column))))
21914 (if (zerop ind) (throw :exit nil)
21915 (setq min-ind (min min-ind ind))))))
21916 min-ind))))
21917 (if (zerop n) (throw :exit nil)
21918 ;; Remove exactly N indentation, but give up if not possible.
21919 (while (not (eobp))
21920 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21921 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21922 ((< ind n) (throw :exit nil))
21923 (t (indent-line-to (- ind n))))
21924 (forward-line)))
21925 ;; Signal success.
21926 t))))
21928 (defun org-fill-template (template alist)
21929 "Find each %key of ALIST in TEMPLATE and replace it."
21930 (let ((case-fold-search nil))
21931 (dolist (entry (sort (copy-sequence alist)
21932 (lambda (a b) (< (length (car a)) (length (car b))))))
21933 (setq template
21934 (replace-regexp-in-string
21935 (concat "%" (regexp-quote (car entry)))
21936 (or (cdr entry) "") template t t)))
21937 template))
21939 (defun org-base-buffer (buffer)
21940 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21941 (if (not buffer)
21942 buffer
21943 (or (buffer-base-buffer buffer)
21944 buffer)))
21946 (defun org-wrap (string &optional width lines)
21947 "Wrap string to either a number of lines, or a width in characters.
21948 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21949 that costs. If there is a word longer than WIDTH, the text is actually
21950 wrapped to the length of that word.
21951 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21952 many lines, whatever width that takes.
21953 The return value is a list of lines, without newlines at the end."
21954 (let* ((words (org-split-string string "[ \t\n]+"))
21955 (maxword (apply 'max (mapcar 'org-string-width words)))
21956 w ll)
21957 (cond (width
21958 (org-do-wrap words (max maxword width)))
21959 (lines
21960 (setq w maxword)
21961 (setq ll (org-do-wrap words maxword))
21962 (if (<= (length ll) lines)
21964 (setq ll words)
21965 (while (> (length ll) lines)
21966 (setq w (1+ w))
21967 (setq ll (org-do-wrap words w)))
21968 ll))
21969 (t (error "Cannot wrap this")))))
21971 (defun org-do-wrap (words width)
21972 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21973 (let (lines line)
21974 (while words
21975 (setq line (pop words))
21976 (while (and words (< (+ (length line) (length (car words))) width))
21977 (setq line (concat line " " (pop words))))
21978 (setq lines (push line lines)))
21979 (nreverse lines)))
21981 (defun org-split-string (string &optional separators)
21982 "Splits STRING into substrings at SEPARATORS.
21983 SEPARATORS is a regular expression.
21984 No empty strings are returned if there are matches at the beginning
21985 and end of string."
21986 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21987 (let ((start 0) notfirst list)
21988 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21989 (if (and notfirst
21990 (= start (match-beginning 0))
21991 (< start (length string)))
21992 (1+ start) start))
21993 (< (match-beginning 0) (length string)))
21994 (setq notfirst t)
21995 (or (eq (match-beginning 0) 0)
21996 (and (eq (match-beginning 0) (match-end 0))
21997 (eq (match-beginning 0) start))
21998 (push (substring string start (match-beginning 0)) list))
21999 (setq start (match-end 0)))
22000 (or (eq start (length string))
22001 (push (substring string start) list))
22002 (nreverse list)))
22004 (defun org-quote-vert (s)
22005 "Replace \"|\" with \"\\vert\"."
22006 (while (string-match "|" s)
22007 (setq s (replace-match "\\vert" t t s)))
22010 (defun org-uuidgen-p (s)
22011 "Is S an ID created by UUIDGEN?"
22012 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22014 (defun org-in-src-block-p (&optional inside)
22015 "Whether point is in a code source block.
22016 When INSIDE is non-nil, don't consider we are within a src block
22017 when point is at #+BEGIN_SRC or #+END_SRC."
22018 (let ((case-fold-search t))
22019 (or (and (eq (get-char-property (point) 'src-block) t))
22020 (and (not inside)
22021 (save-match-data
22022 (save-excursion
22023 (beginning-of-line)
22024 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22026 (defun org-context ()
22027 "Return a list of contexts of the current cursor position.
22028 If several contexts apply, all are returned.
22029 Each context entry is a list with a symbol naming the context, and
22030 two positions indicating start and end of the context. Possible
22031 contexts are:
22033 :headline anywhere in a headline
22034 :headline-stars on the leading stars in a headline
22035 :todo-keyword on a TODO keyword (including DONE) in a headline
22036 :tags on the TAGS in a headline
22037 :priority on the priority cookie in a headline
22038 :item on the first line of a plain list item
22039 :item-bullet on the bullet/number of a plain list item
22040 :checkbox on the checkbox in a plain list item
22041 :table in an Org table
22042 :table-special on a special filed in a table
22043 :table-table in a table.el table
22044 :clocktable in a clocktable
22045 :src-block in a source block
22046 :link on a hyperlink
22047 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22048 :target on a <<target>>
22049 :radio-target on a <<<radio-target>>>
22050 :latex-fragment on a LaTeX fragment
22051 :latex-preview on a LaTeX fragment with overlaid preview image
22053 This function expects the position to be visible because it uses font-lock
22054 faces as a help to recognize the following contexts: :table-special, :link,
22055 and :keyword."
22056 (let* ((f (get-text-property (point) 'face))
22057 (faces (if (listp f) f (list f)))
22058 (case-fold-search t)
22059 (p (point)) clist o)
22060 ;; First the large context
22061 (cond
22062 ((org-at-heading-p t)
22063 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22064 (when (progn
22065 (beginning-of-line 1)
22066 (looking-at org-todo-line-tags-regexp))
22067 (push (org-point-in-group p 1 :headline-stars) clist)
22068 (push (org-point-in-group p 2 :todo-keyword) clist)
22069 (push (org-point-in-group p 4 :tags) clist))
22070 (goto-char p)
22071 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22072 (when (looking-at "\\[#[A-Z0-9]\\]")
22073 (push (org-point-in-group p 0 :priority) clist)))
22075 ((org-at-item-p)
22076 (push (org-point-in-group p 2 :item-bullet) clist)
22077 (push (list :item (point-at-bol)
22078 (save-excursion (org-end-of-item) (point)))
22079 clist)
22080 (and (org-at-item-checkbox-p)
22081 (push (org-point-in-group p 0 :checkbox) clist)))
22083 ((org-at-table-p)
22084 (push (list :table (org-table-begin) (org-table-end)) clist)
22085 (when (memq 'org-formula faces)
22086 (push (list :table-special
22087 (previous-single-property-change p 'face)
22088 (next-single-property-change p 'face)) clist)))
22089 ((org-at-table-p 'any)
22090 (push (list :table-table) clist)))
22091 (goto-char p)
22093 (let ((case-fold-search t))
22094 ;; New the "medium" contexts: clocktables, source blocks
22095 (cond ((org-in-clocktable-p)
22096 (push (list :clocktable
22097 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22098 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22099 (match-beginning 1))
22100 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22101 (match-end 0))) clist))
22102 ((org-in-src-block-p)
22103 (push (list :src-block
22104 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22105 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22106 (match-beginning 1))
22107 (and (search-forward "#+END_SRC" nil t)
22108 (match-beginning 0))) clist))))
22109 (goto-char p)
22111 ;; Now the small context
22112 (cond
22113 ((org-at-timestamp-p)
22114 (push (org-point-in-group p 0 :timestamp) clist))
22115 ((memq 'org-link faces)
22116 (push (list :link
22117 (previous-single-property-change p 'face)
22118 (next-single-property-change p 'face)) clist))
22119 ((memq 'org-special-keyword faces)
22120 (push (list :keyword
22121 (previous-single-property-change p 'face)
22122 (next-single-property-change p 'face)) clist))
22123 ((org-at-target-p)
22124 (push (org-point-in-group p 0 :target) clist)
22125 (goto-char (1- (match-beginning 0)))
22126 (when (looking-at org-radio-target-regexp)
22127 (push (org-point-in-group p 0 :radio-target) clist))
22128 (goto-char p))
22129 ((setq o (cl-some
22130 (lambda (o)
22131 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22133 (overlays-at (point))))
22134 (push (list :latex-fragment
22135 (overlay-start o) (overlay-end o)) clist)
22136 (push (list :latex-preview
22137 (overlay-start o) (overlay-end o)) clist))
22138 ((org-inside-LaTeX-fragment-p)
22139 ;; FIXME: positions wrong.
22140 (push (list :latex-fragment (point) (point)) clist)))
22142 (setq clist (nreverse (delq nil clist)))
22143 clist))
22145 (defun org-in-regexp (regexp &optional nlines visually)
22146 "Check if point is inside a match of REGEXP.
22148 Normally only the current line is checked, but you can include
22149 NLINES extra lines around point into the search. If VISUALLY is
22150 set, require that the cursor is not after the match but really
22151 on, so that the block visually is on the match.
22153 Return nil or a cons cell (BEG . END) where BEG and END are,
22154 respectively, the positions at the beginning and the end of the
22155 match."
22156 (catch :exit
22157 (let ((pos (point))
22158 (eol (line-end-position (if nlines (1+ nlines) 1))))
22159 (save-excursion
22160 (beginning-of-line (- 1 (or nlines 0)))
22161 (while (and (re-search-forward regexp eol t)
22162 (<= (match-beginning 0) pos))
22163 (let ((end (match-end 0)))
22164 (when (or (> end pos) (and (= end pos) (not visually)))
22165 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22167 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22168 "Non-nil when point is between matches of START-RE and END-RE.
22170 Also return a non-nil value when point is on one of the matches.
22172 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22173 buffer positions. Default values are the positions of headlines
22174 surrounding the point.
22176 The functions returns a cons cell whose car (resp. cdr) is the
22177 position before START-RE (resp. after END-RE)."
22178 (save-match-data
22179 (let ((pos (point))
22180 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22181 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22182 beg end)
22183 (save-excursion
22184 ;; Point is on a block when on START-RE or if START-RE can be
22185 ;; found before it...
22186 (and (or (org-in-regexp start-re)
22187 (re-search-backward start-re limit-up t))
22188 (setq beg (match-beginning 0))
22189 ;; ... and END-RE after it...
22190 (goto-char (match-end 0))
22191 (re-search-forward end-re limit-down t)
22192 (> (setq end (match-end 0)) pos)
22193 ;; ... without another START-RE in-between.
22194 (goto-char (match-beginning 0))
22195 (not (re-search-backward start-re (1+ beg) t))
22196 ;; Return value.
22197 (cons beg end))))))
22199 (defun org-in-block-p (names)
22200 "Non-nil when point belongs to a block whose name belongs to NAMES.
22202 NAMES is a list of strings containing names of blocks.
22204 Return first block name matched, or nil. Beware that in case of
22205 nested blocks, the returned name may not belong to the closest
22206 block from point."
22207 (save-match-data
22208 (catch 'exit
22209 (let ((case-fold-search t)
22210 (lim-up (save-excursion (outline-previous-heading)))
22211 (lim-down (save-excursion (outline-next-heading))))
22212 (dolist (name names)
22213 (let ((n (regexp-quote name)))
22214 (when (org-between-regexps-p
22215 (concat "^[ \t]*#\\+begin_" n)
22216 (concat "^[ \t]*#\\+end_" n)
22217 lim-up lim-down)
22218 (throw 'exit n)))))
22219 nil)))
22221 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22222 "Call `multi-occur' with buffers for all agenda files."
22223 (interactive "sOrg-files matching: ")
22224 (let* ((files (org-agenda-files))
22225 (tnames (mapcar #'file-truename files))
22226 (extra org-agenda-text-search-extra-files))
22227 (when (eq (car extra) 'agenda-archives)
22228 (setq extra (cdr extra))
22229 (setq files (org-add-archive-files files)))
22230 (dolist (f extra)
22231 (unless (member (file-truename f) tnames)
22232 (unless (member f files) (setq files (append files (list f))))
22233 (setq tnames (append tnames (list (file-truename f))))))
22234 (multi-occur
22235 (mapcar (lambda (x)
22236 (with-current-buffer
22237 ;; FIXME: Why not just (find-file-noselect x)?
22238 ;; Is it to avoid the "revert buffer" prompt?
22239 (or (get-file-buffer x) (find-file-noselect x))
22240 (widen)
22241 (current-buffer)))
22242 files)
22243 regexp)))
22245 (add-hook 'occur-mode-find-occurrence-hook
22246 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22248 (defun org-occur-link-in-agenda-files ()
22249 "Create a link and search for it in the agendas.
22250 The link is not stored in `org-stored-links', it is just created
22251 for the search purpose."
22252 (interactive)
22253 (let ((link (condition-case nil
22254 (org-store-link nil)
22255 (error "Unable to create a link to here"))))
22256 (org-occur-in-agenda-files (regexp-quote link))))
22258 (defun org-reverse-string (string)
22259 "Return the reverse of STRING."
22260 (apply 'string (reverse (string-to-list string))))
22262 ;; defsubst org-uniquify must be defined before first use
22264 (defun org-uniquify-alist (alist)
22265 "Merge elements of ALIST with the same key.
22267 For example, in this alist:
22269 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22270 => \\='((a 1 3) (b 2))
22272 merge (a 1) and (a 3) into (a 1 3).
22274 The function returns the new ALIST."
22275 (let (rtn)
22276 (dolist (e alist rtn)
22277 (let (n)
22278 (if (not (assoc (car e) rtn))
22279 (push e rtn)
22280 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22281 (setq rtn (assq-delete-all (car e) rtn))
22282 (push n rtn))))))
22284 (defun org-delete-all (elts list)
22285 "Remove all elements in ELTS from LIST.
22286 Comparison is done with `equal'. It is a destructive operation
22287 that may remove elements by altering the list structure."
22288 (while elts
22289 (setq list (delete (pop elts) list)))
22290 list)
22292 (defun org-back-over-empty-lines ()
22293 "Move backwards over whitespace, to the beginning of the first empty line.
22294 Returns the number of empty lines passed."
22295 (let ((pos (point)))
22296 (if (cdr (assq 'heading org-blank-before-new-entry))
22297 (skip-chars-backward " \t\n\r")
22298 (unless (eobp)
22299 (forward-line -1)))
22300 (beginning-of-line 2)
22301 (goto-char (min (point) pos))
22302 (count-lines (point) pos)))
22304 (defun org-skip-whitespace ()
22305 (skip-chars-forward " \t\n\r"))
22307 (defun org-point-in-group (point group &optional context)
22308 "Check if POINT is in match-group GROUP.
22309 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22310 match. If the match group does not exist or point is not inside it,
22311 return nil."
22312 (and (match-beginning group)
22313 (>= point (match-beginning group))
22314 (<= point (match-end group))
22315 (if context
22316 (list context (match-beginning group) (match-end group))
22317 t)))
22319 (defun org-switch-to-buffer-other-window (&rest args)
22320 "Switch to buffer in a second window on the current frame.
22321 In particular, do not allow pop-up frames.
22322 Returns the newly created buffer."
22323 (org-no-popups
22324 (apply 'switch-to-buffer-other-window args)))
22326 (defun org-combine-plists (&rest plists)
22327 "Create a single property list from all plists in PLISTS.
22328 The process starts by copying the first list, and then setting properties
22329 from the other lists. Settings in the last list are the most significant
22330 ones and overrule settings in the other lists."
22331 (let ((rtn (copy-sequence (pop plists)))
22332 p v ls)
22333 (while plists
22334 (setq ls (pop plists))
22335 (while ls
22336 (setq p (pop ls) v (pop ls))
22337 (setq rtn (plist-put rtn p v))))
22338 rtn))
22340 (defun org-replace-escapes (string table)
22341 "Replace %-escapes in STRING with values in TABLE.
22342 TABLE is an association list with keys like \"%a\" and string values.
22343 The sequences in STRING may contain normal field width and padding information,
22344 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22345 so values can contain further %-escapes if they are define later in TABLE."
22346 (let ((tbl (copy-alist table))
22347 (case-fold-search nil)
22348 (pchg 0)
22349 re rpl)
22350 (dolist (e tbl)
22351 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22352 (when (and (cdr e) (string-match re (cdr e)))
22353 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22354 (safe "SREF"))
22355 (add-text-properties 0 3 (list 'sref sref) safe)
22356 (setcdr e (replace-match safe t t (cdr e)))))
22357 (while (string-match re string)
22358 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22359 (cdr e)))
22360 (setq string (replace-match rpl t t string))))
22361 (while (setq pchg (next-property-change pchg string))
22362 (let ((sref (get-text-property pchg 'sref string)))
22363 (when (and sref (string-match "SREF" string pchg))
22364 (setq string (replace-match sref t t string)))))
22365 string))
22367 (defun org-find-base-buffer-visiting (file)
22368 "Like `find-buffer-visiting' but always return the base buffer and
22369 not an indirect buffer."
22370 (let ((buf (or (get-file-buffer file)
22371 (find-buffer-visiting file))))
22372 (if buf
22373 (or (buffer-base-buffer buf) buf)
22374 nil)))
22376 ;;; TODO: Only called once, from ox-odt which should probably use
22377 ;;; org-export-inline-image-p or something.
22378 (defun org-file-image-p (file)
22379 "Return non-nil if FILE is an image."
22380 (save-match-data
22381 (string-match (image-file-name-regexp) file)))
22383 (defun org-get-cursor-date (&optional with-time)
22384 "Return the date at cursor in as a time.
22385 This works in the calendar and in the agenda, anywhere else it just
22386 returns the current time.
22387 If WITH-TIME is non-nil, returns the time of the event at point (in
22388 the agenda) or the current time of the day."
22389 (let (date day defd tp hod mod)
22390 (when with-time
22391 (setq tp (get-text-property (point) 'time))
22392 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22393 (setq hod (string-to-number (match-string 1 tp))
22394 mod (string-to-number (match-string 2 tp))))
22395 (or tp (let ((now (decode-time)))
22396 (setq hod (nth 2 now)
22397 mod (nth 1 now)))))
22398 (cond
22399 ((eq major-mode 'calendar-mode)
22400 (setq date (calendar-cursor-to-date)
22401 defd (encode-time 0 (or mod 0) (or hod 0)
22402 (nth 1 date) (nth 0 date) (nth 2 date))))
22403 ((eq major-mode 'org-agenda-mode)
22404 (setq day (get-text-property (point) 'day))
22405 (when day
22406 (setq date (calendar-gregorian-from-absolute day)
22407 defd (encode-time 0 (or mod 0) (or hod 0)
22408 (nth 1 date) (nth 0 date) (nth 2 date))))))
22409 (or defd (current-time))))
22411 (defun org-mark-subtree (&optional up)
22412 "Mark the current subtree.
22413 This puts point at the start of the current subtree, and mark at
22414 the end. If a numeric prefix UP is given, move up into the
22415 hierarchy of headlines by UP levels before marking the subtree."
22416 (interactive "P")
22417 (org-with-limited-levels
22418 (cond ((org-at-heading-p) (beginning-of-line))
22419 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22420 (t (outline-previous-visible-heading 1))))
22421 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22422 (if (called-interactively-p 'any)
22423 (call-interactively 'org-mark-element)
22424 (org-mark-element)))
22426 (defun org-file-newer-than-p (file time)
22427 "Non-nil if FILE is newer than TIME.
22428 FILE is a filename, as a string, TIME is a list of integers, as
22429 returned by, e.g., `current-time'."
22430 (and (file-exists-p file)
22431 ;; Only compare times up to whole seconds as some file-systems
22432 ;; (e.g. HFS+) do not retain any finer granularity. As
22433 ;; a consequence, make sure we return non-nil when the two
22434 ;; times are equal.
22435 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22436 (cl-subseq time 0 2)))))
22438 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22439 "Compile a SOURCE file using PROCESS.
22441 PROCESS is either a function or a list of shell commands, as
22442 strings. EXT is a file extension, without the leading dot, as
22443 a string. It is used to check if the process actually succeeded.
22445 PROCESS must create a file with the same base name and directory
22446 as SOURCE, but ending with EXT. The function then returns its
22447 filename. Otherwise, it raises an error. The error message can
22448 then be refined by providing string ERR-MSG, which is appended to
22449 the standard message.
22451 If PROCESS is a function, it is called with a single argument:
22452 the SOURCE file.
22454 If it is a list of commands, each of them is called using
22455 `shell-command'. By default, in each command, %b, %f, %F, %o and
22456 %O are replaced with, respectively, SOURCE base name, name, full
22457 name, directory and absolute output file name. It is possible,
22458 however, to use more place-holders by specifying them in optional
22459 argument SPEC, as an alist following the pattern
22461 (CHARACTER . REPLACEMENT-STRING).
22463 When PROCESS is a list of commands, optional argument LOG-BUF can
22464 be set to a buffer or a buffer name. `shell-command' then uses
22465 it for output."
22466 (let* ((base-name (file-name-base source))
22467 (full-name (file-truename source))
22468 (out-dir (or (file-name-directory source) "./"))
22469 (output (expand-file-name (concat base-name "." ext) out-dir))
22470 (time (current-time))
22471 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22472 (save-window-excursion
22473 (pcase process
22474 ((pred functionp) (funcall process (shell-quote-argument source)))
22475 ((pred consp)
22476 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22477 (spec (append spec
22478 `((?b . ,(shell-quote-argument base-name))
22479 (?f . ,(shell-quote-argument source))
22480 (?F . ,(shell-quote-argument full-name))
22481 (?o . ,(shell-quote-argument out-dir))
22482 (?O . ,(shell-quote-argument output))))))
22483 (dolist (command process)
22484 (shell-command (format-spec command spec) log-buf))
22485 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22486 (_ (error "No valid command to process %S%s" source err-msg))))
22487 ;; Check for process failure. Output file is expected to be
22488 ;; located in the same directory as SOURCE.
22489 (unless (org-file-newer-than-p output time)
22490 (error (format "File %S wasn't produced%s" output err-msg)))
22491 output))
22493 ;;; Indentation
22495 (defun org--get-expected-indentation (element contentsp)
22496 "Expected indentation column for current line, according to ELEMENT.
22497 ELEMENT is an element containing point. CONTENTSP is non-nil
22498 when indentation is to be computed according to contents of
22499 ELEMENT."
22500 (let ((type (org-element-type element))
22501 (start (org-element-property :begin element))
22502 (post-affiliated (org-element-property :post-affiliated element)))
22503 (org-with-wide-buffer
22504 (cond
22505 (contentsp
22506 (cl-case type
22507 ((diary-sexp footnote-definition) 0)
22508 ((headline inlinetask nil)
22509 (if (not org-adapt-indentation) 0
22510 (let ((level (org-current-level)))
22511 (if level (1+ level) 0))))
22512 ((item plain-list) (org-list-item-body-column post-affiliated))
22514 (goto-char start)
22515 (org-get-indentation))))
22516 ((memq type '(headline inlinetask nil))
22517 (if (org-match-line "[ \t]*$")
22518 (org--get-expected-indentation element t)
22520 ((memq type '(diary-sexp footnote-definition)) 0)
22521 ;; First paragraph of a footnote definition or an item.
22522 ;; Indent like parent.
22523 ((< (line-beginning-position) start)
22524 (org--get-expected-indentation
22525 (org-element-property :parent element) t))
22526 ;; At first line: indent according to previous sibling, if any,
22527 ;; ignoring footnote definitions and inline tasks, or parent's
22528 ;; contents.
22529 ((= (line-beginning-position) start)
22530 (catch 'exit
22531 (while t
22532 (if (= (point-min) start) (throw 'exit 0)
22533 (goto-char (1- start))
22534 (let* ((previous (org-element-at-point))
22535 (parent previous))
22536 (while (and parent (<= (org-element-property :end parent) start))
22537 (setq previous parent
22538 parent (org-element-property :parent parent)))
22539 (cond
22540 ((not previous) (throw 'exit 0))
22541 ((> (org-element-property :end previous) start)
22542 (throw 'exit (org--get-expected-indentation previous t)))
22543 ((memq (org-element-type previous)
22544 '(footnote-definition inlinetask))
22545 (setq start (org-element-property :begin previous)))
22546 (t (goto-char (org-element-property :begin previous))
22547 (throw 'exit
22548 (if (bolp) (org-get-indentation)
22549 ;; At first paragraph in an item or
22550 ;; a footnote definition.
22551 (org--get-expected-indentation
22552 (org-element-property :parent previous) t))))))))))
22553 ;; Otherwise, move to the first non-blank line above.
22555 (beginning-of-line)
22556 (let ((pos (point)))
22557 (skip-chars-backward " \r\t\n")
22558 (cond
22559 ;; Two blank lines end a footnote definition or a plain
22560 ;; list. When we indent an empty line after them, the
22561 ;; containing list or footnote definition is over, so it
22562 ;; qualifies as a previous sibling. Therefore, we indent
22563 ;; like its first line.
22564 ((and (memq type '(footnote-definition plain-list))
22565 (> (count-lines (point) pos) 2))
22566 (goto-char start)
22567 (org-get-indentation))
22568 ;; Line above is the first one of a paragraph at the
22569 ;; beginning of an item or a footnote definition. Indent
22570 ;; like parent.
22571 ((< (line-beginning-position) start)
22572 (org--get-expected-indentation
22573 (org-element-property :parent element) t))
22574 ;; Line above is the beginning of an element, i.e., point
22575 ;; was originally on the blank lines between element's start
22576 ;; and contents.
22577 ((= (line-beginning-position) post-affiliated)
22578 (org--get-expected-indentation element t))
22579 ;; POS is after contents in a greater element. Indent like
22580 ;; the beginning of the element.
22581 ((and (memq type org-element-greater-elements)
22582 (let ((cend (org-element-property :contents-end element)))
22583 (and cend (<= cend pos))))
22584 ;; As a special case, if point is at the end of a footnote
22585 ;; definition or an item, indent like the very last element
22586 ;; within. If that last element is an item, indent like
22587 ;; its contents.
22588 (if (memq type '(footnote-definition item plain-list))
22589 (let ((last (org-element-at-point)))
22590 (goto-char pos)
22591 (org--get-expected-indentation
22592 last (eq (org-element-type last) 'item)))
22593 (goto-char start)
22594 (org-get-indentation)))
22595 ;; In any other case, indent like the current line.
22596 (t (org-get-indentation)))))))))
22598 (defun org--align-node-property ()
22599 "Align node property at point.
22600 Alignment is done according to `org-property-format', which see."
22601 (when (save-excursion
22602 (beginning-of-line)
22603 (looking-at org-property-re))
22604 (replace-match
22605 (concat (match-string 4)
22606 (org-trim
22607 (format org-property-format (match-string 1) (match-string 3))))
22608 t t)))
22610 (defun org-indent-line ()
22611 "Indent line depending on context.
22613 Indentation is done according to the following rules:
22615 - Footnote definitions, diary sexps, headlines and inline tasks
22616 have to start at column 0.
22618 - On the very first line of an element, consider, in order, the
22619 next rules until one matches:
22621 1. If there's a sibling element before, ignoring footnote
22622 definitions and inline tasks, indent like its first line.
22624 2. If element has a parent, indent like its contents. More
22625 precisely, if parent is an item, indent after the
22626 description part, if any, or the bullet (see
22627 `org-list-description-max-indent'). Else, indent like
22628 parent's first line.
22630 3. Otherwise, indent relatively to current level, if
22631 `org-adapt-indentation' is non-nil, or to left margin.
22633 - On a blank line at the end of an element, indent according to
22634 the type of the element. More precisely
22636 1. If element is a plain list, an item, or a footnote
22637 definition, indent like the very last element within.
22639 2. If element is a paragraph, indent like its last non blank
22640 line.
22642 3. Otherwise, indent like its very first line.
22644 - In the code part of a source block, use language major mode
22645 to indent current line if `org-src-tab-acts-natively' is
22646 non-nil. If it is nil, do nothing.
22648 - Otherwise, indent like the first non-blank line above.
22650 The function doesn't indent an item as it could break the whole
22651 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22652 `\\[org-shiftmetaright]'.
22654 Also align node properties according to `org-property-format'."
22655 (interactive)
22656 (cond
22657 (orgstruct-is-++
22658 (let ((indent-line-function
22659 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22660 (indent-according-to-mode)))
22661 ((org-at-heading-p) 'noindent)
22663 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22664 (type (org-element-type element)))
22665 (cond ((and (memq type '(plain-list item))
22666 (= (line-beginning-position)
22667 (org-element-property :post-affiliated element)))
22668 'noindent)
22669 ((and (eq type 'latex-environment)
22670 (>= (point) (org-element-property :post-affiliated element))
22671 (< (point) (org-with-wide-buffer
22672 (goto-char (org-element-property :end element))
22673 (skip-chars-backward " \r\t\n")
22674 (line-beginning-position 2))))
22675 'noindent)
22676 ((and (eq type 'src-block)
22677 org-src-tab-acts-natively
22678 (> (line-beginning-position)
22679 (org-element-property :post-affiliated element))
22680 (< (line-beginning-position)
22681 (org-with-wide-buffer
22682 (goto-char (org-element-property :end element))
22683 (skip-chars-backward " \r\t\n")
22684 (line-beginning-position))))
22685 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22687 (let ((column (org--get-expected-indentation element nil)))
22688 ;; Preserve current column.
22689 (if (<= (current-column) (current-indentation))
22690 (indent-line-to column)
22691 (save-excursion (indent-line-to column))))
22692 ;; Align node property. Also preserve current column.
22693 (when (eq type 'node-property)
22694 (let ((column (current-column)))
22695 (org--align-node-property)
22696 (org-move-to-column column)))))))))
22698 (defun org-indent-region (start end)
22699 "Indent each non-blank line in the region.
22700 Called from a program, START and END specify the region to
22701 indent. The function will not indent contents of example blocks,
22702 verse blocks and export blocks as leading white spaces are
22703 assumed to be significant there."
22704 (interactive "r")
22705 (save-excursion
22706 (goto-char start)
22707 (skip-chars-forward " \r\t\n")
22708 (unless (eobp) (beginning-of-line))
22709 (let ((indent-to
22710 (lambda (ind pos)
22711 ;; Set IND as indentation for all lines between point and
22712 ;; POS. Blank lines are ignored. Leave point after POS
22713 ;; once done.
22714 (let ((limit (copy-marker pos)))
22715 (while (< (point) limit)
22716 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22717 (forward-line))
22718 (set-marker limit nil))))
22719 (end (copy-marker end)))
22720 (while (< (point) end)
22721 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22722 (let* ((element (org-element-at-point))
22723 (type (org-element-type element))
22724 (element-end (copy-marker (org-element-property :end element)))
22725 (ind (org--get-expected-indentation element nil)))
22726 (cond
22727 ;; Element indented as a single block. Example blocks
22728 ;; preserving indentation are a special case since the
22729 ;; "contents" must not be indented whereas the block
22730 ;; boundaries can.
22731 ((or (memq type '(export-block latex-environment))
22732 (and (eq type 'example-block)
22733 (not
22734 (or org-src-preserve-indentation
22735 (org-element-property :preserve-indent element)))))
22736 (let ((offset (- ind (org-get-indentation))))
22737 (unless (zerop offset)
22738 (indent-rigidly (org-element-property :begin element)
22739 (org-element-property :end element)
22740 offset)))
22741 (goto-char element-end))
22742 ;; Elements indented line wise. Be sure to exclude
22743 ;; example blocks (preserving indentation) and source
22744 ;; blocks from this category as they are treated
22745 ;; specially later.
22746 ((or (memq type '(paragraph table table-row))
22747 (not (or (org-element-property :contents-begin element)
22748 (memq type '(example-block src-block)))))
22749 (when (eq type 'node-property)
22750 (org--align-node-property)
22751 (beginning-of-line))
22752 (funcall indent-to ind (min element-end end)))
22753 ;; Elements consisting of three parts: before the
22754 ;; contents, the contents, and after the contents. The
22755 ;; contents are treated specially, according to the
22756 ;; element type, or not indented at all. Other parts are
22757 ;; indented as a single block.
22759 (let* ((post (copy-marker
22760 (org-element-property :post-affiliated element)))
22761 (cbeg
22762 (copy-marker
22763 (cond
22764 ((not (org-element-property :contents-begin element))
22765 ;; Fake contents for source blocks.
22766 (org-with-wide-buffer
22767 (goto-char post)
22768 (line-beginning-position 2)))
22769 ((memq type '(footnote-definition item plain-list))
22770 ;; Contents in these elements could start on
22771 ;; the same line as the beginning of the
22772 ;; element. Make sure we start indenting
22773 ;; from the second line.
22774 (org-with-wide-buffer
22775 (goto-char post)
22776 (end-of-line)
22777 (skip-chars-forward " \r\t\n")
22778 (if (eobp) (point) (line-beginning-position))))
22779 (t (org-element-property :contents-begin element)))))
22780 (cend (copy-marker
22781 (or (org-element-property :contents-end element)
22782 ;; Fake contents for source blocks.
22783 (org-with-wide-buffer
22784 (goto-char element-end)
22785 (skip-chars-backward " \r\t\n")
22786 (line-beginning-position)))
22787 t)))
22788 ;; Do not change items indentation individually as it
22789 ;; might break the list as a whole. On the other
22790 ;; hand, when at a plain list, indent it as a whole.
22791 (cond ((eq type 'plain-list)
22792 (let ((offset (- ind (org-get-indentation))))
22793 (unless (zerop offset)
22794 (indent-rigidly (org-element-property :begin element)
22795 (org-element-property :end element)
22796 offset))
22797 (goto-char cbeg)))
22798 ((eq type 'item) (goto-char cbeg))
22799 (t (funcall indent-to ind (min cbeg end))))
22800 (when (< (point) end)
22801 (cl-case type
22802 ((example-block verse-block))
22803 (src-block
22804 ;; In a source block, indent source code
22805 ;; according to language major mode, but only if
22806 ;; `org-src-tab-acts-natively' is non-nil.
22807 (when (and (< (point) end) org-src-tab-acts-natively)
22808 (ignore-errors
22809 (org-babel-do-in-edit-buffer
22810 (indent-region (point-min) (point-max))))))
22811 (t (org-indent-region (point) (min cend end))))
22812 (goto-char (min cend end))
22813 (when (< (point) end)
22814 (funcall indent-to ind (min element-end end))))
22815 (set-marker post nil)
22816 (set-marker cbeg nil)
22817 (set-marker cend nil))))
22818 (set-marker element-end nil))))
22819 (set-marker end nil))))
22821 (defun org-indent-drawer ()
22822 "Indent the drawer at point."
22823 (interactive)
22824 (unless (save-excursion
22825 (beginning-of-line)
22826 (looking-at-p org-drawer-regexp))
22827 (user-error "Not at a drawer"))
22828 (let ((element (org-element-at-point)))
22829 (unless (memq (org-element-type element) '(drawer property-drawer))
22830 (user-error "Not at a drawer"))
22831 (org-with-wide-buffer
22832 (org-indent-region (org-element-property :begin element)
22833 (org-element-property :end element))))
22834 (message "Drawer at point indented"))
22836 (defun org-indent-block ()
22837 "Indent the block at point."
22838 (interactive)
22839 (unless (save-excursion
22840 (beginning-of-line)
22841 (let ((case-fold-search t))
22842 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22843 (user-error "Not at a block"))
22844 (let ((element (org-element-at-point)))
22845 (unless (memq (org-element-type element)
22846 '(comment-block center-block dynamic-block example-block
22847 export-block quote-block special-block
22848 src-block verse-block))
22849 (user-error "Not at a block"))
22850 (org-with-wide-buffer
22851 (org-indent-region (org-element-property :begin element)
22852 (org-element-property :end element))))
22853 (message "Block at point indented"))
22856 ;;; Filling
22858 ;; We use our own fill-paragraph and auto-fill functions.
22860 ;; `org-fill-paragraph' relies on adaptive filling and context
22861 ;; checking. Appropriate `fill-prefix' is computed with
22862 ;; `org-adaptive-fill-function'.
22864 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22865 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22866 ;; `org-adaptive-fill-function' value. Internally,
22867 ;; `org-comment-line-break-function' breaks the line.
22869 ;; `org-setup-filling' installs filling and auto-filling related
22870 ;; variables during `org-mode' initialization.
22872 (defvar org-element-paragraph-separate) ; org-element.el
22873 (defun org-setup-filling ()
22874 (require 'org-element)
22875 ;; Prevent auto-fill from inserting unwanted new items.
22876 (when (boundp 'fill-nobreak-predicate)
22877 (setq-local
22878 fill-nobreak-predicate
22879 (org-uniquify
22880 (append fill-nobreak-predicate
22881 '(org-fill-line-break-nobreak-p
22882 org-fill-paragraph-with-timestamp-nobreak-p)))))
22883 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22884 (setq-local paragraph-start paragraph-ending)
22885 (setq-local paragraph-separate paragraph-ending))
22886 (setq-local fill-paragraph-function 'org-fill-paragraph)
22887 (setq-local auto-fill-inhibit-regexp nil)
22888 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22889 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22890 (setq-local comment-line-break-function 'org-comment-line-break-function))
22892 (defun org-fill-line-break-nobreak-p ()
22893 "Non-nil when a new line at point would create an Org line break."
22894 (save-excursion
22895 (skip-chars-backward "[ \t]")
22896 (skip-chars-backward "\\\\")
22897 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22899 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22900 "Non-nil when a new line at point would split a timestamp."
22901 (and (org-at-timestamp-p t)
22902 (not (looking-at org-ts-regexp-both))))
22904 (declare-function message-in-body-p "message" ())
22905 (defvar orgtbl-line-start-regexp) ; From org-table.el
22906 (defun org-adaptive-fill-function ()
22907 "Compute a fill prefix for the current line.
22908 Return fill prefix, as a string, or nil if current line isn't
22909 meant to be filled. For convenience, if `adaptive-fill-regexp'
22910 matches in paragraphs or comments, use it."
22911 (catch 'exit
22912 (when (derived-mode-p 'message-mode)
22913 (save-excursion
22914 (beginning-of-line)
22915 (cond ((not (message-in-body-p)) (throw 'exit nil))
22916 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22917 ((looking-at message-cite-prefix-regexp)
22918 (throw 'exit (match-string-no-properties 0)))
22919 ((looking-at org-outline-regexp)
22920 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22921 (org-with-wide-buffer
22922 (unless (org-at-heading-p)
22923 (let* ((p (line-beginning-position))
22924 (element (save-excursion
22925 (beginning-of-line)
22926 (org-element-at-point)))
22927 (type (org-element-type element))
22928 (post-affiliated (org-element-property :post-affiliated element)))
22929 (unless (< p post-affiliated)
22930 (cl-case type
22931 (comment
22932 (save-excursion
22933 (beginning-of-line)
22934 (looking-at "[ \t]*")
22935 (concat (match-string 0) "# ")))
22936 (footnote-definition "")
22937 ((item plain-list)
22938 (make-string (org-list-item-body-column post-affiliated) ?\s))
22939 (paragraph
22940 ;; Fill prefix is usually the same as the current line,
22941 ;; unless the paragraph is at the beginning of an item.
22942 (let ((parent (org-element-property :parent element)))
22943 (save-excursion
22944 (beginning-of-line)
22945 (cond ((eq (org-element-type parent) 'item)
22946 (make-string (org-list-item-body-column
22947 (org-element-property :begin parent))
22948 ?\s))
22949 ((and adaptive-fill-regexp
22950 ;; Locally disable
22951 ;; `adaptive-fill-function' to let
22952 ;; `fill-context-prefix' handle
22953 ;; `adaptive-fill-regexp' variable.
22954 (let (adaptive-fill-function)
22955 (fill-context-prefix
22956 post-affiliated
22957 (org-element-property :end element)))))
22958 ((looking-at "[ \t]+") (match-string 0))
22959 (t "")))))
22960 (comment-block
22961 ;; Only fill contents if P is within block boundaries.
22962 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22963 (forward-line)
22964 (point)))
22965 (cend (save-excursion
22966 (goto-char (org-element-property :end element))
22967 (skip-chars-backward " \r\t\n")
22968 (line-beginning-position))))
22969 (when (and (>= p cbeg) (< p cend))
22970 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22971 (match-string 0)
22972 "")))))))))))
22974 (declare-function message-goto-body "message" ())
22975 (defvar message-cite-prefix-regexp) ; From message.el
22976 (defun org-fill-paragraph (&optional justify)
22977 "Fill element at point, when applicable.
22979 This function only applies to comment blocks, comments, example
22980 blocks and paragraphs. Also, as a special case, re-align table
22981 when point is at one.
22983 If JUSTIFY is non-nil (interactively, with prefix argument),
22984 justify as well. If `sentence-end-double-space' is non-nil, then
22985 period followed by one space does not end a sentence, so don't
22986 break a line there. The variable `fill-column' controls the
22987 width for filling.
22989 For convenience, when point is at a plain list, an item or
22990 a footnote definition, try to fill the first paragraph within."
22991 (interactive)
22992 (if (and (derived-mode-p 'message-mode)
22993 (or (not (message-in-body-p))
22994 (save-excursion (move-beginning-of-line 1)
22995 (looking-at message-cite-prefix-regexp))))
22996 ;; First ensure filling is correct in message-mode.
22997 (let ((fill-paragraph-function
22998 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22999 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23000 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23001 (paragraph-separate
23002 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23003 (fill-paragraph nil))
23004 (with-syntax-table org-mode-transpose-word-syntax-table
23005 ;; Move to end of line in order to get the first paragraph
23006 ;; within a plain list or a footnote definition.
23007 (let ((element (save-excursion
23008 (end-of-line)
23009 (or (ignore-errors (org-element-at-point))
23010 (user-error "An element cannot be parsed line %d"
23011 (line-number-at-pos (point)))))))
23012 ;; First check if point is in a blank line at the beginning of
23013 ;; the buffer. In that case, ignore filling.
23014 (cl-case (org-element-type element)
23015 ;; Use major mode filling function is src blocks.
23016 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23017 ;; Align Org tables, leave table.el tables as-is.
23018 (table-row (org-table-align) t)
23019 (table
23020 (when (eq (org-element-property :type element) 'org)
23021 (save-excursion
23022 (goto-char (org-element-property :post-affiliated element))
23023 (org-table-align)))
23025 (paragraph
23026 ;; Paragraphs may contain `line-break' type objects.
23027 (let ((beg (max (point-min)
23028 (org-element-property :contents-begin element)))
23029 (end (min (point-max)
23030 (org-element-property :contents-end element))))
23031 ;; Do nothing if point is at an affiliated keyword.
23032 (if (< (line-end-position) beg) t
23033 (when (derived-mode-p 'message-mode)
23034 ;; In `message-mode', do not fill following citation
23035 ;; in current paragraph nor text before message body.
23036 (let ((body-start (save-excursion (message-goto-body))))
23037 (when body-start (setq beg (max body-start beg))))
23038 (when (save-excursion
23039 (re-search-forward
23040 (concat "^" message-cite-prefix-regexp) end t))
23041 (setq end (match-beginning 0))))
23042 ;; Fill paragraph, taking line breaks into account.
23043 (save-excursion
23044 (goto-char beg)
23045 (let ((cuts (list beg)))
23046 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23047 (when (eq 'line-break
23048 (org-element-type
23049 (save-excursion (backward-char)
23050 (org-element-context))))
23051 (push (point) cuts)))
23052 (dolist (c (delq end cuts))
23053 (fill-region-as-paragraph c end justify)
23054 (setq end c))))
23055 t)))
23056 ;; Contents of `comment-block' type elements should be
23057 ;; filled as plain text, but only if point is within block
23058 ;; markers.
23059 (comment-block
23060 (let* ((case-fold-search t)
23061 (beg (save-excursion
23062 (goto-char (org-element-property :begin element))
23063 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23064 (forward-line)
23065 (point)))
23066 (end (save-excursion
23067 (goto-char (org-element-property :end element))
23068 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23069 (line-beginning-position))))
23070 (if (or (< (point) beg) (> (point) end)) t
23071 (fill-region-as-paragraph
23072 (save-excursion (end-of-line)
23073 (re-search-backward "^[ \t]*$" beg 'move)
23074 (line-beginning-position))
23075 (save-excursion (beginning-of-line)
23076 (re-search-forward "^[ \t]*$" end 'move)
23077 (line-beginning-position))
23078 justify))))
23079 ;; Fill comments.
23080 (comment
23081 (let ((begin (org-element-property :post-affiliated element))
23082 (end (org-element-property :end element)))
23083 (when (and (>= (point) begin) (<= (point) end))
23084 (let ((begin (save-excursion
23085 (end-of-line)
23086 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23087 (progn (forward-line) (point))
23088 begin)))
23089 (end (save-excursion
23090 (end-of-line)
23091 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23092 (1- (line-beginning-position))
23093 (skip-chars-backward " \r\t\n")
23094 (line-end-position)))))
23095 ;; Do not fill comments when at a blank line.
23096 (when (> end begin)
23097 (let ((fill-prefix
23098 (save-excursion
23099 (beginning-of-line)
23100 (looking-at "[ \t]*#")
23101 (let ((comment-prefix (match-string 0)))
23102 (goto-char (match-end 0))
23103 (if (looking-at adaptive-fill-regexp)
23104 (concat comment-prefix (match-string 0))
23105 (concat comment-prefix " "))))))
23106 (save-excursion
23107 (fill-region-as-paragraph begin end justify))))))
23109 ;; Ignore every other element.
23110 (otherwise t))))))
23112 (defun org-auto-fill-function ()
23113 "Auto-fill function."
23114 ;; Check if auto-filling is meaningful.
23115 (let ((fc (current-fill-column)))
23116 (when (and fc (> (current-column) fc))
23117 (let* ((fill-prefix (org-adaptive-fill-function))
23118 ;; Enforce empty fill prefix, if required. Otherwise, it
23119 ;; will be computed again.
23120 (adaptive-fill-mode (not (equal fill-prefix ""))))
23121 (when fill-prefix (do-auto-fill))))))
23123 (defun org-comment-line-break-function (&optional soft)
23124 "Break line at point and indent, continuing comment if within one.
23125 The inserted newline is marked hard if variable
23126 `use-hard-newlines' is true, unless optional argument SOFT is
23127 non-nil."
23128 (if soft (insert-and-inherit ?\n) (newline 1))
23129 (save-excursion (forward-char -1) (delete-horizontal-space))
23130 (delete-horizontal-space)
23131 (indent-to-left-margin)
23132 (insert-before-markers-and-inherit fill-prefix))
23135 ;;; Fixed Width Areas
23137 (defun org-toggle-fixed-width ()
23138 "Toggle fixed-width markup.
23140 Add or remove fixed-width markup on current line, whenever it
23141 makes sense. Return an error otherwise.
23143 If a region is active and if it contains only fixed-width areas
23144 or blank lines, remove all fixed-width markup in it. If the
23145 region contains anything else, convert all non-fixed-width lines
23146 to fixed-width ones.
23148 Blank lines at the end of the region are ignored unless the
23149 region only contains such lines."
23150 (interactive)
23151 (if (not (org-region-active-p))
23152 ;; No region:
23154 ;; Remove fixed width marker only in a fixed-with element.
23156 ;; Add fixed width maker in paragraphs, in blank lines after
23157 ;; elements or at the beginning of a headline or an inlinetask,
23158 ;; and before any one-line elements (e.g., a clock).
23159 (progn
23160 (beginning-of-line)
23161 (let* ((element (org-element-at-point))
23162 (type (org-element-type element)))
23163 (cond
23164 ((and (eq type 'fixed-width)
23165 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23166 (replace-match
23167 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23168 ((and (memq type '(babel-call clock comment diary-sexp headline
23169 horizontal-rule keyword paragraph
23170 planning))
23171 (<= (org-element-property :post-affiliated element) (point)))
23172 (skip-chars-forward " \t")
23173 (insert ": "))
23174 ((and (looking-at-p "[ \t]*$")
23175 (or (eq type 'inlinetask)
23176 (save-excursion
23177 (skip-chars-forward " \r\t\n")
23178 (<= (org-element-property :end element) (point)))))
23179 (delete-region (point) (line-end-position))
23180 (org-indent-line)
23181 (insert ": "))
23182 (t (user-error "Cannot insert a fixed-width line here")))))
23183 ;; Region active.
23184 (let* ((begin (save-excursion
23185 (goto-char (region-beginning))
23186 (line-beginning-position)))
23187 (end (copy-marker
23188 (save-excursion
23189 (goto-char (region-end))
23190 (unless (eolp) (beginning-of-line))
23191 (if (save-excursion (re-search-backward "\\S-" begin t))
23192 (progn (skip-chars-backward " \r\t\n") (point))
23193 (point)))))
23194 (all-fixed-width-p
23195 (catch 'not-all-p
23196 (save-excursion
23197 (goto-char begin)
23198 (skip-chars-forward " \r\t\n")
23199 (when (eobp) (throw 'not-all-p nil))
23200 (while (< (point) end)
23201 (let ((element (org-element-at-point)))
23202 (if (eq (org-element-type element) 'fixed-width)
23203 (goto-char (org-element-property :end element))
23204 (throw 'not-all-p nil))))
23205 t))))
23206 (if all-fixed-width-p
23207 (save-excursion
23208 (goto-char begin)
23209 (while (< (point) end)
23210 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23211 (replace-match
23212 "" nil nil nil
23213 (if (= (line-end-position) (match-end 0)) 0 1)))
23214 (forward-line)))
23215 (let ((min-ind (point-max)))
23216 ;; Find minimum indentation across all lines.
23217 (save-excursion
23218 (goto-char begin)
23219 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23220 (setq min-ind 0)
23221 (catch 'zerop
23222 (while (< (point) end)
23223 (unless (looking-at-p "[ \t]*$")
23224 (let ((ind (org-get-indentation)))
23225 (setq min-ind (min min-ind ind))
23226 (when (zerop ind) (throw 'zerop t))))
23227 (forward-line)))))
23228 ;; Loop over all lines and add fixed-width markup everywhere
23229 ;; but in fixed-width lines.
23230 (save-excursion
23231 (goto-char begin)
23232 (while (< (point) end)
23233 (cond
23234 ((org-at-heading-p)
23235 (insert ": ")
23236 (forward-line)
23237 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23238 (insert ":")
23239 (forward-line)))
23240 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23241 (let* ((element (org-element-at-point))
23242 (element-end (org-element-property :end element)))
23243 (if (eq (org-element-type element) 'fixed-width)
23244 (progn (goto-char element-end)
23245 (skip-chars-backward " \r\t\n")
23246 (forward-line))
23247 (let ((limit (min end element-end)))
23248 (while (< (point) limit)
23249 (org-move-to-column min-ind t)
23250 (insert ": ")
23251 (forward-line))))))
23253 (org-move-to-column min-ind t)
23254 (insert ": ")
23255 (forward-line)))))))
23256 (set-marker end nil))))
23259 ;;; Comments
23261 ;; Org comments syntax is quite complex. It requires the entire line
23262 ;; to be just a comment. Also, even with the right syntax at the
23263 ;; beginning of line, some some elements (i.e. verse-block or
23264 ;; example-block) don't accept comments. Usual Emacs comment commands
23265 ;; cannot cope with those requirements. Therefore, Org replaces them.
23267 ;; Org still relies on `comment-dwim', but cannot trust
23268 ;; `comment-only-p'. So, `comment-region-function' and
23269 ;; `uncomment-region-function' both point
23270 ;; to`org-comment-or-uncomment-region'. Eventually,
23271 ;; `org-insert-comment' takes care of insertion of comments at the
23272 ;; beginning of line.
23274 ;; `org-setup-comments-handling' install comments related variables
23275 ;; during `org-mode' initialization.
23277 (defun org-setup-comments-handling ()
23278 (interactive)
23279 (setq-local comment-use-syntax nil)
23280 (setq-local comment-start "# ")
23281 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23282 (setq-local comment-insert-comment-function 'org-insert-comment)
23283 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23284 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23286 (defun org-insert-comment ()
23287 "Insert an empty comment above current line.
23288 If the line is empty, insert comment at its beginning. When
23289 point is within a source block, comment according to the related
23290 major mode."
23291 (if (let ((element (org-element-at-point)))
23292 (and (eq (org-element-type element) 'src-block)
23293 (< (save-excursion
23294 (goto-char (org-element-property :post-affiliated element))
23295 (line-end-position))
23296 (point))
23297 (> (save-excursion
23298 (goto-char (org-element-property :end element))
23299 (skip-chars-backward " \r\t\n")
23300 (line-beginning-position))
23301 (point))))
23302 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23303 (beginning-of-line)
23304 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23305 (open-line 1))
23306 (org-indent-line)
23307 (insert "# ")))
23309 (defvar comment-empty-lines) ; From newcomment.el.
23310 (defun org-comment-or-uncomment-region (beg end &rest _)
23311 "Comment or uncomment each non-blank line in the region.
23312 Uncomment each non-blank line between BEG and END if it only
23313 contains commented lines. Otherwise, comment them. If region is
23314 strictly within a source block, use appropriate comment syntax."
23315 (if (let ((element (org-element-at-point)))
23316 (and (eq (org-element-type element) 'src-block)
23317 (< (save-excursion
23318 (goto-char (org-element-property :post-affiliated element))
23319 (line-end-position))
23320 beg)
23321 (>= (save-excursion
23322 (goto-char (org-element-property :end element))
23323 (skip-chars-backward " \r\t\n")
23324 (line-beginning-position))
23325 end)))
23326 ;; Translate region boundaries for the Org buffer to the source
23327 ;; buffer.
23328 (let ((offset (- end beg)))
23329 (save-excursion
23330 (goto-char beg)
23331 (org-babel-do-in-edit-buffer
23332 (comment-or-uncomment-region (point) (+ offset (point))))))
23333 (save-restriction
23334 ;; Restrict region
23335 (narrow-to-region (save-excursion (goto-char beg)
23336 (skip-chars-forward " \r\t\n" end)
23337 (line-beginning-position))
23338 (save-excursion (goto-char end)
23339 (skip-chars-backward " \r\t\n" beg)
23340 (line-end-position)))
23341 (let ((uncommentp
23342 ;; UNCOMMENTP is non-nil when every non blank line between
23343 ;; BEG and END is a comment.
23344 (save-excursion
23345 (goto-char (point-min))
23346 (while (and (not (eobp))
23347 (let ((element (org-element-at-point)))
23348 (and (eq (org-element-type element) 'comment)
23349 (goto-char (min (point-max)
23350 (org-element-property
23351 :end element)))))))
23352 (eobp))))
23353 (if uncommentp
23354 ;; Only blank lines and comments in region: uncomment it.
23355 (save-excursion
23356 (goto-char (point-min))
23357 (while (not (eobp))
23358 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23359 (replace-match "" nil nil nil 1))
23360 (forward-line)))
23361 ;; Comment each line in region.
23362 (let ((min-indent (point-max)))
23363 ;; First find the minimum indentation across all lines.
23364 (save-excursion
23365 (goto-char (point-min))
23366 (while (and (not (eobp)) (not (zerop min-indent)))
23367 (unless (looking-at "[ \t]*$")
23368 (setq min-indent (min min-indent (current-indentation))))
23369 (forward-line)))
23370 ;; Then loop over all lines.
23371 (save-excursion
23372 (goto-char (point-min))
23373 (while (not (eobp))
23374 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23375 ;; Don't get fooled by invisible text (e.g. link path)
23376 ;; when moving to column MIN-INDENT.
23377 (let ((buffer-invisibility-spec nil))
23378 (org-move-to-column min-indent t))
23379 (insert comment-start))
23380 (forward-line)))))))))
23382 (defun org-comment-dwim (_arg)
23383 "Call `comment-dwim' within a source edit buffer if needed."
23384 (interactive "*P")
23385 (if (org-in-src-block-p)
23386 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23387 (call-interactively 'comment-dwim)))
23390 ;;; Timestamps API
23392 ;; This section contains tools to operate on timestamp objects, as
23393 ;; returned by, e.g. `org-element-context'.
23395 (defun org-timestamp--to-internal-time (timestamp &optional end)
23396 "Encode TIMESTAMP object into Emacs internal time.
23397 Use end of date range or time range when END is non-nil."
23398 (apply #'encode-time
23399 (cons 0
23400 (mapcar
23401 (lambda (prop) (or (org-element-property prop timestamp) 0))
23402 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23403 '(:minute-start :hour-start :day-start :month-start
23404 :year-start))))))
23406 (defun org-timestamp-has-time-p (timestamp)
23407 "Non-nil when TIMESTAMP has a time specified."
23408 (org-element-property :hour-start timestamp))
23410 (defun org-timestamp-format (timestamp format &optional end utc)
23411 "Format a TIMESTAMP object into a string.
23413 FORMAT is a format specifier to be passed to
23414 `format-time-string'.
23416 When optional argument END is non-nil, use end of date-range or
23417 time-range, if possible.
23419 When optional argument UTC is non-nil, time will be expressed as
23420 Universal Time."
23421 (format-time-string
23422 format (org-timestamp--to-internal-time timestamp end)
23423 (and utc t)))
23425 (defun org-timestamp-split-range (timestamp &optional end)
23426 "Extract a TIMESTAMP object from a date or time range.
23428 END, when non-nil, means extract the end of the range.
23429 Otherwise, extract its start.
23431 Return a new timestamp object."
23432 (let ((type (org-element-property :type timestamp)))
23433 (if (memq type '(active inactive diary)) timestamp
23434 (let ((split-ts (org-element-copy timestamp)))
23435 ;; Set new type.
23436 (org-element-put-property
23437 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23438 ;; Copy start properties over end properties if END is
23439 ;; non-nil. Otherwise, copy end properties over `start' ones.
23440 (let ((p-alist '((:minute-start . :minute-end)
23441 (:hour-start . :hour-end)
23442 (:day-start . :day-end)
23443 (:month-start . :month-end)
23444 (:year-start . :year-end))))
23445 (dolist (p-cell p-alist)
23446 (org-element-put-property
23447 split-ts
23448 (funcall (if end #'car #'cdr) p-cell)
23449 (org-element-property
23450 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23451 ;; Eventually refresh `:raw-value'.
23452 (org-element-put-property split-ts :raw-value nil)
23453 (org-element-put-property
23454 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23456 (defun org-timestamp-translate (timestamp &optional boundary)
23457 "Translate TIMESTAMP object to custom format.
23459 Format string is defined in `org-time-stamp-custom-formats',
23460 which see.
23462 When optional argument BOUNDARY is non-nil, it is either the
23463 symbol `start' or `end'. In this case, only translate the
23464 starting or ending part of TIMESTAMP if it is a date or time
23465 range. Otherwise, translate both parts.
23467 Return timestamp as-is if `org-display-custom-times' is nil or if
23468 it has a `diary' type."
23469 (let ((type (org-element-property :type timestamp)))
23470 (if (or (not org-display-custom-times) (eq type 'diary))
23471 (org-element-interpret-data timestamp)
23472 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23473 org-time-stamp-custom-formats)))
23474 (if (and (not boundary) (memq type '(active-range inactive-range)))
23475 (concat (org-timestamp-format timestamp fmt)
23476 "--"
23477 (org-timestamp-format timestamp fmt t))
23478 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23482 ;;; Other stuff.
23484 (defvar reftex-docstruct-symbol)
23485 (defvar org--rds)
23487 (defun org-reftex-citation ()
23488 "Use reftex-citation to insert a citation into the buffer.
23489 This looks for a line like
23491 #+BIBLIOGRAPHY: foo plain option:-d
23493 and derives from it that foo.bib is the bibliography file relevant
23494 for this document. It then installs the necessary environment for RefTeX
23495 to work in this buffer and calls `reftex-citation' to insert a citation
23496 into the buffer.
23498 Export of such citations to both LaTeX and HTML is handled by the contributed
23499 package ox-bibtex by Taru Karttunen."
23500 (interactive)
23501 (let ((reftex-docstruct-symbol 'org--rds)
23502 org--rds bib)
23503 (org-with-wide-buffer
23504 (let ((case-fold-search t)
23505 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23506 (if (not (save-excursion
23507 (or (re-search-forward re nil t)
23508 (re-search-backward re nil t))))
23509 (user-error "No bibliography defined in file")
23510 (setq bib (concat (match-string 1) ".bib")
23511 org--rds (list (list 'bib bib))))))
23512 (call-interactively 'reftex-citation)))
23514 ;;;; Functions extending outline functionality
23516 (defun org-beginning-of-line (&optional n)
23517 "Go to the beginning of the current visible line.
23519 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23520 tags on the first attempt, and only move to after the tags when
23521 the cursor is already beyond the end of the headline.
23523 With argument N not nil or 1, move forward N - 1 lines first."
23524 (interactive "^p")
23525 (let ((origin (point))
23526 (special (pcase org-special-ctrl-a/e
23527 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23528 deactivate-mark)
23529 ;; First move to a visible line.
23530 (if (bound-and-true-p visual-line-mode)
23531 (beginning-of-visual-line n)
23532 (move-beginning-of-line n)
23533 ;; `move-beginning-of-line' may leave point after invisible
23534 ;; characters if line starts with such of these (e.g., with
23535 ;; a link at column 0). Really move to the beginning of the
23536 ;; current visible line.
23537 (beginning-of-line))
23538 (cond
23539 ;; No special behavior. Point is already at the beginning of
23540 ;; a line, logical or visual.
23541 ((not special))
23542 ;; `beginning-of-visual-line' left point before logical beginning
23543 ;; of line: point is at the beginning of a visual line. Bail
23544 ;; out.
23545 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23546 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23547 ;; At a headline, special position is before the title, but
23548 ;; after any TODO keyword or priority cookie.
23549 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23550 (line-end-position)))
23551 (bol (point)))
23552 (if (eq special 'reversed)
23553 (when (and (= origin bol) (eq last-command this-command))
23554 (goto-char refpos))
23555 (when (or (> origin refpos) (= origin bol))
23556 (goto-char refpos)))))
23557 ((and (looking-at org-list-full-item-re)
23558 (memq (org-element-type (save-match-data (org-element-at-point)))
23559 '(item plain-list)))
23560 ;; Set special position at first white space character after
23561 ;; bullet, and check-box, if any.
23562 (let ((after-bullet
23563 (let ((box (match-end 3)))
23564 (cond ((not box) (match-end 1))
23565 ((eq (char-after box) ?\s) (1+ box))
23566 (t box)))))
23567 (if (eq special 'reversed)
23568 (when (and (= (point) origin) (eq last-command this-command))
23569 (goto-char after-bullet))
23570 (when (or (> origin after-bullet) (= (point) origin))
23571 (goto-char after-bullet)))))
23572 ;; No special context. Point is already at beginning of line.
23573 (t nil))))
23575 (defun org-end-of-line (&optional n)
23576 "Go to the end of the line, but before ellipsis, if any.
23578 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23579 tags on the first attempt, and only move to after the tags when
23580 the cursor is already beyond the end of the headline.
23582 With argument N not nil or 1, move forward N - 1 lines first."
23583 (interactive "^p")
23584 (let ((origin (point))
23585 (special (pcase org-special-ctrl-a/e
23586 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23587 deactivate-mark)
23588 ;; First move to a visible line.
23589 (if (bound-and-true-p visual-line-mode)
23590 (beginning-of-visual-line n)
23591 (move-beginning-of-line n))
23592 (cond
23593 ;; At a headline, with tags.
23594 ((and special
23595 (save-excursion
23596 (beginning-of-line)
23597 (let ((case-fold-search nil))
23598 (looking-at org-complex-heading-regexp)))
23599 (match-end 5))
23600 (let ((tags (save-excursion
23601 (goto-char (match-beginning 5))
23602 (skip-chars-backward " \t")
23603 (point)))
23604 (visual-end (and (bound-and-true-p visual-line-mode)
23605 (save-excursion
23606 (end-of-visual-line)
23607 (point)))))
23608 ;; If `end-of-visual-line' brings us before end of line or
23609 ;; even tags, i.e., the headline spans over multiple visual
23610 ;; lines, move there.
23611 (cond ((and visual-end
23612 (< visual-end tags)
23613 (<= origin visual-end))
23614 (goto-char visual-end))
23615 ((eq special 'reversed)
23616 (if (and (= origin (line-end-position))
23617 (eq this-command last-command))
23618 (goto-char tags)
23619 (end-of-line)))
23621 (if (or (< origin tags) (= origin (line-end-position)))
23622 (goto-char tags)
23623 (end-of-line))))))
23624 ((bound-and-true-p visual-line-mode)
23625 (let ((bol (line-beginning-position)))
23626 (end-of-visual-line)
23627 ;; If `end-of-visual-line' gets us past the ellipsis at the
23628 ;; end of a line, backtrack and use `end-of-line' instead.
23629 (when (/= bol (line-beginning-position))
23630 (goto-char bol)
23631 (end-of-line))))
23632 (t (end-of-line)))))
23634 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23635 (define-key org-mode-map "\C-e" 'org-end-of-line)
23637 (defun org-backward-sentence (&optional _arg)
23638 "Go to beginning of sentence, or beginning of table field.
23639 This will call `backward-sentence' or `org-table-beginning-of-field',
23640 depending on context."
23641 (interactive)
23642 (let* ((element (org-element-at-point))
23643 (contents-begin (org-element-property :contents-begin element))
23644 (table (org-element-lineage element '(table) t)))
23645 (if (and table
23646 (> (point) contents-begin)
23647 (<= (point) (org-element-property :contents-end table)))
23648 (call-interactively #'org-table-beginning-of-field)
23649 (save-restriction
23650 (when (and contents-begin
23651 (< (point-min) contents-begin)
23652 (> (point) contents-begin))
23653 (narrow-to-region contents-begin
23654 (org-element-property :contents-end element)))
23655 (call-interactively #'backward-sentence)))))
23657 (defun org-forward-sentence (&optional _arg)
23658 "Go to end of sentence, or end of table field.
23659 This will call `forward-sentence' or `org-table-end-of-field',
23660 depending on context."
23661 (interactive)
23662 (let* ((element (org-element-at-point))
23663 (contents-end (org-element-property :contents-end element))
23664 (table (org-element-lineage element '(table) t)))
23665 (if (and table
23666 (>= (point) (org-element-property :contents-begin table))
23667 (< (point) contents-end))
23668 (call-interactively #'org-table-end-of-field)
23669 (save-restriction
23670 (when (and contents-end
23671 (> (point-max) contents-end)
23672 ;; Skip blank lines between elements.
23673 (< (org-element-property :end element)
23674 (save-excursion (goto-char contents-end)
23675 (skip-chars-forward " \r\t\n"))))
23676 (narrow-to-region (org-element-property :contents-begin element)
23677 contents-end))
23678 (call-interactively #'forward-sentence)))))
23680 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23681 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23683 (defun org-kill-line (&optional _arg)
23684 "Kill line, to tags or end of line."
23685 (interactive)
23686 (cond
23687 ((or (not org-special-ctrl-k)
23688 (bolp)
23689 (not (org-at-heading-p)))
23690 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23691 org-ctrl-k-protect-subtree
23692 (or (eq org-ctrl-k-protect-subtree 'error)
23693 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23694 (user-error "C-k aborted as it would kill a hidden subtree"))
23695 (call-interactively
23696 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23697 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23698 (kill-region (point) (match-beginning 1))
23699 (org-set-tags nil t))
23700 (t (kill-region (point) (point-at-eol)))))
23702 (define-key org-mode-map "\C-k" 'org-kill-line)
23704 (defun org-yank (&optional arg)
23705 "Yank. If the kill is a subtree, treat it specially.
23706 This command will look at the current kill and check if is a single
23707 subtree, or a series of subtrees[1]. If it passes the test, and if the
23708 cursor is at the beginning of a line or after the stars of a currently
23709 empty headline, then the yank is handled specially. How exactly depends
23710 on the value of the following variables.
23712 `org-yank-folded-subtrees'
23713 By default, this variable is non-nil, which results in
23714 subtree(s) being folded after insertion, except if doing so
23715 would swallow text after the yanked text.
23717 `org-yank-adjusted-subtrees'
23718 When non-nil (the default value is nil), the subtree will be
23719 promoted or demoted in order to fit into the local outline tree
23720 structure, which means that the level will be adjusted so that it
23721 becomes the smaller one of the two *visible* surrounding headings.
23723 Any prefix to this command will cause `yank' to be called directly with
23724 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23725 will just
23726 plainly yank the text as it is.
23728 \[1] The test checks if the first non-white line is a heading
23729 and if there are no other headings with fewer stars."
23730 (interactive "P")
23731 (org-yank-generic 'yank arg))
23733 (defun org-yank-generic (command arg)
23734 "Perform some yank-like command.
23736 This function implements the behavior described in the `org-yank'
23737 documentation. However, it has been generalized to work for any
23738 interactive command with similar behavior."
23740 ;; pretend to be command COMMAND
23741 (setq this-command command)
23743 (if arg
23744 (call-interactively command)
23746 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23747 (and (org-kill-is-subtree-p)
23748 (or (bolp)
23749 (and (looking-at "[ \t]*$")
23750 (string-match
23751 "\\`\\*+\\'"
23752 (buffer-substring (point-at-bol) (point)))))))
23753 swallowp)
23754 (cond
23755 ((and subtreep org-yank-folded-subtrees)
23756 (let ((beg (point))
23757 end)
23758 (if (and subtreep org-yank-adjusted-subtrees)
23759 (org-paste-subtree nil nil 'for-yank)
23760 (call-interactively command))
23762 (setq end (point))
23763 (goto-char beg)
23764 (when (and (bolp) subtreep
23765 (not (setq swallowp
23766 (org-yank-folding-would-swallow-text beg end))))
23767 (org-with-limited-levels
23768 (or (looking-at org-outline-regexp)
23769 (re-search-forward org-outline-regexp-bol end t))
23770 (while (and (< (point) end) (looking-at org-outline-regexp))
23771 (outline-hide-subtree)
23772 (org-cycle-show-empty-lines 'folded)
23773 (condition-case nil
23774 (outline-forward-same-level 1)
23775 (error (goto-char end))))))
23776 (when swallowp
23777 (message
23778 "Inserted text not folded because that would swallow text"))
23780 (goto-char end)
23781 (skip-chars-forward " \t\n\r")
23782 (beginning-of-line 1)
23783 (push-mark beg 'nomsg)))
23784 ((and subtreep org-yank-adjusted-subtrees)
23785 (let ((beg (point-at-bol)))
23786 (org-paste-subtree nil nil 'for-yank)
23787 (push-mark beg 'nomsg)))
23789 (call-interactively command))))))
23791 (defun org-yank-folding-would-swallow-text (beg end)
23792 "Would hide-subtree at BEG swallow any text after END?"
23793 (let (level)
23794 (org-with-limited-levels
23795 (save-excursion
23796 (goto-char beg)
23797 (when (or (looking-at org-outline-regexp)
23798 (re-search-forward org-outline-regexp-bol end t))
23799 (setq level (org-outline-level)))
23800 (goto-char end)
23801 (skip-chars-forward " \t\r\n\v\f")
23802 (not (or (eobp)
23803 (and (bolp) (looking-at-p org-outline-regexp)
23804 (<= (org-outline-level) level))))))))
23806 (define-key org-mode-map "\C-y" 'org-yank)
23808 (defun org-truely-invisible-p ()
23809 "Check if point is at a character currently not visible.
23810 This version does not only check the character property, but also
23811 `visible-mode'."
23812 ;; Early versions of noutline don't have `outline-invisible-p'.
23813 (unless (bound-and-true-p visible-mode)
23814 (outline-invisible-p)))
23816 (defun org-invisible-p2 ()
23817 "Check if point is at a character currently not visible."
23818 (save-excursion
23819 (when (and (eolp) (not (bobp))) (backward-char 1))
23820 ;; Early versions of noutline don't have `outline-invisible-p'.
23821 (outline-invisible-p)))
23823 (defun org-back-to-heading (&optional invisible-ok)
23824 "Call `outline-back-to-heading', but provide a better error message."
23825 (condition-case nil
23826 (outline-back-to-heading invisible-ok)
23827 (error (error "Before first headline at position %d in buffer %s"
23828 (point) (current-buffer)))))
23830 (defun org-before-first-heading-p ()
23831 "Before first heading?"
23832 (save-excursion
23833 (end-of-line)
23834 (null (re-search-backward org-outline-regexp-bol nil t))))
23836 (defun org-at-heading-p (&optional ignored)
23837 (outline-on-heading-p t))
23839 (defun org-in-commented-heading-p (&optional no-inheritance)
23840 "Non-nil if point is under a commented heading.
23841 This function also checks ancestors of the current headline,
23842 unless optional argument NO-INHERITANCE is non-nil."
23843 (cond
23844 ((org-before-first-heading-p) nil)
23845 ((let ((headline (nth 4 (org-heading-components))))
23846 (and headline
23847 (let ((case-fold-search nil))
23848 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23849 headline)))))
23850 (no-inheritance nil)
23852 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23854 (defun org-at-comment-p nil
23855 "Is cursor in a commented line?"
23856 (save-excursion
23857 (save-match-data
23858 (beginning-of-line)
23859 (looking-at "^[ \t]*# "))))
23861 (defun org-at-drawer-p nil
23862 "Is cursor at a drawer keyword?"
23863 (save-excursion
23864 (move-beginning-of-line 1)
23865 (looking-at org-drawer-regexp)))
23867 (defun org-at-block-p nil
23868 "Is cursor at a block keyword?"
23869 (save-excursion
23870 (move-beginning-of-line 1)
23871 (looking-at org-block-regexp)))
23873 (defun org-point-at-end-of-empty-headline ()
23874 "If point is at the end of an empty headline, return t, else nil.
23875 If the heading only contains a TODO keyword, it is still still considered
23876 empty."
23877 (let ((case-fold-search nil))
23878 (and (looking-at "[ \t]*$")
23879 org-todo-line-regexp
23880 (save-excursion
23881 (beginning-of-line)
23882 (looking-at org-todo-line-regexp)
23883 (string= (match-string 3) "")))))
23885 (defun org-at-heading-or-item-p ()
23886 (or (org-at-heading-p) (org-at-item-p)))
23888 (defun org-at-target-p ()
23889 (or (org-in-regexp org-radio-target-regexp)
23890 (org-in-regexp org-target-regexp)))
23891 ;; Compatibility alias with Org versions < 7.8.03
23892 (defalias 'org-on-target-p 'org-at-target-p)
23894 (defun org-up-heading-all (arg)
23895 "Move to the heading line of which the present line is a subheading.
23896 This function considers both visible and invisible heading lines.
23897 With argument, move up ARG levels."
23898 (outline-up-heading arg t))
23900 (defun org-up-heading-safe ()
23901 "Move to the heading line of which the present line is a subheading.
23902 This version will not throw an error. It will return the level of the
23903 headline found, or nil if no higher level is found.
23905 Also, this function will be a lot faster than `outline-up-heading',
23906 because it relies on stars being the outline starters. This can really
23907 make a significant difference in outlines with very many siblings."
23908 (when (ignore-errors (org-back-to-heading t))
23909 (let ((level-up (1- (funcall outline-level))))
23910 (and (> level-up 0)
23911 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23912 (funcall outline-level)))))
23914 (defun org-first-sibling-p ()
23915 "Is this heading the first child of its parents?"
23916 (interactive)
23917 (let ((re org-outline-regexp-bol)
23918 level l)
23919 (unless (org-at-heading-p t)
23920 (user-error "Not at a heading"))
23921 (setq level (funcall outline-level))
23922 (save-excursion
23923 (if (not (re-search-backward re nil t))
23925 (setq l (funcall outline-level))
23926 (< l level)))))
23928 (defun org-goto-sibling (&optional previous)
23929 "Goto the next sibling, even if it is invisible.
23930 When PREVIOUS is set, go to the previous sibling instead. Returns t
23931 when a sibling was found. When none is found, return nil and don't
23932 move point."
23933 (let ((fun (if previous 're-search-backward 're-search-forward))
23934 (pos (point))
23935 (re org-outline-regexp-bol)
23936 level l)
23937 (when (ignore-errors (org-back-to-heading t))
23938 (setq level (funcall outline-level))
23939 (catch 'exit
23940 (or previous (forward-char 1))
23941 (while (funcall fun re nil t)
23942 (setq l (funcall outline-level))
23943 (when (< l level) (goto-char pos) (throw 'exit nil))
23944 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23945 (goto-char pos)
23946 nil))))
23948 (defun org-show-siblings ()
23949 "Show all siblings of the current headline."
23950 (save-excursion
23951 (while (org-goto-sibling) (org-flag-heading nil)))
23952 (save-excursion
23953 (while (org-goto-sibling 'previous)
23954 (org-flag-heading nil))))
23956 (defun org-goto-first-child ()
23957 "Goto the first child, even if it is invisible.
23958 Return t when a child was found. Otherwise don't move point and
23959 return nil."
23960 (let (level (pos (point)) (re org-outline-regexp-bol))
23961 (when (ignore-errors (org-back-to-heading t))
23962 (setq level (outline-level))
23963 (forward-char 1)
23964 (if (and (re-search-forward re nil t) (> (outline-level) level))
23965 (progn (goto-char (match-beginning 0)) t)
23966 (goto-char pos) nil))))
23968 (defun org-show-hidden-entry ()
23969 "Show an entry where even the heading is hidden."
23970 (save-excursion
23971 (org-show-entry)))
23973 (defun org-flag-heading (flag &optional entry)
23974 "Flag the current heading. FLAG non-nil means make invisible.
23975 When ENTRY is non-nil, show the entire entry."
23976 (save-excursion
23977 (org-back-to-heading t)
23978 ;; Check if we should show the entire entry
23979 (if entry
23980 (progn
23981 (org-show-entry)
23982 (save-excursion
23983 (and (outline-next-heading)
23984 (org-flag-heading nil))))
23985 (outline-flag-region (max (point-min) (1- (point)))
23986 (save-excursion (outline-end-of-heading) (point))
23987 flag))))
23989 (defun org-get-next-sibling ()
23990 "Move to next heading of the same level, and return point.
23991 If there is no such heading, return nil.
23992 This is like outline-next-sibling, but invisible headings are ok."
23993 (let ((level (funcall outline-level)))
23994 (outline-next-heading)
23995 (while (and (not (eobp)) (> (funcall outline-level) level))
23996 (outline-next-heading))
23997 (unless (or (eobp) (< (funcall outline-level) level))
23998 (point))))
24000 (defun org-get-last-sibling ()
24001 "Move to previous heading of the same level, and return point.
24002 If there is no such heading, return nil."
24003 (let ((opoint (point))
24004 (level (funcall outline-level)))
24005 (outline-previous-heading)
24006 (when (and (/= (point) opoint) (outline-on-heading-p t))
24007 (while (and (> (funcall outline-level) level)
24008 (not (bobp)))
24009 (outline-previous-heading))
24010 (unless (< (funcall outline-level) level)
24011 (point)))))
24013 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24014 "Goto to the end of a subtree."
24015 ;; This contains an exact copy of the original function, but it uses
24016 ;; `org-back-to-heading', to make it work also in invisible
24017 ;; trees. And is uses an invisible-ok argument.
24018 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24019 ;; Furthermore, when used inside Org, finding the end of a large subtree
24020 ;; with many children and grandchildren etc, this can be much faster
24021 ;; than the outline version.
24022 (org-back-to-heading invisible-ok)
24023 (let ((first t)
24024 (level (funcall outline-level)))
24025 (if (and (derived-mode-p 'org-mode) (< level 1000))
24026 ;; A true heading (not a plain list item), in Org
24027 ;; This means we can easily find the end by looking
24028 ;; only for the right number of stars. Using a regexp to do
24029 ;; this is so much faster than using a Lisp loop.
24030 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24031 (forward-char 1)
24032 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24033 ;; something else, do it the slow way
24034 (while (and (not (eobp))
24035 (or first (> (funcall outline-level) level)))
24036 (setq first nil)
24037 (outline-next-heading)))
24038 (unless to-heading
24039 (when (memq (preceding-char) '(?\n ?\^M))
24040 ;; Go to end of line before heading
24041 (forward-char -1)
24042 (when (memq (preceding-char) '(?\n ?\^M))
24043 ;; leave blank line before heading
24044 (forward-char -1)))))
24045 (point))
24047 (defun org-end-of-meta-data (&optional full)
24048 "Skip planning line and properties drawer in current entry.
24049 When optional argument FULL is non-nil, also skip empty lines,
24050 clocking lines and regular drawers at the beginning of the
24051 entry."
24052 (org-back-to-heading t)
24053 (forward-line)
24054 (when (looking-at-p org-planning-line-re) (forward-line))
24055 (when (looking-at org-property-drawer-re)
24056 (goto-char (match-end 0))
24057 (forward-line))
24058 (when (and full (not (org-at-heading-p)))
24059 (catch 'exit
24060 (let ((end (save-excursion (outline-next-heading) (point)))
24061 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24062 (while (not (eobp))
24063 (cond ((looking-at-p org-drawer-regexp)
24064 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24065 (forward-line)
24066 (throw 'exit t)))
24067 ((looking-at-p re) (forward-line))
24068 (t (throw 'exit t))))))))
24070 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24071 "Move forward to the ARG'th subheading at same level as this one.
24072 Stop at the first and last subheadings of a superior heading.
24073 Normally this only looks at visible headings, but when INVISIBLE-OK is
24074 non-nil it will also look at invisible ones."
24075 (interactive "p")
24076 (let ((backward? (and arg (< arg 0))))
24077 (if (org-before-first-heading-p)
24078 (if backward? (goto-char (point-min)) (outline-next-heading))
24079 (org-back-to-heading invisible-ok)
24080 (unless backward? (end-of-line)) ;do not match current headline
24081 (let ((level (- (match-end 0) (match-beginning 0) 1))
24082 (f (if backward? #'re-search-backward #'re-search-forward))
24083 (count (if arg (abs arg) 1))
24084 (result (point)))
24085 (while (and (> count 0)
24086 (funcall f org-outline-regexp-bol nil 'move))
24087 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24088 (cond ((< l level) (setq count 0))
24089 ((and (= l level)
24090 (or invisible-ok
24091 (not (outline-invisible-p
24092 (line-beginning-position)))))
24093 (cl-decf count)
24094 (when (= l level) (setq result (point)))))))
24095 (goto-char result))
24096 (beginning-of-line))))
24098 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24099 "Move backward to the ARG'th subheading at same level as this one.
24100 Stop at the first and last subheadings of a superior heading."
24101 (interactive "p")
24102 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24104 (defun org-next-visible-heading (arg)
24105 "Move to the next visible heading.
24107 This function wraps `outline-next-visible-heading' with
24108 `org-with-limited-levels' in order to skip over inline tasks and
24109 respect customization of `org-odd-levels-only'."
24110 (interactive "p")
24111 (org-with-limited-levels
24112 (outline-next-visible-heading arg)))
24114 (defun org-previous-visible-heading (arg)
24115 "Move to the previous visible heading.
24117 This function wraps `outline-previous-visible-heading' with
24118 `org-with-limited-levels' in order to skip over inline tasks and
24119 respect customization of `org-odd-levels-only'."
24120 (interactive "p")
24121 (org-with-limited-levels
24122 (outline-previous-visible-heading arg)))
24124 (defun org-next-block (arg &optional backward block-regexp)
24125 "Jump to the next block.
24127 With a prefix argument ARG, jump forward ARG many blocks.
24129 When BACKWARD is non-nil, jump to the previous block.
24131 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24132 Match data is set according to this regexp when the function
24133 returns.
24135 Return point at beginning of the opening line of found block.
24136 Throw an error if no block is found."
24137 (interactive "p")
24138 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24139 (case-fold-search t)
24140 (search-fn (if backward #'re-search-backward #'re-search-forward))
24141 (count (or arg 1))
24142 (origin (point))
24143 last-element)
24144 (if backward (beginning-of-line) (end-of-line))
24145 (while (and (> count 0) (funcall search-fn re nil t))
24146 (let ((element (save-excursion
24147 (goto-char (match-beginning 0))
24148 (save-match-data (org-element-at-point)))))
24149 (when (and (memq (org-element-type element)
24150 '(center-block comment-block dynamic-block
24151 example-block export-block quote-block
24152 special-block src-block verse-block))
24153 (<= (match-beginning 0)
24154 (org-element-property :post-affiliated element)))
24155 (setq last-element element)
24156 (cl-decf count))))
24157 (if (= count 0)
24158 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24159 (save-match-data (org-show-context)))
24160 (goto-char origin)
24161 (user-error "No %s code blocks" (if backward "previous" "further")))))
24163 (defun org-previous-block (arg &optional block-regexp)
24164 "Jump to the previous block.
24165 With a prefix argument ARG, jump backward ARG many source blocks.
24166 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24167 (interactive "p")
24168 (org-next-block arg t block-regexp))
24170 (defun org-forward-paragraph ()
24171 "Move forward to beginning of next paragraph or equivalent.
24173 The function moves point to the beginning of the next visible
24174 structural element, which can be a paragraph, a table, a list
24175 item, etc. It also provides some special moves for convenience:
24177 - On an affiliated keyword, jump to the beginning of the
24178 relative element.
24179 - On an item or a footnote definition, move to the second
24180 element inside, if any.
24181 - On a table or a property drawer, jump after it.
24182 - On a verse or source block, stop after blank lines."
24183 (interactive)
24184 (when (eobp) (user-error "Cannot move further down"))
24185 (let* ((deactivate-mark nil)
24186 (element (org-element-at-point))
24187 (type (org-element-type element))
24188 (post-affiliated (org-element-property :post-affiliated element))
24189 (contents-begin (org-element-property :contents-begin element))
24190 (contents-end (org-element-property :contents-end element))
24191 (end (let ((end (org-element-property :end element)) (parent element))
24192 (while (and (setq parent (org-element-property :parent parent))
24193 (= (org-element-property :contents-end parent) end))
24194 (setq end (org-element-property :end parent)))
24195 end)))
24196 (cond ((not element)
24197 (skip-chars-forward " \r\t\n")
24198 (or (eobp) (beginning-of-line)))
24199 ;; On affiliated keywords, move to element's beginning.
24200 ((< (point) post-affiliated)
24201 (goto-char post-affiliated))
24202 ;; At a table row, move to the end of the table. Similarly,
24203 ;; at a node property, move to the end of the property
24204 ;; drawer.
24205 ((memq type '(node-property table-row))
24206 (goto-char (org-element-property
24207 :end (org-element-property :parent element))))
24208 ((memq type '(property-drawer table)) (goto-char end))
24209 ;; Consider blank lines as separators in verse and source
24210 ;; blocks to ease editing.
24211 ((memq type '(src-block verse-block))
24212 (when (eq type 'src-block)
24213 (setq contents-end
24214 (save-excursion (goto-char end)
24215 (skip-chars-backward " \r\t\n")
24216 (line-beginning-position))))
24217 (beginning-of-line)
24218 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24219 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24220 (goto-char end)
24221 (skip-chars-forward " \r\t\n")
24222 (if (= (point) contents-end) (goto-char end)
24223 (beginning-of-line))))
24224 ;; With no contents, just skip element.
24225 ((not contents-begin) (goto-char end))
24226 ;; If contents are invisible, skip the element altogether.
24227 ((outline-invisible-p (line-end-position))
24228 (cl-case type
24229 (headline
24230 (org-with-limited-levels (outline-next-visible-heading 1)))
24231 ;; At a plain list, make sure we move to the next item
24232 ;; instead of skipping the whole list.
24233 (plain-list (forward-char)
24234 (org-forward-paragraph))
24235 (otherwise (goto-char end))))
24236 ((>= (point) contents-end) (goto-char end))
24237 ((>= (point) contents-begin)
24238 ;; This can only happen on paragraphs and plain lists.
24239 (cl-case type
24240 (paragraph (goto-char end))
24241 ;; At a plain list, try to move to second element in
24242 ;; first item, if possible.
24243 (plain-list (end-of-line)
24244 (org-forward-paragraph))))
24245 ;; When contents start on the middle of a line (e.g. in
24246 ;; items and footnote definitions), try to reach first
24247 ;; element starting after current line.
24248 ((> (line-end-position) contents-begin)
24249 (end-of-line)
24250 (org-forward-paragraph))
24251 (t (goto-char contents-begin)))))
24253 (defun org-backward-paragraph ()
24254 "Move backward to start of previous paragraph or equivalent.
24256 The function moves point to the beginning of the current
24257 structural element, which can be a paragraph, a table, a list
24258 item, etc., or to the beginning of the previous visible one if
24259 point is already there. It also provides some special moves for
24260 convenience:
24262 - On an affiliated keyword, jump to the first one.
24263 - On a table or a property drawer, move to its beginning.
24264 - On a verse or source block, stop before blank lines."
24265 (interactive)
24266 (when (bobp) (user-error "Cannot move further up"))
24267 (let* ((deactivate-mark nil)
24268 (element (org-element-at-point))
24269 (type (org-element-type element))
24270 (contents-begin (org-element-property :contents-begin element))
24271 (contents-end (org-element-property :contents-end element))
24272 (post-affiliated (org-element-property :post-affiliated element))
24273 (begin (org-element-property :begin element)))
24274 (cond
24275 ((not element) (goto-char (point-min)))
24276 ((= (point) begin)
24277 (backward-char)
24278 (org-backward-paragraph))
24279 ((<= (point) post-affiliated) (goto-char begin))
24280 ((memq type '(node-property table-row))
24281 (goto-char (org-element-property
24282 :post-affiliated (org-element-property :parent element))))
24283 ((memq type '(property-drawer table)) (goto-char begin))
24284 ((memq type '(src-block verse-block))
24285 (when (eq type 'src-block)
24286 (setq contents-begin
24287 (save-excursion (goto-char begin) (forward-line) (point))))
24288 (if (= (point) contents-begin) (goto-char post-affiliated)
24289 ;; Inside a verse block, see blank lines as paragraph
24290 ;; separators.
24291 (let ((origin (point)))
24292 (skip-chars-backward " \r\t\n" contents-begin)
24293 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24294 (skip-chars-forward " \r\t\n" origin)
24295 (if (= (point) origin) (goto-char contents-begin)
24296 (beginning-of-line))))))
24297 ((not contents-begin) (goto-char (or post-affiliated begin)))
24298 ((eq type 'paragraph)
24299 (goto-char contents-begin)
24300 ;; When at first paragraph in an item or a footnote definition,
24301 ;; move directly to beginning of line.
24302 (let ((parent-contents
24303 (org-element-property
24304 :contents-begin (org-element-property :parent element))))
24305 (when (and parent-contents (= parent-contents contents-begin))
24306 (beginning-of-line))))
24307 ;; At the end of a greater element, move to the beginning of the
24308 ;; last element within.
24309 ((>= (point) contents-end)
24310 (goto-char (1- contents-end))
24311 (org-backward-paragraph))
24312 (t (goto-char (or post-affiliated begin))))
24313 ;; Ensure we never leave point invisible.
24314 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24316 (defun org-forward-element ()
24317 "Move forward by one element.
24318 Move to the next element at the same level, when possible."
24319 (interactive)
24320 (cond ((eobp) (user-error "Cannot move further down"))
24321 ((org-with-limited-levels (org-at-heading-p))
24322 (let ((origin (point)))
24323 (goto-char (org-end-of-subtree nil t))
24324 (unless (org-with-limited-levels (org-at-heading-p))
24325 (goto-char origin)
24326 (user-error "Cannot move further down"))))
24328 (let* ((elem (org-element-at-point))
24329 (end (org-element-property :end elem))
24330 (parent (org-element-property :parent elem)))
24331 (cond ((and parent (= (org-element-property :contents-end parent) end))
24332 (goto-char (org-element-property :end parent)))
24333 ((integer-or-marker-p end) (goto-char end))
24334 (t (message "No element at point")))))))
24336 (defun org-backward-element ()
24337 "Move backward by one element.
24338 Move to the previous element at the same level, when possible."
24339 (interactive)
24340 (cond ((bobp) (user-error "Cannot move further up"))
24341 ((org-with-limited-levels (org-at-heading-p))
24342 ;; At a headline, move to the previous one, if any, or stay
24343 ;; here.
24344 (let ((origin (point)))
24345 (org-with-limited-levels (org-backward-heading-same-level 1))
24346 ;; When current headline has no sibling above, move to its
24347 ;; parent.
24348 (when (= (point) origin)
24349 (or (org-with-limited-levels (org-up-heading-safe))
24350 (progn (goto-char origin)
24351 (user-error "Cannot move further up"))))))
24353 (let* ((elem (org-element-at-point))
24354 (beg (org-element-property :begin elem)))
24355 (cond
24356 ;; Move to beginning of current element if point isn't
24357 ;; there already.
24358 ((null beg) (message "No element at point"))
24359 ((/= (point) beg) (goto-char beg))
24360 (t (goto-char beg)
24361 (skip-chars-backward " \r\t\n")
24362 (unless (bobp)
24363 (let ((prev (org-element-at-point)))
24364 (goto-char (org-element-property :begin prev))
24365 (while (and (setq prev (org-element-property :parent prev))
24366 (<= (org-element-property :end prev) beg))
24367 (goto-char (org-element-property :begin prev)))))))))))
24369 (defun org-up-element ()
24370 "Move to upper element."
24371 (interactive)
24372 (if (org-with-limited-levels (org-at-heading-p))
24373 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24374 (let* ((elem (org-element-at-point))
24375 (parent (org-element-property :parent elem)))
24376 (if parent (goto-char (org-element-property :begin parent))
24377 (if (org-with-limited-levels (org-before-first-heading-p))
24378 (user-error "No surrounding element")
24379 (org-with-limited-levels (org-back-to-heading)))))))
24381 (defvar org-element-greater-elements)
24382 (defun org-down-element ()
24383 "Move to inner element."
24384 (interactive)
24385 (let ((element (org-element-at-point)))
24386 (cond
24387 ((memq (org-element-type element) '(plain-list table))
24388 (goto-char (org-element-property :contents-begin element))
24389 (forward-char))
24390 ((memq (org-element-type element) org-element-greater-elements)
24391 ;; If contents are hidden, first disclose them.
24392 (when (outline-invisible-p (line-end-position)) (org-cycle))
24393 (goto-char (or (org-element-property :contents-begin element)
24394 (user-error "No content for this element"))))
24395 (t (user-error "No inner element")))))
24397 (defun org-drag-element-backward ()
24398 "Move backward element at point."
24399 (interactive)
24400 (let ((elem (or (org-element-at-point)
24401 (user-error "No element at point"))))
24402 (if (eq (org-element-type elem) 'headline)
24403 ;; Preserve point when moving a whole tree, even if point was
24404 ;; on blank lines below the headline.
24405 (let ((offset (skip-chars-backward " \t\n")))
24406 (unwind-protect (org-move-subtree-up)
24407 (forward-char (- offset))))
24408 (let ((prev-elem
24409 (save-excursion
24410 (goto-char (org-element-property :begin elem))
24411 (skip-chars-backward " \r\t\n")
24412 (unless (bobp)
24413 (let* ((beg (org-element-property :begin elem))
24414 (prev (org-element-at-point))
24415 (up prev))
24416 (while (and (setq up (org-element-property :parent up))
24417 (<= (org-element-property :end up) beg))
24418 (setq prev up))
24419 prev)))))
24420 ;; Error out if no previous element or previous element is
24421 ;; a parent of the current one.
24422 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24423 (user-error "Cannot drag element backward")
24424 (let ((pos (point)))
24425 (org-element-swap-A-B prev-elem elem)
24426 (goto-char (+ (org-element-property :begin prev-elem)
24427 (- pos (org-element-property :begin elem))))))))))
24429 (defun org-drag-element-forward ()
24430 "Move forward element at point."
24431 (interactive)
24432 (let* ((pos (point))
24433 (elem (or (org-element-at-point)
24434 (user-error "No element at point"))))
24435 (when (= (point-max) (org-element-property :end elem))
24436 (user-error "Cannot drag element forward"))
24437 (goto-char (org-element-property :end elem))
24438 (let ((next-elem (org-element-at-point)))
24439 (when (or (org-element-nested-p elem next-elem)
24440 (and (eq (org-element-type next-elem) 'headline)
24441 (not (eq (org-element-type elem) 'headline))))
24442 (goto-char pos)
24443 (user-error "Cannot drag element forward"))
24444 ;; Compute new position of point: it's shifted by NEXT-ELEM
24445 ;; body's length (without final blanks) and by the length of
24446 ;; blanks between ELEM and NEXT-ELEM.
24447 (let ((size-next (- (save-excursion
24448 (goto-char (org-element-property :end next-elem))
24449 (skip-chars-backward " \r\t\n")
24450 (forward-line)
24451 ;; Small correction if buffer doesn't end
24452 ;; with a newline character.
24453 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24454 (org-element-property :begin next-elem)))
24455 (size-blank (- (org-element-property :end elem)
24456 (save-excursion
24457 (goto-char (org-element-property :end elem))
24458 (skip-chars-backward " \r\t\n")
24459 (forward-line)
24460 (point)))))
24461 (org-element-swap-A-B elem next-elem)
24462 (goto-char (+ pos size-next size-blank))))))
24464 (defun org-drag-line-forward (arg)
24465 "Drag the line at point ARG lines forward."
24466 (interactive "p")
24467 (dotimes (_ (abs arg))
24468 (let ((c (current-column)))
24469 (if (< 0 arg)
24470 (progn
24471 (beginning-of-line 2)
24472 (transpose-lines 1)
24473 (beginning-of-line 0))
24474 (transpose-lines 1)
24475 (beginning-of-line -1))
24476 (org-move-to-column c))))
24478 (defun org-drag-line-backward (arg)
24479 "Drag the line at point ARG lines backward."
24480 (interactive "p")
24481 (org-drag-line-forward (- arg)))
24483 (defun org-mark-element ()
24484 "Put point at beginning of this element, mark at end.
24486 Interactively, if this command is repeated or (in Transient Mark
24487 mode) if the mark is active, it marks the next element after the
24488 ones already marked."
24489 (interactive)
24490 (let (deactivate-mark)
24491 (if (and (called-interactively-p 'any)
24492 (or (and (eq last-command this-command) (mark t))
24493 (and transient-mark-mode mark-active)))
24494 (set-mark
24495 (save-excursion
24496 (goto-char (mark))
24497 (goto-char (org-element-property :end (org-element-at-point)))))
24498 (let ((element (org-element-at-point)))
24499 (end-of-line)
24500 (push-mark (org-element-property :end element) t t)
24501 (goto-char (org-element-property :begin element))))))
24503 (defun org-narrow-to-element ()
24504 "Narrow buffer to current element."
24505 (interactive)
24506 (let ((elem (org-element-at-point)))
24507 (cond
24508 ((eq (car elem) 'headline)
24509 (narrow-to-region
24510 (org-element-property :begin elem)
24511 (org-element-property :end elem)))
24512 ((memq (car elem) org-element-greater-elements)
24513 (narrow-to-region
24514 (org-element-property :contents-begin elem)
24515 (org-element-property :contents-end elem)))
24517 (narrow-to-region
24518 (org-element-property :begin elem)
24519 (org-element-property :end elem))))))
24521 (defun org-transpose-element ()
24522 "Transpose current and previous elements, keeping blank lines between.
24523 Point is moved after both elements."
24524 (interactive)
24525 (org-skip-whitespace)
24526 (let ((end (org-element-property :end (org-element-at-point))))
24527 (org-drag-element-backward)
24528 (goto-char end)))
24530 (defun org-unindent-buffer ()
24531 "Un-indent the visible part of the buffer.
24532 Relative indentation (between items, inside blocks, etc.) isn't
24533 modified."
24534 (interactive)
24535 (unless (eq major-mode 'org-mode)
24536 (user-error "Cannot un-indent a buffer not in Org mode"))
24537 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24538 (unindent-tree
24539 (lambda (contents)
24540 (dolist (element (reverse contents))
24541 (if (memq (org-element-type element) '(headline section))
24542 (funcall unindent-tree (org-element-contents element))
24543 (save-excursion
24544 (save-restriction
24545 (narrow-to-region
24546 (org-element-property :begin element)
24547 (org-element-property :end element))
24548 (org-do-remove-indentation))))))))
24549 (funcall unindent-tree (org-element-contents parse-tree))))
24551 (defun org-show-children (&optional level)
24552 "Show all direct subheadings of this heading.
24553 Prefix arg LEVEL is how many levels below the current level
24554 should be shown. Default is enough to cause the following
24555 heading to appear."
24556 (interactive "p")
24557 ;; If `orgstruct-mode' is active, use the slower version.
24558 (if orgstruct-mode (call-interactively #'outline-show-children)
24559 (save-excursion
24560 (org-back-to-heading t)
24561 (let* ((current-level (funcall outline-level))
24562 (max-level (org-get-valid-level
24563 current-level
24564 (if level (prefix-numeric-value level) 1)))
24565 (end (save-excursion (org-end-of-subtree t t)))
24566 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24567 (past-first-child nil)
24568 ;; Make sure to skip inlinetasks.
24569 (re (format regexp-fmt
24570 current-level
24571 (cond
24572 ((not (featurep 'org-inlinetask)) "")
24573 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24575 (t (1- org-inlinetask-min-level))))))
24576 ;; Display parent heading.
24577 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24578 (forward-line)
24579 ;; Display children. First child may be deeper than expected
24580 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24581 ;; MAX-LEVEL accordingly.
24582 (while (re-search-forward re end t)
24583 (unless past-first-child
24584 (setq re (format regexp-fmt
24585 current-level
24586 (max (funcall outline-level) max-level)))
24587 (setq past-first-child t))
24588 (outline-flag-region
24589 (line-end-position 0) (line-end-position) nil))))))
24591 (defun org-show-subtree ()
24592 "Show everything after this heading at deeper levels."
24593 (interactive)
24594 (outline-flag-region
24595 (point)
24596 (save-excursion
24597 (org-end-of-subtree t t))
24598 nil))
24600 (defun org-show-entry ()
24601 "Show the body directly following this heading.
24602 Show the heading too, if it is currently invisible."
24603 (interactive)
24604 (save-excursion
24605 (ignore-errors
24606 (org-back-to-heading t)
24607 (outline-flag-region
24608 (max (point-min) (1- (point)))
24609 (save-excursion
24610 (if (re-search-forward
24611 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24612 (match-beginning 1)
24613 (point-max)))
24614 nil)
24615 (org-cycle-hide-drawers 'children))))
24617 (defun org-make-options-regexp (kwds &optional extra)
24618 "Make a regular expression for keyword lines.
24619 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24620 when non-nil, is a regexp matching keywords names."
24621 (concat "^[ \t]*#\\+\\("
24622 (regexp-opt kwds)
24623 (and extra (concat (and kwds "\\|") extra))
24624 "\\):[ \t]*\\(.*\\)"))
24626 ;;;; Integration with and fixes for other packages
24628 ;;; Imenu support
24630 (defvar-local org-imenu-markers nil
24631 "All markers currently used by Imenu.")
24633 (defun org-imenu-new-marker (&optional pos)
24634 "Return a new marker for use by Imenu, and remember the marker."
24635 (let ((m (make-marker)))
24636 (move-marker m (or pos (point)))
24637 (push m org-imenu-markers)
24640 (defun org-imenu-get-tree ()
24641 "Produce the index for Imenu."
24642 (dolist (x org-imenu-markers) (move-marker x nil))
24643 (setq org-imenu-markers nil)
24644 (let* ((case-fold-search nil)
24645 (n org-imenu-depth)
24646 (re (concat "^" (org-get-limited-outline-regexp)))
24647 (subs (make-vector (1+ n) nil))
24648 (last-level 0)
24649 m level head0 head)
24650 (org-with-wide-buffer
24651 (goto-char (point-max))
24652 (while (re-search-backward re nil t)
24653 (setq level (org-reduced-level (funcall outline-level)))
24654 (when (and (<= level n)
24655 (looking-at org-complex-heading-regexp)
24656 (setq head0 (match-string-no-properties 4)))
24657 (setq head (org-link-display-format head0)
24658 m (org-imenu-new-marker))
24659 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24660 (if (>= level last-level)
24661 (push (cons head m) (aref subs level))
24662 (push (cons head (aref subs (1+ level))) (aref subs level))
24663 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24664 (setq last-level level))))
24665 (aref subs 1)))
24667 (eval-after-load "imenu"
24668 '(progn
24669 (add-hook 'imenu-after-jump-hook
24670 (lambda ()
24671 (when (derived-mode-p 'org-mode)
24672 (org-show-context 'org-goto))))))
24674 (defun org-link-display-format (s)
24675 "Replace links in string S with their description.
24676 If there is no description, use the link target."
24677 (save-match-data
24678 (replace-regexp-in-string
24679 org-bracket-link-analytic-regexp
24680 (lambda (m)
24681 (if (match-end 5) (match-string 5 m)
24682 (concat (match-string 1 m) (match-string 3 m))))
24683 s nil t)))
24685 (defun org-toggle-link-display ()
24686 "Toggle the literal or descriptive display of links."
24687 (interactive)
24688 (if org-descriptive-links
24689 (progn (org-remove-from-invisibility-spec '(org-link))
24690 (org-restart-font-lock)
24691 (setq org-descriptive-links nil))
24692 (progn (add-to-invisibility-spec '(org-link))
24693 (org-restart-font-lock)
24694 (setq org-descriptive-links t))))
24696 ;; Speedbar support
24698 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24699 "Overlay marking the agenda restriction line in speedbar.")
24700 (overlay-put org-speedbar-restriction-lock-overlay
24701 'face 'org-agenda-restriction-lock)
24702 (overlay-put org-speedbar-restriction-lock-overlay
24703 'help-echo "Agendas are currently limited to this item.")
24704 (delete-overlay org-speedbar-restriction-lock-overlay)
24706 (defun org-speedbar-set-agenda-restriction ()
24707 "Restrict future agenda commands to the location at point in speedbar.
24708 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24709 (interactive)
24710 (require 'org-agenda)
24711 (let (p m tp np dir txt)
24712 (cond
24713 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24714 'org-imenu t))
24715 (setq m (get-text-property p 'org-imenu-marker))
24716 (with-current-buffer (marker-buffer m)
24717 (goto-char m)
24718 (org-agenda-set-restriction-lock 'subtree)))
24719 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24720 'speedbar-function 'speedbar-find-file))
24721 (setq tp (previous-single-property-change
24722 (1+ p) 'speedbar-function)
24723 np (next-single-property-change
24724 tp 'speedbar-function)
24725 dir (speedbar-line-directory)
24726 txt (buffer-substring-no-properties (or tp (point-min))
24727 (or np (point-max))))
24728 (with-current-buffer (find-file-noselect
24729 (let ((default-directory dir))
24730 (expand-file-name txt)))
24731 (unless (derived-mode-p 'org-mode)
24732 (user-error "Cannot restrict to non-Org mode file"))
24733 (org-agenda-set-restriction-lock 'file)))
24734 (t (user-error "Don't know how to restrict Org mode agenda")))
24735 (move-overlay org-speedbar-restriction-lock-overlay
24736 (point-at-bol) (point-at-eol))
24737 (setq current-prefix-arg nil)
24738 (org-agenda-maybe-redo)))
24740 (defvar speedbar-file-key-map)
24741 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24742 (eval-after-load "speedbar"
24743 '(progn
24744 (speedbar-add-supported-extension ".org")
24745 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24746 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24747 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24748 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24749 (add-hook 'speedbar-visiting-tag-hook
24750 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24752 ;;; Fixes and Hacks for problems with other packages
24754 (defun org--flyspell-object-check-p (element)
24755 "Non-nil when Flyspell can check object at point.
24756 ELEMENT is the element at point."
24757 (let ((object (save-excursion
24758 (when (looking-at-p "\\>") (backward-char))
24759 (org-element-context element))))
24760 (cl-case (org-element-type object)
24761 ;; Prevent checks in links due to keybinding conflict with
24762 ;; Flyspell.
24763 ((code entity export-snippet inline-babel-call
24764 inline-src-block line-break latex-fragment link macro
24765 statistics-cookie target timestamp verbatim)
24766 nil)
24767 (footnote-reference
24768 ;; Only in inline footnotes, within the definition.
24769 (and (eq (org-element-property :type object) 'inline)
24770 (< (save-excursion
24771 (goto-char (org-element-property :begin object))
24772 (search-forward ":" nil t 2))
24773 (point))))
24774 (otherwise t))))
24776 (defun org-mode-flyspell-verify ()
24777 "Function used for `flyspell-generic-check-word-predicate'."
24778 (if (org-at-heading-p)
24779 ;; At a headline or an inlinetask, check title only. This is
24780 ;; faster than relying on `org-element-at-point'.
24781 (and (save-excursion (beginning-of-line)
24782 (and (let ((case-fold-search t))
24783 (not (looking-at-p "\\*+ END[ \t]*$")))
24784 (let ((case-fold-search nil))
24785 (looking-at org-complex-heading-regexp))))
24786 (match-beginning 4)
24787 (>= (point) (match-beginning 4))
24788 (or (not (match-beginning 5))
24789 (< (point) (match-beginning 5))))
24790 (let* ((element (org-element-at-point))
24791 (post-affiliated (org-element-property :post-affiliated element)))
24792 (cond
24793 ;; Ignore checks in all affiliated keywords but captions.
24794 ((< (point) post-affiliated)
24795 (and (save-excursion
24796 (beginning-of-line)
24797 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24798 (> (point) (match-end 0))
24799 (org--flyspell-object-check-p element)))
24800 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24801 ((let ((log (org-log-into-drawer)))
24802 (and log
24803 (let ((drawer (org-element-lineage element '(drawer))))
24804 (and drawer
24805 (eq (compare-strings
24806 log nil nil
24807 (org-element-property :drawer-name drawer) nil nil t)
24808 t)))))
24809 nil)
24811 (cl-case (org-element-type element)
24812 ((comment quote-section) t)
24813 (comment-block
24814 ;; Allow checks between block markers, not on them.
24815 (and (> (line-beginning-position) post-affiliated)
24816 (save-excursion
24817 (end-of-line)
24818 (skip-chars-forward " \r\t\n")
24819 (< (point) (org-element-property :end element)))))
24820 ;; Arbitrary list of keywords where checks are meaningful.
24821 ;; Make sure point is on the value part of the element.
24822 (keyword
24823 (and (member (org-element-property :key element)
24824 '("DESCRIPTION" "TITLE"))
24825 (save-excursion
24826 (search-backward ":" (line-beginning-position) t))))
24827 ;; Check is globally allowed in paragraphs verse blocks and
24828 ;; table rows (after affiliated keywords) but some objects
24829 ;; must not be affected.
24830 ((paragraph table-row verse-block)
24831 (let ((cbeg (org-element-property :contents-begin element))
24832 (cend (org-element-property :contents-end element)))
24833 (and cbeg (>= (point) cbeg) (< (point) cend)
24834 (org--flyspell-object-check-p element))))))))))
24835 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24837 (defun org-remove-flyspell-overlays-in (beg end)
24838 "Remove flyspell overlays in region."
24839 (and (bound-and-true-p flyspell-mode)
24840 (fboundp 'flyspell-delete-region-overlays)
24841 (flyspell-delete-region-overlays beg end)))
24843 (defvar flyspell-delayed-commands)
24844 (eval-after-load "flyspell"
24845 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24847 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24848 (eval-after-load "bookmark"
24849 '(if (boundp 'bookmark-after-jump-hook)
24850 ;; We can use the hook
24851 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24852 ;; Hook not available, use advice
24853 (defadvice bookmark-jump (after org-make-visible activate)
24854 "Make the position visible."
24855 (org-bookmark-jump-unhide))))
24857 ;; Make sure saveplace shows the location if it was hidden
24858 (eval-after-load "saveplace"
24859 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24860 "Make the position visible."
24861 (org-bookmark-jump-unhide)))
24863 ;; Make sure ecb shows the location if it was hidden
24864 (eval-after-load "ecb"
24865 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24866 "Make hierarchy visible when jumping into location from ECB tree buffer."
24867 (when (derived-mode-p 'org-mode)
24868 (org-show-context))))
24870 (defun org-bookmark-jump-unhide ()
24871 "Unhide the current position, to show the bookmark location."
24872 (and (derived-mode-p 'org-mode)
24873 (or (outline-invisible-p)
24874 (save-excursion (goto-char (max (point-min) (1- (point))))
24875 (outline-invisible-p)))
24876 (org-show-context 'bookmark-jump)))
24878 (defun org-mark-jump-unhide ()
24879 "Make the point visible with `org-show-context' after jumping to the mark."
24880 (when (and (derived-mode-p 'org-mode)
24881 (outline-invisible-p))
24882 (org-show-context 'mark-goto)))
24884 (eval-after-load "simple"
24885 '(defadvice pop-to-mark-command (after org-make-visible activate)
24886 "Make the point visible with `org-show-context'."
24887 (org-mark-jump-unhide)))
24889 (eval-after-load "simple"
24890 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24891 "Make the point visible with `org-show-context'."
24892 (org-mark-jump-unhide)))
24894 (eval-after-load "simple"
24895 '(defadvice pop-global-mark (after org-make-visible activate)
24896 "Make the point visible with `org-show-context'."
24897 (org-mark-jump-unhide)))
24899 ;; Make session.el ignore our circular variable
24900 (defvar session-globals-exclude)
24901 (eval-after-load "session"
24902 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24904 ;;;; Finish up
24906 (provide 'org)
24908 (run-hooks 'org-load-hook)
24910 ;;; org.el ends here