Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blobb73f9091132b458da3e70750e1d8e9cefdd5ba9d
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 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\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."
2557 :group 'org-refile
2558 :type '(choice
2559 (const :tag "Not" nil)
2560 (const :tag "Yes" t)
2561 (const :tag "Start with file name" file)
2562 (const :tag "Start with full file path" full-file-path)))
2564 (defcustom org-outline-path-complete-in-steps t
2565 "Non-nil means complete the outline path in hierarchical steps.
2566 When Org uses the refile interface to select an outline path (see
2567 `org-refile-use-outline-path'), the completion of the path can be
2568 done in a single go, or it can be done in steps down the headline
2569 hierarchy. Going in steps is probably the best if you do not use
2570 a special completion package like `ido' or `icicles'. However,
2571 when using these packages, going in one step can be very fast,
2572 while still showing the whole path to the entry."
2573 :group 'org-refile
2574 :type 'boolean)
2576 (defcustom org-refile-allow-creating-parent-nodes nil
2577 "Non-nil means allow the creation of new nodes as refile targets.
2578 New nodes are then created by adding \"/new node name\" to the completion
2579 of an existing node. When the value of this variable is `confirm',
2580 new node creation must be confirmed by the user (recommended).
2581 When nil, the completion must match an existing entry.
2583 Note that, if the new heading is not seen by the criteria
2584 listed in `org-refile-targets', multiple instances of the same
2585 heading would be created by trying again to file under the new
2586 heading."
2587 :group 'org-refile
2588 :type '(choice
2589 (const :tag "Never" nil)
2590 (const :tag "Always" t)
2591 (const :tag "Prompt for confirmation" confirm)))
2593 (defcustom org-refile-active-region-within-subtree nil
2594 "Non-nil means also refile active region within a subtree.
2596 By default `org-refile' doesn't allow refiling regions if they
2597 don't contain a set of subtrees, but it might be convenient to
2598 do so sometimes: in that case, the first line of the region is
2599 converted to a headline before refiling."
2600 :group 'org-refile
2601 :version "24.1"
2602 :type 'boolean)
2604 (defgroup org-todo nil
2605 "Options concerning TODO items in Org mode."
2606 :tag "Org TODO"
2607 :group 'org)
2609 (defgroup org-progress nil
2610 "Options concerning Progress logging in Org mode."
2611 :tag "Org Progress"
2612 :group 'org-time)
2614 (defvar org-todo-interpretation-widgets
2615 '((:tag "Sequence (cycling hits every state)" sequence)
2616 (:tag "Type (cycling directly to DONE)" type))
2617 "The available interpretation symbols for customizing `org-todo-keywords'.
2618 Interested libraries should add to this list.")
2620 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2621 "List of TODO entry keyword sequences and their interpretation.
2622 \\<org-mode-map>This is a list of sequences.
2624 Each sequence starts with a symbol, either `sequence' or `type',
2625 indicating if the keywords should be interpreted as a sequence of
2626 action steps, or as different types of TODO items. The first
2627 keywords are states requiring action - these states will select a headline
2628 for inclusion into the global TODO list Org produces. If one of the
2629 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2630 signify that no further action is necessary. If \"|\" is not found,
2631 the last keyword is treated as the only DONE state of the sequence.
2633 The command `\\[org-todo]' cycles an entry through these states, and one
2634 additional state where no keyword is present. For details about this
2635 cycling, see the manual.
2637 TODO keywords and interpretation can also be set on a per-file basis with
2638 the special #+SEQ_TODO and #+TYP_TODO lines.
2640 Each keyword can optionally specify a character for fast state selection
2641 \(in combination with the variable `org-use-fast-todo-selection')
2642 and specifiers for state change logging, using the same syntax that
2643 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2644 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2645 indicates to record a time stamp each time this state is selected.
2647 Each keyword may also specify if a timestamp or a note should be
2648 recorded when entering or leaving the state, by adding additional
2649 characters in the parenthesis after the keyword. This looks like this:
2650 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2651 record only the time of the state change. With X and Y being either
2652 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2653 Y when leaving the state if and only if the *target* state does not
2654 define X. You may omit any of the fast-selection key or X or /Y,
2655 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2657 For backward compatibility, this variable may also be just a list
2658 of keywords. In this case the interpretation (sequence or type) will be
2659 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2660 :group 'org-todo
2661 :group 'org-keywords
2662 :type '(choice
2663 (repeat :tag "Old syntax, just keywords"
2664 (string :tag "Keyword"))
2665 (repeat :tag "New syntax"
2666 (cons
2667 (choice
2668 :tag "Interpretation"
2669 ;;Quick and dirty way to see
2670 ;;`org-todo-interpretations'. This takes the
2671 ;;place of item arguments
2672 :convert-widget
2673 (lambda (widget)
2674 (widget-put widget
2675 :args (mapcar
2676 (lambda (x)
2677 (widget-convert
2678 (cons 'const x)))
2679 org-todo-interpretation-widgets))
2680 widget))
2681 (repeat
2682 (string :tag "Keyword"))))))
2684 (defvar-local org-todo-keywords-1 nil
2685 "All TODO and DONE keywords active in a buffer.")
2686 (defvar org-todo-keywords-for-agenda nil)
2687 (defvar org-done-keywords-for-agenda nil)
2688 (defvar org-todo-keyword-alist-for-agenda nil)
2689 (defvar org-tag-alist-for-agenda nil
2690 "Alist of all tags from all agenda files.")
2691 (defvar org-tag-groups-alist-for-agenda nil
2692 "Alist of all groups tags from all current agenda files.")
2693 (defvar-local org-tag-groups-alist nil)
2694 (defvar org-agenda-contributing-files nil)
2695 (defvar-local org-current-tag-alist nil
2696 "Alist of all tag groups in current buffer.
2697 This variable takes into consideration `org-tag-alist',
2698 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2699 (defvar-local org-not-done-keywords nil)
2700 (defvar-local org-done-keywords nil)
2701 (defvar-local org-todo-heads nil)
2702 (defvar-local org-todo-sets nil)
2703 (defvar-local org-todo-log-states nil)
2704 (defvar-local org-todo-kwd-alist nil)
2705 (defvar-local org-todo-key-alist nil)
2706 (defvar-local org-todo-key-trigger nil)
2708 (defcustom org-todo-interpretation 'sequence
2709 "Controls how TODO keywords are interpreted.
2710 This variable is in principle obsolete and is only used for
2711 backward compatibility, if the interpretation of todo keywords is
2712 not given already in `org-todo-keywords'. See that variable for
2713 more information."
2714 :group 'org-todo
2715 :group 'org-keywords
2716 :type '(choice (const sequence)
2717 (const type)))
2719 (defcustom org-use-fast-todo-selection t
2720 "\\<org-mode-map>\
2721 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2722 This variable describes if and under what circumstances the cycling
2723 mechanism for TODO keywords will be replaced by a single-key, direct
2724 selection scheme.
2726 When nil, fast selection is never used.
2728 When the symbol `prefix', it will be used when `org-todo' is called
2729 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2730 in an Org buffer, and
2731 `\\[universal-argument] t' in an agenda buffer.
2733 When t, fast selection is used by default. In this case, the prefix
2734 argument forces cycling instead.
2736 In all cases, the special interface is only used if access keys have
2737 actually been assigned by the user, i.e. if keywords in the configuration
2738 are followed by a letter in parenthesis, like TODO(t)."
2739 :group 'org-todo
2740 :type '(choice
2741 (const :tag "Never" nil)
2742 (const :tag "By default" t)
2743 (const :tag "Only with C-u C-c C-t" prefix)))
2745 (defcustom org-provide-todo-statistics t
2746 "Non-nil means update todo statistics after insert and toggle.
2747 ALL-HEADLINES means update todo statistics by including headlines
2748 with no TODO keyword as well, counting them as not done.
2749 A list of TODO keywords means the same, but skip keywords that are
2750 not in this list.
2751 When set to a list of two lists, the first list contains keywords
2752 to consider as TODO keywords, the second list contains keywords
2753 to consider as DONE keywords.
2755 When this is set, todo statistics is updated in the parent of the
2756 current entry each time a todo state is changed."
2757 :group 'org-todo
2758 :type '(choice
2759 (const :tag "Yes, only for TODO entries" t)
2760 (const :tag "Yes, including all entries" all-headlines)
2761 (repeat :tag "Yes, for TODOs in this list"
2762 (string :tag "TODO keyword"))
2763 (list :tag "Yes, for TODOs and DONEs in these lists"
2764 (repeat (string :tag "TODO keyword"))
2765 (repeat (string :tag "DONE keyword")))
2766 (other :tag "No TODO statistics" nil)))
2768 (defcustom org-hierarchical-todo-statistics t
2769 "Non-nil means TODO statistics covers just direct children.
2770 When nil, all entries in the subtree are considered.
2771 This has only an effect if `org-provide-todo-statistics' is set.
2772 To set this to nil for only a single subtree, use a COOKIE_DATA
2773 property and include the word \"recursive\" into the value."
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-after-todo-state-change-hook nil
2778 "Hook which is run after the state of a TODO item was changed.
2779 The new state (a string with a TODO keyword, or nil) is available in the
2780 Lisp variable `org-state'."
2781 :group 'org-todo
2782 :type 'hook)
2784 (defvar org-blocker-hook nil
2785 "Hook for functions that are allowed to block a state change.
2787 Functions in this hook should not modify the buffer.
2788 Each function gets as its single argument a property list,
2789 see `org-trigger-hook' for more information about this list.
2791 If any of the functions in this hook returns nil, the state change
2792 is blocked.")
2794 (defvar org-trigger-hook nil
2795 "Hook for functions that are triggered by a state change.
2797 Each function gets as its single argument a property list with at
2798 least the following elements:
2800 (:type type-of-change :position pos-at-entry-start
2801 :from old-state :to new-state)
2803 Depending on the type, more properties may be present.
2805 This mechanism is currently implemented for:
2807 TODO state changes
2808 ------------------
2809 :type todo-state-change
2810 :from previous state (keyword as a string), or nil, or a symbol
2811 `todo' or `done', to indicate the general type of state.
2812 :to new state, like in :from")
2814 (defcustom org-enforce-todo-dependencies nil
2815 "Non-nil means undone TODO entries will block switching the parent to DONE.
2816 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2817 be blocked if any prior sibling is not yet done.
2818 Finally, if the parent is blocked because of ordered siblings of its own,
2819 the child will also be blocked."
2820 :set (lambda (var val)
2821 (set var val)
2822 (if val
2823 (add-hook 'org-blocker-hook
2824 'org-block-todo-from-children-or-siblings-or-parent)
2825 (remove-hook 'org-blocker-hook
2826 'org-block-todo-from-children-or-siblings-or-parent)))
2827 :group 'org-todo
2828 :type 'boolean)
2830 (defcustom org-enforce-todo-checkbox-dependencies nil
2831 "Non-nil means unchecked boxes will block switching the parent to DONE.
2832 When this is nil, checkboxes have no influence on switching TODO states.
2833 When non-nil, you first need to check off all check boxes before the TODO
2834 entry can be switched to DONE.
2835 This variable needs to be set before org.el is loaded, and you need to
2836 restart Emacs after a change to make the change effective. The only way
2837 to change is while Emacs is running is through the customize interface."
2838 :set (lambda (var val)
2839 (set var val)
2840 (if val
2841 (add-hook 'org-blocker-hook
2842 'org-block-todo-from-checkboxes)
2843 (remove-hook 'org-blocker-hook
2844 'org-block-todo-from-checkboxes)))
2845 :group 'org-todo
2846 :type 'boolean)
2848 (defcustom org-treat-insert-todo-heading-as-state-change nil
2849 "Non-nil means inserting a TODO heading is treated as state change.
2850 So when the command `\\[org-insert-todo-heading]' is used, state change
2851 logging will apply if appropriate. When nil, the new TODO item will
2852 be inserted directly, and no logging will take place."
2853 :group 'org-todo
2854 :type 'boolean)
2856 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2857 "Non-nil means switching TODO states with S-cursor counts as state change.
2858 This is the default behavior. However, setting this to nil allows a
2859 convenient way to select a TODO state and bypass any logging associated
2860 with that."
2861 :group 'org-todo
2862 :type 'boolean)
2864 (defcustom org-todo-state-tags-triggers nil
2865 "Tag changes that should be triggered by TODO state changes.
2866 This is a list. Each entry is
2868 (state-change (tag . flag) .......)
2870 State-change can be a string with a state, and empty string to indicate the
2871 state that has no TODO keyword, or it can be one of the symbols `todo'
2872 or `done', meaning any not-done or done state, respectively."
2873 :group 'org-todo
2874 :group 'org-tags
2875 :type '(repeat
2876 (cons (choice :tag "When changing to"
2877 (const :tag "Not-done state" todo)
2878 (const :tag "Done state" done)
2879 (string :tag "State"))
2880 (repeat
2881 (cons :tag "Tag action"
2882 (string :tag "Tag")
2883 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2885 (defcustom org-log-done nil
2886 "Information to record when a task moves to the DONE state.
2888 Possible values are:
2890 nil Don't add anything, just change the keyword
2891 time Add a time stamp to the task
2892 note Prompt for a note and add it with template `org-log-note-headings'
2894 This option can also be set with on a per-file-basis with
2896 #+STARTUP: nologdone
2897 #+STARTUP: logdone
2898 #+STARTUP: lognotedone
2900 You can have local logging settings for a subtree by setting the LOGGING
2901 property to one or more of these keywords."
2902 :group 'org-todo
2903 :group 'org-progress
2904 :type '(choice
2905 (const :tag "No logging" nil)
2906 (const :tag "Record CLOSED timestamp" time)
2907 (const :tag "Record CLOSED timestamp with note." note)))
2909 ;; Normalize old uses of org-log-done.
2910 (cond
2911 ((eq org-log-done t) (setq org-log-done 'time))
2912 ((and (listp org-log-done) (memq 'done org-log-done))
2913 (setq org-log-done 'note)))
2915 (defcustom org-log-reschedule nil
2916 "Information to record when the scheduling date of a tasks is modified.
2918 Possible values are:
2920 nil Don't add anything, just change the date
2921 time Add a time stamp to the task
2922 note Prompt for a note and add it with template `org-log-note-headings'
2924 This option can also be set with on a per-file-basis with
2926 #+STARTUP: nologreschedule
2927 #+STARTUP: logreschedule
2928 #+STARTUP: lognotereschedule"
2929 :group 'org-todo
2930 :group 'org-progress
2931 :type '(choice
2932 (const :tag "No logging" nil)
2933 (const :tag "Record timestamp" time)
2934 (const :tag "Record timestamp with note." note)))
2936 (defcustom org-log-redeadline nil
2937 "Information to record when the deadline date of a tasks is modified.
2939 Possible values are:
2941 nil Don't add anything, just change the date
2942 time Add a time stamp to the task
2943 note Prompt for a note and add it with template `org-log-note-headings'
2945 This option can also be set with on a per-file-basis with
2947 #+STARTUP: nologredeadline
2948 #+STARTUP: logredeadline
2949 #+STARTUP: lognoteredeadline
2951 You can have local logging settings for a subtree by setting the LOGGING
2952 property to one or more of these keywords."
2953 :group 'org-todo
2954 :group 'org-progress
2955 :type '(choice
2956 (const :tag "No logging" nil)
2957 (const :tag "Record timestamp" time)
2958 (const :tag "Record timestamp with note." note)))
2960 (defcustom org-log-note-clock-out nil
2961 "Non-nil means record a note when clocking out of an item.
2962 This can also be configured on a per-file basis by adding one of
2963 the following lines anywhere in the buffer:
2965 #+STARTUP: lognoteclock-out
2966 #+STARTUP: nolognoteclock-out"
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-done-with-time t
2972 "Non-nil means the CLOSED time stamp will contain date and time.
2973 When nil, only the date will be recorded."
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-note-headings
2978 '((done . "CLOSING NOTE %t")
2979 (state . "State %-12s from %-12S %t")
2980 (note . "Note taken on %t")
2981 (reschedule . "Rescheduled from %S on %t")
2982 (delschedule . "Not scheduled, was %S on %t")
2983 (redeadline . "New deadline from %S on %t")
2984 (deldeadline . "Removed deadline, was %S on %t")
2985 (refile . "Refiled on %t")
2986 (clock-out . ""))
2987 "Headings for notes added to entries.
2989 The value is an alist, with the car being a symbol indicating the
2990 note context, and the cdr is the heading to be used. The heading
2991 may also be the empty string. The following placeholders can be
2992 used:
2994 %t a time stamp.
2995 %T an active time stamp instead the default inactive one
2996 %d a short-format time stamp.
2997 %D an active short-format time stamp.
2998 %s the new TODO state or time stamp (inactive), in double quotes.
2999 %S the old TODO state or time stamp (inactive), in double quotes.
3000 %u the user name.
3001 %U full user name.
3003 In fact, it is not a good idea to change the `state' entry,
3004 because Agenda Log mode depends on the format of these entries."
3005 :group 'org-todo
3006 :group 'org-progress
3007 :type '(list :greedy t
3008 (cons (const :tag "Heading when closing an item" done) string)
3009 (cons (const :tag
3010 "Heading when changing todo state (todo sequence only)"
3011 state) string)
3012 (cons (const :tag "Heading when just taking a note" note) string)
3013 (cons (const :tag "Heading when rescheduling" reschedule) string)
3014 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3015 (cons (const :tag "Heading when changing deadline" redeadline) string)
3016 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3017 (cons (const :tag "Heading when refiling" refile) string)
3018 (cons (const :tag "Heading when clocking out" clock-out) string)))
3020 (unless (assq 'note org-log-note-headings)
3021 (push '(note . "%t") org-log-note-headings))
3023 (defcustom org-log-into-drawer nil
3024 "Non-nil means insert state change notes and time stamps into a drawer.
3025 When nil, state changes notes will be inserted after the headline and
3026 any scheduling and clock lines, but not inside a drawer.
3028 The value of this variable should be the name of the drawer to use.
3029 LOGBOOK is proposed as the default drawer for this purpose, you can
3030 also set this to a string to define the drawer of your choice.
3032 A value of t is also allowed, representing \"LOGBOOK\".
3034 A value of t or nil can also be set with on a per-file-basis with
3036 #+STARTUP: logdrawer
3037 #+STARTUP: nologdrawer
3039 If this variable is set, `org-log-state-notes-insert-after-drawers'
3040 will be ignored.
3042 You can set the property LOG_INTO_DRAWER to overrule this setting for
3043 a subtree.
3045 Do not check directly this variable in a Lisp program. Call
3046 function `org-log-into-drawer' instead."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type '(choice
3050 (const :tag "Not into a drawer" nil)
3051 (const :tag "LOGBOOK" t)
3052 (string :tag "Other")))
3054 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3056 (defun org-log-into-drawer ()
3057 "Name of the log drawer, as a string, or nil.
3058 This is the value of `org-log-into-drawer'. However, if the
3059 current entry has or inherits a LOG_INTO_DRAWER property, it will
3060 be used instead of the default value."
3061 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3062 (cond ((equal p "nil") nil)
3063 ((equal p "t") "LOGBOOK")
3064 ((stringp p) p)
3065 (p "LOGBOOK")
3066 ((stringp org-log-into-drawer) org-log-into-drawer)
3067 (org-log-into-drawer "LOGBOOK"))))
3069 (defcustom org-log-state-notes-insert-after-drawers nil
3070 "Non-nil means insert state change notes after any drawers in entry.
3071 Only the drawers that *immediately* follow the headline and the
3072 deadline/scheduled line are skipped.
3073 When nil, insert notes right after the heading and perhaps the line
3074 with deadline/scheduling if present.
3076 This variable will have no effect if `org-log-into-drawer' is
3077 set."
3078 :group 'org-todo
3079 :group 'org-progress
3080 :type 'boolean)
3082 (defcustom org-log-states-order-reversed t
3083 "Non-nil means the latest state note will be directly after heading.
3084 When nil, the state change notes will be ordered according to time.
3086 This option can also be set with on a per-file-basis with
3088 #+STARTUP: logstatesreversed
3089 #+STARTUP: nologstatesreversed"
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-todo-repeat-to-state nil
3095 "The TODO state to which a repeater should return the repeating task.
3096 By default this is the first task in a TODO sequence, or the previous state
3097 in a TODO_TYP set. But you can specify another task here.
3098 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3099 :group 'org-todo
3100 :version "24.1"
3101 :type '(choice (const :tag "Head of sequence" nil)
3102 (string :tag "Specific state")))
3104 (defcustom org-log-repeat 'time
3105 "Non-nil means record moving through the DONE state when triggering repeat.
3106 An auto-repeating task is immediately switched back to TODO when
3107 marked DONE. If you are not logging state changes (by adding \"@\"
3108 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3109 record a closing note, there will be no record of the task moving
3110 through DONE. This variable forces taking a note anyway.
3112 nil Don't force a record
3113 time Record a time stamp
3114 note Prompt for a note and add it with template `org-log-note-headings'
3116 This option can also be set with on a per-file-basis with
3118 #+STARTUP: nologrepeat
3119 #+STARTUP: logrepeat
3120 #+STARTUP: lognoterepeat
3122 You can have local logging settings for a subtree by setting the LOGGING
3123 property to one or more of these keywords."
3124 :group 'org-todo
3125 :group 'org-progress
3126 :type '(choice
3127 (const :tag "Don't force a record" nil)
3128 (const :tag "Force recording the DONE state" time)
3129 (const :tag "Force recording a note with the DONE state" note)))
3132 (defgroup org-priorities nil
3133 "Priorities in Org mode."
3134 :tag "Org Priorities"
3135 :group 'org-todo)
3137 (defcustom org-enable-priority-commands t
3138 "Non-nil means priority commands are active.
3139 When nil, these commands will be disabled, so that you never accidentally
3140 set a priority."
3141 :group 'org-priorities
3142 :type 'boolean)
3144 (defcustom org-highest-priority ?A
3145 "The highest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a smaller ASCII number than `org-lowest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-lowest-priority ?C
3151 "The lowest priority of TODO items. A character like ?A, ?B etc.
3152 Must have a larger ASCII number than `org-highest-priority'."
3153 :group 'org-priorities
3154 :type 'character)
3156 (defcustom org-default-priority ?B
3157 "The default priority of TODO items.
3158 This is the priority an item gets if no explicit priority is given.
3159 When starting to cycle on an empty priority the first step in the cycle
3160 depends on `org-priority-start-cycle-with-default'. The resulting first
3161 step priority must not exceed the range from `org-highest-priority' to
3162 `org-lowest-priority' which means that `org-default-priority' has to be
3163 in this range exclusive or inclusive the range boundaries. Else the
3164 first step refuses to set the default and the second will fall back
3165 to (depending on the command used) the highest or lowest priority."
3166 :group 'org-priorities
3167 :type 'character)
3169 (defcustom org-priority-start-cycle-with-default t
3170 "Non-nil means start with default priority when starting to cycle.
3171 When this is nil, the first step in the cycle will be (depending on the
3172 command used) one higher or lower than the default priority.
3173 See also `org-default-priority'."
3174 :group 'org-priorities
3175 :type 'boolean)
3177 (defcustom org-get-priority-function nil
3178 "Function to extract the priority from a string.
3179 The string is normally the headline. If this is nil Org computes the
3180 priority from the priority cookie like [#A] in the headline. It returns
3181 an integer, increasing by 1000 for each priority level.
3182 The user can set a different function here, which should take a string
3183 as an argument and return the numeric priority."
3184 :group 'org-priorities
3185 :version "24.1"
3186 :type '(choice
3187 (const nil)
3188 (function)))
3190 (defgroup org-time nil
3191 "Options concerning time stamps and deadlines in Org mode."
3192 :tag "Org Time"
3193 :group 'org)
3195 (defcustom org-time-stamp-rounding-minutes '(0 5)
3196 "Number of minutes to round time stamps to.
3197 \\<org-mode-map>\
3198 These are two values, the first applies when first creating a time stamp.
3199 The second applies when changing it with the commands `S-up' and `S-down'.
3200 When changing the time stamp, this means that it will change in steps
3201 of N minutes, as given by the second value.
3203 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3204 numbers should be factors of 60, so for example 5, 10, 15.
3206 When this is larger than 1, you can still force an exact time stamp by using
3207 a double prefix argument to a time stamp command like \
3208 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3209 and by using a prefix arg to `S-up/down' to specify the exact number
3210 of minutes to shift."
3211 :group 'org-time
3212 :get (lambda (var) ; Make sure both elements are there
3213 (if (integerp (default-value var))
3214 (list (default-value var) 5)
3215 (default-value var)))
3216 :type '(list
3217 (integer :tag "when inserting times")
3218 (integer :tag "when modifying times")))
3220 ;; Normalize old customizations of this variable.
3221 (when (integerp org-time-stamp-rounding-minutes)
3222 (setq org-time-stamp-rounding-minutes
3223 (list org-time-stamp-rounding-minutes
3224 org-time-stamp-rounding-minutes)))
3226 (defcustom org-display-custom-times nil
3227 "Non-nil means overlay custom formats over all time stamps.
3228 The formats are defined through the variable `org-time-stamp-custom-formats'.
3229 To turn this on on a per-file basis, insert anywhere in the file:
3230 #+STARTUP: customtime"
3231 :group 'org-time
3232 :set 'set-default
3233 :type 'sexp)
3234 (make-variable-buffer-local 'org-display-custom-times)
3236 (defcustom org-time-stamp-custom-formats
3237 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3238 "Custom formats for time stamps. See `format-time-string' for the syntax.
3239 These are overlaid over the default ISO format if the variable
3240 `org-display-custom-times' is set. Time like %H:%M should be at the
3241 end of the second format. The custom formats are also honored by export
3242 commands, if custom time display is turned on at the time of export."
3243 :group 'org-time
3244 :type 'sexp)
3246 (defun org-time-stamp-format (&optional long inactive)
3247 "Get the right format for a time string."
3248 (let ((f (if long (cdr org-time-stamp-formats)
3249 (car org-time-stamp-formats))))
3250 (if inactive
3251 (concat "[" (substring f 1 -1) "]")
3252 f)))
3254 (defcustom org-deadline-warning-days 14
3255 "Number of days before expiration during which a deadline becomes active.
3256 This variable governs the display in sparse trees and in the agenda.
3257 When 0 or negative, it means use this number (the absolute value of it)
3258 even if a deadline has a different individual lead time specified.
3260 Custom commands can set this variable in the options section."
3261 :group 'org-time
3262 :group 'org-agenda-daily/weekly
3263 :type 'integer)
3265 (defcustom org-scheduled-delay-days 0
3266 "Number of days before a scheduled item becomes active.
3267 This variable governs the display in sparse trees and in the agenda.
3268 The default value (i.e. 0) means: don't delay scheduled item.
3269 When negative, it means use this number (the absolute value of it)
3270 even if a scheduled item has a different individual delay time
3271 specified.
3273 Custom commands can set this variable in the options section."
3274 :group 'org-time
3275 :group 'org-agenda-daily/weekly
3276 :version "24.4"
3277 :package-version '(Org . "8.0")
3278 :type 'integer)
3280 (defcustom org-read-date-prefer-future t
3281 "Non-nil means assume future for incomplete date input from user.
3282 This affects the following situations:
3283 1. The user gives a month but not a year.
3284 For example, if it is April and you enter \"feb 2\", this will be read
3285 as Feb 2, *next* year. \"May 5\", however, will be this year.
3286 2. The user gives a day, but no month.
3287 For example, if today is the 15th, and you enter \"3\", Org will read
3288 this as the third of *next* month. However, if you enter \"17\",
3289 it will be considered as *this* month.
3291 If you set this variable to the symbol `time', then also the following
3292 will work:
3294 3. If the user gives a time.
3295 If the time is before now, it will be interpreted as tomorrow.
3297 Currently none of this works for ISO week specifications.
3299 When this option is nil, the current day, month and year will always be
3300 used as defaults.
3302 See also `org-agenda-jump-prefer-future'."
3303 :group 'org-time
3304 :type '(choice
3305 (const :tag "Never" nil)
3306 (const :tag "Check month and day" t)
3307 (const :tag "Check month, day, and time" time)))
3309 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3310 "Should the agenda jump command prefer the future for incomplete dates?
3311 The default is to do the same as configured in `org-read-date-prefer-future'.
3312 But you can also set a deviating value here.
3313 This may t or nil, or the symbol `org-read-date-prefer-future'."
3314 :group 'org-agenda
3315 :group 'org-time
3316 :version "24.1"
3317 :type '(choice
3318 (const :tag "Use org-read-date-prefer-future"
3319 org-read-date-prefer-future)
3320 (const :tag "Never" nil)
3321 (const :tag "Always" t)))
3323 (defcustom org-read-date-force-compatible-dates t
3324 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3326 Depending on the system Emacs is running on, certain dates cannot
3327 be represented with the type used internally to represent time.
3328 Dates between 1970-1-1 and 2038-1-1 can always be represented
3329 correctly. Some systems allow for earlier dates, some for later,
3330 some for both. One way to find out it to insert any date into an
3331 Org buffer, putting the cursor on the year and hitting S-up and
3332 S-down to test the range.
3334 When this variable is set to t, the date/time prompt will not let
3335 you specify dates outside the 1970-2037 range, so it is certain that
3336 these dates will work in whatever version of Emacs you are
3337 running, and also that you can move a file from one Emacs implementation
3338 to another. WHenever Org is forcing the year for you, it will display
3339 a message and beep.
3341 When this variable is nil, Org will check if the date is
3342 representable in the specific Emacs implementation you are using.
3343 If not, it will force a year, usually the current year, and beep
3344 to remind you. Currently this setting is not recommended because
3345 the likelihood that you will open your Org files in an Emacs that
3346 has limited date range is not negligible.
3348 A workaround for this problem is to use diary sexp dates for time
3349 stamps outside of this range."
3350 :group 'org-time
3351 :version "24.1"
3352 :type 'boolean)
3354 (defcustom org-read-date-display-live t
3355 "Non-nil means display current interpretation of date prompt live.
3356 This display will be in an overlay, in the minibuffer."
3357 :group 'org-time
3358 :type 'boolean)
3360 (defcustom org-read-date-popup-calendar t
3361 "Non-nil means pop up a calendar when prompting for a date.
3362 In the calendar, the date can be selected with mouse-1. However, the
3363 minibuffer will also be active, and you can simply enter the date as well.
3364 When nil, only the minibuffer will be available."
3365 :group 'org-time
3366 :type 'boolean)
3367 (defvaralias 'org-popup-calendar-for-date-prompt
3368 'org-read-date-popup-calendar)
3370 (defcustom org-extend-today-until 0
3371 "The hour when your day really ends. Must be an integer.
3372 This has influence for the following applications:
3373 - When switching the agenda to \"today\". It it is still earlier than
3374 the time given here, the day recognized as TODAY is actually yesterday.
3375 - When a date is read from the user and it is still before the time given
3376 here, the current date and time will be assumed to be yesterday, 23:59.
3377 Also, timestamps inserted in capture templates follow this rule.
3379 IMPORTANT: This is a feature whose implementation is and likely will
3380 remain incomplete. Really, it is only here because past midnight seems to
3381 be the favorite working time of John Wiegley :-)"
3382 :group 'org-time
3383 :type 'integer)
3385 (defcustom org-use-effective-time nil
3386 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3387 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3388 \"effective time\" of any timestamps between midnight and 8am will be
3389 23:59 of the previous day."
3390 :group 'org-time
3391 :version "24.1"
3392 :type 'boolean)
3394 (defcustom org-use-last-clock-out-time-as-effective-time nil
3395 "When non-nil, use the last clock out time for `org-todo'.
3396 Note that this option has precedence over the combined use of
3397 `org-use-effective-time' and `org-extend-today-until'."
3398 :group 'org-time
3399 :version "24.4"
3400 :package-version '(Org . "8.0")
3401 :type 'boolean)
3403 (defcustom org-edit-timestamp-down-means-later nil
3404 "Non-nil means S-down will increase the time in a time stamp.
3405 When nil, S-up will increase."
3406 :group 'org-time
3407 :type 'boolean)
3409 (defcustom org-calendar-follow-timestamp-change t
3410 "Non-nil means make the calendar window follow timestamp changes.
3411 When a timestamp is modified and the calendar window is visible, it will be
3412 moved to the new date."
3413 :group 'org-time
3414 :type 'boolean)
3416 (defgroup org-tags nil
3417 "Options concerning tags in Org mode."
3418 :tag "Org Tags"
3419 :group 'org)
3421 (defcustom org-tag-alist nil
3422 "Default tags available in Org files.
3424 The value of this variable is an alist. Associations either:
3426 (TAG)
3427 (TAG . SELECT)
3428 (SPECIAL)
3430 where TAG is a tag as a string, SELECT is character, used to
3431 select that tag through the fast tag selection interface, and
3432 SPECIAL is one of the following keywords: `:startgroup',
3433 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3434 `:newline'. These keywords are used to define a hierarchy of
3435 tags. See manual for details.
3437 When this variable is nil, Org mode bases tag input on what is
3438 already in the buffer. The value can be overridden locally by
3439 using a TAGS keyword, e.g.,
3441 #+TAGS: tag1 tag2
3443 See also `org-tag-persistent-alist' to sidestep this behavior."
3444 :group 'org-tags
3445 :type '(repeat
3446 (choice
3447 (cons (string :tag "Tag name")
3448 (character :tag "Access char"))
3449 (const :tag "Start radio group" (:startgroup))
3450 (const :tag "Start tag group, non distinct" (:startgrouptag))
3451 (const :tag "Group tags delimiter" (:grouptags))
3452 (const :tag "End radio group" (:endgroup))
3453 (const :tag "End tag group, non distinct" (:endgrouptag))
3454 (const :tag "New line" (:newline)))))
3456 (defcustom org-tag-persistent-alist nil
3457 "Tags always available in Org files.
3459 The value of this variable is an alist. Associations either:
3461 (TAG)
3462 (TAG . SELECT)
3463 (SPECIAL)
3465 where TAG is a tag as a string, SELECT is a character, used to
3466 select that tag through the fast tag selection interface, and
3467 SPECIAL is one of the following keywords: `:startgroup',
3468 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3469 `:newline'. These keywords are used to define a hierarchy of
3470 tags. See manual for details.
3472 Unlike to `org-tag-alist', tags defined in this variable do not
3473 depend on a local TAGS keyword. Instead, to disable these tags
3474 on a per-file basis, insert anywhere in the file:
3476 #+STARTUP: noptag"
3477 :group 'org-tags
3478 :type '(repeat
3479 (choice
3480 (cons (string :tag "Tag name")
3481 (character :tag "Access char"))
3482 (const :tag "Start radio group" (:startgroup))
3483 (const :tag "Start tag group, non distinct" (:startgrouptag))
3484 (const :tag "Group tags delimiter" (:grouptags))
3485 (const :tag "End radio group" (:endgroup))
3486 (const :tag "End tag group, non distinct" (:endgrouptag))
3487 (const :tag "New line" (:newline)))))
3489 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3490 "If non-nil, always offer completion for all tags of all agenda files.
3491 Instead of customizing this variable directly, you might want to
3492 set it locally for capture buffers, because there no list of
3493 tags in that file can be created dynamically (there are none).
3495 (add-hook \\='org-capture-mode-hook
3496 (lambda ()
3497 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3498 :group 'org-tags
3499 :version "24.1"
3500 :type 'boolean)
3502 (defvar org-file-tags nil
3503 "List of tags that can be inherited by all entries in the file.
3504 The tags will be inherited if the variable `org-use-tag-inheritance'
3505 says they should be.
3506 This variable is populated from #+FILETAGS lines.")
3508 (defcustom org-use-fast-tag-selection 'auto
3509 "Non-nil means use fast tag selection scheme.
3510 This is a special interface to select and deselect tags with single keys.
3511 When nil, fast selection is never used.
3512 When the symbol `auto', fast selection is used if and only if selection
3513 characters for tags have been configured, either through the variable
3514 `org-tag-alist' or through a #+TAGS line in the buffer.
3515 When t, fast selection is always used and selection keys are assigned
3516 automatically if necessary."
3517 :group 'org-tags
3518 :type '(choice
3519 (const :tag "Always" t)
3520 (const :tag "Never" nil)
3521 (const :tag "When selection characters are configured" auto)))
3523 (defcustom org-fast-tag-selection-single-key nil
3524 "Non-nil means fast tag selection exits after first change.
3525 When nil, you have to press RET to exit it.
3526 During fast tag selection, you can toggle this flag with `C-c'.
3527 This variable can also have the value `expert'. In this case, the window
3528 displaying the tags menu is not even shown, until you press C-c again."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "No" nil)
3532 (const :tag "Yes" t)
3533 (const :tag "Expert" expert)))
3535 (defvar org-fast-tag-selection-include-todo nil
3536 "Non-nil means fast tags selection interface will also offer TODO states.
3537 This is an undocumented feature, you should not rely on it.")
3539 (defcustom org-tags-column -77
3540 "The column to which tags should be indented in a headline.
3541 If this number is positive, it specifies the column. If it is negative,
3542 it means that the tags should be flushright to that column. For example,
3543 -80 works well for a normal 80 character screen.
3544 When 0, place tags directly after headline text, with only one space in
3545 between."
3546 :group 'org-tags
3547 :type 'integer)
3549 (defcustom org-auto-align-tags t
3550 "Non-nil keeps tags aligned when modifying headlines.
3551 Some operations (i.e. demoting) change the length of a headline and
3552 therefore shift the tags around. With this option turned on, after
3553 each such operation the tags are again aligned to `org-tags-column'."
3554 :group 'org-tags
3555 :type 'boolean)
3557 (defcustom org-use-tag-inheritance t
3558 "Non-nil means tags in levels apply also for sublevels.
3559 When nil, only the tags directly given in a specific line apply there.
3560 This may also be a list of tags that should be inherited, or a regexp that
3561 matches tags that should be inherited. Additional control is possible
3562 with the variable `org-tags-exclude-from-inheritance' which gives an
3563 explicit list of tags to be excluded from inheritance, even if the value of
3564 `org-use-tag-inheritance' would select it for inheritance.
3566 If this option is t, a match early-on in a tree can lead to a large
3567 number of matches in the subtree when constructing the agenda or creating
3568 a sparse tree. If you only want to see the first match in a tree during
3569 a search, check out the variable `org-tags-match-list-sublevels'."
3570 :group 'org-tags
3571 :type '(choice
3572 (const :tag "Not" nil)
3573 (const :tag "Always" t)
3574 (repeat :tag "Specific tags" (string :tag "Tag"))
3575 (regexp :tag "Tags matched by regexp")))
3577 (defcustom org-tags-exclude-from-inheritance nil
3578 "List of tags that should never be inherited.
3579 This is a way to exclude a few tags from inheritance. For way to do
3580 the opposite, to actively allow inheritance for selected tags,
3581 see the variable `org-use-tag-inheritance'."
3582 :group 'org-tags
3583 :type '(repeat (string :tag "Tag")))
3585 (defun org-tag-inherit-p (tag)
3586 "Check if TAG is one that should be inherited."
3587 (cond
3588 ((member tag org-tags-exclude-from-inheritance) nil)
3589 ((eq org-use-tag-inheritance t) t)
3590 ((not org-use-tag-inheritance) nil)
3591 ((stringp org-use-tag-inheritance)
3592 (string-match org-use-tag-inheritance tag))
3593 ((listp org-use-tag-inheritance)
3594 (member tag org-use-tag-inheritance))
3595 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3597 (defcustom org-tags-match-list-sublevels t
3598 "Non-nil means list also sublevels of headlines matching a search.
3599 This variable applies to tags/property searches, and also to stuck
3600 projects because this search is based on a tags match as well.
3602 When set to the symbol `indented', sublevels are indented with
3603 leading dots.
3605 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3606 the sublevels of a headline matching a tag search often also match
3607 the same search. Listing all of them can create very long lists.
3608 Setting this variable to nil causes subtrees of a match to be skipped.
3610 This variable is semi-obsolete and probably should always be true. It
3611 is better to limit inheritance to certain tags using the variables
3612 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3613 :group 'org-tags
3614 :type '(choice
3615 (const :tag "No, don't list them" nil)
3616 (const :tag "Yes, do list them" t)
3617 (const :tag "List them, indented with leading dots" indented)))
3619 (defcustom org-tags-sort-function nil
3620 "When set, tags are sorted using this function as a comparator."
3621 :group 'org-tags
3622 :type '(choice
3623 (const :tag "No sorting" nil)
3624 (const :tag "Alphabetical" string<)
3625 (const :tag "Reverse alphabetical" string>)
3626 (function :tag "Custom function" nil)))
3628 (defvar org-tags-history nil
3629 "History of minibuffer reads for tags.")
3630 (defvar org-last-tags-completion-table nil
3631 "The last used completion table for tags.")
3632 (defvar org-after-tags-change-hook nil
3633 "Hook that is run after the tags in a line have changed.")
3635 (defgroup org-properties nil
3636 "Options concerning properties in Org mode."
3637 :tag "Org Properties"
3638 :group 'org)
3640 (defcustom org-property-format "%-10s %s"
3641 "How property key/value pairs should be formatted by `indent-line'.
3642 When `indent-line' hits a property definition, it will format the line
3643 according to this format, mainly to make sure that the values are
3644 lined-up with respect to each other."
3645 :group 'org-properties
3646 :type 'string)
3648 (defcustom org-properties-postprocess-alist nil
3649 "Alist of properties and functions to adjust inserted values.
3650 Elements of this alist must be of the form
3652 ([string] [function])
3654 where [string] must be a property name and [function] must be a
3655 lambda expression: this lambda expression must take one argument,
3656 the value to adjust, and return the new value as a string.
3658 For example, this element will allow the property \"Remaining\"
3659 to be updated wrt the relation between the \"Effort\" property
3660 and the clock summary:
3662 ((\"Remaining\" (lambda(value)
3663 (let ((clocksum (org-clock-sum-current-item))
3664 (effort (org-duration-to-minutes
3665 (org-entry-get (point) \"Effort\"))))
3666 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3667 :group 'org-properties
3668 :version "24.1"
3669 :type '(alist :key-type (string :tag "Property")
3670 :value-type (function :tag "Function")))
3672 (defcustom org-use-property-inheritance nil
3673 "Non-nil means properties apply also for sublevels.
3675 This setting is chiefly used during property searches. Turning it on can
3676 cause significant overhead when doing a search, which is why it is not
3677 on by default.
3679 When nil, only the properties directly given in the current entry count.
3680 When t, every property is inherited. The value may also be a list of
3681 properties that should have inheritance, or a regular expression matching
3682 properties that should be inherited.
3684 However, note that some special properties use inheritance under special
3685 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3686 and the properties ending in \"_ALL\" when they are used as descriptor
3687 for valid values of a property.
3689 Note for programmers:
3690 When querying an entry with `org-entry-get', you can control if inheritance
3691 should be used. By default, `org-entry-get' looks only at the local
3692 properties. You can request inheritance by setting the inherit argument
3693 to t (to force inheritance) or to `selective' (to respect the setting
3694 in this variable)."
3695 :group 'org-properties
3696 :type '(choice
3697 (const :tag "Not" nil)
3698 (const :tag "Always" t)
3699 (repeat :tag "Specific properties" (string :tag "Property"))
3700 (regexp :tag "Properties matched by regexp")))
3702 (defun org-property-inherit-p (property)
3703 "Return a non-nil value if PROPERTY should be inherited."
3704 (cond
3705 ((eq org-use-property-inheritance t) t)
3706 ((not org-use-property-inheritance) nil)
3707 ((stringp org-use-property-inheritance)
3708 (string-match org-use-property-inheritance property))
3709 ((listp org-use-property-inheritance)
3710 (member-ignore-case property org-use-property-inheritance))
3711 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3713 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3714 "The default column format, if no other format has been defined.
3715 This variable can be set on the per-file basis by inserting a line
3717 #+COLUMNS: %25ITEM ....."
3718 :group 'org-properties
3719 :type 'string)
3721 (defcustom org-columns-ellipses ".."
3722 "The ellipses to be used when a field in column view is truncated.
3723 When this is the empty string, as many characters as possible are shown,
3724 but then there will be no visual indication that the field has been truncated.
3725 When this is a string of length N, the last N characters of a truncated
3726 field are replaced by this string. If the column is narrower than the
3727 ellipses string, only part of the ellipses string will be shown."
3728 :group 'org-properties
3729 :type 'string)
3731 (defconst org-global-properties-fixed
3732 '(("VISIBILITY_ALL" . "folded children content all")
3733 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3734 "List of property/value pairs that can be inherited by any entry.
3736 These are fixed values, for the preset properties. The user variable
3737 that can be used to add to this list is `org-global-properties'.
3739 The entries in this list are cons cells where the car is a property
3740 name and cdr is a string with the value. If the value represents
3741 multiple items like an \"_ALL\" property, separate the items by
3742 spaces.")
3744 (defcustom org-global-properties nil
3745 "List of property/value pairs that can be inherited by any entry.
3747 This list will be combined with the constant `org-global-properties-fixed'.
3749 The entries in this list are cons cells where the car is a property
3750 name and cdr is a string with the value.
3752 You can set buffer-local values for the same purpose in the variable
3753 `org-file-properties' this by adding lines like
3755 #+PROPERTY: NAME VALUE"
3756 :group 'org-properties
3757 :type '(repeat
3758 (cons (string :tag "Property")
3759 (string :tag "Value"))))
3761 (defvar-local org-file-properties nil
3762 "List of property/value pairs that can be inherited by any entry.
3763 Valid for the current buffer.
3764 This variable is populated from #+PROPERTY lines.")
3766 (defgroup org-agenda nil
3767 "Options concerning agenda views in Org mode."
3768 :tag "Org Agenda"
3769 :group 'org)
3771 (defvar-local org-category nil
3772 "Variable used by org files to set a category for agenda display.
3773 Such files should use a file variable to set it, for example
3775 # -*- mode: org; org-category: \"ELisp\"
3777 or contain a special line
3779 #+CATEGORY: ELisp
3781 If the file does not specify a category, then file's base name
3782 is used instead.")
3783 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3785 (defcustom org-agenda-files nil
3786 "The files to be used for agenda display.
3788 If an entry is a directory, all files in that directory that are matched
3789 by `org-agenda-file-regexp' will be part of the file list.
3791 If the value of the variable is not a list but a single file name, then
3792 the list of agenda files is actually stored and maintained in that file,
3793 one agenda file per line. In this file paths can be given relative to
3794 `org-directory'. Tilde expansion and environment variable substitution
3795 are also made.
3797 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3798 and removed with `\\[org-remove-file]'."
3799 :group 'org-agenda
3800 :type '(choice
3801 (repeat :tag "List of files and directories" file)
3802 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3804 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3805 "Regular expression to match files for `org-agenda-files'.
3806 If any element in the list in that variable contains a directory instead
3807 of a normal file, all files in that directory that are matched by this
3808 regular expression will be included."
3809 :group 'org-agenda
3810 :type 'regexp)
3812 (defcustom org-agenda-text-search-extra-files nil
3813 "List of extra files to be searched by text search commands.
3814 These files will be searched in addition to the agenda files by the
3815 commands `org-search-view' (`\\[org-agenda] s') \
3816 and `org-occur-in-agenda-files'.
3817 Note that these files will only be searched for text search commands,
3818 not for the other agenda views like todo lists, tag searches or the weekly
3819 agenda. This variable is intended to list notes and possibly archive files
3820 that should also be searched by these two commands.
3821 In fact, if the first element in the list is the symbol `agenda-archives',
3822 then all archive files of all agenda files will be added to the search
3823 scope."
3824 :group 'org-agenda
3825 :type '(set :greedy t
3826 (const :tag "Agenda Archives" agenda-archives)
3827 (repeat :inline t (file))))
3829 (defvaralias 'org-agenda-multi-occur-extra-files
3830 'org-agenda-text-search-extra-files)
3832 (defcustom org-agenda-skip-unavailable-files nil
3833 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3834 A nil value means to remove them, after a query, from the list."
3835 :group 'org-agenda
3836 :type 'boolean)
3838 (defcustom org-calendar-to-agenda-key [?c]
3839 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3840 The command `org-calendar-goto-agenda' will be bound to this key. The
3841 default is the character `c' because then `c' can be used to switch back and
3842 forth between agenda and calendar."
3843 :group 'org-agenda
3844 :type 'sexp)
3846 (defcustom org-calendar-insert-diary-entry-key [?i]
3847 "The key to be installed in `calendar-mode-map' for adding diary entries.
3848 This option is irrelevant until `org-agenda-diary-file' has been configured
3849 to point to an Org file. When that is the case, the command
3850 `org-agenda-diary-entry' will be bound to the key given here, by default
3851 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3852 if you want to continue doing this, you need to change this to a different
3853 key."
3854 :group 'org-agenda
3855 :type 'sexp)
3857 (defcustom org-agenda-diary-file 'diary-file
3858 "File to which to add new entries with the `i' key in agenda and calendar.
3859 When this is the symbol `diary-file', the functionality in the Emacs
3860 calendar will be used to add entries to the `diary-file'. But when this
3861 points to a file, `org-agenda-diary-entry' will be used instead."
3862 :group 'org-agenda
3863 :type '(choice
3864 (const :tag "The standard Emacs diary file" diary-file)
3865 (file :tag "Special Org file diary entries")))
3867 (eval-after-load "calendar"
3868 '(progn
3869 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3870 'org-calendar-goto-agenda)
3871 (add-hook 'calendar-mode-hook
3872 (lambda ()
3873 (unless (eq org-agenda-diary-file 'diary-file)
3874 (define-key calendar-mode-map
3875 org-calendar-insert-diary-entry-key
3876 'org-agenda-diary-entry))))))
3878 (defgroup org-latex nil
3879 "Options for embedding LaTeX code into Org mode."
3880 :tag "Org LaTeX"
3881 :group 'org)
3883 (defcustom org-format-latex-options
3884 '(:foreground default :background default :scale 1.0
3885 :html-foreground "Black" :html-background "Transparent"
3886 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3887 "Options for creating images from LaTeX fragments.
3888 This is a property list with the following properties:
3889 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3890 `default' means use the foreground of the default face.
3891 `auto' means use the foreground from the text face.
3892 :background the background color, or \"Transparent\".
3893 `default' means use the background of the default face.
3894 `auto' means use the background from the text face.
3895 :scale a scaling factor for the size of the images, to get more pixels
3896 :html-foreground, :html-background, :html-scale
3897 the same numbers for HTML export.
3898 :matchers a list indicating which matchers should be used to
3899 find LaTeX fragments. Valid members of this list are:
3900 \"begin\" find environments
3901 \"$1\" find single characters surrounded by $.$
3902 \"$\" find math expressions surrounded by $...$
3903 \"$$\" find math expressions surrounded by $$....$$
3904 \"\\(\" find math expressions surrounded by \\(...\\)
3905 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3906 :group 'org-latex
3907 :type 'plist)
3909 (defcustom org-format-latex-signal-error t
3910 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3911 When nil, just push out a message."
3912 :group 'org-latex
3913 :version "24.1"
3914 :type 'boolean)
3916 (defcustom org-latex-to-mathml-jar-file nil
3917 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3918 Use this to specify additional executable file say a jar file.
3920 When using MathToWeb as the converter, specify the full-path to
3921 your mathtoweb.jar file."
3922 :group 'org-latex
3923 :version "24.1"
3924 :type '(choice
3925 (const :tag "None" nil)
3926 (file :tag "JAR file" :must-match t)))
3928 (defcustom org-latex-to-mathml-convert-command nil
3929 "Command to convert LaTeX fragments to MathML.
3930 Replace format-specifiers in the command as noted below and use
3931 `shell-command' to convert LaTeX to MathML.
3932 %j: Executable file in fully expanded form as specified by
3933 `org-latex-to-mathml-jar-file'.
3934 %I: Input LaTeX file in fully expanded form.
3935 %i: The latex fragment to be converted.
3936 %o: Output MathML file.
3938 This command is used by `org-create-math-formula'.
3940 When using MathToWeb as the converter, set this option to
3941 \"java -jar %j -unicode -force -df %o %I\".
3943 When using LaTeXML set this option to
3944 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3945 :group 'org-latex
3946 :version "24.1"
3947 :type '(choice
3948 (const :tag "None" nil)
3949 (string :tag "\nShell command")))
3951 (defcustom org-preview-latex-default-process 'dvipng
3952 "The default process to convert LaTeX fragments to image files.
3953 All available processes and theirs documents can be found in
3954 `org-preview-latex-process-alist', which see."
3955 :group 'org-latex
3956 :version "26.1"
3957 :package-version '(Org . "9.0")
3958 :type 'symbol)
3960 (defcustom org-preview-latex-process-alist
3961 '((dvipng
3962 :programs ("latex" "dvipng")
3963 :description "dvi > png"
3964 :message "you need to install the programs: latex and dvipng."
3965 :image-input-type "dvi"
3966 :image-output-type "png"
3967 :image-size-adjust (1.0 . 1.0)
3968 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3969 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3970 (dvisvgm
3971 :programs ("latex" "dvisvgm")
3972 :description "dvi > svg"
3973 :message "you need to install the programs: latex and dvisvgm."
3974 :use-xcolor t
3975 :image-input-type "dvi"
3976 :image-output-type "svg"
3977 :image-size-adjust (1.7 . 1.5)
3978 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3979 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3980 (imagemagick
3981 :programs ("latex" "convert")
3982 :description "pdf > png"
3983 :message "you need to install the programs: latex and imagemagick."
3984 :use-xcolor t
3985 :image-input-type "pdf"
3986 :image-output-type "png"
3987 :image-size-adjust (1.0 . 1.0)
3988 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3989 :image-converter
3990 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3991 "Definitions of external processes for LaTeX previewing.
3992 Org mode can use some external commands to generate TeX snippet's images for
3993 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3994 `org-create-formula-image' how to call them.
3996 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3997 PROPERTIES accepts the following attributes:
3999 :programs list of strings, required programs.
4000 :description string, describe the process.
4001 :message string, message it when required programs cannot be found.
4002 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4003 :image-output-type string, output file type of image converter (e.g., \"png\").
4004 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4005 deal with background and foreground color of image.
4006 Otherwise, dvipng style background and foregroud color
4007 format are generated. You may then refer to them in
4008 command options with \"%F\" and \"%B\".
4009 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4010 image size showed in buffer and the cdr element is for
4011 HTML file. This option is only useful for process
4012 developers, users should use variable
4013 `org-format-latex-options' instead.
4014 :post-clean list of strings, files matched are to be cleaned up once
4015 the image is generated. When nil, the files with \".dvi\",
4016 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4017 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4018 be cleaned up.
4019 :latex-header list of strings, the LaTeX header of the snippet file.
4020 When nil, the fallback value is used instead, which is
4021 controlled by `org-format-latex-header',
4022 `org-latex-default-packages-alist' and
4023 `org-latex-packages-alist', which see.
4024 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4025 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4026 replaced with values defined below.
4027 :image-converter list of image converter commands strings. Each of them is
4028 given to the shell and supports any of the following
4029 place-holders defined below.
4031 Place-holders used by `:image-converter' and `:latex-compiler':
4033 %f input file name
4034 %b base name of input file
4035 %o base directory of input file
4036 %O absolute output file name
4038 Place-holders only used by `:image-converter':
4040 %F foreground of image
4041 %B background of image
4042 %D dpi, which is used to adjust image size by some processing commands.
4043 %S the image size scale ratio, which is used to adjust image size by some
4044 processing commands."
4045 :group 'org-latex
4046 :version "26.1"
4047 :package-version '(Org . "9.0")
4048 :type '(alist :tag "LaTeX to image backends"
4049 :value-type (plist)))
4051 (defcustom org-preview-latex-image-directory "ltximg/"
4052 "Path to store latex preview images.
4053 A relative path here creates many directories relative to the
4054 processed org files paths. An absolute path puts all preview
4055 images at the same place."
4056 :group 'org-latex
4057 :version "26.1"
4058 :package-version '(Org . "9.0")
4059 :type 'string)
4061 (defun org-format-latex-mathml-available-p ()
4062 "Return t if `org-latex-to-mathml-convert-command' is usable."
4063 (save-match-data
4064 (when (and (boundp 'org-latex-to-mathml-convert-command)
4065 org-latex-to-mathml-convert-command)
4066 (let ((executable (car (split-string
4067 org-latex-to-mathml-convert-command))))
4068 (when (executable-find executable)
4069 (if (string-match
4070 "%j" org-latex-to-mathml-convert-command)
4071 (file-readable-p org-latex-to-mathml-jar-file)
4072 t))))))
4074 (defcustom org-format-latex-header "\\documentclass{article}
4075 \\usepackage[usenames]{color}
4076 \[PACKAGES]
4077 \[DEFAULT-PACKAGES]
4078 \\pagestyle{empty} % do not remove
4079 % The settings below are copied from fullpage.sty
4080 \\setlength{\\textwidth}{\\paperwidth}
4081 \\addtolength{\\textwidth}{-3cm}
4082 \\setlength{\\oddsidemargin}{1.5cm}
4083 \\addtolength{\\oddsidemargin}{-2.54cm}
4084 \\setlength{\\evensidemargin}{\\oddsidemargin}
4085 \\setlength{\\textheight}{\\paperheight}
4086 \\addtolength{\\textheight}{-\\headheight}
4087 \\addtolength{\\textheight}{-\\headsep}
4088 \\addtolength{\\textheight}{-\\footskip}
4089 \\addtolength{\\textheight}{-3cm}
4090 \\setlength{\\topmargin}{1.5cm}
4091 \\addtolength{\\topmargin}{-2.54cm}"
4092 "The document header used for processing LaTeX fragments.
4093 It is imperative that this header make sure that no page number
4094 appears on the page. The package defined in the variables
4095 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4096 will either replace the placeholder \"[PACKAGES]\" in this
4097 header, or they will be appended."
4098 :group 'org-latex
4099 :type 'string)
4101 (defun org-set-packages-alist (var val)
4102 "Set the packages alist and make sure it has 3 elements per entry."
4103 (set var (mapcar (lambda (x)
4104 (if (and (consp x) (= (length x) 2))
4105 (list (car x) (nth 1 x) t)
4107 val)))
4109 (defun org-get-packages-alist (var)
4110 "Get the packages alist and make sure it has 3 elements per entry."
4111 (mapcar (lambda (x)
4112 (if (and (consp x) (= (length x) 2))
4113 (list (car x) (nth 1 x) t)
4115 (default-value var)))
4117 (defcustom org-latex-default-packages-alist
4118 '(("AUTO" "inputenc" t ("pdflatex"))
4119 ("T1" "fontenc" t ("pdflatex"))
4120 ("" "graphicx" t)
4121 ("" "grffile" t)
4122 ("" "longtable" nil)
4123 ("" "wrapfig" nil)
4124 ("" "rotating" nil)
4125 ("normalem" "ulem" t)
4126 ("" "amsmath" t)
4127 ("" "textcomp" t)
4128 ("" "amssymb" t)
4129 ("" "capt-of" nil)
4130 ("" "hyperref" nil))
4131 "Alist of default packages to be inserted in the header.
4133 Change this only if one of the packages here causes an
4134 incompatibility with another package you are using.
4136 The packages in this list are needed by one part or another of
4137 Org mode to function properly:
4139 - inputenc, fontenc: for basic font and character selection
4140 - graphicx: for including images
4141 - grffile: allow periods and spaces in graphics file names
4142 - longtable: For multipage tables
4143 - wrapfig: for figure placement
4144 - rotating: for sideways figures and tables
4145 - ulem: for underline and strike-through
4146 - amsmath: for subscript and superscript and math environments
4147 - textcomp, amssymb: for various symbols used
4148 for interpreting the entities in `org-entities'. You can skip
4149 some of these packages if you don't use any of their symbols.
4150 - capt-of: for captions outside of floats
4151 - hyperref: for cross references
4153 Therefore you should not modify this variable unless you know
4154 what you are doing. The one reason to change it anyway is that
4155 you might be loading some other package that conflicts with one
4156 of the default packages. Each element is either a cell or
4157 a string.
4159 A cell is of the format
4161 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4163 If SNIPPET-FLAG is non-nil, the package also needs to be included
4164 when compiling LaTeX snippets into images for inclusion into
4165 non-LaTeX output. COMPILERS is a list of compilers that should
4166 include the package, see `org-latex-compiler'. If the document
4167 compiler is not in the list, and the list is non-nil, the package
4168 will not be inserted in the final document.
4170 A string will be inserted as-is in the header of the document."
4171 :group 'org-latex
4172 :group 'org-export-latex
4173 :set 'org-set-packages-alist
4174 :get 'org-get-packages-alist
4175 :version "26.1"
4176 :package-version '(Org . "8.3")
4177 :type '(repeat
4178 (choice
4179 (list :tag "options/package pair"
4180 (string :tag "options")
4181 (string :tag "package")
4182 (boolean :tag "Snippet"))
4183 (string :tag "A line of LaTeX"))))
4185 (defcustom org-latex-packages-alist nil
4186 "Alist of packages to be inserted in every LaTeX header.
4188 These will be inserted after `org-latex-default-packages-alist'.
4189 Each element is either a cell or a string.
4191 A cell is of the format:
4193 (\"options\" \"package\" SNIPPET-FLAG)
4195 SNIPPET-FLAG, when non-nil, indicates that this package is also
4196 needed when turning LaTeX snippets into images for inclusion into
4197 non-LaTeX output.
4199 A string will be inserted as-is in the header of the document.
4201 Make sure that you only list packages here which:
4203 - you want in every file;
4204 - do not conflict with the setup in `org-format-latex-header';
4205 - do not conflict with the default packages in
4206 `org-latex-default-packages-alist'."
4207 :group 'org-latex
4208 :group 'org-export-latex
4209 :set 'org-set-packages-alist
4210 :get 'org-get-packages-alist
4211 :type '(repeat
4212 (choice
4213 (list :tag "options/package pair"
4214 (string :tag "options")
4215 (string :tag "package")
4216 (boolean :tag "Snippet"))
4217 (string :tag "A line of LaTeX"))))
4219 (defgroup org-appearance nil
4220 "Settings for Org mode appearance."
4221 :tag "Org Appearance"
4222 :group 'org)
4224 (defcustom org-level-color-stars-only nil
4225 "Non-nil means fontify only the stars in each headline.
4226 When nil, the entire headline is fontified.
4227 Changing it requires restart of `font-lock-mode' to become effective
4228 also in regions already fontified."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-hide-leading-stars nil
4233 "Non-nil means hide the first N-1 stars in a headline.
4234 This works by using the face `org-hide' for these stars. This
4235 face is white for a light background, and black for a dark
4236 background. You may have to customize the face `org-hide' to
4237 make this work.
4238 Changing it requires restart of `font-lock-mode' to become effective
4239 also in regions already fontified.
4240 You may also set this on a per-file basis by adding one of the following
4241 lines to the buffer:
4243 #+STARTUP: hidestars
4244 #+STARTUP: showstars"
4245 :group 'org-appearance
4246 :type 'boolean)
4248 (defcustom org-hidden-keywords nil
4249 "List of symbols corresponding to keywords to be hidden the org buffer.
4250 For example, a value \\='(title) for this list will make the document's title
4251 appear in the buffer without the initial #+TITLE: keyword."
4252 :group 'org-appearance
4253 :version "24.1"
4254 :type '(set (const :tag "#+AUTHOR" author)
4255 (const :tag "#+DATE" date)
4256 (const :tag "#+EMAIL" email)
4257 (const :tag "#+TITLE" title)))
4259 (defcustom org-custom-properties nil
4260 "List of properties (as strings) with a special meaning.
4261 The default use of these custom properties is to let the user
4262 hide them with `org-toggle-custom-properties-visibility'."
4263 :group 'org-properties
4264 :group 'org-appearance
4265 :version "24.3"
4266 :type '(repeat (string :tag "Property Name")))
4268 (defcustom org-fontify-done-headline nil
4269 "Non-nil means change the face of a headline if it is marked DONE.
4270 Normally, only the TODO/DONE keyword indicates the state of a headline.
4271 When this is non-nil, the headline after the keyword is set to the
4272 `org-headline-done' as an additional indication."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-fontify-emphasized-text t
4277 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4278 Changing this variable requires a restart of Emacs to take effect."
4279 :group 'org-appearance
4280 :type 'boolean)
4282 (defcustom org-fontify-whole-heading-line nil
4283 "Non-nil means fontify the whole line for headings.
4284 This is useful when setting a background color for the
4285 org-level-* faces."
4286 :group 'org-appearance
4287 :type 'boolean)
4289 (defcustom org-highlight-latex-and-related nil
4290 "Non-nil means highlight LaTeX related syntax in the buffer.
4291 When non nil, the value should be a list containing any of the
4292 following symbols:
4293 `latex' Highlight LaTeX snippets and environments.
4294 `script' Highlight subscript and superscript.
4295 `entities' Highlight entities."
4296 :group 'org-appearance
4297 :version "24.4"
4298 :package-version '(Org . "8.0")
4299 :type '(choice
4300 (const :tag "No highlighting" nil)
4301 (set :greedy t :tag "Highlight"
4302 (const :tag "LaTeX snippets and environments" latex)
4303 (const :tag "Subscript and superscript" script)
4304 (const :tag "Entities" entities))))
4306 (defcustom org-hide-emphasis-markers nil
4307 "Non-nil mean font-lock should hide the emphasis marker characters."
4308 :group 'org-appearance
4309 :type 'boolean)
4311 (defcustom org-hide-macro-markers nil
4312 "Non-nil mean font-lock should hide the brackets marking macro calls."
4313 :group 'org-appearance
4314 :type 'boolean)
4316 (defcustom org-pretty-entities nil
4317 "Non-nil means show entities as UTF8 characters.
4318 When nil, the \\name form remains in the buffer."
4319 :group 'org-appearance
4320 :version "24.1"
4321 :type 'boolean)
4323 (defcustom org-pretty-entities-include-sub-superscripts t
4324 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4325 :group 'org-appearance
4326 :version "24.1"
4327 :type 'boolean)
4329 (defvar org-emph-re nil
4330 "Regular expression for matching emphasis.
4331 After a match, the match groups contain these elements:
4332 0 The match of the full regular expression, including the characters
4333 before and after the proper match
4334 1 The character before the proper match, or empty at beginning of line
4335 2 The proper match, including the leading and trailing markers
4336 3 The leading marker like * or /, indicating the type of highlighting
4337 4 The text between the emphasis markers, not including the markers
4338 5 The character after the match, empty at the end of a line")
4340 (defvar org-verbatim-re nil
4341 "Regular expression for matching verbatim text.")
4343 (defvar org-emphasis-regexp-components) ; defined just below
4344 (defvar org-emphasis-alist) ; defined just below
4345 (defun org-set-emph-re (var val)
4346 "Set variable and compute the emphasis regular expression."
4347 (set var val)
4348 (when (and (boundp 'org-emphasis-alist)
4349 (boundp 'org-emphasis-regexp-components)
4350 org-emphasis-alist org-emphasis-regexp-components)
4351 (pcase-let*
4352 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4353 (body (if (<= nl 0) body
4354 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4355 (template
4356 (format (concat "\\([%s]\\|^\\)" ;before markers
4357 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4358 "\\([%s]\\|$\\)") ;after markers
4359 pre border border body border post)))
4360 (setq org-emph-re (format template "*/_+"))
4361 (setq org-verbatim-re (format template "=~")))))
4363 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4364 ;; set this option proved cumbersome. See this message/thread:
4365 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4366 (defvar org-emphasis-regexp-components
4367 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4368 "Components used to build the regular expression for emphasis.
4369 This is a list with five entries. Terminology: In an emphasis string
4370 like \" *strong word* \", we call the initial space PREMATCH, the final
4371 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4372 and \"trong wor\" is the body. The different components in this variable
4373 specify what is allowed/forbidden in each part:
4375 pre Chars allowed as prematch. Beginning of line will be allowed too.
4376 post Chars allowed as postmatch. End of line will be allowed too.
4377 border The chars *forbidden* as border characters.
4378 body-regexp A regexp like \".\" to match a body character. Don't use
4379 non-shy groups here, and don't allow newline here.
4380 newline The maximum number of newlines allowed in an emphasis exp.
4382 You need to reload Org or to restart Emacs after customizing this.")
4384 (defcustom org-emphasis-alist
4385 '(("*" bold)
4386 ("/" italic)
4387 ("_" underline)
4388 ("=" org-verbatim verbatim)
4389 ("~" org-code verbatim)
4390 ("+" (:strike-through t)))
4391 "Alist of characters and faces to emphasize text.
4392 Text starting and ending with a special character will be emphasized,
4393 for example *bold*, _underlined_ and /italic/. This variable sets the
4394 marker characters and the face to be used by font-lock for highlighting
4395 in Org buffers.
4397 You need to reload Org or to restart Emacs after customizing this."
4398 :group 'org-appearance
4399 :set 'org-set-emph-re
4400 :version "24.4"
4401 :package-version '(Org . "8.0")
4402 :type '(repeat
4403 (list
4404 (string :tag "Marker character")
4405 (choice
4406 (face :tag "Font-lock-face")
4407 (plist :tag "Face property list"))
4408 (option (const verbatim)))))
4410 (defvar org-protecting-blocks '("src" "example" "export")
4411 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4412 This is needed for font-lock setup.")
4414 ;;; Functions and variables from their packages
4415 ;; Declared here to avoid compiler warnings
4416 (defvar mark-active)
4418 ;; Various packages
4419 (declare-function calc-eval "calc" (str &optional separator &rest args))
4420 (declare-function calendar-forward-day "cal-move" (arg))
4421 (declare-function calendar-goto-date "cal-move" (date))
4422 (declare-function calendar-goto-today "cal-move" ())
4423 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4424 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4425 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4426 (declare-function cdlatex-tab "ext:cdlatex" ())
4427 (declare-function dired-get-filename
4428 "dired"
4429 (&optional localp no-error-if-not-filep))
4430 (declare-function iswitchb-read-buffer
4431 "iswitchb"
4432 (prompt &optional
4433 default require-match _predicate start matches-set))
4434 (declare-function org-agenda-change-all-lines
4435 "org-agenda"
4436 (newhead hdmarker &optional fixface just-this))
4437 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4438 "org-agenda"
4439 (&optional end))
4440 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4441 (declare-function org-agenda-format-item
4442 "org-agenda"
4443 (extra txt &optional level category tags dotime
4444 remove-re habitp))
4445 (declare-function org-agenda-maybe-redo "org-agenda" ())
4446 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4447 (declare-function org-agenda-save-markers-for-cut-and-paste
4448 "org-agenda"
4449 (beg end))
4450 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4451 (declare-function org-agenda-skip "org-agenda" ())
4452 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4453 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4454 (declare-function org-indent-mode "org-indent" (&optional arg))
4455 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4456 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4457 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4458 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4459 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4460 (declare-function parse-time-string "parse-time" (string))
4461 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4463 (defvar align-mode-rules-list)
4464 (defvar calc-embedded-close-formula)
4465 (defvar calc-embedded-open-formula)
4466 (defvar calc-embedded-open-mode)
4467 (defvar font-lock-unfontify-region-function)
4468 (defvar iswitchb-temp-buflist)
4469 (defvar org-agenda-tags-todo-honor-ignore-options)
4470 (defvar remember-data-file)
4471 (defvar texmathp-why)
4473 ;;;###autoload
4474 (defun turn-on-orgtbl ()
4475 "Unconditionally turn on `orgtbl-mode'."
4476 (require 'org-table)
4477 (orgtbl-mode 1))
4479 (defun org-at-table-p (&optional table-type)
4480 "Non-nil if the cursor is inside an Org table.
4481 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4482 If `org-enable-table-editor' is nil, return nil unconditionally."
4483 (and
4484 org-enable-table-editor
4485 (save-excursion
4486 (beginning-of-line)
4487 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4488 (or (not (derived-mode-p 'org-mode))
4489 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4490 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4492 (defun org-at-table.el-p ()
4493 "Non-nil when point is at a table.el table."
4494 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4495 (let ((element (org-element-at-point)))
4496 (and (eq (org-element-type element) 'table)
4497 (eq (org-element-property :type element) 'table.el)))))
4499 (defun org-at-table-hline-p ()
4500 "Non-nil when point is inside a hline in a table.
4501 Assume point is already in a table. If `org-enable-table-editor'
4502 is nil, return nil unconditionally."
4503 (and org-enable-table-editor
4504 (save-excursion
4505 (beginning-of-line)
4506 (looking-at org-table-hline-regexp))))
4508 (defun org-table-map-tables (function &optional quietly)
4509 "Apply FUNCTION to the start of all tables in the buffer."
4510 (org-with-wide-buffer
4511 (goto-char (point-min))
4512 (while (re-search-forward org-table-any-line-regexp nil t)
4513 (unless quietly
4514 (message "Mapping tables: %d%%"
4515 (floor (* 100.0 (point)) (buffer-size))))
4516 (beginning-of-line 1)
4517 (when (and (looking-at org-table-line-regexp)
4518 ;; Exclude tables in src/example/verbatim/clocktable blocks
4519 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4520 (save-excursion (funcall function))
4521 (or (looking-at org-table-line-regexp)
4522 (forward-char 1)))
4523 (re-search-forward org-table-any-border-regexp nil 1)))
4524 (unless quietly (message "Mapping tables: done")))
4526 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4527 (declare-function org-clock-update-mode-line "org-clock" ())
4528 (declare-function org-resolve-clocks "org-clock"
4529 (&optional also-non-dangling-p prompt last-valid))
4531 (defun org-at-TBLFM-p (&optional pos)
4532 "Non-nil when point (or POS) is in #+TBLFM line."
4533 (save-excursion
4534 (goto-char (or pos (point)))
4535 (beginning-of-line)
4536 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4537 (eq (org-element-type (org-element-at-point)) 'table))))
4539 (defvar org-clock-start-time)
4540 (defvar org-clock-marker (make-marker)
4541 "Marker recording the last clock-in.")
4542 (defvar org-clock-hd-marker (make-marker)
4543 "Marker recording the last clock-in, but the headline position.")
4544 (defvar org-clock-heading ""
4545 "The heading of the current clock entry.")
4546 (defun org-clock-is-active ()
4547 "Return the buffer where the clock is currently running.
4548 Return nil if no clock is running."
4549 (marker-buffer org-clock-marker))
4551 (defun org-check-running-clock ()
4552 "Check if the current buffer contains the running clock.
4553 If yes, offer to stop it and to save the buffer with the changes."
4554 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4555 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4556 (buffer-name))))
4557 (org-clock-out)
4558 (when (y-or-n-p "Save changed buffer?")
4559 (save-buffer))))
4561 (defun org-clocktable-try-shift (dir n)
4562 "Check if this line starts a clock table, if yes, shift the time block."
4563 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4564 (org-clocktable-shift dir n)))
4566 ;;;###autoload
4567 (defun org-clock-persistence-insinuate ()
4568 "Set up hooks for clock persistence."
4569 (require 'org-clock)
4570 (add-hook 'org-mode-hook 'org-clock-load)
4571 (add-hook 'kill-emacs-hook 'org-clock-save))
4573 (defgroup org-archive nil
4574 "Options concerning archiving in Org mode."
4575 :tag "Org Archive"
4576 :group 'org-structure)
4578 (defcustom org-archive-location "%s_archive::"
4579 "The location where subtrees should be archived.
4581 The value of this variable is a string, consisting of two parts,
4582 separated by a double-colon. The first part is a filename and
4583 the second part is a headline.
4585 When the filename is omitted, archiving happens in the same file.
4586 %s in the filename will be replaced by the current file
4587 name (without the directory part). Archiving to a different file
4588 is useful to keep archived entries from contributing to the
4589 Org Agenda.
4591 The archived entries will be filed as subtrees of the specified
4592 headline. When the headline is omitted, the subtrees are simply
4593 filed away at the end of the file, as top-level entries. Also in
4594 the heading you can use %s to represent the file name, this can be
4595 useful when using the same archive for a number of different files.
4597 Here are a few examples:
4598 \"%s_archive::\"
4599 If the current file is Projects.org, archive in file
4600 Projects.org_archive, as top-level trees. This is the default.
4602 \"::* Archived Tasks\"
4603 Archive in the current file, under the top-level headline
4604 \"* Archived Tasks\".
4606 \"~/org/archive.org::\"
4607 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4609 \"~/org/archive.org::* From %s\"
4610 Archive in file ~/org/archive.org (absolute path), under headlines
4611 \"From FILENAME\" where file name is the current file name.
4613 \"~/org/datetree.org::datetree/* Finished Tasks\"
4614 The \"datetree/\" string is special, signifying to archive
4615 items to the datetree. Items are placed in either the CLOSED
4616 date of the item, or the current date if there is no CLOSED date.
4617 The heading will be a subentry to the current date. There doesn't
4618 need to be a heading, but there always needs to be a slash after
4619 datetree. For example, to store archived items directly in the
4620 datetree, use \"~/org/datetree.org::datetree/\".
4622 \"basement::** Finished Tasks\"
4623 Archive in file ./basement (relative path), as level 3 trees
4624 below the level 2 heading \"** Finished Tasks\".
4626 You may set this option on a per-file basis by adding to the buffer a
4627 line like
4629 #+ARCHIVE: basement::** Finished Tasks
4631 You may also define it locally for a subtree by setting an ARCHIVE property
4632 in the entry. If such a property is found in an entry, or anywhere up
4633 the hierarchy, it will be used."
4634 :group 'org-archive
4635 :type 'string)
4637 (defcustom org-agenda-skip-archived-trees t
4638 "Non-nil means the agenda will skip any items located in archived trees.
4639 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4640 variable is no longer recommended, you should leave it at the value t.
4641 Instead, use the key `v' to cycle the archives-mode in the agenda."
4642 :group 'org-archive
4643 :group 'org-agenda-skip
4644 :type 'boolean)
4646 (defcustom org-columns-skip-archived-trees t
4647 "Non-nil means ignore archived trees when creating column view."
4648 :group 'org-archive
4649 :group 'org-properties
4650 :type 'boolean)
4652 (defcustom org-cycle-open-archived-trees nil
4653 "Non-nil means `org-cycle' will open archived trees.
4654 An archived tree is a tree marked with the tag ARCHIVE.
4655 When nil, archived trees will stay folded. You can still open them with
4656 normal outline commands like `show-all', but not with the cycling commands."
4657 :group 'org-archive
4658 :group 'org-cycle
4659 :type 'boolean)
4661 (defcustom org-sparse-tree-open-archived-trees nil
4662 "Non-nil means sparse tree construction shows matches in archived trees.
4663 When nil, matches in these trees are highlighted, but the trees are kept in
4664 collapsed state."
4665 :group 'org-archive
4666 :group 'org-sparse-trees
4667 :type 'boolean)
4669 (defcustom org-sparse-tree-default-date-type nil
4670 "The default date type when building a sparse tree.
4671 When this is nil, a date is a scheduled or a deadline timestamp.
4672 Otherwise, these types are allowed:
4674 all: all timestamps
4675 active: only active timestamps (<...>)
4676 inactive: only inactive timestamps ([...])
4677 scheduled: only scheduled timestamps
4678 deadline: only deadline timestamps"
4679 :type '(choice (const :tag "Scheduled or deadline" nil)
4680 (const :tag "All timestamps" all)
4681 (const :tag "Only active timestamps" active)
4682 (const :tag "Only inactive timestamps" inactive)
4683 (const :tag "Only scheduled timestamps" scheduled)
4684 (const :tag "Only deadline timestamps" deadline)
4685 (const :tag "Only closed timestamps" closed))
4686 :version "26.1"
4687 :package-version '(Org . "8.3")
4688 :group 'org-sparse-trees)
4690 (defun org-cycle-hide-archived-subtrees (state)
4691 "Re-hide all archived subtrees after a visibility state change."
4692 (when (and (not org-cycle-open-archived-trees)
4693 (not (memq state '(overview folded))))
4694 (save-excursion
4695 (let* ((globalp (memq state '(contents all)))
4696 (beg (if globalp (point-min) (point)))
4697 (end (if globalp (point-max) (org-end-of-subtree t))))
4698 (org-hide-archived-subtrees beg end)
4699 (goto-char beg)
4700 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4701 (message "%s" (substitute-command-keys
4702 "Subtree is archived and stays closed. Use \
4703 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4705 (defun org-force-cycle-archived ()
4706 "Cycle subtree even if it is archived."
4707 (interactive)
4708 (setq this-command 'org-cycle)
4709 (let ((org-cycle-open-archived-trees t))
4710 (call-interactively 'org-cycle)))
4712 (defun org-hide-archived-subtrees (beg end)
4713 "Re-hide all archived subtrees after a visibility state change."
4714 (org-with-wide-buffer
4715 (let ((case-fold-search nil)
4716 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4717 (goto-char beg)
4718 ;; Include headline point is currently on.
4719 (beginning-of-line)
4720 (while (and (< (point) end) (re-search-forward re end t))
4721 (when (member org-archive-tag (org-get-tags))
4722 (org-flag-subtree t)
4723 (org-end-of-subtree t))))))
4725 (declare-function outline-end-of-heading "outline" ())
4726 (declare-function outline-flag-region "outline" (from to flag))
4727 (defun org-flag-subtree (flag)
4728 (save-excursion
4729 (org-back-to-heading t)
4730 (outline-end-of-heading)
4731 (outline-flag-region (point)
4732 (progn (org-end-of-subtree t) (point))
4733 flag)))
4735 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4737 ;; Declare Column View Code
4739 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4740 (declare-function org-columns-compute "org-colview" (property))
4742 ;; Declare ID code
4744 (declare-function org-id-store-link "org-id")
4745 (declare-function org-id-locations-load "org-id")
4746 (declare-function org-id-locations-save "org-id")
4747 (defvar org-id-track-globally)
4749 ;;; Variables for pre-computed regular expressions, all buffer local
4751 (defvar-local org-todo-regexp nil
4752 "Matches any of the TODO state keywords.
4753 Since TODO keywords are case-sensitive, `case-fold-search' is
4754 expected to be bound to nil when matching against this regexp.")
4756 (defvar-local org-not-done-regexp nil
4757 "Matches any of the TODO state keywords except the last one.
4758 Since TODO keywords are case-sensitive, `case-fold-search' is
4759 expected to be bound to nil when matching against this regexp.")
4761 (defvar-local org-not-done-heading-regexp nil
4762 "Matches a TODO headline that is not done.
4763 Since TODO keywords are case-sensitive, `case-fold-search' is
4764 expected to be bound to nil when matching against this regexp.")
4766 (defvar-local org-todo-line-regexp nil
4767 "Matches a headline and puts TODO state into group 2 if present.
4768 Since TODO keywords are case-sensitive, `case-fold-search' is
4769 expected to be bound to nil when matching against this regexp.")
4771 (defvar-local org-complex-heading-regexp nil
4772 "Matches a headline and puts everything into groups:
4774 group 1: Stars
4775 group 2: The TODO keyword, maybe
4776 group 3: Priority cookie
4777 group 4: True headline
4778 group 5: Tags
4780 Since TODO keywords are case-sensitive, `case-fold-search' is
4781 expected to be bound to nil when matching against this regexp.")
4783 (defvar-local org-complex-heading-regexp-format nil
4784 "Printf format to make regexp to match an exact headline.
4785 This regexp will match the headline of any node which has the
4786 exact headline text that is put into the format, but may have any
4787 TODO state, priority and tags.")
4789 (defvar-local org-todo-line-tags-regexp nil
4790 "Matches a headline and puts TODO state into group 2 if present.
4791 Also put tags into group 4 if tags are present.")
4793 (defconst org-plain-time-of-day-regexp
4794 (concat
4795 "\\(\\<[012]?[0-9]"
4796 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4797 "\\(--?"
4798 "\\(\\<[012]?[0-9]"
4799 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4800 "\\)?")
4801 "Regular expression to match a plain time or time range.
4802 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4803 groups carry important information:
4804 0 the full match
4805 1 the first time, range or not
4806 8 the second time, if it is a range.")
4808 (defconst org-plain-time-extension-regexp
4809 (concat
4810 "\\(\\<[012]?[0-9]"
4811 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4812 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4813 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4814 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4815 groups carry important information:
4816 0 the full match
4817 7 hours of duration
4818 9 minutes of duration")
4820 (defconst org-stamp-time-of-day-regexp
4821 (concat
4822 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4823 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4824 "\\(--?"
4825 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4826 "Regular expression to match a timestamp time or time range.
4827 After a match, the following groups carry important information:
4828 0 the full match
4829 1 date plus weekday, for back referencing to make sure both times are on the same day
4830 2 the first time, range or not
4831 4 the second time, if it is a range.")
4833 (defconst org-startup-options
4834 '(("fold" org-startup-folded t)
4835 ("overview" org-startup-folded t)
4836 ("nofold" org-startup-folded nil)
4837 ("showall" org-startup-folded nil)
4838 ("showeverything" org-startup-folded showeverything)
4839 ("content" org-startup-folded content)
4840 ("indent" org-startup-indented t)
4841 ("noindent" org-startup-indented nil)
4842 ("hidestars" org-hide-leading-stars t)
4843 ("showstars" org-hide-leading-stars nil)
4844 ("odd" org-odd-levels-only t)
4845 ("oddeven" org-odd-levels-only nil)
4846 ("align" org-startup-align-all-tables t)
4847 ("noalign" org-startup-align-all-tables nil)
4848 ("inlineimages" org-startup-with-inline-images t)
4849 ("noinlineimages" org-startup-with-inline-images nil)
4850 ("latexpreview" org-startup-with-latex-preview t)
4851 ("nolatexpreview" org-startup-with-latex-preview nil)
4852 ("customtime" org-display-custom-times t)
4853 ("logdone" org-log-done time)
4854 ("lognotedone" org-log-done note)
4855 ("nologdone" org-log-done nil)
4856 ("lognoteclock-out" org-log-note-clock-out t)
4857 ("nolognoteclock-out" org-log-note-clock-out nil)
4858 ("logrepeat" org-log-repeat state)
4859 ("lognoterepeat" org-log-repeat note)
4860 ("logdrawer" org-log-into-drawer t)
4861 ("nologdrawer" org-log-into-drawer nil)
4862 ("logstatesreversed" org-log-states-order-reversed t)
4863 ("nologstatesreversed" org-log-states-order-reversed nil)
4864 ("nologrepeat" org-log-repeat nil)
4865 ("logreschedule" org-log-reschedule time)
4866 ("lognotereschedule" org-log-reschedule note)
4867 ("nologreschedule" org-log-reschedule nil)
4868 ("logredeadline" org-log-redeadline time)
4869 ("lognoteredeadline" org-log-redeadline note)
4870 ("nologredeadline" org-log-redeadline nil)
4871 ("logrefile" org-log-refile time)
4872 ("lognoterefile" org-log-refile note)
4873 ("nologrefile" org-log-refile nil)
4874 ("fninline" org-footnote-define-inline t)
4875 ("nofninline" org-footnote-define-inline nil)
4876 ("fnlocal" org-footnote-section nil)
4877 ("fnauto" org-footnote-auto-label t)
4878 ("fnprompt" org-footnote-auto-label nil)
4879 ("fnconfirm" org-footnote-auto-label confirm)
4880 ("fnplain" org-footnote-auto-label plain)
4881 ("fnadjust" org-footnote-auto-adjust t)
4882 ("nofnadjust" org-footnote-auto-adjust nil)
4883 ("constcgs" constants-unit-system cgs)
4884 ("constSI" constants-unit-system SI)
4885 ("noptag" org-tag-persistent-alist nil)
4886 ("hideblocks" org-hide-block-startup t)
4887 ("nohideblocks" org-hide-block-startup nil)
4888 ("beamer" org-startup-with-beamer-mode t)
4889 ("entitiespretty" org-pretty-entities t)
4890 ("entitiesplain" org-pretty-entities nil))
4891 "Variable associated with STARTUP options for org-mode.
4892 Each element is a list of three items: the startup options (as written
4893 in the #+STARTUP line), the corresponding variable, and the value to set
4894 this variable to if the option is found. An optional forth element PUSH
4895 means to push this value onto the list in the variable.")
4897 (defcustom org-group-tags t
4898 "When non-nil (the default), use group tags.
4899 This can be turned on/off through `org-toggle-tags-groups'."
4900 :group 'org-tags
4901 :group 'org-startup
4902 :type 'boolean)
4904 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4906 (defun org-toggle-tags-groups ()
4907 "Toggle support for group tags.
4908 Support for group tags is controlled by the option
4909 `org-group-tags', which is non-nil by default."
4910 (interactive)
4911 (setq org-group-tags (not org-group-tags))
4912 (cond ((and (derived-mode-p 'org-agenda-mode)
4913 org-group-tags)
4914 (org-agenda-redo))
4915 ((derived-mode-p 'org-mode)
4916 (let ((org-inhibit-startup t)) (org-mode))))
4917 (message "Groups tags support has been turned %s"
4918 (if org-group-tags "on" "off")))
4920 (defun org-set-regexps-and-options (&optional tags-only)
4921 "Precompute regular expressions used in the current buffer.
4922 When optional argument TAGS-ONLY is non-nil, only compute tags
4923 related expressions."
4924 (when (derived-mode-p 'org-mode)
4925 (let ((alist (org--setup-collect-keywords
4926 (org-make-options-regexp
4927 (append '("FILETAGS" "TAGS" "SETUPFILE")
4928 (and (not tags-only)
4929 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4930 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4931 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4932 ;; Startup options. Get this early since it does change
4933 ;; behavior for other options (e.g., tags).
4934 (let ((startup (cdr (assq 'startup alist))))
4935 (dolist (option startup)
4936 (let ((entry (assoc-string option org-startup-options t)))
4937 (when entry
4938 (let ((var (nth 1 entry))
4939 (val (nth 2 entry)))
4940 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4941 (unless (listp (symbol-value var))
4942 (set (make-local-variable var) nil))
4943 (add-to-list var val)))))))
4944 (setq-local org-file-tags
4945 (mapcar #'org-add-prop-inherited
4946 (cdr (assq 'filetags alist))))
4947 (setq org-current-tag-alist
4948 (append org-tag-persistent-alist
4949 (let ((tags (cdr (assq 'tags alist))))
4950 (if tags (org-tag-string-to-alist tags)
4951 org-tag-alist))))
4952 (setq org-tag-groups-alist
4953 (org-tag-alist-to-groups org-current-tag-alist))
4954 (unless tags-only
4955 ;; File properties.
4956 (setq-local org-file-properties (cdr (assq 'property alist)))
4957 ;; Archive location.
4958 (let ((archive (cdr (assq 'archive alist))))
4959 (when archive (setq-local org-archive-location archive)))
4960 ;; Category.
4961 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4962 (when cat
4963 (setq-local org-category (intern cat))
4964 (setq-local org-file-properties
4965 (org--update-property-plist
4966 "CATEGORY" cat org-file-properties))))
4967 ;; Columns.
4968 (let ((column (cdr (assq 'columns alist))))
4969 (when column (setq-local org-columns-default-format column)))
4970 ;; Constants.
4971 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4972 ;; Link abbreviations.
4973 (let ((links (cdr (assq 'link alist))))
4974 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4975 ;; Priorities.
4976 (let ((priorities (cdr (assq 'priorities alist))))
4977 (when priorities
4978 (setq-local org-highest-priority (nth 0 priorities))
4979 (setq-local org-lowest-priority (nth 1 priorities))
4980 (setq-local org-default-priority (nth 2 priorities))))
4981 ;; Scripts.
4982 (let ((scripts (assq 'scripts alist)))
4983 (when scripts
4984 (setq-local org-use-sub-superscripts (cdr scripts))))
4985 ;; TODO keywords.
4986 (setq-local org-todo-kwd-alist nil)
4987 (setq-local org-todo-key-alist nil)
4988 (setq-local org-todo-key-trigger nil)
4989 (setq-local org-todo-keywords-1 nil)
4990 (setq-local org-done-keywords nil)
4991 (setq-local org-todo-heads nil)
4992 (setq-local org-todo-sets nil)
4993 (setq-local org-todo-log-states nil)
4994 (let ((todo-sequences
4995 (or (nreverse (cdr (assq 'todo alist)))
4996 (let ((d (default-value 'org-todo-keywords)))
4997 (if (not (stringp (car d))) d
4998 ;; XXX: Backward compatibility code.
4999 (list (cons org-todo-interpretation d)))))))
5000 (dolist (sequence todo-sequences)
5001 (let* ((sequence (or (run-hook-with-args-until-success
5002 'org-todo-setup-filter-hook sequence)
5003 sequence))
5004 (sequence-type (car sequence))
5005 (keywords (cdr sequence))
5006 (sep (member "|" keywords))
5007 names alist)
5008 (dolist (k (remove "|" keywords))
5009 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5011 (error "Invalid TODO keyword %s" k))
5012 (let ((name (match-string 1 k))
5013 (key (match-string 2 k))
5014 (log (org-extract-log-state-settings k)))
5015 (push name names)
5016 (push (cons name (and key (string-to-char key))) alist)
5017 (when log (push log org-todo-log-states))))
5018 (let* ((names (nreverse names))
5019 (done (if sep (org-remove-keyword-keys (cdr sep))
5020 (last names)))
5021 (head (car names))
5022 (tail (list sequence-type head (car done) (org-last done))))
5023 (add-to-list 'org-todo-heads head 'append)
5024 (push names org-todo-sets)
5025 (setq org-done-keywords (append org-done-keywords done nil))
5026 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5027 (setq org-todo-key-alist
5028 (append org-todo-key-alist
5029 (and alist
5030 (append '((:startgroup))
5031 (nreverse alist)
5032 '((:endgroup))))))
5033 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5034 (setq org-todo-sets (nreverse org-todo-sets)
5035 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5036 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5037 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5038 ;; Compute the regular expressions and other local variables.
5039 ;; Using `org-outline-regexp-bol' would complicate them much,
5040 ;; because of the fixed white space at the end of that string.
5041 (unless org-done-keywords
5042 (setq org-done-keywords
5043 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5044 (setq org-not-done-keywords
5045 (org-delete-all org-done-keywords
5046 (copy-sequence org-todo-keywords-1))
5047 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5048 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5049 org-not-done-heading-regexp
5050 (format org-heading-keyword-regexp-format org-not-done-regexp)
5051 org-todo-line-regexp
5052 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5053 org-complex-heading-regexp
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(\\[#.\\]\\)\\)?"
5057 "\\(?: +\\(.*?\\)\\)??"
5058 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5059 "[ \t]*$")
5060 org-complex-heading-regexp-format
5061 (concat "^\\(\\*+\\)"
5062 "\\(?: +" org-todo-regexp "\\)?"
5063 "\\(?: +\\(\\[#.\\]\\)\\)?"
5064 "\\(?: +"
5065 ;; Stats cookies can be stuck to body.
5066 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5067 "\\(%s\\)"
5068 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5069 "\\)"
5070 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5071 "[ \t]*$")
5072 org-todo-line-tags-regexp
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(.*?\\)\\)??"
5076 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5077 "[ \t]*$"))
5078 (org-compute-latex-and-related-regexp)))))
5080 (defun org--setup-collect-keywords (regexp &optional files alist)
5081 "Return setup keywords values as an alist.
5083 REGEXP matches a subset of setup keywords. FILES is a list of
5084 file names already visited. It is used to avoid circular setup
5085 files. ALIST, when non-nil, is the alist computed so far.
5087 Return value contains the following keys: `archive', `category',
5088 `columns', `constants', `filetags', `link', `priorities',
5089 `property', `scripts', `startup', `tags' and `todo'."
5090 (org-with-wide-buffer
5091 (goto-char (point-min))
5092 (let ((case-fold-search t))
5093 (while (re-search-forward regexp nil t)
5094 (let ((element (org-element-at-point)))
5095 (when (eq (org-element-type element) 'keyword)
5096 (let ((key (org-element-property :key element))
5097 (value (org-element-property :value element)))
5098 (cond
5099 ((equal key "ARCHIVE")
5100 (when (org-string-nw-p value)
5101 (push (cons 'archive value) alist)))
5102 ((equal key "CATEGORY") (push (cons 'category value) alist))
5103 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5104 ((equal key "CONSTANTS")
5105 (let* ((constants (assq 'constants alist))
5106 (store (cdr constants)))
5107 (dolist (pair (org-split-string value))
5108 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5109 pair)
5110 (let* ((name (match-string 1 pair))
5111 (value (match-string 2 pair))
5112 (old (assoc name store)))
5113 (if old (setcdr old value)
5114 (push (cons name value) store)))))
5115 (if constants (setcdr constants store)
5116 (push (cons 'constants store) alist))))
5117 ((equal key "FILETAGS")
5118 (when (org-string-nw-p value)
5119 (let ((old (assq 'filetags alist))
5120 (new (apply #'nconc
5121 (mapcar (lambda (x) (org-split-string x ":"))
5122 (org-split-string value)))))
5123 (if old (setcdr old (append new (cdr old)))
5124 (push (cons 'filetags new) alist)))))
5125 ((equal key "LINK")
5126 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5127 (let ((links (assq 'link alist))
5128 (pair (cons (match-string-no-properties 1 value)
5129 (match-string-no-properties 2 value))))
5130 (if links (push pair (cdr links))
5131 (push (list 'link pair) alist)))))
5132 ((equal key "OPTIONS")
5133 (when (and (org-string-nw-p value)
5134 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5135 (push (cons 'scripts (read (match-string 1 value))) alist)))
5136 ((equal key "PRIORITIES")
5137 (push (cons 'priorities
5138 (let ((prio (org-split-string value)))
5139 (if (< (length prio) 3) '(?A ?C ?B)
5140 (mapcar #'string-to-char prio))))
5141 alist))
5142 ((equal key "PROPERTY")
5143 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5144 (let* ((property (assq 'property alist))
5145 (value (org--update-property-plist
5146 (match-string-no-properties 1 value)
5147 (match-string-no-properties 2 value)
5148 (cdr property))))
5149 (if property (setcdr property value)
5150 (push (cons 'property value) alist)))))
5151 ((equal key "STARTUP")
5152 (let ((startup (assq 'startup alist)))
5153 (if startup
5154 (setcdr startup
5155 (append (cdr startup) (org-split-string value)))
5156 (push (cons 'startup (org-split-string value)) alist))))
5157 ((equal key "TAGS")
5158 (let ((tag-cell (assq 'tags alist)))
5159 (if tag-cell
5160 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5161 (push (cons 'tags value) alist))))
5162 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5163 (let ((todo (assq 'todo alist))
5164 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5165 (org-split-string value))))
5166 (if todo (push value (cdr todo))
5167 (push (list 'todo value) alist))))
5168 ((equal key "SETUPFILE")
5169 (unless buffer-read-only ; Do not check in Gnus messages.
5170 (let ((f (and (org-string-nw-p value)
5171 (expand-file-name
5172 (org-unbracket-string "\"" "\"" value)))))
5173 (when (and f (file-readable-p f) (not (member f files)))
5174 (with-temp-buffer
5175 (setq default-directory (file-name-directory f))
5176 (insert-file-contents f)
5177 (setq alist
5178 ;; Fake Org mode to benefit from cache
5179 ;; without recurring needlessly.
5180 (let ((major-mode 'org-mode))
5181 (org--setup-collect-keywords
5182 regexp (cons f files) alist)))))))))))))))
5183 alist)
5185 (defun org-tag-string-to-alist (s)
5186 "Return tag alist associated to string S.
5187 S is a value for TAGS keyword or produced with
5188 `org-tag-alist-to-string'. Return value is an alist suitable for
5189 `org-tag-alist' or `org-tag-persistent-alist'."
5190 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5191 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5192 "\\|{.+?}\\)" ; regular expression
5193 "\\(?:(\\(.\\))\\)?\\'"))
5194 alist group-flag)
5195 (dolist (tokens lines (cdr (nreverse alist)))
5196 (push '(:newline) alist)
5197 (while tokens
5198 (let ((token (pop tokens)))
5199 (pcase token
5200 ("{"
5201 (push '(:startgroup) alist)
5202 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5203 ("}"
5204 (push '(:endgroup) alist)
5205 (setq group-flag nil))
5206 ("["
5207 (push '(:startgrouptag) alist)
5208 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5209 ("]"
5210 (push '(:endgrouptag) alist)
5211 (setq group-flag nil))
5212 (":"
5213 (push '(:grouptags) alist))
5214 ((guard (string-match tag-re token))
5215 (let ((tag (match-string 1 token))
5216 (key (and (match-beginning 2)
5217 (string-to-char (match-string 2 token)))))
5218 ;; Push all tags in groups, no matter if they already
5219 ;; appear somewhere else in the list.
5220 (when (or group-flag (not (assoc tag alist)))
5221 (push (cons tag key) alist))))))))))
5223 (defun org-tag-alist-to-string (alist &optional skip-key)
5224 "Return tag string associated to ALIST.
5226 ALIST is an alist, as defined in `org-tag-alist' or
5227 `org-tag-persistent-alist', or produced with
5228 `org-tag-string-to-alist'.
5230 Return value is a string suitable as a value for \"TAGS\"
5231 keyword.
5233 When optional argument SKIP-KEY is non-nil, skip selection keys
5234 next to tags."
5235 (mapconcat (lambda (token)
5236 (pcase token
5237 (`(:startgroup) "{")
5238 (`(:endgroup) "}")
5239 (`(:startgrouptag) "[")
5240 (`(:endgrouptag) "]")
5241 (`(:grouptags) ":")
5242 (`(:newline) "\\n")
5243 ((and
5244 (guard (not skip-key))
5245 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5246 (format "%s(%c)" tag key))
5247 (`(,(and tag (pred stringp)) . ,_) tag)
5248 (_ (user-error "Invalid tag token: %S" token))))
5249 alist
5250 " "))
5252 (defun org-tag-alist-to-groups (alist)
5253 "Return group alist from tag ALIST.
5254 ALIST is an alist, as defined in `org-tag-alist' or
5255 `org-tag-persistent-alist', or produced with
5256 `org-tag-string-to-alist'. Return value is an alist following
5257 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5258 a string, summarizing TAGS, as a list of strings."
5259 (let (groups group-status current-group)
5260 (dolist (token alist (nreverse groups))
5261 (pcase token
5262 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5263 (`(,(or :endgroup :endgrouptag))
5264 (when (eq group-status 'append)
5265 (push (nreverse current-group) groups))
5266 (setq group-status nil))
5267 (`(:grouptags) (setq group-status 'append))
5268 ((and `(,tag . ,_) (guard group-status))
5269 (if (eq group-status 'append) (push tag current-group)
5270 (setq current-group (list tag))))
5271 (_ nil)))))
5273 (defun org-file-contents (file &optional noerror)
5274 "Return the contents of FILE, as a string."
5275 (if (and file (file-readable-p file))
5276 (with-temp-buffer
5277 (insert-file-contents file)
5278 (buffer-string))
5279 (funcall (if noerror 'message 'error)
5280 "Cannot read file \"%s\"%s"
5281 file
5282 (let ((from (buffer-file-name (buffer-base-buffer))))
5283 (if from (concat " (referenced in file \"" from "\")") "")))))
5285 (defun org-extract-log-state-settings (x)
5286 "Extract the log state setting from a TODO keyword string.
5287 This will extract info from a string like \"WAIT(w@/!)\"."
5288 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5289 (let ((kw (match-string 1 x))
5290 (log1 (and (match-end 3) (match-string 3 x)))
5291 (log2 (and (match-end 4) (match-string 4 x))))
5292 (and (or log1 log2)
5293 (list kw
5294 (and log1 (if (equal log1 "!") 'time 'note))
5295 (and log2 (if (equal log2 "!") 'time 'note)))))))
5297 (defun org-remove-keyword-keys (list)
5298 "Remove a pair of parenthesis at the end of each string in LIST."
5299 (mapcar (lambda (x)
5300 (if (string-match "(.*)$" x)
5301 (substring x 0 (match-beginning 0))
5303 list))
5305 (defun org-assign-fast-keys (alist)
5306 "Assign fast keys to a keyword-key alist.
5307 Respect keys that are already there."
5308 (let (new e (alt ?0))
5309 (while (setq e (pop alist))
5310 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5311 (cdr e)) ;; Key already assigned.
5312 (push e new)
5313 (let ((clist (string-to-list (downcase (car e))))
5314 (used (append new alist)))
5315 (when (= (car clist) ?@)
5316 (pop clist))
5317 (while (and clist (rassoc (car clist) used))
5318 (pop clist))
5319 (unless clist
5320 (while (rassoc alt used)
5321 (cl-incf alt)))
5322 (push (cons (car e) (or (car clist) alt)) new))))
5323 (nreverse new)))
5325 ;;; Some variables used in various places
5327 (defvar org-window-configuration nil
5328 "Used in various places to store a window configuration.")
5329 (defvar org-selected-window nil
5330 "Used in various places to store a window configuration.")
5331 (defvar org-finish-function nil
5332 "Function to be called when `C-c C-c' is used.
5333 This is for getting out of special buffers like capture.")
5334 (defvar org-last-state)
5336 ;; Defined somewhere in this file, but used before definition.
5337 (defvar org-entities) ;; defined in org-entities.el
5338 (defvar org-struct-menu)
5339 (defvar org-org-menu)
5340 (defvar org-tbl-menu)
5342 ;;;; Define the Org mode
5344 ;; We use a before-change function to check if a table might need
5345 ;; an update.
5346 (defvar org-table-may-need-update t
5347 "Indicates that a table might need an update.
5348 This variable is set by `org-before-change-function'.
5349 `org-table-align' sets it back to nil.")
5350 (defun org-before-change-function (_beg _end)
5351 "Every change indicates that a table might need an update."
5352 (setq org-table-may-need-update t))
5353 (defvar org-mode-map)
5354 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5355 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5356 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5357 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5358 (defvar org-table-buffer-is-an nil)
5360 (defvar bidi-paragraph-direction)
5361 (defvar buffer-face-mode-face)
5363 (require 'outline)
5365 ;; Other stuff we need.
5366 (require 'time-date)
5367 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5368 (require 'easymenu)
5369 (autoload 'easy-menu-add "easymenu")
5370 (require 'overlay)
5372 ;; (require 'org-macs) moved higher up in the file before it is first used
5373 (require 'org-entities)
5374 ;; (require 'org-compat) moved higher up in the file before it is first used
5375 (require 'org-faces)
5376 (require 'org-list)
5377 (require 'org-pcomplete)
5378 (require 'org-src)
5379 (require 'org-footnote)
5380 (require 'org-macro)
5382 ;; babel
5383 (require 'ob)
5385 ;;;###autoload
5386 (define-derived-mode org-mode outline-mode "Org"
5387 "Outline-based notes management and organizer, alias
5388 \"Carsten's outline-mode for keeping track of everything.\"
5390 Org mode develops organizational tasks around a NOTES file which
5391 contains information about projects as plain text. Org mode is
5392 implemented on top of Outline mode, which is ideal to keep the content
5393 of large files well structured. It supports ToDo items, deadlines and
5394 time stamps, which magically appear in the diary listing of the Emacs
5395 calendar. Tables are easily created with a built-in table editor.
5396 Plain text URL-like links connect to websites, emails (VM), Usenet
5397 messages (Gnus), BBDB entries, and any files related to the project.
5398 For printing and sharing of notes, an Org file (or a part of it)
5399 can be exported as a structured ASCII or HTML file.
5401 The following commands are available:
5403 \\{org-mode-map}"
5405 ;; Get rid of Outline menus, they are not needed
5406 ;; Need to do this here because define-derived-mode sets up
5407 ;; the keymap so late. Still, it is a waste to call this each time
5408 ;; we switch another buffer into Org mode.
5409 (define-key org-mode-map [menu-bar headings] 'undefined)
5410 (define-key org-mode-map [menu-bar hide] 'undefined)
5411 (define-key org-mode-map [menu-bar show] 'undefined)
5413 (org-load-modules-maybe)
5414 (org-install-agenda-files-menu)
5415 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5416 (add-to-invisibility-spec '(org-cwidth))
5417 (add-to-invisibility-spec '(org-hide-block . t))
5418 (setq-local outline-regexp org-outline-regexp)
5419 (setq-local outline-level 'org-outline-level)
5420 (setq bidi-paragraph-direction 'left-to-right)
5421 (when (and org-ellipsis
5422 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5423 (fboundp 'make-glyph-code))
5424 (unless org-display-table
5425 (setq org-display-table (make-display-table)))
5426 (set-display-table-slot
5427 org-display-table 4
5428 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5429 (if (stringp org-ellipsis) org-ellipsis "..."))))
5430 (setq buffer-display-table org-display-table))
5431 (org-set-regexps-and-options)
5432 (org-set-font-lock-defaults)
5433 (when (and org-tag-faces (not org-tags-special-faces-re))
5434 ;; tag faces set outside customize.... force initialization.
5435 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5436 ;; Calc embedded
5437 (setq-local calc-embedded-open-mode "# ")
5438 ;; Modify a few syntax entries
5439 (modify-syntax-entry ?@ "w")
5440 (modify-syntax-entry ?\" "\"")
5441 (modify-syntax-entry ?\\ "_")
5442 (modify-syntax-entry ?~ "_")
5443 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5444 ;; Activate before-change-function
5445 (setq-local org-table-may-need-update t)
5446 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5447 ;; Check for running clock before killing a buffer
5448 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5449 ;; Initialize macros templates.
5450 (org-macro-initialize-templates)
5451 ;; Initialize radio targets.
5452 (org-update-radio-target-regexp)
5453 ;; Indentation.
5454 (setq-local indent-line-function 'org-indent-line)
5455 (setq-local indent-region-function 'org-indent-region)
5456 ;; Filling and auto-filling.
5457 (org-setup-filling)
5458 ;; Comments.
5459 (org-setup-comments-handling)
5460 ;; Initialize cache.
5461 (org-element-cache-reset)
5462 ;; Beginning/end of defun
5463 (setq-local beginning-of-defun-function 'org-backward-element)
5464 (setq-local end-of-defun-function
5465 (lambda ()
5466 (if (not (org-at-heading-p))
5467 (org-forward-element)
5468 (org-forward-element)
5469 (forward-char -1))))
5470 ;; Next error for sparse trees
5471 (setq-local next-error-function 'org-occur-next-match)
5472 ;; Make sure dependence stuff works reliably, even for users who set it
5473 ;; too late :-(
5474 (if org-enforce-todo-dependencies
5475 (add-hook 'org-blocker-hook
5476 'org-block-todo-from-children-or-siblings-or-parent)
5477 (remove-hook 'org-blocker-hook
5478 'org-block-todo-from-children-or-siblings-or-parent))
5479 (if org-enforce-todo-checkbox-dependencies
5480 (add-hook 'org-blocker-hook
5481 'org-block-todo-from-checkboxes)
5482 (remove-hook 'org-blocker-hook
5483 'org-block-todo-from-checkboxes))
5485 ;; Align options lines
5486 (setq-local
5487 align-mode-rules-list
5488 '((org-in-buffer-settings
5489 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5490 (modes . '(org-mode)))))
5492 ;; Imenu
5493 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5495 ;; Make isearch reveal context
5496 (setq-local outline-isearch-open-invisible-function
5497 (lambda (&rest _) (org-show-context 'isearch)))
5499 ;; Setup the pcomplete hooks
5500 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5501 (setq-local pcomplete-command-name-function 'org-command-at-point)
5502 (setq-local pcomplete-default-completion-function 'ignore)
5503 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5504 (setq-local pcomplete-termination-string "")
5505 (setq-local buffer-face-mode-face 'org-default)
5507 ;; If empty file that did not turn on Org mode automatically, make
5508 ;; it to.
5509 (when (and org-insert-mode-line-in-empty-file
5510 (called-interactively-p 'any)
5511 (= (point-min) (point-max)))
5512 (insert "# -*- mode: org -*-\n\n"))
5513 (unless org-inhibit-startup
5514 (org-unmodified
5515 (when org-startup-with-beamer-mode (org-beamer-mode))
5516 (when org-startup-align-all-tables
5517 (org-table-map-tables #'org-table-align t))
5518 (when org-startup-with-inline-images (org-display-inline-images))
5519 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5520 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5521 (when org-startup-truncated (setq truncate-lines t))
5522 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5523 (org-refresh-effort-properties)))
5524 ;; Try to set `org-hide' face correctly.
5525 (let ((foreground (org-find-invisible-foreground)))
5526 (when foreground
5527 (set-face-foreground 'org-hide foreground))))
5529 ;; Update `customize-package-emacs-version-alist'
5530 (add-to-list 'customize-package-emacs-version-alist
5531 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5532 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5533 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5534 ("9.0" . "26.1")))
5536 (defvar org-mode-transpose-word-syntax-table
5537 (let ((st (make-syntax-table text-mode-syntax-table)))
5538 (dolist (c org-emphasis-alist st)
5539 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5541 (when (fboundp 'abbrev-table-put)
5542 (abbrev-table-put org-mode-abbrev-table
5543 :parents (list text-mode-abbrev-table)))
5545 (defun org-find-invisible-foreground ()
5546 (let ((candidates (remove
5547 "unspecified-bg"
5548 (nconc
5549 (list (face-background 'default)
5550 (face-background 'org-default))
5551 (mapcar
5552 (lambda (alist)
5553 (when (boundp alist)
5554 (cdr (assq 'background-color (symbol-value alist)))))
5555 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5556 (list (face-foreground 'org-hide))))))
5557 (car (remove nil candidates))))
5559 (defun org-current-time (&optional rounding-minutes past)
5560 "Current time, possibly rounded to ROUNDING-MINUTES.
5561 When ROUNDING-MINUTES is not an integer, fall back on the car of
5562 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5563 the rounding returns a past time."
5564 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5565 (car org-time-stamp-rounding-minutes)))
5566 (time (decode-time)) res)
5567 (if (< r 1)
5568 (current-time)
5569 (setq res
5570 (apply 'encode-time
5571 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5572 (nthcdr 2 time))))
5573 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5574 (seconds-to-time (- (float-time res) (* r 60)))
5575 res))))
5577 (defun org-today ()
5578 "Return today date, considering `org-extend-today-until'."
5579 (time-to-days
5580 (time-subtract (current-time)
5581 (list 0 (* 3600 org-extend-today-until) 0))))
5583 ;;;; Font-Lock stuff, including the activators
5585 (defvar org-mouse-map (make-sparse-keymap))
5586 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5587 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5588 (when org-mouse-1-follows-link
5589 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5590 (when org-tab-follows-link
5591 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5592 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5594 (require 'font-lock)
5596 (defconst org-non-link-chars "]\t\n\r<>")
5597 (defvar org-link-types-re nil
5598 "Matches a link that has a url-like prefix like \"http:\"")
5599 (defvar org-link-re-with-space nil
5600 "Matches a link with spaces, optional angular brackets around it.")
5601 (defvar org-link-re-with-space2 nil
5602 "Matches a link with spaces, optional angular brackets around it.")
5603 (defvar org-link-re-with-space3 nil
5604 "Matches a link with spaces, only for internal part in bracket links.")
5605 (defvar org-angle-link-re nil
5606 "Matches link with angular brackets, spaces are allowed.")
5607 (defvar org-plain-link-re nil
5608 "Matches plain link, without spaces.")
5609 (defvar org-bracket-link-regexp nil
5610 "Matches a link in double brackets.")
5611 (defvar org-bracket-link-analytic-regexp nil
5612 "Regular expression used to analyze links.
5613 Here is what the match groups contain after a match:
5614 1: http:
5615 2: http
5616 3: path
5617 4: [desc]
5618 5: desc")
5619 (defvar org-bracket-link-analytic-regexp++ nil
5620 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5621 (defvar org-any-link-re nil
5622 "Regular expression matching any link.")
5624 (defconst org-match-sexp-depth 3
5625 "Number of stacked braces for sub/superscript matching.")
5627 (defun org-create-multibrace-regexp (left right n)
5628 "Create a regular expression which will match a balanced sexp.
5629 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5630 as single character strings.
5631 The regexp returned will match the entire expression including the
5632 delimiters. It will also define a single group which contains the
5633 match except for the outermost delimiters. The maximum depth of
5634 stacked delimiters is N. Escaping delimiters is not possible."
5635 (let* ((nothing (concat "[^" left right "]*?"))
5636 (or "\\|")
5637 (re nothing)
5638 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5639 (while (> n 1)
5640 (setq n (1- n)
5641 re (concat re or next)
5642 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5643 (concat left "\\(" re "\\)" right)))
5645 (defconst org-match-substring-regexp
5646 (concat
5647 "\\(\\S-\\)\\([_^]\\)\\("
5648 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5649 "\\|"
5650 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5651 "\\|"
5652 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5653 "The regular expression matching a sub- or superscript.")
5655 (defconst org-match-substring-with-braces-regexp
5656 (concat
5657 "\\(\\S-\\)\\([_^]\\)"
5658 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5659 "The regular expression matching a sub- or superscript, forcing braces.")
5661 (defun org-make-link-regexps ()
5662 "Update the link regular expressions.
5663 This should be called after the variable `org-link-parameters' has changed."
5664 (let ((types-re (regexp-opt (org-link-types) t)))
5665 (setq org-link-types-re
5666 (concat "\\`" types-re ":")
5667 org-link-re-with-space
5668 (concat "<?" types-re ":"
5669 "\\([^" org-non-link-chars " ]"
5670 "[^" org-non-link-chars "]*"
5671 "[^" org-non-link-chars " ]\\)>?")
5672 org-link-re-with-space2
5673 (concat "<?" types-re ":"
5674 "\\([^" org-non-link-chars " ]"
5675 "[^\t\n\r]*"
5676 "[^" org-non-link-chars " ]\\)>?")
5677 org-link-re-with-space3
5678 (concat "<?" types-re ":"
5679 "\\([^" org-non-link-chars " ]"
5680 "[^\t\n\r]*\\)")
5681 org-angle-link-re
5682 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5683 types-re)
5684 org-plain-link-re
5685 (concat
5686 "\\<" types-re ":"
5687 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5688 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5689 org-bracket-link-regexp
5690 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5691 org-bracket-link-analytic-regexp
5692 (concat
5693 "\\[\\["
5694 "\\(" types-re ":\\)?"
5695 "\\([^]]+\\)"
5696 "\\]"
5697 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5698 "\\]")
5699 org-bracket-link-analytic-regexp++
5700 (concat
5701 "\\[\\["
5702 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5703 "\\([^]]+\\)"
5704 "\\]"
5705 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5706 "\\]")
5707 org-any-link-re
5708 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5709 org-angle-link-re "\\)\\|\\("
5710 org-plain-link-re "\\)"))))
5712 (org-make-link-regexps)
5714 (defvar org-emph-face nil)
5716 (defun org-do-emphasis-faces (limit)
5717 "Run through the buffer and emphasize strings."
5718 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5719 (car org-emphasis-regexp-components))))
5720 (catch :exit
5721 (while (re-search-forward quick-re limit t)
5722 (let* ((marker (match-string 2))
5723 (verbatim? (member marker '("~" "="))))
5724 (when (save-excursion
5725 (goto-char (match-beginning 0))
5726 ;; Do not match headline stars. Do not consider
5727 ;; stars of a headline as closing marker for bold
5728 ;; markup either.
5729 (and (not (looking-at-p org-outline-regexp-bol))
5730 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5731 (not (string-match-p
5732 (concat org-outline-regexp-bol "\\'")
5733 (match-string 0)))))
5734 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5735 (font-lock-prepend-text-property
5736 (match-beginning 2) (match-end 2) 'face face)
5737 (when verbatim?
5738 (org-remove-flyspell-overlays-in
5739 (match-beginning 0) (match-end 0)))
5740 (add-text-properties (match-beginning 2) (match-end 2)
5741 '(font-lock-multiline t org-emphasis t))
5742 (when org-hide-emphasis-markers
5743 (add-text-properties (match-end 4) (match-beginning 5)
5744 '(invisible org-link))
5745 (add-text-properties (match-beginning 3) (match-end 3)
5746 '(invisible org-link)))
5747 (throw :exit t))))))))
5749 (defun org-emphasize (&optional char)
5750 "Insert or change an emphasis, i.e. a font like bold or italic.
5751 If there is an active region, change that region to a new emphasis.
5752 If there is no region, just insert the marker characters and position
5753 the cursor between them.
5754 CHAR should be the marker character. If it is a space, it means to
5755 remove the emphasis of the selected region.
5756 If CHAR is not given (for example in an interactive call) it will be
5757 prompted for."
5758 (interactive)
5759 (let ((erc org-emphasis-regexp-components)
5760 (string "") beg end move s)
5761 (if (org-region-active-p)
5762 (setq beg (region-beginning)
5763 end (region-end)
5764 string (buffer-substring beg end))
5765 (setq move t))
5767 (unless char
5768 (message "Emphasis marker or tag: [%s]"
5769 (mapconcat #'car org-emphasis-alist ""))
5770 (setq char (read-char-exclusive)))
5771 (if (equal char ?\s)
5772 (setq s ""
5773 move nil)
5774 (unless (assoc (char-to-string char) org-emphasis-alist)
5775 (user-error "No such emphasis marker: \"%c\"" char))
5776 (setq s (char-to-string char)))
5777 (while (and (> (length string) 1)
5778 (equal (substring string 0 1) (substring string -1))
5779 (assoc (substring string 0 1) org-emphasis-alist))
5780 (setq string (substring string 1 -1)))
5781 (setq string (concat s string s))
5782 (when beg (delete-region beg end))
5783 (unless (or (bolp)
5784 (string-match (concat "[" (nth 0 erc) "\n]")
5785 (char-to-string (char-before (point)))))
5786 (insert " "))
5787 (unless (or (eobp)
5788 (string-match (concat "[" (nth 1 erc) "\n]")
5789 (char-to-string (char-after (point)))))
5790 (insert " ") (backward-char 1))
5791 (insert string)
5792 (and move (backward-char 1))))
5794 (defconst org-nonsticky-props
5795 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5797 (defsubst org-rear-nonsticky-at (pos)
5798 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5800 (defun org-activate-plain-links (limit)
5801 "Add link properties for plain links."
5802 (when (and (re-search-forward org-plain-link-re limit t)
5803 (not (org-in-src-block-p)))
5805 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5806 'face))
5807 (link (match-string-no-properties 0))
5808 (type (match-string-no-properties 1))
5809 (path (match-string-no-properties 2))
5810 (link-start (match-beginning 0))
5811 (link-end (match-end 0))
5812 (link-face (org-link-get-parameter type :face))
5813 (help-echo (org-link-get-parameter type :help-echo))
5814 (htmlize-link (org-link-get-parameter type :htmlize-link))
5815 (activate-func (org-link-get-parameter type :activate-func)))
5816 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5817 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5818 (add-text-properties (match-beginning 0) (match-end 0)
5819 (list
5820 'mouse-face (or (org-link-get-parameter type :mouse-face)
5821 'highlight)
5822 'face (cond
5823 ;; A function that returns a face
5824 ((functionp link-face)
5825 (funcall link-face path))
5826 ;; a face
5827 ((facep link-face)
5828 link-face)
5829 ;; An anonymous face
5830 ((consp link-face)
5831 link-face)
5832 ;; default
5834 'org-link))
5835 'help-echo (cond
5836 ((stringp help-echo)
5837 help-echo)
5838 ((functionp help-echo)
5839 help-echo)
5841 (concat "LINK: "
5842 (save-match-data
5843 (org-link-unescape link)))))
5844 'htmlize-link (cond
5845 ((functionp htmlize-link)
5846 (funcall htmlize-link path))
5848 `(:uri ,link)))
5849 'keymap (or (org-link-get-parameter type :keymap)
5850 org-mouse-map)
5851 'org-link-start (match-beginning 0)))
5852 (org-rear-nonsticky-at (match-end 0))
5853 (when activate-func
5854 (funcall activate-func link-start link-end path nil))
5855 t))))
5857 (defun org-activate-code (limit)
5858 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5859 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5860 (remove-text-properties (match-beginning 0) (match-end 0)
5861 '(display t invisible t intangible t))
5864 (defcustom org-src-fontify-natively t
5865 "When non-nil, fontify code in code blocks.
5866 See also the `org-block' face."
5867 :type 'boolean
5868 :version "24.4"
5869 :package-version '(Org . "8.3")
5870 :group 'org-appearance
5871 :group 'org-babel)
5873 (defcustom org-allow-promoting-top-level-subtree nil
5874 "When non-nil, allow promoting a top level subtree.
5875 The leading star of the top level headline will be replaced
5876 by a #."
5877 :type 'boolean
5878 :version "24.1"
5879 :group 'org-appearance)
5881 (defun org-fontify-meta-lines-and-blocks (limit)
5882 (condition-case nil
5883 (org-fontify-meta-lines-and-blocks-1 limit)
5884 (error (message "org-mode fontification error in %S at %d"
5885 (current-buffer)
5886 (line-number-at-pos)))))
5888 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5889 "Fontify #+ lines and blocks."
5890 (let ((case-fold-search t))
5891 (when (re-search-forward
5892 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5893 limit t)
5894 (let ((beg (match-beginning 0))
5895 (block-start (match-end 0))
5896 (block-end nil)
5897 (lang (match-string 7))
5898 (beg1 (line-beginning-position 2))
5899 (dc1 (downcase (match-string 2)))
5900 (dc3 (downcase (match-string 3)))
5901 end end1 quoting block-type)
5902 (cond
5903 ((and (match-end 4) (equal dc3 "+begin"))
5904 ;; Truly a block
5905 (setq block-type (downcase (match-string 5))
5906 quoting (member block-type org-protecting-blocks))
5907 (when (re-search-forward
5908 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5909 nil t) ;; on purpose, we look further than LIMIT
5910 (setq end (min (point-max) (match-end 0))
5911 end1 (min (point-max) (1- (match-beginning 0))))
5912 (setq block-end (match-beginning 0))
5913 (when quoting
5914 (org-remove-flyspell-overlays-in beg1 end1)
5915 (remove-text-properties beg end
5916 '(display t invisible t intangible t)))
5917 (add-text-properties
5918 beg end '(font-lock-fontified t font-lock-multiline t))
5919 (add-text-properties beg beg1 '(face org-meta-line))
5920 (org-remove-flyspell-overlays-in beg beg1)
5921 (add-text-properties ; For end_src
5922 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5923 (org-remove-flyspell-overlays-in end1 end)
5924 (cond
5925 ((and lang (not (string= lang "")) org-src-fontify-natively)
5926 (org-src-font-lock-fontify-block lang block-start block-end)
5927 (add-text-properties beg1 block-end '(src-block t)))
5928 (quoting
5929 (add-text-properties beg1 (min (point-max) (1+ end1))
5930 (list 'face
5931 (list :inherit
5932 (let ((face-name
5933 (intern (format "org-block-%s" lang))))
5934 (append (and (facep face-name) (list face-name))
5935 '(org-block))))))) ; end of source block
5936 ((not org-fontify-quote-and-verse-blocks))
5937 ((string= block-type "quote")
5938 (add-face-text-property
5939 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5940 ((string= block-type "verse")
5941 (add-face-text-property
5942 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5943 (add-text-properties beg beg1 '(face org-block-begin-line))
5944 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5945 '(face org-block-end-line))
5947 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5948 (org-remove-flyspell-overlays-in
5949 (match-beginning 0)
5950 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5951 (add-text-properties
5952 beg (match-end 3)
5953 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5954 '(font-lock-fontified t invisible t)
5955 '(font-lock-fontified t face org-document-info-keyword)))
5956 (add-text-properties
5957 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5958 (if (string-equal dc1 "+title:")
5959 '(font-lock-fontified t face org-document-title)
5960 '(font-lock-fontified t face org-document-info))))
5961 ((string-prefix-p "+caption" dc1)
5962 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5963 (remove-text-properties (match-beginning 0) (match-end 0)
5964 '(display t invisible t intangible t))
5965 ;; Handle short captions.
5966 (save-excursion
5967 (beginning-of-line)
5968 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5969 (add-text-properties (line-beginning-position) (match-end 1)
5970 '(font-lock-fontified t face org-meta-line))
5971 (add-text-properties (match-end 0) (line-end-position)
5972 '(font-lock-fontified t face org-block))
5974 ((member dc3 '(" " ""))
5975 (org-remove-flyspell-overlays-in beg (match-end 0))
5976 (add-text-properties
5977 beg (match-end 0)
5978 '(font-lock-fontified t face font-lock-comment-face)))
5979 (t ;; just any other in-buffer setting, but not indented
5980 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5981 (remove-text-properties (match-beginning 0) (match-end 0)
5982 '(display t invisible t intangible t))
5983 (add-text-properties beg (match-end 0)
5984 '(font-lock-fontified t face org-meta-line))
5985 t))))))
5987 (defun org-fontify-drawers (limit)
5988 "Fontify drawers."
5989 (when (re-search-forward org-drawer-regexp limit t)
5990 (add-text-properties
5991 (match-beginning 0) (match-end 0)
5992 '(font-lock-fontified t face org-special-keyword))
5993 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (defun org-fontify-macros (limit)
5997 "Fontify macros."
5998 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5999 (add-text-properties
6000 (match-beginning 0) (match-end 0)
6001 '(font-lock-fontified t face org-macro))
6002 (when org-hide-macro-markers
6003 (add-text-properties (match-end 2) (match-beginning 2)
6004 '(invisible t))
6005 (add-text-properties (match-beginning 1) (match-end 1)
6006 '(invisible t)))
6007 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (defun org-activate-angle-links (limit)
6011 "Add text properties for angle links."
6012 (when (and (re-search-forward org-angle-link-re limit t)
6013 (not (org-in-src-block-p)))
6014 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6015 (add-text-properties (match-beginning 0) (match-end 0)
6016 (list 'mouse-face 'highlight
6017 'keymap org-mouse-map
6018 'font-lock-multiline t))
6019 (org-rear-nonsticky-at (match-end 0))
6022 (defun org-activate-footnote-links (limit)
6023 "Add text properties for footnotes."
6024 (let ((fn (org-footnote-next-reference-or-definition limit)))
6025 (when fn
6026 (let* ((beg (nth 1 fn))
6027 (end (nth 2 fn))
6028 (label (car fn))
6029 (referencep (/= (line-beginning-position) beg)))
6030 (when (and referencep (nth 3 fn))
6031 (save-excursion
6032 (goto-char beg)
6033 (search-forward (or label "fn:"))
6034 (org-remove-flyspell-overlays-in beg (match-end 0))))
6035 (add-text-properties beg end
6036 (list 'mouse-face 'highlight
6037 'keymap org-mouse-map
6038 'help-echo
6039 (if referencep "Footnote reference"
6040 "Footnote definition")
6041 'font-lock-fontified t
6042 'font-lock-multiline t
6043 'face 'org-footnote))))))
6045 (defun org-activate-bracket-links (limit)
6046 "Add text properties for bracketed links."
6047 (when (and (re-search-forward org-bracket-link-regexp limit t)
6048 (not (org-in-src-block-p)))
6049 (let* ((hl (save-match-data
6050 (org-link-expand-abbrev (match-string-no-properties 1))))
6051 (type (save-match-data
6052 (and (string-match org-plain-link-re hl)
6053 (match-string-no-properties 1 hl))))
6054 (path (save-match-data
6055 (and (string-match org-plain-link-re hl)
6056 (match-string-no-properties 2 hl))))
6057 (link-start (match-beginning 0))
6058 (link-end (match-end 0))
6059 (bracketp t)
6060 (help-echo (org-link-get-parameter type :help-echo))
6061 (help (cond
6062 ((stringp help-echo)
6063 help-echo)
6064 ((functionp help-echo)
6065 help-echo)
6067 (concat "LINK: "
6068 (save-match-data
6069 (org-link-unescape hl))))))
6070 (link-face (org-link-get-parameter type :face))
6071 (face (cond
6072 ;; A function that returns a face
6073 ((functionp link-face)
6074 (funcall link-face path))
6075 ;; a face
6076 ((facep link-face)
6077 link-face)
6078 ;; An anonymous face
6079 ((consp link-face)
6080 link-face)
6081 ;; default
6083 'org-link)))
6084 (keymap (or (org-link-get-parameter type :keymap)
6085 org-mouse-map))
6086 (mouse-face (or (org-link-get-parameter type :mouse-face)
6087 'highlight))
6088 (htmlize (org-link-get-parameter type :htmlize-link))
6089 (htmlize-link (cond
6090 ((functionp htmlize)
6091 (funcall htmlize))
6093 `(:uri ,(format "%s:%s" type path)))))
6094 (activate-func (org-link-get-parameter type :activate-func))
6095 ;; invisible part
6096 (ip (list 'invisible (or
6097 (org-link-get-parameter type :display)
6098 'org-link)
6099 'face face
6100 'keymap keymap
6101 'mouse-face mouse-face
6102 'font-lock-multiline t
6103 'help-echo help
6104 'htmlize-link htmlize-link))
6105 ;; visible part
6106 (vp (list 'keymap keymap
6107 'face face
6108 'mouse-face mouse-face
6109 'font-lock-multiline t
6110 'help-echo help
6111 'htmlize-link htmlize-link)))
6112 ;; We need to remove the invisible property here. Table narrowing
6113 ;; may have made some of this invisible.
6114 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6115 (remove-text-properties (match-beginning 0) (match-end 0)
6116 '(invisible nil))
6117 (if (match-end 3)
6118 (progn
6119 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6120 (org-rear-nonsticky-at (match-beginning 3))
6121 (add-text-properties (match-beginning 3) (match-end 3) vp)
6122 (org-rear-nonsticky-at (match-end 3))
6123 (add-text-properties (match-end 3) (match-end 0) ip)
6124 (org-rear-nonsticky-at (match-end 0)))
6125 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6126 (org-rear-nonsticky-at (match-beginning 1))
6127 (add-text-properties (match-beginning 1) (match-end 1) vp)
6128 (org-rear-nonsticky-at (match-end 1))
6129 (add-text-properties (match-end 1) (match-end 0) ip)
6130 (org-rear-nonsticky-at (match-end 0)))
6131 (when activate-func
6132 (funcall activate-func link-start link-end path bracketp))
6133 t)))
6135 (defun org-activate-dates (limit)
6136 "Add text properties for dates."
6137 (when (and (re-search-forward org-tsr-regexp-both limit t)
6138 (not (equal (char-before (match-beginning 0)) 91)))
6139 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6140 (add-text-properties (match-beginning 0) (match-end 0)
6141 (list 'mouse-face 'highlight
6142 'keymap org-mouse-map))
6143 (org-rear-nonsticky-at (match-end 0))
6144 (when org-display-custom-times
6145 (if (match-end 3)
6146 (org-display-custom-time (match-beginning 3) (match-end 3))
6147 (org-display-custom-time (match-beginning 1) (match-end 1))))
6150 (defvar-local org-target-link-regexp nil
6151 "Regular expression matching radio targets in plain text.")
6153 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6154 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6155 border border border))
6156 "Regular expression matching a link target.")
6158 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6159 "Regular expression matching a radio target.")
6161 (defconst org-any-target-regexp
6162 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6163 "Regular expression matching any target.")
6165 (defun org-activate-target-links (limit)
6166 "Add text properties for target matches."
6167 (when org-target-link-regexp
6168 (let ((case-fold-search t))
6169 (when (re-search-forward org-target-link-regexp limit t)
6170 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6171 (add-text-properties (match-beginning 1) (match-end 1)
6172 (list 'mouse-face 'highlight
6173 'keymap org-mouse-map
6174 'help-echo "Radio target link"
6175 'org-linked-text t))
6176 (org-rear-nonsticky-at (match-end 1))
6177 t))))
6179 (defun org-update-radio-target-regexp ()
6180 "Find all radio targets in this file and update the regular expression.
6181 Also refresh fontification if needed."
6182 (interactive)
6183 (let ((old-regexp org-target-link-regexp)
6184 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6185 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6186 (targets
6187 (org-with-wide-buffer
6188 (goto-char (point-min))
6189 (let (rtn)
6190 (while (re-search-forward org-radio-target-regexp nil t)
6191 ;; Make sure point is really within the object.
6192 (backward-char)
6193 (let ((obj (org-element-context)))
6194 (when (eq (org-element-type obj) 'radio-target)
6195 (cl-pushnew (org-element-property :value obj) rtn
6196 :test #'equal))))
6197 rtn))))
6198 (setq org-target-link-regexp
6199 (and targets
6200 (concat before-re
6201 (mapconcat
6202 (lambda (x)
6203 (replace-regexp-in-string
6204 " +" "\\s-+" (regexp-quote x) t t))
6205 targets
6206 "\\|")
6207 after-re)))
6208 (unless (equal old-regexp org-target-link-regexp)
6209 ;; Clean-up cache.
6210 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6211 ((not org-target-link-regexp) old-regexp)
6213 (concat before-re
6214 (mapconcat
6215 (lambda (re)
6216 (substring re (length before-re)
6217 (- (length after-re))))
6218 (list old-regexp org-target-link-regexp)
6219 "\\|")
6220 after-re)))))
6221 (org-with-wide-buffer
6222 (goto-char (point-min))
6223 (while (re-search-forward regexp nil t)
6224 (org-element-cache-refresh (match-beginning 1)))))
6225 ;; Re fontify buffer.
6226 (when (memq 'radio org-highlight-links)
6227 (org-restart-font-lock)))))
6229 (defun org-hide-wide-columns (limit)
6230 (let (s e)
6231 (setq s (text-property-any (point) (or limit (point-max))
6232 'org-cwidth t))
6233 (when s
6234 (setq e (next-single-property-change s 'org-cwidth))
6235 (add-text-properties s e '(invisible org-cwidth))
6236 (goto-char e)
6237 t)))
6239 (defvar org-latex-and-related-regexp nil
6240 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6242 (defun org-compute-latex-and-related-regexp ()
6243 "Compute regular expression for LaTeX, entities and sub/superscript.
6244 Result depends on variable `org-highlight-latex-and-related'."
6245 (setq-local
6246 org-latex-and-related-regexp
6247 (let* ((re-sub
6248 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6249 ((eq org-use-sub-superscripts '{})
6250 (list org-match-substring-with-braces-regexp))
6251 (org-use-sub-superscripts (list org-match-substring-regexp))))
6252 (re-latex
6253 (when (memq 'latex org-highlight-latex-and-related)
6254 (let ((matchers (plist-get org-format-latex-options :matchers)))
6255 (delq nil
6256 (mapcar (lambda (x)
6257 (and (member (car x) matchers) (nth 1 x)))
6258 org-latex-regexps)))))
6259 (re-entities
6260 (when (memq 'entities org-highlight-latex-and-related)
6261 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6262 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6264 (defun org-do-latex-and-related (limit)
6265 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6266 LIMIT bounds the search for syntax to highlight. Stop at first
6267 highlighted object, if any. Return t if some highlighting was
6268 done, nil otherwise."
6269 (when (org-string-nw-p org-latex-and-related-regexp)
6270 (catch 'found
6271 (while (re-search-forward org-latex-and-related-regexp limit t)
6272 (unless
6273 (cl-some
6274 (lambda (f)
6275 (memq f '(org-code org-verbatim underline org-special-keyword)))
6276 (save-excursion
6277 (goto-char (1+ (match-beginning 0)))
6278 (face-at-point nil t)))
6279 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6280 '(?_ ?^))
6282 0)))
6283 (font-lock-prepend-text-property
6284 (+ offset (match-beginning 0)) (match-end 0)
6285 'face 'org-latex-and-related)
6286 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6287 '(font-lock-multiline t)))
6288 (throw 'found t)))
6289 nil)))
6291 (defun org-restart-font-lock ()
6292 "Restart `font-lock-mode', to force refontification."
6293 (when (and (boundp 'font-lock-mode) font-lock-mode)
6294 (font-lock-mode -1)
6295 (font-lock-mode 1)))
6297 (defun org-activate-tags (limit)
6298 (when (re-search-forward
6299 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6300 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6301 (add-text-properties (match-beginning 1) (match-end 1)
6302 (list 'mouse-face 'highlight
6303 'keymap org-mouse-map))
6304 (org-rear-nonsticky-at (match-end 1))
6307 (defun org-outline-level ()
6308 "Compute the outline level of the heading at point.
6310 If this is called at a normal headline, the level is the number
6311 of stars. Use `org-reduced-level' to remove the effect of
6312 `org-odd-levels'. Unlike to `org-current-level', this function
6313 takes into consideration inlinetasks."
6314 (org-with-wide-buffer
6315 (end-of-line)
6316 (if (re-search-backward org-outline-regexp-bol nil t)
6317 (1- (- (match-end 0) (match-beginning 0)))
6318 0)))
6320 (defvar org-font-lock-keywords nil)
6322 (defsubst org-re-property (property &optional literal allow-null value)
6323 "Return a regexp matching a PROPERTY line.
6325 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6326 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6327 non-nil, match properties even without a value.
6329 Match group 3 is set to the value when it exists. If there is no
6330 value and ALLOW-NULL is non-nil, it is set to the empty string.
6332 With optional argument VALUE, match only property lines with
6333 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6334 unless LITERAL is non-nil."
6335 (concat
6336 "^\\(?4:[ \t]*\\)"
6337 (format "\\(?1::\\(?2:%s\\):\\)"
6338 (if literal property (regexp-quote property)))
6339 (cond (value
6340 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6341 (if literal value (regexp-quote value))))
6342 (allow-null
6343 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6345 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6347 (defconst org-property-re
6348 (org-re-property "\\S-+" 'literal t)
6349 "Regular expression matching a property line.
6350 There are four matching groups:
6351 1: :PROPKEY: including the leading and trailing colon,
6352 2: PROPKEY without the leading and trailing colon,
6353 3: PROPVAL without leading or trailing spaces,
6354 4: the indentation of the current line,
6355 5: trailing whitespace.")
6357 (defvar org-font-lock-hook nil
6358 "Functions to be called for special font lock stuff.")
6360 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6362 (defvar org-font-lock-set-keywords-hook nil
6363 "Functions that can manipulate `org-font-lock-extra-keywords'.
6364 This is called after `org-font-lock-extra-keywords' is defined, but before
6365 it is installed to be used by font lock. This can be useful if something
6366 needs to be inserted at a specific position in the font-lock sequence.")
6368 (defun org-font-lock-hook (limit)
6369 "Run `org-font-lock-hook' within LIMIT."
6370 (run-hook-with-args 'org-font-lock-hook limit))
6372 (defun org-set-font-lock-defaults ()
6373 "Set font lock defaults for the current buffer."
6374 (let* ((em org-fontify-emphasized-text)
6375 (lk org-highlight-links)
6376 (org-font-lock-extra-keywords
6377 (list
6378 ;; Call the hook
6379 '(org-font-lock-hook)
6380 ;; Headlines
6381 `(,(if org-fontify-whole-heading-line
6382 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6383 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6384 (1 (org-get-level-face 1))
6385 (2 (org-get-level-face 2))
6386 (3 (org-get-level-face 3)))
6387 ;; Table lines
6388 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6389 (1 'org-table t))
6390 ;; Table internals
6391 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6392 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6393 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6394 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6395 ;; Drawers
6396 '(org-fontify-drawers)
6397 ;; Properties
6398 (list org-property-re
6399 '(1 'org-special-keyword t)
6400 '(3 'org-property-value t))
6401 ;; Links
6402 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6403 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6404 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6405 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6406 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6407 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6408 (when (memq 'footnote lk) '(org-activate-footnote-links))
6409 ;; Targets.
6410 (list org-any-target-regexp '(0 'org-target t))
6411 ;; Diary sexps.
6412 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6413 ;; Macro
6414 '(org-fontify-macros)
6415 '(org-hide-wide-columns (0 nil append))
6416 ;; TODO keyword
6417 (list (format org-heading-keyword-regexp-format
6418 org-todo-regexp)
6419 '(2 (org-get-todo-face 2) t))
6420 ;; DONE
6421 (if org-fontify-done-headline
6422 (list (format org-heading-keyword-regexp-format
6423 (concat
6424 "\\(?:"
6425 (mapconcat 'regexp-quote org-done-keywords "\\|")
6426 "\\)"))
6427 '(2 'org-headline-done t))
6428 nil)
6429 ;; Priorities
6430 '(org-font-lock-add-priority-faces)
6431 ;; Tags
6432 '(org-font-lock-add-tag-faces)
6433 ;; Tags groups
6434 (when (and org-group-tags org-tag-groups-alist)
6435 (list (concat org-outline-regexp-bol ".+\\(:"
6436 (regexp-opt (mapcar 'car org-tag-groups-alist))
6437 ":\\).*$")
6438 '(1 'org-tag-group prepend)))
6439 ;; Special keywords
6440 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6441 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6442 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6443 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6444 ;; Emphasis
6445 (when em '(org-do-emphasis-faces))
6446 ;; Checkboxes
6447 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6448 1 'org-checkbox prepend)
6449 (when (cdr (assq 'checkbox org-list-automatic-rules))
6450 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6451 (0 (org-get-checkbox-statistics-face) t)))
6452 ;; Description list items
6453 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6454 1 'org-list-dt prepend)
6455 ;; ARCHIVEd headings
6456 (list (concat
6457 org-outline-regexp-bol
6458 "\\(.*:" org-archive-tag ":.*\\)")
6459 '(1 'org-archived prepend))
6460 ;; Specials
6461 '(org-do-latex-and-related)
6462 '(org-fontify-entities)
6463 '(org-raise-scripts)
6464 ;; Code
6465 '(org-activate-code (1 'org-code t))
6466 ;; COMMENT
6467 (list (format
6468 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6469 org-todo-regexp
6470 org-comment-string)
6471 '(9 'org-special-keyword t))
6472 ;; Blocks and meta lines
6473 '(org-fontify-meta-lines-and-blocks))))
6474 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6475 (run-hooks 'org-font-lock-set-keywords-hook)
6476 ;; Now set the full font-lock-keywords
6477 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6478 (setq-local font-lock-defaults
6479 '(org-font-lock-keywords t nil nil backward-paragraph))
6480 (kill-local-variable 'font-lock-keywords)
6481 nil))
6483 (defun org-toggle-pretty-entities ()
6484 "Toggle the composition display of entities as UTF8 characters."
6485 (interactive)
6486 (setq-local org-pretty-entities (not org-pretty-entities))
6487 (org-restart-font-lock)
6488 (if org-pretty-entities
6489 (message "Entities are now displayed as UTF8 characters")
6490 (save-restriction
6491 (widen)
6492 (decompose-region (point-min) (point-max))
6493 (message "Entities are now displayed as plain text"))))
6495 (defvar-local org-custom-properties-overlays nil
6496 "List of overlays used for custom properties.")
6498 (defun org-toggle-custom-properties-visibility ()
6499 "Display or hide properties in `org-custom-properties'."
6500 (interactive)
6501 (if org-custom-properties-overlays
6502 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6503 (setq org-custom-properties-overlays nil))
6504 (when org-custom-properties
6505 (org-with-wide-buffer
6506 (goto-char (point-min))
6507 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6508 (while (re-search-forward regexp nil t)
6509 (let ((end (cdr (save-match-data (org-get-property-block)))))
6510 (when (and end (< (point) end))
6511 ;; Hide first custom property in current drawer.
6512 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6513 (overlay-put o 'invisible t)
6514 (overlay-put o 'org-custom-property t)
6515 (push o org-custom-properties-overlays))
6516 ;; Hide additional custom properties in the same drawer.
6517 (while (re-search-forward regexp end t)
6518 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6519 (overlay-put o 'invisible t)
6520 (overlay-put o 'org-custom-property t)
6521 (push o org-custom-properties-overlays)))))
6522 ;; Each entry is limited to a single property drawer.
6523 (outline-next-heading)))))))
6525 (defun org-fontify-entities (limit)
6526 "Find an entity to fontify."
6527 (let (ee)
6528 (when org-pretty-entities
6529 (catch 'match
6530 ;; "\_ "-family is left out on purpose. Only the first one,
6531 ;; i.e., "\_ ", could be fontified anyway, and it would be
6532 ;; confusing when adding a second white space character.
6533 (while (re-search-forward
6534 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6535 limit t)
6536 (when (and (not (org-at-comment-p))
6537 (setq ee (org-entity-get (match-string 1)))
6538 (= (length (nth 6 ee)) 1))
6539 (let* ((end (if (equal (match-string 2) "{}")
6540 (match-end 2)
6541 (match-end 1))))
6542 (add-text-properties
6543 (match-beginning 0) end
6544 (list 'font-lock-fontified t))
6545 (compose-region (match-beginning 0) end
6546 (nth 6 ee) nil)
6547 (backward-char 1)
6548 (throw 'match t))))
6549 nil))))
6551 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6552 "Fontify string S like in Org mode."
6553 (with-temp-buffer
6554 (insert s)
6555 (let ((org-odd-levels-only odd-levels))
6556 (org-mode)
6557 (org-font-lock-ensure)
6558 (buffer-string))))
6560 (defvar org-m nil)
6561 (defvar org-l nil)
6562 (defvar org-f nil)
6563 (defun org-get-level-face (n)
6564 "Get the right face for match N in font-lock matching of headlines."
6565 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6566 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6567 (if org-cycle-level-faces
6568 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6569 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6570 (cond
6571 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6572 ((eq n 2) org-f)
6573 (t (unless org-level-color-stars-only org-f))))
6575 (defun org-face-from-face-or-color (context inherit face-or-color)
6576 "Create a face list that inherits INHERIT, but sets the foreground color.
6577 When FACE-OR-COLOR is not a string, just return it."
6578 (if (stringp face-or-color)
6579 (list :inherit inherit
6580 (cdr (assoc context org-faces-easy-properties))
6581 face-or-color)
6582 face-or-color))
6584 (defun org-get-todo-face (kwd)
6585 "Get the right face for a TODO keyword KWD.
6586 If KWD is a number, get the corresponding match group."
6587 (when (numberp kwd) (setq kwd (match-string kwd)))
6588 (or (org-face-from-face-or-color
6589 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6590 (and (member kwd org-done-keywords) 'org-done)
6591 'org-todo))
6593 (defun org-get-priority-face (priority)
6594 "Get the right face for PRIORITY.
6595 PRIORITY is a character."
6596 (or (org-face-from-face-or-color
6597 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6598 'org-priority))
6600 (defun org-get-tag-face (tag)
6601 "Get the right face for TAG.
6602 If TAG is a number, get the corresponding match group."
6603 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6604 (or (org-face-from-face-or-color
6605 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6606 'org-tag)))
6608 (defun org-font-lock-add-priority-faces (limit)
6609 "Add the special priority faces."
6610 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6611 (add-text-properties
6612 (match-beginning 1) (match-end 1)
6613 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6614 'font-lock-fontified t))))
6616 (defun org-font-lock-add-tag-faces (limit)
6617 "Add the special tag faces."
6618 (when (and org-tag-faces org-tags-special-faces-re)
6619 (while (re-search-forward org-tags-special-faces-re limit t)
6620 (add-text-properties (match-beginning 1) (match-end 1)
6621 (list 'face (org-get-tag-face 1)
6622 'font-lock-fontified t))
6623 (backward-char 1))))
6625 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6626 "Remove fontification and activation overlays from links."
6627 (font-lock-default-unfontify-region beg end)
6628 (let* ((buffer-undo-list t)
6629 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6630 (inhibit-modification-hooks t)
6631 deactivate-mark buffer-file-name buffer-file-truename)
6632 (decompose-region beg end)
6633 (remove-text-properties beg end
6634 '(mouse-face t keymap t org-linked-text t
6635 invisible t intangible t
6636 org-emphasis t))
6637 (org-remove-font-lock-display-properties beg end)))
6639 (defconst org-script-display '(((raise -0.3) (height 0.7))
6640 ((raise 0.3) (height 0.7))
6641 ((raise -0.5))
6642 ((raise 0.5)))
6643 "Display properties for showing superscripts and subscripts.")
6645 (defun org-remove-font-lock-display-properties (beg end)
6646 "Remove specific display properties that have been added by font lock.
6647 The will remove the raise properties that are used to show superscripts
6648 and subscripts."
6649 (let (next prop)
6650 (while (< beg end)
6651 (setq next (next-single-property-change beg 'display nil end)
6652 prop (get-text-property beg 'display))
6653 (when (member prop org-script-display)
6654 (put-text-property beg next 'display nil))
6655 (setq beg next))))
6657 (defun org-raise-scripts (limit)
6658 "Add raise properties to sub/superscripts."
6659 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6660 (re-search-forward
6661 (if (eq org-use-sub-superscripts t)
6662 org-match-substring-regexp
6663 org-match-substring-with-braces-regexp)
6664 limit t))
6665 (let* ((pos (point)) table-p comment-p
6666 (mpos (match-beginning 3))
6667 (emph-p (get-text-property mpos 'org-emphasis))
6668 (link-p (get-text-property mpos 'mouse-face))
6669 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6670 (goto-char (point-at-bol))
6671 (setq table-p (looking-at-p org-table-dataline-regexp)
6672 comment-p (looking-at-p "^[ \t]*#[ +]"))
6673 (goto-char pos)
6674 ;; Handle a_b^c
6675 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6676 (unless (or comment-p emph-p link-p keyw-p)
6677 (put-text-property (match-beginning 3) (match-end 0)
6678 'display
6679 (if (equal (char-after (match-beginning 2)) ?^)
6680 (nth (if table-p 3 1) org-script-display)
6681 (nth (if table-p 2 0) org-script-display)))
6682 (add-text-properties (match-beginning 2) (match-end 2)
6683 (list 'invisible t
6684 'org-dwidth t 'org-dwidth-n 1))
6685 (if (and (eq (char-after (match-beginning 3)) ?{)
6686 (eq (char-before (match-end 3)) ?}))
6687 (progn
6688 (add-text-properties
6689 (match-beginning 3) (1+ (match-beginning 3))
6690 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6691 (add-text-properties
6692 (1- (match-end 3)) (match-end 3)
6693 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6694 t)))
6696 ;;;; Visibility cycling, including org-goto and indirect buffer
6698 ;;; Cycling
6700 (defvar-local org-cycle-global-status nil)
6701 (put 'org-cycle-global-status 'org-state t)
6702 (defvar-local org-cycle-subtree-status nil)
6703 (put 'org-cycle-subtree-status 'org-state t)
6705 (defvar org-inlinetask-min-level)
6707 (defun org-unlogged-message (&rest args)
6708 "Display a message, but avoid logging it in the *Messages* buffer."
6709 (let ((message-log-max nil))
6710 (apply 'message args)))
6712 ;;;###autoload
6713 (defun org-cycle (&optional arg)
6714 "TAB-action and visibility cycling for Org mode.
6716 This is the command invoked in Org mode by the `TAB' key. Its main
6717 purpose is outline visibility cycling, but it also invokes other actions
6718 in special contexts.
6720 When this function is called with a `\\[universal-argument]' prefix, rotate \
6721 the entire
6722 buffer through 3 states (global cycling)
6723 1. OVERVIEW: Show only top-level headlines.
6724 2. CONTENTS: Show all headlines of all levels, but no body text.
6725 3. SHOW ALL: Show everything.
6727 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6728 switch to the startup visibility,
6729 determined by the variable `org-startup-folded', and by any VISIBILITY
6730 properties in the buffer.
6732 With a `\\[universal-argument] \\[universal-argument] \
6733 \\[universal-argument]' prefix argument, show the entire buffer, including
6734 any drawers.
6736 When inside a table, re-align the table and move to the next field.
6738 When point is at the beginning of a headline, rotate the subtree started
6739 by this line through 3 different states (local cycling)
6740 1. FOLDED: Only the main headline is shown.
6741 2. CHILDREN: The main headline and the direct children are shown.
6742 From this state, you can move to one of the children
6743 and zoom in further.
6744 3. SUBTREE: Show the entire subtree, including body text.
6745 If there is no subtree, switch directly from CHILDREN to FOLDED.
6747 When point is at the beginning of an empty headline and the variable
6748 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6749 of the headline by demoting and promoting it to likely levels. This
6750 speeds up creation document structure by pressing `TAB' once or several
6751 times right after creating a new headline.
6753 When there is a numeric prefix, go up to a heading with level ARG, do
6754 a `show-subtree' and return to the previous cursor position. If ARG
6755 is negative, go up that many levels.
6757 When point is not at the beginning of a headline, execute the global
6758 binding for `TAB', which is re-indenting the line. See the option
6759 `org-cycle-emulate-tab' for details.
6761 As a special case, if point is at the beginning of the buffer and there is
6762 no headline in line 1, this function will act as if called with prefix arg
6763 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6764 prefix arg, but only
6765 if the variable `org-cycle-global-at-bob' is t."
6766 (interactive "P")
6767 (org-load-modules-maybe)
6768 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6769 (and org-cycle-level-after-item/entry-creation
6770 (or (org-cycle-level)
6771 (org-cycle-item-indentation))))
6772 (let* ((limit-level
6773 (or org-cycle-max-level
6774 (and (boundp 'org-inlinetask-min-level)
6775 org-inlinetask-min-level
6776 (1- org-inlinetask-min-level))))
6777 (nstars (and limit-level
6778 (if org-odd-levels-only
6779 (and limit-level (1- (* limit-level 2)))
6780 limit-level)))
6781 (org-outline-regexp
6782 (if (not (derived-mode-p 'org-mode))
6783 outline-regexp
6784 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6785 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6786 (not (looking-at org-outline-regexp))))
6787 (org-cycle-hook
6788 (if bob-special
6789 (delq 'org-optimize-window-after-visibility-change
6790 (copy-sequence org-cycle-hook))
6791 org-cycle-hook))
6792 (pos (point)))
6794 (cond
6796 ((equal arg '(16))
6797 (setq last-command 'dummy)
6798 (org-set-startup-visibility)
6799 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6801 ((equal arg '(64))
6802 (outline-show-all)
6803 (org-unlogged-message "Entire buffer visible, including drawers"))
6805 ((equal arg '(4)) (org-cycle-internal-global))
6807 ;; Try hiding block at point.
6808 ((org-hide-block-toggle-maybe))
6810 ;; Try cdlatex TAB completion
6811 ((org-try-cdlatex-tab))
6813 ;; Table: enter it or move to the next field.
6814 ((org-at-table-p 'any)
6815 (if (org-at-table.el-p)
6816 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6817 Use `\\[org-edit-special]' to edit table.el tables"))
6818 (if arg (org-table-edit-field t)
6819 (org-table-justify-field-maybe)
6820 (call-interactively 'org-table-next-field))))
6822 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6824 ;; Global cycling: delegate to `org-cycle-internal-global'.
6825 (bob-special (org-cycle-internal-global))
6827 ;; Drawers: delegate to `org-flag-drawer'.
6828 ((save-excursion
6829 (beginning-of-line 1)
6830 (looking-at org-drawer-regexp))
6831 (org-flag-drawer ; toggle block visibility
6832 (not (get-char-property (match-end 0) 'invisible))))
6834 ;; Show-subtree, ARG levels up from here.
6835 ((integerp arg)
6836 (save-excursion
6837 (org-back-to-heading)
6838 (outline-up-heading (if (< arg 0) (- arg)
6839 (- (funcall outline-level) arg)))
6840 (org-show-subtree)))
6842 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6843 ((and (featurep 'org-inlinetask)
6844 (org-inlinetask-at-task-p)
6845 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6846 (org-inlinetask-toggle-visibility))
6848 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6849 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6850 (save-excursion (move-beginning-of-line 1)
6851 (looking-at org-outline-regexp)))
6852 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6853 (org-cycle-internal-local))
6855 ;; From there: TAB emulation and template completion.
6856 (buffer-read-only (org-back-to-heading))
6858 ((run-hook-with-args-until-success
6859 'org-tab-after-check-for-cycling-hook))
6861 ((org-try-structure-completion))
6863 ((run-hook-with-args-until-success
6864 'org-tab-before-tab-emulation-hook))
6866 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6867 (or (not (bolp))
6868 (not (looking-at org-outline-regexp))))
6869 (call-interactively (global-key-binding "\t")))
6871 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6872 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6873 (or (and (eq org-cycle-emulate-tab 'white)
6874 (= (match-end 0) (point-at-eol)))
6875 (and (eq org-cycle-emulate-tab 'whitestart)
6876 (>= (match-end 0) pos))))
6878 (eq org-cycle-emulate-tab t))
6879 (call-interactively (global-key-binding "\t")))
6881 (t (save-excursion
6882 (org-back-to-heading)
6883 (org-cycle)))))))
6885 (defun org-cycle-internal-global ()
6886 "Do the global cycling action."
6887 ;; Hack to avoid display of messages for .org attachments in Gnus
6888 (let ((ga (string-match "\\*fontification" (buffer-name))))
6889 (cond
6890 ((and (eq last-command this-command)
6891 (eq org-cycle-global-status 'overview))
6892 ;; We just created the overview - now do table of contents
6893 ;; This can be slow in very large buffers, so indicate action
6894 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6895 (unless ga (org-unlogged-message "CONTENTS..."))
6896 (org-content)
6897 (unless ga (org-unlogged-message "CONTENTS...done"))
6898 (setq org-cycle-global-status 'contents)
6899 (run-hook-with-args 'org-cycle-hook 'contents))
6901 ((and (eq last-command this-command)
6902 (eq org-cycle-global-status 'contents))
6903 ;; We just showed the table of contents - now show everything
6904 (run-hook-with-args 'org-pre-cycle-hook 'all)
6905 (outline-show-all)
6906 (unless ga (org-unlogged-message "SHOW ALL"))
6907 (setq org-cycle-global-status 'all)
6908 (run-hook-with-args 'org-cycle-hook 'all))
6911 ;; Default action: go to overview
6912 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6913 (org-overview)
6914 (unless ga (org-unlogged-message "OVERVIEW"))
6915 (setq org-cycle-global-status 'overview)
6916 (run-hook-with-args 'org-cycle-hook 'overview)))))
6918 (defvar org-called-with-limited-levels nil
6919 "Non-nil when `org-with-limited-levels' is currently active.")
6921 (defun org-cycle-internal-local ()
6922 "Do the local cycling action."
6923 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6924 ;; First, determine end of headline (EOH), end of subtree or item
6925 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6926 (save-excursion
6927 (if (org-at-item-p)
6928 (progn
6929 (beginning-of-line)
6930 (setq struct (org-list-struct))
6931 (setq eoh (point-at-eol))
6932 (setq eos (org-list-get-item-end-before-blank (point) struct))
6933 (setq has-children (org-list-has-child-p (point) struct)))
6934 (org-back-to-heading)
6935 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6936 (setq eos (save-excursion (org-end-of-subtree t t)
6937 (when (bolp) (backward-char)) (point)))
6938 (setq has-children
6939 (or (save-excursion
6940 (let ((level (funcall outline-level)))
6941 (outline-next-heading)
6942 (and (org-at-heading-p t)
6943 (> (funcall outline-level) level))))
6944 (save-excursion
6945 (org-list-search-forward (org-item-beginning-re) eos t)))))
6946 ;; Determine end invisible part of buffer (EOL)
6947 (beginning-of-line 2)
6948 (while (and (not (eobp)) ;This is like `next-line'.
6949 (get-char-property (1- (point)) 'invisible))
6950 (goto-char (next-single-char-property-change (point) 'invisible))
6951 (and (eolp) (beginning-of-line 2)))
6952 (setq eol (point)))
6953 ;; Find out what to do next and set `this-command'
6954 (cond
6955 ((= eos eoh)
6956 ;; Nothing is hidden behind this heading
6957 (unless (org-before-first-heading-p)
6958 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6959 (org-unlogged-message "EMPTY ENTRY")
6960 (setq org-cycle-subtree-status nil)
6961 (save-excursion
6962 (goto-char eos)
6963 (outline-next-heading)
6964 (when (outline-invisible-p) (org-flag-heading nil))))
6965 ((and (or (>= eol eos)
6966 (not (string-match "\\S-" (buffer-substring eol eos))))
6967 (or has-children
6968 (not (setq children-skipped
6969 org-cycle-skip-children-state-if-no-children))))
6970 ;; Entire subtree is hidden in one line: children view
6971 (unless (org-before-first-heading-p)
6972 (run-hook-with-args 'org-pre-cycle-hook 'children))
6973 (if (org-at-item-p)
6974 (org-list-set-item-visibility (point-at-bol) struct 'children)
6975 (org-show-entry)
6976 (org-with-limited-levels (org-show-children))
6977 ;; FIXME: This slows down the func way too much.
6978 ;; How keep drawers hidden in subtree anyway?
6979 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6980 ;; (org-cycle-hide-drawers 'subtree))
6982 ;; Fold every list in subtree to top-level items.
6983 (when (eq org-cycle-include-plain-lists 'integrate)
6984 (save-excursion
6985 (org-back-to-heading)
6986 (while (org-list-search-forward (org-item-beginning-re) eos t)
6987 (beginning-of-line 1)
6988 (let* ((struct (org-list-struct))
6989 (prevs (org-list-prevs-alist struct))
6990 (end (org-list-get-bottom-point struct)))
6991 (dolist (e (org-list-get-all-items (point) struct prevs))
6992 (org-list-set-item-visibility e struct 'folded))
6993 (goto-char (if (< end eos) end eos)))))))
6994 (org-unlogged-message "CHILDREN")
6995 (save-excursion
6996 (goto-char eos)
6997 (outline-next-heading)
6998 (when (outline-invisible-p) (org-flag-heading nil)))
6999 (setq org-cycle-subtree-status 'children)
7000 (unless (org-before-first-heading-p)
7001 (run-hook-with-args 'org-cycle-hook 'children)))
7002 ((or children-skipped
7003 (and (eq last-command this-command)
7004 (eq org-cycle-subtree-status 'children)))
7005 ;; We just showed the children, or no children are there,
7006 ;; now show everything.
7007 (unless (org-before-first-heading-p)
7008 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7009 (outline-flag-region eoh eos nil)
7010 (org-unlogged-message
7011 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7012 (setq org-cycle-subtree-status 'subtree)
7013 (unless (org-before-first-heading-p)
7014 (run-hook-with-args 'org-cycle-hook 'subtree)))
7016 ;; Default action: hide the subtree.
7017 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7018 (outline-flag-region eoh eos t)
7019 (org-unlogged-message "FOLDED")
7020 (setq org-cycle-subtree-status 'folded)
7021 (unless (org-before-first-heading-p)
7022 (run-hook-with-args 'org-cycle-hook 'folded))))))
7024 ;;;###autoload
7025 (defun org-global-cycle (&optional arg)
7026 "Cycle the global visibility. For details see `org-cycle'.
7027 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7028 With a numeric prefix, show all headlines up to that level."
7029 (interactive "P")
7030 (let ((org-cycle-include-plain-lists
7031 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7032 (cond
7033 ((integerp arg)
7034 (outline-show-all)
7035 (outline-hide-sublevels arg)
7036 (setq org-cycle-global-status 'contents))
7037 ((equal arg '(4))
7038 (org-set-startup-visibility)
7039 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7041 (org-cycle '(4))))))
7043 (defun org-set-startup-visibility ()
7044 "Set the visibility required by startup options and properties."
7045 (cond
7046 ((eq org-startup-folded t)
7047 (org-overview))
7048 ((eq org-startup-folded 'content)
7049 (org-content))
7050 ((or (eq org-startup-folded 'showeverything)
7051 (eq org-startup-folded nil))
7052 (outline-show-all)))
7053 (unless (eq org-startup-folded 'showeverything)
7054 (when org-hide-block-startup (org-hide-block-all))
7055 (org-set-visibility-according-to-property 'no-cleanup)
7056 (org-cycle-hide-archived-subtrees 'all)
7057 (org-cycle-hide-drawers 'all)
7058 (org-cycle-show-empty-lines t)))
7060 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7061 "Switch subtree visibilities according to :VISIBILITY: property."
7062 (interactive)
7063 (org-with-wide-buffer
7064 (goto-char (point-min))
7065 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7066 (if (not (org-at-property-p)) (outline-next-heading)
7067 (let ((state (match-string 3)))
7068 (save-excursion
7069 (org-back-to-heading t)
7070 (outline-hide-subtree)
7071 (org-reveal)
7072 (cond
7073 ((equal state "folded")
7074 (outline-hide-subtree))
7075 ((equal state "children")
7076 (org-show-hidden-entry)
7077 (org-show-children))
7078 ((equal state "content")
7079 (save-excursion
7080 (save-restriction
7081 (org-narrow-to-subtree)
7082 (org-content))))
7083 ((member state '("all" "showall"))
7084 (outline-show-subtree)))))))
7085 (unless no-cleanup
7086 (org-cycle-hide-archived-subtrees 'all)
7087 (org-cycle-hide-drawers 'all)
7088 (org-cycle-show-empty-lines 'all))))
7090 ;; This function uses outline-regexp instead of the more fundamental
7091 ;; org-outline-regexp so that org-cycle-global works outside of Org
7092 ;; buffers, where outline-regexp is needed.
7093 (defun org-overview ()
7094 "Switch to overview mode, showing only top-level headlines.
7095 This shows all headlines with a level equal or greater than the level
7096 of the first headline in the buffer. This is important, because if the
7097 first headline is not level one, then (hide-sublevels 1) gives confusing
7098 results."
7099 (interactive)
7100 (save-excursion
7101 (let ((level
7102 (save-excursion
7103 (goto-char (point-min))
7104 (when (re-search-forward (concat "^" outline-regexp) nil t)
7105 (goto-char (match-beginning 0))
7106 (funcall outline-level)))))
7107 (and level (outline-hide-sublevels level)))))
7109 (defun org-content (&optional arg)
7110 "Show all headlines in the buffer, like a table of contents.
7111 With numerical argument N, show content up to level N."
7112 (interactive "P")
7113 (org-overview)
7114 (save-excursion
7115 ;; Visit all headings and show their offspring
7116 (and (integerp arg) (org-overview))
7117 (goto-char (point-max))
7118 (catch 'exit
7119 (while (and (progn (condition-case nil
7120 (outline-previous-visible-heading 1)
7121 (error (goto-char (point-min))))
7123 (looking-at org-outline-regexp))
7124 (if (integerp arg)
7125 (org-show-children (1- arg))
7126 (outline-show-branches))
7127 (when (bobp) (throw 'exit nil))))))
7129 (defun org-optimize-window-after-visibility-change (state)
7130 "Adjust the window after a change in outline visibility.
7131 This function is the default value of the hook `org-cycle-hook'."
7132 (when (get-buffer-window (current-buffer))
7133 (cond
7134 ((eq state 'content) nil)
7135 ((eq state 'all) nil)
7136 ((eq state 'folded) nil)
7137 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7138 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7140 (defun org-remove-empty-overlays-at (pos)
7141 "Remove outline overlays that do not contain non-white stuff."
7142 (dolist (o (overlays-at pos))
7143 (and (eq 'outline (overlay-get o 'invisible))
7144 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7145 (overlay-end o))))
7146 (delete-overlay o))))
7148 (defun org-clean-visibility-after-subtree-move ()
7149 "Fix visibility issues after moving a subtree."
7150 ;; First, find a reasonable region to look at:
7151 ;; Start two siblings above, end three below
7152 (let* ((beg (save-excursion
7153 (and (org-get-last-sibling)
7154 (org-get-last-sibling))
7155 (point)))
7156 (end (save-excursion
7157 (and (org-get-next-sibling)
7158 (org-get-next-sibling)
7159 (org-get-next-sibling))
7160 (if (org-at-heading-p)
7161 (point-at-eol)
7162 (point))))
7163 (level (looking-at "\\*+"))
7164 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7165 (save-excursion
7166 (save-restriction
7167 (narrow-to-region beg end)
7168 (when re
7169 ;; Properly fold already folded siblings
7170 (goto-char (point-min))
7171 (while (re-search-forward re nil t)
7172 (when (and (not (outline-invisible-p))
7173 (save-excursion
7174 (goto-char (point-at-eol)) (outline-invisible-p)))
7175 (outline-hide-entry))))
7176 (org-cycle-show-empty-lines 'overview)
7177 (org-cycle-hide-drawers 'overview)))))
7179 (defun org-cycle-show-empty-lines (state)
7180 "Show empty lines above all visible headlines.
7181 The region to be covered depends on STATE when called through
7182 `org-cycle-hook'. Lisp program can use t for STATE to get the
7183 entire buffer covered. Note that an empty line is only shown if there
7184 are at least `org-cycle-separator-lines' empty lines before the headline."
7185 (when (/= org-cycle-separator-lines 0)
7186 (save-excursion
7187 (let* ((n (abs org-cycle-separator-lines))
7188 (re (cond
7189 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7190 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7191 (t (let ((ns (number-to-string (- n 2))))
7192 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7193 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7194 beg end)
7195 (cond
7196 ((memq state '(overview contents t))
7197 (setq beg (point-min) end (point-max)))
7198 ((memq state '(children folded))
7199 (setq beg (point)
7200 end (progn (org-end-of-subtree t t)
7201 (line-beginning-position 2)))))
7202 (when beg
7203 (goto-char beg)
7204 (while (re-search-forward re end t)
7205 (unless (get-char-property (match-end 1) 'invisible)
7206 (let ((e (match-end 1))
7207 (b (if (>= org-cycle-separator-lines 0)
7208 (match-beginning 1)
7209 (save-excursion
7210 (goto-char (match-beginning 0))
7211 (skip-chars-backward " \t\n")
7212 (line-end-position)))))
7213 (outline-flag-region b e nil))))))))
7214 ;; Never hide empty lines at the end of the file.
7215 (save-excursion
7216 (goto-char (point-max))
7217 (outline-previous-heading)
7218 (outline-end-of-heading)
7219 (when (and (looking-at "[ \t\n]+")
7220 (= (match-end 0) (point-max)))
7221 (outline-flag-region (point) (match-end 0) nil))))
7223 (defun org-show-empty-lines-in-parent ()
7224 "Move to the parent and re-show empty lines before visible headlines."
7225 (save-excursion
7226 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7227 (org-cycle-show-empty-lines context))))
7229 (defun org-files-list ()
7230 "Return `org-agenda-files' list, plus all open Org files.
7231 This is useful for operations that need to scan all of a user's
7232 open and agenda-wise Org files."
7233 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7234 (dolist (buf (buffer-list))
7235 (with-current-buffer buf
7236 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7237 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7238 files))
7240 (defsubst org-entry-beginning-position ()
7241 "Return the beginning position of the current entry."
7242 (save-excursion (org-back-to-heading t) (point)))
7244 (defsubst org-entry-end-position ()
7245 "Return the end position of the current entry."
7246 (save-excursion (outline-next-heading) (point)))
7248 (defun org-cycle-hide-drawers (state &optional exceptions)
7249 "Re-hide all drawers after a visibility state change.
7250 When non-nil, optional argument EXCEPTIONS is a list of strings
7251 specifying which drawers should not be hidden."
7252 (when (and (derived-mode-p 'org-mode)
7253 (not (memq state '(overview folded contents))))
7254 (save-excursion
7255 (let* ((globalp (memq state '(contents all)))
7256 (beg (if globalp (point-min) (point)))
7257 (end (if globalp (point-max)
7258 (if (eq state 'children)
7259 (save-excursion (outline-next-heading) (point))
7260 (org-end-of-subtree t)))))
7261 (goto-char beg)
7262 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7263 (unless (member-ignore-case (match-string 1) exceptions)
7264 (let ((drawer (org-element-at-point)))
7265 (when (memq (org-element-type drawer) '(drawer property-drawer))
7266 (org-flag-drawer t drawer)
7267 ;; Make sure to skip drawer entirely or we might flag
7268 ;; it another time when matching its ending line with
7269 ;; `org-drawer-regexp'.
7270 (goto-char (org-element-property :end drawer))))))))))
7272 (defun org-flag-drawer (flag &optional element)
7273 "When FLAG is non-nil, hide the drawer we are at.
7274 Otherwise make it visible. When optional argument ELEMENT is
7275 a parsed drawer, as returned by `org-element-at-point', hide or
7276 show that drawer instead."
7277 (let ((drawer (or element
7278 (and (save-excursion
7279 (beginning-of-line)
7280 (looking-at-p org-drawer-regexp))
7281 (org-element-at-point)))))
7282 (when (memq (org-element-type drawer) '(drawer property-drawer))
7283 (let ((post (org-element-property :post-affiliated drawer)))
7284 (save-excursion
7285 (outline-flag-region
7286 (progn (goto-char post) (line-end-position))
7287 (progn (goto-char (org-element-property :end drawer))
7288 (skip-chars-backward " \r\t\n")
7289 (line-end-position))
7290 flag))
7291 ;; When the drawer is hidden away, make sure point lies in
7292 ;; a visible part of the buffer.
7293 (when (and flag (> (line-beginning-position) post))
7294 (goto-char post))))))
7296 (defun org-subtree-end-visible-p ()
7297 "Is the end of the current subtree visible?"
7298 (pos-visible-in-window-p
7299 (save-excursion (org-end-of-subtree t) (point))))
7301 (defun org-first-headline-recenter ()
7302 "Move cursor to the first headline and recenter the headline."
7303 (let ((window (get-buffer-window)))
7304 (when window
7305 (goto-char (point-min))
7306 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7307 (set-window-start window (line-beginning-position))))))
7309 ;;; Saving and restoring visibility
7311 (defun org-outline-overlay-data (&optional use-markers)
7312 "Return a list of the locations of all outline overlays.
7313 These are overlays with the `invisible' property value `outline'.
7314 The return value is a list of cons cells, with start and stop
7315 positions for each overlay.
7316 If USE-MARKERS is set, return the positions as markers."
7317 (let (beg end)
7318 (org-with-wide-buffer
7319 (delq nil
7320 (mapcar (lambda (o)
7321 (when (eq (overlay-get o 'invisible) 'outline)
7322 (setq beg (overlay-start o)
7323 end (overlay-end o))
7324 (and beg end (> end beg)
7325 (if use-markers
7326 (cons (copy-marker beg)
7327 (copy-marker end t))
7328 (cons beg end)))))
7329 (overlays-in (point-min) (point-max)))))))
7331 (defun org-set-outline-overlay-data (data)
7332 "Create visibility overlays for all positions in DATA.
7333 DATA should have been made by `org-outline-overlay-data'."
7334 (org-with-wide-buffer
7335 (outline-show-all)
7336 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7338 ;;; Folding of blocks
7340 (defvar-local org-hide-block-overlays nil
7341 "Overlays hiding blocks.")
7343 (defun org-block-map (function &optional start end)
7344 "Call FUNCTION at the head of all source blocks in the current buffer.
7345 Optional arguments START and END can be used to limit the range."
7346 (let ((start (or start (point-min)))
7347 (end (or end (point-max))))
7348 (save-excursion
7349 (goto-char start)
7350 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7351 (save-excursion
7352 (save-match-data
7353 (goto-char (match-beginning 0))
7354 (funcall function)))))))
7356 (defun org-hide-block-toggle-all ()
7357 "Toggle the visibility of all blocks in the current buffer."
7358 (org-block-map 'org-hide-block-toggle))
7360 (defun org-hide-block-all ()
7361 "Fold all blocks in the current buffer."
7362 (interactive)
7363 (org-show-block-all)
7364 (org-block-map 'org-hide-block-toggle-maybe))
7366 (defun org-show-block-all ()
7367 "Unfold all blocks in the current buffer."
7368 (interactive)
7369 (mapc #'delete-overlay org-hide-block-overlays)
7370 (setq org-hide-block-overlays nil))
7372 (defun org-hide-block-toggle-maybe ()
7373 "Toggle visibility of block at point.
7374 Unlike to `org-hide-block-toggle', this function does not throw
7375 an error. Return a non-nil value when toggling is successful."
7376 (interactive)
7377 (ignore-errors (org-hide-block-toggle)))
7379 (defun org-hide-block-toggle (&optional force)
7380 "Toggle the visibility of the current block.
7381 When optional argument FORCE is `off', make block visible. If it
7382 is non-nil, hide it unconditionally. Throw an error when not at
7383 a block. Return a non-nil value when toggling is successful."
7384 (interactive)
7385 (let ((element (org-element-at-point)))
7386 (unless (memq (org-element-type element)
7387 '(center-block comment-block dynamic-block example-block
7388 export-block quote-block special-block
7389 src-block verse-block))
7390 (user-error "Not at a block"))
7391 (let* ((start (save-excursion
7392 (goto-char (org-element-property :post-affiliated element))
7393 (line-end-position)))
7394 (end (save-excursion
7395 (goto-char (org-element-property :end element))
7396 (skip-chars-backward " \r\t\n")
7397 (line-end-position)))
7398 (overlays (overlays-at start)))
7399 (cond
7400 ;; Do nothing when not before or at the block opening line or
7401 ;; at the block closing line.
7402 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7403 ((and (not (eq force 'off))
7404 (not (memq t (mapcar
7405 (lambda (o)
7406 (eq (overlay-get o 'invisible) 'org-hide-block))
7407 overlays))))
7408 (let ((ov (make-overlay start end)))
7409 (overlay-put ov 'invisible 'org-hide-block)
7410 ;; Make the block accessible to `isearch'.
7411 (overlay-put
7412 ov 'isearch-open-invisible
7413 (lambda (ov)
7414 (when (memq ov org-hide-block-overlays)
7415 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7416 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7417 (delete-overlay ov))))
7418 (push ov org-hide-block-overlays)
7419 ;; When the block is hidden away, make sure point is left in
7420 ;; a visible part of the buffer.
7421 (when (> (line-beginning-position) start)
7422 (goto-char start)
7423 (beginning-of-line))
7424 ;; Signal successful toggling.
7426 ((or (not force) (eq force 'off))
7427 (dolist (ov overlays t)
7428 (when (memq ov org-hide-block-overlays)
7429 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7430 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7431 (delete-overlay ov))))))))
7433 ;; Remove overlays when changing major mode
7434 (add-hook 'org-mode-hook
7435 (lambda () (add-hook 'change-major-mode-hook
7436 'org-show-block-all 'append 'local)))
7438 ;;; Org-goto
7440 (defvar org-goto-window-configuration nil)
7441 (defvar org-goto-marker nil)
7442 (defvar org-goto-map)
7443 (defun org-goto-map ()
7444 "Set the keymap `org-goto'."
7445 (setq org-goto-map
7446 (let ((map (make-sparse-keymap)))
7447 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7448 mouse-drag-region universal-argument org-occur)))
7449 (dolist (cmd cmds)
7450 (substitute-key-definition cmd cmd map global-map)))
7451 (suppress-keymap map)
7452 (org-defkey map "\C-m" 'org-goto-ret)
7453 (org-defkey map [(return)] 'org-goto-ret)
7454 (org-defkey map [(left)] 'org-goto-left)
7455 (org-defkey map [(right)] 'org-goto-right)
7456 (org-defkey map [(control ?g)] 'org-goto-quit)
7457 (org-defkey map "\C-i" 'org-cycle)
7458 (org-defkey map [(tab)] 'org-cycle)
7459 (org-defkey map [(down)] 'outline-next-visible-heading)
7460 (org-defkey map [(up)] 'outline-previous-visible-heading)
7461 (if org-goto-auto-isearch
7462 (if (fboundp 'define-key-after)
7463 (define-key-after map [t] 'org-goto-local-auto-isearch)
7464 nil)
7465 (org-defkey map "q" 'org-goto-quit)
7466 (org-defkey map "n" 'outline-next-visible-heading)
7467 (org-defkey map "p" 'outline-previous-visible-heading)
7468 (org-defkey map "f" 'outline-forward-same-level)
7469 (org-defkey map "b" 'outline-backward-same-level)
7470 (org-defkey map "u" 'outline-up-heading))
7471 (org-defkey map "/" 'org-occur)
7472 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7473 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7474 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7475 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7476 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7477 map)))
7479 (defconst org-goto-help
7480 "Browse buffer copy, to find location or copy text.%s
7481 RET=jump to location C-g=quit and return to previous location
7482 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7484 (defvar org-goto-start-pos) ; dynamically scoped parameter
7486 (defun org-goto (&optional alternative-interface)
7487 "Look up a different location in the current file, keeping current visibility.
7489 When you want look-up or go to a different location in a
7490 document, the fastest way is often to fold the entire buffer and
7491 then dive into the tree. This method has the disadvantage, that
7492 the previous location will be folded, which may not be what you
7493 want.
7495 This command works around this by showing a copy of the current
7496 buffer in an indirect buffer, in overview mode. You can dive
7497 into the tree in that copy, use org-occur and incremental search
7498 to find a location. When pressing RET or `Q', the command
7499 returns to the original buffer in which the visibility is still
7500 unchanged. After RET it will also jump to the location selected
7501 in the indirect buffer and expose the headline hierarchy above.
7503 With a prefix argument, use the alternative interface: e.g., if
7504 `org-goto-interface' is `outline' use `outline-path-completion'."
7505 (interactive "P")
7506 (org-goto-map)
7507 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7508 (org-refile-use-outline-path t)
7509 (org-refile-target-verify-function nil)
7510 (interface
7511 (if (not alternative-interface)
7512 org-goto-interface
7513 (if (eq org-goto-interface 'outline)
7514 'outline-path-completion
7515 'outline)))
7516 (org-goto-start-pos (point))
7517 (selected-point
7518 (if (eq interface 'outline)
7519 (car (org-get-location (current-buffer) org-goto-help))
7520 (let ((pa (org-refile-get-location "Goto")))
7521 (org-refile-check-position pa)
7522 (nth 3 pa)))))
7523 (if selected-point
7524 (progn
7525 (org-mark-ring-push org-goto-start-pos)
7526 (goto-char selected-point)
7527 (when (or (outline-invisible-p) (org-invisible-p2))
7528 (org-show-context 'org-goto)))
7529 (message "Quit"))))
7531 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7532 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7533 (defvar org-goto-local-auto-isearch-map) ; defined below
7535 (defun org-get-location (_buf help)
7536 "Let the user select a location in current buffer.
7537 This function uses a recursive edit. It returns the selected position
7538 or nil."
7539 (org-no-popups
7540 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7541 (isearch-hide-immediately nil)
7542 (isearch-search-fun-function
7543 (lambda () 'org-goto-local-search-headings))
7544 (org-goto-selected-point org-goto-exit-command))
7545 (save-excursion
7546 (save-window-excursion
7547 (delete-other-windows)
7548 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7549 (pop-to-buffer-same-window
7550 (condition-case nil
7551 (make-indirect-buffer (current-buffer) "*org-goto*")
7552 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7553 (with-output-to-temp-buffer "*Org Help*"
7554 (princ (format help (if org-goto-auto-isearch
7555 " Just type for auto-isearch."
7556 " n/p/f/b/u to navigate, q to quit."))))
7557 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7558 (setq buffer-read-only nil)
7559 (let ((org-startup-truncated t)
7560 (org-startup-folded nil)
7561 (org-startup-align-all-tables nil))
7562 (org-mode)
7563 (org-overview))
7564 (setq buffer-read-only t)
7565 (if (and (boundp 'org-goto-start-pos)
7566 (integer-or-marker-p org-goto-start-pos))
7567 (progn (goto-char org-goto-start-pos)
7568 (when (outline-invisible-p)
7569 (org-show-set-visibility 'lineage)))
7570 (goto-char (point-min)))
7571 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7572 (message "Select location and press RET")
7573 (use-local-map org-goto-map)
7574 (recursive-edit)))
7575 (kill-buffer "*org-goto*")
7576 (cons org-goto-selected-point org-goto-exit-command))))
7578 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7579 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7580 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7581 (if (fboundp 'isearch-other-control-char)
7582 (progn
7583 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7584 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7585 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7586 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7587 (define-key org-goto-local-auto-isearch-map [return] nil))
7589 (defun org-goto-local-search-headings (string bound noerror)
7590 "Search and make sure that any matches are in headlines."
7591 (catch 'return
7592 (while (if isearch-forward
7593 (search-forward string bound noerror)
7594 (search-backward string bound noerror))
7595 (when (save-match-data
7596 (and (save-excursion
7597 (beginning-of-line)
7598 (looking-at org-complex-heading-regexp))
7599 (or (not (match-beginning 5))
7600 (< (point) (match-beginning 5)))))
7601 (throw 'return (point))))))
7603 (defun org-goto-local-auto-isearch ()
7604 "Start isearch."
7605 (interactive)
7606 (goto-char (point-min))
7607 (let ((keys (this-command-keys)))
7608 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7609 (isearch-mode t)
7610 (isearch-process-search-char (string-to-char keys)))))
7612 (defun org-goto-ret (&optional _arg)
7613 "Finish `org-goto' by going to the new location."
7614 (interactive "P")
7615 (setq org-goto-selected-point (point))
7616 (setq org-goto-exit-command 'return)
7617 (throw 'exit nil))
7619 (defun org-goto-left ()
7620 "Finish `org-goto' by going to the new location."
7621 (interactive)
7622 (if (org-at-heading-p)
7623 (progn
7624 (beginning-of-line 1)
7625 (setq org-goto-selected-point (point)
7626 org-goto-exit-command 'left)
7627 (throw 'exit nil))
7628 (user-error "Not on a heading")))
7630 (defun org-goto-right ()
7631 "Finish `org-goto' by going to the new location."
7632 (interactive)
7633 (if (org-at-heading-p)
7634 (progn
7635 (setq org-goto-selected-point (point)
7636 org-goto-exit-command 'right)
7637 (throw 'exit nil))
7638 (user-error "Not on a heading")))
7640 (defun org-goto-quit ()
7641 "Finish `org-goto' without cursor motion."
7642 (interactive)
7643 (setq org-goto-selected-point nil)
7644 (setq org-goto-exit-command 'quit)
7645 (throw 'exit nil))
7647 ;;; Indirect buffer display of subtrees
7649 (defvar org-indirect-dedicated-frame nil
7650 "This is the frame being used for indirect tree display.")
7651 (defvar org-last-indirect-buffer nil)
7653 (defun org-tree-to-indirect-buffer (&optional arg)
7654 "Create indirect buffer and narrow it to current subtree.
7656 With a numerical prefix ARG, go up to this level and then take that tree.
7657 If ARG is negative, go up that many levels.
7659 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7660 indirect buffer previously made with this command, to avoid proliferation of
7661 indirect buffers. However, when you call the command with a \
7662 `\\[universal-argument]' prefix, or
7663 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7664 so that you can work with several indirect buffers at the same time. If
7665 `org-indirect-buffer-display' is `dedicated-frame', the \
7666 `\\[universal-argument]' prefix also
7667 requests that a new frame be made for the new buffer, so that the dedicated
7668 frame is not changed."
7669 (interactive "P")
7670 (let ((cbuf (current-buffer))
7671 (cwin (selected-window))
7672 (pos (point))
7673 beg end level heading ibuf)
7674 (save-excursion
7675 (org-back-to-heading t)
7676 (when (numberp arg)
7677 (setq level (org-outline-level))
7678 (when (< arg 0) (setq arg (+ level arg)))
7679 (while (> (setq level (org-outline-level)) arg)
7680 (org-up-heading-safe)))
7681 (setq beg (point)
7682 heading (org-get-heading 'no-tags))
7683 (org-end-of-subtree t t)
7684 (when (org-at-heading-p) (backward-char 1))
7685 (setq end (point)))
7686 (when (and (buffer-live-p org-last-indirect-buffer)
7687 (not (eq org-indirect-buffer-display 'new-frame))
7688 (not arg))
7689 (kill-buffer org-last-indirect-buffer))
7690 (setq ibuf (org-get-indirect-buffer cbuf heading)
7691 org-last-indirect-buffer ibuf)
7692 (cond
7693 ((or (eq org-indirect-buffer-display 'new-frame)
7694 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7695 (select-frame (make-frame))
7696 (delete-other-windows)
7697 (pop-to-buffer-same-window ibuf)
7698 (org-set-frame-title heading))
7699 ((eq org-indirect-buffer-display 'dedicated-frame)
7700 (raise-frame
7701 (select-frame (or (and org-indirect-dedicated-frame
7702 (frame-live-p org-indirect-dedicated-frame)
7703 org-indirect-dedicated-frame)
7704 (setq org-indirect-dedicated-frame (make-frame)))))
7705 (delete-other-windows)
7706 (pop-to-buffer-same-window ibuf)
7707 (org-set-frame-title (concat "Indirect: " heading)))
7708 ((eq org-indirect-buffer-display 'current-window)
7709 (pop-to-buffer-same-window ibuf))
7710 ((eq org-indirect-buffer-display 'other-window)
7711 (pop-to-buffer ibuf))
7712 (t (error "Invalid value")))
7713 (narrow-to-region beg end)
7714 (outline-show-all)
7715 (goto-char pos)
7716 (run-hook-with-args 'org-cycle-hook 'all)
7717 (and (window-live-p cwin) (select-window cwin))))
7719 (defun org-get-indirect-buffer (&optional buffer heading)
7720 (setq buffer (or buffer (current-buffer)))
7721 (let ((n 1) (base (buffer-name buffer)) bname)
7722 (while (buffer-live-p
7723 (get-buffer
7724 (setq bname
7725 (concat base "-"
7726 (if heading (concat heading "-" (number-to-string n))
7727 (number-to-string n))))))
7728 (setq n (1+ n)))
7729 (condition-case nil
7730 (make-indirect-buffer buffer bname 'clone)
7731 (error (make-indirect-buffer buffer bname)))))
7733 (defun org-set-frame-title (title)
7734 "Set the title of the current frame to the string TITLE."
7735 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7737 ;;;; Structure editing
7739 ;;; Inserting headlines
7741 (defun org--line-empty-p (n)
7742 "Is the Nth next line empty?
7744 Counts the current line as N = 1 and the previous line as N = 0;
7745 see `beginning-of-line'."
7746 (save-excursion
7747 (and (not (bobp))
7748 (or (beginning-of-line n) t)
7749 (save-match-data
7750 (looking-at "[ \t]*$")))))
7752 (defun org-previous-line-empty-p ()
7753 "Is the previous line a blank line?
7754 When NEXT is non-nil, check the next line instead."
7755 (org--line-empty-p 0))
7757 (defun org-next-line-empty-p ()
7758 "Is the previous line a blank line?
7759 When NEXT is non-nil, check the next line instead."
7760 (org--line-empty-p 2))
7762 (defun org--blank-before-heading-p (&optional parent)
7763 "Non-nil when an empty line should precede a new heading here.
7764 When optional argument PARENT is non-nil, consider parent
7765 headline instead of current one."
7766 (pcase (assq 'heading org-blank-before-new-entry)
7767 (`(heading . auto)
7768 (save-excursion
7769 (org-with-limited-levels
7770 (unless (and (org-before-first-heading-p)
7771 (not (outline-next-heading)))
7772 (org-back-to-heading t)
7773 (when parent (org-up-heading-safe))
7774 (cond ((not (bobp))
7775 (org-previous-line-empty-p))
7776 ((outline-next-heading)
7777 (org-previous-line-empty-p))
7778 ;; Ignore trailing spaces on last buffer line.
7779 ((progn (skip-chars-backward " \t") (bolp))
7780 (org-previous-line-empty-p))
7781 (t nil))))))
7782 (`(heading . ,value) value)
7783 (_ nil)))
7785 (defun org-insert-heading (&optional arg invisible-ok top)
7786 "Insert a new heading or an item with the same depth at point.
7788 If point is at the beginning of a heading, insert a new heading
7789 or a new headline above the current one. When at the beginning
7790 of a regular line of text, turn it into a heading.
7792 If point is in the middle of a line, split it and create a new
7793 headline with the text in the current line after point (see
7794 `org-M-RET-may-split-line' on how to modify this behavior). As
7795 a special case, on a headline, splitting can only happen on the
7796 title itself. E.g., this excludes breaking stars or tags.
7798 With a `\\[universal-argument]' prefix, set \
7799 `org-insert-heading-respect-content' to
7800 a non-nil value for the duration of the command. This forces the
7801 insertion of a heading after the current subtree, independently
7802 on the location of point.
7804 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7805 insert the heading at the end of the tree
7806 above the current heading. For example, if point is within a
7807 2nd-level heading, then it will insert a 2nd-level heading at
7808 the end of the 1st-level parent subtree.
7810 When INVISIBLE-OK is set, stop at invisible headlines when going
7811 back. This is important for non-interactive uses of the
7812 command.
7814 When optional argument TOP is non-nil, insert a level 1 heading,
7815 unconditionally."
7816 (interactive "P")
7817 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7818 (level (org-current-level))
7819 (stars (make-string (if (and level (not top)) level 1) ?*)))
7820 (cond
7821 ((or org-insert-heading-respect-content
7822 (member arg '((4) (16)))
7823 (and (not invisible-ok)
7824 (invisible-p (max (1- (point)) (point-min)))))
7825 ;; Position point at the location of insertion.
7826 (if (not level) ;before first headline
7827 (org-with-limited-levels (outline-next-heading))
7828 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7829 ;; is nil.
7830 (org-with-limited-levels (org-back-to-heading invisible-ok))
7831 (cond ((equal arg '(16))
7832 (org-up-heading-safe)
7833 (org-end-of-subtree t t))
7835 (org-end-of-subtree t t))))
7836 (unless (bolp) (insert "\n")) ;ensure final newline
7837 (unless (and blank? (org-previous-line-empty-p))
7838 (org-N-empty-lines-before-current (if blank? 1 0)))
7839 (insert stars " \n")
7840 (forward-char -1))
7841 ;; At a headline...
7842 ((org-at-heading-p)
7843 (cond ((bolp)
7844 (when blank? (save-excursion (insert "\n")))
7845 (save-excursion (insert stars " \n"))
7846 (unless (and blank? (org-previous-line-empty-p))
7847 (org-N-empty-lines-before-current (if blank? 1 0)))
7848 (end-of-line))
7849 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7850 (org-match-line org-complex-heading-regexp)
7851 (org-pos-in-match-range (point) 4))
7852 ;; Grab the text that should moved to the new headline.
7853 ;; Preserve tags.
7854 (let ((split (delete-and-extract-region (point) (match-end 4))))
7855 (if (looking-at "[ \t]*$") (replace-match "")
7856 (org-set-tags nil t))
7857 (end-of-line)
7858 (when blank? (insert "\n"))
7859 (insert "\n" stars " ")
7860 (when (org-string-nw-p split) (insert split))
7861 (when (eobp) (save-excursion (insert "\n")))))
7863 (end-of-line)
7864 (when blank? (insert "\n"))
7865 (insert "\n" stars " ")
7866 (when (eobp) (save-excursion (insert "\n"))))))
7867 ;; On regular text, turn line into a headline or split, if
7868 ;; appropriate.
7869 ((bolp)
7870 (insert stars " ")
7871 (unless (and blank? (org-previous-line-empty-p))
7872 (org-N-empty-lines-before-current (if blank? 1 0))))
7874 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7875 (end-of-line))
7876 (insert "\n" stars " ")
7877 (unless (and blank? (org-previous-line-empty-p))
7878 (org-N-empty-lines-before-current (if blank? 1 0))))))
7879 (run-hooks 'org-insert-heading-hook))
7881 (defun org-N-empty-lines-before-current (n)
7882 "Make the number of empty lines before current exactly N.
7883 So this will delete or add empty lines."
7884 (save-excursion
7885 (beginning-of-line)
7886 (unless (bobp)
7887 (let ((start (save-excursion
7888 (skip-chars-backward " \r\t\n")
7889 (line-end-position))))
7890 (delete-region start (line-end-position 0))))
7891 (insert (make-string n ?\n))))
7893 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7894 "Return the heading of the current entry, without the stars.
7895 When NO-TAGS is non-nil, don't include tags.
7896 When NO-TODO is non-nil, don't include TODO keywords.
7897 When NO-PRIORITY is non-nil, don't include priority cookie.
7898 When NO-COMMENT is non-nil, don't include COMMENT string."
7899 (save-excursion
7900 (org-back-to-heading t)
7901 (let ((case-fold-search nil))
7902 (looking-at org-complex-heading-regexp)
7903 (let ((todo (and (not no-todo) (match-string 2)))
7904 (priority (and (not no-priority) (match-string 3)))
7905 (headline (pcase (match-string 4)
7906 (`nil "")
7907 ((and (guard no-comment) h)
7908 (replace-regexp-in-string
7909 (eval-when-compile
7910 (format "\\`%s[ \t]+" org-comment-string))
7911 "" h))
7912 (h h)))
7913 (tags (and (not no-tags) (match-string 5))))
7914 (mapconcat #'identity
7915 (delq nil (list todo priority headline tags))
7916 " ")))))
7918 (defvar orgstruct-mode) ; defined below
7920 (defun org-heading-components ()
7921 "Return the components of the current heading.
7922 This is a list with the following elements:
7923 - the level as an integer
7924 - the reduced level, different if `org-odd-levels-only' is set.
7925 - the TODO keyword, or nil
7926 - the priority character, like ?A, or nil if no priority is given
7927 - the headline text itself, or the tags string if no headline text
7928 - the tags string, or nil."
7929 (save-excursion
7930 (org-back-to-heading t)
7931 (when (let (case-fold-search)
7932 (looking-at
7933 (if orgstruct-mode
7934 org-heading-regexp
7935 org-complex-heading-regexp)))
7936 (if orgstruct-mode
7937 (list (length (match-string 1))
7938 (org-reduced-level (length (match-string 1)))
7941 (match-string 2)
7942 nil)
7943 (list (length (match-string 1))
7944 (org-reduced-level (length (match-string 1)))
7945 (match-string-no-properties 2)
7946 (and (match-end 3) (aref (match-string 3) 2))
7947 (match-string-no-properties 4)
7948 (match-string-no-properties 5))))))
7950 (defun org-get-entry ()
7951 "Get the entry text, after heading, entire subtree."
7952 (save-excursion
7953 (org-back-to-heading t)
7954 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7956 (defun org-edit-headline (&optional heading)
7957 "Edit the current headline.
7958 Set it to HEADING when provided."
7959 (interactive)
7960 (org-with-wide-buffer
7961 (org-back-to-heading t)
7962 (let ((case-fold-search nil))
7963 (when (looking-at org-complex-heading-regexp)
7964 (let* ((old (match-string-no-properties 4))
7965 (new (save-match-data
7966 (org-trim (or heading (read-string "Edit: " old))))))
7967 (unless (equal old new)
7968 (if old (replace-match new t t nil 4)
7969 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7970 (insert " " new))
7971 (org-set-tags nil t)
7972 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7974 (defun org-insert-heading-after-current ()
7975 "Insert a new heading with same level as current, after current subtree."
7976 (interactive)
7977 (org-back-to-heading)
7978 (org-insert-heading)
7979 (org-move-subtree-down)
7980 (end-of-line 1))
7982 (defun org-insert-heading-respect-content (&optional invisible-ok)
7983 "Insert heading with `org-insert-heading-respect-content' set to t."
7984 (interactive)
7985 (org-insert-heading '(4) invisible-ok))
7987 (defun org-insert-todo-heading-respect-content (&optional force-state)
7988 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7989 (interactive)
7990 (org-insert-todo-heading force-state '(4)))
7992 (defun org-insert-todo-heading (arg &optional force-heading)
7993 "Insert a new heading with the same level and TODO state as current heading.
7995 If the heading has no TODO state, or if the state is DONE, use
7996 the first state (TODO by default). Also with one prefix arg,
7997 force first state. With two prefix args, force inserting at the
7998 end of the parent subtree.
8000 When called at a plain list item, insert a new item with an
8001 unchecked check box."
8002 (interactive "P")
8003 (when (or force-heading (not (org-insert-item 'checkbox)))
8004 (org-insert-heading (or (and (equal arg '(16)) '(16))
8005 force-heading))
8006 (save-excursion
8007 (org-back-to-heading)
8008 (outline-previous-heading)
8009 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8010 (let* ((new-mark-x
8011 (if (or (equal arg '(4))
8012 (not (match-beginning 2))
8013 (member (match-string 2) org-done-keywords))
8014 (car org-todo-keywords-1)
8015 (match-string 2)))
8016 (new-mark
8018 (run-hook-with-args-until-success
8019 'org-todo-get-default-hook new-mark-x nil)
8020 new-mark-x)))
8021 (beginning-of-line 1)
8022 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8023 (if org-treat-insert-todo-heading-as-state-change
8024 (org-todo new-mark)
8025 (insert new-mark " "))))
8026 (when org-provide-todo-statistics
8027 (org-update-parent-todo-statistics))))
8029 (defun org-insert-subheading (arg)
8030 "Insert a new subheading and demote it.
8031 Works for outline headings and for plain lists alike."
8032 (interactive "P")
8033 (org-insert-heading arg)
8034 (cond
8035 ((org-at-heading-p) (org-do-demote))
8036 ((org-at-item-p) (org-indent-item))))
8038 (defun org-insert-todo-subheading (arg)
8039 "Insert a new subheading with TODO keyword or checkbox and demote it.
8040 Works for outline headings and for plain lists alike."
8041 (interactive "P")
8042 (org-insert-todo-heading arg)
8043 (cond
8044 ((org-at-heading-p) (org-do-demote))
8045 ((org-at-item-p) (org-indent-item))))
8047 ;;; Promotion and Demotion
8049 (defvar org-after-demote-entry-hook nil
8050 "Hook run after an entry has been demoted.
8051 The cursor will be at the beginning of the entry.
8052 When a subtree is being demoted, the hook will be called for each node.")
8054 (defvar org-after-promote-entry-hook nil
8055 "Hook run after an entry has been promoted.
8056 The cursor will be at the beginning of the entry.
8057 When a subtree is being promoted, the hook will be called for each node.")
8059 (defun org-promote-subtree ()
8060 "Promote the entire subtree.
8061 See also `org-promote'."
8062 (interactive)
8063 (save-excursion
8064 (org-with-limited-levels (org-map-tree 'org-promote)))
8065 (org-fix-position-after-promote))
8067 (defun org-demote-subtree ()
8068 "Demote the entire subtree.
8069 See `org-demote' and `org-promote'."
8070 (interactive)
8071 (save-excursion
8072 (org-with-limited-levels (org-map-tree 'org-demote)))
8073 (org-fix-position-after-promote))
8075 (defun org-do-promote ()
8076 "Promote the current heading higher up the tree.
8077 If the region is active in `transient-mark-mode', promote all
8078 headings in the region."
8079 (interactive)
8080 (save-excursion
8081 (if (org-region-active-p)
8082 (org-map-region 'org-promote (region-beginning) (region-end))
8083 (org-promote)))
8084 (org-fix-position-after-promote))
8086 (defun org-do-demote ()
8087 "Demote the current heading lower down the tree.
8088 If the region is active in `transient-mark-mode', demote all
8089 headings in the region."
8090 (interactive)
8091 (save-excursion
8092 (if (org-region-active-p)
8093 (org-map-region 'org-demote (region-beginning) (region-end))
8094 (org-demote)))
8095 (org-fix-position-after-promote))
8097 (defun org-fix-position-after-promote ()
8098 "Fix cursor position and indentation after demoting/promoting."
8099 (let ((pos (point)))
8100 (when (save-excursion
8101 (beginning-of-line)
8102 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8103 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8104 (cond ((eobp) (insert " "))
8105 ((eolp) (insert " "))
8106 ((equal (char-after) ?\s) (forward-char 1))))))
8108 (defun org-current-level ()
8109 "Return the level of the current entry, or nil if before the first headline.
8110 The level is the number of stars at the beginning of the
8111 headline. Use `org-reduced-level' to remove the effect of
8112 `org-odd-levels'. Unlike to `org-outline-level', this function
8113 ignores inlinetasks."
8114 (let ((level (org-with-limited-levels (org-outline-level))))
8115 (and (> level 0) level)))
8117 (defun org-get-previous-line-level ()
8118 "Return the outline depth of the last headline before the current line.
8119 Returns 0 for the first headline in the buffer, and nil if before the
8120 first headline."
8121 (and (org-current-level)
8122 (or (and (/= (line-beginning-position) (point-min))
8123 (save-excursion (beginning-of-line 0) (org-current-level)))
8124 0)))
8126 (defun org-reduced-level (l)
8127 "Compute the effective level of a heading.
8128 This takes into account the setting of `org-odd-levels-only'."
8129 (cond
8130 ((zerop l) 0)
8131 (org-odd-levels-only (1+ (floor (/ l 2))))
8132 (t l)))
8134 (defun org-level-increment ()
8135 "Return the number of stars that will be added or removed at a
8136 time to headlines when structure editing, based on the value of
8137 `org-odd-levels-only'."
8138 (if org-odd-levels-only 2 1))
8140 (defun org-get-valid-level (level &optional change)
8141 "Rectify a level change under the influence of `org-odd-levels-only'.
8142 LEVEL is a current level, CHANGE is by how much the level should
8143 be modified. Even if CHANGE is nil, LEVEL may be returned
8144 modified because even level numbers will become the next higher
8145 odd number. Returns values greater than 0."
8146 (if org-odd-levels-only
8147 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8148 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8149 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8150 (max 1 (+ level (or change 0)))))
8152 (defun org-promote ()
8153 "Promote the current heading higher up the tree."
8154 (org-with-wide-buffer
8155 (org-back-to-heading t)
8156 (let* ((after-change-functions (remq 'flyspell-after-change-function
8157 after-change-functions))
8158 (level (save-match-data (funcall outline-level)))
8159 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8160 (diff (abs (- level (length up-head) -1))))
8161 (cond
8162 ((and (= level 1) org-allow-promoting-top-level-subtree)
8163 (replace-match "# " nil t))
8164 ((= level 1)
8165 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8166 (t (replace-match up-head nil t)))
8167 (unless (= level 1)
8168 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8169 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8170 (run-hooks 'org-after-promote-entry-hook))))
8172 (defun org-demote ()
8173 "Demote the current heading lower down the tree."
8174 (org-with-wide-buffer
8175 (org-back-to-heading t)
8176 (let* ((after-change-functions (remq 'flyspell-after-change-function
8177 after-change-functions))
8178 (level (save-match-data (funcall outline-level)))
8179 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8180 (diff (abs (- level (length down-head) -1))))
8181 (replace-match down-head nil t)
8182 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8183 (when org-adapt-indentation (org-fixup-indentation diff))
8184 (run-hooks 'org-after-demote-entry-hook))))
8186 (defun org-cycle-level ()
8187 "Cycle the level of an empty headline through possible states.
8188 This goes first to child, then to parent, level, then up the hierarchy.
8189 After top level, it switches back to sibling level."
8190 (interactive)
8191 (let ((org-adapt-indentation nil))
8192 (when (org-point-at-end-of-empty-headline)
8193 (setq this-command 'org-cycle-level) ; Only needed for caching
8194 (let ((cur-level (org-current-level))
8195 (prev-level (org-get-previous-line-level)))
8196 (cond
8197 ;; If first headline in file, promote to top-level.
8198 ((= prev-level 0)
8199 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8200 do (org-do-promote)))
8201 ;; If same level as prev, demote one.
8202 ((= prev-level cur-level)
8203 (org-do-demote))
8204 ;; If parent is top-level, promote to top level if not already.
8205 ((= prev-level 1)
8206 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8207 do (org-do-promote)))
8208 ;; If top-level, return to prev-level.
8209 ((= cur-level 1)
8210 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8211 do (org-do-demote)))
8212 ;; If less than prev-level, promote one.
8213 ((< cur-level prev-level)
8214 (org-do-promote))
8215 ;; If deeper than prev-level, promote until higher than
8216 ;; prev-level.
8217 ((> cur-level prev-level)
8218 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8219 do (org-do-promote))))
8220 t))))
8222 (defun org-map-tree (fun)
8223 "Call FUN for every heading underneath the current one."
8224 (org-back-to-heading t)
8225 (let ((level (funcall outline-level)))
8226 (save-excursion
8227 (funcall fun)
8228 (while (and (progn
8229 (outline-next-heading)
8230 (> (funcall outline-level) level))
8231 (not (eobp)))
8232 (funcall fun)))))
8234 (defun org-map-region (fun beg end)
8235 "Call FUN for every heading between BEG and END."
8236 (let ((org-ignore-region t))
8237 (save-excursion
8238 (setq end (copy-marker end))
8239 (goto-char beg)
8240 (when (and (re-search-forward org-outline-regexp-bol nil t)
8241 (< (point) end))
8242 (funcall fun))
8243 (while (and (progn
8244 (outline-next-heading)
8245 (< (point) end))
8246 (not (eobp)))
8247 (funcall fun)))))
8249 (defun org-fixup-indentation (diff)
8250 "Change the indentation in the current entry by DIFF.
8252 DIFF is an integer. Indentation is done according to the
8253 following rules:
8255 - Planning information and property drawers are always indented
8256 according to the new level of the headline;
8258 - Footnote definitions and their contents are ignored;
8260 - Inlinetasks' boundaries are not shifted;
8262 - Empty lines are ignored;
8264 - Other lines' indentation are shifted by DIFF columns, unless
8265 it would introduce a structural change in the document, in
8266 which case no shifting is done at all.
8268 Assume point is at a heading or an inlinetask beginning."
8269 (org-with-wide-buffer
8270 (narrow-to-region (line-beginning-position)
8271 (save-excursion
8272 (if (org-with-limited-levels (org-at-heading-p))
8273 (org-with-limited-levels (outline-next-heading))
8274 (org-inlinetask-goto-end))
8275 (point)))
8276 (forward-line)
8277 ;; Indent properly planning info and property drawer.
8278 (when (looking-at-p org-planning-line-re)
8279 (org-indent-line)
8280 (forward-line))
8281 (when (looking-at org-property-drawer-re)
8282 (goto-char (match-end 0))
8283 (forward-line)
8284 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8285 (catch 'no-shift
8286 (when (zerop diff) (throw 'no-shift nil))
8287 ;; If DIFF is negative, first check if a shift is possible at all
8288 ;; (e.g., it doesn't break structure). This can only happen if
8289 ;; some contents are not properly indented.
8290 (let ((case-fold-search t))
8291 (when (< diff 0)
8292 (let ((diff (- diff))
8293 (forbidden-re (concat org-outline-regexp
8294 "\\|"
8295 (substring org-footnote-definition-re 1))))
8296 (save-excursion
8297 (while (not (eobp))
8298 (cond
8299 ((looking-at-p "[ \t]*$") (forward-line))
8300 ((and (looking-at-p org-footnote-definition-re)
8301 (let ((e (org-element-at-point)))
8302 (and (eq (org-element-type e) 'footnote-definition)
8303 (goto-char (org-element-property :end e))))))
8304 ((looking-at-p org-outline-regexp) (forward-line))
8305 ;; Give up if shifting would move before column 0 or
8306 ;; if it would introduce a headline or a footnote
8307 ;; definition.
8309 (skip-chars-forward " \t")
8310 (let ((ind (current-column)))
8311 (when (or (< ind diff)
8312 (and (= ind diff) (looking-at-p forbidden-re)))
8313 (throw 'no-shift nil)))
8314 ;; Ignore contents of example blocks and source
8315 ;; blocks if their indentation is meant to be
8316 ;; preserved. Jump to block's closing line.
8317 (beginning-of-line)
8318 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8319 (let ((e (org-element-at-point)))
8320 (and (memq (org-element-type e)
8321 '(example-block src-block))
8322 (or org-src-preserve-indentation
8323 (org-element-property :preserve-indent e))
8324 (goto-char (org-element-property :end e))
8325 (progn (skip-chars-backward " \r\t\n")
8326 (beginning-of-line)
8327 t))))
8328 (forward-line))))))))
8329 ;; Shift lines but footnote definitions, inlinetasks boundaries
8330 ;; by DIFF. Also skip contents of source or example blocks
8331 ;; when indentation is meant to be preserved.
8332 (while (not (eobp))
8333 (cond
8334 ((and (looking-at-p org-footnote-definition-re)
8335 (let ((e (org-element-at-point)))
8336 (and (eq (org-element-type e) 'footnote-definition)
8337 (goto-char (org-element-property :end e))))))
8338 ((looking-at-p org-outline-regexp) (forward-line))
8339 ((looking-at-p "[ \t]*$") (forward-line))
8341 (indent-line-to (+ (org-get-indentation) diff))
8342 (beginning-of-line)
8343 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8344 (let ((e (org-element-at-point)))
8345 (and (memq (org-element-type e)
8346 '(example-block src-block))
8347 (or org-src-preserve-indentation
8348 (org-element-property :preserve-indent e))
8349 (goto-char (org-element-property :end e))
8350 (progn (skip-chars-backward " \r\t\n")
8351 (beginning-of-line)
8352 t))))
8353 (forward-line)))))))))
8355 (defun org-convert-to-odd-levels ()
8356 "Convert an Org file with all levels allowed to one with odd levels.
8357 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8358 level 5 etc."
8359 (interactive)
8360 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8361 (let ((outline-level 'org-outline-level)
8362 (org-odd-levels-only nil) n)
8363 (save-excursion
8364 (goto-char (point-min))
8365 (while (re-search-forward "^\\*\\*+ " nil t)
8366 (setq n (- (length (match-string 0)) 2))
8367 (while (>= (setq n (1- n)) 0)
8368 (org-demote))
8369 (end-of-line 1))))))
8371 (defun org-convert-to-oddeven-levels ()
8372 "Convert an Org file with only odd levels to one with odd/even levels.
8373 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8374 file contains a section with an even level, conversion would
8375 destroy the structure of the file. An error is signaled in this
8376 case."
8377 (interactive)
8378 (goto-char (point-min))
8379 ;; First check if there are no even levels
8380 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8381 (org-show-set-visibility 'canonical)
8382 (error "Not all levels are odd in this file. Conversion not possible"))
8383 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8384 (let ((outline-regexp org-outline-regexp)
8385 (outline-level 'org-outline-level)
8386 (org-odd-levels-only nil) n)
8387 (save-excursion
8388 (goto-char (point-min))
8389 (while (re-search-forward "^\\*\\*+ " nil t)
8390 (setq n (/ (1- (length (match-string 0))) 2))
8391 (while (>= (setq n (1- n)) 0)
8392 (org-promote))
8393 (end-of-line 1))))))
8395 (defun org-tr-level (n)
8396 "Make N odd if required."
8397 (if org-odd-levels-only (1+ (/ n 2)) n))
8399 ;;; Vertical tree motion, cutting and pasting of subtrees
8401 (defun org-move-subtree-up (&optional arg)
8402 "Move the current subtree up past ARG headlines of the same level."
8403 (interactive "p")
8404 (org-move-subtree-down (- (prefix-numeric-value arg))))
8406 (defun org-move-subtree-down (&optional arg)
8407 "Move the current subtree down past ARG headlines of the same level."
8408 (interactive "p")
8409 (setq arg (prefix-numeric-value arg))
8410 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8411 'org-get-last-sibling))
8412 (ins-point (make-marker))
8413 (cnt (abs arg))
8414 (col (current-column))
8415 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8416 ;; Select the tree
8417 (org-back-to-heading)
8418 (setq beg0 (point))
8419 (save-excursion
8420 (setq ne-beg (org-back-over-empty-lines))
8421 (setq beg (point)))
8422 (save-match-data
8423 (save-excursion (outline-end-of-heading)
8424 (setq folded (outline-invisible-p)))
8425 (progn (org-end-of-subtree nil t)
8426 (unless (eobp) (backward-char))))
8427 (outline-next-heading)
8428 (setq ne-end (org-back-over-empty-lines))
8429 (setq end (point))
8430 (goto-char beg0)
8431 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8432 ;; include less whitespace
8433 (save-excursion
8434 (goto-char beg)
8435 (forward-line (- ne-beg ne-end))
8436 (setq beg (point))))
8437 ;; Find insertion point, with error handling
8438 (while (> cnt 0)
8439 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8440 (progn (goto-char beg0)
8441 (user-error "Cannot move past superior level or buffer limit")))
8442 (setq cnt (1- cnt)))
8443 (when (> arg 0)
8444 ;; Moving forward - still need to move over subtree
8445 (org-end-of-subtree t t)
8446 (save-excursion
8447 (org-back-over-empty-lines)
8448 (or (bolp) (newline))))
8449 (setq ne-ins (org-back-over-empty-lines))
8450 (move-marker ins-point (point))
8451 (setq txt (buffer-substring beg end))
8452 (org-save-markers-in-region beg end)
8453 (delete-region beg end)
8454 (org-remove-empty-overlays-at beg)
8455 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8456 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8457 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8458 (let ((bbb (point)))
8459 (insert-before-markers txt)
8460 (org-reinstall-markers-in-region bbb)
8461 (move-marker ins-point bbb))
8462 (or (bolp) (insert "\n"))
8463 (setq ins-end (point))
8464 (goto-char ins-point)
8465 (org-skip-whitespace)
8466 (when (and (< arg 0)
8467 (org-first-sibling-p)
8468 (> ne-ins ne-beg))
8469 ;; Move whitespace back to beginning
8470 (save-excursion
8471 (goto-char ins-end)
8472 (let ((kill-whole-line t))
8473 (kill-line (- ne-ins ne-beg)) (point)))
8474 (insert (make-string (- ne-ins ne-beg) ?\n)))
8475 (move-marker ins-point nil)
8476 (if folded
8477 (outline-hide-subtree)
8478 (org-show-entry)
8479 (org-show-children)
8480 (org-cycle-hide-drawers 'children))
8481 (org-clean-visibility-after-subtree-move)
8482 ;; move back to the initial column we were at
8483 (move-to-column col)))
8485 (defvar org-subtree-clip ""
8486 "Clipboard for cut and paste of subtrees.
8487 This is actually only a copy of the kill, because we use the normal kill
8488 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8490 (defvar org-subtree-clip-folded nil
8491 "Was the last copied subtree folded?
8492 This is used to fold the tree back after pasting.")
8494 (defun org-cut-subtree (&optional n)
8495 "Cut the current subtree into the clipboard.
8496 With prefix arg N, cut this many sequential subtrees.
8497 This is a short-hand for marking the subtree and then cutting it."
8498 (interactive "p")
8499 (org-copy-subtree n 'cut))
8501 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8502 "Copy the current subtree it in the clipboard.
8503 With prefix arg N, copy this many sequential subtrees.
8504 This is a short-hand for marking the subtree and then copying it.
8505 If CUT is non-nil, actually cut the subtree.
8506 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8507 of some markers in the region, even if CUT is non-nil. This is
8508 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8509 (interactive "p")
8510 (let (beg end folded (beg0 (point)))
8511 (if (called-interactively-p 'any)
8512 (org-back-to-heading nil) ; take what looks like a subtree
8513 (org-back-to-heading t)) ; take what is really there
8514 (setq beg (point))
8515 (skip-chars-forward " \t\r\n")
8516 (save-match-data
8517 (if nosubtrees
8518 (outline-next-heading)
8519 (save-excursion (outline-end-of-heading)
8520 (setq folded (outline-invisible-p)))
8521 (ignore-errors (org-forward-heading-same-level (1- n) t))
8522 (org-end-of-subtree t t)))
8523 ;; Include the end of an inlinetask
8524 (when (and (featurep 'org-inlinetask)
8525 (looking-at-p (concat (org-inlinetask-outline-regexp)
8526 "END[ \t]*$")))
8527 (end-of-line))
8528 (setq end (point))
8529 (goto-char beg0)
8530 (when (> end beg)
8531 (setq org-subtree-clip-folded folded)
8532 (when (or cut force-store-markers)
8533 (org-save-markers-in-region beg end))
8534 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8535 (setq org-subtree-clip (current-kill 0))
8536 (message "%s: Subtree(s) with %d characters"
8537 (if cut "Cut" "Copied")
8538 (length org-subtree-clip)))))
8540 (defun org-paste-subtree (&optional level tree for-yank remove)
8541 "Paste the clipboard as a subtree, with modification of headline level.
8542 The entire subtree is promoted or demoted in order to match a new headline
8543 level.
8545 If the cursor is at the beginning of a headline, the same level as
8546 that headline is used to paste the tree.
8548 If not, the new level is derived from the *visible* headings
8549 before and after the insertion point, and taken to be the inferior headline
8550 level of the two. So if the previous visible heading is level 3 and the
8551 next is level 4 (or vice versa), level 4 will be used for insertion.
8552 This makes sure that the subtree remains an independent subtree and does
8553 not swallow low level entries.
8555 You can also force a different level, either by using a numeric prefix
8556 argument, or by inserting the heading marker by hand. For example, if the
8557 cursor is after \"*****\", then the tree will be shifted to level 5.
8559 If optional TREE is given, use this text instead of the kill ring.
8561 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8562 move back over whitespace before inserting, and move point to the end of
8563 the inserted text when done.
8565 When REMOVE is non-nil, remove the subtree from the clipboard."
8566 (interactive "P")
8567 (setq tree (or tree (and kill-ring (current-kill 0))))
8568 (unless (org-kill-is-subtree-p tree)
8569 (user-error "%s"
8570 (substitute-command-keys
8571 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8572 (org-with-limited-levels
8573 (let* ((visp (not (outline-invisible-p)))
8574 (txt tree)
8575 (^re_ "\\(\\*+\\)[ \t]*")
8576 (old-level (if (string-match org-outline-regexp-bol txt)
8577 (- (match-end 0) (match-beginning 0) 1)
8578 -1))
8579 (force-level (cond (level (prefix-numeric-value level))
8580 ((and (looking-at "[ \t]*$")
8581 (string-match
8582 "^\\*+$" (buffer-substring
8583 (point-at-bol) (point))))
8584 (- (match-end 0) (match-beginning 0)))
8585 ((and (bolp)
8586 (looking-at org-outline-regexp))
8587 (- (match-end 0) (point) 1))))
8588 (previous-level (save-excursion
8589 (condition-case nil
8590 (progn
8591 (outline-previous-visible-heading 1)
8592 (if (looking-at ^re_)
8593 (- (match-end 0) (match-beginning 0) 1)
8595 (error 1))))
8596 (next-level (save-excursion
8597 (condition-case nil
8598 (progn
8599 (or (looking-at org-outline-regexp)
8600 (outline-next-visible-heading 1))
8601 (if (looking-at ^re_)
8602 (- (match-end 0) (match-beginning 0) 1)
8604 (error 1))))
8605 (new-level (or force-level (max previous-level next-level)))
8606 (shift (if (or (= old-level -1)
8607 (= new-level -1)
8608 (= old-level new-level))
8610 (- new-level old-level)))
8611 (delta (if (> shift 0) -1 1))
8612 (func (if (> shift 0) 'org-demote 'org-promote))
8613 (org-odd-levels-only nil)
8614 beg end newend)
8615 ;; Remove the forced level indicator
8616 (when force-level
8617 (delete-region (point-at-bol) (point)))
8618 ;; Paste
8619 (beginning-of-line (if (bolp) 1 2))
8620 (setq beg (point))
8621 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8622 (insert-before-markers txt)
8623 (unless (string-suffix-p "\n" txt) (insert "\n"))
8624 (setq newend (point))
8625 (org-reinstall-markers-in-region beg)
8626 (setq end (point))
8627 (goto-char beg)
8628 (skip-chars-forward " \t\n\r")
8629 (setq beg (point))
8630 (when (and (outline-invisible-p) visp)
8631 (save-excursion (outline-show-heading)))
8632 ;; Shift if necessary
8633 (unless (= shift 0)
8634 (save-restriction
8635 (narrow-to-region beg end)
8636 (while (not (= shift 0))
8637 (org-map-region func (point-min) (point-max))
8638 (setq shift (+ delta shift)))
8639 (goto-char (point-min))
8640 (setq newend (point-max))))
8641 (when (or (called-interactively-p 'interactive) for-yank)
8642 (message "Clipboard pasted as level %d subtree" new-level))
8643 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8644 kill-ring
8645 (eq org-subtree-clip (current-kill 0))
8646 org-subtree-clip-folded)
8647 ;; The tree was folded before it was killed/copied
8648 (outline-hide-subtree))
8649 (and for-yank (goto-char newend))
8650 (and remove (setq kill-ring (cdr kill-ring))))))
8652 (defun org-kill-is-subtree-p (&optional txt)
8653 "Check if the current kill is an outline subtree, or a set of trees.
8654 Returns nil if kill does not start with a headline, or if the first
8655 headline level is not the largest headline level in the tree.
8656 So this will actually accept several entries of equal levels as well,
8657 which is OK for `org-paste-subtree'.
8658 If optional TXT is given, check this string instead of the current kill."
8659 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8660 (re (org-get-limited-outline-regexp))
8661 (^re (concat "^" re))
8662 (start-level (and kill
8663 (string-match
8664 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8665 kill)
8666 (- (match-end 2) (match-beginning 2) 1)))
8667 (start (1+ (or (match-beginning 2) -1))))
8668 (if (not start-level)
8669 (progn
8670 nil) ;; does not even start with a heading
8671 (catch 'exit
8672 (while (setq start (string-match ^re kill (1+ start)))
8673 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8674 (throw 'exit nil)))
8675 t))))
8677 (defvar org-markers-to-move nil
8678 "Markers that should be moved with a cut-and-paste operation.
8679 Those markers are stored together with their positions relative to
8680 the start of the region.")
8682 (defun org-save-markers-in-region (beg end)
8683 "Check markers in region.
8684 If these markers are between BEG and END, record their position relative
8685 to BEG, so that after moving the block of text, we can put the markers back
8686 into place.
8687 This function gets called just before an entry or tree gets cut from the
8688 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8689 called immediately, to move the markers with the entries."
8690 (setq org-markers-to-move nil)
8691 (when (featurep 'org-clock)
8692 (org-clock-save-markers-for-cut-and-paste beg end))
8693 (when (featurep 'org-agenda)
8694 (org-agenda-save-markers-for-cut-and-paste beg end)))
8696 (defun org-check-and-save-marker (marker beg end)
8697 "Check if MARKER is between BEG and END.
8698 If yes, remember the marker and the distance to BEG."
8699 (when (and (marker-buffer marker)
8700 (equal (marker-buffer marker) (current-buffer))
8701 (>= marker beg) (< marker end))
8702 (push (cons marker (- marker beg)) org-markers-to-move)))
8704 (defun org-reinstall-markers-in-region (beg)
8705 "Move all remembered markers to their position relative to BEG."
8706 (dolist (x org-markers-to-move)
8707 (move-marker (car x) (+ beg (cdr x))))
8708 (setq org-markers-to-move nil))
8710 (defun org-narrow-to-subtree ()
8711 "Narrow buffer to the current subtree."
8712 (interactive)
8713 (save-excursion
8714 (save-match-data
8715 (org-with-limited-levels
8716 (narrow-to-region
8717 (progn (org-back-to-heading t) (point))
8718 (progn (org-end-of-subtree t t)
8719 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8720 (point)))))))
8722 (defun org-narrow-to-block ()
8723 "Narrow buffer to the current block."
8724 (interactive)
8725 (let* ((case-fold-search t)
8726 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8727 "^[ \t]*#\\+end_.*")))
8728 (if blockp
8729 (narrow-to-region (car blockp) (cdr blockp))
8730 (user-error "Not in a block"))))
8732 (defun org-clone-subtree-with-time-shift (n &optional shift)
8733 "Clone the task (subtree) at point N times.
8734 The clones will be inserted as siblings.
8736 In interactive use, the user will be prompted for the number of
8737 clones to be produced. If the entry has a timestamp, the user
8738 will also be prompted for a time shift, which may be a repeater
8739 as used in time stamps, for example `+3d'. To disable this,
8740 you can call the function with a universal prefix argument.
8742 When a valid repeater is given and the entry contains any time
8743 stamps, the clones will become a sequence in time, with time
8744 stamps in the subtree shifted for each clone produced. If SHIFT
8745 is nil or the empty string, time stamps will be left alone. The
8746 ID property of the original subtree is removed.
8748 In each clone, all the CLOCK entries will be removed. This
8749 prevents Org from considering that the clocked times overlap.
8751 If the original subtree did contain time stamps with a repeater,
8752 the following will happen:
8753 - the repeater will be removed in each clone
8754 - an additional clone will be produced, with the current, unshifted
8755 date(s) in the entry.
8756 - the original entry will be placed *after* all the clones, with
8757 repeater intact.
8758 - the start days in the repeater in the original entry will be shifted
8759 to past the last clone.
8760 In this way you can spell out a number of instances of a repeating task,
8761 and still retain the repeater to cover future instances of the task.
8763 As described above, N+1 clones are produced when the original
8764 subtree has a repeater. Setting N to 0, then, can be used to
8765 remove the repeater from a subtree and create a shifted clone
8766 with the original repeater."
8767 (interactive "nNumber of clones to produce: ")
8768 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8769 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8770 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8771 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8772 (shift
8773 (or shift
8774 (if (and (not (equal current-prefix-arg '(4)))
8775 (save-excursion
8776 (goto-char beg)
8777 (re-search-forward org-ts-regexp-both end-of-tree t)))
8778 (read-from-minibuffer
8779 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8780 ""))) ;No time shift
8781 (doshift
8782 (and (org-string-nw-p shift)
8783 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8784 shift)
8785 (user-error "Invalid shift specification %s" shift)))))
8786 (goto-char end-of-tree)
8787 (unless (bolp) (insert "\n"))
8788 (let* ((end (point))
8789 (template (buffer-substring beg end))
8790 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8791 (shift-what (pcase (and doshift (match-string 2 shift))
8792 (`nil nil)
8793 ("d" 'day)
8794 ("w" (setq shift-n (* 7 shift-n)) 'day)
8795 ("m" 'month)
8796 ("y" 'year)
8797 (_ (error "Unsupported time unit"))))
8798 (nmin 1)
8799 (nmax n)
8800 (n-no-remove -1)
8801 (idprop (org-entry-get nil "ID")))
8802 (when (and doshift
8803 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8804 template))
8805 (delete-region beg end)
8806 (setq end beg)
8807 (setq nmin 0)
8808 (setq nmax (1+ nmax))
8809 (setq n-no-remove nmax))
8810 (goto-char end)
8811 (cl-loop for n from nmin to nmax do
8812 (insert
8813 ;; Prepare clone.
8814 (with-temp-buffer
8815 (insert template)
8816 (org-mode)
8817 (goto-char (point-min))
8818 (org-show-subtree)
8819 (and idprop (if org-clone-delete-id
8820 (org-entry-delete nil "ID")
8821 (org-id-get-create t)))
8822 (unless (= n 0)
8823 (while (re-search-forward org-clock-line-re nil t)
8824 (delete-region (line-beginning-position)
8825 (line-beginning-position 2)))
8826 (goto-char (point-min))
8827 (while (re-search-forward org-drawer-regexp nil t)
8828 (org-remove-empty-drawer-at (point))))
8829 (goto-char (point-min))
8830 (when doshift
8831 (while (re-search-forward org-ts-regexp-both nil t)
8832 (org-timestamp-change (* n shift-n) shift-what))
8833 (unless (= n n-no-remove)
8834 (goto-char (point-min))
8835 (while (re-search-forward org-ts-regexp nil t)
8836 (save-excursion
8837 (goto-char (match-beginning 0))
8838 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8839 (delete-region (match-beginning 1) (match-end 1)))))))
8840 (buffer-string)))))
8841 (goto-char beg)))
8843 ;;; Outline Sorting
8845 (defun org-sort (with-case)
8846 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8847 Optional argument WITH-CASE means sort case-sensitively."
8848 (interactive "P")
8849 (cond
8850 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8851 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8853 (org-call-with-arg 'org-sort-entries with-case))))
8855 (defun org-sort-remove-invisible (s)
8856 "Remove invisible part of links and emphasis markers from string S."
8857 (remove-text-properties 0 (length s) org-rm-props s)
8858 (replace-regexp-in-string
8859 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8860 (replace-regexp-in-string
8861 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8862 (org-link-display-format s)
8863 t t) t t))
8865 (defvar org-priority-regexp) ; defined later in the file
8867 (defvar org-after-sorting-entries-or-items-hook nil
8868 "Hook that is run after a bunch of entries or items have been sorted.
8869 When children are sorted, the cursor is in the parent line when this
8870 hook gets called. When a region or a plain list is sorted, the cursor
8871 will be in the first entry of the sorted region/list.")
8873 (defun org-sort-entries
8874 (&optional with-case sorting-type getkey-func compare-func property)
8875 "Sort entries on a certain level of an outline tree.
8876 If there is an active region, the entries in the region are sorted.
8877 Else, if the cursor is before the first entry, sort the top-level items.
8878 Else, the children of the entry at point are sorted.
8880 Sorting can be alphabetically, numerically, by date/time as given by
8881 a time stamp, by a property, by priority order, or by a custom function.
8883 The command prompts for the sorting type unless it has been given to the
8884 function through the SORTING-TYPE argument, which needs to be a character,
8885 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8886 the precise meaning of each character:
8888 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8889 c By creation time, which is assumed to be the first inactive time stamp
8890 at the beginning of a line.
8891 d By deadline date/time.
8892 k By clocking time.
8893 n Numerically, by converting the beginning of the entry/item to a number.
8894 o By order of TODO keywords.
8895 p By priority according to the cookie.
8896 r By the value of a property.
8897 s By scheduled date/time.
8898 t By date/time, either the first active time stamp in the entry, or, if
8899 none exist, by the first inactive one.
8901 Capital letters will reverse the sort order.
8903 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8904 called with point at the beginning of the record. It must return either
8905 a string or a number that should serve as the sorting key for that record.
8907 Comparing entries ignores case by default. However, with an optional argument
8908 WITH-CASE, the sorting considers case as well.
8910 Sorting is done against the visible part of the headlines, it ignores hidden
8911 links.
8913 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8914 (interactive "P")
8915 (let ((case-func (if with-case 'identity 'downcase))
8916 (cmstr
8917 ;; The clock marker is lost when using `sort-subr', let's
8918 ;; store the clocking string.
8919 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8920 (save-excursion
8921 (goto-char org-clock-marker)
8922 (buffer-substring-no-properties (line-beginning-position)
8923 (point)))))
8924 start beg end stars re re2
8925 txt what tmp)
8926 ;; Find beginning and end of region to sort
8927 (cond
8928 ((org-region-active-p)
8929 ;; we will sort the region
8930 (setq end (region-end)
8931 what "region")
8932 (goto-char (region-beginning))
8933 (unless (org-at-heading-p) (outline-next-heading))
8934 (setq start (point)))
8935 ((or (org-at-heading-p)
8936 (ignore-errors (progn (org-back-to-heading) t)))
8937 ;; we will sort the children of the current headline
8938 (org-back-to-heading)
8939 (setq start (point)
8940 end (progn (org-end-of-subtree t t)
8941 (or (bolp) (insert "\n"))
8942 (when (>= (org-back-over-empty-lines) 1)
8943 (forward-line 1))
8944 (point))
8945 what "children")
8946 (goto-char start)
8947 (outline-show-subtree)
8948 (outline-next-heading))
8950 ;; we will sort the top-level entries in this file
8951 (goto-char (point-min))
8952 (or (org-at-heading-p) (outline-next-heading))
8953 (setq start (point))
8954 (goto-char (point-max))
8955 (beginning-of-line 1)
8956 (when (looking-at ".*?\\S-")
8957 ;; File ends in a non-white line
8958 (end-of-line 1)
8959 (insert "\n"))
8960 (setq end (point-max))
8961 (setq what "top-level")
8962 (goto-char start)
8963 (outline-show-all)))
8965 (setq beg (point))
8966 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8968 (looking-at "\\(\\*+\\)")
8969 (setq stars (match-string 1)
8970 re (concat "^" (regexp-quote stars) " +")
8971 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8972 txt (buffer-substring beg end))
8973 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8974 (when (and (not (equal stars "*")) (string-match re2 txt))
8975 (user-error "Region to sort contains a level above the first entry"))
8977 (unless sorting-type
8978 (message
8979 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8980 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8981 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8982 what)
8983 (setq sorting-type (read-char-exclusive))
8985 (unless getkey-func
8986 (and (= (downcase sorting-type) ?f)
8987 (setq getkey-func
8988 (completing-read "Sort using function: "
8989 obarray 'fboundp t nil nil))
8990 (setq getkey-func (intern getkey-func))))
8992 (and (= (downcase sorting-type) ?r)
8993 (not property)
8994 (setq property
8995 (completing-read "Property: "
8996 (mapcar #'list (org-buffer-property-keys t))
8997 nil t))))
8999 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9000 (message "Sorting entries...")
9002 (save-restriction
9003 (narrow-to-region start end)
9004 (let ((dcst (downcase sorting-type))
9005 (case-fold-search nil)
9006 (now (current-time)))
9007 (sort-subr
9008 (/= dcst sorting-type)
9009 ;; This function moves to the beginning character of the "record" to
9010 ;; be sorted.
9011 (lambda nil
9012 (if (re-search-forward re nil t)
9013 (goto-char (match-beginning 0))
9014 (goto-char (point-max))))
9015 ;; This function moves to the last character of the "record" being
9016 ;; sorted.
9017 (lambda nil
9018 (save-match-data
9019 (condition-case nil
9020 (outline-forward-same-level 1)
9021 (error
9022 (goto-char (point-max))))))
9023 ;; This function returns the value that gets sorted against.
9024 (lambda nil
9025 (cond
9026 ((= dcst ?n)
9027 (if (looking-at org-complex-heading-regexp)
9028 (string-to-number (org-sort-remove-invisible (match-string 4)))
9029 nil))
9030 ((= dcst ?a)
9031 (if (looking-at org-complex-heading-regexp)
9032 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9033 nil))
9034 ((= dcst ?k)
9035 (or (get-text-property (point) :org-clock-minutes) 0))
9036 ((= dcst ?t)
9037 (let ((end (save-excursion (outline-next-heading) (point))))
9038 (if (or (re-search-forward org-ts-regexp end t)
9039 (re-search-forward org-ts-regexp-both end t))
9040 (org-time-string-to-seconds (match-string 0))
9041 (float-time now))))
9042 ((= dcst ?c)
9043 (let ((end (save-excursion (outline-next-heading) (point))))
9044 (if (re-search-forward
9045 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9046 end t)
9047 (org-time-string-to-seconds (match-string 0))
9048 (float-time now))))
9049 ((= dcst ?s)
9050 (let ((end (save-excursion (outline-next-heading) (point))))
9051 (if (re-search-forward org-scheduled-time-regexp end t)
9052 (org-time-string-to-seconds (match-string 1))
9053 (float-time now))))
9054 ((= dcst ?d)
9055 (let ((end (save-excursion (outline-next-heading) (point))))
9056 (if (re-search-forward org-deadline-time-regexp end t)
9057 (org-time-string-to-seconds (match-string 1))
9058 (float-time now))))
9059 ((= dcst ?p)
9060 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9061 (string-to-char (match-string 2))
9062 org-default-priority))
9063 ((= dcst ?r)
9064 (or (org-entry-get nil property) ""))
9065 ((= dcst ?o)
9066 (when (looking-at org-complex-heading-regexp)
9067 (let* ((m (match-string 2))
9068 (s (if (member m org-done-keywords) '- '+)))
9069 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9070 ((= dcst ?f)
9071 (if getkey-func
9072 (progn
9073 (setq tmp (funcall getkey-func))
9074 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9075 tmp)
9076 (error "Invalid key function `%s'" getkey-func)))
9077 (t (error "Invalid sorting type `%c'" sorting-type))))
9079 (cond
9080 ((= dcst ?a) 'string<)
9081 ((= dcst ?f) compare-func)
9082 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9083 (run-hooks 'org-after-sorting-entries-or-items-hook)
9084 ;; Reset the clock marker if needed
9085 (when cmstr
9086 (save-excursion
9087 (goto-char start)
9088 (search-forward cmstr nil t)
9089 (move-marker org-clock-marker (point))))
9090 (message "Sorting entries...done")))
9092 ;;; The orgstruct minor mode
9094 ;; Define a minor mode which can be used in other modes in order to
9095 ;; integrate the Org mode structure editing commands.
9097 ;; This is really a hack, because the Org mode structure commands use
9098 ;; keys which normally belong to the major mode. Here is how it
9099 ;; works: The minor mode defines all the keys necessary to operate the
9100 ;; structure commands, but wraps the commands into a function which
9101 ;; tests if the cursor is currently at a headline or a plain list
9102 ;; item. If that is the case, the structure command is used,
9103 ;; temporarily setting many Org mode variables like regular
9104 ;; expressions for filling etc. However, when any of those keys is
9105 ;; used at a different location, function uses `key-binding' to look
9106 ;; up if the key has an associated command in another currently active
9107 ;; keymap (minor modes, major mode, global), and executes that
9108 ;; command. There might be problems if any of the keys is otherwise
9109 ;; used as a prefix key.
9111 (defcustom orgstruct-heading-prefix-regexp ""
9112 "Regexp that matches the custom prefix of Org headlines in
9113 orgstruct(++)-mode."
9114 :group 'org
9115 :version "24.4"
9116 :package-version '(Org . "8.3")
9117 :type 'regexp)
9118 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9120 (defcustom orgstruct-setup-hook nil
9121 "Hook run after orgstruct-mode-map is filled."
9122 :group 'org
9123 :version "24.4"
9124 :package-version '(Org . "8.0")
9125 :type 'hook)
9127 (defvar orgstruct-initialized nil)
9129 (defvar org-local-vars nil
9130 "List of local variables, for use by `orgstruct-mode'.")
9132 ;;;###autoload
9133 (define-minor-mode orgstruct-mode
9134 "Toggle the minor mode `orgstruct-mode'.
9135 This mode is for using Org mode structure commands in other
9136 modes. The following keys behave as if Org mode were active, if
9137 the cursor is on a headline, or on a plain list item (both as
9138 defined by Org mode)."
9139 nil " OrgStruct" (make-sparse-keymap)
9140 (funcall (if orgstruct-mode
9141 'add-to-invisibility-spec
9142 'remove-from-invisibility-spec)
9143 '(outline . t))
9144 (when orgstruct-mode
9145 (org-load-modules-maybe)
9146 (unless orgstruct-initialized
9147 (orgstruct-setup)
9148 (setq orgstruct-initialized t))))
9150 ;;;###autoload
9151 (defun turn-on-orgstruct ()
9152 "Unconditionally turn on `orgstruct-mode'."
9153 (orgstruct-mode 1))
9155 (defvar-local orgstruct-is-++ nil
9156 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9157 (defvar-local org-fb-vars nil)
9158 (defun orgstruct++-mode (&optional arg)
9159 "Toggle `orgstruct-mode', the enhanced version of it.
9160 In addition to setting orgstruct-mode, this also exports all
9161 indentation and autofilling variables from Org mode into the
9162 buffer. It will also recognize item context in multiline items."
9163 (interactive "P")
9164 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9165 (if (< arg 1)
9166 (progn (orgstruct-mode -1)
9167 (dolist (v org-fb-vars)
9168 (set (make-local-variable (car v))
9169 (if (eq (car-safe (cadr v)) 'quote)
9170 (cl-cadadr v)
9171 (nth 1 v)))))
9172 (orgstruct-mode 1)
9173 (setq org-fb-vars nil)
9174 (unless org-local-vars
9175 (setq org-local-vars (org-get-local-variables)))
9176 (let (var val)
9177 (dolist (x org-local-vars)
9178 (when (string-match
9179 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9180 \\|fill-prefix\\|indent-\\)"
9181 (symbol-name (car x)))
9182 (setq var (car x) val (nth 1 x))
9183 (push (list var `(quote ,(eval var))) org-fb-vars)
9184 (set (make-local-variable var)
9185 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9186 (setq-local orgstruct-is-++ t))))
9188 ;;;###autoload
9189 (defun turn-on-orgstruct++ ()
9190 "Unconditionally turn on `orgstruct++-mode'."
9191 (orgstruct++-mode 1))
9193 (defun orgstruct-error ()
9194 "Error when there is no default binding for a structure key."
9195 (interactive)
9196 (funcall (if (fboundp 'user-error)
9197 'user-error
9198 'error)
9199 "This key has no function outside structure elements"))
9201 (defun orgstruct-setup ()
9202 "Setup orgstruct keymap."
9203 (dolist (cell '((org-demote . t)
9204 (org-metaleft . t)
9205 (org-metaright . t)
9206 (org-promote . t)
9207 (org-shiftmetaleft . t)
9208 (org-shiftmetaright . t)
9209 org-backward-element
9210 org-backward-heading-same-level
9211 org-ctrl-c-ret
9212 org-ctrl-c-minus
9213 org-ctrl-c-star
9214 org-cycle
9215 org-force-cycle-archived
9216 org-forward-heading-same-level
9217 org-insert-heading
9218 org-insert-heading-respect-content
9219 org-kill-note-or-show-branches
9220 org-mark-subtree
9221 org-meta-return
9222 org-metadown
9223 org-metaup
9224 org-narrow-to-subtree
9225 org-promote-subtree
9226 org-reveal
9227 org-shiftdown
9228 org-shiftleft
9229 org-shiftmetadown
9230 org-shiftmetaup
9231 org-shiftright
9232 org-shifttab
9233 org-shifttab
9234 org-shiftup
9235 org-show-children
9236 org-show-subtree
9237 org-sort
9238 org-up-element
9239 outline-demote
9240 outline-next-visible-heading
9241 outline-previous-visible-heading
9242 outline-promote
9243 outline-up-heading))
9244 (let ((f (or (car-safe cell) cell))
9245 (disable-when-heading-prefix (cdr-safe cell)))
9246 (when (fboundp f)
9247 (let ((new-bindings))
9248 (dolist (binding (nconc (where-is-internal f org-mode-map)
9249 (where-is-internal f outline-mode-map)))
9250 (push binding new-bindings)
9251 ;; TODO use local-function-key-map
9252 (dolist (rep '(("<tab>" . "TAB")
9253 ("<return>" . "RET")
9254 ("<escape>" . "ESC")
9255 ("<delete>" . "DEL")))
9256 (setq binding (read-kbd-macro
9257 (let ((case-fold-search))
9258 (replace-regexp-in-string
9259 (regexp-quote (cdr rep))
9260 (car rep)
9261 (key-description binding)))))
9262 (cl-pushnew binding new-bindings :test 'equal)))
9263 (dolist (binding new-bindings)
9264 (let ((key (lookup-key orgstruct-mode-map binding)))
9265 (when (or (not key) (numberp key))
9266 (ignore-errors
9267 (org-defkey orgstruct-mode-map
9268 binding
9269 (orgstruct-make-binding
9270 f binding disable-when-heading-prefix))))))))))
9271 (run-hooks 'orgstruct-setup-hook))
9273 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9274 "Create a function for binding in the structure minor mode.
9275 FUN is the command to call inside a table. KEY is the key that
9276 should be checked in for a command to execute outside of tables.
9277 Non-nil `disable-when-heading-prefix' means to disable the command
9278 if `orgstruct-heading-prefix-regexp' is not empty."
9279 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9280 (let ((nname name)
9281 (i 0))
9282 (while (fboundp (intern nname))
9283 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9284 (setq name (intern nname)))
9285 (eval
9286 (let ((bindings '((org-heading-regexp
9287 (concat "^"
9288 orgstruct-heading-prefix-regexp
9289 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9290 (org-outline-regexp
9291 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9292 (org-outline-regexp-bol
9293 (concat "^" org-outline-regexp))
9294 (outline-regexp org-outline-regexp)
9295 (outline-heading-end-regexp "\n")
9296 (outline-level 'org-outline-level)
9297 (outline-heading-alist))))
9298 `(defun ,name (arg)
9299 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9300 "Outside of structure, run the binding of `"
9301 (key-description key) "'."
9302 (when disable-when-heading-prefix
9303 (concat
9304 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9305 "back to the default binding due to limitations of Org's implementation of\n"
9306 "`" (symbol-name fun) "'.")))
9307 (interactive "p")
9308 (let* ((disable
9309 ,(and disable-when-heading-prefix
9310 '(not (string= orgstruct-heading-prefix-regexp ""))))
9311 (fallback
9312 (or disable
9313 (not
9314 (let* ,bindings
9315 (org-context-p 'headline 'item
9316 ,(when (memq fun
9317 '(org-insert-heading
9318 org-insert-heading-respect-content
9319 org-meta-return))
9320 '(when orgstruct-is-++
9321 'item-body))))))))
9322 (if fallback
9323 (let* ((orgstruct-mode)
9324 (binding
9325 (let ((key ,key))
9326 (catch 'exit
9327 (dolist
9328 (rep
9329 '(nil
9330 ("<\\([^>]*\\)tab>" . "\\1TAB")
9331 ("<\\([^>]*\\)return>" . "\\1RET")
9332 ("<\\([^>]*\\)escape>" . "\\1ESC")
9333 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9334 nil)
9335 (when rep
9336 (setq key (read-kbd-macro
9337 (let ((case-fold-search))
9338 (replace-regexp-in-string
9339 (car rep)
9340 (cdr rep)
9341 (key-description key))))))
9342 (when (key-binding key)
9343 (throw 'exit (key-binding key))))))))
9344 (if (keymapp binding)
9345 (org-set-transient-map binding)
9346 (let ((func (or binding
9347 (unless disable
9348 'orgstruct-error))))
9349 (when func
9350 (call-interactively func)))))
9351 (org-run-like-in-org-mode
9352 (lambda ()
9353 (interactive)
9354 (let* ,bindings
9355 (call-interactively ',fun)))))))))
9356 name))
9358 (defun org-contextualize-keys (alist contexts)
9359 "Return valid elements in ALIST depending on CONTEXTS.
9361 `org-agenda-custom-commands' or `org-capture-templates' are the
9362 values used for ALIST, and `org-agenda-custom-commands-contexts'
9363 or `org-capture-templates-contexts' are the associated contexts
9364 definitions."
9365 (let ((contexts
9366 ;; normalize contexts
9367 (mapcar
9368 (lambda(c) (cond ((listp (cadr c))
9369 (list (car c) (car c) (nth 1 c)))
9370 ((string= "" (cadr c))
9371 (list (car c) (car c) (nth 2 c)))
9372 (t c)))
9373 contexts))
9374 (a alist) r s)
9375 ;; loop over all commands or templates
9376 (dolist (c a)
9377 (let (vrules repl)
9378 (cond
9379 ((not (assoc (car c) contexts))
9380 (push c r))
9381 ((and (assoc (car c) contexts)
9382 (setq vrules (org-contextualize-validate-key
9383 (car c) contexts)))
9384 (mapc (lambda (vr)
9385 (unless (equal (car vr) (cadr vr))
9386 (setq repl vr)))
9387 vrules)
9388 (if (not repl) (push c r)
9389 (push (cadr repl) s)
9390 (push
9391 (cons (car c)
9392 (cdr (or (assoc (cadr repl) alist)
9393 (error "Undefined key `%s' as contextual replacement for `%s'"
9394 (cadr repl) (car c)))))
9395 r))))))
9396 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9397 (delq
9399 (delete-dups
9400 (mapcar (lambda (x)
9401 (let ((tpl (car x)))
9402 (unless (delq
9404 (mapcar (lambda (y)
9405 (equal y tpl))
9407 x)))
9408 (reverse r))))))
9410 (defun org-contextualize-validate-key (key contexts)
9411 "Check CONTEXTS for agenda or capture KEY."
9412 (let (res)
9413 (dolist (r contexts)
9414 (dolist (rr (car (last r)))
9415 (when
9416 (and (equal key (car r))
9417 (if (functionp rr) (funcall rr)
9418 (or (and (eq (car rr) 'in-file)
9419 (buffer-file-name)
9420 (string-match (cdr rr) (buffer-file-name)))
9421 (and (eq (car rr) 'in-mode)
9422 (string-match (cdr rr) (symbol-name major-mode)))
9423 (and (eq (car rr) 'in-buffer)
9424 (string-match (cdr rr) (buffer-name)))
9425 (when (and (eq (car rr) 'not-in-file)
9426 (buffer-file-name))
9427 (not (string-match (cdr rr) (buffer-file-name))))
9428 (when (eq (car rr) 'not-in-mode)
9429 (not (string-match (cdr rr) (symbol-name major-mode))))
9430 (when (eq (car rr) 'not-in-buffer)
9431 (not (string-match (cdr rr) (buffer-name)))))))
9432 (push r res))))
9433 (delete-dups (delq nil res))))
9435 (defun org-context-p (&rest contexts)
9436 "Check if local context is any of CONTEXTS.
9437 Possible values in the list of contexts are `table', `headline', and `item'."
9438 (let ((pos (point)))
9439 (goto-char (point-at-bol))
9440 (prog1 (or (and (memq 'table contexts)
9441 (looking-at "[ \t]*|"))
9442 (and (memq 'headline contexts)
9443 (looking-at org-outline-regexp))
9444 (and (memq 'item contexts)
9445 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9446 (and (memq 'item-body contexts)
9447 (org-in-item-p)))
9448 (goto-char pos))))
9450 (defconst org-unique-local-variables
9451 '(org-element--cache
9452 org-element--cache-objects
9453 org-element--cache-sync-keys
9454 org-element--cache-sync-requests
9455 org-element--cache-sync-timer)
9456 "List of local variables that cannot be transferred to another buffer.")
9458 (defun org-get-local-variables ()
9459 "Return a list of all local variables in an Org mode buffer."
9460 (delq nil
9461 (mapcar
9462 (lambda (x)
9463 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9464 (name (car binding)))
9465 (and (not (get name 'org-state))
9466 (not (memq name org-unique-local-variables))
9467 (string-match-p
9468 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9469 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9470 (symbol-name name))
9471 binding)))
9472 (with-temp-buffer
9473 (org-mode)
9474 (buffer-local-variables)))))
9476 (defun org-clone-local-variables (from-buffer &optional regexp)
9477 "Clone local variables from FROM-BUFFER.
9478 Optional argument REGEXP selects variables to clone."
9479 (dolist (pair (buffer-local-variables from-buffer))
9480 (let ((name (car pair)))
9481 (when (and (symbolp name)
9482 (not (memq name org-unique-local-variables))
9483 (or (null regexp) (string-match regexp (symbol-name name))))
9484 (set (make-local-variable name) (cdr pair))))))
9486 ;;;###autoload
9487 (defun org-run-like-in-org-mode (cmd)
9488 "Run a command, pretending that the current buffer is in Org mode.
9489 This will temporarily bind local variables that are typically bound in
9490 Org mode to the values they have in Org mode, and then interactively
9491 call CMD."
9492 (org-load-modules-maybe)
9493 (unless org-local-vars
9494 (setq org-local-vars (org-get-local-variables)))
9495 (let (binds)
9496 (dolist (var org-local-vars)
9497 (when (or (not (boundp (car var)))
9498 (eq (symbol-value (car var))
9499 (default-value (car var))))
9500 (push (list (car var) `(quote ,(cadr var))) binds)))
9501 (eval `(let ,binds
9502 (call-interactively (quote ,cmd))))))
9504 (defun org-get-category (&optional pos force-refresh)
9505 "Get the category applying to position POS."
9506 (save-match-data
9507 (when force-refresh (org-refresh-category-properties))
9508 (let ((pos (or pos (point))))
9509 (or (get-text-property pos 'org-category)
9510 (progn (org-refresh-category-properties)
9511 (get-text-property pos 'org-category))))))
9513 ;;; Refresh properties
9515 (defun org-refresh-properties (dprop tprop)
9516 "Refresh buffer text properties.
9517 DPROP is the drawer property and TPROP is either the
9518 corresponding text property to set, or an alist with each element
9519 being a text property (as a symbol) and a function to apply to
9520 the value of the drawer property."
9521 (let* ((case-fold-search t)
9522 (inhibit-read-only t)
9523 (inherit? (org-property-inherit-p dprop))
9524 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9525 (global (and inherit? (org--property-global-value dprop nil))))
9526 (org-with-silent-modifications
9527 (org-with-point-at 1
9528 ;; Set global values (e.g., values defined through
9529 ;; "#+PROPERTY:" keywords) to the whole buffer.
9530 (when global (put-text-property (point-min) (point-max) tprop global))
9531 ;; Set local values.
9532 (while (re-search-forward property-re nil t)
9533 (when (org-at-property-p)
9534 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9535 (outline-next-heading))))))
9537 (defun org-refresh-property (tprop p &optional inherit)
9538 "Refresh the buffer text property TPROP from the drawer property P.
9539 The refresh happens only for the current headline, or the whole
9540 sub-tree if optional argument INHERIT is non-nil."
9541 (unless (org-before-first-heading-p)
9542 (save-excursion
9543 (org-back-to-heading t)
9544 (let ((start (point))
9545 (end (save-excursion
9546 (if inherit (org-end-of-subtree t t)
9547 (or (outline-next-heading) (point-max))))))
9548 (if (symbolp tprop)
9549 ;; TPROP is a text property symbol.
9550 (put-text-property start end tprop p)
9551 ;; TPROP is an alist with (property . function) elements.
9552 (pcase-dolist (`(,prop . ,f) tprop)
9553 (put-text-property start end prop (funcall f p))))))))
9555 (defun org-refresh-category-properties ()
9556 "Refresh category text properties in the buffer."
9557 (let ((case-fold-search t)
9558 (inhibit-read-only t)
9559 (default-category
9560 (cond ((null org-category)
9561 (if buffer-file-name
9562 (file-name-sans-extension
9563 (file-name-nondirectory buffer-file-name))
9564 "???"))
9565 ((symbolp org-category) (symbol-name org-category))
9566 (t org-category))))
9567 (org-with-silent-modifications
9568 (org-with-wide-buffer
9569 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9570 ;; This is the default category for the buffer. If none is
9571 ;; found, fall-back to `org-category' or buffer file name.
9572 (put-text-property
9573 (point-min) (point-max)
9574 'org-category
9575 (catch 'buffer-category
9576 (goto-char (point-max))
9577 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9578 (let ((element (org-element-at-point)))
9579 (when (eq (org-element-type element) 'keyword)
9580 (throw 'buffer-category
9581 (org-element-property :value element)))))
9582 default-category))
9583 ;; Set sub-tree specific categories.
9584 (goto-char (point-min))
9585 (let ((regexp (org-re-property "CATEGORY")))
9586 (while (re-search-forward regexp nil t)
9587 (let ((value (match-string-no-properties 3)))
9588 (when (org-at-property-p)
9589 (put-text-property
9590 (save-excursion (org-back-to-heading t) (point))
9591 (save-excursion (org-end-of-subtree t t) (point))
9592 'org-category
9593 value)))))))))
9595 (defun org-refresh-stats-properties ()
9596 "Refresh stats text properties in the buffer."
9597 (let (stats)
9598 (org-with-silent-modifications
9599 (org-with-wide-buffer
9600 (goto-char (point-min))
9601 (while (re-search-forward
9602 (concat org-outline-regexp-bol ".*"
9603 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9604 nil t)
9605 (setq stats (cond ((equal (match-string 3) "0") 0)
9606 ((match-string 2)
9607 (/ (* (string-to-number (match-string 2)) 100)
9608 (string-to-number (match-string 3))))
9609 (t (string-to-number (match-string 1)))))
9610 (org-back-to-heading t)
9611 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9612 'org-stats stats))))))
9614 (defun org-refresh-effort-properties ()
9615 "Refresh effort properties"
9616 (org-refresh-properties
9617 org-effort-property
9618 '((effort . identity)
9619 (effort-minutes . org-duration-to-minutes))))
9621 ;;;; Link Stuff
9623 ;;; Link abbreviations
9625 (defun org-link-expand-abbrev (link)
9626 "Apply replacements as defined in `org-link-abbrev-alist'."
9627 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9628 (let* ((key (match-string 1 link))
9629 (as (or (assoc key org-link-abbrev-alist-local)
9630 (assoc key org-link-abbrev-alist)))
9631 (tag (and (match-end 2) (match-string 3 link)))
9632 rpl)
9633 (if (not as)
9634 link
9635 (setq rpl (cdr as))
9636 (cond
9637 ((symbolp rpl) (funcall rpl tag))
9638 ((string-match "%(\\([^)]+\\))" rpl)
9639 (replace-match
9640 (save-match-data
9641 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9642 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9643 ((string-match "%h" rpl)
9644 (replace-match (url-hexify-string (or tag "")) t t rpl))
9645 (t (concat rpl tag)))))
9646 link))
9648 ;;; Storing and inserting links
9650 (defvar org-insert-link-history nil
9651 "Minibuffer history for links inserted with `org-insert-link'.")
9653 (defvar org-stored-links nil
9654 "Contains the links stored with `org-store-link'.")
9656 (defvar org-store-link-plist nil
9657 "Plist with info about the most recently link created with `org-store-link'.")
9659 (defun org-store-link-functions ()
9660 "Return a list of functions that are called to create and store a link.
9661 The functions defined in the :store property of
9662 `org-link-parameters'.
9664 Each function will be called in turn until one returns a non-nil
9665 value. Each function should check if it is responsible for
9666 creating this link (for example by looking at the major mode).
9667 If not, it must exit and return nil. If yes, it should return
9668 a non-nil value after calling `org-store-link-props' with a list
9669 of properties and values. Special properties are:
9671 :type The link prefix, like \"http\". This must be given.
9672 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9673 This is obligatory as well.
9674 :description Optional default description for the second pair
9675 of brackets in an Org mode link. The user can still change
9676 this when inserting this link into an Org mode buffer.
9678 In addition to these, any additional properties can be specified
9679 and then used in capture templates."
9680 (cl-loop for link in org-link-parameters
9681 with store-func
9682 do (setq store-func (org-link-get-parameter (car link) :store))
9683 if store-func
9684 collect store-func))
9686 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9687 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9689 ;;;###autoload
9690 (defun org-store-link (arg)
9691 "Store an org-link to the current location.
9692 \\<org-mode-map>
9693 This link is added to `org-stored-links' and can later be inserted
9694 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9696 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9697 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9698 For file links, ARG negates `org-context-in-file-links'.
9700 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9701 skipping storing functions that are not
9702 part of Org core.
9704 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9705 prefix ARG forces storing a link for each line in the
9706 active region."
9707 (interactive "P")
9708 (org-load-modules-maybe)
9709 (if (and (equal arg '(64)) (org-region-active-p))
9710 (save-excursion
9711 (let ((end (region-end)))
9712 (goto-char (region-beginning))
9713 (set-mark (point))
9714 (while (< (point-at-eol) end)
9715 (move-end-of-line 1) (activate-mark)
9716 (let (current-prefix-arg)
9717 (call-interactively 'org-store-link))
9718 (move-beginning-of-line 2)
9719 (set-mark (point)))))
9720 (setq org-store-link-plist nil)
9721 (let (link cpltxt desc description search
9722 txt custom-id agenda-link sfuns sfunsn)
9723 (cond
9725 ;; Store a link using an external link type
9726 ((and (not (equal arg '(16)))
9727 (setq sfuns
9728 (delq
9729 nil (mapcar (lambda (f)
9730 (let (fs) (if (funcall f) (push f fs))))
9731 (org-store-link-functions)))
9732 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9733 (or (and (cdr sfuns)
9734 (funcall (intern
9735 (completing-read
9736 "Which function for creating the link? "
9737 sfunsn nil t (car sfunsn)))))
9738 (funcall (caar sfuns)))
9739 (setq link (plist-get org-store-link-plist :link)
9740 desc (or (plist-get org-store-link-plist
9741 :description)
9742 link))))
9744 ;; Store a link from a source code buffer.
9745 ((org-src-edit-buffer-p)
9746 (let ((coderef-format (org-src-coderef-format)))
9747 (cond ((save-excursion
9748 (beginning-of-line)
9749 (looking-at (org-src-coderef-regexp coderef-format)))
9750 (setq link (format "(%s)" (match-string-no-properties 3))))
9751 ((called-interactively-p 'any)
9752 (let ((label (read-string "Code line label: ")))
9753 (end-of-line)
9754 (setq link (format coderef-format label))
9755 (let ((gc (- 79 (length link))))
9756 (if (< (current-column) gc)
9757 (org-move-to-column gc t)
9758 (insert " ")))
9759 (insert link)
9760 (setq link (concat "(" label ")"))
9761 (setq desc nil)))
9762 (t (setq link nil)))))
9764 ;; We are in the agenda, link to referenced location
9765 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9766 (let ((m (or (get-text-property (point) 'org-hd-marker)
9767 (get-text-property (point) 'org-marker))))
9768 (when m
9769 (org-with-point-at m
9770 (setq agenda-link
9771 (if (called-interactively-p 'any)
9772 (call-interactively 'org-store-link)
9773 (org-store-link nil)))))))
9775 ((eq major-mode 'calendar-mode)
9776 (let ((cd (calendar-cursor-to-date)))
9777 (setq link
9778 (format-time-string
9779 (car org-time-stamp-formats)
9780 (apply 'encode-time
9781 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9782 nil nil nil))))
9783 (org-store-link-props :type "calendar" :date cd)))
9785 ((eq major-mode 'help-mode)
9786 (setq link (concat "help:" (save-excursion
9787 (goto-char (point-min))
9788 (looking-at "^[^ ]+")
9789 (match-string 0))))
9790 (org-store-link-props :type "help"))
9792 ((eq major-mode 'w3-mode)
9793 (setq cpltxt (if (and (buffer-name)
9794 (not (string-match "Untitled" (buffer-name))))
9795 (buffer-name)
9796 (url-view-url t))
9797 link (url-view-url t))
9798 (org-store-link-props :type "w3" :url (url-view-url t)))
9800 ((eq major-mode 'image-mode)
9801 (setq cpltxt (concat "file:"
9802 (abbreviate-file-name buffer-file-name))
9803 link cpltxt)
9804 (org-store-link-props :type "image" :file buffer-file-name))
9806 ;; In dired, store a link to the file of the current line
9807 ((derived-mode-p 'dired-mode)
9808 (let ((file (dired-get-filename nil t)))
9809 (setq file (if file
9810 (abbreviate-file-name
9811 (expand-file-name (dired-get-filename nil t)))
9812 ;; otherwise, no file so use current directory.
9813 default-directory))
9814 (setq cpltxt (concat "file:" file)
9815 link cpltxt)))
9817 ((setq search (run-hook-with-args-until-success
9818 'org-create-file-search-functions))
9819 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9820 "::" search))
9821 (setq cpltxt (or description link)))
9823 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9824 (org-with-limited-levels
9825 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9826 (cond
9827 ;; Store a link using the target at point
9828 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9829 (setq cpltxt
9830 (concat "file:"
9831 (abbreviate-file-name
9832 (buffer-file-name (buffer-base-buffer)))
9833 "::" (match-string 1))
9834 link cpltxt))
9835 ((and (featurep 'org-id)
9836 (or (eq org-id-link-to-org-use-id t)
9837 (and (called-interactively-p 'any)
9838 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9839 (and (eq org-id-link-to-org-use-id
9840 'create-if-interactive-and-no-custom-id)
9841 (not custom-id))))
9842 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9843 ;; Store a link using the ID at point
9844 (setq link (condition-case nil
9845 (prog1 (org-id-store-link)
9846 (setq desc (or (plist-get org-store-link-plist
9847 :description)
9848 "")))
9849 (error
9850 ;; Probably before first headline, link only to file
9851 (concat "file:"
9852 (abbreviate-file-name
9853 (buffer-file-name (buffer-base-buffer))))))))
9855 ;; Just link to current headline
9856 (setq cpltxt (concat "file:"
9857 (abbreviate-file-name
9858 (buffer-file-name (buffer-base-buffer)))))
9859 ;; Add a context search string
9860 (when (org-xor org-context-in-file-links arg)
9861 (let* ((element (org-element-at-point))
9862 (name (org-element-property :name element)))
9863 (setq txt (cond
9864 ((org-at-heading-p) nil)
9865 (name)
9866 ((org-region-active-p)
9867 (buffer-substring (region-beginning) (region-end)))))
9868 (when (or (null txt) (string-match "\\S-" txt))
9869 (setq cpltxt
9870 (concat cpltxt "::"
9871 (condition-case nil
9872 (org-make-org-heading-search-string txt)
9873 (error "")))
9874 desc (or name
9875 (nth 4 (ignore-errors (org-heading-components)))
9876 "NONE")))))
9877 (when (string-match "::\\'" cpltxt)
9878 (setq cpltxt (substring cpltxt 0 -2)))
9879 (setq link cpltxt)))))
9881 ((buffer-file-name (buffer-base-buffer))
9882 ;; Just link to this file here.
9883 (setq cpltxt (concat "file:"
9884 (abbreviate-file-name
9885 (buffer-file-name (buffer-base-buffer)))))
9886 ;; Add a context string.
9887 (when (org-xor org-context-in-file-links arg)
9888 (setq txt (if (org-region-active-p)
9889 (buffer-substring (region-beginning) (region-end))
9890 (buffer-substring (point-at-bol) (point-at-eol))))
9891 ;; Only use search option if there is some text.
9892 (when (string-match "\\S-" txt)
9893 (setq cpltxt
9894 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9895 desc "NONE")))
9896 (setq link cpltxt))
9898 ((called-interactively-p 'interactive)
9899 (user-error "No method for storing a link from this buffer"))
9901 (t (setq link nil)))
9903 ;; We're done setting link and desc, clean up
9904 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9905 (setq link (or link cpltxt)
9906 desc (or desc cpltxt))
9907 (cond ((not desc))
9908 ((equal desc "NONE") (setq desc nil))
9909 (t (setq desc
9910 (replace-regexp-in-string
9911 org-bracket-link-analytic-regexp
9912 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9913 desc))))
9914 ;; Return the link
9915 (if (not (and (or (called-interactively-p 'any)
9916 executing-kbd-macro)
9917 link))
9918 (or agenda-link (and link (org-make-link-string link desc)))
9919 (push (list link desc) org-stored-links)
9920 (message "Stored: %s" (or desc link))
9921 (when custom-id
9922 (setq link (concat "file:" (abbreviate-file-name
9923 (buffer-file-name)) "::#" custom-id))
9924 (push (list link desc) org-stored-links))
9925 (car org-stored-links)))))
9927 (defun org-store-link-props (&rest plist)
9928 "Store link properties, extract names, addresses and dates."
9929 (let ((x (plist-get plist :from)))
9930 (when x
9931 (let ((adr (mail-extract-address-components x)))
9932 (setq plist (plist-put plist :fromname (car adr)))
9933 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9934 (let ((x (plist-get plist :to)))
9935 (when x
9936 (let ((adr (mail-extract-address-components x)))
9937 (setq plist (plist-put plist :toname (car adr)))
9938 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9939 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9940 (when x
9941 (setq plist (plist-put plist :date-timestamp
9942 (format-time-string
9943 (org-time-stamp-format t) x)))
9944 (setq plist (plist-put plist :date-timestamp-inactive
9945 (format-time-string
9946 (org-time-stamp-format t t) x)))))
9947 (let ((from (plist-get plist :from))
9948 (to (plist-get plist :to)))
9949 (when (and from to org-from-is-user-regexp)
9950 (setq plist
9951 (plist-put plist :fromto
9952 (if (string-match org-from-is-user-regexp from)
9953 (concat "to %t")
9954 (concat "from %f"))))))
9955 (setq org-store-link-plist plist))
9957 (defun org-add-link-props (&rest plist)
9958 "Add these properties to the link property list."
9959 (let (key value)
9960 (while plist
9961 (setq key (pop plist) value (pop plist))
9962 (setq org-store-link-plist
9963 (plist-put org-store-link-plist key value)))))
9965 (defun org-email-link-description (&optional fmt)
9966 "Return the description part of an email link.
9967 This takes information from `org-store-link-plist' and formats it
9968 according to FMT (default from `org-email-link-description-format')."
9969 (setq fmt (or fmt org-email-link-description-format))
9970 (let* ((p org-store-link-plist)
9971 (to (plist-get p :toaddress))
9972 (from (plist-get p :fromaddress))
9973 (table
9974 (list
9975 (cons "%c" (plist-get p :fromto))
9976 (cons "%F" (plist-get p :from))
9977 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9978 (cons "%T" (plist-get p :to))
9979 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9980 (cons "%s" (plist-get p :subject))
9981 (cons "%d" (plist-get p :date))
9982 (cons "%m" (plist-get p :message-id)))))
9983 (when (string-match "%c" fmt)
9984 ;; Check if the user wrote this message
9985 (if (and org-from-is-user-regexp from to
9986 (save-match-data (string-match org-from-is-user-regexp from)))
9987 (setq fmt (replace-match "to %t" t t fmt))
9988 (setq fmt (replace-match "from %f" t t fmt))))
9989 (org-replace-escapes fmt table)))
9991 (defun org-make-org-heading-search-string (&optional string)
9992 "Make search string for the current headline or STRING."
9993 (let ((s (or string
9994 (and (derived-mode-p 'org-mode)
9995 (save-excursion
9996 (org-back-to-heading t)
9997 (org-element-property :raw-value (org-element-at-point))))))
9998 (lines org-context-in-file-links))
9999 (or string (setq s (concat "*" s))) ; Add * for headlines
10000 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10001 (when (and string (integerp lines) (> lines 0))
10002 (let ((slines (org-split-string s "\n")))
10003 (when (< lines (length slines))
10004 (setq s (mapconcat
10005 'identity
10006 (reverse (nthcdr (- (length slines) lines)
10007 (reverse slines))) "\n")))))
10008 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10010 (defun org-make-link-string (link &optional description)
10011 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10012 (unless (org-string-nw-p link) (error "Empty link"))
10013 (let ((uri (cond ((string-match org-link-types-re link)
10014 (concat (match-string 1 link)
10015 (org-link-escape (substring link (match-end 1)))))
10016 ;; For readability, url-encode internal links only
10017 ;; when absolutely needed (i.e, when they contain
10018 ;; square brackets). File links however, are
10019 ;; encoded since, e.g., spaces are significant.
10020 ((or (file-name-absolute-p link)
10021 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10022 (org-link-escape link))
10023 (t link)))
10024 (description
10025 (and (org-string-nw-p description)
10026 ;; Remove brackets from description, as they are fatal.
10027 (replace-regexp-in-string
10028 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10029 (org-trim description)))))
10030 (format "[[%s]%s]"
10032 (if description (format "[%s]" description) ""))))
10034 (defconst org-link-escape-chars
10035 ;;%20 %5B %5D %25
10036 '(?\s ?\[ ?\] ?%)
10037 "List of characters that should be escaped in a link when stored to Org.
10038 This is the list that is used for internal purposes.")
10040 (defun org-link-escape (text &optional table merge)
10041 "Return percent escaped representation of TEXT.
10042 TEXT is a string with the text to escape.
10043 Optional argument TABLE is a list with characters that should be
10044 escaped. When nil, `org-link-escape-chars' is used.
10045 If optional argument MERGE is set, merge TABLE into
10046 `org-link-escape-chars'."
10047 (let ((characters-to-encode
10048 (cond ((null table) org-link-escape-chars)
10049 (merge (append org-link-escape-chars table))
10050 (t table))))
10051 (mapconcat
10052 (lambda (c)
10053 (if (or (memq c characters-to-encode)
10054 (and org-url-hexify-p (or (< c 32) (> c 126))))
10055 (mapconcat (lambda (e) (format "%%%.2X" e))
10056 (or (encode-coding-char c 'utf-8)
10057 (error "Unable to percent escape character: %c" c))
10059 (char-to-string c)))
10060 text "")))
10062 (defun org-link-unescape (str)
10063 "Unhex hexified Unicode parts in string STR.
10064 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10065 reciprocal of `org-link-escape', which see."
10066 (if (org-string-nw-p str)
10067 (replace-regexp-in-string
10068 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10069 str))
10071 (defun org-link-unescape-compound (hex)
10072 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10073 Note: this function also decodes single byte encodings like
10074 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10075 (save-match-data
10076 (let* ((bytes (cdr (split-string hex "%")))
10077 (ret "")
10078 (eat 0)
10079 (sum 0))
10080 (while bytes
10081 (let* ((val (string-to-number (pop bytes) 16))
10082 (shift-xor
10083 (if (= 0 eat)
10084 (cond
10085 ((>= val 252) (cons 6 252))
10086 ((>= val 248) (cons 5 248))
10087 ((>= val 240) (cons 4 240))
10088 ((>= val 224) (cons 3 224))
10089 ((>= val 192) (cons 2 192))
10090 (t (cons 0 0)))
10091 (cons 6 128))))
10092 (when (>= val 192) (setq eat (car shift-xor)))
10093 (setq val (logxor val (cdr shift-xor)))
10094 (setq sum (+ (lsh sum (car shift-xor)) val))
10095 (when (> eat 0) (setq eat (- eat 1)))
10096 (cond
10097 ((= 0 eat) ;multi byte
10098 (setq ret (concat ret (char-to-string sum)))
10099 (setq sum 0))
10100 ((not bytes) ; single byte(s)
10101 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10102 ret)))
10104 (defun org-link-unescape-single-byte-sequence (hex)
10105 "Unhexify hex-encoded single byte character sequences."
10106 (mapconcat (lambda (byte)
10107 (char-to-string (string-to-number byte 16)))
10108 (cdr (split-string hex "%")) ""))
10110 (defun org-xor (a b)
10111 "Exclusive or."
10112 (if a (not b) b))
10114 (defun org-fixup-message-id-for-http (s)
10115 "Replace special characters in a message id, so it can be used in an http query."
10116 (when (string-match "%" s)
10117 (setq s (mapconcat (lambda (c)
10118 (if (eq c ?%)
10119 "%25"
10120 (char-to-string c)))
10121 s "")))
10122 (while (string-match "<" s)
10123 (setq s (replace-match "%3C" t t s)))
10124 (while (string-match ">" s)
10125 (setq s (replace-match "%3E" t t s)))
10126 (while (string-match "@" s)
10127 (setq s (replace-match "%40" t t s)))
10130 (defun org-link-prettify (link)
10131 "Return a human-readable representation of LINK.
10132 The car of LINK must be a raw link.
10133 The cdr of LINK must be either a link description or nil."
10134 (let ((desc (or (cadr link) "<no description>")))
10135 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10136 "<" (car link) ">")))
10138 ;;;###autoload
10139 (defun org-insert-link-global ()
10140 "Insert a link like Org mode does.
10141 This command can be called in any mode to insert a link in Org syntax."
10142 (interactive)
10143 (org-load-modules-maybe)
10144 (org-run-like-in-org-mode 'org-insert-link))
10146 (defun org-insert-all-links (arg &optional pre post)
10147 "Insert all links in `org-stored-links'.
10148 When a universal prefix, do not delete the links from `org-stored-links'.
10149 When `ARG' is a number, insert the last N link(s).
10150 `PRE' and `POST' are optional arguments to define a string to
10151 prepend or to append."
10152 (interactive "P")
10153 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10154 (links (copy-sequence org-stored-links))
10155 (pr (or pre "- "))
10156 (po (or post "\n"))
10157 (cnt 1) l)
10158 (if (null org-stored-links)
10159 (message "No link to insert")
10160 (while (and (or (listp arg) (>= arg cnt))
10161 (setq l (if (listp arg)
10162 (pop links)
10163 (pop org-stored-links))))
10164 (setq cnt (1+ cnt))
10165 (insert pr)
10166 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10167 (insert po)))))
10169 (defun org-insert-last-stored-link (arg)
10170 "Insert the last link stored in `org-stored-links'."
10171 (interactive "p")
10172 (org-insert-all-links arg "" "\n"))
10174 (defun org-link-fontify-links-to-this-file ()
10175 "Fontify links to the current file in `org-stored-links'."
10176 (let ((f (buffer-file-name)) a b)
10177 (setq a (mapcar (lambda(l)
10178 (let ((ll (car l)))
10179 (when (and (string-match "^file:\\(.+\\)::" ll)
10180 (equal f (expand-file-name (match-string 1 ll))))
10181 ll)))
10182 org-stored-links))
10183 (when (featurep 'org-id)
10184 (setq b (mapcar (lambda(l)
10185 (let ((ll (car l)))
10186 (when (and (string-match "^id:\\(.+\\)$" ll)
10187 (equal f (expand-file-name
10188 (or (org-id-find-id-file
10189 (match-string 1 ll)) ""))))
10190 ll)))
10191 org-stored-links)))
10192 (mapcar (lambda(l)
10193 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10194 (delq nil (append a b)))))
10196 (defvar org--links-history nil)
10197 (defun org-insert-link (&optional complete-file link-location default-description)
10198 "Insert a link. At the prompt, enter the link.
10200 Completion can be used to insert any of the link protocol prefixes in use.
10202 The history can be used to select a link previously stored with
10203 `org-store-link'. When the empty string is entered (i.e. if you just
10204 press `RET' at the prompt), the link defaults to the most recently
10205 stored link. As `SPC' triggers completion in the minibuffer, you need to
10206 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10208 You will also be prompted for a description, and if one is given, it will
10209 be displayed in the buffer instead of the link.
10211 If there is already a link at point, this command will allow you to edit
10212 link and description parts.
10214 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10215 file name can be
10216 selected using completion. The path to the file will be relative to the
10217 current directory if the file is in the current directory or a subdirectory.
10218 Otherwise, the link will be the absolute path as completed in the minibuffer
10219 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10220 option `org-link-file-path-type'.
10222 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10223 absolute path even if the file is in
10224 the current directory or below.
10226 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10227 prefix negates `org-keep-stored-link-after-insertion'.
10229 If `org-make-link-description-function' is non-nil, this function will be
10230 called with the link target, and the result will be the default
10231 link description.
10233 If the LINK-LOCATION parameter is non-nil, this value will be used as
10234 the link location instead of reading one interactively.
10236 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10237 as the default description."
10238 (interactive "P")
10239 (let* ((wcf (current-window-configuration))
10240 (origbuf (current-buffer))
10241 (region (when (org-region-active-p)
10242 (buffer-substring (region-beginning) (region-end))))
10243 (remove (and region (list (region-beginning) (region-end))))
10244 (desc region)
10245 (link link-location)
10246 (abbrevs org-link-abbrev-alist-local)
10247 entry all-prefixes auto-desc)
10248 (cond
10249 (link-location) ; specified by arg, just use it.
10250 ((org-in-regexp org-bracket-link-regexp 1)
10251 ;; We do have a link at point, and we are going to edit it.
10252 (setq remove (list (match-beginning 0) (match-end 0)))
10253 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10254 (setq link (read-string "Link: "
10255 (org-link-unescape
10256 (match-string-no-properties 1)))))
10257 ((or (org-in-regexp org-angle-link-re)
10258 (org-in-regexp org-plain-link-re))
10259 ;; Convert to bracket link
10260 (setq remove (list (match-beginning 0) (match-end 0))
10261 link (read-string "Link: "
10262 (org-unbracket-string "<" ">" (match-string 0)))))
10263 ((member complete-file '((4) (16)))
10264 ;; Completing read for file names.
10265 (setq link (org-file-complete-link complete-file)))
10267 ;; Read link, with completion for stored links.
10268 (org-link-fontify-links-to-this-file)
10269 (org-switch-to-buffer-other-window "*Org Links*")
10270 (with-current-buffer "*Org Links*"
10271 (erase-buffer)
10272 (insert "Insert a link.
10273 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10274 (when org-stored-links
10275 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10276 (insert (mapconcat 'org-link-prettify
10277 (reverse org-stored-links) "\n")))
10278 (goto-char (point-min)))
10279 (let ((cw (selected-window)))
10280 (select-window (get-buffer-window "*Org Links*" 'visible))
10281 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10282 (unless (pos-visible-in-window-p (point-max))
10283 (org-fit-window-to-buffer))
10284 (and (window-live-p cw) (select-window cw)))
10285 (setq all-prefixes (append (mapcar 'car abbrevs)
10286 (mapcar 'car org-link-abbrev-alist)
10287 (org-link-types)))
10288 (unwind-protect
10289 ;; Fake a link history, containing the stored links.
10290 (let ((org--links-history
10291 (append (mapcar #'car org-stored-links)
10292 org-insert-link-history)))
10293 (setq link
10294 (org-completing-read
10295 "Link: "
10296 (append
10297 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10298 (mapcar #'car org-stored-links))
10299 nil nil nil
10300 'org--links-history
10301 (caar org-stored-links)))
10302 (unless (org-string-nw-p link) (user-error "No link selected"))
10303 (dolist (l org-stored-links)
10304 (when (equal link (cadr l))
10305 (setq link (car l))
10306 (setq auto-desc t)))
10307 (when (or (member link all-prefixes)
10308 (and (equal ":" (substring link -1))
10309 (member (substring link 0 -1) all-prefixes)
10310 (setq link (substring link 0 -1))))
10311 (setq link (with-current-buffer origbuf
10312 (org-link-try-special-completion link)))))
10313 (set-window-configuration wcf)
10314 (kill-buffer "*Org Links*"))
10315 (setq entry (assoc link org-stored-links))
10316 (or entry (push link org-insert-link-history))
10317 (setq desc (or desc (nth 1 entry)))))
10319 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10320 (not org-keep-stored-link-after-insertion))
10321 (setq org-stored-links (delq (assoc link org-stored-links)
10322 org-stored-links)))
10324 (when (and (string-match org-plain-link-re link)
10325 (not (string-match org-ts-regexp link)))
10326 ;; URL-like link, normalize the use of angular brackets.
10327 (setq link (org-unbracket-string "<" ">" link)))
10329 ;; Check if we are linking to the current file with a search
10330 ;; option If yes, simplify the link by using only the search
10331 ;; option.
10332 (when (and buffer-file-name
10333 (let ((case-fold-search nil))
10334 (string-match "\\`file:\\(.+?\\)::" link)))
10335 (let ((path (match-string-no-properties 1 link))
10336 (search (substring-no-properties link (match-end 0))))
10337 (save-match-data
10338 (when (equal (file-truename buffer-file-name) (file-truename path))
10339 ;; We are linking to this same file, with a search option
10340 (setq link search)))))
10342 ;; Check if we can/should use a relative path. If yes, simplify the link
10343 (let ((case-fold-search nil))
10344 (when (string-match "\\`\\(file:\\|docview\\):" link)
10345 (let ((type (match-string-no-properties 0 link))
10346 (path (substring-no-properties link (match-end 0)))
10347 (origpath path))
10348 (cond
10349 ((or (eq org-link-file-path-type 'absolute)
10350 (equal complete-file '(16)))
10351 (setq path (abbreviate-file-name (expand-file-name path))))
10352 ((eq org-link-file-path-type 'noabbrev)
10353 (setq path (expand-file-name path)))
10354 ((eq org-link-file-path-type 'relative)
10355 (setq path (file-relative-name path)))
10357 (save-match-data
10358 (if (string-match (concat "^" (regexp-quote
10359 (expand-file-name
10360 (file-name-as-directory
10361 default-directory))))
10362 (expand-file-name path))
10363 ;; We are linking a file with relative path name.
10364 (setq path (substring (expand-file-name path)
10365 (match-end 0)))
10366 (setq path (abbreviate-file-name (expand-file-name path)))))))
10367 (setq link (concat type path))
10368 (when (equal desc origpath)
10369 (setq desc path)))))
10371 (if org-make-link-description-function
10372 (setq desc
10373 (or (condition-case nil
10374 (funcall org-make-link-description-function link desc)
10375 (error (progn (message "Can't get link description from `%s'"
10376 (symbol-name org-make-link-description-function))
10377 (sit-for 2) nil)))
10378 (read-string "Description: " default-description)))
10379 (if default-description (setq desc default-description)
10380 (setq desc (or (and auto-desc desc)
10381 (read-string "Description: " desc)))))
10383 (unless (string-match "\\S-" desc) (setq desc nil))
10384 (when remove (apply 'delete-region remove))
10385 (insert (org-make-link-string link desc))
10386 ;; Redisplay so as the new link has proper invisible characters.
10387 (sit-for 0)))
10389 (defun org-link-try-special-completion (type)
10390 "If there is completion support for link type TYPE, offer it."
10391 (let ((fun (org-link-get-parameter type :complete)))
10392 (if (functionp fun)
10393 (funcall fun)
10394 (read-string "Link (no completion support): " (concat type ":")))))
10396 (defun org-file-complete-link (&optional arg)
10397 "Create a file link using completion."
10398 (let ((file (read-file-name "File: "))
10399 (pwd (file-name-as-directory (expand-file-name ".")))
10400 (pwd1 (file-name-as-directory (abbreviate-file-name
10401 (expand-file-name ".")))))
10402 (cond ((equal arg '(16))
10403 (concat "file:"
10404 (abbreviate-file-name (expand-file-name file))))
10405 ((string-match
10406 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10407 (concat "file:" (match-string 1 file)))
10408 ((string-match
10409 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10410 (expand-file-name file))
10411 (concat "file:"
10412 (match-string 1 (expand-file-name file))))
10413 (t (concat "file:" file)))))
10415 (defun org-completing-read (&rest args)
10416 "Completing-read with SPACE being a normal character."
10417 (let ((enable-recursive-minibuffers t)
10418 (minibuffer-local-completion-map
10419 (copy-keymap minibuffer-local-completion-map)))
10420 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10421 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10422 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10423 'org-time-stamp-inactive)
10424 (apply #'completing-read args)))
10426 ;;; Opening/following a link
10428 (defvar org-link-search-failed nil)
10430 (defvar org-open-link-functions nil
10431 "Hook for functions finding a plain text link.
10432 These functions must take a single argument, the link content.
10433 They will be called for links that look like [[link text][description]]
10434 when LINK TEXT does not have a protocol like \"http:\" and does not look
10435 like a filename (e.g. \"./blue.png\").
10437 These functions will be called *before* Org attempts to resolve the
10438 link by doing text searches in the current buffer - so if you want a
10439 link \"[[target]]\" to still find \"<<target>>\", your function should
10440 handle this as a special case.
10442 When the function does handle the link, it must return a non-nil value.
10443 If it decides that it is not responsible for this link, it must return
10444 nil to indicate that that Org can continue with other options like
10445 exact and fuzzy text search.")
10447 (defun org-next-link (&optional search-backward)
10448 "Move forward to the next link.
10449 If the link is in hidden text, expose it."
10450 (interactive "P")
10451 (when (and org-link-search-failed (eq this-command last-command))
10452 (goto-char (point-min))
10453 (message "Link search wrapped back to beginning of buffer"))
10454 (setq org-link-search-failed nil)
10455 (let* ((pos (point))
10456 (ct (org-context))
10457 (a (assq :link ct))
10458 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10459 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10460 ((looking-at org-any-link-re)
10461 ;; Don't stay stuck at link without an org-link face
10462 (forward-char (if search-backward -1 1))))
10463 (if (funcall srch-fun org-any-link-re nil t)
10464 (progn
10465 (goto-char (match-beginning 0))
10466 (when (outline-invisible-p) (org-show-context)))
10467 (goto-char pos)
10468 (setq org-link-search-failed t)
10469 (message "No further link found"))))
10471 (defun org-previous-link ()
10472 "Move backward to the previous link.
10473 If the link is in hidden text, expose it."
10474 (interactive)
10475 (funcall 'org-next-link t))
10477 (defun org-translate-link (s)
10478 "Translate a link string if a translation function has been defined."
10479 (with-temp-buffer
10480 (insert (org-trim s))
10481 (org-trim (org-element-interpret-data (org-element-context)))))
10483 (defun org-translate-link-from-planner (type path)
10484 "Translate a link from Emacs Planner syntax so that Org can follow it.
10485 This is still an experimental function, your mileage may vary."
10486 (cond
10487 ((member type '("http" "https" "news" "ftp"))
10488 ;; standard Internet links are the same.
10489 nil)
10490 ((and (equal type "irc") (string-match "^//" path))
10491 ;; Planner has two / at the beginning of an irc link, we have 1.
10492 ;; We should have zero, actually....
10493 (setq path (substring path 1)))
10494 ((and (equal type "lisp") (string-match "^/" path))
10495 ;; Planner has a slash, we do not.
10496 (setq type "elisp" path (substring path 1)))
10497 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10498 ;; A typical message link. Planner has the id after the final slash,
10499 ;; we separate it with a hash mark
10500 (setq path (concat (match-string 1 path) "#"
10501 (org-unbracket-string "<" ">" (match-string 2 path))))))
10502 (cons type path))
10504 (defun org-find-file-at-mouse (ev)
10505 "Open file link or URL at mouse."
10506 (interactive "e")
10507 (mouse-set-point ev)
10508 (org-open-at-point 'in-emacs))
10510 (defun org-open-at-mouse (ev)
10511 "Open file link or URL at mouse.
10512 See the docstring of `org-open-file' for details."
10513 (interactive "e")
10514 (mouse-set-point ev)
10515 (when (eq major-mode 'org-agenda-mode)
10516 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10517 (org-open-at-point))
10519 (defvar org-window-config-before-follow-link nil
10520 "The window configuration before following a link.
10521 This is saved in case the need arises to restore it.")
10523 ;;;###autoload
10524 (defun org-open-at-point-global ()
10525 "Follow a link or time-stamp like Org mode does.
10526 This command can be called in any mode to follow an external link
10527 or a time-stamp that has Org mode syntax. Its behavior is
10528 undefined when called on internal links (e.g., fuzzy links).
10529 Raise an error when there is nothing to follow. "
10530 (interactive)
10531 (cond ((org-in-regexp org-any-link-re)
10532 (org-open-link-from-string (match-string-no-properties 0)))
10533 ((or (org-in-regexp org-ts-regexp-both nil t)
10534 (org-in-regexp org-tsr-regexp-both nil t))
10535 (org-follow-timestamp-link))
10536 (t (user-error "No link found"))))
10538 ;;;###autoload
10539 (defun org-open-link-from-string (s &optional arg reference-buffer)
10540 "Open a link in the string S, as if it was in Org mode."
10541 (interactive "sLink: \nP")
10542 (let ((reference-buffer (or reference-buffer (current-buffer))))
10543 (with-temp-buffer
10544 (let ((org-inhibit-startup (not reference-buffer)))
10545 (org-mode)
10546 (insert s)
10547 (goto-char (point-min))
10548 (when reference-buffer
10549 (setq org-link-abbrev-alist-local
10550 (with-current-buffer reference-buffer
10551 org-link-abbrev-alist-local)))
10552 (org-open-at-point arg reference-buffer)))))
10554 (defvar org-open-at-point-functions nil
10555 "Hook that is run when following a link at point.
10557 Functions in this hook must return t if they identify and follow
10558 a link at point. If they don't find anything interesting at point,
10559 they must return nil.")
10561 (defvar org-link-search-inhibit-query nil)
10562 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10563 (defun org--open-doi-link (path)
10564 "Open a \"doi\" type link.
10565 PATH is a the path to search for, as a string."
10566 (browse-url (url-encode-url (concat org-doi-server-url path))))
10568 (defun org--open-elisp-link (path)
10569 "Open a \"elisp\" type link.
10570 PATH is the sexp to evaluate, as a string."
10571 (let ((cmd path))
10572 (if (or (and (org-string-nw-p
10573 org-confirm-elisp-link-not-regexp)
10574 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10575 (not org-confirm-elisp-link-function)
10576 (funcall org-confirm-elisp-link-function
10577 (format "Execute \"%s\" as elisp? "
10578 (org-add-props cmd nil 'face 'org-warning))))
10579 (message "%s => %s" cmd
10580 (if (eq (string-to-char cmd) ?\()
10581 (eval (read cmd))
10582 (call-interactively (read cmd))))
10583 (user-error "Abort"))))
10585 (defun org--open-help-link (path)
10586 "Open a \"help\" type link.
10587 PATH is a symbol name, as a string."
10588 (pcase (intern path)
10589 ((and (pred fboundp) variable) (describe-function variable))
10590 ((and (pred boundp) function) (describe-variable function))
10591 (name (user-error "Unknown function or variable: %s" name))))
10593 (defun org--open-shell-link (path)
10594 "Open a \"shell\" type link.
10595 PATH is the command to execute, as a string."
10596 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10597 (cmd path))
10598 (if (or (and (org-string-nw-p
10599 org-confirm-shell-link-not-regexp)
10600 (string-match
10601 org-confirm-shell-link-not-regexp cmd))
10602 (not org-confirm-shell-link-function)
10603 (funcall org-confirm-shell-link-function
10604 (format "Execute \"%s\" in shell? "
10605 (org-add-props cmd nil
10606 'face 'org-warning))))
10607 (progn
10608 (message "Executing %s" cmd)
10609 (shell-command cmd buf)
10610 (when (featurep 'midnight)
10611 (setq clean-buffer-list-kill-buffer-names
10612 (cons (buffer-name buf)
10613 clean-buffer-list-kill-buffer-names))))
10614 (user-error "Abort"))))
10616 (defun org-open-at-point (&optional arg reference-buffer)
10617 "Open link, timestamp, footnote or tags at point.
10619 When point is on a link, follow it. Normally, files will be
10620 opened by an appropriate application. If the optional prefix
10621 argument ARG is non-nil, Emacs will visit the file. With
10622 a double prefix argument, try to open outside of Emacs, in the
10623 application the system uses for this file type.
10625 When point is on a timestamp, open the agenda at the day
10626 specified.
10628 When point is a footnote definition, move to the first reference
10629 found. If it is on a reference, move to the associated
10630 definition.
10632 When point is on a headline, display a list of every link in the
10633 entry, so it is possible to pick one, or all, of them. If point
10634 is on a tag, call `org-tags-view' instead.
10636 When optional argument REFERENCE-BUFFER is non-nil, it should
10637 specify a buffer from where the link search should happen. This
10638 is used internally by `org-open-link-from-string'.
10640 On top of syntactically correct links, this function will open
10641 the link at point in comments or comment blocks and the first
10642 link in a property drawer line."
10643 (interactive "P")
10644 ;; On a code block, open block's results.
10645 (unless (call-interactively 'org-babel-open-src-block-result)
10646 (org-load-modules-maybe)
10647 (setq org-window-config-before-follow-link (current-window-configuration))
10648 (org-remove-occur-highlights nil nil t)
10649 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10650 (let* ((context
10651 ;; Only consider supported types, even if they are not
10652 ;; the closest one.
10653 (org-element-lineage
10654 (org-element-context)
10655 '(clock comment comment-block footnote-definition
10656 footnote-reference headline inlinetask keyword link
10657 node-property timestamp)
10659 (type (org-element-type context))
10660 (value (org-element-property :value context)))
10661 (cond
10662 ((not context) (user-error "No link found"))
10663 ;; Exception: open timestamps and links in properties
10664 ;; drawers, keywords and comments.
10665 ((memq type '(comment comment-block keyword node-property))
10666 (call-interactively #'org-open-at-point-global))
10667 ;; On a headline or an inlinetask, but not on a timestamp,
10668 ;; a link, a footnote reference or on tags.
10669 ((and (memq type '(headline inlinetask))
10670 ;; Not on tags.
10671 (let ((case-fold-search nil))
10672 (save-excursion
10673 (beginning-of-line)
10674 (looking-at org-complex-heading-regexp))
10675 (or (not (match-beginning 5))
10676 (< (point) (match-beginning 5)))))
10677 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10678 (links (car data))
10679 (links-end (cdr data)))
10680 (if links
10681 (dolist (link (if (stringp links) (list links) links))
10682 (search-forward link nil links-end)
10683 (goto-char (match-beginning 0))
10684 (org-open-at-point))
10685 (require 'org-attach)
10686 (org-attach-reveal 'if-exists))))
10687 ;; On a clock line, make sure point is on the timestamp
10688 ;; before opening it.
10689 ((and (eq type 'clock)
10690 value
10691 (>= (point) (org-element-property :begin value))
10692 (<= (point) (org-element-property :end value)))
10693 (org-follow-timestamp-link))
10694 ;; Do nothing on white spaces after an object.
10695 ((>= (point)
10696 (save-excursion
10697 (goto-char (org-element-property :end context))
10698 (skip-chars-backward " \t")
10699 (point)))
10700 (user-error "No link found"))
10701 ((eq type 'timestamp) (org-follow-timestamp-link))
10702 ;; On tags within a headline or an inlinetask.
10703 ((and (memq type '(headline inlinetask))
10704 (let ((case-fold-search nil))
10705 (save-excursion (beginning-of-line)
10706 (looking-at org-complex-heading-regexp))
10707 (and (match-beginning 5)
10708 (>= (point) (match-beginning 5)))))
10709 (org-tags-view arg (substring (match-string 5) 0 -1)))
10710 ((eq type 'link)
10711 (let ((type (org-element-property :type context))
10712 (path (org-link-unescape (org-element-property :path context))))
10713 ;; Switch back to REFERENCE-BUFFER needed when called in
10714 ;; a temporary buffer through `org-open-link-from-string'.
10715 (with-current-buffer (or reference-buffer (current-buffer))
10716 (cond
10717 ((equal type "file")
10718 (if (string-match "[*?{]" (file-name-nondirectory path))
10719 (dired path)
10720 ;; Look into `org-link-parameters' in order to find
10721 ;; a DEDICATED-FUNCTION to open file. The function
10722 ;; will be applied on raw link instead of parsed
10723 ;; link due to the limitation in `org-add-link-type'
10724 ;; ("open" function called with a single argument).
10725 ;; If no such function is found, fallback to
10726 ;; `org-open-file'.
10727 (let* ((option (org-element-property :search-option context))
10728 (app (org-element-property :application context))
10729 (dedicated-function
10730 (org-link-get-parameter
10731 (if app (concat type "+" app) type)
10732 :follow)))
10733 (if dedicated-function
10734 (funcall dedicated-function
10735 (concat path
10736 (and option (concat "::" option))))
10737 (apply #'org-open-file
10738 path
10739 (cond (arg)
10740 ((equal app "emacs") 'emacs)
10741 ((equal app "sys") 'system))
10742 (cond ((not option) nil)
10743 ((string-match-p "\\`[0-9]+\\'" option)
10744 (list (string-to-number option)))
10745 (t (list nil
10746 (org-link-unescape option)))))))))
10747 ((functionp (org-link-get-parameter type :follow))
10748 (funcall (org-link-get-parameter type :follow) path))
10749 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10750 (unless (run-hook-with-args-until-success
10751 'org-open-link-functions path)
10752 (if (not arg) (org-mark-ring-push)
10753 (switch-to-buffer-other-window
10754 (org-get-buffer-for-internal-link (current-buffer))))
10755 (let ((destination
10756 (org-with-wide-buffer
10757 (if (equal type "radio")
10758 (org-search-radio-target
10759 (org-element-property :path context))
10760 (org-link-search
10761 (if (member type '("custom-id" "coderef"))
10762 (org-element-property :raw-link context)
10763 path)
10764 ;; Prevent fuzzy links from matching
10765 ;; themselves.
10766 (and (equal type "fuzzy")
10767 (+ 2 (org-element-property :begin context)))))
10768 (point))))
10769 (unless (and (<= (point-min) destination)
10770 (>= (point-max) destination))
10771 (widen))
10772 (goto-char destination))))
10773 (t (browse-url-at-point))))))
10774 ;; On a footnote reference or at a footnote definition's label.
10775 ((or (eq type 'footnote-reference)
10776 (and (eq type 'footnote-definition)
10777 (save-excursion
10778 ;; Do not validate action when point is on the
10779 ;; spaces right after the footnote label, in
10780 ;; order to be on par with behaviour on links.
10781 (skip-chars-forward " \t")
10782 (let ((begin
10783 (org-element-property :contents-begin context)))
10784 (if begin (< (point) begin)
10785 (= (org-element-property :post-affiliated context)
10786 (line-beginning-position)))))))
10787 (org-footnote-action))
10788 (t (user-error "No link found")))))
10789 (run-hook-with-args 'org-follow-link-hook)))
10791 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10792 "Offer links in the current entry and return the selected link.
10793 If there is only one link, return it.
10794 If NTH is an integer, return the NTH link found.
10795 If ZERO is a string, check also this string for a link, and if
10796 there is one, return it."
10797 (with-current-buffer buffer
10798 (org-with-wide-buffer
10799 (goto-char marker)
10800 (let ((cnt ?0)
10801 have-zero end links link c)
10802 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10803 (push (match-string 0 zero) links)
10804 (setq cnt (1- cnt) have-zero t))
10805 (save-excursion
10806 (org-back-to-heading t)
10807 (setq end (save-excursion (outline-next-heading) (point)))
10808 (while (re-search-forward org-any-link-re end t)
10809 (push (match-string 0) links))
10810 (setq links (org-uniquify (reverse links))))
10811 (cond
10812 ((null links)
10813 (message "No links"))
10814 ((equal (length links) 1)
10815 (setq link (car links)))
10816 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10817 (setq link (nth (if have-zero nth (1- nth)) links)))
10818 (t ; we have to select a link
10819 (save-excursion
10820 (save-window-excursion
10821 (delete-other-windows)
10822 (with-output-to-temp-buffer "*Select Link*"
10823 (dolist (l links)
10824 (cond
10825 ((not (string-match org-bracket-link-regexp l))
10826 (princ (format "[%c] %s\n" (cl-incf cnt)
10827 (org-unbracket-string "<" ">" l))))
10828 ((match-end 3)
10829 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10830 (match-string 3 l) (match-string 1 l))))
10831 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10832 (match-string 1 l)))))))
10833 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10834 (message "Select link to open, RET to open all:")
10835 (setq c (read-char-exclusive))
10836 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10837 (when (equal c ?q) (user-error "Abort"))
10838 (if (equal c ?\C-m)
10839 (setq link links)
10840 (setq nth (- c ?0))
10841 (when have-zero (setq nth (1+ nth)))
10842 (unless (and (integerp nth) (>= (length links) nth))
10843 (user-error "Invalid link selection"))
10844 (setq link (nth (1- nth) links)))))
10845 (cons link end)))))
10847 ;; TODO: These functions are deprecated since `org-open-at-point'
10848 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10849 (defun org-open-file-with-system (path)
10850 "Open file at PATH using the system way of opening it."
10851 (org-open-file path 'system))
10852 (defun org-open-file-with-emacs (path)
10853 "Open file at PATH in Emacs."
10854 (org-open-file path 'emacs))
10857 ;;; File search
10859 (defvar org-create-file-search-functions nil
10860 "List of functions to construct the right search string for a file link.
10861 These functions are called in turn with point at the location to
10862 which the link should point.
10864 A function in the hook should first test if it would like to
10865 handle this file type, for example by checking the `major-mode'
10866 or the file extension. If it decides not to handle this file, it
10867 should just return nil to give other functions a chance. If it
10868 does handle the file, it must return the search string to be used
10869 when following the link. The search string will be part of the
10870 file link, given after a double colon, and `org-open-at-point'
10871 will automatically search for it. If special measures must be
10872 taken to make the search successful, another function should be
10873 added to the companion hook `org-execute-file-search-functions',
10874 which see.
10876 A function in this hook may also use `setq' to set the variable
10877 `description' to provide a suggestion for the descriptive text to
10878 be used for this link when it gets inserted into an Org buffer
10879 with \\[org-insert-link].")
10881 (defvar org-execute-file-search-functions nil
10882 "List of functions to execute a file search triggered by a link.
10884 Functions added to this hook must accept a single argument, the
10885 search string that was part of the file link, the part after the
10886 double colon. The function must first check if it would like to
10887 handle this search, for example by checking the `major-mode' or
10888 the file extension. If it decides not to handle this search, it
10889 should just return nil to give other functions a chance. If it
10890 does handle the search, it must return a non-nil value to keep
10891 other functions from trying.
10893 Each function can access the current prefix argument through the
10894 variable `current-prefix-arg'. Note that a single prefix is used
10895 to force opening a link in Emacs, so it may be good to only use a
10896 numeric or double prefix to guide the search function.
10898 In case this is needed, a function in this hook can also restore
10899 the window configuration before `org-open-at-point' was called using:
10901 (set-window-configuration org-window-config-before-follow-link)")
10903 (defun org-search-radio-target (target)
10904 "Search a radio target matching TARGET in current buffer.
10905 White spaces are not significant."
10906 (let ((re (format "<<<%s>>>"
10907 (mapconcat #'regexp-quote
10908 (org-split-string target "[ \t\n]+")
10909 "[ \t]+\\(?:\n[ \t]*\\)?")))
10910 (origin (point)))
10911 (goto-char (point-min))
10912 (catch :radio-match
10913 (while (re-search-forward re nil t)
10914 (backward-char)
10915 (let ((object (org-element-context)))
10916 (when (eq (org-element-type object) 'radio-target)
10917 (goto-char (org-element-property :begin object))
10918 (org-show-context 'link-search)
10919 (throw :radio-match nil))))
10920 (goto-char origin)
10921 (user-error "No match for radio target: %s" target))))
10923 (defun org-link-search (s &optional avoid-pos stealth)
10924 "Search for a search string S.
10926 If S starts with \"#\", it triggers a custom ID search.
10928 If S is enclosed within parenthesis, it initiates a coderef
10929 search.
10931 If S is surrounded by forward slashes, it is interpreted as
10932 a regular expression. In Org mode files, this will create an
10933 `org-occur' sparse tree. In ordinary files, `occur' will be used
10934 to list matches. If the current buffer is in `dired-mode', grep
10935 will be used to search in all files.
10937 When AVOID-POS is given, ignore matches near that position.
10939 When optional argument STEALTH is non-nil, do not modify
10940 visibility around point, thus ignoring `org-show-context-detail'
10941 variable.
10943 Search is case-insensitive and ignores white spaces. Return type
10944 of matched result, which is either `dedicated' or `fuzzy'."
10945 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10946 (let* ((case-fold-search t)
10947 (origin (point))
10948 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10949 (starred (eq (string-to-char normalized) ?*))
10950 (words (split-string (if starred (substring s 1) s)))
10951 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10952 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10953 type)
10954 (cond
10955 ;; Check if there are any special search functions.
10956 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10957 ((eq (string-to-char s) ?#)
10958 ;; Look for a custom ID S if S starts with "#".
10959 (let* ((id (substring normalized 1))
10960 (match (org-find-property "CUSTOM_ID" id)))
10961 (if match (progn (goto-char match) (setf type 'dedicated))
10962 (error "No match for custom ID: %s" id))))
10963 ((string-match "\\`(\\(.*\\))\\'" normalized)
10964 ;; Look for coderef targets if S is enclosed within parenthesis.
10965 (let ((coderef (match-string-no-properties 1 normalized))
10966 (re (substring s-single-re 1 -1)))
10967 (goto-char (point-min))
10968 (catch :coderef-match
10969 (while (re-search-forward re nil t)
10970 (let ((element (org-element-at-point)))
10971 (when (and (memq (org-element-type element)
10972 '(example-block src-block))
10973 ;; Build proper regexp according to current
10974 ;; block's label format.
10975 (let ((label-fmt
10976 (regexp-quote
10977 (or (org-element-property :label-fmt element)
10978 org-coderef-label-format))))
10979 (save-excursion
10980 (beginning-of-line)
10981 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10982 (format label-fmt coderef))))))
10983 (setq type 'dedicated)
10984 (goto-char (match-beginning 1))
10985 (throw :coderef-match nil))))
10986 (goto-char origin)
10987 (error "No match for coderef: %s" coderef))))
10988 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10989 ;; Look for a regular expression.
10990 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10991 (match-string 1 s)))
10992 ;; From here, we handle fuzzy links.
10994 ;; Look for targets, only if not in a headline search.
10995 ((and (not starred)
10996 (let ((target (format "<<%s>>" s-multi-re)))
10997 (catch :target-match
10998 (goto-char (point-min))
10999 (while (re-search-forward target nil t)
11000 (backward-char)
11001 (let ((context (org-element-context)))
11002 (when (eq (org-element-type context) 'target)
11003 (setq type 'dedicated)
11004 (goto-char (org-element-property :begin context))
11005 (throw :target-match t))))
11006 nil))))
11007 ;; Look for elements named after S, only if not in a headline
11008 ;; search.
11009 ((and (not starred)
11010 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11011 (catch :name-match
11012 (goto-char (point-min))
11013 (while (re-search-forward name nil t)
11014 (let ((element (org-element-at-point)))
11015 (when (equal words
11016 (split-string
11017 (org-element-property :name element)))
11018 (setq type 'dedicated)
11019 (beginning-of-line)
11020 (throw :name-match t))))
11021 nil))))
11022 ;; Regular text search. Prefer headlines in Org mode buffers.
11023 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11024 ;; statistics cookies and tags.
11025 ((and (derived-mode-p 'org-mode)
11026 (let ((title-re
11027 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11028 org-outline-regexp-bol
11029 org-comment-string
11030 (mapconcat #'regexp-quote words ".+")))
11031 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11032 (comment-re (eval-when-compile
11033 (format "\\`%s[ \t]+" org-comment-string))))
11034 (goto-char (point-min))
11035 (catch :found
11036 (while (re-search-forward title-re nil t)
11037 (when (equal words
11038 (split-string
11039 (replace-regexp-in-string
11040 cookie-re ""
11041 (replace-regexp-in-string
11042 comment-re "" (org-get-heading t t t)))))
11043 (throw :found t)))
11044 nil)))
11045 (beginning-of-line)
11046 (setq type 'dedicated))
11047 ;; Offer to create non-existent headline depending on
11048 ;; `org-link-search-must-match-exact-headline'.
11049 ((and (derived-mode-p 'org-mode)
11050 (not org-link-search-inhibit-query)
11051 (eq org-link-search-must-match-exact-headline 'query-to-create)
11052 (yes-or-no-p "No match - create this as a new heading? "))
11053 (goto-char (point-max))
11054 (unless (bolp) (newline))
11055 (org-insert-heading nil t t)
11056 (insert s "\n")
11057 (beginning-of-line 0))
11058 ;; Only headlines are looked after. No need to process
11059 ;; further: throw an error.
11060 ((and (derived-mode-p 'org-mode)
11061 (or starred org-link-search-must-match-exact-headline))
11062 (goto-char origin)
11063 (error "No match for fuzzy expression: %s" normalized))
11064 ;; Regular text search.
11065 ((catch :fuzzy-match
11066 (goto-char (point-min))
11067 (while (re-search-forward s-multi-re nil t)
11068 ;; Skip match if it contains AVOID-POS or it is included in
11069 ;; a link with a description but outside the description.
11070 (unless (or (and avoid-pos
11071 (<= (match-beginning 0) avoid-pos)
11072 (> (match-end 0) avoid-pos))
11073 (and (save-match-data
11074 (org-in-regexp org-bracket-link-regexp))
11075 (match-beginning 3)
11076 (or (> (match-beginning 3) (point))
11077 (<= (match-end 3) (point)))
11078 (org-element-lineage
11079 (save-match-data (org-element-context))
11080 '(link) t)))
11081 (goto-char (match-beginning 0))
11082 (setq type 'fuzzy)
11083 (throw :fuzzy-match t)))
11084 nil))
11085 ;; All failed. Throw an error.
11086 (t (goto-char origin)
11087 (error "No match for fuzzy expression: %s" normalized)))
11088 ;; Disclose surroundings of match, if appropriate.
11089 (when (and (derived-mode-p 'org-mode) (not stealth))
11090 (org-show-context 'link-search))
11091 type))
11093 (defun org-get-buffer-for-internal-link (buffer)
11094 "Return a buffer to be used for displaying the link target of internal links."
11095 (cond
11096 ((not org-display-internal-link-with-indirect-buffer)
11097 buffer)
11098 ((string-suffix-p "(Clone)" (buffer-name buffer))
11099 (message "Buffer is already a clone, not making another one")
11100 ;; we also do not modify visibility in this case
11101 buffer)
11102 (t ; make a new indirect buffer for displaying the link
11103 (let* ((bn (buffer-name buffer))
11104 (ibn (concat bn "(Clone)"))
11105 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11106 (with-current-buffer ib (org-overview))
11107 ib))))
11109 (defun org-do-occur (regexp &optional cleanup)
11110 "Call the Emacs command `occur'.
11111 If CLEANUP is non-nil, remove the printout of the regular expression
11112 in the *Occur* buffer. This is useful if the regex is long and not useful
11113 to read."
11114 (occur regexp)
11115 (when cleanup
11116 (let ((cwin (selected-window)) win beg end)
11117 (when (setq win (get-buffer-window "*Occur*"))
11118 (select-window win))
11119 (goto-char (point-min))
11120 (when (re-search-forward "match[a-z]+" nil t)
11121 (setq beg (match-end 0))
11122 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11123 (setq end (1- (match-beginning 0)))))
11124 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11125 (goto-char (point-min))
11126 (select-window cwin))))
11128 ;;; The mark ring for links jumps
11130 (defvar org-mark-ring nil
11131 "Mark ring for positions before jumps in Org mode.")
11132 (defvar org-mark-ring-last-goto nil
11133 "Last position in the mark ring used to go back.")
11134 ;; Fill and close the ring
11135 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11136 (dotimes (_ org-mark-ring-length)
11137 (push (make-marker) org-mark-ring))
11138 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11139 org-mark-ring)
11141 (defun org-mark-ring-push (&optional pos buffer)
11142 "Put the current position or POS into the mark ring and rotate it."
11143 (interactive)
11144 (setq pos (or pos (point)))
11145 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11146 (move-marker (car org-mark-ring)
11147 (or pos (point))
11148 (or buffer (current-buffer)))
11149 (message "%s"
11150 (substitute-command-keys
11151 "Position saved to mark ring, go back with \
11152 `\\[org-mark-ring-goto]'.")))
11154 (defun org-mark-ring-goto (&optional n)
11155 "Jump to the previous position in the mark ring.
11156 With prefix arg N, jump back that many stored positions. When
11157 called several times in succession, walk through the entire ring.
11158 Org mode commands jumping to a different position in the current file,
11159 or to another Org file, automatically push the old position onto the ring."
11160 (interactive "p")
11161 (let (p m)
11162 (if (eq last-command this-command)
11163 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11164 (setq p org-mark-ring))
11165 (setq org-mark-ring-last-goto p)
11166 (setq m (car p))
11167 (pop-to-buffer-same-window (marker-buffer m))
11168 (goto-char m)
11169 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11171 (defun org-add-angle-brackets (s)
11172 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11173 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11176 ;;; Following specific links
11178 (defvar org-agenda-buffer-tmp-name)
11179 (defvar org-agenda-start-on-weekday)
11180 (defun org-follow-timestamp-link ()
11181 "Open an agenda view for the time-stamp date/range at point."
11182 (cond
11183 ((org-at-date-range-p t)
11184 (let ((org-agenda-start-on-weekday)
11185 (t1 (match-string 1))
11186 (t2 (match-string 2)) tt1 tt2)
11187 (setq tt1 (time-to-days (org-time-string-to-time t1))
11188 tt2 (time-to-days (org-time-string-to-time t2)))
11189 (let ((org-agenda-buffer-tmp-name
11190 (format "*Org Agenda(a:%s)"
11191 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11192 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11193 ((org-at-timestamp-p t)
11194 (let ((org-agenda-buffer-tmp-name
11195 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11196 (org-agenda-list nil (time-to-days (org-time-string-to-time
11197 (substring (match-string 1) 0 10)))
11198 1)))
11199 (t (error "This should not happen"))))
11202 ;;; Following file links
11203 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11204 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11205 (declare-function mailcap-mime-info
11206 "mailcap" (string &optional request no-decode))
11207 (defvar org-wait nil)
11208 (defun org-open-file (path &optional in-emacs line search)
11209 "Open the file at PATH.
11210 First, this expands any special file name abbreviations. Then the
11211 configuration variable `org-file-apps' is checked if it contains an
11212 entry for this file type, and if yes, the corresponding command is launched.
11214 If no application is found, Emacs simply visits the file.
11216 With optional prefix argument IN-EMACS, Emacs will visit the file.
11217 With a double \\[universal-argument] \\[universal-argument] \
11218 prefix arg, Org tries to avoid opening in Emacs
11219 and to use an external application to visit the file.
11221 Optional LINE specifies a line to go to, optional SEARCH a string
11222 to search for. If LINE or SEARCH is given, the file will be
11223 opened in Emacs, unless an entry from org-file-apps that makes
11224 use of groups in a regexp matches.
11226 If you want to change the way frames are used when following a
11227 link, please customize `org-link-frame-setup'.
11229 If the file does not exist, an error is thrown."
11230 (let* ((file (if (equal path "")
11231 buffer-file-name
11232 (substitute-in-file-name (expand-file-name path))))
11233 (file-apps (append org-file-apps (org-default-apps)))
11234 (apps (cl-remove-if
11235 'org-file-apps-entry-match-against-dlink-p file-apps))
11236 (apps-dlink (cl-remove-if-not
11237 'org-file-apps-entry-match-against-dlink-p file-apps))
11238 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11239 (dirp (unless remp (file-directory-p file)))
11240 (file (if (and dirp org-open-directory-means-index-dot-org)
11241 (concat (file-name-as-directory file) "index.org")
11242 file))
11243 (a-m-a-p (assq 'auto-mode apps))
11244 (dfile (downcase file))
11245 ;; Reconstruct the original link from the PATH, LINE and
11246 ;; SEARCH args.
11247 (link (cond (line (concat file "::" (number-to-string line)))
11248 (search (concat file "::" search))
11249 (t file)))
11250 (dlink (downcase link))
11251 (ext
11252 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11253 (match-string 1 dfile)))
11254 (save-position-maybe
11255 (let ((old-buffer (current-buffer))
11256 (old-pos (point))
11257 (old-mode major-mode))
11258 (lambda ()
11259 (and (derived-mode-p 'org-mode)
11260 (eq old-mode 'org-mode)
11261 (or (not (eq old-buffer (current-buffer)))
11262 (not (eq old-pos (point))))
11263 (org-mark-ring-push old-pos old-buffer)))))
11264 cmd link-match-data)
11265 (cond
11266 ((member in-emacs '((16) system))
11267 (setq cmd (cdr (assq 'system apps))))
11268 (in-emacs (setq cmd 'emacs))
11270 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11271 (and dirp (cdr (assq 'directory apps)))
11272 ;; First, try matching against apps-dlink if we
11273 ;; get a match here, store the match data for
11274 ;; later.
11275 (let ((match (assoc-default dlink apps-dlink
11276 'string-match)))
11277 (if match
11278 (progn (setq link-match-data (match-data))
11279 match)
11280 (progn (setq in-emacs (or in-emacs line search))
11281 nil))) ; if we have no match in apps-dlink,
11282 ; always open the file in emacs if line or search
11283 ; is given (for backwards compatibility)
11284 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11285 'string-match)
11286 (cdr (assoc ext apps))
11287 (cdr (assq t apps))))))
11288 (when (eq cmd 'system)
11289 (setq cmd (cdr (assq 'system apps))))
11290 (when (eq cmd 'default)
11291 (setq cmd (cdr (assoc t apps))))
11292 (when (eq cmd 'mailcap)
11293 (require 'mailcap)
11294 (mailcap-parse-mailcaps)
11295 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11296 (command (mailcap-mime-info mime-type)))
11297 (if (stringp command)
11298 (setq cmd command)
11299 (setq cmd 'emacs))))
11300 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11301 (not (file-exists-p file))
11302 (not org-open-non-existing-files))
11303 (user-error "No such file: %s" file))
11304 (cond
11305 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11306 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11307 (while (string-match "['\"]%s['\"]" cmd)
11308 (setq cmd (replace-match "%s" t t cmd)))
11309 (setq cmd (replace-regexp-in-string
11310 "%s"
11311 (shell-quote-argument (convert-standard-filename file))
11313 nil t))
11315 ;; Replace "%1", "%2" etc. in command with group matches from regex
11316 (save-match-data
11317 (let ((match-index 1)
11318 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11319 (set-match-data link-match-data)
11320 (while (<= match-index number-of-groups)
11321 (let ((regex (concat "%" (number-to-string match-index)))
11322 (replace-with (match-string match-index dlink)))
11323 (while (string-match regex cmd)
11324 (setq cmd (replace-match replace-with t t cmd))))
11325 (setq match-index (+ match-index 1)))))
11327 (save-window-excursion
11328 (message "Running %s...done" cmd)
11329 (start-process-shell-command cmd nil cmd)
11330 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11331 ((or (stringp cmd)
11332 (eq cmd 'emacs))
11333 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11334 (widen)
11335 (cond (line (org-goto-line line)
11336 (when (derived-mode-p 'org-mode) (org-reveal)))
11337 (search (condition-case err
11338 (org-link-search search)
11339 ;; Save position before error-ing out so user
11340 ;; can easily move back to the original buffer.
11341 (error (funcall save-position-maybe)
11342 (error (nth 1 err)))))))
11343 ((functionp cmd)
11344 (save-match-data
11345 (set-match-data link-match-data)
11346 (condition-case nil
11347 (funcall cmd file link)
11348 ;; FIXME: Remove this check when most default installations
11349 ;; of Emacs have at least Org 9.0.
11350 ((debug wrong-number-of-arguments wrong-type-argument
11351 invalid-function)
11352 (user-error "Please see Org News for version 9.0 about \
11353 `org-file-apps'--Lisp error: %S" cmd)))))
11354 ((consp cmd)
11355 ;; FIXME: Remove this check when most default installations of
11356 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11357 ;; fall back to `org-link-frame-setup' for an old usage of
11358 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11359 (user-error "Please see Org News for version 9.0 about \
11360 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11361 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11362 (funcall save-position-maybe)))
11364 (defun org-file-apps-entry-match-against-dlink-p (entry)
11365 "This function returns non-nil if `entry' uses a regular
11366 expression which should be matched against the whole link by
11367 org-open-file.
11369 It assumes that is the case when the entry uses a regular
11370 expression which has at least one grouping construct and the
11371 action is either a lisp form or a command string containing
11372 `%1', i.e. using at least one subexpression match as a
11373 parameter."
11374 (let ((selector (car entry))
11375 (action (cdr entry)))
11376 (if (stringp selector)
11377 (and (> (regexp-opt-depth selector) 0)
11378 (or (and (stringp action)
11379 (string-match "%[0-9]" action))
11380 (consp action)))
11381 nil)))
11383 (defun org-default-apps ()
11384 "Return the default applications for this operating system."
11385 (cond
11386 ((eq system-type 'darwin)
11387 org-file-apps-defaults-macosx)
11388 ((eq system-type 'windows-nt)
11389 org-file-apps-defaults-windowsnt)
11390 (t org-file-apps-defaults-gnu)))
11392 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11393 "Convert extensions to regular expressions in the cars of LIST.
11394 Also, weed out any non-string entries, because the return value is used
11395 only for regexp matching.
11396 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11397 point to the symbol `emacs', indicating that the file should
11398 be opened in Emacs."
11399 (append
11400 (delq nil
11401 (mapcar (lambda (x)
11402 (unless (not (stringp (car x)))
11403 (if (string-match "\\W" (car x))
11405 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11406 list))
11407 (when add-auto-mode
11408 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11410 (defvar ange-ftp-name-format)
11411 (defun org-file-remote-p (file)
11412 "Test whether FILE specifies a location on a remote system.
11413 Return non-nil if the location is indeed remote.
11415 For example, the filename \"/user@host:/foo\" specifies a location
11416 on the system \"/user@host:\"."
11417 (cond ((fboundp 'file-remote-p)
11418 (file-remote-p file))
11419 ((fboundp 'tramp-handle-file-remote-p)
11420 (tramp-handle-file-remote-p file))
11421 ((and (boundp 'ange-ftp-name-format)
11422 (string-match (car ange-ftp-name-format) file))
11423 t)))
11426 ;;;; Refiling
11428 (defun org-get-org-file ()
11429 "Read a filename, with default directory `org-directory'."
11430 (let ((default (or org-default-notes-file remember-data-file)))
11431 (read-file-name (format "File name [%s]: " default)
11432 (file-name-as-directory org-directory)
11433 default)))
11435 (defun org-notes-order-reversed-p ()
11436 "Check if the current file should receive notes in reversed order."
11437 (cond
11438 ((not org-reverse-note-order) nil)
11439 ((eq t org-reverse-note-order) t)
11440 ((not (listp org-reverse-note-order)) nil)
11441 (t (catch 'exit
11442 (dolist (entry org-reverse-note-order)
11443 (when (string-match (car entry) buffer-file-name)
11444 (throw 'exit (cdr entry))))))))
11446 (defvar org-refile-target-table nil
11447 "The list of refile targets, created by `org-refile'.")
11449 (defvar org-agenda-new-buffers nil
11450 "Buffers created to visit agenda files.")
11452 (defvar org-refile-cache nil
11453 "Cache for refile targets.")
11455 (defvar org-refile-markers nil
11456 "All the markers used for caching refile locations.")
11458 (defun org-refile-marker (pos)
11459 "Get a new refile marker, but only if caching is in use."
11460 (if (not org-refile-use-cache)
11462 (let ((m (make-marker)))
11463 (move-marker m pos)
11464 (push m org-refile-markers)
11465 m)))
11467 (defun org-refile-cache-clear ()
11468 "Clear the refile cache and disable all the markers."
11469 (dolist (m org-refile-markers) (move-marker m nil))
11470 (setq org-refile-markers nil)
11471 (setq org-refile-cache nil)
11472 (message "Refile cache has been cleared"))
11474 (defun org-refile-cache-check-set (set)
11475 "Check if all the markers in the cache still have live buffers."
11476 (let (marker)
11477 (catch 'exit
11478 (while (and set (setq marker (nth 3 (pop set))))
11479 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11480 (when (and marker (null (marker-buffer marker)))
11481 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11482 (sit-for 3)
11483 (throw 'exit nil)))
11484 t)))
11486 (defun org-refile-cache-put (set &rest identifiers)
11487 "Push the refile targets SET into the cache, under IDENTIFIERS."
11488 (let* ((key (sha1 (prin1-to-string identifiers)))
11489 (entry (assoc key org-refile-cache)))
11490 (if entry
11491 (setcdr entry set)
11492 (push (cons key set) org-refile-cache))))
11494 (defun org-refile-cache-get (&rest identifiers)
11495 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11496 (cond
11497 ((not org-refile-cache) nil)
11498 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11500 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11501 org-refile-cache))))
11502 (and set (org-refile-cache-check-set set) set)))))
11504 (defvar org-outline-path-cache nil
11505 "Alist between buffer positions and outline paths.
11506 It value is an alist (POSITION . PATH) where POSITION is the
11507 buffer position at the beginning of an entry and PATH is a list
11508 of strings describing the outline path for that entry, in reverse
11509 order.")
11511 (defun org-refile-get-targets (&optional default-buffer)
11512 "Produce a table with refile targets."
11513 (let ((case-fold-search nil)
11514 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11515 (entries (or org-refile-targets '((nil . (:level . 1)))))
11516 targets tgs files desc descre)
11517 (message "Getting targets...")
11518 (with-current-buffer (or default-buffer (current-buffer))
11519 (dolist (entry entries)
11520 (setq files (car entry) desc (cdr entry))
11521 (cond
11522 ((null files) (setq files (list (current-buffer))))
11523 ((eq files 'org-agenda-files)
11524 (setq files (org-agenda-files 'unrestricted)))
11525 ((and (symbolp files) (fboundp files))
11526 (setq files (funcall files)))
11527 ((and (symbolp files) (boundp files))
11528 (setq files (symbol-value files))))
11529 (when (stringp files) (setq files (list files)))
11530 (cond
11531 ((eq (car desc) :tag)
11532 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11533 ((eq (car desc) :todo)
11534 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11535 ((eq (car desc) :regexp)
11536 (setq descre (cdr desc)))
11537 ((eq (car desc) :level)
11538 (setq descre (concat "^\\*\\{" (number-to-string
11539 (if org-odd-levels-only
11540 (1- (* 2 (cdr desc)))
11541 (cdr desc)))
11542 "\\}[ \t]")))
11543 ((eq (car desc) :maxlevel)
11544 (setq descre (concat "^\\*\\{1," (number-to-string
11545 (if org-odd-levels-only
11546 (1- (* 2 (cdr desc)))
11547 (cdr desc)))
11548 "\\}[ \t]")))
11549 (t (error "Bad refiling target description %s" desc)))
11550 (dolist (f files)
11551 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11553 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11554 (progn
11555 (when (bufferp f)
11556 (setq f (buffer-file-name (buffer-base-buffer f))))
11557 (setq f (and f (expand-file-name f)))
11558 (when (eq org-refile-use-outline-path 'file)
11559 (push (list (file-name-nondirectory f) f nil nil) tgs))
11560 (org-with-wide-buffer
11561 (goto-char (point-min))
11562 (setq org-outline-path-cache nil)
11563 (while (re-search-forward descre nil t)
11564 (beginning-of-line)
11565 (let ((case-fold-search nil))
11566 (looking-at org-complex-heading-regexp))
11567 (let ((begin (point))
11568 (heading (match-string-no-properties 4)))
11569 (unless (or (and
11570 org-refile-target-verify-function
11571 (not
11572 (funcall org-refile-target-verify-function)))
11573 (not heading))
11574 (let ((re (format org-complex-heading-regexp-format
11575 (regexp-quote heading)))
11576 (target
11577 (if (not org-refile-use-outline-path) heading
11578 (mapconcat
11579 #'org-protect-slash
11580 (append
11581 (pcase org-refile-use-outline-path
11582 (`file (list (file-name-nondirectory
11583 (buffer-file-name
11584 (buffer-base-buffer)))))
11585 (`full-file-path
11586 (list (buffer-file-name
11587 (buffer-base-buffer))))
11588 (_ nil))
11589 (org-get-outline-path t t))
11590 "/"))))
11591 (push (list target f re (org-refile-marker (point)))
11592 tgs)))
11593 (when (= (point) begin)
11594 ;; Verification function has not moved point.
11595 (end-of-line)))))))
11596 (when org-refile-use-cache
11597 (org-refile-cache-put tgs (buffer-file-name) descre))
11598 (setq targets (append tgs targets))))))
11599 (message "Getting targets...done")
11600 (nreverse targets)))
11602 (defun org-protect-slash (s)
11603 (replace-regexp-in-string "/" "\\/" s nil t))
11605 (defun org--get-outline-path-1 (&optional use-cache)
11606 "Return outline path to current headline.
11608 Outline path is a list of strings, in reverse order. When
11609 optional argument USE-CACHE is non-nil, make use of a cache. See
11610 `org-get-outline-path' for details.
11612 Assume buffer is widened and point is on a headline."
11613 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11614 (let ((p (point))
11615 (heading (let ((case-fold-search nil))
11616 (looking-at org-complex-heading-regexp)
11617 (if (not (match-end 4)) ""
11618 ;; Remove statistics cookies.
11619 (org-trim
11620 (org-link-display-format
11621 (replace-regexp-in-string
11622 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11623 (match-string-no-properties 4))))))))
11624 (if (org-up-heading-safe)
11625 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11626 (when use-cache
11627 (push (cons p path) org-outline-path-cache))
11628 path)
11629 ;; This is a new root node. Since we assume we are moving
11630 ;; forward, we can drop previous cache so as to limit number
11631 ;; of associations there.
11632 (let ((path (list heading)))
11633 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11634 path)))))
11636 (defun org-get-outline-path (&optional with-self use-cache)
11637 "Return the outline path to the current entry.
11639 An outline path is a list of ancestors for current headline, as
11640 a list of strings. Statistics cookies are removed and links are
11641 replaced with their description, if any, or their path otherwise.
11643 When optional argument WITH-SELF is non-nil, the path also
11644 includes the current headline.
11646 When optional argument USE-CACHE is non-nil, cache outline paths
11647 between calls to this function so as to avoid backtracking. This
11648 argument is useful when planning to find more than one outline
11649 path in the same document. In that case, there are two
11650 conditions to satisfy:
11651 - `org-outline-path-cache' is set to nil before starting the
11652 process;
11653 - outline paths are computed by increasing buffer positions."
11654 (org-with-wide-buffer
11655 (and (or (and with-self (org-back-to-heading t))
11656 (org-up-heading-safe))
11657 (reverse (org--get-outline-path-1 use-cache)))))
11659 (defun org-format-outline-path (path &optional width prefix separator)
11660 "Format the outline path PATH for display.
11661 WIDTH is the maximum number of characters that is available.
11662 PREFIX is a prefix to be included in the returned string,
11663 such as the file name.
11664 SEPARATOR is inserted between the different parts of the path,
11665 the default is \"/\"."
11666 (setq width (or width 79))
11667 (setq path (delq nil path))
11668 (unless (> width 0)
11669 (user-error "Argument `width' must be positive"))
11670 (setq separator (or separator "/"))
11671 (let* ((org-odd-levels-only nil)
11672 (fpath (concat
11673 prefix (and prefix path separator)
11674 (mapconcat
11675 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11676 (cl-loop for head in path
11677 for n from 0
11678 collect (org-add-props
11679 head nil 'face
11680 (nth (% n org-n-level-faces) org-level-faces)))
11681 separator))))
11682 (when (> (length fpath) width)
11683 (if (< width 7)
11684 ;; It's unlikely that `width' will be this small, but don't
11685 ;; waste characters by adding ".." if it is.
11686 (setq fpath (substring fpath 0 width))
11687 (setf (substring fpath (- width 2)) "..")))
11688 fpath))
11690 (defun org-display-outline-path (&optional file current separator just-return-string)
11691 "Display the current outline path in the echo area.
11693 If FILE is non-nil, prepend the output with the file name.
11694 If CURRENT is non-nil, append the current heading to the output.
11695 SEPARATOR is passed through to `org-format-outline-path'. It separates
11696 the different parts of the path and defaults to \"/\".
11697 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11698 (interactive "P")
11699 (let* (case-fold-search
11700 (bfn (buffer-file-name (buffer-base-buffer)))
11701 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11702 res)
11703 (when current (setq path (append path
11704 (save-excursion
11705 (org-back-to-heading t)
11706 (when (looking-at org-complex-heading-regexp)
11707 (list (match-string 4)))))))
11708 (setq res
11709 (org-format-outline-path
11710 path
11711 (1- (frame-width))
11712 (and file bfn (concat (file-name-nondirectory bfn) separator))
11713 separator))
11714 (if just-return-string
11715 (org-no-properties res)
11716 (org-unlogged-message "%s" res))))
11718 (defvar org-refile-history nil
11719 "History for refiling operations.")
11721 (defvar org-after-refile-insert-hook nil
11722 "Hook run after `org-refile' has inserted its stuff at the new location.
11723 Note that this is still *before* the stuff will be removed from
11724 the *old* location.")
11726 (defvar org-capture-last-stored-marker)
11727 (defvar org-refile-keep nil
11728 "Non-nil means `org-refile' will copy instead of refile.")
11730 (defun org-copy ()
11731 "Like `org-refile', but copy."
11732 (interactive)
11733 (let ((org-refile-keep t))
11734 (funcall 'org-refile nil nil nil "Copy")))
11736 (defun org-refile (&optional arg default-buffer rfloc msg)
11737 "Move the entry or entries at point to another heading.
11739 The list of target headings is compiled using the information in
11740 `org-refile-targets', which see.
11742 At the target location, the entry is filed as a subitem of the
11743 target heading. Depending on `org-reverse-note-order', the new
11744 subitem will either be the first or the last subitem.
11746 If there is an active region, all entries in that region will be
11747 refiled. However, the region must fulfill the requirement that
11748 the first heading sets the top-level of the moved text.
11750 With a `\\[universal-argument]' ARG, the command will only visit the target \
11751 location
11752 and not actually move anything.
11754 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11755 location where the last
11756 refiling operation has put the subtree.
11758 With a numeric prefix argument of `2', refile to the running clock.
11760 With a numeric prefix argument of `3', emulate `org-refile-keep'
11761 being set to t and copy to the target location, don't move it.
11762 Beware that keeping refiled entries may result in duplicated ID
11763 properties.
11765 RFLOC can be a refile location obtained in a different way.
11767 MSG is a string to replace \"Refile\" in the default prompt with
11768 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11770 See also `org-refile-use-outline-path'.
11772 If you are using target caching (see `org-refile-use-cache'), you
11773 have to clear the target cache in order to find new targets.
11774 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11775 prefix argument (`C-u C-u C-u C-c C-w')."
11776 (interactive "P")
11777 (if (member arg '(0 (64)))
11778 (org-refile-cache-clear)
11779 (let* ((actionmsg (cond (msg msg)
11780 ((equal arg 3) "Refile (and keep)")
11781 (t "Refile")))
11782 (regionp (org-region-active-p))
11783 (region-start (and regionp (region-beginning)))
11784 (region-end (and regionp (region-end)))
11785 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11786 pos it nbuf file level reversed)
11787 (setq last-command nil)
11788 (when regionp
11789 (goto-char region-start)
11790 (or (bolp) (goto-char (point-at-bol)))
11791 (setq region-start (point))
11792 (unless (or (org-kill-is-subtree-p
11793 (buffer-substring region-start region-end))
11794 (prog1 org-refile-active-region-within-subtree
11795 (let ((s (point-at-eol)))
11796 (org-toggle-heading)
11797 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11798 (user-error "The region is not a (sequence of) subtree(s)")))
11799 (if (equal arg '(16))
11800 (org-refile-goto-last-stored)
11801 (when (or
11802 (and (equal arg 2)
11803 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11804 (prog1
11805 (setq it (list (or org-clock-heading "running clock")
11806 (buffer-file-name
11807 (marker-buffer org-clock-hd-marker))
11809 (marker-position org-clock-hd-marker)))
11810 (setq arg nil)))
11811 (setq it
11812 (or rfloc
11813 (let (heading-text)
11814 (save-excursion
11815 (unless (and arg (listp arg))
11816 (org-back-to-heading t)
11817 (setq heading-text
11818 (replace-regexp-in-string
11819 org-bracket-link-regexp
11820 "\\3"
11821 (or (nth 4 (org-heading-components))
11822 ""))))
11823 (org-refile-get-location
11824 (cond ((and arg (listp arg)) "Goto")
11825 (regionp (concat actionmsg " region to"))
11826 (t (concat actionmsg " subtree \""
11827 heading-text "\" to")))
11828 default-buffer
11829 (and (not (equal '(4) arg))
11830 org-refile-allow-creating-parent-nodes)))))))
11831 (setq file (nth 1 it)
11832 pos (nth 3 it))
11833 (when (and (not arg)
11835 (equal (buffer-file-name) file)
11836 (if regionp
11837 (and (>= pos region-start)
11838 (<= pos region-end))
11839 (and (>= pos (point))
11840 (< pos (save-excursion
11841 (org-end-of-subtree t t))))))
11842 (error "Cannot refile to position inside the tree or region"))
11843 (setq nbuf (or (find-buffer-visiting file)
11844 (find-file-noselect file)))
11845 (if (and arg (not (equal arg 3)))
11846 (progn
11847 (pop-to-buffer-same-window nbuf)
11848 (goto-char pos)
11849 (org-show-context 'org-goto))
11850 (if regionp
11851 (progn
11852 (org-kill-new (buffer-substring region-start region-end))
11853 (org-save-markers-in-region region-start region-end))
11854 (org-copy-subtree 1 nil t))
11855 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11856 (find-file-noselect file)))
11857 (setq reversed (org-notes-order-reversed-p))
11858 (org-with-wide-buffer
11859 (if pos
11860 (progn
11861 (goto-char pos)
11862 (setq level (org-get-valid-level (funcall outline-level) 1))
11863 (goto-char
11864 (if reversed
11865 (or (outline-next-heading) (point-max))
11866 (or (save-excursion (org-get-next-sibling))
11867 (org-end-of-subtree t t)
11868 (point-max)))))
11869 (setq level 1)
11870 (if (not reversed)
11871 (goto-char (point-max))
11872 (goto-char (point-min))
11873 (or (outline-next-heading) (goto-char (point-max)))))
11874 (unless (bolp) (newline))
11875 (org-paste-subtree level nil nil t)
11876 (when org-log-refile
11877 (org-add-log-setup 'refile nil nil org-log-refile)
11878 (unless (eq org-log-refile 'note)
11879 (save-excursion (org-add-log-note))))
11880 (and org-auto-align-tags
11881 (let ((org-loop-over-headlines-in-active-region nil))
11882 (org-set-tags nil t)))
11883 (let ((bookmark-name (plist-get org-bookmark-names-plist
11884 :last-refile)))
11885 (when bookmark-name
11886 (with-demoted-errors
11887 (bookmark-set bookmark-name))))
11888 ;; If we are refiling for capture, make sure that the
11889 ;; last-capture pointers point here
11890 (when (bound-and-true-p org-capture-is-refiling)
11891 (let ((bookmark-name (plist-get org-bookmark-names-plist
11892 :last-capture-marker)))
11893 (when bookmark-name
11894 (with-demoted-errors
11895 (bookmark-set bookmark-name))))
11896 (move-marker org-capture-last-stored-marker (point)))
11897 (when (fboundp 'deactivate-mark) (deactivate-mark))
11898 (run-hooks 'org-after-refile-insert-hook)))
11899 (unless org-refile-keep
11900 (if regionp
11901 (delete-region (point) (+ (point) (- region-end region-start)))
11902 (delete-region
11903 (and (org-back-to-heading t) (point))
11904 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11905 (when (featurep 'org-inlinetask)
11906 (org-inlinetask-remove-END-maybe))
11907 (setq org-markers-to-move nil)
11908 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11910 (defun org-refile-goto-last-stored ()
11911 "Go to the location where the last refile was stored."
11912 (interactive)
11913 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11914 (message "This is the location of the last refile"))
11916 (defun org-refile--get-location (refloc tbl)
11917 "When user refile to REFLOC, find the associated target in TBL.
11918 Also check `org-refile-target-table'."
11919 (car (delq
11921 (mapcar
11922 (lambda (r) (or (assoc r tbl)
11923 (assoc r org-refile-target-table)))
11924 (list (replace-regexp-in-string "/$" "" refloc)
11925 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11927 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11928 "Prompt the user for a refile location, using PROMPT.
11929 PROMPT should not be suffixed with a colon and a space, because
11930 this function appends the default value from
11931 `org-refile-history' automatically, if that is not empty."
11932 (let ((org-refile-targets org-refile-targets)
11933 (org-refile-use-outline-path org-refile-use-outline-path))
11934 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11935 (unless org-refile-target-table
11936 (user-error "No refile targets"))
11937 (let* ((cbuf (current-buffer))
11938 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11939 (cfunc (if (and org-refile-use-outline-path
11940 org-outline-path-complete-in-steps)
11941 #'org-olpath-completing-read
11942 #'completing-read))
11943 (extra (if org-refile-use-outline-path "/" ""))
11944 (cbnex (concat (buffer-name) extra))
11945 (filename (and cfn (expand-file-name cfn)))
11946 (tbl (mapcar
11947 (lambda (x)
11948 (if (and (not (member org-refile-use-outline-path
11949 '(file full-file-path)))
11950 (not (equal filename (nth 1 x))))
11951 (cons (concat (car x) extra " ("
11952 (file-name-nondirectory (nth 1 x)) ")")
11953 (cdr x))
11954 (cons (concat (car x) extra) (cdr x))))
11955 org-refile-target-table))
11956 (completion-ignore-case t)
11957 cdef
11958 (prompt (concat prompt
11959 (or (and (car org-refile-history)
11960 (concat " (default " (car org-refile-history) ")"))
11961 (and (assoc cbnex tbl) (setq cdef cbnex)
11962 (concat " (default " cbnex ")"))) ": "))
11963 pa answ parent-target child parent old-hist)
11964 (setq old-hist org-refile-history)
11965 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11966 nil 'org-refile-history (or cdef (car org-refile-history))))
11967 (if (setq pa (org-refile--get-location answ tbl))
11968 (progn
11969 (org-refile-check-position pa)
11970 (when (or (not org-refile-history)
11971 (not (eq old-hist org-refile-history))
11972 (not (equal (car pa) (car org-refile-history))))
11973 (setq org-refile-history
11974 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11975 org-refile-history
11976 (cdr org-refile-history))))
11977 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11978 (pop org-refile-history)))
11980 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11981 (progn
11982 (setq parent (match-string 1 answ)
11983 child (match-string 2 answ))
11984 (setq parent-target (org-refile--get-location parent tbl))
11985 (when (and parent-target
11986 (or (eq new-nodes t)
11987 (and (eq new-nodes 'confirm)
11988 (y-or-n-p (format "Create new node \"%s\"? "
11989 child)))))
11990 (org-refile-new-child parent-target child)))
11991 (user-error "Invalid target location")))))
11993 (declare-function org-string-nw-p "org-macs" (s))
11994 (defun org-refile-check-position (refile-pointer)
11995 "Check if the refile pointer matches the headline to which it points."
11996 (let* ((file (nth 1 refile-pointer))
11997 (re (nth 2 refile-pointer))
11998 (pos (nth 3 refile-pointer))
11999 buffer)
12000 (if (and (not (markerp pos)) (not file))
12001 (user-error "Please indicate a target file in the refile path")
12002 (when (org-string-nw-p re)
12003 (setq buffer (if (markerp pos)
12004 (marker-buffer pos)
12005 (or (find-buffer-visiting file)
12006 (find-file-noselect file))))
12007 (with-current-buffer buffer
12008 (org-with-wide-buffer
12009 (goto-char pos)
12010 (beginning-of-line 1)
12011 (unless (looking-at-p re)
12012 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12014 (defun org-refile-new-child (parent-target child)
12015 "Use refile target PARENT-TARGET to add new CHILD below it."
12016 (unless parent-target
12017 (error "Cannot find parent for new node"))
12018 (let ((file (nth 1 parent-target))
12019 (pos (nth 3 parent-target))
12020 level)
12021 (with-current-buffer (or (find-buffer-visiting file)
12022 (find-file-noselect file))
12023 (org-with-wide-buffer
12024 (if pos
12025 (goto-char pos)
12026 (goto-char (point-max))
12027 (unless (bolp) (newline)))
12028 (when (looking-at org-outline-regexp)
12029 (setq level (funcall outline-level))
12030 (org-end-of-subtree t t))
12031 (org-back-over-empty-lines)
12032 (insert "\n" (make-string
12033 (if pos (org-get-valid-level level 1) 1) ?*)
12034 " " child "\n")
12035 (beginning-of-line 0)
12036 (list (concat (car parent-target) "/" child) file "" (point))))))
12038 (defun org-olpath-completing-read (prompt collection &rest args)
12039 "Read an outline path like a file name."
12040 (let ((thetable collection))
12041 (apply #'completing-read
12042 prompt
12043 (lambda (string predicate &optional flag)
12044 (cond
12045 ((eq flag nil) (try-completion string thetable))
12046 ((eq flag t)
12047 (let ((l (length string)))
12048 (mapcar (lambda (x)
12049 (let ((r (substring x l))
12050 (f (if (string-match " ([^)]*)$" x)
12051 (match-string 0 x)
12052 "")))
12053 (if (string-match "/" r)
12054 (concat string (substring r 0 (match-end 0)) f)
12055 x)))
12056 (all-completions string thetable predicate))))
12057 ;; Exact match?
12058 ((eq flag 'lambda) (assoc string thetable))))
12059 args)))
12061 ;;;; Dynamic blocks
12063 (defun org-find-dblock (name)
12064 "Find the first dynamic block with name NAME in the buffer.
12065 If not found, stay at current position and return nil."
12066 (let ((case-fold-search t) pos)
12067 (save-excursion
12068 (goto-char (point-min))
12069 (setq pos (and (re-search-forward
12070 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12071 (match-beginning 0))))
12072 (when pos (goto-char pos))
12073 pos))
12075 (defun org-create-dblock (plist)
12076 "Create a dynamic block section, with parameters taken from PLIST.
12077 PLIST must contain a :name entry which is used as the name of the block."
12078 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12079 (end-of-line 1)
12080 (newline))
12081 (let ((col (current-column))
12082 (name (plist-get plist :name)))
12083 (insert "#+BEGIN: " name)
12084 (while plist
12085 (if (eq (car plist) :name)
12086 (setq plist (cddr plist))
12087 (insert " " (prin1-to-string (pop plist)))))
12088 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12089 (beginning-of-line -2)))
12091 (defun org-prepare-dblock ()
12092 "Prepare dynamic block for refresh.
12093 This empties the block, puts the cursor at the insert position and returns
12094 the property list including an extra property :name with the block name."
12095 (unless (looking-at org-dblock-start-re)
12096 (user-error "Not at a dynamic block"))
12097 (let* ((begdel (1+ (match-end 0)))
12098 (name (org-no-properties (match-string 1)))
12099 (params (append (list :name name)
12100 (read (concat "(" (match-string 3) ")")))))
12101 (save-excursion
12102 (beginning-of-line 1)
12103 (skip-chars-forward " \t")
12104 (setq params (plist-put params :indentation-column (current-column))))
12105 (unless (re-search-forward org-dblock-end-re nil t)
12106 (error "Dynamic block not terminated"))
12107 (setq params
12108 (append params
12109 (list :content (buffer-substring
12110 begdel (match-beginning 0)))))
12111 (delete-region begdel (match-beginning 0))
12112 (goto-char begdel)
12113 (open-line 1)
12114 params))
12116 (defun org-map-dblocks (&optional command)
12117 "Apply COMMAND to all dynamic blocks in the current buffer.
12118 If COMMAND is not given, use `org-update-dblock'."
12119 (let ((cmd (or command 'org-update-dblock)))
12120 (save-excursion
12121 (goto-char (point-min))
12122 (while (re-search-forward org-dblock-start-re nil t)
12123 (goto-char (match-beginning 0))
12124 (save-excursion
12125 (condition-case nil
12126 (funcall cmd)
12127 (error (message "Error during update of dynamic block"))))
12128 (unless (re-search-forward org-dblock-end-re nil t)
12129 (error "Dynamic block not terminated"))))))
12131 (defun org-dblock-update (&optional arg)
12132 "User command for updating dynamic blocks.
12133 Update the dynamic block at point. With prefix ARG, update all dynamic
12134 blocks in the buffer."
12135 (interactive "P")
12136 (if arg
12137 (org-update-all-dblocks)
12138 (or (looking-at org-dblock-start-re)
12139 (org-beginning-of-dblock))
12140 (org-update-dblock)))
12142 (defun org-update-dblock ()
12143 "Update the dynamic block at point.
12144 This means to empty the block, parse for parameters and then call
12145 the correct writing function."
12146 (interactive)
12147 (save-excursion
12148 (let* ((win (selected-window))
12149 (pos (point))
12150 (line (org-current-line))
12151 (params (org-prepare-dblock))
12152 (name (plist-get params :name))
12153 (indent (plist-get params :indentation-column))
12154 (cmd (intern (concat "org-dblock-write:" name))))
12155 (message "Updating dynamic block `%s' at line %d..." name line)
12156 (funcall cmd params)
12157 (message "Updating dynamic block `%s' at line %d...done" name line)
12158 (goto-char pos)
12159 (when (and indent (> indent 0))
12160 (setq indent (make-string indent ?\ ))
12161 (save-excursion
12162 (select-window win)
12163 (org-beginning-of-dblock)
12164 (forward-line 1)
12165 (while (not (looking-at org-dblock-end-re))
12166 (insert indent)
12167 (beginning-of-line 2))
12168 (when (looking-at org-dblock-end-re)
12169 (and (looking-at "[ \t]+")
12170 (replace-match ""))
12171 (insert indent)))))))
12173 (defun org-beginning-of-dblock ()
12174 "Find the beginning of the dynamic block at point.
12175 Error if there is no such block at point."
12176 (let ((pos (point))
12177 beg)
12178 (end-of-line 1)
12179 (if (and (re-search-backward org-dblock-start-re nil t)
12180 (setq beg (match-beginning 0))
12181 (re-search-forward org-dblock-end-re nil t)
12182 (> (match-end 0) pos))
12183 (goto-char beg)
12184 (goto-char pos)
12185 (error "Not in a dynamic block"))))
12187 (defun org-update-all-dblocks ()
12188 "Update all dynamic blocks in the buffer.
12189 This function can be used in a hook."
12190 (interactive)
12191 (when (derived-mode-p 'org-mode)
12192 (org-map-dblocks 'org-update-dblock)))
12195 ;;;; Completion
12197 (declare-function org-export-backend-options "ox" (cl-x) t)
12198 (defun org-get-export-keywords ()
12199 "Return a list of all currently understood export keywords.
12200 Export keywords include options, block names, attributes and
12201 keywords relative to each registered export back-end."
12202 (let (keywords)
12203 (dolist (backend
12204 (bound-and-true-p org-export-registered-backends)
12205 (delq nil keywords))
12206 ;; Back-end name (for keywords, like #+LATEX:)
12207 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12208 (dolist (option-entry (org-export-backend-options backend))
12209 ;; Back-end options.
12210 (push (nth 1 option-entry) keywords)))))
12212 (defconst org-options-keywords
12213 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12214 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12215 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12216 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12217 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12219 (defcustom org-structure-template-alist
12220 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12221 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12222 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12223 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12224 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12225 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12226 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12227 ("L" "#+LaTeX: ")
12228 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12229 ("H" "#+HTML: ")
12230 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12231 ("A" "#+ASCII: ")
12232 ("i" "#+INDEX: ?")
12233 ("I" "#+INCLUDE: %file ?"))
12234 "Structure completion elements.
12235 This is a list of abbreviation keys and values. The value gets inserted
12236 if you type `<' followed by the key and then press the completion key,
12237 usually `TAB'. %file will be replaced by a file name after prompting
12238 for the file using completion. The cursor will be placed at the position
12239 of the `?' in the template.
12240 There are two templates for each key, the first uses the original Org syntax,
12241 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12242 the default when the /org-mtags.el/ module has been loaded. See also the
12243 variable `org-mtags-prefer-muse-templates'."
12244 :group 'org-completion
12245 :type '(repeat
12246 (list
12247 (string :tag "Key")
12248 (string :tag "Template")))
12249 :version "26.1"
12250 :package-version '(Org . "8.3"))
12252 (defun org-try-structure-completion ()
12253 "Try to complete a structure template before point.
12254 This looks for strings like \"<e\" on an otherwise empty line and
12255 expands them."
12256 (let ((l (buffer-substring (point-at-bol) (point)))
12258 (when (and (looking-at "[ \t]*$")
12259 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12260 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12261 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12262 (match-beginning 1)) a)
12263 t)))
12265 (defun org-complete-expand-structure-template (start cell)
12266 "Expand a structure template."
12267 (let ((rpl (nth 1 cell))
12268 (ind ""))
12269 (delete-region start (point))
12270 (when (string-match "\\`[ \t]*#\\+" rpl)
12271 (cond
12272 ((bolp))
12273 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12274 (setq ind (buffer-substring (point-at-bol) (point))))
12275 (t (newline))))
12276 (setq start (point))
12277 (when (string-match "%file" rpl)
12278 (setq rpl (replace-match
12279 (concat
12280 "\""
12281 (save-match-data
12282 (abbreviate-file-name (read-file-name "Include file: ")))
12283 "\"")
12284 t t rpl)))
12285 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12286 (concat "\n" ind)))
12287 (insert rpl)
12288 (when (re-search-backward "\\?" start t) (delete-char 1))))
12290 ;;;; TODO, DEADLINE, Comments
12292 (defun org-toggle-comment ()
12293 "Change the COMMENT state of an entry."
12294 (interactive)
12295 (save-excursion
12296 (org-back-to-heading)
12297 (let ((case-fold-search nil))
12298 (looking-at org-complex-heading-regexp))
12299 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12300 (skip-chars-forward " \t")
12301 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12302 (if (org-in-commented-heading-p t)
12303 (delete-region (point)
12304 (progn (search-forward " " (line-end-position) 'move)
12305 (skip-chars-forward " \t")
12306 (point)))
12307 (insert org-comment-string)
12308 (unless (eolp) (insert " ")))))
12310 (defvar org-last-todo-state-is-todo nil
12311 "This is non-nil when the last TODO state change led to a TODO state.
12312 If the last change removed the TODO tag or switched to DONE, then
12313 this is nil.")
12315 (defvar org-setting-tags nil) ; dynamically skipped
12317 (defvar org-todo-setup-filter-hook nil
12318 "Hook for functions that pre-filter todo specs.
12319 Each function takes a todo spec and returns either nil or the spec
12320 transformed into canonical form." )
12322 (defvar org-todo-get-default-hook nil
12323 "Hook for functions that get a default item for todo.
12324 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12325 nil or a string to be used for the todo mark." )
12327 (defvar org-agenda-headline-snapshot-before-repeat)
12329 (defun org-current-effective-time ()
12330 "Return current time adjusted for `org-extend-today-until' variable."
12331 (let* ((ct (org-current-time))
12332 (dct (decode-time ct))
12333 (ct1
12334 (cond
12335 (org-use-last-clock-out-time-as-effective-time
12336 (or (org-clock-get-last-clock-out-time) ct))
12337 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12338 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12339 (t ct))))
12340 ct1))
12342 (defun org-todo-yesterday (&optional arg)
12343 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12344 (interactive "P")
12345 (if (eq major-mode 'org-agenda-mode)
12346 (apply 'org-agenda-todo-yesterday arg)
12347 (let* ((org-use-effective-time t)
12348 (hour (nth 2 (decode-time (org-current-time))))
12349 (org-extend-today-until (1+ hour)))
12350 (org-todo arg))))
12352 (defvar org-block-entry-blocking ""
12353 "First entry preventing the TODO state change.")
12355 (defun org-cancel-repeater ()
12356 "Cancel a repeater by setting its numeric value to zero."
12357 (interactive)
12358 (save-excursion
12359 (org-back-to-heading t)
12360 (let ((bound1 (point))
12361 (bound0 (save-excursion (outline-next-heading) (point))))
12362 (when (and (re-search-forward
12363 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12364 org-deadline-time-regexp "\\)\\|\\("
12365 org-ts-regexp "\\)")
12366 bound0 t)
12367 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12368 bound1 t))
12369 (replace-match "0" t nil nil 1)))))
12371 (defvar org-state) ;; dynamically scoped into this function
12372 (defun org-todo (&optional arg)
12373 "Change the TODO state of an item.
12375 The state of an item is given by a keyword at the start of the heading,
12376 like
12377 *** TODO Write paper
12378 *** DONE Call mom
12380 The different keywords are specified in the variable `org-todo-keywords'.
12381 By default the available states are \"TODO\" and \"DONE\". So, for this
12382 example: when the item starts with TODO, it is changed to DONE.
12383 When it starts with DONE, the DONE is removed. And when neither TODO nor
12384 DONE are present, add TODO at the beginning of the heading.
12386 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12387 state.
12388 With numeric prefix ARG, switch to that state.
12389 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12390 next set of TODO \
12391 keywords (nextset).
12392 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12393 prefix, circumvent any state blocking.
12394 With a numeric prefix arg of 0, inhibit note taking for the change.
12395 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12397 When called through ELisp, arg is also interpreted in the following way:
12398 `none' -> empty state
12399 \"\" -> switch to empty state
12400 `done' -> switch to DONE
12401 `nextset' -> switch to the next set of keywords
12402 `previousset' -> switch to the previous set of keywords
12403 \"WAITING\" -> switch to the specified keyword, but only if it
12404 really is a member of `org-todo-keywords'."
12405 (interactive "P")
12406 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12407 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12408 'region-start-level 'region))
12409 org-loop-over-headlines-in-active-region)
12410 (org-map-entries
12411 `(org-todo ,arg)
12412 org-loop-over-headlines-in-active-region
12413 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12414 (when (equal arg '(16)) (setq arg 'nextset))
12415 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12416 (let ((org-blocker-hook org-blocker-hook)
12417 commentp
12418 case-fold-search)
12419 (when (equal arg '(64))
12420 (setq arg nil org-blocker-hook nil))
12421 (when (and org-blocker-hook
12422 (or org-inhibit-blocking
12423 (org-entry-get nil "NOBLOCKING")))
12424 (setq org-blocker-hook nil))
12425 (save-excursion
12426 (catch 'exit
12427 (org-back-to-heading t)
12428 (when (org-in-commented-heading-p t)
12429 (org-toggle-comment)
12430 (setq commentp t))
12431 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12432 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12433 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12434 (let* ((match-data (match-data))
12435 (startpos (point-at-bol))
12436 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12437 (org-log-done org-log-done)
12438 (org-log-repeat org-log-repeat)
12439 (org-todo-log-states org-todo-log-states)
12440 (org-inhibit-logging
12441 (if (equal arg 0)
12442 (progn (setq arg nil) 'note) org-inhibit-logging))
12443 (this (match-string 1))
12444 (hl-pos (match-beginning 0))
12445 (head (org-get-todo-sequence-head this))
12446 (ass (assoc head org-todo-kwd-alist))
12447 (interpret (nth 1 ass))
12448 (done-word (nth 3 ass))
12449 (final-done-word (nth 4 ass))
12450 (org-last-state (or this ""))
12451 (completion-ignore-case t)
12452 (member (member this org-todo-keywords-1))
12453 (tail (cdr member))
12454 (org-state (cond
12455 ((and org-todo-key-trigger
12456 (or (and (equal arg '(4))
12457 (eq org-use-fast-todo-selection 'prefix))
12458 (and (not arg) org-use-fast-todo-selection
12459 (not (eq org-use-fast-todo-selection
12460 'prefix)))))
12461 ;; Use fast selection
12462 (org-fast-todo-selection))
12463 ((and (equal arg '(4))
12464 (or (not org-use-fast-todo-selection)
12465 (not org-todo-key-trigger)))
12466 ;; Read a state with completion
12467 (completing-read
12468 "State: " (mapcar #'list org-todo-keywords-1)
12469 nil t))
12470 ((eq arg 'right)
12471 (if this
12472 (if tail (car tail) nil)
12473 (car org-todo-keywords-1)))
12474 ((eq arg 'left)
12475 (unless (equal member org-todo-keywords-1)
12476 (if this
12477 (nth (- (length org-todo-keywords-1)
12478 (length tail) 2)
12479 org-todo-keywords-1)
12480 (org-last org-todo-keywords-1))))
12481 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12482 (setq arg nil))) ; hack to fall back to cycling
12483 (arg
12484 ;; user or caller requests a specific state
12485 (cond
12486 ((equal arg "") nil)
12487 ((eq arg 'none) nil)
12488 ((eq arg 'done) (or done-word (car org-done-keywords)))
12489 ((eq arg 'nextset)
12490 (or (car (cdr (member head org-todo-heads)))
12491 (car org-todo-heads)))
12492 ((eq arg 'previousset)
12493 (let ((org-todo-heads (reverse org-todo-heads)))
12494 (or (car (cdr (member head org-todo-heads)))
12495 (car org-todo-heads))))
12496 ((car (member arg org-todo-keywords-1)))
12497 ((stringp arg)
12498 (user-error "State `%s' not valid in this file" arg))
12499 ((nth (1- (prefix-numeric-value arg))
12500 org-todo-keywords-1))))
12501 ((null member) (or head (car org-todo-keywords-1)))
12502 ((equal this final-done-word) nil) ;; -> make empty
12503 ((null tail) nil) ;; -> first entry
12504 ((memq interpret '(type priority))
12505 (if (eq this-command last-command)
12506 (car tail)
12507 (if (> (length tail) 0)
12508 (or done-word (car org-done-keywords))
12509 nil)))
12511 (car tail))))
12512 (org-state (or
12513 (run-hook-with-args-until-success
12514 'org-todo-get-default-hook org-state org-last-state)
12515 org-state))
12516 (next (if org-state (concat " " org-state " ") " "))
12517 (change-plist (list :type 'todo-state-change :from this :to org-state
12518 :position startpos))
12519 dolog now-done-p)
12520 (when org-blocker-hook
12521 (setq org-last-todo-state-is-todo
12522 (not (member this org-done-keywords)))
12523 (unless (save-excursion
12524 (save-match-data
12525 (org-with-wide-buffer
12526 (run-hook-with-args-until-failure
12527 'org-blocker-hook change-plist))))
12528 (if (called-interactively-p 'interactive)
12529 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12530 this org-state org-block-entry-blocking)
12531 ;; fail silently
12532 (message "TODO state change from %s to %s blocked (by \"%s\")"
12533 this org-state org-block-entry-blocking)
12534 (throw 'exit nil))))
12535 (store-match-data match-data)
12536 (replace-match next t t)
12537 (cond ((equal this org-state)
12538 (message "TODO state was already %s" (org-trim next)))
12539 ((pos-visible-in-window-p hl-pos)
12540 (message "TODO state changed to %s" (org-trim next))))
12541 (unless head
12542 (setq head (org-get-todo-sequence-head org-state)
12543 ass (assoc head org-todo-kwd-alist)
12544 interpret (nth 1 ass)
12545 done-word (nth 3 ass)
12546 final-done-word (nth 4 ass)))
12547 (when (memq arg '(nextset previousset))
12548 (message "Keyword-Set %d/%d: %s"
12549 (- (length org-todo-sets) -1
12550 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12551 (length org-todo-sets)
12552 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12553 (setq org-last-todo-state-is-todo
12554 (not (member org-state org-done-keywords)))
12555 (setq now-done-p (and (member org-state org-done-keywords)
12556 (not (member this org-done-keywords))))
12557 (and logging (org-local-logging logging))
12558 (when (and (or org-todo-log-states org-log-done)
12559 (not (eq org-inhibit-logging t))
12560 (not (memq arg '(nextset previousset))))
12561 ;; we need to look at recording a time and note
12562 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12563 (nth 2 (assoc this org-todo-log-states))))
12564 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12565 (setq dolog 'time))
12566 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12567 (and org-state
12568 (member org-state org-not-done-keywords)
12569 (not (member this org-not-done-keywords))))
12570 ;; This is now a todo state and was not one before
12571 ;; If there was a CLOSED time stamp, get rid of it.
12572 (org-add-planning-info nil nil 'closed))
12573 (when (and now-done-p org-log-done)
12574 ;; It is now done, and it was not done before
12575 (org-add-planning-info 'closed (org-current-effective-time))
12576 (when (and (not dolog) (eq 'note org-log-done))
12577 (org-add-log-setup 'done org-state this 'note)))
12578 (when (and org-state dolog)
12579 ;; This is a non-nil state, and we need to log it
12580 (org-add-log-setup 'state org-state this dolog)))
12581 ;; Fixup tag positioning
12582 (org-todo-trigger-tag-changes org-state)
12583 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12584 (when org-provide-todo-statistics
12585 (org-update-parent-todo-statistics))
12586 (run-hooks 'org-after-todo-state-change-hook)
12587 (when (and arg (not (member org-state org-done-keywords)))
12588 (setq head (org-get-todo-sequence-head org-state)))
12589 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12590 ;; Do we need to trigger a repeat?
12591 (when now-done-p
12592 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12593 ;; This is for the agenda, take a snapshot of the headline.
12594 (save-match-data
12595 (setq org-agenda-headline-snapshot-before-repeat
12596 (org-get-heading))))
12597 (org-auto-repeat-maybe org-state))
12598 ;; Fixup cursor location if close to the keyword
12599 (when (and (outline-on-heading-p)
12600 (not (bolp))
12601 (save-excursion (beginning-of-line 1)
12602 (looking-at org-todo-line-regexp))
12603 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12604 (goto-char (or (match-end 2) (match-end 1)))
12605 (and (looking-at " ") (just-one-space)))
12606 (when org-trigger-hook
12607 (save-excursion
12608 (run-hook-with-args 'org-trigger-hook change-plist)))
12609 (when commentp (org-toggle-comment))))))))
12611 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12612 "Block turning an entry into a TODO, using the hierarchy.
12613 This checks whether the current task should be blocked from state
12614 changes. Such blocking occurs when:
12616 1. The task has children which are not all in a completed state.
12618 2. A task has a parent with the property :ORDERED:, and there
12619 are siblings prior to the current task with incomplete
12620 status.
12622 3. The parent of the task is blocked because it has siblings that should
12623 be done first, or is child of a block grandparent TODO entry."
12625 (if (not org-enforce-todo-dependencies)
12626 t ; if locally turned off don't block
12627 (catch 'dont-block
12628 ;; If this is not a todo state change, or if this entry is already DONE,
12629 ;; do not block
12630 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12631 (member (plist-get change-plist :from)
12632 (cons 'done org-done-keywords))
12633 (member (plist-get change-plist :to)
12634 (cons 'todo org-not-done-keywords))
12635 (not (plist-get change-plist :to)))
12636 (throw 'dont-block t))
12637 ;; If this task has children, and any are undone, it's blocked
12638 (save-excursion
12639 (org-back-to-heading t)
12640 (let ((this-level (funcall outline-level)))
12641 (outline-next-heading)
12642 (let ((child-level (funcall outline-level)))
12643 (while (and (not (eobp))
12644 (> child-level this-level))
12645 ;; this todo has children, check whether they are all
12646 ;; completed
12647 (when (and (not (org-entry-is-done-p))
12648 (org-entry-is-todo-p))
12649 (setq org-block-entry-blocking (org-get-heading))
12650 (throw 'dont-block nil))
12651 (outline-next-heading)
12652 (setq child-level (funcall outline-level))))))
12653 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12654 ;; any previous siblings are undone, it's blocked
12655 (save-excursion
12656 (org-back-to-heading t)
12657 (let* ((pos (point))
12658 (parent-pos (and (org-up-heading-safe) (point)))
12659 (case-fold-search nil))
12660 (unless parent-pos (throw 'dont-block t)) ; no parent
12661 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12662 (forward-line 1)
12663 (re-search-forward org-not-done-heading-regexp pos t))
12664 (setq org-block-entry-blocking (match-string 0))
12665 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12666 ;; Search further up the hierarchy, to see if an ancestor is blocked
12667 (while t
12668 (goto-char parent-pos)
12669 (unless (looking-at org-not-done-heading-regexp)
12670 (throw 'dont-block t)) ; do not block, parent is not a TODO
12671 (setq pos (point))
12672 (setq parent-pos (and (org-up-heading-safe) (point)))
12673 (unless parent-pos (throw 'dont-block t)) ; no parent
12674 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12675 (forward-line 1)
12676 (re-search-forward org-not-done-heading-regexp pos t)
12677 (setq org-block-entry-blocking (org-get-heading)))
12678 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12680 (defcustom org-track-ordered-property-with-tag nil
12681 "Should the ORDERED property also be shown as a tag?
12682 The ORDERED property decides if an entry should require subtasks to be
12683 completed in sequence. Since a property is not very visible, setting
12684 this option means that toggling the ORDERED property with the command
12685 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12686 not relevant for the behavior, but it makes things more visible.
12688 Note that toggling the tag with tags commands will not change the property
12689 and therefore not influence behavior!
12691 This can be t, meaning the tag ORDERED should be used, It can also be a
12692 string to select a different tag for this task."
12693 :group 'org-todo
12694 :type '(choice
12695 (const :tag "No tracking" nil)
12696 (const :tag "Track with ORDERED tag" t)
12697 (string :tag "Use other tag")))
12699 (defun org-toggle-ordered-property ()
12700 "Toggle the ORDERED property of the current entry.
12701 For better visibility, you can track the value of this property with a tag.
12702 See variable `org-track-ordered-property-with-tag'."
12703 (interactive)
12704 (let* ((t1 org-track-ordered-property-with-tag)
12705 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12706 (save-excursion
12707 (org-back-to-heading)
12708 (if (org-entry-get nil "ORDERED")
12709 (progn
12710 (org-delete-property "ORDERED")
12711 (and tag (org-toggle-tag tag 'off))
12712 (message "Subtasks can be completed in arbitrary order"))
12713 (org-entry-put nil "ORDERED" "t")
12714 (and tag (org-toggle-tag tag 'on))
12715 (message "Subtasks must be completed in sequence")))))
12717 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12718 (defun org-block-todo-from-checkboxes (change-plist)
12719 "Block turning an entry into a TODO, using checkboxes.
12720 This checks whether the current task should be blocked from state
12721 changes because there are unchecked boxes in this entry."
12722 (if (not org-enforce-todo-checkbox-dependencies)
12723 t ; if locally turned off don't block
12724 (catch 'dont-block
12725 ;; If this is not a todo state change, or if this entry is already DONE,
12726 ;; do not block
12727 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12728 (member (plist-get change-plist :from)
12729 (cons 'done org-done-keywords))
12730 (member (plist-get change-plist :to)
12731 (cons 'todo org-not-done-keywords))
12732 (not (plist-get change-plist :to)))
12733 (throw 'dont-block t))
12734 ;; If this task has checkboxes that are not checked, it's blocked
12735 (save-excursion
12736 (org-back-to-heading t)
12737 (let ((beg (point)) end)
12738 (outline-next-heading)
12739 (setq end (point))
12740 (goto-char beg)
12741 (when (org-list-search-forward
12742 (concat (org-item-beginning-re)
12743 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12744 "\\[[- ]\\]")
12745 end t)
12746 (when (boundp 'org-blocked-by-checkboxes)
12747 (setq org-blocked-by-checkboxes t))
12748 (throw 'dont-block nil))))
12749 t))) ; do not block
12751 (defun org-entry-blocked-p ()
12752 "Non-nil if entry at point is blocked."
12753 (and (not (org-entry-get nil "NOBLOCKING"))
12754 (member (org-entry-get nil "TODO") org-not-done-keywords)
12755 (not (run-hook-with-args-until-failure
12756 'org-blocker-hook
12757 (list :type 'todo-state-change
12758 :position (point)
12759 :from 'todo
12760 :to 'done)))))
12762 (defun org-update-statistics-cookies (all)
12763 "Update the statistics cookie, either from TODO or from checkboxes.
12764 This should be called with the cursor in a line with a statistics
12765 cookie. When called with a \\[universal-argument] prefix, update
12766 all statistics cookies in the buffer."
12767 (interactive "P")
12768 (if all
12769 (progn
12770 (org-update-checkbox-count 'all)
12771 (org-map-entries 'org-update-parent-todo-statistics))
12772 (if (not (org-at-heading-p))
12773 (org-update-checkbox-count)
12774 (let ((pos (point-marker))
12775 end l1 l2)
12776 (ignore-errors (org-back-to-heading t))
12777 (if (not (org-at-heading-p))
12778 (org-update-checkbox-count)
12779 (setq l1 (org-outline-level))
12780 (setq end (save-excursion
12781 (outline-next-heading)
12782 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12783 (point)))
12784 (if (and (save-excursion
12785 (re-search-forward
12786 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12787 (not (save-excursion (re-search-forward
12788 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12789 (org-update-checkbox-count)
12790 (if (and l2 (> l2 l1))
12791 (progn
12792 (goto-char end)
12793 (org-update-parent-todo-statistics))
12794 (goto-char pos)
12795 (beginning-of-line 1)
12796 (while (re-search-forward
12797 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12798 (point-at-eol) t)
12799 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12800 (goto-char pos)
12801 (move-marker pos nil)))))
12803 (defvar org-entry-property-inherited-from) ;; defined below
12804 (defun org-update-parent-todo-statistics ()
12805 "Update any statistics cookie in the parent of the current headline.
12806 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12807 the entire subtree and this will travel up the hierarchy and update
12808 statistics everywhere."
12809 (let* ((prop (save-excursion (org-up-heading-safe)
12810 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12811 (recursive (or (not org-hierarchical-todo-statistics)
12812 (and prop (string-match "\\<recursive\\>" prop))))
12813 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12815 (first t)
12816 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12817 level ltoggle l1 new ndel
12818 (cnt-all 0) (cnt-done 0) is-percent kwd
12819 checkbox-beg cookie-present)
12820 (catch 'exit
12821 (save-excursion
12822 (beginning-of-line 1)
12823 (setq ltoggle (funcall outline-level))
12824 ;; Three situations are to consider:
12826 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12827 ;; to the top-level ancestor on the headline;
12829 ;; 2. If parent has "recursive" property, repeat up to the
12830 ;; headline setting that property, taking inheritance into
12831 ;; account;
12833 ;; 3. Else, move up to direct parent and proceed only once.
12834 (while (and (setq level (org-up-heading-safe))
12835 (or recursive first)
12836 (>= (point) lim))
12837 (setq first nil cookie-present nil)
12838 (unless (and level
12839 (not (string-match
12840 "\\<checkbox\\>"
12841 (downcase (or (org-entry-get nil "COOKIE_DATA")
12842 "")))))
12843 (throw 'exit nil))
12844 (while (re-search-forward box-re (point-at-eol) t)
12845 (setq cnt-all 0 cnt-done 0 cookie-present t)
12846 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12847 (save-match-data
12848 (unless (outline-next-heading) (throw 'exit nil))
12849 (while (and (looking-at org-complex-heading-regexp)
12850 (> (setq l1 (length (match-string 1))) level))
12851 (setq kwd (and (or recursive (= l1 ltoggle))
12852 (match-string 2)))
12853 (if (or (eq org-provide-todo-statistics 'all-headlines)
12854 (and (eq org-provide-todo-statistics t)
12855 (or (member kwd org-done-keywords)))
12856 (and (listp org-provide-todo-statistics)
12857 (stringp (car org-provide-todo-statistics))
12858 (or (member kwd org-provide-todo-statistics)
12859 (member kwd org-done-keywords)))
12860 (and (listp org-provide-todo-statistics)
12861 (listp (car org-provide-todo-statistics))
12862 (or (member kwd (car org-provide-todo-statistics))
12863 (and (member kwd org-done-keywords)
12864 (member kwd (cadr org-provide-todo-statistics))))))
12865 (setq cnt-all (1+ cnt-all))
12866 (and (eq org-provide-todo-statistics t)
12868 (setq cnt-all (1+ cnt-all))))
12869 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12870 (member kwd org-done-keywords))
12871 (and (listp org-provide-todo-statistics)
12872 (listp (car org-provide-todo-statistics))
12873 (member kwd org-done-keywords)
12874 (member kwd (cadr org-provide-todo-statistics)))
12875 (and (listp org-provide-todo-statistics)
12876 (stringp (car org-provide-todo-statistics))
12877 (member kwd org-done-keywords)))
12878 (setq cnt-done (1+ cnt-done)))
12879 (outline-next-heading)))
12880 (setq new
12881 (if is-percent
12882 (format "[%d%%]" (floor (* 100.0 cnt-done)
12883 (max 1 cnt-all)))
12884 (format "[%d/%d]" cnt-done cnt-all))
12885 ndel (- (match-end 0) checkbox-beg))
12886 (goto-char checkbox-beg)
12887 (insert new)
12888 (delete-region (point) (+ (point) ndel))
12889 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12890 (when cookie-present
12891 (run-hook-with-args 'org-after-todo-statistics-hook
12892 cnt-done (- cnt-all cnt-done))))))
12893 (run-hooks 'org-todo-statistics-hook)))
12895 (defvar org-after-todo-statistics-hook nil
12896 "Hook that is called after a TODO statistics cookie has been updated.
12897 Each function is called with two arguments: the number of not-done entries
12898 and the number of done entries.
12900 For example, the following function, when added to this hook, will switch
12901 an entry to DONE when all children are done, and back to TODO when new
12902 entries are set to a TODO status. Note that this hook is only called
12903 when there is a statistics cookie in the headline!
12905 (defun org-summary-todo (n-done n-not-done)
12906 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12907 (let (org-log-done org-log-states) ; turn off logging
12908 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12911 (defvar org-todo-statistics-hook nil
12912 "Hook that is run whenever Org thinks TODO statistics should be updated.
12913 This hook runs even if there is no statistics cookie present, in which case
12914 `org-after-todo-statistics-hook' would not run.")
12916 (defun org-todo-trigger-tag-changes (state)
12917 "Apply the changes defined in `org-todo-state-tags-triggers'."
12918 (let ((l org-todo-state-tags-triggers)
12919 changes)
12920 (when (or (not state) (equal state ""))
12921 (setq changes (append changes (cdr (assoc "" l)))))
12922 (when (and (stringp state) (> (length state) 0))
12923 (setq changes (append changes (cdr (assoc state l)))))
12924 (when (member state org-not-done-keywords)
12925 (setq changes (append changes (cdr (assq 'todo l)))))
12926 (when (member state org-done-keywords)
12927 (setq changes (append changes (cdr (assq 'done l)))))
12928 (dolist (c changes)
12929 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12931 (defun org-local-logging (value)
12932 "Get logging settings from a property VALUE."
12933 ;; Directly set the variables, they are already local.
12934 (setq org-log-done nil
12935 org-log-repeat nil
12936 org-todo-log-states nil)
12937 (dolist (w (org-split-string value))
12938 (let (a)
12939 (cond
12940 ((setq a (assoc w org-startup-options))
12941 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12942 (set (nth 1 a) (nth 2 a))))
12943 ((setq a (org-extract-log-state-settings w))
12944 (and (member (car a) org-todo-keywords-1)
12945 (push a org-todo-log-states)))))))
12947 (defun org-get-todo-sequence-head (kwd)
12948 "Return the head of the TODO sequence to which KWD belongs.
12949 If KWD is not set, check if there is a text property remembering the
12950 right sequence."
12951 (let (p)
12952 (cond
12953 ((not kwd)
12954 (or (get-text-property (point-at-bol) 'org-todo-head)
12955 (progn
12956 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12957 nil (point-at-eol)))
12958 (get-text-property p 'org-todo-head))))
12959 ((not (member kwd org-todo-keywords-1))
12960 (car org-todo-keywords-1))
12961 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12963 (defun org-fast-todo-selection ()
12964 "Fast TODO keyword selection with single keys.
12965 Returns the new TODO keyword, or nil if no state change should occur."
12966 (let* ((fulltable org-todo-key-alist)
12967 (done-keywords org-done-keywords) ;; needed for the faces.
12968 (maxlen (apply 'max (mapcar
12969 (lambda (x)
12970 (if (stringp (car x)) (string-width (car x)) 0))
12971 fulltable)))
12972 (expert nil)
12973 (fwidth (+ maxlen 3 1 3))
12974 (ncol (/ (- (window-width) 4) fwidth))
12975 tg cnt e c tbl
12976 groups ingroup)
12977 (save-excursion
12978 (save-window-excursion
12979 (if expert
12980 (set-buffer (get-buffer-create " *Org todo*"))
12981 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12982 (erase-buffer)
12983 (setq-local org-done-keywords done-keywords)
12984 (setq tbl fulltable cnt 0)
12985 (while (setq e (pop tbl))
12986 (cond
12987 ((equal e '(:startgroup))
12988 (push '() groups) (setq ingroup t)
12989 (unless (= cnt 0)
12990 (setq cnt 0)
12991 (insert "\n"))
12992 (insert "{ "))
12993 ((equal e '(:endgroup))
12994 (setq ingroup nil cnt 0)
12995 (insert "}\n"))
12996 ((equal e '(:newline))
12997 (unless (= cnt 0)
12998 (setq cnt 0)
12999 (insert "\n")
13000 (setq e (car tbl))
13001 (while (equal (car tbl) '(:newline))
13002 (insert "\n")
13003 (setq tbl (cdr tbl)))))
13005 (setq tg (car e) c (cdr e))
13006 (when ingroup (push tg (car groups)))
13007 (setq tg (org-add-props tg nil 'face
13008 (org-get-todo-face tg)))
13009 (when (and (= cnt 0) (not ingroup)) (insert " "))
13010 (insert "[" c "] " tg (make-string
13011 (- fwidth 4 (length tg)) ?\ ))
13012 (when (= (setq cnt (1+ cnt)) ncol)
13013 (insert "\n")
13014 (when ingroup (insert " "))
13015 (setq cnt 0)))))
13016 (insert "\n")
13017 (goto-char (point-min))
13018 (unless expert (org-fit-window-to-buffer))
13019 (message "[a-z..]:Set [SPC]:clear")
13020 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13021 (cond
13022 ((or (= c ?\C-g)
13023 (and (= c ?q) (not (rassoc c fulltable))))
13024 (setq quit-flag t))
13025 ((= c ?\ ) nil)
13026 ((setq e (rassoc c fulltable) tg (car e))
13028 (t (setq quit-flag t)))))))
13030 (defun org-entry-is-todo-p ()
13031 (member (org-get-todo-state) org-not-done-keywords))
13033 (defun org-entry-is-done-p ()
13034 (member (org-get-todo-state) org-done-keywords))
13036 (defun org-get-todo-state ()
13037 "Return the TODO keyword of the current subtree."
13038 (save-excursion
13039 (org-back-to-heading t)
13040 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13041 (match-end 2)
13042 (match-string 2))))
13044 (defun org-at-date-range-p (&optional inactive-ok)
13045 "Non-nil if point is inside a date range.
13047 When optional argument INACTIVE-OK is non-nil, also consider
13048 inactive time ranges.
13050 When this function returns a non-nil value, match data is set
13051 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13052 on INACTIVE-OK."
13053 (interactive)
13054 (save-excursion
13055 (catch 'exit
13056 (let ((pos (point)))
13057 (skip-chars-backward "^[<\r\n")
13058 (skip-chars-backward "<[")
13059 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13060 (>= (match-end 0) pos)
13061 (throw 'exit t))
13062 (skip-chars-backward "^<[\r\n")
13063 (skip-chars-backward "<[")
13064 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13065 (>= (match-end 0) pos)
13066 (throw 'exit t)))
13067 nil)))
13069 (defun org-get-repeat (&optional timestamp)
13070 "Check if there is a time-stamp with repeater in this entry.
13072 Return the repeater, as a string, or nil. Also return nil when
13073 this function is called before first heading.
13075 When optional argument TIMESTAMP is a string, extract the
13076 repeater from there instead."
13077 (save-match-data
13078 (cond (timestamp
13079 (and (string-match org-repeat-re timestamp)
13080 (match-string-no-properties 1 timestamp)))
13081 ((org-before-first-heading-p) nil)
13083 (save-excursion
13084 (org-back-to-heading t)
13085 (let ((end (org-entry-end-position)))
13086 (catch :repeat
13087 (while (re-search-forward org-repeat-re end t)
13088 (when (save-match-data (org-at-timestamp-p))
13089 (throw :repeat (match-string-no-properties 1)))))))))))
13091 (defvar org-last-changed-timestamp)
13092 (defvar org-last-inserted-timestamp)
13093 (defvar org-log-post-message)
13094 (defvar org-log-note-purpose)
13095 (defvar org-log-note-how nil)
13096 (defvar org-log-note-extra)
13097 (defun org-auto-repeat-maybe (done-word)
13098 "Check if the current headline contains a repeated time-stamp.
13100 If yes, set TODO state back to what it was and change the base date
13101 of repeating deadline/scheduled time stamps to new date.
13103 This function is run automatically after each state change to a DONE state."
13104 (let* ((repeat (org-get-repeat))
13105 (aa (assoc org-last-state org-todo-kwd-alist))
13106 (interpret (nth 1 aa))
13107 (head (nth 2 aa))
13108 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13109 (msg "Entry repeats: ")
13110 (org-log-done nil)
13111 (org-todo-log-states nil)
13112 (end (copy-marker (org-entry-end-position))))
13113 (unwind-protect
13114 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13115 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13116 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13117 org-todo-repeat-to-state)))
13118 (org-todo (cond
13119 ((and to-state (member to-state org-todo-keywords-1))
13120 to-state)
13121 ((eq interpret 'type) org-last-state)
13122 (head)
13123 (t 'none))))
13124 (org-back-to-heading t)
13125 (org-add-planning-info nil nil 'closed)
13126 ;; When `org-log-repeat' is non-nil or entry contains
13127 ;; a clock, set LAST_REPEAT property.
13128 (when (or org-log-repeat
13129 (catch :clock
13130 (while (re-search-forward org-clock-line-re end t)
13131 (when (org-at-clock-log-p) (throw :clock t)))))
13132 (org-entry-put nil "LAST_REPEAT" (format-time-string
13133 (org-time-stamp-format t t)
13134 (current-time))))
13135 (when org-log-repeat
13136 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13137 (memq 'org-add-log-note post-command-hook))
13138 ;; We are already setup for some record.
13139 (when (eq org-log-repeat 'note)
13140 ;; Make sure we take a note, not only a time stamp.
13141 (setq org-log-note-how 'note))
13142 ;; Set up for taking a record.
13143 (org-add-log-setup 'state
13144 (or done-word (car org-done-keywords))
13145 org-last-state
13146 org-log-repeat)))
13147 (let ((planning-re (regexp-opt
13148 (list org-scheduled-string org-deadline-string))))
13149 (while (re-search-forward org-ts-regexp end t)
13150 (let* ((ts (match-string 0))
13151 (planning? (org-at-planning-p))
13152 (type (if (not planning?) "Plain:"
13153 (save-excursion
13154 (re-search-backward
13155 planning-re (line-beginning-position) t)
13156 (match-string 0)))))
13157 (cond
13158 ;; Ignore fake time-stamps (e.g., within comments).
13159 ((not (org-at-timestamp-p t)))
13160 ;; Time-stamps without a repeater are usually
13161 ;; skipped. However, a SCHEDULED time-stamp without
13162 ;; one is removed, as they are no longer relevant.
13163 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13164 ts))
13165 (when (equal type org-scheduled-string)
13166 (org-remove-timestamp-with-keyword type)))
13168 (let ((n (string-to-number (match-string 2 ts)))
13169 (what (match-string 3 ts)))
13170 (when (equal what "w") (setq n (* n 7) what "d"))
13171 (when (and (equal what "h")
13172 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13173 ts)))
13174 (user-error
13175 "Cannot repeat in Repeat in %d hour(s) because no hour \
13176 has been set"
13178 ;; Preparation, see if we need to modify the start
13179 ;; date for the change.
13180 (when (match-end 1)
13181 (let ((time (save-match-data
13182 (org-time-string-to-time ts))))
13183 (cond
13184 ((equal (match-string 1 ts) ".")
13185 ;; Shift starting date to today
13186 (org-timestamp-change
13187 (- (org-today) (time-to-days time))
13188 'day))
13189 ((equal (match-string 1 ts) "+")
13190 (let ((nshiftmax 10)
13191 (nshift 0))
13192 (while (or (= nshift 0)
13193 (not (time-less-p (current-time) time)))
13194 (when (= (cl-incf nshift) nshiftmax)
13195 (or (y-or-n-p
13196 (format "%d repeater intervals were not \
13197 enough to shift date past today. Continue? "
13198 nshift))
13199 (user-error "Abort")))
13200 (org-timestamp-change n (cdr (assoc what whata)))
13201 (org-in-regexp org-ts-regexp3)
13202 (setq ts (match-string 1))
13203 (setq time
13204 (save-match-data
13205 (org-time-string-to-time ts)))))
13206 (org-timestamp-change (- n) (cdr (assoc what whata)))
13207 ;; Rematch, so that we have everything in place
13208 ;; for the real shift.
13209 (org-in-regexp org-ts-regexp3)
13210 (setq ts (match-string 1))
13211 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13212 ts)))))
13213 (save-excursion
13214 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13215 (setq msg
13216 (concat
13217 msg type " " org-last-changed-timestamp " "))))))))
13218 (setq org-log-post-message msg)
13219 (message "%s" msg))
13220 (set-marker end nil))))
13222 (defun org-show-todo-tree (arg)
13223 "Make a compact tree which shows all headlines marked with TODO.
13224 The tree will show the lines where the regexp matches, and all higher
13225 headlines above the match.
13226 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13227 With a numeric prefix N, construct a sparse tree for the Nth element
13228 of `org-todo-keywords-1'."
13229 (interactive "P")
13230 (let ((case-fold-search nil)
13231 (kwd-re
13232 (cond ((null arg) org-not-done-regexp)
13233 ((equal arg '(4))
13234 (let ((kwd
13235 (completing-read "Keyword (or KWD1|KWD2|...): "
13236 (mapcar #'list org-todo-keywords-1))))
13237 (concat "\\("
13238 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13239 "\\)\\>")))
13240 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13241 (regexp-quote (nth (1- (prefix-numeric-value arg))
13242 org-todo-keywords-1)))
13243 (t (user-error "Invalid prefix argument: %s" arg)))))
13244 (message "%d TODO entries found"
13245 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13247 (defun org--deadline-or-schedule (arg type time)
13248 "Insert DEADLINE or SCHEDULE information in current entry.
13249 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13250 `org-schedule' for information about ARG and TIME arguments."
13251 (let* ((deadline? (eq type 'deadline))
13252 (keyword (if deadline? org-deadline-string org-scheduled-string))
13253 (log (if deadline? org-log-redeadline org-log-reschedule))
13254 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13255 (old-date-time (and old-date (org-time-string-to-time old-date)))
13256 ;; Save repeater cookie from either TIME or current scheduled
13257 ;; time stamp. We are going to insert it back at the end of
13258 ;; the process.
13259 (repeater (or (and (org-string-nw-p time)
13260 ;; We use `org-repeat-re' because we need
13261 ;; to tell the difference between a real
13262 ;; repeater and a time delta, e.g. "+2d".
13263 (string-match org-repeat-re time)
13264 (match-string 1 time))
13265 (and (org-string-nw-p old-date)
13266 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13267 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13268 old-date)
13269 (match-string 1 old-date)))))
13270 (pcase arg
13271 (`(4)
13272 (when (and old-date log)
13273 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13274 nil old-date log))
13275 (org-remove-timestamp-with-keyword keyword)
13276 (message (if deadline? "Item no longer has a deadline."
13277 "Item is no longer scheduled.")))
13278 (`(16)
13279 (save-excursion
13280 (org-back-to-heading t)
13281 (let ((regexp (if deadline? org-deadline-time-regexp
13282 org-scheduled-time-regexp)))
13283 (if (not (re-search-forward regexp (line-end-position 2) t))
13284 (user-error (if deadline? "No deadline information to update"
13285 "No scheduled information to update"))
13286 (let* ((rpl0 (match-string 1))
13287 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13288 (msg (if deadline? "Warn starting from" "Delay until")))
13289 (replace-match
13290 (concat keyword
13291 " <" rpl
13292 (format " -%dd"
13293 (abs (- (time-to-days
13294 (save-match-data
13295 (org-read-date
13296 nil t nil msg old-date-time)))
13297 (time-to-days old-date-time))))
13298 ">") t t))))))
13300 (org-add-planning-info type time 'closed)
13301 (when (and old-date
13303 (not (equal old-date org-last-inserted-timestamp)))
13304 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13305 org-last-inserted-timestamp
13306 old-date
13307 log))
13308 (when repeater
13309 (save-excursion
13310 (org-back-to-heading t)
13311 (when (re-search-forward
13312 (concat keyword " " org-last-inserted-timestamp)
13313 (line-end-position 2)
13315 (goto-char (1- (match-end 0)))
13316 (insert " " repeater)
13317 (setq org-last-inserted-timestamp
13318 (concat (substring org-last-inserted-timestamp 0 -1)
13319 " " repeater
13320 (substring org-last-inserted-timestamp -1))))))
13321 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13322 org-last-inserted-timestamp)))))
13324 (defun org-deadline (arg &optional time)
13325 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13326 With one universal prefix argument, remove any deadline from the item.
13327 With two universal prefix arguments, prompt for a warning delay.
13328 With argument TIME, set the deadline at the corresponding date. TIME
13329 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13330 (interactive "P")
13331 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13332 (org-map-entries
13333 (lambda () (org--deadline-or-schedule arg 'deadline time))
13335 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13336 'region-start-level
13337 'region)
13338 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13339 (org--deadline-or-schedule arg 'deadline time)))
13341 (defun org-schedule (arg &optional time)
13342 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13343 With one universal prefix argument, remove any scheduling date from the item.
13344 With two universal prefix arguments, prompt for a delay cookie.
13345 With argument TIME, scheduled at the corresponding date. TIME can
13346 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13347 (interactive "P")
13348 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13349 (org-map-entries
13350 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13352 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13353 'region-start-level
13354 'region)
13355 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13356 (org--deadline-or-schedule arg 'scheduled time)))
13358 (defun org-get-scheduled-time (pom &optional inherit)
13359 "Get the scheduled time as a time tuple, of a format suitable
13360 for calling org-schedule with, or if there is no scheduling,
13361 returns nil."
13362 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13363 (when time
13364 (apply 'encode-time (org-parse-time-string time)))))
13366 (defun org-get-deadline-time (pom &optional inherit)
13367 "Get the deadline as a time tuple, of a format suitable for
13368 calling org-deadline with, or if there is no scheduling, returns
13369 nil."
13370 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13371 (when time
13372 (apply 'encode-time (org-parse-time-string time)))))
13374 (defun org-remove-timestamp-with-keyword (keyword)
13375 "Remove all time stamps with KEYWORD in the current entry."
13376 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13377 beg)
13378 (save-excursion
13379 (org-back-to-heading t)
13380 (setq beg (point))
13381 (outline-next-heading)
13382 (while (re-search-backward re beg t)
13383 (replace-match "")
13384 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13385 (equal (char-before) ?\ ))
13386 (backward-delete-char 1)
13387 (when (string-match "^[ \t]*$" (buffer-substring
13388 (point-at-bol) (point-at-eol)))
13389 (delete-region (point-at-bol)
13390 (min (point-max) (1+ (point-at-eol))))))))))
13392 (defvar org-time-was-given) ; dynamically scoped parameter
13393 (defvar org-end-time-was-given) ; dynamically scoped parameter
13395 (defun org-at-planning-p ()
13396 "Non-nil when point is on a planning info line."
13397 ;; This is as accurate and faster than `org-element-at-point' since
13398 ;; planning info location is fixed in the section.
13399 (org-with-wide-buffer
13400 (beginning-of-line)
13401 (and (looking-at-p org-planning-line-re)
13402 (eq (point)
13403 (ignore-errors
13404 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13405 (org-back-to-heading t)
13406 (org-with-limited-levels (org-back-to-heading t)))
13407 (line-beginning-position 2))))))
13409 (defun org-add-planning-info (what &optional time &rest remove)
13410 "Insert new timestamp with keyword in the planning line.
13411 WHAT indicates what kind of time stamp to add. It is a symbol
13412 among `closed', `deadline', `scheduled' and nil. TIME indicates
13413 the time to use. If none is given, the user is prompted for
13414 a date. REMOVE indicates what kind of entries to remove. An old
13415 WHAT entry will also be removed."
13416 (let (org-time-was-given org-end-time-was-given default-time default-input)
13417 (catch 'exit
13418 (when (and (memq what '(scheduled deadline))
13419 (or (not time)
13420 (and (stringp time)
13421 (string-match "^[-+]+[0-9]" time))))
13422 ;; Try to get a default date/time from existing timestamp
13423 (save-excursion
13424 (org-back-to-heading t)
13425 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13426 (when (re-search-forward (if (eq what 'scheduled)
13427 org-scheduled-time-regexp
13428 org-deadline-time-regexp)
13429 end t)
13430 (setq ts (match-string 1)
13431 default-time (apply 'encode-time (org-parse-time-string ts))
13432 default-input (and ts (org-get-compact-tod ts)))))))
13433 (when what
13434 (setq time
13435 (if (stringp time)
13436 ;; This is a string (relative or absolute), set
13437 ;; proper date.
13438 (apply #'encode-time
13439 (org-read-date-analyze
13440 time default-time (decode-time default-time)))
13441 ;; If necessary, get the time from the user
13442 (or time (org-read-date nil 'to-time nil nil
13443 default-time default-input)))))
13445 (org-with-wide-buffer
13446 (org-back-to-heading t)
13447 (forward-line)
13448 (unless (bolp) (insert "\n"))
13449 (cond ((looking-at-p org-planning-line-re)
13450 ;; Move to current indentation.
13451 (skip-chars-forward " \t")
13452 ;; Check if we have to remove something.
13453 (dolist (type (if what (cons what remove) remove))
13454 (save-excursion
13455 (when (re-search-forward
13456 (cl-case type
13457 (closed org-closed-time-regexp)
13458 (deadline org-deadline-time-regexp)
13459 (scheduled org-scheduled-time-regexp)
13460 (otherwise
13461 (error "Invalid planning type: %s" type)))
13462 (line-end-position) t)
13463 ;; Delete until next keyword or end of line.
13464 (delete-region
13465 (match-beginning 0)
13466 (if (re-search-forward org-keyword-time-not-clock-regexp
13467 (line-end-position)
13469 (match-beginning 0)
13470 (line-end-position))))))
13471 ;; If there is nothing more to add and no more keyword
13472 ;; is left, remove the line completely.
13473 (if (and (looking-at-p "[ \t]*$") (not what))
13474 (delete-region (line-beginning-position)
13475 (line-beginning-position 2))
13476 ;; If we removed last keyword, do not leave trailing
13477 ;; white space at the end of line.
13478 (let ((p (point)))
13479 (save-excursion
13480 (end-of-line)
13481 (unless (= (skip-chars-backward " \t" p) 0)
13482 (delete-region (point) (line-end-position)))))))
13483 ((not what) (throw 'exit nil)) ; Nothing to do.
13484 (t (insert-before-markers "\n")
13485 (backward-char 1)
13486 (when org-adapt-indentation
13487 (indent-to-column (1+ (org-outline-level))))))
13488 (when what
13489 ;; Insert planning keyword.
13490 (insert (cl-case what
13491 (closed org-closed-string)
13492 (deadline org-deadline-string)
13493 (scheduled org-scheduled-string)
13494 (otherwise (error "Invalid planning type: %s" what)))
13495 " ")
13496 ;; Insert associated timestamp.
13497 (let ((ts (org-insert-time-stamp
13498 time
13499 (or org-time-was-given
13500 (and (eq what 'closed) org-log-done-with-time))
13501 (eq what 'closed)
13502 nil nil (list org-end-time-was-given))))
13503 (unless (eolp) (insert " "))
13504 ts))))))
13506 (defvar org-log-note-marker (make-marker)
13507 "Marker pointing at the entry where the note is to be inserted.")
13508 (defvar org-log-note-purpose nil)
13509 (defvar org-log-note-state nil)
13510 (defvar org-log-note-previous-state nil)
13511 (defvar org-log-note-extra nil)
13512 (defvar org-log-note-window-configuration nil)
13513 (defvar org-log-note-return-to (make-marker))
13514 (defvar org-log-note-effective-time nil
13515 "Remembered current time so that dynamically scoped
13516 `org-extend-today-until' affects timestamps in state change log")
13518 (defvar org-log-post-message nil
13519 "Message to be displayed after a log note has been stored.
13520 The auto-repeater uses this.")
13522 (defun org-add-note ()
13523 "Add a note to the current entry.
13524 This is done in the same way as adding a state change note."
13525 (interactive)
13526 (org-add-log-setup 'note))
13528 (defun org-log-beginning (&optional create)
13529 "Return expected start of log notes in current entry.
13530 When optional argument CREATE is non-nil, the function creates
13531 a drawer to store notes, if necessary. Returned position ignores
13532 narrowing."
13533 (org-with-wide-buffer
13534 (let ((drawer (org-log-into-drawer)))
13535 (cond
13536 (drawer
13537 (org-end-of-meta-data)
13538 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13539 (end (if (org-at-heading-p) (point)
13540 (save-excursion (outline-next-heading) (point))))
13541 (case-fold-search t))
13542 (catch 'exit
13543 ;; Try to find existing drawer.
13544 (while (re-search-forward regexp end t)
13545 (let ((element (org-element-at-point)))
13546 (when (eq (org-element-type element) 'drawer)
13547 (let ((cend (org-element-property :contents-end element)))
13548 (when (and (not org-log-states-order-reversed) cend)
13549 (goto-char cend)))
13550 (throw 'exit nil))))
13551 ;; No drawer found. Create one, if permitted.
13552 (when create
13553 (unless (bolp) (insert "\n"))
13554 (let ((beg (point)))
13555 (insert ":" drawer ":\n:END:\n")
13556 (org-indent-region beg (point)))
13557 (end-of-line -1)))))
13559 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13560 (skip-chars-forward " \t\n")
13561 (beginning-of-line)
13562 (unless org-log-states-order-reversed
13563 (org-skip-over-state-notes)
13564 (skip-chars-backward " \t\n")
13565 (forward-line)))))
13566 (if (bolp) (point) (line-beginning-position 2))))
13568 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13569 "Set up the post command hook to take a note.
13570 If this is about to TODO state change, the new state is expected in STATE.
13571 HOW is an indicator what kind of note should be created.
13572 EXTRA is additional text that will be inserted into the notes buffer."
13573 (move-marker org-log-note-marker (point))
13574 (setq org-log-note-purpose purpose
13575 org-log-note-state state
13576 org-log-note-previous-state prev-state
13577 org-log-note-how how
13578 org-log-note-extra extra
13579 org-log-note-effective-time (org-current-effective-time))
13580 (add-hook 'post-command-hook 'org-add-log-note 'append))
13582 (defun org-skip-over-state-notes ()
13583 "Skip past the list of State notes in an entry."
13584 (when (ignore-errors (goto-char (org-in-item-p)))
13585 (let* ((struct (org-list-struct))
13586 (prevs (org-list-prevs-alist struct))
13587 (regexp
13588 (concat "[ \t]*- +"
13589 (replace-regexp-in-string
13590 " +" " +"
13591 (org-replace-escapes
13592 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13593 `(("%d" . ,org-ts-regexp-inactive)
13594 ("%D" . ,org-ts-regexp)
13595 ("%s" . "\"\\S-+\"")
13596 ("%S" . "\"\\S-+\"")
13597 ("%t" . ,org-ts-regexp-inactive)
13598 ("%T" . ,org-ts-regexp)
13599 ("%u" . ".*?")
13600 ("%U" . ".*?")))))))
13601 (while (looking-at-p regexp)
13602 (goto-char (or (org-list-get-next-item (point) struct prevs)
13603 (org-list-get-item-end (point) struct)))))))
13605 (defun org-add-log-note (&optional _purpose)
13606 "Pop up a window for taking a note, and add this note later."
13607 (remove-hook 'post-command-hook 'org-add-log-note)
13608 (setq org-log-note-window-configuration (current-window-configuration))
13609 (delete-other-windows)
13610 (move-marker org-log-note-return-to (point))
13611 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13612 (goto-char org-log-note-marker)
13613 (org-switch-to-buffer-other-window "*Org Note*")
13614 (erase-buffer)
13615 (if (memq org-log-note-how '(time state))
13616 (let (current-prefix-arg) (org-store-log-note))
13617 (let ((org-inhibit-startup t)) (org-mode))
13618 (insert (format "# Insert note for %s.
13619 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13620 (cond
13621 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13622 ((eq org-log-note-purpose 'done) "closed todo item")
13623 ((eq org-log-note-purpose 'state)
13624 (format "state change from \"%s\" to \"%s\""
13625 (or org-log-note-previous-state "")
13626 (or org-log-note-state "")))
13627 ((eq org-log-note-purpose 'reschedule)
13628 "rescheduling")
13629 ((eq org-log-note-purpose 'delschedule)
13630 "no longer scheduled")
13631 ((eq org-log-note-purpose 'redeadline)
13632 "changing deadline")
13633 ((eq org-log-note-purpose 'deldeadline)
13634 "removing deadline")
13635 ((eq org-log-note-purpose 'refile)
13636 "refiling")
13637 ((eq org-log-note-purpose 'note)
13638 "this entry")
13639 (t (error "This should not happen")))))
13640 (when org-log-note-extra (insert org-log-note-extra))
13641 (setq-local org-finish-function 'org-store-log-note)
13642 (run-hooks 'org-log-buffer-setup-hook)))
13644 (defvar org-note-abort nil) ; dynamically scoped
13645 (defun org-store-log-note ()
13646 "Finish taking a log note, and insert it to where it belongs."
13647 (let ((txt (prog1 (buffer-string)
13648 (kill-buffer)))
13649 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13650 lines)
13651 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13652 (setq txt (replace-match "" t t txt)))
13653 (when (string-match "\\s-+\\'" txt)
13654 (setq txt (replace-match "" t t txt)))
13655 (setq lines (org-split-string txt "\n"))
13656 (when (org-string-nw-p note)
13657 (setq note
13658 (org-replace-escapes
13659 note
13660 (list (cons "%u" (user-login-name))
13661 (cons "%U" user-full-name)
13662 (cons "%t" (format-time-string
13663 (org-time-stamp-format 'long 'inactive)
13664 org-log-note-effective-time))
13665 (cons "%T" (format-time-string
13666 (org-time-stamp-format 'long nil)
13667 org-log-note-effective-time))
13668 (cons "%d" (format-time-string
13669 (org-time-stamp-format nil 'inactive)
13670 org-log-note-effective-time))
13671 (cons "%D" (format-time-string
13672 (org-time-stamp-format nil nil)
13673 org-log-note-effective-time))
13674 (cons "%s" (cond
13675 ((not org-log-note-state) "")
13676 ((string-match-p org-ts-regexp
13677 org-log-note-state)
13678 (format "\"[%s]\""
13679 (substring org-log-note-state 1 -1)))
13680 (t (format "\"%s\"" org-log-note-state))))
13681 (cons "%S"
13682 (cond
13683 ((not org-log-note-previous-state) "")
13684 ((string-match-p org-ts-regexp
13685 org-log-note-previous-state)
13686 (format "\"[%s]\""
13687 (substring
13688 org-log-note-previous-state 1 -1)))
13689 (t (format "\"%s\""
13690 org-log-note-previous-state)))))))
13691 (when lines (setq note (concat note " \\\\")))
13692 (push note lines))
13693 (when (and lines (not (or current-prefix-arg org-note-abort)))
13694 (with-current-buffer (marker-buffer org-log-note-marker)
13695 (org-with-wide-buffer
13696 ;; Find location for the new note.
13697 (goto-char org-log-note-marker)
13698 (set-marker org-log-note-marker nil)
13699 ;; Note associated to a clock is to be located right after
13700 ;; the clock. Do not move point.
13701 (unless (eq org-log-note-purpose 'clock-out)
13702 (goto-char (org-log-beginning t)))
13703 ;; Make sure point is at the beginning of an empty line.
13704 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13705 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13706 ;; In an existing list, add a new item at the top level.
13707 ;; Otherwise, indent line like a regular one.
13708 (let ((itemp (org-in-item-p)))
13709 (if itemp
13710 (indent-line-to
13711 (let ((struct (save-excursion
13712 (goto-char itemp) (org-list-struct))))
13713 (org-list-get-ind (org-list-get-top-point struct) struct)))
13714 (org-indent-line)))
13715 (insert (org-list-bullet-string "-") (pop lines))
13716 (let ((ind (org-list-item-body-column (line-beginning-position))))
13717 (dolist (line lines)
13718 (insert "\n")
13719 (indent-line-to ind)
13720 (insert line)))
13721 (message "Note stored")
13722 (org-back-to-heading t)
13723 (org-cycle-hide-drawers 'children))
13724 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13725 ;; from within `org-add-log-note' because `buffer-undo-list'
13726 ;; is then modified outside of `org-with-remote-undo'.
13727 (when (eq this-command 'org-agenda-todo)
13728 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13729 ;; Don't add undo information when called from `org-agenda-todo'.
13730 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13731 (set-window-configuration org-log-note-window-configuration)
13732 (with-current-buffer (marker-buffer org-log-note-return-to)
13733 (goto-char org-log-note-return-to))
13734 (move-marker org-log-note-return-to nil)
13735 (when org-log-post-message (message "%s" org-log-post-message))))
13737 (defun org-remove-empty-drawer-at (pos)
13738 "Remove an empty drawer at position POS.
13739 POS may also be a marker."
13740 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13741 (org-with-wide-buffer
13742 (goto-char pos)
13743 (let ((drawer (org-element-at-point)))
13744 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13745 (not (org-element-property :contents-begin drawer)))
13746 (delete-region (org-element-property :begin drawer)
13747 (progn (goto-char (org-element-property :end drawer))
13748 (skip-chars-backward " \r\t\n")
13749 (forward-line)
13750 (point))))))))
13752 (defvar org-ts-type nil)
13753 (defun org-sparse-tree (&optional arg type)
13754 "Create a sparse tree, prompt for the details.
13755 This command can create sparse trees. You first need to select the type
13756 of match used to create the tree:
13758 t Show all TODO entries.
13759 T Show entries with a specific TODO keyword.
13760 m Show entries selected by a tags/property match.
13761 p Enter a property name and its value (both with completion on existing
13762 names/values) and show entries with that property.
13763 r Show entries matching a regular expression (`/' can be used as well).
13764 b Show deadlines and scheduled items before a date.
13765 a Show deadlines and scheduled items after a date.
13766 d Show deadlines due within `org-deadline-warning-days'.
13767 D Show deadlines and scheduled items between a date range."
13768 (interactive "P")
13769 (setq type (or type org-sparse-tree-default-date-type))
13770 (setq org-ts-type type)
13771 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13772 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13773 \[c]ycle through date types: %s"
13774 (cl-case type
13775 (all "all timestamps")
13776 (scheduled "only scheduled")
13777 (deadline "only deadline")
13778 (active "only active timestamps")
13779 (inactive "only inactive timestamps")
13780 (closed "with a closed time-stamp")
13781 (otherwise "scheduled/deadline")))
13782 (let ((answer (read-char-exclusive)))
13783 (cl-case answer
13785 (org-sparse-tree
13787 (cadr
13788 (memq type '(nil all scheduled deadline active inactive closed)))))
13789 (?d (call-interactively 'org-check-deadlines))
13790 (?b (call-interactively 'org-check-before-date))
13791 (?a (call-interactively 'org-check-after-date))
13792 (?D (call-interactively 'org-check-dates-range))
13793 (?t (call-interactively 'org-show-todo-tree))
13794 (?T (org-show-todo-tree '(4)))
13795 (?m (call-interactively 'org-match-sparse-tree))
13796 ((?p ?P)
13797 (let* ((kwd (completing-read
13798 "Property: " (mapcar #'list (org-buffer-property-keys))))
13799 (value (completing-read
13800 "Value: " (mapcar #'list (org-property-values kwd)))))
13801 (unless (string-match "\\`{.*}\\'" value)
13802 (setq value (concat "\"" value "\"")))
13803 (org-match-sparse-tree arg (concat kwd "=" value))))
13804 ((?r ?R ?/) (call-interactively 'org-occur))
13805 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13807 (defvar-local org-occur-highlights nil
13808 "List of overlays used for occur matches.")
13809 (defvar-local org-occur-parameters nil
13810 "Parameters of the active org-occur calls.
13811 This is a list, each call to org-occur pushes as cons cell,
13812 containing the regular expression and the callback, onto the list.
13813 The list can contain several entries if `org-occur' has been called
13814 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13815 will only contain one set of parameters. When the highlights are
13816 removed (for example with `C-c C-c', or with the next edit (depending
13817 on `org-remove-highlights-with-change'), this variable is emptied
13818 as well.")
13820 (defun org-occur (regexp &optional keep-previous callback)
13821 "Make a compact tree which shows all matches of REGEXP.
13823 The tree will show the lines where the regexp matches, and any other context
13824 defined in `org-show-context-detail', which see.
13826 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13827 done by a previous call to `org-occur' will be kept, to allow stacking of
13828 calls to this command.
13830 Optional argument CALLBACK can be a function of no argument. In this case,
13831 it is called with point at the end of the match, match data being set
13832 accordingly. Current match is shown only if the return value is non-nil.
13833 The function must neither move point nor alter narrowing."
13834 (interactive "sRegexp: \nP")
13835 (when (equal regexp "")
13836 (user-error "Regexp cannot be empty"))
13837 (unless keep-previous
13838 (org-remove-occur-highlights nil nil t))
13839 (push (cons regexp callback) org-occur-parameters)
13840 (let ((cnt 0))
13841 (save-excursion
13842 (goto-char (point-min))
13843 (when (or (not keep-previous) ; do not want to keep
13844 (not org-occur-highlights)) ; no previous matches
13845 ;; hide everything
13846 (org-overview))
13847 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13848 (isearch-no-upper-case-p regexp t)
13849 org-occur-case-fold-search)))
13850 (while (re-search-forward regexp nil t)
13851 (when (or (not callback)
13852 (save-match-data (funcall callback)))
13853 (setq cnt (1+ cnt))
13854 (when org-highlight-sparse-tree-matches
13855 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13856 (org-show-context 'occur-tree)))))
13857 (when org-remove-highlights-with-change
13858 (add-hook 'before-change-functions 'org-remove-occur-highlights
13859 nil 'local))
13860 (unless org-sparse-tree-open-archived-trees
13861 (org-hide-archived-subtrees (point-min) (point-max)))
13862 (run-hooks 'org-occur-hook)
13863 (when (called-interactively-p 'interactive)
13864 (message "%d match(es) for regexp %s" cnt regexp))
13865 cnt))
13867 (defun org-occur-next-match (&optional n _reset)
13868 "Function for `next-error-function' to find sparse tree matches.
13869 N is the number of matches to move, when negative move backwards.
13870 This function always goes back to the starting point when no
13871 match is found."
13872 (let* ((limit (if (< n 0) (point-min) (point-max)))
13873 (search-func (if (< n 0)
13874 'previous-single-char-property-change
13875 'next-single-char-property-change))
13876 (n (abs n))
13877 (pos (point))
13879 (catch 'exit
13880 (while (setq p1 (funcall search-func (point) 'org-type))
13881 (when (equal p1 limit)
13882 (goto-char pos)
13883 (user-error "No more matches"))
13884 (when (equal (get-char-property p1 'org-type) 'org-occur)
13885 (setq n (1- n))
13886 (when (= n 0)
13887 (goto-char p1)
13888 (throw 'exit (point))))
13889 (goto-char p1))
13890 (goto-char p1)
13891 (user-error "No more matches"))))
13893 (defun org-show-context (&optional key)
13894 "Make sure point and context are visible.
13895 Optional argument KEY, when non-nil, is a symbol. See
13896 `org-show-context-detail' for allowed values and how much is to
13897 be shown."
13898 (org-show-set-visibility
13899 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13900 ((cdr (assq key org-show-context-detail)))
13901 (t (cdr (assq 'default org-show-context-detail))))))
13903 (defun org-show-set-visibility (detail)
13904 "Set visibility around point according to DETAIL.
13905 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13906 `tree', `canonical' or t. See `org-show-context-detail' for more
13907 information."
13908 ;; Show current heading and possibly its entry, following headline
13909 ;; or all children.
13910 (if (and (org-at-heading-p) (not (eq detail 'local)))
13911 (org-flag-heading nil)
13912 (org-show-entry)
13913 ;; If point is hidden within a drawer or a block, make sure to
13914 ;; expose it.
13915 (dolist (o (overlays-at (point)))
13916 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13917 (delete-overlay o)))
13918 (unless (org-before-first-heading-p)
13919 (org-with-limited-levels
13920 (cl-case detail
13921 ((tree canonical t) (org-show-children))
13922 ((nil minimal ancestors))
13923 (t (save-excursion
13924 (outline-next-heading)
13925 (org-flag-heading nil)))))))
13926 ;; Show all siblings.
13927 (when (eq detail 'lineage) (org-show-siblings))
13928 ;; Show ancestors, possibly with their children.
13929 (when (memq detail '(ancestors lineage tree canonical t))
13930 (save-excursion
13931 (while (org-up-heading-safe)
13932 (org-flag-heading nil)
13933 (when (memq detail '(canonical t)) (org-show-entry))
13934 (when (memq detail '(tree canonical t)) (org-show-children))))))
13936 (defvar org-reveal-start-hook nil
13937 "Hook run before revealing a location.")
13939 (defun org-reveal (&optional siblings)
13940 "Show current entry, hierarchy above it, and the following headline.
13942 This can be used to show a consistent set of context around
13943 locations exposed with `org-show-context'.
13945 With optional argument SIBLINGS, on each level of the hierarchy all
13946 siblings are shown. This repairs the tree structure to what it would
13947 look like when opened with hierarchical calls to `org-cycle'.
13949 With a \\[universal-argument] \\[universal-argument] prefix, \
13950 go to the parent and show the entire tree."
13951 (interactive "P")
13952 (run-hooks 'org-reveal-start-hook)
13953 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13954 ((equal siblings '(16))
13955 (save-excursion
13956 (when (org-up-heading-safe)
13957 (org-show-subtree)
13958 (run-hook-with-args 'org-cycle-hook 'subtree))))
13959 (t (org-show-set-visibility 'lineage))))
13961 (defun org-highlight-new-match (beg end)
13962 "Highlight from BEG to END and mark the highlight is an occur headline."
13963 (let ((ov (make-overlay beg end)))
13964 (overlay-put ov 'face 'secondary-selection)
13965 (overlay-put ov 'org-type 'org-occur)
13966 (push ov org-occur-highlights)))
13968 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13969 "Remove the occur highlights from the buffer.
13970 BEG and END are ignored. If NOREMOVE is nil, remove this function
13971 from the `before-change-functions' in the current buffer."
13972 (interactive)
13973 (unless org-inhibit-highlight-removal
13974 (mapc #'delete-overlay org-occur-highlights)
13975 (setq org-occur-highlights nil)
13976 (setq org-occur-parameters nil)
13977 (unless noremove
13978 (remove-hook 'before-change-functions
13979 'org-remove-occur-highlights 'local))))
13981 ;;;; Priorities
13983 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13984 "Regular expression matching the priority indicator.")
13986 (defvar org-remove-priority-next-time nil)
13988 (defun org-priority-up ()
13989 "Increase the priority of the current item."
13990 (interactive)
13991 (org-priority 'up))
13993 (defun org-priority-down ()
13994 "Decrease the priority of the current item."
13995 (interactive)
13996 (org-priority 'down))
13998 (defun org-priority (&optional action _show)
13999 "Change the priority of an item.
14000 ACTION can be `set', `up', `down', or a character."
14001 (interactive "P")
14002 (if (equal action '(4))
14003 (org-show-priority)
14004 (unless org-enable-priority-commands
14005 (user-error "Priority commands are disabled"))
14006 (setq action (or action 'set))
14007 (let (current new news have remove)
14008 (save-excursion
14009 (org-back-to-heading t)
14010 (when (looking-at org-priority-regexp)
14011 (setq current (string-to-char (match-string 2))
14012 have t))
14013 (cond
14014 ((eq action 'remove)
14015 (setq remove t new ?\ ))
14016 ((or (eq action 'set)
14017 (integerp action))
14018 (if (not (eq action 'set))
14019 (setq new action)
14020 (message "Priority %c-%c, SPC to remove: "
14021 org-highest-priority org-lowest-priority)
14022 (save-match-data
14023 (setq new (read-char-exclusive))))
14024 (when (and (= (upcase org-highest-priority) org-highest-priority)
14025 (= (upcase org-lowest-priority) org-lowest-priority))
14026 (setq new (upcase new)))
14027 (cond ((equal new ?\ ) (setq remove t))
14028 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14029 (user-error "Priority must be between `%c' and `%c'"
14030 org-highest-priority org-lowest-priority))))
14031 ((eq action 'up)
14032 (setq new (if have
14033 (1- current) ; normal cycling
14034 ;; last priority was empty
14035 (if (eq last-command this-command)
14036 org-lowest-priority ; wrap around empty to lowest
14037 ;; default
14038 (if org-priority-start-cycle-with-default
14039 org-default-priority
14040 (1- org-default-priority))))))
14041 ((eq action 'down)
14042 (setq new (if have
14043 (1+ current) ; normal cycling
14044 ;; last priority was empty
14045 (if (eq last-command this-command)
14046 org-highest-priority ; wrap around empty to highest
14047 ;; default
14048 (if org-priority-start-cycle-with-default
14049 org-default-priority
14050 (1+ org-default-priority))))))
14051 (t (user-error "Invalid action")))
14052 (when (or (< (upcase new) org-highest-priority)
14053 (> (upcase new) org-lowest-priority))
14054 (if (and (memq action '(up down))
14055 (not have) (not (eq last-command this-command)))
14056 ;; `new' is from default priority
14057 (error
14058 "The default can not be set, see `org-default-priority' why")
14059 ;; normal cycling: `new' is beyond highest/lowest priority
14060 ;; and is wrapped around to the empty priority
14061 (setq remove t)))
14062 (setq news (format "%c" new))
14063 (if have
14064 (if remove
14065 (replace-match "" t t nil 1)
14066 (replace-match news t t nil 2))
14067 (if remove
14068 (user-error "No priority cookie found in line")
14069 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14070 (if (match-end 2)
14071 (progn
14072 (goto-char (match-end 2))
14073 (insert " [#" news "]"))
14074 (goto-char (match-beginning 3))
14075 (insert "[#" news "] "))))
14076 (org-set-tags nil 'align))
14077 (if remove
14078 (message "Priority removed")
14079 (message "Priority of current item set to %s" news)))))
14081 (defun org-show-priority ()
14082 "Show the priority of the current item.
14083 This priority is composed of the main priority given with the [#A] cookies,
14084 and by additional input from the age of a schedules or deadline entry."
14085 (interactive)
14086 (let ((pri (if (eq major-mode 'org-agenda-mode)
14087 (org-get-at-bol 'priority)
14088 (save-excursion
14089 (save-match-data
14090 (beginning-of-line)
14091 (and (looking-at org-heading-regexp)
14092 (org-get-priority (match-string 0))))))))
14093 (message "Priority is %d" (if pri pri -1000))))
14095 (defun org-get-priority (s)
14096 "Find priority cookie and return priority."
14097 (save-match-data
14098 (if (functionp org-get-priority-function)
14099 (funcall org-get-priority-function)
14100 (if (not (string-match org-priority-regexp s))
14101 (* 1000 (- org-lowest-priority org-default-priority))
14102 (* 1000 (- org-lowest-priority
14103 (string-to-char (match-string 2 s))))))))
14105 ;;;; Tags
14107 (defvar org-agenda-archives-mode)
14108 (defvar org-map-continue-from nil
14109 "Position from where mapping should continue.
14110 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14112 (defvar org-scanner-tags nil
14113 "The current tag list while the tags scanner is running.")
14115 (defvar org-trust-scanner-tags nil
14116 "Should `org-get-tags-at' use the tags for the scanner.
14117 This is for internal dynamical scoping only.
14118 When this is non-nil, the function `org-get-tags-at' will return the value
14119 of `org-scanner-tags' instead of building the list by itself. This
14120 can lead to large speed-ups when the tags scanner is used in a file with
14121 many entries, and when the list of tags is retrieved, for example to
14122 obtain a list of properties. Building the tags list for each entry in such
14123 a file becomes an N^2 operation - but with this variable set, it scales
14124 as N.")
14126 (defvar org--matcher-tags-todo-only nil)
14128 (defun org-scan-tags (action matcher todo-only &optional start-level)
14129 "Scan headline tags with inheritance and produce output ACTION.
14131 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14132 or `agenda' to produce an entry list for an agenda view. It can also be
14133 a Lisp form or a function that should be called at each matched headline, in
14134 this case the return value is a list of all return values from these calls.
14136 MATCHER is a function accepting three arguments, returning
14137 a non-nil value whenever a given set of tags qualifies a headline
14138 for inclusion. See `org-make-tags-matcher' for more information.
14139 As a special case, it can also be set to t (respectively nil) in
14140 order to match all (respectively none) headline.
14142 When TODO-ONLY is non-nil, only lines with a not-done TODO
14143 keyword are included in the output.
14145 START-LEVEL can be a string with asterisks, reducing the scope to
14146 headlines matching this string."
14147 (require 'org-agenda)
14148 (let* ((re (concat "^"
14149 (if start-level
14150 ;; Get the correct level to match
14151 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14152 org-outline-regexp)
14153 " *\\(\\<\\("
14154 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14155 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14156 (props (list 'face 'default
14157 'done-face 'org-agenda-done
14158 'undone-face 'default
14159 'mouse-face 'highlight
14160 'org-not-done-regexp org-not-done-regexp
14161 'org-todo-regexp org-todo-regexp
14162 'org-complex-heading-regexp org-complex-heading-regexp
14163 'help-echo
14164 (format "mouse-2 or RET jump to org file %s"
14165 (abbreviate-file-name
14166 (or (buffer-file-name (buffer-base-buffer))
14167 (buffer-name (buffer-base-buffer)))))))
14168 (org-map-continue-from nil)
14169 lspos tags tags-list
14170 (tags-alist (list (cons 0 org-file-tags)))
14171 (llast 0) rtn rtn1 level category i txt
14172 todo marker entry priority
14173 ts-date ts-date-type ts-date-pair)
14174 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14175 (setq action (list 'lambda nil action)))
14176 (save-excursion
14177 (goto-char (point-min))
14178 (when (eq action 'sparse-tree)
14179 (org-overview)
14180 (org-remove-occur-highlights))
14181 (while (let (case-fold-search)
14182 (re-search-forward re nil t))
14183 (setq org-map-continue-from nil)
14184 (catch :skip
14185 (setq todo
14186 ;; TODO: is the 1-2 difference a bug?
14187 (when (match-end 1) (match-string-no-properties 2))
14188 tags (when (match-end 4) (match-string-no-properties 4)))
14189 (goto-char (setq lspos (match-beginning 0)))
14190 (setq level (org-reduced-level (org-outline-level))
14191 category (org-get-category))
14192 (when (eq action 'agenda)
14193 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14194 ts-date (car ts-date-pair)
14195 ts-date-type (cdr ts-date-pair)))
14196 (setq i llast llast level)
14197 ;; remove tag lists from same and sublevels
14198 (while (>= i level)
14199 (when (setq entry (assoc i tags-alist))
14200 (setq tags-alist (delete entry tags-alist)))
14201 (setq i (1- i)))
14202 ;; add the next tags
14203 (when tags
14204 (setq tags (org-split-string tags ":")
14205 tags-alist
14206 (cons (cons level tags) tags-alist)))
14207 ;; compile tags for current headline
14208 (setq tags-list
14209 (if org-use-tag-inheritance
14210 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14211 tags)
14212 org-scanner-tags tags-list)
14213 (when org-use-tag-inheritance
14214 (setcdr (car tags-alist)
14215 (mapcar (lambda (x)
14216 (setq x (copy-sequence x))
14217 (org-add-prop-inherited x))
14218 (cdar tags-alist))))
14219 (when (and tags org-use-tag-inheritance
14220 (or (not (eq t org-use-tag-inheritance))
14221 org-tags-exclude-from-inheritance))
14222 ;; Selective inheritance, remove uninherited ones.
14223 (setcdr (car tags-alist)
14224 (org-remove-uninherited-tags (cdar tags-alist))))
14225 (when (and
14227 ;; eval matcher only when the todo condition is OK
14228 (and (or (not todo-only) (member todo org-not-done-keywords))
14229 (if (functionp matcher)
14230 (let ((case-fold-search t) (org-trust-scanner-tags t))
14231 (funcall matcher todo tags-list level))
14232 matcher))
14234 ;; Call the skipper, but return t if it does not
14235 ;; skip, so that the `and' form continues evaluating.
14236 (progn
14237 (unless (eq action 'sparse-tree) (org-agenda-skip))
14240 ;; Check if timestamps are deselecting this entry
14241 (or (not todo-only)
14242 (and (member todo org-not-done-keywords)
14243 (or (not org-agenda-tags-todo-honor-ignore-options)
14244 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14246 ;; select this headline
14247 (cond
14248 ((eq action 'sparse-tree)
14249 (and org-highlight-sparse-tree-matches
14250 (org-get-heading) (match-end 0)
14251 (org-highlight-new-match
14252 (match-beginning 1) (match-end 1)))
14253 (org-show-context 'tags-tree))
14254 ((eq action 'agenda)
14255 (setq txt (org-agenda-format-item
14257 (concat
14258 (if (eq org-tags-match-list-sublevels 'indented)
14259 (make-string (1- level) ?.) "")
14260 (org-get-heading))
14261 (make-string level ?\s)
14262 category
14263 tags-list)
14264 priority (org-get-priority txt))
14265 (goto-char lspos)
14266 (setq marker (org-agenda-new-marker))
14267 (org-add-props txt props
14268 'org-marker marker 'org-hd-marker marker 'org-category category
14269 'todo-state todo
14270 'ts-date ts-date
14271 'priority priority
14272 'type (concat "tagsmatch" ts-date-type))
14273 (push txt rtn))
14274 ((functionp action)
14275 (setq org-map-continue-from nil)
14276 (save-excursion
14277 (setq rtn1 (funcall action))
14278 (push rtn1 rtn)))
14279 (t (user-error "Invalid action")))
14281 ;; if we are to skip sublevels, jump to end of subtree
14282 (unless org-tags-match-list-sublevels
14283 (org-end-of-subtree t)
14284 (backward-char 1))))
14285 ;; Get the correct position from where to continue
14286 (if org-map-continue-from
14287 (goto-char org-map-continue-from)
14288 (and (= (point) lspos) (end-of-line 1)))))
14289 (when (and (eq action 'sparse-tree)
14290 (not org-sparse-tree-open-archived-trees))
14291 (org-hide-archived-subtrees (point-min) (point-max)))
14292 (nreverse rtn)))
14294 (defun org-remove-uninherited-tags (tags)
14295 "Remove all tags that are not inherited from the list TAGS."
14296 (cond
14297 ((eq org-use-tag-inheritance t)
14298 (if org-tags-exclude-from-inheritance
14299 (org-delete-all org-tags-exclude-from-inheritance tags)
14300 tags))
14301 ((not org-use-tag-inheritance) nil)
14302 ((stringp org-use-tag-inheritance)
14303 (delq nil (mapcar
14304 (lambda (x)
14305 (if (and (string-match org-use-tag-inheritance x)
14306 (not (member x org-tags-exclude-from-inheritance)))
14307 x nil))
14308 tags)))
14309 ((listp org-use-tag-inheritance)
14310 (delq nil (mapcar
14311 (lambda (x)
14312 (if (member x org-use-tag-inheritance) x nil))
14313 tags)))))
14315 (defun org-match-sparse-tree (&optional todo-only match)
14316 "Create a sparse tree according to tags string MATCH.
14318 MATCH is a string with match syntax. It can contain a selection
14319 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14320 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14321 those. See the manual for details.
14323 If optional argument TODO-ONLY is non-nil, only select lines that
14324 are also TODO tasks."
14325 (interactive "P")
14326 (org-agenda-prepare-buffers (list (current-buffer)))
14327 (let ((org--matcher-tags-todo-only todo-only))
14328 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14329 org--matcher-tags-todo-only)))
14331 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14333 (defvar org-cached-props nil)
14334 (defun org-cached-entry-get (pom property)
14335 (if (or (eq t org-use-property-inheritance)
14336 (and (stringp org-use-property-inheritance)
14337 (let ((case-fold-search t))
14338 (string-match-p org-use-property-inheritance property)))
14339 (and (listp org-use-property-inheritance)
14340 (member-ignore-case property org-use-property-inheritance)))
14341 ;; Caching is not possible, check it directly.
14342 (org-entry-get pom property 'inherit)
14343 ;; Get all properties, so we can do complicated checks easily.
14344 (cdr (assoc-string property
14345 (or org-cached-props
14346 (setq org-cached-props (org-entry-properties pom)))
14347 t))))
14349 (defun org-global-tags-completion-table (&optional files)
14350 "Return the list of all tags in all agenda buffer/files.
14351 Optional FILES argument is a list of files which can be used
14352 instead of the agenda files."
14353 (save-excursion
14354 (org-uniquify
14355 (delq nil
14356 (apply #'append
14357 (mapcar
14358 (lambda (file)
14359 (set-buffer (find-file-noselect file))
14360 (mapcar (lambda (x)
14361 (and (stringp (car-safe x))
14362 (list (car-safe x))))
14363 (or org-current-tag-alist (org-get-buffer-tags))))
14364 (if (car-safe files) files
14365 (org-agenda-files))))))))
14367 (defun org-make-tags-matcher (match)
14368 "Create the TAGS/TODO matcher form for the selection string MATCH.
14370 Returns a cons of the selection string MATCH and a function
14371 implementing the matcher.
14373 The matcher is to be called at an Org entry, with point on the
14374 headline, and returns non-nil if the entry matches the selection
14375 string MATCH. It must be called with three arguments: the TODO
14376 keyword at the entry (or nil if none), the list of all tags at
14377 the entry including inherited ones and the reduced level of the
14378 headline. Additionally, the category of the entry, if any, must
14379 be specified as the text property `org-category' on the headline.
14381 This function sets the variable `org--matcher-tags-todo-only' to
14382 a non-nil value if the matcher restricts matching to TODO
14383 entries, otherwise it is not touched.
14385 See also `org-scan-tags'."
14386 (unless match
14387 ;; Get a new match request, with completion against the global
14388 ;; tags table and the local tags in current buffer.
14389 (let ((org-last-tags-completion-table
14390 (org-uniquify
14391 (delq nil (append (org-get-buffer-tags)
14392 (org-global-tags-completion-table))))))
14393 (setq match
14394 (completing-read
14395 "Match: "
14396 'org-tags-completion-function nil nil nil 'org-tags-history))))
14398 (let ((match0 match)
14399 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14400 (start 0)
14401 tagsmatch todomatch tagsmatcher todomatcher)
14403 ;; Expand group tags.
14404 (setq match (org-tags-expand match))
14406 ;; Check if there is a TODO part of this match, which would be the
14407 ;; part after a "/". To make sure that this slash is not part of
14408 ;; a property value to be matched against, we also check that
14409 ;; there is no / after that slash. First, find the last slash.
14410 (let ((s 0))
14411 (while (string-match "/+" match s)
14412 (setq start (match-beginning 0))
14413 (setq s (match-end 0))))
14414 (if (and (string-match "/+" match start)
14415 (not (string-match-p "\"" match start)))
14416 ;; Match contains also a TODO-matching request.
14417 (progn
14418 (setq tagsmatch (substring match 0 (match-beginning 0)))
14419 (setq todomatch (substring match (match-end 0)))
14420 (when (string-prefix-p "!" todomatch)
14421 (setq org--matcher-tags-todo-only t)
14422 (setq todomatch (substring todomatch 1)))
14423 (when (string-match "\\`\\s-*\\'" todomatch)
14424 (setq todomatch nil)))
14425 ;; Only matching tags.
14426 (setq tagsmatch match)
14427 (setq todomatch nil))
14429 ;; Make the tags matcher.
14430 (when (org-string-nw-p tagsmatch)
14431 (let ((orlist nil)
14432 (orterms (org-split-string tagsmatch "|"))
14433 term)
14434 (while (setq term (pop orterms))
14435 (while (and (equal (substring term -1) "\\") orterms)
14436 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14437 (while (string-match re term)
14438 (let* ((rest (substring term (match-end 0)))
14439 (minus (and (match-end 1)
14440 (equal (match-string 1 term) "-")))
14441 (tag (save-match-data
14442 (replace-regexp-in-string
14443 "\\\\-" "-" (match-string 2 term))))
14444 (regexp (eq (string-to-char tag) ?{))
14445 (levelp (match-end 4))
14446 (propp (match-end 5))
14448 (cond
14449 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14450 (levelp
14451 `(,(org-op-to-function (match-string 3 term))
14452 level
14453 ,(string-to-number (match-string 4 term))))
14454 (propp
14455 (let* ((gv (pcase (upcase (match-string 5 term))
14456 ("CATEGORY"
14457 '(get-text-property (point) 'org-category))
14458 ("TODO" 'todo)
14459 (p `(org-cached-entry-get nil ,p))))
14460 (pv (match-string 7 term))
14461 (regexp (eq (string-to-char pv) ?{))
14462 (strp (eq (string-to-char pv) ?\"))
14463 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14464 (po (org-op-to-function (match-string 6 term)
14465 (if timep 'time strp))))
14466 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14467 (when timep (setq pv (org-matcher-time pv)))
14468 (cond ((and regexp (eq po 'org<>))
14469 `(not (string-match ,pv (or ,gv ""))))
14470 (regexp `(string-match ,pv (or ,gv "")))
14471 (strp `(,po (or ,gv "") ,pv))
14473 `(,po
14474 (string-to-number (or ,gv ""))
14475 ,(string-to-number pv))))))
14476 (t `(member ,tag tags-list)))))
14477 (push (if minus `(not ,mm) mm) tagsmatcher)
14478 (setq term rest)))
14479 (push `(and ,@tagsmatcher) orlist)
14480 (setq tagsmatcher nil))
14481 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14483 ;; Make the TODO matcher.
14484 (when (org-string-nw-p todomatch)
14485 (let ((orlist nil))
14486 (dolist (term (org-split-string todomatch "|"))
14487 (while (string-match re term)
14488 (let* ((minus (and (match-end 1)
14489 (equal (match-string 1 term) "-")))
14490 (kwd (match-string 2 term))
14491 (regexp (eq (string-to-char kwd) ?{))
14492 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14493 `(equal todo ,kwd))))
14494 (push (if minus `(not ,mm) mm) todomatcher))
14495 (setq term (substring term (match-end 0))))
14496 (push (if (> (length todomatcher) 1)
14497 (cons 'and todomatcher)
14498 (car todomatcher))
14499 orlist)
14500 (setq todomatcher nil))
14501 (setq todomatcher (cons 'or orlist))))
14503 ;; Return the string and function of the matcher. If no
14504 ;; tags-specific or todo-specific matcher exists, match
14505 ;; everything.
14506 (let ((matcher (if (and tagsmatcher todomatcher)
14507 `(and ,tagsmatcher ,todomatcher)
14508 (or tagsmatcher todomatcher t))))
14509 (when org--matcher-tags-todo-only
14510 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14511 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14513 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14514 "Expand group tags in MATCH.
14516 This replaces every group tag in MATCH with a regexp tag search.
14517 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14518 will be replaced like this:
14520 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14521 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14522 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14524 Replacing by a regexp preserves the structure of the match.
14525 E.g., this expansion
14527 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14529 will match anything tagged with \"Lab\" and \"Home\", or tagged
14530 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14532 A group tag in MATCH can contain regular expressions of its own.
14533 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14534 will be replaced like this:
14536 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14538 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14539 assumed to be a single group tag, and the function will return
14540 the list of tags in this group.
14542 When DOWNCASE is non-nil, expand downcased TAGS."
14543 (if org-group-tags
14544 (let* ((case-fold-search t)
14545 (stable org-mode-syntax-table)
14546 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14547 (taggroups (if downcased
14548 (mapcar (lambda (tg) (mapcar #'downcase tg))
14549 taggroups)
14550 taggroups))
14551 (taggroups-keys (mapcar #'car taggroups))
14552 (return-match (if downcased (downcase match) match))
14553 (count 0)
14554 (work-already-expanded tags-already-expanded)
14555 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14556 ;; @ and _ are allowed as word-components in tags.
14557 (modify-syntax-entry ?@ "w" stable)
14558 (modify-syntax-entry ?_ "w" stable)
14559 ;; Temporarily replace regexp-expressions in the match-expression.
14560 (while (string-match "{.+?}" return-match)
14561 (cl-incf count)
14562 (push (match-string 0 return-match) regexps-in-match)
14563 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14564 (while (and taggroups-keys
14565 (with-syntax-table stable
14566 (string-match
14567 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14568 (regexp-opt taggroups-keys) "\\>\\)")
14569 return-match)))
14570 (let* ((dir (match-string 1 return-match))
14571 (tag (match-string 2 return-match))
14572 (tag (if downcased (downcase tag) tag)))
14573 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14574 (member tag work-already-expanded))
14575 (setq tags-in-group (assoc tag taggroups))
14576 (push tag work-already-expanded)
14577 ;; Recursively expand each tag in the group, if the tag hasn't
14578 ;; already been expanded. Restore the match-data after all recursive calls.
14579 (save-match-data
14580 (let (tags-expanded)
14581 (dolist (x (cdr tags-in-group))
14582 (if (and (member x taggroups-keys)
14583 (not (member x work-already-expanded)))
14584 (setq tags-expanded
14585 (delete-dups
14586 (append
14587 (org-tags-expand x t downcased
14588 work-already-expanded)
14589 tags-expanded)))
14590 (setq tags-expanded
14591 (append (list x) tags-expanded)))
14592 (setq work-already-expanded
14593 (delete-dups
14594 (append tags-expanded
14595 work-already-expanded))))
14596 (setq tags-in-group
14597 (delete-dups (cons (car tags-in-group)
14598 tags-expanded)))))
14599 ;; Filter tag-regexps from tags.
14600 (setq regexp-in-group-escaped
14601 (delq nil (mapcar (lambda (x)
14602 (if (stringp x)
14603 (and (equal "{" (substring x 0 1))
14604 (equal "}" (substring x -1))
14607 tags-in-group))
14608 regexp-in-group
14609 (mapcar (lambda (x)
14610 (substring x 1 -1))
14611 regexp-in-group-escaped)
14612 tags-in-group
14613 (delq nil (mapcar (lambda (x)
14614 (if (stringp x)
14615 (and (not (equal "{" (substring x 0 1)))
14616 (not (equal "}" (substring x -1)))
14619 tags-in-group)))
14620 ;; If single-as-list, do no more in the while-loop.
14621 (if (not single-as-list)
14622 (progn
14623 (when regexp-in-group
14624 (setq regexp-in-group
14625 (concat "\\|"
14626 (mapconcat 'identity regexp-in-group
14627 "\\|"))))
14628 (setq tags-in-group
14629 (concat dir
14630 "{\\<"
14631 (regexp-opt tags-in-group)
14632 "\\>"
14633 regexp-in-group
14634 "}"))
14635 (when (stringp tags-in-group)
14636 (org-add-props tags-in-group '(grouptag t)))
14637 (setq return-match
14638 (replace-match tags-in-group t t return-match)))
14639 (setq tags-in-group
14640 (append regexp-in-group-escaped tags-in-group))))
14641 (setq taggroups-keys (delete tag taggroups-keys))))
14642 ;; Add the regular expressions back into the match-expression again.
14643 (while regexps-in-match
14644 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14645 (pop regexps-in-match)
14646 return-match t t))
14647 (cl-decf count))
14648 (if single-as-list
14649 (if tags-in-group tags-in-group (list return-match))
14650 return-match))
14651 (if single-as-list
14652 (list (if downcased (downcase match) match))
14653 match)))
14655 (defun org-op-to-function (op &optional stringp)
14656 "Turn an operator into the appropriate function."
14657 (setq op
14658 (cond
14659 ((equal op "<" ) '(< string< org-time<))
14660 ((equal op ">" ) '(> org-string> org-time>))
14661 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14662 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14663 ((member op '("=" "==")) '(= string= org-time=))
14664 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14665 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14667 (defun org<> (a b) (not (= a b)))
14668 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14669 (defun org-string>= (a b) (not (string< a b)))
14670 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14671 (defun org-string<> (a b) (not (string= a b)))
14672 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14673 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14674 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14675 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14676 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14677 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14678 (defun org-2ft (s)
14679 "Convert S to a floating point time.
14680 If S is already a number, just return it. If it is a string, parse
14681 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14682 (cond
14683 ((numberp s) s)
14684 ((stringp s)
14685 (condition-case nil
14686 (float-time (apply 'encode-time (org-parse-time-string s)))
14687 (error 0.)))
14688 (t 0.)))
14690 (defun org-time-today ()
14691 "Time in seconds today at 0:00.
14692 Returns the float number of seconds since the beginning of the
14693 epoch to the beginning of today (00:00)."
14694 (float-time (apply 'encode-time
14695 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14697 (defun org-matcher-time (s)
14698 "Interpret a time comparison value."
14699 (save-match-data
14700 (cond
14701 ((string= s "<now>") (float-time))
14702 ((string= s "<today>") (org-time-today))
14703 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14704 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14705 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14706 (+ (org-time-today)
14707 (* (string-to-number (match-string 1 s))
14708 (cdr (assoc (match-string 2 s)
14709 '(("d" . 86400.0) ("w" . 604800.0)
14710 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14711 (t (org-2ft s)))))
14713 (defun org-match-any-p (re list)
14714 "Does re match any element of list?"
14715 (setq list (mapcar (lambda (x) (string-match re x)) list))
14716 (delq nil list))
14718 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14719 (defvar org-tags-overlay (make-overlay 1 1))
14720 (delete-overlay org-tags-overlay)
14722 (defun org-get-local-tags-at (&optional pos)
14723 "Get a list of tags defined in the current headline."
14724 (org-get-tags-at pos 'local))
14726 (defun org-get-local-tags ()
14727 "Get a list of tags defined in the current headline."
14728 (org-get-tags-at nil 'local))
14730 (defun org-get-tags-at (&optional pos local)
14731 "Get a list of all headline tags applicable at POS.
14732 POS defaults to point. If tags are inherited, the list contains
14733 the targets in the same sequence as the headlines appear, i.e.
14734 the tags of the current headline come last.
14735 When LOCAL is non-nil, only return tags from the current headline,
14736 ignore inherited ones."
14737 (interactive)
14738 (if (and org-trust-scanner-tags
14739 (or (not pos) (equal pos (point)))
14740 (not local))
14741 org-scanner-tags
14742 (let (tags ltags lastpos parent)
14743 (save-excursion
14744 (save-restriction
14745 (widen)
14746 (goto-char (or pos (point)))
14747 (save-match-data
14748 (catch 'done
14749 (condition-case nil
14750 (progn
14751 (org-back-to-heading t)
14752 (while (not (equal lastpos (point)))
14753 (setq lastpos (point))
14754 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14755 (setq ltags (org-split-string
14756 (match-string-no-properties 1) ":"))
14757 (when parent
14758 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14759 (setq tags (append
14760 (if parent
14761 (org-remove-uninherited-tags ltags)
14762 ltags)
14763 tags)))
14764 (or org-use-tag-inheritance (throw 'done t))
14765 (when local (throw 'done t))
14766 (or (org-up-heading-safe) (error nil))
14767 (setq parent t)))
14768 (error nil)))))
14769 (if local
14770 tags
14771 (reverse (delete-dups
14772 (reverse (append
14773 (org-remove-uninherited-tags
14774 org-file-tags)
14775 tags)))))))))
14777 (defun org-add-prop-inherited (s)
14778 (add-text-properties 0 (length s) '(inherited t) s)
14781 (defun org-toggle-tag (tag &optional onoff)
14782 "Toggle the tag TAG for the current line.
14783 If ONOFF is `on' or `off', don't toggle but set to this state."
14784 (let (res current)
14785 (save-excursion
14786 (org-back-to-heading t)
14787 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14788 (point-at-eol) t)
14789 (progn
14790 (setq current (match-string 1))
14791 (replace-match ""))
14792 (setq current ""))
14793 (setq current (nreverse (org-split-string current ":")))
14794 (cond
14795 ((eq onoff 'on)
14796 (setq res t)
14797 (or (member tag current) (push tag current)))
14798 ((eq onoff 'off)
14799 (or (not (member tag current)) (setq current (delete tag current))))
14800 (t (if (member tag current)
14801 (setq current (delete tag current))
14802 (setq res t)
14803 (push tag current))))
14804 (end-of-line 1)
14805 (if current
14806 (progn
14807 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14808 (org-set-tags nil t))
14809 (delete-horizontal-space))
14810 (run-hooks 'org-after-tags-change-hook))
14811 res))
14813 (defun org--align-tags-here (to-col)
14814 "Align tags on the current headline to TO-COL.
14815 Assume point is on a headline."
14816 (let ((pos (point)))
14817 (beginning-of-line)
14818 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14819 (>= pos (match-beginning 2)))
14820 ;; No tags or point within tags: do not align.
14821 (goto-char pos)
14822 (goto-char (match-beginning 1))
14823 (let ((shift (max (- (if (>= to-col 0) to-col
14824 (- (abs to-col) (string-width (match-string 2))))
14825 (current-column))
14826 1)))
14827 (replace-match (make-string shift ?\s) nil nil nil 1)
14828 ;; Preserve initial position, if possible. In any case, stop
14829 ;; before tags.
14830 (when (< pos (point)) (goto-char pos))))))
14832 (defun org-set-tags-command (&optional arg just-align)
14833 "Call the set-tags command for the current entry."
14834 (interactive "P")
14835 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14836 (org-set-tags arg just-align)
14837 (save-excursion
14838 (unless (and (org-region-active-p)
14839 org-loop-over-headlines-in-active-region)
14840 (org-back-to-heading t))
14841 (org-set-tags arg just-align))))
14843 (defun org-set-tags-to (data)
14844 "Set the tags of the current entry to DATA, replacing the current tags.
14845 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14846 If DATA is nil or the empty string, any tags will be removed."
14847 (interactive "sTags: ")
14848 (setq data
14849 (cond
14850 ((eq data nil) "")
14851 ((equal data "") "")
14852 ((stringp data)
14853 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14854 ":"))
14855 ((listp data)
14856 (concat ":" (mapconcat 'identity data ":") ":"))))
14857 (when data
14858 (save-excursion
14859 (org-back-to-heading t)
14860 (when (let ((case-fold-search nil))
14861 (looking-at org-complex-heading-regexp))
14862 (if (match-end 5)
14863 (progn
14864 (goto-char (match-beginning 5))
14865 (insert data)
14866 (delete-region (point) (point-at-eol))
14867 (org-set-tags nil 'align))
14868 (goto-char (point-at-eol))
14869 (insert " " data)
14870 (org-set-tags nil 'align)))
14871 (beginning-of-line 1)
14872 (when (looking-at ".*?\\([ \t]+\\)$")
14873 (delete-region (match-beginning 1) (match-end 1))))))
14875 (defun org-align-all-tags ()
14876 "Align the tags in all headings."
14877 (interactive)
14878 (save-excursion
14879 (or (ignore-errors (org-back-to-heading t))
14880 (outline-next-heading))
14881 (if (org-at-heading-p)
14882 (org-set-tags t)
14883 (message "No headings"))))
14885 (defvar org-indent-indentation-per-level)
14886 (defun org-set-tags (&optional arg just-align)
14887 "Set the tags for the current headline.
14888 With prefix ARG, realign all tags in headings in the current buffer.
14889 When JUST-ALIGN is non-nil, only align tags."
14890 (interactive "P")
14891 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14892 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14893 'region-start-level
14894 'region))
14895 org-loop-over-headlines-in-active-region)
14896 (org-map-entries
14897 ;; We don't use ARG and JUST-ALIGN here because these args
14898 ;; are not useful when looping over headlines.
14899 #'org-set-tags
14900 org-loop-over-headlines-in-active-region
14902 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14903 (let ((org-setting-tags t))
14904 (if arg
14905 (save-excursion
14906 (goto-char (point-min))
14907 (while (re-search-forward org-outline-regexp-bol nil t)
14908 (org-set-tags nil t)
14909 (end-of-line))
14910 (message "All tags realigned to column %d" org-tags-column))
14911 (let* ((current (org-get-tags-string))
14912 (tags
14913 (if just-align current
14914 ;; Get a new set of tags from the user.
14915 (save-excursion
14916 (let* ((seen)
14917 (table
14918 (setq
14919 org-last-tags-completion-table
14920 ;; Uniquify tags in alists, yet preserve
14921 ;; structure (i.e., keywords).
14922 (delq nil
14923 (mapcar
14924 (lambda (pair)
14925 (let ((head (car pair)))
14926 (cond ((symbolp head) pair)
14927 ((member head seen) nil)
14928 (t (push head seen)
14929 pair))))
14930 (append
14931 (or org-current-tag-alist
14932 (org-get-buffer-tags))
14933 (and
14934 org-complete-tags-always-offer-all-agenda-tags
14935 (org-global-tags-completion-table
14936 (org-agenda-files))))))))
14937 (current-tags (org-split-string current ":"))
14938 (inherited-tags
14939 (nreverse (nthcdr (length current-tags)
14940 (nreverse (org-get-tags-at))))))
14941 (replace-regexp-in-string
14942 "\\([-+&]+\\|,\\)"
14944 (if (or (eq t org-use-fast-tag-selection)
14945 (and org-use-fast-tag-selection
14946 (delq nil (mapcar #'cdr table))))
14947 (org-fast-tag-selection
14948 current-tags inherited-tags table
14949 (and org-fast-tag-selection-include-todo
14950 org-todo-key-alist))
14951 (let ((org-add-colon-after-tag-completion
14952 (< 1 (length table))))
14953 (org-trim
14954 (completing-read
14955 "Tags: "
14956 #'org-tags-completion-function
14957 nil nil current 'org-tags-history))))))))))
14959 (when org-tags-sort-function
14960 (setq tags
14961 (mapconcat
14962 #'identity
14963 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14964 org-tags-sort-function)
14965 ":")))
14967 (if (or (string= ":" tags)
14968 (string= "::" tags))
14969 (setq tags ""))
14970 (if (not (org-string-nw-p tags)) (setq tags "")
14971 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14972 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14974 ;; Insert new tags at the correct column.
14975 (unless (equal current tags)
14976 (save-excursion
14977 (beginning-of-line)
14978 (let ((case-fold-search nil))
14979 (looking-at org-complex-heading-regexp))
14980 ;; Remove current tags, if any.
14981 (when (match-end 5) (replace-match "" nil nil nil 5))
14982 ;; Insert new tags, if any. Otherwise, remove trailing
14983 ;; white spaces.
14984 (end-of-line)
14985 (if (not (equal tags ""))
14986 ;; When text is being inserted on an invisible
14987 ;; region boundary, it can be inadvertently sucked
14988 ;; into invisibility.
14989 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14990 (skip-chars-backward " \t")
14991 (delete-region (point) (line-end-position)))))
14992 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14993 ;; is on.
14994 (unless (equal tags "")
14995 (let* ((level (save-excursion
14996 (beginning-of-line)
14997 (skip-chars-forward "\\*")))
14998 (offset (if (bound-and-true-p org-indent-mode)
14999 (* (1- org-indent-indentation-per-level)
15000 (1- level))
15002 (tags-column
15003 (+ org-tags-column
15004 (if (> org-tags-column 0) (- offset) offset))))
15005 (org--align-tags-here tags-column))))
15006 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15008 (defun org-change-tag-in-region (beg end tag off)
15009 "Add or remove TAG for each entry in the region.
15010 This works in the agenda, and also in an Org buffer."
15011 (interactive
15012 (list (region-beginning) (region-end)
15013 (let ((org-last-tags-completion-table
15014 (if (derived-mode-p 'org-mode)
15015 (org-uniquify
15016 (delq nil (append (org-get-buffer-tags)
15017 (org-global-tags-completion-table))))
15018 (org-global-tags-completion-table))))
15019 (completing-read
15020 "Tag: " 'org-tags-completion-function nil nil nil
15021 'org-tags-history))
15022 (progn
15023 (message "[s]et or [r]emove? ")
15024 (equal (read-char-exclusive) ?r))))
15025 (when (fboundp 'deactivate-mark) (deactivate-mark))
15026 (let ((agendap (equal major-mode 'org-agenda-mode))
15027 l1 l2 m buf pos newhead (cnt 0))
15028 (goto-char end)
15029 (setq l2 (1- (org-current-line)))
15030 (goto-char beg)
15031 (setq l1 (org-current-line))
15032 (cl-loop for l from l1 to l2 do
15033 (org-goto-line l)
15034 (setq m (get-text-property (point) 'org-hd-marker))
15035 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15036 (and agendap m))
15037 (setq buf (if agendap (marker-buffer m) (current-buffer))
15038 pos (if agendap m (point)))
15039 (with-current-buffer buf
15040 (save-excursion
15041 (save-restriction
15042 (goto-char pos)
15043 (setq cnt (1+ cnt))
15044 (org-toggle-tag tag (if off 'off 'on))
15045 (setq newhead (org-get-heading)))))
15046 (and agendap (org-agenda-change-all-lines newhead m))))
15047 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15049 (defun org-tags-completion-function (string _predicate &optional flag)
15050 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15051 (confirm (lambda (x) (stringp (car x)))))
15052 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15053 (setq s1 (match-string 1 string)
15054 s2 (match-string 2 string))
15055 (setq s1 "" s2 string))
15056 (cond
15057 ((eq flag nil)
15058 ;; try completion
15059 (setq rtn (try-completion s2 ctable confirm))
15060 (when (stringp rtn)
15061 (setq rtn
15062 (concat s1 s2 (substring rtn (length s2))
15063 (if (and org-add-colon-after-tag-completion
15064 (assoc rtn ctable))
15065 ":" ""))))
15066 rtn)
15067 ((eq flag t)
15068 ;; all-completions
15069 (all-completions s2 ctable confirm))
15070 ((eq flag 'lambda)
15071 ;; exact match?
15072 (assoc s2 ctable)))))
15074 (defun org-fast-tag-insert (kwd tags face &optional end)
15075 "Insert KDW, and the TAGS, the latter with face FACE.
15076 Also insert END."
15077 (insert (format "%-12s" (concat kwd ":"))
15078 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15079 (or end "")))
15081 (defun org-fast-tag-show-exit (flag)
15082 (save-excursion
15083 (org-goto-line 3)
15084 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15085 (replace-match ""))
15086 (when flag
15087 (end-of-line 1)
15088 (org-move-to-column (- (window-width) 19) t)
15089 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15091 (defun org-set-current-tags-overlay (current prefix)
15092 "Add an overlay to CURRENT tag with PREFIX."
15093 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15094 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15095 (org-overlay-display org-tags-overlay (concat prefix s))))
15097 (defvar org-last-tag-selection-key nil)
15098 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15099 "Fast tag selection with single keys.
15100 CURRENT is the current list of tags in the headline, INHERITED is the
15101 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15102 possibly with grouping information. TODO-TABLE is a similar table with
15103 TODO keywords, should these have keys assigned to them.
15104 If the keys are nil, a-z are automatically assigned.
15105 Returns the new tags string, or nil to not change the current settings."
15106 (let* ((fulltable (append table todo-table))
15107 (maxlen (apply 'max (mapcar
15108 (lambda (x)
15109 (if (stringp (car x)) (string-width (car x)) 0))
15110 fulltable)))
15111 (buf (current-buffer))
15112 (expert (eq org-fast-tag-selection-single-key 'expert))
15113 (buffer-tags nil)
15114 (fwidth (+ maxlen 3 1 3))
15115 (ncol (/ (- (window-width) 4) fwidth))
15116 (i-face 'org-done)
15117 (c-face 'org-todo)
15118 tg cnt e c char c1 c2 ntable tbl rtn
15119 ov-start ov-end ov-prefix
15120 (exit-after-next org-fast-tag-selection-single-key)
15121 (done-keywords org-done-keywords)
15122 groups ingroup intaggroup)
15123 (save-excursion
15124 (beginning-of-line 1)
15125 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15126 (setq ov-start (match-beginning 1)
15127 ov-end (match-end 1)
15128 ov-prefix "")
15129 (setq ov-start (1- (point-at-eol))
15130 ov-end (1+ ov-start))
15131 (skip-chars-forward "^\n\r")
15132 (setq ov-prefix
15133 (concat
15134 (buffer-substring (1- (point)) (point))
15135 (if (> (current-column) org-tags-column)
15137 (make-string (- org-tags-column (current-column)) ?\ ))))))
15138 (move-overlay org-tags-overlay ov-start ov-end)
15139 (save-window-excursion
15140 (if expert
15141 (set-buffer (get-buffer-create " *Org tags*"))
15142 (delete-other-windows)
15143 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15144 (org-switch-to-buffer-other-window " *Org tags*"))
15145 (erase-buffer)
15146 (setq-local org-done-keywords done-keywords)
15147 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15148 (org-fast-tag-insert "Current" current c-face "\n\n")
15149 (org-fast-tag-show-exit exit-after-next)
15150 (org-set-current-tags-overlay current ov-prefix)
15151 (setq tbl fulltable char ?a cnt 0)
15152 (while (setq e (pop tbl))
15153 (cond
15154 ((eq (car e) :startgroup)
15155 (push '() groups) (setq ingroup t)
15156 (unless (zerop cnt)
15157 (setq cnt 0)
15158 (insert "\n"))
15159 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15160 ((eq (car e) :endgroup)
15161 (setq ingroup nil cnt 0)
15162 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15163 ((eq (car e) :startgrouptag)
15164 (setq intaggroup t)
15165 (unless (zerop cnt)
15166 (setq cnt 0)
15167 (insert "\n"))
15168 (insert "[ "))
15169 ((eq (car e) :endgrouptag)
15170 (setq intaggroup nil cnt 0)
15171 (insert "]\n"))
15172 ((equal e '(:newline))
15173 (unless (zerop cnt)
15174 (setq cnt 0)
15175 (insert "\n")
15176 (setq e (car tbl))
15177 (while (equal (car tbl) '(:newline))
15178 (insert "\n")
15179 (setq tbl (cdr tbl)))))
15180 ((equal e '(:grouptags)) (insert " : "))
15182 (setq tg (copy-sequence (car e)) c2 nil)
15183 (if (cdr e)
15184 (setq c (cdr e))
15185 ;; automatically assign a character.
15186 (setq c1 (string-to-char
15187 (downcase (substring
15188 tg (if (= (string-to-char tg) ?@) 1 0)))))
15189 (if (or (rassoc c1 ntable) (rassoc c1 table))
15190 (while (or (rassoc char ntable) (rassoc char table))
15191 (setq char (1+ char)))
15192 (setq c2 c1))
15193 (setq c (or c2 char)))
15194 (when ingroup (push tg (car groups)))
15195 (setq tg (org-add-props tg nil 'face
15196 (cond
15197 ((not (assoc tg table))
15198 (org-get-todo-face tg))
15199 ((member tg current) c-face)
15200 ((member tg inherited) i-face))))
15201 (when (equal (caar tbl) :grouptags)
15202 (org-add-props tg nil 'face 'org-tag-group))
15203 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15204 (insert "[" c "] " tg (make-string
15205 (- fwidth 4 (length tg)) ?\ ))
15206 (push (cons tg c) ntable)
15207 (when (= (cl-incf cnt) ncol)
15208 (insert "\n")
15209 (when (or ingroup intaggroup) (insert " "))
15210 (setq cnt 0)))))
15211 (setq ntable (nreverse ntable))
15212 (insert "\n")
15213 (goto-char (point-min))
15214 (unless expert (org-fit-window-to-buffer))
15215 (setq rtn
15216 (catch 'exit
15217 (while t
15218 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15219 (if (not groups) "no " "")
15220 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15221 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15222 (setq org-last-tag-selection-key c)
15223 (cond
15224 ((= c ?\r) (throw 'exit t))
15225 ((= c ?!)
15226 (setq groups (not groups))
15227 (goto-char (point-min))
15228 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15229 ((= c ?\C-c)
15230 (if (not expert)
15231 (org-fast-tag-show-exit
15232 (setq exit-after-next (not exit-after-next)))
15233 (setq expert nil)
15234 (delete-other-windows)
15235 (set-window-buffer (split-window-vertically) " *Org tags*")
15236 (org-switch-to-buffer-other-window " *Org tags*")
15237 (org-fit-window-to-buffer)))
15238 ((or (= c ?\C-g)
15239 (and (= c ?q) (not (rassoc c ntable))))
15240 (delete-overlay org-tags-overlay)
15241 (setq quit-flag t))
15242 ((= c ?\ )
15243 (setq current nil)
15244 (when exit-after-next (setq exit-after-next 'now)))
15245 ((= c ?\t)
15246 (condition-case nil
15247 (setq tg (completing-read
15248 "Tag: "
15249 (or buffer-tags
15250 (with-current-buffer buf
15251 (setq buffer-tags
15252 (org-get-buffer-tags))))))
15253 (quit (setq tg "")))
15254 (when (string-match "\\S-" tg)
15255 (cl-pushnew (list tg) buffer-tags :test #'equal)
15256 (if (member tg current)
15257 (setq current (delete tg current))
15258 (push tg current)))
15259 (when exit-after-next (setq exit-after-next 'now)))
15260 ((setq e (rassoc c todo-table) tg (car e))
15261 (with-current-buffer buf
15262 (save-excursion (org-todo tg)))
15263 (when exit-after-next (setq exit-after-next 'now)))
15264 ((setq e (rassoc c ntable) tg (car e))
15265 (if (member tg current)
15266 (setq current (delete tg current))
15267 (cl-loop for g in groups do
15268 (when (member tg g)
15269 (dolist (x g) (setq current (delete x current)))))
15270 (push tg current))
15271 (when exit-after-next (setq exit-after-next 'now))))
15273 ;; Create a sorted list
15274 (setq current
15275 (sort current
15276 (lambda (a b)
15277 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15278 (when (eq exit-after-next 'now) (throw 'exit t))
15279 (goto-char (point-min))
15280 (beginning-of-line 2)
15281 (delete-region (point) (point-at-eol))
15282 (org-fast-tag-insert "Current" current c-face)
15283 (org-set-current-tags-overlay current ov-prefix)
15284 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15285 (setq tg (match-string 1))
15286 (add-text-properties
15287 (match-beginning 1) (match-end 1)
15288 (list 'face
15289 (cond
15290 ((member tg current) c-face)
15291 ((member tg inherited) i-face)
15292 (t (get-text-property (match-beginning 1) 'face))))))
15293 (goto-char (point-min)))))
15294 (delete-overlay org-tags-overlay)
15295 (if rtn
15296 (mapconcat 'identity current ":")
15297 nil))))
15299 (defun org-get-tags-string ()
15300 "Get the TAGS string in the current headline."
15301 (unless (org-at-heading-p t)
15302 (user-error "Not on a heading"))
15303 (save-excursion
15304 (beginning-of-line 1)
15305 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15306 (match-string-no-properties 1)
15307 "")))
15309 (defun org-get-tags ()
15310 "Get the list of tags specified in the current headline."
15311 (org-split-string (org-get-tags-string) ":"))
15313 (defun org-get-buffer-tags ()
15314 "Get a table of all tags used in the buffer, for completion."
15315 (org-with-wide-buffer
15316 (goto-char (point-min))
15317 (let ((tag-re (concat org-outline-regexp-bol
15318 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15319 tags)
15320 (while (re-search-forward tag-re nil t)
15321 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15322 (push tag tags)))
15323 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15325 ;;;; The mapping API
15327 (defvar org-agenda-skip-comment-trees)
15328 (defvar org-agenda-skip-function)
15329 (defun org-map-entries (func &optional match scope &rest skip)
15330 "Call FUNC at each headline selected by MATCH in SCOPE.
15332 FUNC is a function or a lisp form. The function will be called without
15333 arguments, with the cursor positioned at the beginning of the headline.
15334 The return values of all calls to the function will be collected and
15335 returned as a list.
15337 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15338 does not need to preserve point. After evaluation, the cursor will be
15339 moved to the end of the line (presumably of the headline of the
15340 processed entry) and search continues from there. Under some
15341 circumstances, this may not produce the wanted results. For example,
15342 if you have removed (e.g. archived) the current (sub)tree it could
15343 mean that the next entry will be skipped entirely. In such cases, you
15344 can specify the position from where search should continue by making
15345 FUNC set the variable `org-map-continue-from' to the desired buffer
15346 position.
15348 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15349 Only headlines that are matched by this query will be considered during
15350 the iteration. When MATCH is nil or t, all headlines will be
15351 visited by the iteration.
15353 SCOPE determines the scope of this command. It can be any of:
15355 nil The current buffer, respecting the restriction if any
15356 tree The subtree started with the entry at point
15357 region The entries within the active region, if any
15358 region-start-level
15359 The entries within the active region, but only those at
15360 the same level than the first one.
15361 file The current buffer, without restriction
15362 file-with-archives
15363 The current buffer, and any archives associated with it
15364 agenda All agenda files
15365 agenda-with-archives
15366 All agenda files with any archive files associated with them
15367 \(file1 file2 ...)
15368 If this is a list, all files in the list will be scanned
15370 The remaining args are treated as settings for the skipping facilities of
15371 the scanner. The following items can be given here:
15373 archive skip trees with the archive tag
15374 comment skip trees with the COMMENT keyword
15375 function or Emacs Lisp form:
15376 will be used as value for `org-agenda-skip-function', so
15377 whenever the function returns a position, FUNC will not be
15378 called for that entry and search will continue from the
15379 position returned
15381 If your function needs to retrieve the tags including inherited tags
15382 at the *current* entry, you can use the value of the variable
15383 `org-scanner-tags' which will be much faster than getting the value
15384 with `org-get-tags-at'. If your function gets properties with
15385 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15386 to t around the call to `org-entry-properties' to get the same speedup.
15387 Note that if your function moves around to retrieve tags and properties at
15388 a *different* entry, you cannot use these techniques."
15389 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15390 (not (org-region-active-p)))
15391 (let* ((org-agenda-archives-mode nil) ; just to make sure
15392 (org-agenda-skip-archived-trees (memq 'archive skip))
15393 (org-agenda-skip-comment-trees (memq 'comment skip))
15394 (org-agenda-skip-function
15395 (car (org-delete-all '(comment archive) skip)))
15396 (org-tags-match-list-sublevels t)
15397 (start-level (eq scope 'region-start-level))
15398 matcher res
15399 org-todo-keywords-for-agenda
15400 org-done-keywords-for-agenda
15401 org-todo-keyword-alist-for-agenda
15402 org-tag-alist-for-agenda
15403 org--matcher-tags-todo-only)
15405 (cond
15406 ((eq match t) (setq matcher t))
15407 ((eq match nil) (setq matcher t))
15408 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15410 (save-excursion
15411 (save-restriction
15412 (cond ((eq scope 'tree)
15413 (org-back-to-heading t)
15414 (org-narrow-to-subtree)
15415 (setq scope nil))
15416 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15417 (org-region-active-p))
15418 ;; If needed, set start-level to a string like "2"
15419 (when start-level
15420 (save-excursion
15421 (goto-char (region-beginning))
15422 (unless (org-at-heading-p) (outline-next-heading))
15423 (setq start-level (org-current-level))))
15424 (narrow-to-region (region-beginning)
15425 (save-excursion
15426 (goto-char (region-end))
15427 (unless (and (bolp) (org-at-heading-p))
15428 (outline-next-heading))
15429 (point)))
15430 (setq scope nil)))
15432 (if (not scope)
15433 (progn
15434 (org-agenda-prepare-buffers
15435 (and buffer-file-name (list buffer-file-name)))
15436 (setq res
15437 (org-scan-tags
15438 func matcher org--matcher-tags-todo-only start-level)))
15439 ;; Get the right scope
15440 (cond
15441 ((and scope (listp scope) (symbolp (car scope)))
15442 (setq scope (eval scope)))
15443 ((eq scope 'agenda)
15444 (setq scope (org-agenda-files t)))
15445 ((eq scope 'agenda-with-archives)
15446 (setq scope (org-agenda-files t))
15447 (setq scope (org-add-archive-files scope)))
15448 ((eq scope 'file)
15449 (setq scope (and buffer-file-name (list buffer-file-name))))
15450 ((eq scope 'file-with-archives)
15451 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15452 (org-agenda-prepare-buffers scope)
15453 (dolist (file scope)
15454 (with-current-buffer (org-find-base-buffer-visiting file)
15455 (org-with-wide-buffer
15456 (goto-char (point-min))
15457 (setq res
15458 (append
15460 (org-scan-tags
15461 func matcher org--matcher-tags-todo-only)))))))))
15462 res)))
15464 ;;; Properties API
15466 (defconst org-special-properties
15467 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15468 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15469 "The special properties valid in Org mode.
15470 These are properties that are not defined in the property drawer,
15471 but in some other way.")
15473 (defconst org-default-properties
15474 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15475 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15476 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15477 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15478 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15479 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15480 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15481 "Some properties that are used by Org mode for various purposes.
15482 Being in this list makes sure that they are offered for completion.")
15484 (defun org--valid-property-p (property)
15485 "Non nil when string PROPERTY is a valid property name."
15486 (not
15487 (or (equal property "")
15488 (string-match-p "\\s-" property))))
15490 (defun org--update-property-plist (key val props)
15491 "Associate KEY to VAL in alist PROPS.
15492 Modifications are made by side-effect. Return new alist."
15493 (let* ((appending (string= (substring key -1) "+"))
15494 (key (if appending (substring key 0 -1) key))
15495 (old (assoc-string key props t)))
15496 (if (not old) (cons (cons key val) props)
15497 (setcdr old (if appending (concat (cdr old) " " val) val))
15498 props)))
15500 (defun org-get-property-block (&optional beg force)
15501 "Return the (beg . end) range of the body of the property drawer.
15502 BEG is the beginning of the current subtree, or of the part
15503 before the first headline. If it is not given, it will be found.
15504 If the drawer does not exist, create it if FORCE is non-nil, or
15505 return nil."
15506 (org-with-wide-buffer
15507 (when beg (goto-char beg))
15508 (unless (org-before-first-heading-p)
15509 (let ((beg (cond (beg)
15510 ((or (not (featurep 'org-inlinetask))
15511 (org-inlinetask-in-task-p))
15512 (org-back-to-heading t))
15513 (t (org-with-limited-levels (org-back-to-heading t))))))
15514 (forward-line)
15515 (when (looking-at-p org-planning-line-re) (forward-line))
15516 (cond ((looking-at org-property-drawer-re)
15517 (forward-line)
15518 (cons (point) (progn (goto-char (match-end 0))
15519 (line-beginning-position))))
15520 (force
15521 (goto-char beg)
15522 (org-insert-property-drawer)
15523 (let ((pos (save-excursion (search-forward ":END:")
15524 (line-beginning-position))))
15525 (cons pos pos))))))))
15527 (defun org-at-property-p ()
15528 "Non-nil when point is inside a property drawer.
15529 See `org-property-re' for match data, if applicable."
15530 (save-excursion
15531 (beginning-of-line)
15532 (and (looking-at org-property-re)
15533 (let ((property-drawer (save-match-data (org-get-property-block))))
15534 (and property-drawer
15535 (>= (point) (car property-drawer))
15536 (< (point) (cdr property-drawer)))))))
15538 (defun org-property-action ()
15539 "Do an action on properties."
15540 (interactive)
15541 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15542 (let ((c (read-char-exclusive)))
15543 (cl-case c
15544 (?s (call-interactively #'org-set-property))
15545 (?d (call-interactively #'org-delete-property))
15546 (?D (call-interactively #'org-delete-property-globally))
15547 (?c (call-interactively #'org-compute-property-at-point))
15548 (otherwise (user-error "No such property action %c" c)))))
15550 (defun org-inc-effort ()
15551 "Increment the value of the effort property in the current entry."
15552 (interactive)
15553 (org-set-effort nil t))
15555 (defvar org-clock-effort) ; Defined in org-clock.el.
15556 (defvar org-clock-current-task) ; Defined in org-clock.el.
15557 (defun org-set-effort (&optional value increment)
15558 "Set the effort property of the current entry.
15559 With numerical prefix arg, use the nth allowed value, 0 stands for the
15560 10th allowed value.
15562 When INCREMENT is non-nil, set the property to the next allowed value."
15563 (interactive "P")
15564 (when (equal value 0) (setq value 10))
15565 (let* ((completion-ignore-case t)
15566 (prop org-effort-property)
15567 (cur (org-entry-get nil prop))
15568 (allowed (org-property-get-allowed-values nil prop 'table))
15569 (existing (mapcar 'list (org-property-values prop)))
15570 (heading (nth 4 (org-heading-components)))
15572 (val (cond
15573 ((stringp value) value)
15574 ((and allowed (integerp value))
15575 (or (car (nth (1- value) allowed))
15576 (car (org-last allowed))))
15577 ((and allowed increment)
15578 (or (cl-caadr (member (list cur) allowed))
15579 (user-error "Allowed effort values are not set")))
15580 (allowed
15581 (message "Select 1-9,0, [RET%s]: %s"
15582 (if cur (concat "=" cur) "")
15583 (mapconcat 'car allowed " "))
15584 (setq rpl (read-char-exclusive))
15585 (if (equal rpl ?\r)
15587 (setq rpl (- rpl ?0))
15588 (when (equal rpl 0) (setq rpl 10))
15589 (if (and (> rpl 0) (<= rpl (length allowed)))
15590 (car (nth (1- rpl) allowed))
15591 (org-completing-read "Effort: " allowed nil))))
15593 (org-completing-read
15594 (concat "Effort" (and cur (string-match "\\S-" cur)
15595 (concat " [" cur "]"))
15596 ": ")
15597 existing nil nil "" nil cur)))))
15598 (unless (equal (org-entry-get nil prop) val)
15599 (org-entry-put nil prop val))
15600 (org-refresh-property
15601 '((effort . identity)
15602 (effort-minutes . org-duration-to-minutes))
15603 val)
15604 (when (equal heading (bound-and-true-p org-clock-current-task))
15605 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15606 (org-clock-update-mode-line))
15607 (message "%s is now %s" prop val)))
15609 (defun org-entry-properties (&optional pom which)
15610 "Get all properties of the current entry.
15612 When POM is a buffer position, get all properties from the entry
15613 there instead.
15615 This includes the TODO keyword, the tags, time strings for
15616 deadline, scheduled, and clocking, and any additional properties
15617 defined in the entry.
15619 If WHICH is nil or `all', get all properties. If WHICH is
15620 `special' or `standard', only get that subclass. If WHICH is
15621 a string, only get that property.
15623 Return value is an alist. Keys are properties, as upcased
15624 strings."
15625 (org-with-point-at pom
15626 (when (and (derived-mode-p 'org-mode)
15627 (ignore-errors (org-back-to-heading t)))
15628 (catch 'exit
15629 (let* ((beg (point))
15630 (specific (and (stringp which) (upcase which)))
15631 (which (cond ((not specific) which)
15632 ((member specific org-special-properties) 'special)
15633 (t 'standard)))
15634 props)
15635 ;; Get the special properties, like TODO and TAGS.
15636 (when (memq which '(nil all special))
15637 (when (or (not specific) (string= specific "CLOCKSUM"))
15638 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15639 (when clocksum
15640 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15641 props)))
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15644 (let ((clocksumt (get-text-property (point)
15645 :org-clock-minutes-today)))
15646 (when clocksumt
15647 (push (cons "CLOCKSUM_T"
15648 (org-duration-from-minutes clocksumt))
15649 props)))
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "ITEM"))
15652 (let ((case-fold-search nil))
15653 (when (looking-at org-complex-heading-regexp)
15654 (push (cons "ITEM"
15655 (let ((title (match-string-no-properties 4)))
15656 (if (org-string-nw-p title)
15657 (org-remove-tabs title)
15658 "")))
15659 props)))
15660 (when specific (throw 'exit props)))
15661 (when (or (not specific) (string= specific "TODO"))
15662 (let ((case-fold-search nil))
15663 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15664 (push (cons "TODO" (match-string-no-properties 2)) props)))
15665 (when specific (throw 'exit props)))
15666 (when (or (not specific) (string= specific "PRIORITY"))
15667 (push (cons "PRIORITY"
15668 (if (looking-at org-priority-regexp)
15669 (match-string-no-properties 2)
15670 (char-to-string org-default-priority)))
15671 props)
15672 (when specific (throw 'exit props)))
15673 (when (or (not specific) (string= specific "FILE"))
15674 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15675 props)
15676 (when specific (throw 'exit props)))
15677 (when (or (not specific) (string= specific "TAGS"))
15678 (let ((value (org-string-nw-p (org-get-tags-string))))
15679 (when value (push (cons "TAGS" value) props)))
15680 (when specific (throw 'exit props)))
15681 (when (or (not specific) (string= specific "ALLTAGS"))
15682 (let ((value (org-get-tags-at)))
15683 (when value
15684 (push (cons "ALLTAGS"
15685 (format ":%s:" (mapconcat #'identity value ":")))
15686 props)))
15687 (when specific (throw 'exit props)))
15688 (when (or (not specific) (string= specific "BLOCKED"))
15689 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15690 (when specific (throw 'exit props)))
15691 (when (or (not specific)
15692 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15693 (forward-line)
15694 (when (looking-at-p org-planning-line-re)
15695 (end-of-line)
15696 (let ((bol (line-beginning-position))
15697 ;; Backward compatibility: time keywords used to
15698 ;; be configurable (before 8.3). Make sure we
15699 ;; get the correct keyword.
15700 (key-assoc `(("CLOSED" . ,org-closed-string)
15701 ("DEADLINE" . ,org-deadline-string)
15702 ("SCHEDULED" . ,org-scheduled-string))))
15703 (dolist (pair (if specific (list (assoc specific key-assoc))
15704 key-assoc))
15705 (save-excursion
15706 (when (search-backward (cdr pair) bol t)
15707 (goto-char (match-end 0))
15708 (skip-chars-forward " \t")
15709 (and (looking-at org-ts-regexp-both)
15710 (push (cons (car pair)
15711 (match-string-no-properties 0))
15712 props)))))))
15713 (when specific (throw 'exit props)))
15714 (when (or (not specific)
15715 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15716 (let ((find-ts
15717 (lambda (end ts)
15718 ;; Fix next time-stamp before END. TS is the
15719 ;; list of time-stamps found so far.
15720 (let ((ts ts)
15721 (regexp (cond
15722 ((string= specific "TIMESTAMP")
15723 org-ts-regexp)
15724 ((string= specific "TIMESTAMP_IA")
15725 org-ts-regexp-inactive)
15726 ((assoc "TIMESTAMP_IA" ts)
15727 org-ts-regexp)
15728 ((assoc "TIMESTAMP" ts)
15729 org-ts-regexp-inactive)
15730 (t org-ts-regexp-both))))
15731 (catch 'next
15732 (while (re-search-forward regexp end t)
15733 (backward-char)
15734 (let ((object (org-element-context)))
15735 ;; Accept to match timestamps in node
15736 ;; properties, too.
15737 (when (memq (org-element-type object)
15738 '(node-property timestamp))
15739 (let ((type
15740 (org-element-property :type object)))
15741 (cond
15742 ((and (memq type '(active active-range))
15743 (not (equal specific "TIMESTAMP_IA")))
15744 (unless (assoc "TIMESTAMP" ts)
15745 (push (cons "TIMESTAMP"
15746 (org-element-property
15747 :raw-value object))
15749 (when specific (throw 'exit ts))))
15750 ((and (memq type '(inactive inactive-range))
15751 (not (string= specific "TIMESTAMP")))
15752 (unless (assoc "TIMESTAMP_IA" ts)
15753 (push (cons "TIMESTAMP_IA"
15754 (org-element-property
15755 :raw-value object))
15757 (when specific (throw 'exit ts))))))
15758 ;; Both timestamp types are found,
15759 ;; move to next part.
15760 (when (= (length ts) 2) (throw 'next ts)))))
15761 ts)))))
15762 (goto-char beg)
15763 ;; First look for timestamps within headline.
15764 (let ((ts (funcall find-ts (line-end-position) nil)))
15765 (if (= (length ts) 2) (setq props (nconc ts props))
15766 ;; Then find timestamps in the section, skipping
15767 ;; planning line.
15768 (let ((end (save-excursion (outline-next-heading))))
15769 (forward-line)
15770 (when (looking-at-p org-planning-line-re) (forward-line))
15771 (setq props (nconc (funcall find-ts end ts) props))))))))
15772 ;; Get the standard properties, like :PROP:.
15773 (when (memq which '(nil all standard))
15774 ;; If we are looking after a specific property, delegate
15775 ;; to `org-entry-get', which is faster. However, make an
15776 ;; exception for "CATEGORY", since it can be also set
15777 ;; through keywords (i.e. #+CATEGORY).
15778 (if (and specific (not (equal specific "CATEGORY")))
15779 (let ((value (org-entry-get beg specific nil t)))
15780 (throw 'exit (and value (list (cons specific value)))))
15781 (let ((range (org-get-property-block beg)))
15782 (when range
15783 (let ((end (cdr range)) seen-base)
15784 (goto-char (car range))
15785 ;; Unlike to `org--update-property-plist', we
15786 ;; handle the case where base values is found
15787 ;; after its extension. We also forbid standard
15788 ;; properties to be named as special properties.
15789 (while (re-search-forward org-property-re end t)
15790 (let* ((key (upcase (match-string-no-properties 2)))
15791 (extendp (string-match-p "\\+\\'" key))
15792 (key-base (if extendp (substring key 0 -1) key))
15793 (value (match-string-no-properties 3)))
15794 (cond
15795 ((member-ignore-case key-base org-special-properties))
15796 (extendp
15797 (setq props
15798 (org--update-property-plist key value props)))
15799 ((member key seen-base))
15800 (t (push key seen-base)
15801 (let ((p (assoc-string key props t)))
15802 (if p (setcdr p (concat value " " (cdr p)))
15803 (push (cons key value) props))))))))))))
15804 (unless (assoc "CATEGORY" props)
15805 (push (cons "CATEGORY" (org-get-category beg)) props)
15806 (when (string= specific "CATEGORY") (throw 'exit props)))
15807 ;; Return value.
15808 props)))))
15810 (defun org--property-local-values (property literal-nil)
15811 "Return value for PROPERTY in current entry.
15812 Value is a list whose car is the base value for PROPERTY and cdr
15813 a list of accumulated values. Return nil if neither is found in
15814 the entry. Also return nil when PROPERTY is set to \"nil\",
15815 unless LITERAL-NIL is non-nil."
15816 (let ((range (org-get-property-block)))
15817 (when range
15818 (goto-char (car range))
15819 (let* ((case-fold-search t)
15820 (end (cdr range))
15821 (value
15822 ;; Base value.
15823 (save-excursion
15824 (let ((v (and (re-search-forward
15825 (org-re-property property nil t) end t)
15826 (match-string-no-properties 3))))
15827 (list (if literal-nil v (org-not-nil v)))))))
15828 ;; Find additional values.
15829 (let* ((property+ (org-re-property (concat property "+") nil t)))
15830 (while (re-search-forward property+ end t)
15831 (push (match-string-no-properties 3) value)))
15832 ;; Return final values.
15833 (and (not (equal value '(nil))) (nreverse value))))))
15835 (defun org--property-global-value (property literal-nil)
15836 "Return value for PROPERTY in current buffer.
15837 Return value is a string. Return nil if property is not set
15838 globally. Also return nil when PROPERTY is set to \"nil\",
15839 unless LITERAL-NIL is non-nil."
15840 (let ((global
15841 (cdr (or (assoc-string property org-file-properties t)
15842 (assoc-string property org-global-properties t)
15843 (assoc-string property org-global-properties-fixed t)))))
15844 (if literal-nil global (org-not-nil global))))
15846 (defun org-entry-get (pom property &optional inherit literal-nil)
15847 "Get value of PROPERTY for entry or content at point-or-marker POM.
15849 If INHERIT is non-nil and the entry does not have the property,
15850 then also check higher levels of the hierarchy. If INHERIT is
15851 the symbol `selective', use inheritance only if the setting in
15852 `org-use-property-inheritance' selects PROPERTY for inheritance.
15854 If the property is present but empty, the return value is the
15855 empty string. If the property is not present at all, nil is
15856 returned. In any other case, return the value as a string.
15857 Search is case-insensitive.
15859 If LITERAL-NIL is set, return the string value \"nil\" as
15860 a string, do not interpret it as the list atom nil. This is used
15861 for inheritance when a \"nil\" value can supersede a non-nil
15862 value higher up the hierarchy."
15863 (org-with-point-at pom
15864 (cond
15865 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15866 ;; We need a special property. Use `org-entry-properties' to
15867 ;; retrieve it, but specify the wanted property.
15868 (cdr (assoc-string property (org-entry-properties nil property))))
15869 ((and inherit
15870 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15871 (org-entry-get-with-inheritance property literal-nil))
15873 (let* ((local (org--property-local-values property literal-nil))
15874 (value (and local (mapconcat #'identity (delq nil local) " "))))
15875 (if literal-nil value (org-not-nil value)))))))
15877 (defun org-property-or-variable-value (var &optional inherit)
15878 "Check if there is a property fixing the value of VAR.
15879 If yes, return this value. If not, return the current value of the variable."
15880 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15881 (if (and prop (stringp prop) (string-match "\\S-" prop))
15882 (read prop)
15883 (symbol-value var))))
15885 (defun org-entry-delete (pom property)
15886 "Delete PROPERTY from entry at point-or-marker POM.
15887 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15888 non-nil when a property was removed."
15889 (org-with-point-at pom
15890 (pcase (org-get-property-block)
15891 (`(,begin . ,origin)
15892 (let* ((end (copy-marker origin))
15893 (re (org-re-property
15894 (concat (regexp-quote property) "\\+?") t t)))
15895 (goto-char begin)
15896 (while (re-search-forward re end t)
15897 (delete-region (match-beginning 0) (line-beginning-position 2)))
15898 ;; If drawer is empty, remove it altogether.
15899 (when (= begin end)
15900 (delete-region (line-beginning-position 0)
15901 (line-beginning-position 2)))
15902 ;; Return non-nil if some property was removed.
15903 (prog1 (/= end origin) (set-marker end nil))))
15904 (_ nil))))
15906 ;; Multi-values properties are properties that contain multiple values
15907 ;; These values are assumed to be single words, separated by whitespace.
15908 (defun org-entry-add-to-multivalued-property (pom property value)
15909 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15910 (let* ((old (org-entry-get pom property))
15911 (values (and old (org-split-string old "[ \t]"))))
15912 (setq value (org-entry-protect-space value))
15913 (unless (member value values)
15914 (setq values (append values (list value)))
15915 (org-entry-put pom property
15916 (mapconcat 'identity values " ")))))
15918 (defun org-entry-remove-from-multivalued-property (pom property value)
15919 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15920 (let* ((old (org-entry-get pom property))
15921 (values (and old (org-split-string old "[ \t]"))))
15922 (setq value (org-entry-protect-space value))
15923 (when (member value values)
15924 (setq values (delete value values))
15925 (org-entry-put pom property
15926 (mapconcat 'identity values " ")))))
15928 (defun org-entry-member-in-multivalued-property (pom property value)
15929 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15930 (let* ((old (org-entry-get pom property))
15931 (values (and old (org-split-string old "[ \t]"))))
15932 (setq value (org-entry-protect-space value))
15933 (member value values)))
15935 (defun org-entry-get-multivalued-property (pom property)
15936 "Return a list of values in a multivalued property."
15937 (let* ((value (org-entry-get pom property))
15938 (values (and value (org-split-string value "[ \t]"))))
15939 (mapcar 'org-entry-restore-space values)))
15941 (defun org-entry-put-multivalued-property (pom property &rest values)
15942 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15943 VALUES should be a list of strings. Spaces will be protected."
15944 (org-entry-put pom property
15945 (mapconcat 'org-entry-protect-space values " "))
15946 (let* ((value (org-entry-get pom property))
15947 (values (and value (org-split-string value "[ \t]"))))
15948 (mapcar 'org-entry-restore-space values)))
15950 (defun org-entry-protect-space (s)
15951 "Protect spaces and newline in string S."
15952 (while (string-match " " s)
15953 (setq s (replace-match "%20" t t s)))
15954 (while (string-match "\n" s)
15955 (setq s (replace-match "%0A" t t s)))
15958 (defun org-entry-restore-space (s)
15959 "Restore spaces and newline in string S."
15960 (while (string-match "%20" s)
15961 (setq s (replace-match " " t t s)))
15962 (while (string-match "%0A" s)
15963 (setq s (replace-match "\n" t t s)))
15966 (defvar org-entry-property-inherited-from (make-marker)
15967 "Marker pointing to the entry from where a property was inherited.
15968 Each call to `org-entry-get-with-inheritance' will set this marker to the
15969 location of the entry where the inheritance search matched. If there was
15970 no match, the marker will point nowhere.
15971 Note that also `org-entry-get' calls this function, if the INHERIT flag
15972 is set.")
15974 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15975 "Get PROPERTY of entry or content at point, search higher levels if needed.
15976 The search will stop at the first ancestor which has the property defined.
15977 If the value found is \"nil\", return nil to show that the property
15978 should be considered as undefined (this is the meaning of nil here).
15979 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15980 (move-marker org-entry-property-inherited-from nil)
15981 (org-with-wide-buffer
15982 (let (value)
15983 (catch 'exit
15984 (while t
15985 (let ((v (org--property-local-values property literal-nil)))
15986 (when v
15987 (setq value
15988 (concat (mapconcat #'identity (delq nil v) " ")
15989 (and value " ")
15990 value)))
15991 (cond
15992 ((car v)
15993 (org-back-to-heading t)
15994 (move-marker org-entry-property-inherited-from (point))
15995 (throw 'exit nil))
15996 ((org-up-heading-safe))
15998 (let ((global (org--property-global-value property literal-nil)))
15999 (cond ((not global))
16000 (value (setq value (concat global " " value)))
16001 (t (setq value global))))
16002 (throw 'exit nil))))))
16003 (if literal-nil value (org-not-nil value)))))
16005 (defvar org-property-changed-functions nil
16006 "Hook called when the value of a property has changed.
16007 Each hook function should accept two arguments, the name of the property
16008 and the new value.")
16010 (defun org-entry-put (pom property value)
16011 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16013 If the value is nil, it is converted to the empty string. If it
16014 is not a string, an error is raised. Also raise an error on
16015 invalid property names.
16017 PROPERTY can be any regular property (see
16018 `org-special-properties'). It can also be \"TODO\",
16019 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16021 For the last two properties, VALUE may have any of the special
16022 values \"earlier\" and \"later\". The function then increases or
16023 decreases scheduled or deadline date by one day."
16024 (cond ((null value) (setq value ""))
16025 ((not (stringp value)) (error "Properties values should be strings"))
16026 ((not (org--valid-property-p property))
16027 (user-error "Invalid property name: \"%s\"" property)))
16028 (org-with-point-at pom
16029 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16030 (org-back-to-heading t)
16031 (org-with-limited-levels (org-back-to-heading t)))
16032 (let ((beg (point)))
16033 (cond
16034 ((equal property "TODO")
16035 (cond ((not (org-string-nw-p value)) (setq value 'none))
16036 ((not (member value org-todo-keywords-1))
16037 (user-error "\"%s\" is not a valid TODO state" value)))
16038 (org-todo value)
16039 (org-set-tags nil 'align))
16040 ((equal property "PRIORITY")
16041 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16042 (org-set-tags nil 'align))
16043 ((equal property "SCHEDULED")
16044 (forward-line)
16045 (if (and (looking-at-p org-planning-line-re)
16046 (re-search-forward
16047 org-scheduled-time-regexp (line-end-position) t))
16048 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16049 ((string= value "later") (org-timestamp-change 1 'day))
16050 ((string= value "") (org-schedule '(4)))
16051 (t (org-schedule nil value)))
16052 (if (member value '("earlier" "later" ""))
16053 (call-interactively #'org-schedule)
16054 (org-schedule nil value))))
16055 ((equal property "DEADLINE")
16056 (forward-line)
16057 (if (and (looking-at-p org-planning-line-re)
16058 (re-search-forward
16059 org-deadline-time-regexp (line-end-position) t))
16060 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16061 ((string= value "later") (org-timestamp-change 1 'day))
16062 ((string= value "") (org-deadline '(4)))
16063 (t (org-deadline nil value)))
16064 (if (member value '("earlier" "later" ""))
16065 (call-interactively #'org-deadline)
16066 (org-deadline nil value))))
16067 ((member property org-special-properties)
16068 (error "The %s property cannot be set with `org-entry-put'" property))
16070 (let* ((range (org-get-property-block beg 'force))
16071 (end (cdr range))
16072 (case-fold-search t))
16073 (goto-char (car range))
16074 (if (re-search-forward (org-re-property property nil t) end t)
16075 (progn (delete-region (match-beginning 0) (match-end 0))
16076 (goto-char (match-beginning 0)))
16077 (goto-char end)
16078 (insert "\n")
16079 (backward-char))
16080 (insert ":" property ":")
16081 (when value (insert " " value))
16082 (org-indent-line)))))
16083 (run-hook-with-args 'org-property-changed-functions property value)))
16085 (defun org-buffer-property-keys
16086 (&optional specials defaults columns ignore-malformed)
16087 "Get all property keys in the current buffer.
16089 When SPECIALS is non-nil, also list the special properties that
16090 reflect things like tags and TODO state.
16092 When DEFAULTS is non-nil, also include properties that has
16093 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16094 DESCRIPTION, LOCATION, and LOGGING and others.
16096 When COLUMNS in non-nil, also include property names given in
16097 COLUMN formats in the current buffer.
16099 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16100 automatically performed, such drawers will be silently ignored."
16101 (let ((case-fold-search t)
16102 (props (append
16103 (and specials org-special-properties)
16104 (and defaults (cons org-effort-property org-default-properties))
16105 nil)))
16106 (org-with-wide-buffer
16107 (goto-char (point-min))
16108 (while (re-search-forward org-property-start-re nil t)
16109 (let ((range (org-get-property-block)))
16110 (catch 'skip
16111 (unless range
16112 (when (and (not ignore-malformed)
16113 (not (org-before-first-heading-p))
16114 (y-or-n-p (format "Malformed drawer at %d, repair?"
16115 (line-beginning-position))))
16116 (org-get-property-block nil t))
16117 (throw 'skip nil))
16118 (goto-char (car range))
16119 (let ((begin (car range))
16120 (end (cdr range)))
16121 ;; Make sure that found property block is not located
16122 ;; before current point, as it would generate an infloop.
16123 ;; It can happen, for example, in the following
16124 ;; situation:
16126 ;; * Headline
16127 ;; :PROPERTIES:
16128 ;; ...
16129 ;; :END:
16130 ;; *************** Inlinetask
16131 ;; #+BEGIN_EXAMPLE
16132 ;; :PROPERTIES:
16133 ;; #+END_EXAMPLE
16135 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16136 (while (< (point) end)
16137 (let ((p (progn (looking-at org-property-re)
16138 (match-string-no-properties 2))))
16139 ;; Only add true property name, not extension symbol.
16140 (push (if (not (string-match-p "\\+\\'" p)) p
16141 (substring p 0 -1))
16142 props))
16143 (forward-line))))
16144 (outline-next-heading)))
16145 (when columns
16146 (goto-char (point-min))
16147 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16148 (let ((element (org-element-at-point)))
16149 (when (memq (org-element-type element) '(keyword node-property))
16150 (let ((value (org-element-property :value element))
16151 (start 0))
16152 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16153 (setq start (match-end 0))
16154 (let ((p (match-string-no-properties 1 value)))
16155 (unless (member-ignore-case p org-special-properties)
16156 (push p props))))))))))
16157 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16159 (defun org-property-values (key)
16160 "List all non-nil values of property KEY in current buffer."
16161 (org-with-wide-buffer
16162 (goto-char (point-min))
16163 (let ((case-fold-search t)
16164 (re (org-re-property key))
16165 values)
16166 (while (re-search-forward re nil t)
16167 (push (org-entry-get (point) key) values))
16168 (delete-dups values))))
16170 (defun org-insert-property-drawer ()
16171 "Insert a property drawer into the current entry."
16172 (org-with-wide-buffer
16173 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16174 (org-back-to-heading t)
16175 (org-with-limited-levels (org-back-to-heading t)))
16176 (forward-line)
16177 (when (looking-at-p org-planning-line-re) (forward-line))
16178 (unless (looking-at-p org-property-drawer-re)
16179 ;; Make sure we start editing a line from current entry, not from
16180 ;; next one. It prevents extending text properties or overlays
16181 ;; belonging to the latter.
16182 (when (bolp) (backward-char))
16183 (let ((begin (1+ (point)))
16184 (inhibit-read-only t))
16185 (insert "\n:PROPERTIES:\n:END:")
16186 (when (eobp) (insert "\n"))
16187 (org-indent-region begin (point))))))
16189 (defun org-insert-drawer (&optional arg drawer)
16190 "Insert a drawer at point.
16192 When optional argument ARG is non-nil, insert a property drawer.
16194 Optional argument DRAWER, when non-nil, is a string representing
16195 drawer's name. Otherwise, the user is prompted for a name.
16197 If a region is active, insert the drawer around that region
16198 instead.
16200 Point is left between drawer's boundaries."
16201 (interactive "P")
16202 (let* ((drawer (if arg "PROPERTIES"
16203 (or drawer (read-from-minibuffer "Drawer: ")))))
16204 (cond
16205 ;; With C-u, fall back on `org-insert-property-drawer'
16206 (arg (org-insert-property-drawer))
16207 ;; Check validity of suggested drawer's name.
16208 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16209 (user-error "Invalid drawer name"))
16210 ;; With an active region, insert a drawer at point.
16211 ((not (org-region-active-p))
16212 (progn
16213 (unless (bolp) (insert "\n"))
16214 (insert (format ":%s:\n\n:END:\n" drawer))
16215 (forward-line -2)))
16216 ;; Otherwise, insert the drawer at point
16218 (let ((rbeg (region-beginning))
16219 (rend (copy-marker (region-end))))
16220 (unwind-protect
16221 (progn
16222 (goto-char rbeg)
16223 (beginning-of-line)
16224 (when (save-excursion
16225 (re-search-forward org-outline-regexp-bol rend t))
16226 (user-error "Drawers cannot contain headlines"))
16227 ;; Position point at the beginning of the first
16228 ;; non-blank line in region. Insert drawer's opening
16229 ;; there, then indent it.
16230 (org-skip-whitespace)
16231 (beginning-of-line)
16232 (insert ":" drawer ":\n")
16233 (forward-line -1)
16234 (indent-for-tab-command)
16235 ;; Move point to the beginning of the first blank line
16236 ;; after the last non-blank line in region. Insert
16237 ;; drawer's closing, then indent it.
16238 (goto-char rend)
16239 (skip-chars-backward " \r\t\n")
16240 (insert "\n:END:")
16241 (deactivate-mark t)
16242 (indent-for-tab-command)
16243 (unless (eolp) (insert "\n")))
16244 ;; Clear marker, whatever the outcome of insertion is.
16245 (set-marker rend nil)))))))
16247 (defvar org-property-set-functions-alist nil
16248 "Property set function alist.
16249 Each entry should have the following format:
16251 (PROPERTY . READ-FUNCTION)
16253 The read function will be called with the same argument as
16254 `org-completing-read'.")
16256 (defun org-set-property-function (property)
16257 "Get the function that should be used to set PROPERTY.
16258 This is computed according to `org-property-set-functions-alist'."
16259 (or (cdr (assoc property org-property-set-functions-alist))
16260 'org-completing-read))
16262 (defun org-read-property-value (property)
16263 "Read PROPERTY value from user."
16264 (let* ((completion-ignore-case t)
16265 (allowed (org-property-get-allowed-values nil property 'table))
16266 (cur (org-entry-get nil property))
16267 (prompt (concat property " value"
16268 (if (and cur (string-match "\\S-" cur))
16269 (concat " [" cur "]") "") ": "))
16270 (set-function (org-set-property-function property))
16271 (val (if allowed
16272 (funcall set-function prompt allowed nil
16273 (not (get-text-property 0 'org-unrestricted
16274 (caar allowed))))
16275 (funcall set-function prompt
16276 (mapcar 'list (org-property-values property))
16277 nil nil "" nil cur))))
16278 (org-trim val)))
16280 (defvar org-last-set-property nil)
16281 (defvar org-last-set-property-value nil)
16282 (defun org-read-property-name ()
16283 "Read a property name."
16284 (let ((completion-ignore-case t)
16285 (default-prop (or (and (org-at-property-p)
16286 (match-string-no-properties 2))
16287 org-last-set-property)))
16288 (org-completing-read
16289 (concat "Property"
16290 (if default-prop (concat " [" default-prop "]") "")
16291 ": ")
16292 (mapcar #'list (org-buffer-property-keys nil t t))
16293 nil nil nil nil default-prop)))
16295 (defun org-set-property-and-value (use-last)
16296 "Allow to set [PROPERTY]: [value] direction from prompt.
16297 When use-default, don't even ask, just use the last
16298 \"[PROPERTY]: [value]\" string from the history."
16299 (interactive "P")
16300 (let* ((completion-ignore-case t)
16301 (pv (or (and use-last org-last-set-property-value)
16302 (org-completing-read
16303 "Enter a \"[Property]: [value]\" pair: "
16304 nil nil nil nil nil
16305 org-last-set-property-value)))
16306 prop val)
16307 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16308 (setq prop (match-string 1 pv)
16309 val (match-string 2 pv))
16310 (org-set-property prop val))))
16312 (defun org-set-property (property value)
16313 "In the current entry, set PROPERTY to VALUE.
16315 When called interactively, this will prompt for a property name, offering
16316 completion on existing and default properties. And then it will prompt
16317 for a value, offering completion either on allowed values (via an inherited
16318 xxx_ALL property) or on existing values in other instances of this property
16319 in the current file.
16321 Throw an error when trying to set a property with an invalid name."
16322 (interactive (list nil nil))
16323 (let ((property (or property (org-read-property-name))))
16324 ;; `org-entry-put' also makes the following check, but this one
16325 ;; avoids polluting `org-last-set-property' and
16326 ;; `org-last-set-property-value' needlessly.
16327 (unless (org--valid-property-p property)
16328 (user-error "Invalid property name: \"%s\"" property))
16329 (let ((value (or value (org-read-property-value property)))
16330 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16331 (setq org-last-set-property property)
16332 (setq org-last-set-property-value (concat property ": " value))
16333 ;; Possibly postprocess the inserted value:
16334 (when fn (setq value (funcall fn value)))
16335 (unless (equal (org-entry-get nil property) value)
16336 (org-entry-put nil property value)))))
16338 (defun org-find-property (property &optional value)
16339 "Find first entry in buffer that sets PROPERTY.
16341 When optional argument VALUE is non-nil, only consider an entry
16342 if it contains PROPERTY set to this value. If PROPERTY should be
16343 explicitly set to nil, use string \"nil\" for VALUE.
16345 Return position where the entry begins, or nil if there is no
16346 such entry. If narrowing is in effect, only search the visible
16347 part of the buffer."
16348 (save-excursion
16349 (goto-char (point-min))
16350 (let ((case-fold-search t)
16351 (re (org-re-property property nil (not value) value)))
16352 (catch 'exit
16353 (while (re-search-forward re nil t)
16354 (when (if value (org-at-property-p)
16355 (org-entry-get (point) property nil t))
16356 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16358 (defun org-delete-property (property)
16359 "In the current entry, delete PROPERTY."
16360 (interactive
16361 (let* ((completion-ignore-case t)
16362 (cat (org-entry-get (point) "CATEGORY"))
16363 (props0 (org-entry-properties nil 'standard))
16364 (props (if cat props0
16365 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16366 (prop (if (< 1 (length props))
16367 (completing-read "Property: " props nil t)
16368 (caar props))))
16369 (list prop)))
16370 (if (not property)
16371 (message "No property to delete in this entry")
16372 (org-entry-delete nil property)
16373 (message "Property \"%s\" deleted" property)))
16375 (defun org-delete-property-globally (property)
16376 "Remove PROPERTY globally, from all entries.
16377 This function ignores narrowing, if any."
16378 (interactive
16379 (let* ((completion-ignore-case t)
16380 (prop (completing-read
16381 "Globally remove property: "
16382 (mapcar #'list (org-buffer-property-keys)))))
16383 (list prop)))
16384 (org-with-wide-buffer
16385 (goto-char (point-min))
16386 (let ((count 0)
16387 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16388 (while (re-search-forward re nil t)
16389 (when (org-entry-delete (point) property) (cl-incf count)))
16390 (message "Property \"%s\" removed from %d entries" property count))))
16392 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16394 (defun org-compute-property-at-point ()
16395 "Compute the property at point.
16396 This looks for an enclosing column format, extracts the operator and
16397 then applies it to the property in the column format's scope."
16398 (interactive)
16399 (unless (org-at-property-p)
16400 (user-error "Not at a property"))
16401 (let ((prop (match-string-no-properties 2)))
16402 (org-columns-get-format-and-top-level)
16403 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16404 (user-error "No operator defined for property %s" prop))
16405 (org-columns-compute prop)))
16407 (defvar org-property-allowed-value-functions nil
16408 "Hook for functions supplying allowed values for a specific property.
16409 The functions must take a single argument, the name of the property, and
16410 return a flat list of allowed values. If \":ETC\" is one of
16411 the values, this means that these values are intended as defaults for
16412 completion, but that other values should be allowed too.
16413 The functions must return nil if they are not responsible for this
16414 property.")
16416 (defun org-property-get-allowed-values (pom property &optional table)
16417 "Get allowed values for the property PROPERTY.
16418 When TABLE is non-nil, return an alist that can directly be used for
16419 completion."
16420 (let (vals)
16421 (cond
16422 ((equal property "TODO")
16423 (setq vals (org-with-point-at pom
16424 (append org-todo-keywords-1 '("")))))
16425 ((equal property "PRIORITY")
16426 (let ((n org-lowest-priority))
16427 (while (>= n org-highest-priority)
16428 (push (char-to-string n) vals)
16429 (setq n (1- n)))))
16430 ((equal property "CATEGORY"))
16431 ((member property org-special-properties))
16432 ((setq vals (run-hook-with-args-until-success
16433 'org-property-allowed-value-functions property)))
16435 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16436 (when (and vals (string-match "\\S-" vals))
16437 (setq vals (car (read-from-string (concat "(" vals ")"))))
16438 (setq vals (mapcar (lambda (x)
16439 (cond ((stringp x) x)
16440 ((numberp x) (number-to-string x))
16441 ((symbolp x) (symbol-name x))
16442 (t "???")))
16443 vals)))))
16444 (when (member ":ETC" vals)
16445 (setq vals (remove ":ETC" vals))
16446 (org-add-props (car vals) '(org-unrestricted t)))
16447 (if table (mapcar 'list vals) vals)))
16449 (defun org-property-previous-allowed-value (&optional _previous)
16450 "Switch to the next allowed value for this property."
16451 (interactive)
16452 (org-property-next-allowed-value t))
16454 (defun org-property-next-allowed-value (&optional previous)
16455 "Switch to the next allowed value for this property."
16456 (interactive)
16457 (unless (org-at-property-p)
16458 (user-error "Not at a property"))
16459 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16460 (key (match-string 2))
16461 (value (match-string 3))
16462 (allowed (or (org-property-get-allowed-values (point) key)
16463 (and (member value '("[ ]" "[-]" "[X]"))
16464 '("[ ]" "[X]"))))
16465 (heading (save-match-data (nth 4 (org-heading-components))))
16466 nval)
16467 (unless allowed
16468 (user-error "Allowed values for this property have not been defined"))
16469 (when previous (setq allowed (reverse allowed)))
16470 (when (member value allowed)
16471 (setq nval (car (cdr (member value allowed)))))
16472 (setq nval (or nval (car allowed)))
16473 (when (equal nval value)
16474 (user-error "Only one allowed value for this property"))
16475 (org-at-property-p)
16476 (replace-match (concat " :" key ": " nval) t t)
16477 (org-indent-line)
16478 (beginning-of-line 1)
16479 (skip-chars-forward " \t")
16480 (when (equal prop org-effort-property)
16481 (org-refresh-property
16482 '((effort . identity)
16483 (effort-minutes . org-duration-to-minutes))
16484 nval)
16485 (when (string= org-clock-current-task heading)
16486 (setq org-clock-effort nval)
16487 (org-clock-update-mode-line)))
16488 (run-hook-with-args 'org-property-changed-functions key nval)))
16490 (defun org-find-olp (path &optional this-buffer)
16491 "Return a marker pointing to the entry at outline path OLP.
16492 If anything goes wrong, throw an error.
16493 You can wrap this call to catch the error like this:
16495 (condition-case msg
16496 (org-mobile-locate-entry (match-string 4))
16497 (error (nth 1 msg)))
16499 The return value will then be either a string with the error message,
16500 or a marker if everything is OK.
16502 If THIS-BUFFER is set, the outline path does not contain a file,
16503 only headings."
16504 (let* ((file (if this-buffer buffer-file-name (pop path)))
16505 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16506 (level 1)
16507 (lmin 1)
16508 (lmax 1)
16509 end found flevel)
16510 (unless buffer (error "File not found :%s" file))
16511 (with-current-buffer buffer
16512 (unless (derived-mode-p 'org-mode)
16513 (error "Buffer %s needs to be in Org mode" buffer))
16514 (org-with-wide-buffer
16515 (goto-char (point-min))
16516 (dolist (heading path)
16517 (let ((re (format org-complex-heading-regexp-format
16518 (regexp-quote heading)))
16519 (cnt 0))
16520 (while (re-search-forward re end t)
16521 (setq level (- (match-end 1) (match-beginning 1)))
16522 (when (and (>= level lmin) (<= level lmax))
16523 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16524 (when (= cnt 0)
16525 (error "Heading not found on level %d: %s" lmax heading))
16526 (when (> cnt 1)
16527 (error "Heading not unique on level %d: %s" lmax heading))
16528 (goto-char found)
16529 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16530 (setq end (save-excursion (org-end-of-subtree t t)))))
16531 (when (org-at-heading-p)
16532 (point-marker))))))
16534 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16535 "Find node HEADING in BUFFER.
16536 Return a marker to the heading if it was found, or nil if not.
16537 If POS-ONLY is set, return just the position instead of a marker.
16539 The heading text must match exact, but it may have a TODO keyword,
16540 a priority cookie and tags in the standard locations."
16541 (with-current-buffer (or buffer (current-buffer))
16542 (org-with-wide-buffer
16543 (goto-char (point-min))
16544 (let (case-fold-search)
16545 (when (re-search-forward
16546 (format org-complex-heading-regexp-format
16547 (regexp-quote heading)) nil t)
16548 (if pos-only
16549 (match-beginning 0)
16550 (move-marker (make-marker) (match-beginning 0))))))))
16552 (defun org-find-exact-heading-in-directory (heading &optional dir)
16553 "Find Org node headline HEADING in all .org files in directory DIR.
16554 When the target headline is found, return a marker to this location."
16555 (let ((files (directory-files (or dir default-directory)
16556 t "\\`[^.#].*\\.org\\'"))
16557 visiting m buffer)
16558 (catch 'found
16559 (dolist (file files)
16560 (message "trying %s" file)
16561 (setq visiting (org-find-base-buffer-visiting file))
16562 (setq buffer (or visiting (find-file-noselect file)))
16563 (setq m (org-find-exact-headline-in-buffer
16564 heading buffer))
16565 (when (and (not m) (not visiting)) (kill-buffer buffer))
16566 (and m (throw 'found m))))))
16568 (defun org-find-entry-with-id (ident)
16569 "Locate the entry that contains the ID property with exact value IDENT.
16570 IDENT can be a string, a symbol or a number, this function will search for
16571 the string representation of it.
16572 Return the position where this entry starts, or nil if there is no such entry."
16573 (interactive "sID: ")
16574 (let ((id (cond
16575 ((stringp ident) ident)
16576 ((symbolp ident) (symbol-name ident))
16577 ((numberp ident) (number-to-string ident))
16578 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16579 (org-with-wide-buffer (org-find-property "ID" id))))
16581 ;;;; Timestamps
16583 (defvar org-last-changed-timestamp nil)
16584 (defvar org-last-inserted-timestamp nil
16585 "The last time stamp inserted with `org-insert-time-stamp'.")
16587 (defun org-time-stamp (arg &optional inactive)
16588 "Prompt for a date/time and insert a time stamp.
16590 If the user specifies a time like HH:MM or if this command is
16591 called with at least one prefix argument, the time stamp contains
16592 the date and the time. Otherwise, only the date is included.
16594 All parts of a date not specified by the user are filled in from
16595 the timestamp at point, if any, or the current date/time
16596 otherwise.
16598 If there is already a timestamp at the cursor, it is replaced.
16600 With two universal prefix arguments, insert an active timestamp
16601 with the current time without prompting the user.
16603 When called from lisp, the timestamp is inactive if INACTIVE is
16604 non-nil."
16605 (interactive "P")
16606 (let* ((ts (cond
16607 ((org-at-date-range-p t)
16608 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16609 ((org-at-timestamp-p t) (match-string 0))))
16610 ;; Default time is either the timestamp at point or today.
16611 ;; When entering a range, only the range start is considered.
16612 (default-time (if (not ts) (current-time)
16613 (apply #'encode-time (org-parse-time-string ts))))
16614 (default-input (and ts (org-get-compact-tod ts)))
16615 (repeater (and ts
16616 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16617 (match-string 0 ts)))
16618 org-time-was-given
16619 org-end-time-was-given
16620 (time
16621 (and (if (equal arg '(16)) (current-time)
16622 ;; Preserve `this-command' and `last-command'.
16623 (let ((this-command this-command)
16624 (last-command last-command))
16625 (org-read-date
16626 arg 'totime nil nil default-time default-input
16627 inactive))))))
16628 (cond
16629 ((and ts
16630 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16631 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16632 (insert "--")
16633 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16635 ;; Make sure we're on a timestamp. When in the middle of a date
16636 ;; range, move arbitrarily to range end.
16637 (unless (org-at-timestamp-p t)
16638 (skip-chars-forward "-")
16639 (org-at-timestamp-p t))
16640 (replace-match "")
16641 (setq org-last-changed-timestamp
16642 (org-insert-time-stamp
16643 time (or org-time-was-given arg)
16644 inactive nil nil (list org-end-time-was-given)))
16645 (when repeater
16646 (backward-char)
16647 (insert " " repeater)
16648 (setq org-last-changed-timestamp
16649 (concat (substring org-last-inserted-timestamp 0 -1)
16650 " " repeater ">")))
16651 (message "Timestamp updated"))
16652 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16653 (t (org-insert-time-stamp
16654 time (or org-time-was-given arg) inactive nil nil
16655 (list org-end-time-was-given))))))
16657 ;; FIXME: can we use this for something else, like computing time differences?
16658 (defun org-get-compact-tod (s)
16659 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16660 (let* ((t1 (match-string 1 s))
16661 (h1 (string-to-number (match-string 2 s)))
16662 (m1 (string-to-number (match-string 3 s)))
16663 (t2 (and (match-end 4) (match-string 5 s)))
16664 (h2 (and t2 (string-to-number (match-string 6 s))))
16665 (m2 (and t2 (string-to-number (match-string 7 s))))
16666 dh dm)
16667 (if (not t2)
16669 (setq dh (- h2 h1) dm (- m2 m1))
16670 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16671 (concat t1 "+" (number-to-string dh)
16672 (and (/= 0 dm) (format ":%02d" dm)))))))
16674 (defun org-time-stamp-inactive (&optional arg)
16675 "Insert an inactive time stamp.
16676 An inactive time stamp is enclosed in square brackets instead of angle
16677 brackets. It is inactive in the sense that it does not trigger agenda entries,
16678 does not link to the calendar and cannot be changed with the S-cursor keys.
16679 So these are more for recording a certain time/date."
16680 (interactive "P")
16681 (org-time-stamp arg 'inactive))
16683 (defvar org-date-ovl (make-overlay 1 1))
16684 (overlay-put org-date-ovl 'face 'org-date-selected)
16685 (delete-overlay org-date-ovl)
16687 (defvar org-ans1) ; dynamically scoped parameter
16688 (defvar org-ans2) ; dynamically scoped parameter
16690 (defvar org-plain-time-of-day-regexp) ; defined below
16692 (defvar org-overriding-default-time nil) ; dynamically scoped
16693 (defvar org-read-date-overlay nil)
16694 (defvar org-dcst nil) ; dynamically scoped
16695 (defvar org-read-date-history nil)
16696 (defvar org-read-date-final-answer nil)
16697 (defvar org-read-date-analyze-futurep nil)
16698 (defvar org-read-date-analyze-forced-year nil)
16699 (defvar org-read-date-inactive)
16701 (defvar org-read-date-minibuffer-local-map
16702 (let* ((map (make-sparse-keymap)))
16703 (set-keymap-parent map minibuffer-local-map)
16704 (org-defkey map (kbd ".")
16705 (lambda () (interactive)
16706 ;; Are we at the beginning of the prompt?
16707 (if (looking-back "^[^:]+: "
16708 (let ((inhibit-field-text-motion t))
16709 (line-beginning-position)))
16710 (org-eval-in-calendar '(calendar-goto-today))
16711 (insert "."))))
16712 (org-defkey map (kbd "C-.")
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-goto-today))))
16715 (org-defkey map [(meta shift left)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-month 1))))
16718 (org-defkey map [(meta shift right)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-month 1))))
16721 (org-defkey map [(meta shift up)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-year 1))))
16724 (org-defkey map [(meta shift down)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-year 1))))
16727 (org-defkey map [?\e (shift left)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-month 1))))
16730 (org-defkey map [?\e (shift right)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-month 1))))
16733 (org-defkey map [?\e (shift up)]
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-backward-year 1))))
16736 (org-defkey map [?\e (shift down)]
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(calendar-forward-year 1))))
16739 (org-defkey map [(shift up)]
16740 (lambda () (interactive)
16741 (org-eval-in-calendar '(calendar-backward-week 1))))
16742 (org-defkey map [(shift down)]
16743 (lambda () (interactive)
16744 (org-eval-in-calendar '(calendar-forward-week 1))))
16745 (org-defkey map [(shift left)]
16746 (lambda () (interactive)
16747 (org-eval-in-calendar '(calendar-backward-day 1))))
16748 (org-defkey map [(shift right)]
16749 (lambda () (interactive)
16750 (org-eval-in-calendar '(calendar-forward-day 1))))
16751 (org-defkey map "!"
16752 (lambda () (interactive)
16753 (org-eval-in-calendar '(diary-view-entries))
16754 (message "")))
16755 (org-defkey map ">"
16756 (lambda () (interactive)
16757 (org-eval-in-calendar '(calendar-scroll-left 1))))
16758 (org-defkey map "<"
16759 (lambda () (interactive)
16760 (org-eval-in-calendar '(calendar-scroll-right 1))))
16761 (org-defkey map "\C-v"
16762 (lambda () (interactive)
16763 (org-eval-in-calendar
16764 '(calendar-scroll-left-three-months 1))))
16765 (org-defkey map "\M-v"
16766 (lambda () (interactive)
16767 (org-eval-in-calendar
16768 '(calendar-scroll-right-three-months 1))))
16769 map)
16770 "Keymap for minibuffer commands when using `org-read-date'.")
16772 (defvar org-def)
16773 (defvar org-defdecode)
16774 (defvar org-with-time)
16776 (defvar calendar-setup) ; Dynamically scoped.
16777 (defun org-read-date (&optional with-time to-time from-string prompt
16778 default-time default-input inactive)
16779 "Read a date, possibly a time, and make things smooth for the user.
16780 The prompt will suggest to enter an ISO date, but you can also enter anything
16781 which will at least partially be understood by `parse-time-string'.
16782 Unrecognized parts of the date will default to the current day, month, year,
16783 hour and minute. If this command is called to replace a timestamp at point,
16784 or to enter the second timestamp of a range, the default time is taken
16785 from the existing stamp. Furthermore, the command prefers the future,
16786 so if you are giving a date where the year is not given, and the day-month
16787 combination is already past in the current year, it will assume you
16788 mean next year. For details, see the manual. A few examples:
16790 3-2-5 --> 2003-02-05
16791 feb 15 --> currentyear-02-15
16792 2/15 --> currentyear-02-15
16793 sep 12 9 --> 2009-09-12
16794 12:45 --> today 12:45
16795 22 sept 0:34 --> currentyear-09-22 0:34
16796 12 --> currentyear-currentmonth-12
16797 Fri --> nearest Friday after today
16798 -Tue --> last Tuesday
16799 etc.
16801 Furthermore you can specify a relative date by giving, as the *first* thing
16802 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16803 change in days weeks, months, years.
16804 With a single plus or minus, the date is relative to today. With a double
16805 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16806 +4d --> four days from today
16807 +4 --> same as above
16808 +2w --> two weeks from today
16809 ++5 --> five days from default date
16811 The function understands only English month and weekday abbreviations.
16813 While prompting, a calendar is popped up - you can also select the
16814 date with the mouse (button 1). The calendar shows a period of three
16815 months. To scroll it to other months, use the keys `>' and `<'.
16816 If you don't like the calendar, turn it off with
16817 (setq org-read-date-popup-calendar nil)
16819 With optional argument TO-TIME, the date will immediately be converted
16820 to an internal time.
16821 With an optional argument WITH-TIME, the prompt will suggest to
16822 also insert a time. Note that when WITH-TIME is not set, you can
16823 still enter a time, and this function will inform the calling routine
16824 about this change. The calling routine may then choose to change the
16825 format used to insert the time stamp into the buffer to include the time.
16826 With optional argument FROM-STRING, read from this string instead from
16827 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16828 the time/date that is used for everything that is not specified by the
16829 user."
16830 (require 'parse-time)
16831 (let* ((org-with-time with-time)
16832 (org-time-stamp-rounding-minutes
16833 (if (equal org-with-time '(16))
16834 '(0 0)
16835 org-time-stamp-rounding-minutes))
16836 (org-dcst org-display-custom-times)
16837 (ct (org-current-time))
16838 (org-def (or org-overriding-default-time default-time ct))
16839 (org-defdecode (decode-time org-def))
16840 (cur-frame (selected-frame))
16841 (mouse-autoselect-window nil) ; Don't let the mouse jump
16842 (calendar-setup
16843 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16844 (calendar-move-hook nil)
16845 (calendar-view-diary-initially-flag nil)
16846 (calendar-view-holidays-initially-flag nil)
16847 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16848 ;; Rationalize `org-def' and `org-defdecode', if required.
16849 (when (< (nth 2 org-defdecode) org-extend-today-until)
16850 (setf (nth 2 org-defdecode) -1)
16851 (setf (nth 1 org-defdecode) 59)
16852 (setq org-def (apply #'encode-time org-defdecode))
16853 (setq org-defdecode (decode-time org-def)))
16854 (let* ((timestr (format-time-string
16855 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16856 org-def))
16857 (prompt (concat (if prompt (concat prompt " ") "")
16858 (format "Date+time [%s]: " timestr))))
16859 (cond
16860 (from-string (setq ans from-string))
16861 (org-read-date-popup-calendar
16862 (save-excursion
16863 (save-window-excursion
16864 (calendar)
16865 (when (eq calendar-setup 'calendar-only)
16866 (setq cal-frame
16867 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16868 (select-frame cal-frame))
16869 (org-eval-in-calendar '(setq cursor-type nil) t)
16870 (unwind-protect
16871 (progn
16872 (calendar-forward-day (- (time-to-days org-def)
16873 (calendar-absolute-from-gregorian
16874 (calendar-current-date))))
16875 (org-eval-in-calendar nil t)
16876 (let* ((old-map (current-local-map))
16877 (map (copy-keymap calendar-mode-map))
16878 (minibuffer-local-map
16879 (copy-keymap org-read-date-minibuffer-local-map)))
16880 (org-defkey map (kbd "RET") 'org-calendar-select)
16881 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16882 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16883 (unwind-protect
16884 (progn
16885 (use-local-map map)
16886 (setq org-read-date-inactive inactive)
16887 (add-hook 'post-command-hook 'org-read-date-display)
16888 (setq org-ans0
16889 (read-string prompt
16890 default-input
16891 'org-read-date-history
16892 nil))
16893 ;; org-ans0: from prompt
16894 ;; org-ans1: from mouse click
16895 ;; org-ans2: from calendar motion
16896 (setq ans
16897 (concat org-ans0 " " (or org-ans1 org-ans2))))
16898 (remove-hook 'post-command-hook 'org-read-date-display)
16899 (use-local-map old-map)
16900 (when org-read-date-overlay
16901 (delete-overlay org-read-date-overlay)
16902 (setq org-read-date-overlay nil)))))
16903 (bury-buffer "*Calendar*")
16904 (when cal-frame
16905 (delete-frame cal-frame)
16906 (select-frame-set-input-focus cur-frame))))))
16908 (t ; Naked prompt only
16909 (unwind-protect
16910 (setq ans (read-string prompt default-input
16911 'org-read-date-history timestr))
16912 (when org-read-date-overlay
16913 (delete-overlay org-read-date-overlay)
16914 (setq org-read-date-overlay nil))))))
16916 (setq final (org-read-date-analyze ans org-def org-defdecode))
16918 (when org-read-date-analyze-forced-year
16919 (message "Year was forced into %s"
16920 (if org-read-date-force-compatible-dates
16921 "compatible range (1970-2037)"
16922 "range representable on this machine"))
16923 (ding))
16925 ;; One round trip to get rid of 34th of August and stuff like that....
16926 (setq final (decode-time (apply 'encode-time final)))
16928 (setq org-read-date-final-answer ans)
16930 (if to-time
16931 (apply 'encode-time final)
16932 (if (and (boundp 'org-time-was-given) org-time-was-given)
16933 (format "%04d-%02d-%02d %02d:%02d"
16934 (nth 5 final) (nth 4 final) (nth 3 final)
16935 (nth 2 final) (nth 1 final))
16936 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16938 (defun org-read-date-display ()
16939 "Display the current date prompt interpretation in the minibuffer."
16940 (when org-read-date-display-live
16941 (when org-read-date-overlay
16942 (delete-overlay org-read-date-overlay))
16943 (when (minibufferp (current-buffer))
16944 (save-excursion
16945 (end-of-line 1)
16946 (while (not (equal (buffer-substring
16947 (max (point-min) (- (point) 4)) (point))
16948 " "))
16949 (insert " ")))
16950 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16951 " " (or org-ans1 org-ans2)))
16952 (org-end-time-was-given nil)
16953 (f (org-read-date-analyze ans org-def org-defdecode))
16954 (fmts (if org-dcst
16955 org-time-stamp-custom-formats
16956 org-time-stamp-formats))
16957 (fmt (if (or org-with-time
16958 (and (boundp 'org-time-was-given) org-time-was-given))
16959 (cdr fmts)
16960 (car fmts)))
16961 (txt (format-time-string fmt (apply 'encode-time f)))
16962 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16963 (txt (concat "=> " txt)))
16964 (when (and org-end-time-was-given
16965 (string-match org-plain-time-of-day-regexp txt))
16966 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16967 org-end-time-was-given
16968 (substring txt (match-end 0)))))
16969 (when org-read-date-analyze-futurep
16970 (setq txt (concat txt " (=>F)")))
16971 (setq org-read-date-overlay
16972 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16973 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16975 (defun org-read-date-analyze (ans def defdecode)
16976 "Analyze the combined answer of the date prompt."
16977 ;; FIXME: cleanup and comment
16978 ;; Pass `current-time' result to `decode-time' (instead of calling
16979 ;; without arguments) so that only `current-time' has to be
16980 ;; overriden in tests.
16981 (let ((org-def def)
16982 (org-defdecode defdecode)
16983 (nowdecode (decode-time (current-time)))
16984 delta deltan deltaw deltadef year month day
16985 hour minute second wday pm h2 m2 tl wday1
16986 iso-year iso-weekday iso-week iso-date futurep kill-year)
16987 (setq org-read-date-analyze-futurep nil
16988 org-read-date-analyze-forced-year nil)
16989 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16990 (setq ans "+0"))
16992 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16993 (setq ans (replace-match "" t t ans)
16994 deltan (car delta)
16995 deltaw (nth 1 delta)
16996 deltadef (nth 2 delta)))
16998 ;; Check if there is an iso week date in there. If yes, store the
16999 ;; info and postpone interpreting it until the rest of the parsing
17000 ;; is done.
17001 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17002 (setq iso-year (when (match-end 1)
17003 (org-small-year-to-year
17004 (string-to-number (match-string 1 ans))))
17005 iso-weekday (when (match-end 3)
17006 (string-to-number (match-string 3 ans)))
17007 iso-week (string-to-number (match-string 2 ans)))
17008 (setq ans (replace-match "" t t ans)))
17010 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17011 (when (string-match
17012 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17013 (setq year (if (match-end 2)
17014 (string-to-number (match-string 2 ans))
17015 (progn (setq kill-year t)
17016 (string-to-number (format-time-string "%Y"))))
17017 month (string-to-number (match-string 3 ans))
17018 day (string-to-number (match-string 4 ans)))
17019 (setq year (org-small-year-to-year year))
17020 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17021 t nil ans)))
17023 ;; Help matching dotted european dates
17024 (when (string-match
17025 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17026 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17027 (setq kill-year t)
17028 (string-to-number (format-time-string "%Y")))
17029 day (string-to-number (match-string 1 ans))
17030 month (string-to-number (match-string 2 ans))
17031 ans (replace-match (format "%04d-%02d-%02d" year month day)
17032 t nil ans)))
17034 ;; Help matching american dates, like 5/30 or 5/30/7
17035 (when (string-match
17036 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17037 (setq year (if (match-end 4)
17038 (string-to-number (match-string 4 ans))
17039 (progn (setq kill-year t)
17040 (string-to-number (format-time-string "%Y"))))
17041 month (string-to-number (match-string 1 ans))
17042 day (string-to-number (match-string 2 ans)))
17043 (setq year (org-small-year-to-year year))
17044 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17045 t nil ans)))
17046 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17047 ;; If there is a time with am/pm, and *no* time without it, we convert
17048 ;; so that matching will be successful.
17049 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17050 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17051 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17052 (setq hour (string-to-number (match-string 1 ans))
17053 minute (if (match-end 3)
17054 (string-to-number (match-string 3 ans))
17056 pm (equal ?p
17057 (string-to-char (downcase (match-string 4 ans)))))
17058 (if (and (= hour 12) (not pm))
17059 (setq hour 0)
17060 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17061 (setq ans (replace-match (format "%02d:%02d" hour minute)
17062 t t ans))))
17064 ;; Check if a time range is given as a duration
17065 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17066 (setq hour (string-to-number (match-string 1 ans))
17067 h2 (+ hour (string-to-number (match-string 3 ans)))
17068 minute (string-to-number (match-string 2 ans))
17069 m2 (+ minute (if (match-end 5) (string-to-number
17070 (match-string 5 ans))0)))
17071 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17072 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17073 t t ans)))
17075 ;; Check if there is a time range
17076 (when (boundp 'org-end-time-was-given)
17077 (setq org-time-was-given nil)
17078 (when (and (string-match org-plain-time-of-day-regexp ans)
17079 (match-end 8))
17080 (setq org-end-time-was-given (match-string 8 ans))
17081 (setq ans (concat (substring ans 0 (match-beginning 7))
17082 (substring ans (match-end 7))))))
17084 (setq tl (parse-time-string ans)
17085 day (or (nth 3 tl) (nth 3 org-defdecode))
17086 month
17087 (cond ((nth 4 tl))
17088 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17089 ;; Day was specified. Make sure DAY+MONTH
17090 ;; combination happens in the future.
17091 ((nth 3 tl)
17092 (setq futurep t)
17093 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17094 (nth 4 nowdecode)))
17095 (t (nth 4 org-defdecode)))
17096 year
17097 (cond ((and (not kill-year) (nth 5 tl)))
17098 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17099 ;; Month was guessed in the future and is at least
17100 ;; equal to NOWDECODE's. Fix year accordingly.
17101 (futurep
17102 (if (or (> month (nth 4 nowdecode))
17103 (>= day (nth 3 nowdecode)))
17104 (nth 5 nowdecode)
17105 (1+ (nth 5 nowdecode))))
17106 ;; Month was specified. Make sure MONTH+YEAR
17107 ;; combination happens in the future.
17108 ((nth 4 tl)
17109 (setq futurep t)
17110 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17111 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17112 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17113 (t (nth 5 nowdecode))))
17114 (t (nth 5 org-defdecode)))
17115 hour (or (nth 2 tl) (nth 2 org-defdecode))
17116 minute (or (nth 1 tl) (nth 1 org-defdecode))
17117 second (or (nth 0 tl) 0)
17118 wday (nth 6 tl))
17120 (when (and (eq org-read-date-prefer-future 'time)
17121 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17122 (equal day (nth 3 nowdecode))
17123 (equal month (nth 4 nowdecode))
17124 (equal year (nth 5 nowdecode))
17125 (nth 2 tl)
17126 (or (< (nth 2 tl) (nth 2 nowdecode))
17127 (and (= (nth 2 tl) (nth 2 nowdecode))
17128 (nth 1 tl)
17129 (< (nth 1 tl) (nth 1 nowdecode)))))
17130 (setq day (1+ day)
17131 futurep t))
17133 ;; Special date definitions below
17134 (cond
17135 (iso-week
17136 ;; There was an iso week
17137 (require 'cal-iso)
17138 (setq futurep nil)
17139 (setq year (or iso-year year)
17140 day (or iso-weekday wday 1)
17141 wday nil ; to make sure that the trigger below does not match
17142 iso-date (calendar-gregorian-from-absolute
17143 (calendar-iso-to-absolute
17144 (list iso-week day year))))
17145 ; FIXME: Should we also push ISO weeks into the future?
17146 ; (when (and org-read-date-prefer-future
17147 ; (not iso-year)
17148 ; (< (calendar-absolute-from-gregorian iso-date)
17149 ; (time-to-days (current-time))))
17150 ; (setq year (1+ year)
17151 ; iso-date (calendar-gregorian-from-absolute
17152 ; (calendar-iso-to-absolute
17153 ; (list iso-week day year)))))
17154 (setq month (car iso-date)
17155 year (nth 2 iso-date)
17156 day (nth 1 iso-date)))
17157 (deltan
17158 (setq futurep nil)
17159 (unless deltadef
17160 ;; Pass `current-time' result to `decode-time' (instead of
17161 ;; calling without arguments) so that only `current-time' has
17162 ;; to be overriden in tests.
17163 (let ((now (decode-time (current-time))))
17164 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17165 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17166 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17167 ((equal deltaw "m") (setq month (+ month deltan)))
17168 ((equal deltaw "y") (setq year (+ year deltan)))))
17169 ((and wday (not (nth 3 tl)))
17170 ;; Weekday was given, but no day, so pick that day in the week
17171 ;; on or after the derived date.
17172 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17173 (unless (equal wday wday1)
17174 (setq day (+ day (% (- wday wday1 -7) 7))))))
17175 (when (and (boundp 'org-time-was-given)
17176 (nth 2 tl))
17177 (setq org-time-was-given t))
17178 (when (< year 100) (setq year (+ 2000 year)))
17179 ;; Check of the date is representable
17180 (if org-read-date-force-compatible-dates
17181 (progn
17182 (when (< year 1970)
17183 (setq year 1970 org-read-date-analyze-forced-year t))
17184 (when (> year 2037)
17185 (setq year 2037 org-read-date-analyze-forced-year t)))
17186 (condition-case nil
17187 (ignore (encode-time second minute hour day month year))
17188 (error
17189 (setq year (nth 5 org-defdecode))
17190 (setq org-read-date-analyze-forced-year t))))
17191 (setq org-read-date-analyze-futurep futurep)
17192 (list second minute hour day month year)))
17194 (defvar parse-time-weekdays)
17195 (defun org-read-date-get-relative (s today default)
17196 "Check string S for special relative date string.
17197 TODAY and DEFAULT are internal times, for today and for a default.
17198 Return shift list (N what def-flag)
17199 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17200 N is the number of WHATs to shift.
17201 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17202 the DEFAULT date rather than TODAY."
17203 (require 'parse-time)
17204 (when (and
17205 (string-match
17206 (concat
17207 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17208 "\\([0-9]+\\)?"
17209 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17210 "\\([ \t]\\|$\\)") s)
17211 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17212 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17213 (string-to-char (substring (match-string 1 s) -1))
17214 ?+))
17215 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17216 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17217 (what (if (match-end 3) (match-string 3 s) "d"))
17218 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17219 (date (if rel default today))
17220 (wday (nth 6 (decode-time date)))
17221 delta)
17222 (if wday1
17223 (progn
17224 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17225 (when (= delta 0) (setq delta 7))
17226 (when (= dir ?-)
17227 (setq delta (- delta 7))
17228 (when (= delta 0) (setq delta -7)))
17229 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17230 (list delta "d" rel))
17231 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17233 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17234 "Turn a user-specified date into the internal representation.
17235 The internal representation needed by the calendar is (month day year).
17236 This is a wrapper to handle the brain-dead convention in calendar that
17237 user function argument order change dependent on argument order."
17238 (pcase calendar-date-style
17239 (`american (list arg1 arg2 arg3))
17240 (`european (list arg2 arg1 arg3))
17241 (`iso (list arg2 arg3 arg1))))
17243 (defun org-eval-in-calendar (form &optional keepdate)
17244 "Eval FORM in the calendar window and return to current window.
17245 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17246 (let ((sf (selected-frame))
17247 (sw (selected-window)))
17248 (select-window (get-buffer-window "*Calendar*" t))
17249 (eval form)
17250 (when (and (not keepdate) (calendar-cursor-to-date))
17251 (let* ((date (calendar-cursor-to-date))
17252 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17253 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17254 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17255 (select-window sw)
17256 (select-frame-set-input-focus sf)))
17258 (defun org-calendar-select ()
17259 "Return to `org-read-date' with the date currently selected.
17260 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17261 (interactive)
17262 (when (calendar-cursor-to-date)
17263 (let* ((date (calendar-cursor-to-date))
17264 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17265 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17266 (when (active-minibuffer-window) (exit-minibuffer))))
17268 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17269 "Insert a date stamp for the date given by the internal TIME.
17270 See `format-time-string' for the format of TIME.
17271 WITH-HM means use the stamp format that includes the time of the day.
17272 INACTIVE means use square brackets instead of angular ones, so that the
17273 stamp will not contribute to the agenda.
17274 PRE and POST are optional strings to be inserted before and after the
17275 stamp.
17276 The command returns the inserted time stamp."
17277 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17278 stamp)
17279 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17280 (insert-before-markers (or pre ""))
17281 (when (listp extra)
17282 (setq extra (car extra))
17283 (if (and (stringp extra)
17284 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17285 (setq extra (format "-%02d:%02d"
17286 (string-to-number (match-string 1 extra))
17287 (string-to-number (match-string 2 extra))))
17288 (setq extra nil)))
17289 (when extra
17290 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17291 (insert-before-markers (setq stamp (format-time-string fmt time)))
17292 (insert-before-markers (or post ""))
17293 (setq org-last-inserted-timestamp stamp)))
17295 (defun org-toggle-time-stamp-overlays ()
17296 "Toggle the use of custom time stamp formats."
17297 (interactive)
17298 (setq org-display-custom-times (not org-display-custom-times))
17299 (unless org-display-custom-times
17300 (let ((p (point-min)) (bmp (buffer-modified-p)))
17301 (while (setq p (next-single-property-change p 'display))
17302 (when (and (get-text-property p 'display)
17303 (eq (get-text-property p 'face) 'org-date))
17304 (remove-text-properties
17305 p (setq p (next-single-property-change p 'display))
17306 '(display t))))
17307 (set-buffer-modified-p bmp)))
17308 (org-restart-font-lock)
17309 (setq org-table-may-need-update t)
17310 (if org-display-custom-times
17311 (message "Time stamps are overlaid with custom format")
17312 (message "Time stamp overlays removed")))
17314 (defun org-display-custom-time (beg end)
17315 "Overlay modified time stamp format over timestamp between BEG and END."
17316 (let* ((ts (buffer-substring beg end))
17317 t1 w1 with-hm tf time str w2 (off 0))
17318 (save-match-data
17319 (setq t1 (org-parse-time-string ts t))
17320 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17321 (setq off (- (match-end 0) (match-beginning 0)))))
17322 (setq end (- end off))
17323 (setq w1 (- end beg)
17324 with-hm (and (nth 1 t1) (nth 2 t1))
17325 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17326 time (org-fix-decoded-time t1)
17327 str (org-add-props
17328 (format-time-string
17329 (substring tf 1 -1) (apply 'encode-time time))
17330 nil 'mouse-face 'highlight)
17331 w2 (length str))
17332 (unless (= w2 w1)
17333 (add-text-properties (1+ beg) (+ 2 beg)
17334 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17335 (put-text-property beg end 'display str)))
17337 (defun org-fix-decoded-time (time)
17338 "Set 0 instead of nil for the first 6 elements of time.
17339 Don't touch the rest."
17340 (let ((n 0))
17341 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17343 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17344 "Difference between TIMESTAMP-STRING and now in days.
17345 If SECONDS is non-nil, return the difference in seconds."
17346 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17347 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17348 (funcall fdiff (current-time)))))
17350 (defun org-deadline-close-p (timestamp-string &optional ndays)
17351 "Is the time in TIMESTAMP-STRING close to the current date?"
17352 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17353 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17354 (not (org-entry-is-done-p))))
17356 (defun org-get-wdays (ts &optional delay zero-delay)
17357 "Get the deadline lead time appropriate for timestring TS.
17358 When DELAY is non-nil, get the delay time for scheduled items
17359 instead of the deadline lead time. When ZERO-DELAY is non-nil
17360 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17361 don't try to find the delay cookie in the scheduled timestamp."
17362 (let ((tv (if delay org-scheduled-delay-days
17363 org-deadline-warning-days)))
17364 (cond
17365 ((or (and delay (< tv 0))
17366 (and delay zero-delay (<= tv 0))
17367 (and (not delay) (<= tv 0)))
17368 ;; Enforce this value no matter what
17369 (- tv))
17370 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17371 ;; lead time is specified.
17372 (floor (* (string-to-number (match-string 1 ts))
17373 (cdr (assoc (match-string 2 ts)
17374 '(("d" . 1) ("w" . 7)
17375 ("m" . 30.4) ("y" . 365.25)
17376 ("h" . 0.041667)))))))
17377 ;; go for the default.
17378 (t tv))))
17380 (defun org-calendar-select-mouse (ev)
17381 "Return to `org-read-date' with the date currently selected.
17382 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17383 (interactive "e")
17384 (mouse-set-point ev)
17385 (when (calendar-cursor-to-date)
17386 (let* ((date (calendar-cursor-to-date))
17387 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17388 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17389 (when (active-minibuffer-window) (exit-minibuffer))))
17391 (defun org-check-deadlines (ndays)
17392 "Check if there are any deadlines due or past due.
17393 A deadline is considered due if it happens within `org-deadline-warning-days'
17394 days from today's date. If the deadline appears in an entry marked DONE,
17395 it is not shown. A numeric prefix argument NDAYS can be used to test that
17396 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17397 are shown."
17398 (interactive "P")
17399 (let* ((org-warn-days
17400 (cond
17401 ((equal ndays '(4)) 100000)
17402 (ndays (prefix-numeric-value ndays))
17403 (t (abs org-deadline-warning-days))))
17404 (case-fold-search nil)
17405 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17406 (callback
17407 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17408 (message "%d deadlines past-due or due within %d days"
17409 (org-occur regexp nil callback)
17410 org-warn-days)))
17412 (defsubst org-re-timestamp (type)
17413 "Return a regexp for timestamp TYPE.
17414 Allowed values for TYPE are:
17416 all: all timestamps
17417 active: only active timestamps (<...>)
17418 inactive: only inactive timestamps ([...])
17419 scheduled: only scheduled timestamps
17420 deadline: only deadline timestamps
17421 closed: only closed time-stamps
17423 When TYPE is nil, fall back on returning a regexp that matches
17424 both scheduled and deadline timestamps."
17425 (cl-case type
17426 (all org-ts-regexp-both)
17427 (active org-ts-regexp)
17428 (inactive org-ts-regexp-inactive)
17429 (scheduled org-scheduled-time-regexp)
17430 (deadline org-deadline-time-regexp)
17431 (closed org-closed-time-regexp)
17432 (otherwise
17433 (concat "\\<"
17434 (regexp-opt (list org-deadline-string org-scheduled-string))
17435 " *<\\([^>]+\\)>"))))
17437 (defun org-check-before-date (d)
17438 "Check if there are deadlines or scheduled entries before date D."
17439 (interactive (list (org-read-date)))
17440 (let* ((case-fold-search nil)
17441 (regexp (org-re-timestamp org-ts-type))
17442 (ts-type org-ts-type)
17443 (callback
17444 (lambda ()
17445 (let ((match (match-string 1)))
17446 (and (if (memq ts-type '(active inactive all))
17447 (eq (org-element-type (save-excursion
17448 (backward-char)
17449 (org-element-context)))
17450 'timestamp)
17451 (org-at-planning-p))
17452 (time-less-p
17453 (org-time-string-to-time match)
17454 (org-time-string-to-time d)))))))
17455 (message "%d entries before %s"
17456 (org-occur regexp nil callback)
17457 d)))
17459 (defun org-check-after-date (d)
17460 "Check if there are deadlines or scheduled entries after date D."
17461 (interactive (list (org-read-date)))
17462 (let* ((case-fold-search nil)
17463 (regexp (org-re-timestamp org-ts-type))
17464 (ts-type org-ts-type)
17465 (callback
17466 (lambda ()
17467 (let ((match (match-string 1)))
17468 (and (if (memq ts-type '(active inactive all))
17469 (eq (org-element-type (save-excursion
17470 (backward-char)
17471 (org-element-context)))
17472 'timestamp)
17473 (org-at-planning-p))
17474 (not (time-less-p
17475 (org-time-string-to-time match)
17476 (org-time-string-to-time d))))))))
17477 (message "%d entries after %s"
17478 (org-occur regexp nil callback)
17479 d)))
17481 (defun org-check-dates-range (start-date end-date)
17482 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17483 (interactive (list (org-read-date nil nil nil "Range starts")
17484 (org-read-date nil nil nil "Range end")))
17485 (let ((case-fold-search nil)
17486 (regexp (org-re-timestamp org-ts-type))
17487 (callback
17488 (let ((type org-ts-type))
17489 (lambda ()
17490 (let ((match (match-string 1)))
17491 (and
17492 (if (memq type '(active inactive all))
17493 (eq (org-element-type (save-excursion
17494 (backward-char)
17495 (org-element-context)))
17496 'timestamp)
17497 (org-at-planning-p))
17498 (not (time-less-p
17499 (org-time-string-to-time match)
17500 (org-time-string-to-time start-date)))
17501 (time-less-p
17502 (org-time-string-to-time match)
17503 (org-time-string-to-time end-date))))))))
17504 (message "%d entries between %s and %s"
17505 (org-occur regexp nil callback) start-date end-date)))
17507 (defun org-evaluate-time-range (&optional to-buffer)
17508 "Evaluate a time range by computing the difference between start and end.
17509 Normally the result is just printed in the echo area, but with prefix arg
17510 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17511 If the time range is actually in a table, the result is inserted into the
17512 next column.
17513 For time difference computation, a year is assumed to be exactly 365
17514 days in order to avoid rounding problems."
17515 (interactive "P")
17517 (org-clock-update-time-maybe)
17518 (save-excursion
17519 (unless (org-at-date-range-p t)
17520 (goto-char (point-at-bol))
17521 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17522 (unless (org-at-date-range-p t)
17523 (user-error "Not at a time-stamp range, and none found in current line")))
17524 (let* ((ts1 (match-string 1))
17525 (ts2 (match-string 2))
17526 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17527 (match-end (match-end 0))
17528 (time1 (org-time-string-to-time ts1))
17529 (time2 (org-time-string-to-time ts2))
17530 (t1 (float-time time1))
17531 (t2 (float-time time2))
17532 (diff (abs (- t2 t1)))
17533 (negative (< (- t2 t1) 0))
17534 ;; (ys (floor (* 365 24 60 60)))
17535 (ds (* 24 60 60))
17536 (hs (* 60 60))
17537 (fy "%dy %dd %02d:%02d")
17538 (fy1 "%dy %dd")
17539 (fd "%dd %02d:%02d")
17540 (fd1 "%dd")
17541 (fh "%02d:%02d")
17542 y d h m align)
17543 (if havetime
17544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17546 d (floor (/ diff ds)) diff (mod diff ds)
17547 h (floor (/ diff hs)) diff (mod diff hs)
17548 m (floor (/ diff 60)))
17549 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17551 d (floor (+ (/ diff ds) 0.5))
17552 h 0 m 0))
17553 (if (not to-buffer)
17554 (message "%s" (org-make-tdiff-string y d h m))
17555 (if (org-at-table-p)
17556 (progn
17557 (goto-char match-end)
17558 (setq align t)
17559 (and (looking-at " *|") (goto-char (match-end 0))))
17560 (goto-char match-end))
17561 (when (looking-at
17562 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17563 (replace-match ""))
17564 (when negative (insert " -"))
17565 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17566 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17567 (insert " " (format fh h m))))
17568 (when align (org-table-align))
17569 (message "Time difference inserted")))))
17571 (defun org-make-tdiff-string (y d h m)
17572 (let ((fmt "")
17573 (l nil))
17574 (when (> y 0)
17575 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17576 (push y l))
17577 (when (> d 0)
17578 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17579 (push d l))
17580 (when (> h 0)
17581 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17582 (push h l))
17583 (when (> m 0)
17584 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17585 (push m l))
17586 (apply 'format fmt (nreverse l))))
17588 (defun org-time-string-to-time (s &optional buffer pos)
17589 "Convert a timestamp string into internal time."
17590 (condition-case errdata
17591 (apply 'encode-time (org-parse-time-string s))
17592 (error (error "Bad timestamp `%s'%s\nError was: %s"
17593 s (if (not (and buffer pos))
17595 (format-message " at %d in buffer `%s'" pos buffer))
17596 (cdr errdata)))))
17598 (defun org-time-string-to-seconds (s)
17599 "Convert a timestamp string to a number of seconds."
17600 (float-time (org-time-string-to-time s)))
17602 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17604 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17605 "Convert time stamp S to an absolute day number.
17607 If DAYNR in non-nil, and there is a specifier for a cyclic time
17608 stamp, get the closest date to DAYNR. If PREFER is
17609 `past' (respectively `future') return a date past (respectively
17610 after) or equal to DAYNR.
17612 POS is the location of time stamp S, as a buffer position in
17613 BUFFER.
17615 Diary sexp timestamps are matched against DAYNR, when non-nil.
17616 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17617 signalled."
17618 (cond
17619 ((string-match "\\`%%\\((.*)\\)" s)
17620 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17621 ;; only able to match individual dates. If it fails, raise an
17622 ;; error.
17623 (if (and daynr
17624 (org-diary-sexp-entry
17625 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17626 daynr
17627 (signal 'org-diary-sexp-no-match (list s))))
17628 (daynr (org-closest-date s daynr prefer))
17629 (t (time-to-days
17630 (condition-case errdata
17631 (apply #'encode-time (org-parse-time-string s))
17632 (error (error "Bad timestamp `%s'%s\nError was: %s"
17634 (if (not (and buffer pos)) ""
17635 (format-message " at %d in buffer `%s'" pos buffer))
17636 (cdr errdata))))))))
17638 (defun org-days-to-iso-week (days)
17639 "Return the iso week number."
17640 (require 'cal-iso)
17641 (car (calendar-iso-from-absolute days)))
17643 (defun org-small-year-to-year (year)
17644 "Convert 2-digit years into 4-digit years.
17645 YEAR is expanded into one of the 30 next years, if possible, or
17646 into a past one. Any year larger than 99 is returned unchanged."
17647 (if (>= year 100) year
17648 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17649 (century (/ current 100))
17650 (offset (- year (% current 100))))
17651 (cond ((> offset 30) (+ (* (1- century) 100) year))
17652 ((> offset -70) (+ (* century 100) year))
17653 (t (+ (* (1+ century) 100) year))))))
17655 (defun org-time-from-absolute (d)
17656 "Return the time corresponding to date D.
17657 D may be an absolute day number, or a calendar-type list (month day year)."
17658 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17659 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17661 (defvar org-agenda-current-date)
17662 (defun org-calendar-holiday ()
17663 "List of holidays, for Diary display in Org mode."
17664 (require 'holidays)
17665 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17666 (and hl (mapconcat #'identity hl "; "))))
17668 (defun org-diary-sexp-entry (sexp entry d)
17669 "Process a SEXP diary ENTRY for date D."
17670 (require 'diary-lib)
17671 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17672 ;; dynamically.
17673 (let* ((sexp `(let ((entry ,entry)
17674 (date ',d))
17675 ,(car (read-from-string sexp))))
17676 (result (if calendar-debug-sexp (eval sexp)
17677 (condition-case nil
17678 (eval sexp)
17679 (error
17680 (beep)
17681 (message "Bad sexp at line %d in %s: %s"
17682 (org-current-line)
17683 (buffer-file-name) sexp)
17684 (sleep-for 2))))))
17685 (cond ((stringp result) (split-string result "; "))
17686 ((and (consp result)
17687 (not (consp (cdr result)))
17688 (stringp (cdr result))) (cdr result))
17689 ((and (consp result)
17690 (stringp (car result))) result)
17691 (result entry))))
17693 (defun org-diary-to-ical-string (frombuf)
17694 "Get iCalendar entries from diary entries in buffer FROMBUF.
17695 This uses the icalendar.el library."
17696 (let* ((tmpdir temporary-file-directory)
17697 (tmpfile (make-temp-name
17698 (expand-file-name "orgics" tmpdir)))
17699 buf rtn b e)
17700 (with-current-buffer frombuf
17701 (icalendar-export-region (point-min) (point-max) tmpfile)
17702 (setq buf (find-buffer-visiting tmpfile))
17703 (set-buffer buf)
17704 (goto-char (point-min))
17705 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17706 (setq b (match-beginning 0)))
17707 (goto-char (point-max))
17708 (when (re-search-backward "^END:VEVENT" nil t)
17709 (setq e (match-end 0)))
17710 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17711 (kill-buffer buf)
17712 (delete-file tmpfile)
17713 rtn))
17715 (defun org-closest-date (start current prefer)
17716 "Return closest date to CURRENT starting from START.
17718 CURRENT and START are both time stamps.
17720 When PREFER is `past', return a date that is either CURRENT or
17721 past. When PREFER is `future', return a date that is either
17722 CURRENT or future.
17724 Only time stamps with a repeater are modified. Any other time
17725 stamp stay unchanged. In any case, return value is an absolute
17726 day number."
17727 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17728 ;; No repeater. Do not shift time stamp.
17729 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17730 (let ((value (string-to-number (match-string 1 start)))
17731 (type (match-string 2 start)))
17732 (if (= 0 value)
17733 ;; Repeater with a 0-value is considered as void.
17734 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17735 (let* ((base (org-date-to-gregorian start))
17736 (target (org-date-to-gregorian current))
17737 (sday (calendar-absolute-from-gregorian base))
17738 (cday (calendar-absolute-from-gregorian target))
17739 n1 n2)
17740 ;; If START is already past CURRENT, just return START.
17741 (if (<= cday sday) sday
17742 ;; Compute closest date before (N1) and closest date past
17743 ;; (N2) CURRENT.
17744 (pcase type
17745 ("h"
17746 (let ((missing-hours
17747 (mod (+ (- (* 24 (- cday sday))
17748 (nth 2 (org-parse-time-string start)))
17749 org-extend-today-until)
17750 value)))
17751 (setf n1 (if (= missing-hours 0) cday
17752 (- cday (1+ (/ missing-hours 24)))))
17753 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17754 ((or "d" "w")
17755 (let ((value (if (equal type "w") (* 7 value) value)))
17756 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17757 (setf n2 (+ n1 value))))
17758 ("m"
17759 (let* ((add-months
17760 (lambda (d n)
17761 ;; Add N months to gregorian date D, i.e.,
17762 ;; a list (MONTH DAY YEAR). Return a valid
17763 ;; gregorian date.
17764 (let ((m (+ (nth 0 d) n)))
17765 (list (mod m 12)
17766 (nth 1 d)
17767 (+ (/ m 12) (nth 2 d))))))
17768 (months ; Complete months to TARGET.
17769 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17770 (- (nth 0 target) (nth 0 base))
17771 ;; If START's day is greater than
17772 ;; TARGET's, remove incomplete month.
17773 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17774 value)
17775 value))
17776 (before (funcall add-months base months)))
17777 (setf n1 (calendar-absolute-from-gregorian before))
17778 (setf n2
17779 (calendar-absolute-from-gregorian
17780 (funcall add-months before value)))))
17782 (let* ((d (nth 1 base))
17783 (m (nth 0 base))
17784 (y (nth 2 base))
17785 (years ; Complete years to TARGET.
17786 (* (/ (- (nth 2 target)
17788 ;; If START's month and day are
17789 ;; greater than TARGET's, remove
17790 ;; incomplete year.
17791 (if (or (> (nth 0 target) m)
17792 (and (= (nth 0 target) m)
17793 (> (nth 1 target) d)))
17796 value)
17797 value))
17798 (before (list m d (+ y years))))
17799 (setf n1 (calendar-absolute-from-gregorian before))
17800 (setf n2 (calendar-absolute-from-gregorian
17801 (list m d (+ (nth 2 before) value)))))))
17802 ;; Handle PREFER parameter, if any.
17803 (cond
17804 ((eq prefer 'past) (if (= cday n2) n2 n1))
17805 ((eq prefer 'future) (if (= cday n1) n1 n2))
17806 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17808 (defun org-date-to-gregorian (d)
17809 "Turn any specification of date D into a Gregorian date for the calendar."
17810 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17811 ((and (listp d) (= (length d) 3)) d)
17812 ((stringp d)
17813 (let ((d (org-parse-time-string d)))
17814 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17815 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17817 (defun org-parse-time-string (s &optional nodefault)
17818 "Parse the standard Org time string.
17819 This should be a lot faster than the normal `parse-time-string'.
17820 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17821 hour and minute fields will be nil if not given."
17822 (cond ((string-match org-ts-regexp0 s)
17823 (list 0
17824 (when (or (match-beginning 8) (not nodefault))
17825 (string-to-number (or (match-string 8 s) "0")))
17826 (when (or (match-beginning 7) (not nodefault))
17827 (string-to-number (or (match-string 7 s) "0")))
17828 (string-to-number (match-string 4 s))
17829 (string-to-number (match-string 3 s))
17830 (string-to-number (match-string 2 s))
17831 nil nil nil))
17832 ((string-match "^<[^>]+>$" s)
17833 (decode-time (seconds-to-time (org-matcher-time s))))
17834 (t (error "Not a standard Org time string: %s" s))))
17836 (defun org-timestamp-up (&optional arg)
17837 "Increase the date item at the cursor by one.
17838 If the cursor is on the year, change the year. If it is on the month,
17839 the day or the time, change that.
17840 With prefix ARG, change by that many units."
17841 (interactive "p")
17842 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17844 (defun org-timestamp-down (&optional arg)
17845 "Decrease the date item at the cursor by one.
17846 If the cursor is on the year, change the year. If it is on the month,
17847 the day or the time, change that.
17848 With prefix ARG, change by that many units."
17849 (interactive "p")
17850 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17852 (defun org-timestamp-up-day (&optional arg)
17853 "Increase the date in the time stamp by one day.
17854 With prefix ARG, change that many days."
17855 (interactive "p")
17856 (if (and (not (org-at-timestamp-p t))
17857 (org-at-heading-p))
17858 (org-todo 'up)
17859 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17861 (defun org-timestamp-down-day (&optional arg)
17862 "Decrease the date in the time stamp by one day.
17863 With prefix ARG, change that many days."
17864 (interactive "p")
17865 (if (and (not (org-at-timestamp-p t))
17866 (org-at-heading-p))
17867 (org-todo 'down)
17868 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17870 (defun org-at-timestamp-p (&optional inactive-ok)
17871 "Non-nil if point is inside a timestamp.
17873 When optional argument INACTIVE-OK is non-nil, also consider
17874 inactive timestamps.
17876 When this function returns a non-nil value, match data is set
17877 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17878 INACTIVE-OK.
17880 Return the position of the point as a symbol among `bracket',
17881 `after', `year', `month', `hour', `minute', `day' or a number of
17882 character from the last know part of the time stamp.
17884 This function checks context and only return non-nil for valid
17885 time stamps. If you need to match anything looking like a time
17886 stamp, or if you are sure about the context, consider using
17887 `org-in-regexp', e.g.,
17889 (org-in-regexp org-ts-regexp)
17891 Unlike to `org-element-context', the function recognizes time
17892 stamps in properties drawers, planning lines and clocks."
17893 (interactive)
17894 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17895 (pos (point))
17896 (match
17897 (let ((boundaries (org-in-regexp tsr)))
17898 (save-match-data
17899 (cond ((null boundaries) nil)
17900 ((org-at-planning-p))
17901 ((org-at-property-p))
17902 ;; CLOCK lines only contain inactive time-stamps.
17903 ((and inactive-ok (org-at-clock-log-p)))
17905 (eq 'timestamp
17906 (save-excursion
17907 (when (= pos (cdr boundaries)) (forward-char -1))
17908 (org-element-type (org-element-context))))))))))
17909 (cond
17910 ((not match) nil)
17911 ((= pos (match-beginning 0)) 'bracket)
17912 ;; Distinguish location right before the closing bracket from
17913 ;; right after it.
17914 ((= pos (1- (match-end 0))) 'bracket)
17915 ((= pos (match-end 0)) 'after)
17916 ((org-pos-in-match-range pos 2) 'year)
17917 ((org-pos-in-match-range pos 3) 'month)
17918 ((org-pos-in-match-range pos 7) 'hour)
17919 ((org-pos-in-match-range pos 8) 'minute)
17920 ((or (org-pos-in-match-range pos 4)
17921 (org-pos-in-match-range pos 5)) 'day)
17922 ((and (> pos (or (match-end 8) (match-end 5)))
17923 (< pos (match-end 0)))
17924 (- pos (or (match-end 8) (match-end 5))))
17925 (t 'day))))
17927 (defun org-toggle-timestamp-type ()
17928 "Toggle the type (<active> or [inactive]) of a time stamp."
17929 (interactive)
17930 (when (org-at-timestamp-p t)
17931 (let ((beg (match-beginning 0)) (end (match-end 0))
17932 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17933 (save-excursion
17934 (goto-char beg)
17935 (while (re-search-forward "[][<>]" end t)
17936 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17937 t t)))
17938 (message "Timestamp is now %sactive"
17939 (if (equal (char-after beg) ?<) "" "in")))))
17941 (defun org-at-clock-log-p ()
17942 "Non-nil if point is on a clock log line."
17943 (and (org-match-line org-clock-line-re)
17944 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17946 (defvar org-clock-history) ; defined in org-clock.el
17947 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17948 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17949 "Change the date in the time stamp at point.
17950 The date will be changed by N times WHAT. WHAT can be `day', `month',
17951 `year', `minute', `second'. If WHAT is not given, the cursor position
17952 in the timestamp determines what will be changed.
17953 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17954 (let ((origin (point))
17955 (timestamp? (org-at-timestamp-p t))
17956 origin-cat
17957 with-hm inactive
17958 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17959 extra rem
17960 ts time time0 fixnext clrgx)
17961 (unless timestamp? (user-error "Not at a timestamp"))
17962 (if (and (not what) (eq timestamp? 'bracket))
17963 (org-toggle-timestamp-type)
17964 ;; Point isn't on brackets. Remember the part of the time-stamp
17965 ;; the point was in. Indeed, size of time-stamps may change,
17966 ;; but point must be kept in the same category nonetheless.
17967 (setq origin-cat timestamp?)
17968 (when (and (not what) (not (eq timestamp? 'day))
17969 org-display-custom-times
17970 (get-text-property (point) 'display)
17971 (not (get-text-property (1- (point)) 'display)))
17972 (setq timestamp? 'day))
17973 (setq timestamp? (or what timestamp?)
17974 inactive (= (char-after (match-beginning 0)) ?\[)
17975 ts (match-string 0))
17976 (replace-match "")
17977 (when (string-match
17978 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17980 (setq extra (match-string 1 ts))
17981 (when suppress-tmp-delay
17982 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17983 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17984 (setq with-hm t))
17985 (setq time0 (org-parse-time-string ts))
17986 (when (and updown
17987 (eq timestamp? 'minute)
17988 (not current-prefix-arg))
17989 ;; This looks like s-up and s-down. Change by one rounding step.
17990 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17991 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17992 (setcar (cdr time0) (+ (nth 1 time0)
17993 (if (> n 0) (- rem) (- dm rem))))))
17994 (setq time
17995 (apply #'encode-time
17996 (or (car time0) 0)
17997 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17998 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17999 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18000 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18001 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18002 (nthcdr 6 time0)))
18003 (when (and (memq timestamp? '(hour minute))
18004 extra
18005 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18006 (setq extra (org-modify-ts-extra
18007 extra
18008 (if (eq timestamp? 'hour) 2 5)
18009 n dm)))
18010 (when (integerp timestamp?)
18011 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18012 (when (eq what 'calendar)
18013 (let ((cal-date (org-get-date-from-calendar)))
18014 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18015 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18016 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18017 (setcar time0 (or (car time0) 0))
18018 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18019 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18020 (setq time (apply 'encode-time time0))))
18021 ;; Insert the new time-stamp, and ensure point stays in the same
18022 ;; category as before (i.e. not after the last position in that
18023 ;; category).
18024 (let ((pos (point)))
18025 ;; Stay before inserted string. `save-excursion' is of no use.
18026 (setq org-last-changed-timestamp
18027 (org-insert-time-stamp time with-hm inactive nil nil extra))
18028 (goto-char pos))
18029 (save-match-data
18030 (looking-at org-ts-regexp3)
18031 (goto-char
18032 (pcase origin-cat
18033 ;; `day' category ends before `hour' if any, or at the end
18034 ;; of the day name.
18035 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18036 (`hour (min (match-end 7) origin))
18037 (`minute (min (1- (match-end 8)) origin))
18038 ((pred integerp) (min (1- (match-end 0)) origin))
18039 ;; Point was right after the time-stamp. However, the
18040 ;; time-stamp length might have changed, so refer to
18041 ;; (match-end 0) instead.
18042 (`after (match-end 0))
18043 ;; `year' and `month' have both fixed size: point couldn't
18044 ;; have moved into another part.
18045 (_ origin))))
18046 ;; Update clock if on a CLOCK line.
18047 (org-clock-update-time-maybe)
18048 ;; Maybe adjust the closest clock in `org-clock-history'
18049 (when org-clock-adjust-closest
18050 (if (not (and (org-at-clock-log-p)
18051 (< 1 (length (delq nil (mapcar 'marker-position
18052 org-clock-history))))))
18053 (message "No clock to adjust")
18054 (cond ((save-excursion ; fix previous clock?
18055 (re-search-backward org-ts-regexp0 nil t)
18056 (looking-back (concat org-clock-string " \\[")
18057 (line-beginning-position)))
18058 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18059 ((save-excursion ; fix next clock?
18060 (re-search-backward org-ts-regexp0 nil t)
18061 (looking-at (concat org-ts-regexp0 "\\] =>")))
18062 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18063 (save-window-excursion
18064 ;; Find closest clock to point, adjust the previous/next one in history
18065 (let* ((p (save-excursion (org-back-to-heading t)))
18066 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18067 (clfixnth
18068 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18069 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18070 (if (not clfixpos)
18071 (message "No clock to adjust")
18072 (save-excursion
18073 (org-goto-marker-or-bmk clfixpos)
18074 (org-show-subtree)
18075 (when (re-search-forward clrgx nil t)
18076 (goto-char (match-beginning 1))
18077 (let (org-clock-adjust-closest)
18078 (org-timestamp-change n timestamp? updown))
18079 (message "Clock adjusted in %s for heading: %s"
18080 (file-name-nondirectory (buffer-file-name))
18081 (org-get-heading t t)))))))))
18082 ;; Try to recenter the calendar window, if any.
18083 (when (and org-calendar-follow-timestamp-change
18084 (get-buffer-window "*Calendar*" t)
18085 (memq timestamp? '(day month year)))
18086 (org-recenter-calendar (time-to-days time))))))
18088 (defun org-modify-ts-extra (s pos n dm)
18089 "Change the different parts of the lead-time and repeat fields in timestamp."
18090 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18091 ng h m new rem)
18092 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18093 (cond
18094 ((or (org-pos-in-match-range pos 2)
18095 (org-pos-in-match-range pos 3))
18096 (setq m (string-to-number (match-string 3 s))
18097 h (string-to-number (match-string 2 s)))
18098 (if (org-pos-in-match-range pos 2)
18099 (setq h (+ h n))
18100 (setq n (* dm (with-no-warnings (signum n))))
18101 (unless (= 0 (setq rem (% m dm)))
18102 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18103 (setq m (+ m n)))
18104 (when (< m 0) (setq m (+ m 60) h (1- h)))
18105 (when (> m 59) (setq m (- m 60) h (1+ h)))
18106 (setq h (mod h 24))
18107 (setq ng 1 new (format "-%02d:%02d" h m)))
18108 ((org-pos-in-match-range pos 6)
18109 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18110 ((org-pos-in-match-range pos 5)
18111 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18113 ((org-pos-in-match-range pos 9)
18114 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18115 ((org-pos-in-match-range pos 8)
18116 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18118 (when ng
18119 (setq s (concat
18120 (substring s 0 (match-beginning ng))
18122 (substring s (match-end ng))))))
18125 (defun org-recenter-calendar (d)
18126 "If the calendar is visible, recenter it to date D."
18127 (let ((cwin (get-buffer-window "*Calendar*" t)))
18128 (when cwin
18129 (let ((calendar-move-hook nil))
18130 (with-selected-window cwin
18131 (calendar-goto-date
18132 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18134 (defun org-goto-calendar (&optional arg)
18135 "Go to the Emacs calendar at the current date.
18136 If there is a time stamp in the current line, go to that date.
18137 A prefix ARG can be used to force the current date."
18138 (interactive "P")
18139 (let ((tsr org-ts-regexp) diff
18140 (calendar-move-hook nil)
18141 (calendar-view-holidays-initially-flag nil)
18142 (calendar-view-diary-initially-flag nil))
18143 (when (or (org-at-timestamp-p)
18144 (save-excursion
18145 (beginning-of-line 1)
18146 (looking-at (concat ".*" tsr))))
18147 (let ((d1 (time-to-days (current-time)))
18148 (d2 (time-to-days
18149 (org-time-string-to-time (match-string 1)))))
18150 (setq diff (- d2 d1))))
18151 (calendar)
18152 (calendar-goto-today)
18153 (when (and diff (not arg)) (calendar-forward-day diff))))
18155 (defun org-get-date-from-calendar ()
18156 "Return a list (month day year) of date at point in calendar."
18157 (with-current-buffer "*Calendar*"
18158 (save-match-data
18159 (calendar-cursor-to-date))))
18161 (defun org-date-from-calendar ()
18162 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18163 If there is already a time stamp at the cursor position, update it."
18164 (interactive)
18165 (if (org-at-timestamp-p t)
18166 (org-timestamp-change 0 'calendar)
18167 (let ((cal-date (org-get-date-from-calendar)))
18168 (org-insert-time-stamp
18169 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18171 (defcustom org-effort-durations
18172 `(("min" . 1)
18173 ("h" . 60)
18174 ("d" . ,(* 60 8))
18175 ("w" . ,(* 60 8 5))
18176 ("m" . ,(* 60 8 5 4))
18177 ("y" . ,(* 60 8 5 40)))
18178 "Conversion factor to minutes for an effort modifier.
18180 Each entry has the form (MODIFIER . MINUTES).
18182 In an effort string, a number followed by MODIFIER is multiplied
18183 by the specified number of MINUTES to obtain an effort in
18184 minutes.
18186 For example, if the value of this variable is ((\"hours\" . 60)), then an
18187 effort string \"2hours\" is equivalent to 120 minutes."
18188 :group 'org-agenda
18189 :version "26.1"
18190 :package-version '(Org . "8.3")
18191 :type '(alist :key-type (string :tag "Modifier")
18192 :value-type (number :tag "Minutes")))
18194 (defcustom org-image-actual-width t
18195 "Should we use the actual width of images when inlining them?
18197 When set to t, always use the image width.
18199 When set to a number, use imagemagick (when available) to set
18200 the image's width to this value.
18202 When set to a number in a list, try to get the width from any
18203 #+ATTR.* keyword if it matches a width specification like
18205 #+ATTR_HTML: :width 300px
18207 and fall back on that number if none is found.
18209 When set to nil, try to get the width from an #+ATTR.* keyword
18210 and fall back on the original width if none is found.
18212 This requires Emacs >= 24.1, build with imagemagick support."
18213 :group 'org-appearance
18214 :version "24.4"
18215 :package-version '(Org . "8.0")
18216 :type '(choice
18217 (const :tag "Use the image width" t)
18218 (integer :tag "Use a number of pixels")
18219 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18220 (const :tag "Use #+ATTR* or don't resize" nil)))
18222 (defcustom org-agenda-inhibit-startup nil
18223 "Inhibit startup when preparing agenda buffers.
18224 When this variable is t, the initialization of the Org agenda
18225 buffers is inhibited: e.g. the visibility state is not set, the
18226 tables are not re-aligned, etc."
18227 :type 'boolean
18228 :version "24.3"
18229 :group 'org-agenda)
18231 (defcustom org-agenda-ignore-properties nil
18232 "Avoid updating text properties when building the agenda.
18233 Properties are used to prepare buffers for effort estimates,
18234 appointments, statistics and subtree-local categories.
18235 If you don't use these in the agenda, you can add them to this
18236 list and agenda building will be a bit faster.
18237 The value is a list, with zero or more of the symbols `effort', `appt',
18238 `stats' or `category'."
18239 :type '(set :greedy t
18240 (const effort)
18241 (const appt)
18242 (const stats)
18243 (const category))
18244 :version "26.1"
18245 :package-version '(Org . "8.3")
18246 :group 'org-agenda)
18248 ;;;; Files
18250 (defun org-save-all-org-buffers ()
18251 "Save all Org buffers without user confirmation."
18252 (interactive)
18253 (message "Saving all Org buffers...")
18254 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18255 (when (featurep 'org-id) (org-id-locations-save))
18256 (message "Saving all Org buffers... done"))
18258 (defun org-revert-all-org-buffers ()
18259 "Revert all Org buffers.
18260 Prompt for confirmation when there are unsaved changes.
18261 Be sure you know what you are doing before letting this function
18262 overwrite your changes.
18264 This function is useful in a setup where one tracks org files
18265 with a version control system, to revert on one machine after pulling
18266 changes from another. I believe the procedure must be like this:
18268 1. M-x org-save-all-org-buffers
18269 2. Pull changes from the other machine, resolve conflicts
18270 3. M-x org-revert-all-org-buffers"
18271 (interactive)
18272 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18273 (user-error "Abort"))
18274 (save-excursion
18275 (save-window-excursion
18276 (dolist (b (buffer-list))
18277 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18278 (with-current-buffer b buffer-file-name))
18279 (pop-to-buffer-same-window b)
18280 (revert-buffer t 'no-confirm)))
18281 (when (and (featurep 'org-id) org-id-track-globally)
18282 (org-id-locations-load)))))
18284 ;;;; Agenda files
18286 ;;;###autoload
18287 (defun org-switchb (&optional arg)
18288 "Switch between Org buffers.
18290 With `\\[universal-argument]' prefix, restrict available buffers to files.
18292 With `\\[universal-argument] \\[universal-argument]' \
18293 prefix, restrict available buffers to agenda files."
18294 (interactive "P")
18295 (let ((blist (org-buffer-list
18296 (cond ((equal arg '(4)) 'files)
18297 ((equal arg '(16)) 'agenda)))))
18298 (pop-to-buffer-same-window
18299 (completing-read "Org buffer: "
18300 (mapcar #'list (mapcar #'buffer-name blist))
18301 nil t))))
18303 (defun org-buffer-list (&optional predicate exclude-tmp)
18304 "Return a list of Org buffers.
18305 PREDICATE can be `export', `files' or `agenda'.
18307 export restrict the list to Export buffers.
18308 files restrict the list to buffers visiting Org files.
18309 agenda restrict the list to buffers visiting agenda files.
18311 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18312 (let* ((bfn nil)
18313 (agenda-files (and (eq predicate 'agenda)
18314 (mapcar 'file-truename (org-agenda-files t))))
18315 (filter
18316 (cond
18317 ((eq predicate 'files)
18318 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18319 ((eq predicate 'export)
18320 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18321 ((eq predicate 'agenda)
18322 (lambda (b)
18323 (with-current-buffer b
18324 (and (derived-mode-p 'org-mode)
18325 (setq bfn (buffer-file-name b))
18326 (member (file-truename bfn) agenda-files)))))
18327 (t (lambda (b) (with-current-buffer b
18328 (or (derived-mode-p 'org-mode)
18329 (string-match "\\*Org .*Export"
18330 (buffer-name b)))))))))
18331 (delq nil
18332 (mapcar
18333 (lambda(b)
18334 (if (and (funcall filter b)
18335 (or (not exclude-tmp)
18336 (not (string-match "tmp" (buffer-name b)))))
18338 nil))
18339 (buffer-list)))))
18341 (defun org-agenda-files (&optional unrestricted archives)
18342 "Get the list of agenda files.
18343 Optional UNRESTRICTED means return the full list even if a restriction
18344 is currently in place.
18345 When ARCHIVES is t, include all archive files that are really being
18346 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18347 `org-agenda-archives-mode' is t."
18348 (let ((files
18349 (cond
18350 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18351 ((stringp org-agenda-files) (org-read-agenda-file-list))
18352 ((listp org-agenda-files) org-agenda-files)
18353 (t (error "Invalid value of `org-agenda-files'")))))
18354 (setq files (apply 'append
18355 (mapcar (lambda (f)
18356 (if (file-directory-p f)
18357 (directory-files
18358 f t org-agenda-file-regexp)
18359 (list f)))
18360 files)))
18361 (when org-agenda-skip-unavailable-files
18362 (setq files (delq nil
18363 (mapcar (function
18364 (lambda (file)
18365 (and (file-readable-p file) file)))
18366 files))))
18367 (when (or (eq archives t)
18368 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18369 (setq files (org-add-archive-files files)))
18370 files))
18372 (defun org-agenda-file-p (&optional file)
18373 "Return non-nil, if FILE is an agenda file.
18374 If FILE is omitted, use the file associated with the current
18375 buffer."
18376 (let ((fname (or file (buffer-file-name))))
18377 (and fname
18378 (member (file-truename fname)
18379 (mapcar #'file-truename (org-agenda-files t))))))
18381 (defun org-edit-agenda-file-list ()
18382 "Edit the list of agenda files.
18383 Depending on setup, this either uses customize to edit the variable
18384 `org-agenda-files', or it visits the file that is holding the list. In the
18385 latter case, the buffer is set up in a way that saving it automatically kills
18386 the buffer and restores the previous window configuration."
18387 (interactive)
18388 (if (stringp org-agenda-files)
18389 (let ((cw (current-window-configuration)))
18390 (find-file org-agenda-files)
18391 (setq-local org-window-configuration cw)
18392 (add-hook 'after-save-hook
18393 (lambda ()
18394 (set-window-configuration
18395 (prog1 org-window-configuration
18396 (kill-buffer (current-buffer))))
18397 (org-install-agenda-files-menu)
18398 (message "New agenda file list installed"))
18399 nil 'local)
18400 (message "%s" (substitute-command-keys
18401 "Edit list and finish with \\[save-buffer]")))
18402 (customize-variable 'org-agenda-files)))
18404 (defun org-store-new-agenda-file-list (list)
18405 "Set new value for the agenda file list and save it correctly."
18406 (if (stringp org-agenda-files)
18407 (let ((fe (org-read-agenda-file-list t)) b u)
18408 (while (setq b (find-buffer-visiting org-agenda-files))
18409 (kill-buffer b))
18410 (with-temp-file org-agenda-files
18411 (insert
18412 (mapconcat
18413 (lambda (f) ;; Keep un-expanded entries.
18414 (if (setq u (assoc f fe))
18415 (cdr u)
18417 list "\n")
18418 "\n")))
18419 (let ((org-mode-hook nil) (org-inhibit-startup t)
18420 (org-insert-mode-line-in-empty-file nil))
18421 (setq org-agenda-files list)
18422 (customize-save-variable 'org-agenda-files org-agenda-files))))
18424 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18425 "Read the list of agenda files from a file.
18426 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18427 filenames, used by `org-store-new-agenda-file-list' to write back
18428 un-expanded file names."
18429 (when (file-directory-p org-agenda-files)
18430 (error "`org-agenda-files' cannot be a single directory"))
18431 (when (stringp org-agenda-files)
18432 (with-temp-buffer
18433 (insert-file-contents org-agenda-files)
18434 (mapcar
18435 (lambda (f)
18436 (let ((e (expand-file-name (substitute-in-file-name f)
18437 org-directory)))
18438 (if pair-with-expansion
18439 (cons e f)
18440 e)))
18441 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18443 ;;;###autoload
18444 (defun org-cycle-agenda-files ()
18445 "Cycle through the files in `org-agenda-files'.
18446 If the current buffer visits an agenda file, find the next one in the list.
18447 If the current buffer does not, find the first agenda file."
18448 (interactive)
18449 (let* ((fs (or (org-agenda-files t)
18450 (user-error "No agenda files")))
18451 (files (copy-sequence fs))
18452 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18453 file)
18454 (when tcf
18455 (while (and (setq file (pop files))
18456 (not (equal (file-truename file) tcf)))))
18457 (find-file (car (or files fs)))
18458 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18460 (defun org-agenda-file-to-front (&optional to-end)
18461 "Move/add the current file to the top of the agenda file list.
18462 If the file is not present in the list, it is added to the front. If it is
18463 present, it is moved there. With optional argument TO-END, add/move to the
18464 end of the list."
18465 (interactive "P")
18466 (let ((org-agenda-skip-unavailable-files nil)
18467 (file-alist (mapcar (lambda (x)
18468 (cons (file-truename x) x))
18469 (org-agenda-files t)))
18470 (ctf (file-truename
18471 (or buffer-file-name
18472 (user-error "Please save the current buffer to a file"))))
18473 x had)
18474 (setq x (assoc ctf file-alist) had x)
18476 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18477 (if to-end
18478 (setq file-alist (append (delq x file-alist) (list x)))
18479 (setq file-alist (cons x (delq x file-alist))))
18480 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18481 (org-install-agenda-files-menu)
18482 (message "File %s to %s of agenda file list"
18483 (if had "moved" "added") (if to-end "end" "front"))))
18485 (defun org-remove-file (&optional file)
18486 "Remove current file from the list of files in variable `org-agenda-files'.
18487 These are the files which are being checked for agenda entries.
18488 Optional argument FILE means use this file instead of the current."
18489 (interactive)
18490 (let* ((org-agenda-skip-unavailable-files nil)
18491 (file (or file buffer-file-name
18492 (user-error "Current buffer does not visit a file")))
18493 (true-file (file-truename file))
18494 (afile (abbreviate-file-name file))
18495 (files (delq nil (mapcar
18496 (lambda (x)
18497 (unless (equal true-file
18498 (file-truename x))
18500 (org-agenda-files t)))))
18501 (if (not (= (length files) (length (org-agenda-files t))))
18502 (progn
18503 (org-store-new-agenda-file-list files)
18504 (org-install-agenda-files-menu)
18505 (message "Removed from Org Agenda list: %s" afile))
18506 (message "File was not in list: %s (not removed)" afile))))
18508 (defun org-file-menu-entry (file)
18509 (vector file (list 'find-file file) t))
18511 (defun org-check-agenda-file (file)
18512 "Make sure FILE exists. If not, ask user what to do."
18513 (unless (file-exists-p file)
18514 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18515 (abbreviate-file-name file))
18516 (let ((r (downcase (read-char-exclusive))))
18517 (cond
18518 ((equal r ?r)
18519 (org-remove-file file)
18520 (throw 'nextfile t))
18521 (t (user-error "Abort"))))))
18523 (defun org-get-agenda-file-buffer (file)
18524 "Get an agenda buffer visiting FILE.
18525 If the buffer needs to be created, add it to the list of buffers
18526 which might be released later."
18527 (let ((buf (org-find-base-buffer-visiting file)))
18528 (if buf
18529 buf ; just return it
18530 ;; Make a new buffer and remember it
18531 (setq buf (find-file-noselect file))
18532 (when buf (push buf org-agenda-new-buffers))
18533 buf)))
18535 (defun org-release-buffers (blist)
18536 "Release all buffers in list, asking the user for confirmation when needed.
18537 When a buffer is unmodified, it is just killed. When modified, it is saved
18538 \(if the user agrees) and then killed."
18539 (let (file)
18540 (dolist (buf blist)
18541 (setq file (buffer-file-name buf))
18542 (when (and (buffer-modified-p buf)
18543 file
18544 (y-or-n-p (format "Save file %s? " file)))
18545 (with-current-buffer buf (save-buffer)))
18546 (kill-buffer buf))))
18548 (defun org-agenda-prepare-buffers (files)
18549 "Create buffers for all agenda files, protect archived trees and comments."
18550 (interactive)
18551 (let ((pa '(:org-archived t))
18552 (pc '(:org-comment t))
18553 (pall '(:org-archived t :org-comment t))
18554 (inhibit-read-only t)
18555 (org-inhibit-startup org-agenda-inhibit-startup)
18556 (rea (concat ":" org-archive-tag ":"))
18557 re pos)
18558 (setq org-tag-alist-for-agenda nil
18559 org-tag-groups-alist-for-agenda nil)
18560 (save-excursion
18561 (save-restriction
18562 (dolist (file files)
18563 (catch 'nextfile
18564 (if (bufferp file)
18565 (set-buffer file)
18566 (org-check-agenda-file file)
18567 (set-buffer (org-get-agenda-file-buffer file)))
18568 (widen)
18569 (org-set-regexps-and-options 'tags-only)
18570 (setq pos (point))
18571 (or (memq 'category org-agenda-ignore-properties)
18572 (org-refresh-category-properties))
18573 (or (memq 'stats org-agenda-ignore-properties)
18574 (org-refresh-stats-properties))
18575 (or (memq 'effort org-agenda-ignore-properties)
18576 (org-refresh-effort-properties))
18577 (or (memq 'appt org-agenda-ignore-properties)
18578 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18579 (setq org-todo-keywords-for-agenda
18580 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18581 (setq org-done-keywords-for-agenda
18582 (append org-done-keywords-for-agenda org-done-keywords))
18583 (setq org-todo-keyword-alist-for-agenda
18584 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18585 (setq org-tag-alist-for-agenda
18586 (org-uniquify
18587 (append org-tag-alist-for-agenda
18588 org-current-tag-alist)))
18589 ;; Merge current file's tag groups into global
18590 ;; `org-tag-groups-alist-for-agenda'.
18591 (when org-group-tags
18592 (dolist (alist org-tag-groups-alist)
18593 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18594 (if old
18595 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18596 (push alist org-tag-groups-alist-for-agenda)))))
18597 (org-with-silent-modifications
18598 (save-excursion
18599 (remove-text-properties (point-min) (point-max) pall)
18600 (when org-agenda-skip-archived-trees
18601 (goto-char (point-min))
18602 (while (re-search-forward rea nil t)
18603 (when (org-at-heading-p t)
18604 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18605 (goto-char (point-min))
18606 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18607 (while (re-search-forward re nil t)
18608 (when (save-match-data (org-in-commented-heading-p t))
18609 (add-text-properties
18610 (match-beginning 0) (org-end-of-subtree t) pc)))))
18611 (goto-char pos)))))
18612 (setq org-todo-keywords-for-agenda
18613 (org-uniquify org-todo-keywords-for-agenda))
18614 (setq org-todo-keyword-alist-for-agenda
18615 (org-uniquify org-todo-keyword-alist-for-agenda))))
18618 ;;;; CDLaTeX minor mode
18620 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18621 "Keymap for the minor `org-cdlatex-mode'.")
18623 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18624 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18625 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18626 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18627 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18629 (defvar org-cdlatex-texmathp-advice-is-done nil
18630 "Flag remembering if we have applied the advice to texmathp already.")
18632 (define-minor-mode org-cdlatex-mode
18633 "Toggle the minor `org-cdlatex-mode'.
18634 This mode supports entering LaTeX environment and math in LaTeX fragments
18635 in Org mode.
18636 \\{org-cdlatex-mode-map}"
18637 nil " OCDL" nil
18638 (when org-cdlatex-mode
18639 (require 'cdlatex)
18640 (run-hooks 'cdlatex-mode-hook)
18641 (cdlatex-compute-tables))
18642 (unless org-cdlatex-texmathp-advice-is-done
18643 (setq org-cdlatex-texmathp-advice-is-done t)
18644 (defadvice texmathp (around org-math-always-on activate)
18645 "Always return t in Org buffers.
18646 This is because we want to insert math symbols without dollars even outside
18647 the LaTeX math segments. If Org mode thinks that point is actually inside
18648 an embedded LaTeX fragment, let `texmathp' do its job.
18649 `\\[org-cdlatex-mode-map]'"
18650 (interactive)
18651 (let (p)
18652 (cond
18653 ((not (derived-mode-p 'org-mode)) ad-do-it)
18654 ((eq this-command 'cdlatex-math-symbol)
18655 (setq ad-return-value t
18656 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18658 (let ((p (org-inside-LaTeX-fragment-p)))
18659 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18660 (setq ad-return-value t
18661 texmathp-why '("Org mode embedded math" . 0))
18662 (when p ad-do-it)))))))))
18664 (defun turn-on-org-cdlatex ()
18665 "Unconditionally turn on `org-cdlatex-mode'."
18666 (org-cdlatex-mode 1))
18668 (defun org-try-cdlatex-tab ()
18669 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18670 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18671 - inside a LaTeX fragment, or
18672 - after the first word in a line, where an abbreviation expansion could
18673 insert a LaTeX environment."
18674 (when org-cdlatex-mode
18675 (cond
18676 ;; Before any word on the line: No expansion possible.
18677 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18678 ;; Just after first word on the line: Expand it. Make sure it
18679 ;; cannot happen on headlines, though.
18680 ((save-excursion
18681 (skip-chars-backward "a-zA-Z0-9*")
18682 (skip-chars-backward " \t")
18683 (and (bolp) (not (org-at-heading-p))))
18684 (cdlatex-tab) t)
18685 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18687 (defun org-cdlatex-underscore-caret (&optional _arg)
18688 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18689 Revert to the normal definition outside of these fragments."
18690 (interactive "P")
18691 (if (org-inside-LaTeX-fragment-p)
18692 (call-interactively 'cdlatex-sub-superscript)
18693 (let (org-cdlatex-mode)
18694 (call-interactively (key-binding (vector last-input-event))))))
18696 (defun org-cdlatex-math-modify (&optional _arg)
18697 "Execute `cdlatex-math-modify' in LaTeX fragments.
18698 Revert to the normal definition outside of these fragments."
18699 (interactive "P")
18700 (if (org-inside-LaTeX-fragment-p)
18701 (call-interactively 'cdlatex-math-modify)
18702 (let (org-cdlatex-mode)
18703 (call-interactively (key-binding (vector last-input-event))))))
18705 (defun org-cdlatex-environment-indent (&optional environment item)
18706 "Execute `cdlatex-environment' and indent the inserted environment.
18708 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18710 The inserted environment is indented to current indentation
18711 unless point is at the beginning of the line, in which the
18712 environment remains unintended."
18713 (interactive)
18714 ;; cdlatex-environment always return nil. Therefore, capture output
18715 ;; first and determine if an environment was selected.
18716 (let* ((beg (point-marker))
18717 (end (copy-marker (point) t))
18718 (inserted (progn
18719 (ignore-errors (cdlatex-environment environment item))
18720 (< beg end)))
18721 ;; Figure out how many lines to move forward after the
18722 ;; environment has been inserted.
18723 (lines (when inserted
18724 (save-excursion
18725 (- (cl-loop while (< beg (point))
18726 with x = 0
18727 do (forward-line -1)
18728 (cl-incf x)
18729 finally return x)
18730 (if (progn (goto-char beg)
18731 (and (progn (skip-chars-forward " \t") (eolp))
18732 (progn (skip-chars-backward " \t") (bolp))))
18733 1 0)))))
18734 (env (org-trim (delete-and-extract-region beg end))))
18735 (when inserted
18736 ;; Get indentation of next line unless at column 0.
18737 (let ((ind (if (bolp) 0
18738 (save-excursion
18739 (org-return-indent)
18740 (prog1 (org-get-indentation)
18741 (when (progn (skip-chars-forward " \t") (eolp))
18742 (delete-region beg (point)))))))
18743 (bol (progn (skip-chars-backward " \t") (bolp))))
18744 ;; Insert a newline before environment unless at column zero
18745 ;; to "escape" the current line. Insert a newline if
18746 ;; something is one the same line as \end{ENVIRONMENT}.
18747 (insert
18748 (concat (unless bol "\n") env
18749 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18750 (unless (zerop ind)
18751 (save-excursion
18752 (goto-char beg)
18753 (while (< (point) end)
18754 (unless (eolp) (indent-line-to ind))
18755 (forward-line))))
18756 (goto-char beg)
18757 (forward-line lines)
18758 (indent-line-to ind)))
18759 (set-marker beg nil)
18760 (set-marker end nil)))
18763 ;;;; LaTeX fragments
18765 (defun org-inside-LaTeX-fragment-p ()
18766 "Test if point is inside a LaTeX fragment.
18767 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18768 sequence appearing also before point.
18769 Even though the matchers for math are configurable, this function assumes
18770 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18771 delimiters are skipped when they have been removed by customization.
18772 The return value is nil, or a cons cell with the delimiter and the
18773 position of this delimiter.
18775 This function does a reasonably good job, but can locally be fooled by
18776 for example currency specifications. For example it will assume being in
18777 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18778 fragments that are properly closed, but during editing, we have to live
18779 with the uncertainty caused by missing closing delimiters. This function
18780 looks only before point, not after."
18781 (catch 'exit
18782 (let ((pos (point))
18783 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18784 (lim (progn
18785 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18786 (point)))
18787 dd-on str (start 0) m re)
18788 (goto-char pos)
18789 (when dodollar
18790 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18791 re (nth 1 (assoc "$" org-latex-regexps)))
18792 (while (string-match re str start)
18793 (cond
18794 ((= (match-end 0) (length str))
18795 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18796 ((= (match-end 0) (- (length str) 5))
18797 (throw 'exit nil))
18798 (t (setq start (match-end 0))))))
18799 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18800 (goto-char pos)
18801 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18802 (and (match-beginning 2) (throw 'exit nil))
18803 ;; count $$
18804 (while (re-search-backward "\\$\\$" lim t)
18805 (setq dd-on (not dd-on)))
18806 (goto-char pos)
18807 (when dd-on (cons "$$" m))))))
18809 (defun org-inside-latex-macro-p ()
18810 "Is point inside a LaTeX macro or its arguments?"
18811 (save-match-data
18812 (org-in-regexp
18813 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18815 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18816 "Build an overlay between BEG and END using IMAGE file.
18817 Argument IMAGETYPE is the extension of the displayed image,
18818 as a string. It defaults to \"png\"."
18819 (let ((ov (make-overlay beg end))
18820 (imagetype (or (intern imagetype) 'png)))
18821 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18822 (overlay-put ov 'evaporate t)
18823 (overlay-put ov
18824 'modification-hooks
18825 (list (lambda (o _flag _beg _end &optional _l)
18826 (delete-overlay o))))
18827 (overlay-put ov
18828 'display
18829 (list 'image :type imagetype :file image :ascent 'center))))
18831 (defun org--list-latex-overlays (&optional beg end)
18832 "List all Org LaTeX overlays in current buffer.
18833 Limit to overlays between BEG and END when those are provided."
18834 (cl-remove-if-not
18835 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18836 (overlays-in (or beg (point-min)) (or end (point-max)))))
18838 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18839 "Remove all overlays with LaTeX fragment images in current buffer.
18840 When optional arguments BEG and END are non-nil, remove all
18841 overlays between them instead. Return a non-nil value when some
18842 overlays were removed, nil otherwise."
18843 (let ((overlays (org--list-latex-overlays beg end)))
18844 (mapc #'delete-overlay overlays)
18845 overlays))
18847 (defun org-toggle-latex-fragment (&optional arg)
18848 "Preview the LaTeX fragment at point, or all locally or globally.
18850 If the cursor is on a LaTeX fragment, create the image and overlay
18851 it over the source code, if there is none. Remove it otherwise.
18852 If there is no fragment at point, display all fragments in the
18853 current section.
18855 With prefix ARG, preview or clear image for all fragments in the
18856 current subtree or in the whole buffer when used before the first
18857 headline. With a prefix ARG `\\[universal-argument] \
18858 \\[universal-argument]' preview or clear images
18859 for all fragments in the buffer."
18860 (interactive "P")
18861 (when (display-graphic-p)
18862 (catch 'exit
18863 (save-excursion
18864 (let (beg end msg)
18865 (cond
18866 ((or (equal arg '(16))
18867 (and (equal arg '(4))
18868 (org-with-limited-levels (org-before-first-heading-p))))
18869 (if (org-remove-latex-fragment-image-overlays)
18870 (progn (message "LaTeX fragments images removed from buffer")
18871 (throw 'exit nil))
18872 (setq msg "Creating images for buffer...")))
18873 ((equal arg '(4))
18874 (org-with-limited-levels (org-back-to-heading t))
18875 (setq beg (point))
18876 (setq end (progn (org-end-of-subtree t) (point)))
18877 (if (org-remove-latex-fragment-image-overlays beg end)
18878 (progn
18879 (message "LaTeX fragment images removed from subtree")
18880 (throw 'exit nil))
18881 (setq msg "Creating images for subtree...")))
18882 ((let ((datum (org-element-context)))
18883 (when (memq (org-element-type datum)
18884 '(latex-environment latex-fragment))
18885 (setq beg (org-element-property :begin datum))
18886 (setq end (org-element-property :end datum))
18887 (if (org-remove-latex-fragment-image-overlays beg end)
18888 (progn (message "LaTeX fragment image removed")
18889 (throw 'exit nil))
18890 (setq msg "Creating image...")))))
18892 (org-with-limited-levels
18893 (setq beg (if (org-at-heading-p) (line-beginning-position)
18894 (outline-previous-heading)
18895 (point)))
18896 (setq end (progn (outline-next-heading) (point)))
18897 (if (org-remove-latex-fragment-image-overlays beg end)
18898 (progn
18899 (message "LaTeX fragment images removed from section")
18900 (throw 'exit nil))
18901 (setq msg "Creating images for section...")))))
18902 (let ((file (buffer-file-name (buffer-base-buffer))))
18903 (org-format-latex
18904 (concat org-preview-latex-image-directory "org-ltximg")
18905 beg end
18906 ;; Emacs cannot overlay images from remote hosts. Create
18907 ;; it in `temporary-file-directory' instead.
18908 (if (or (not file) (file-remote-p file))
18909 temporary-file-directory
18910 default-directory)
18911 'overlays msg 'forbuffer org-preview-latex-default-process))
18912 (message (concat msg "done")))))))
18914 (defun org-format-latex
18915 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18916 "Replace LaTeX fragments with links to an image.
18918 The function takes care of creating the replacement image.
18920 Only consider fragments between BEG and END when those are
18921 provided.
18923 When optional argument OVERLAYS is non-nil, display the image on
18924 top of the fragment instead of replacing it.
18926 PROCESSING-TYPE is the conversion method to use, as a symbol.
18928 Some of the options can be changed using the variable
18929 `org-format-latex-options', which see."
18930 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18931 (unless (eq processing-type 'verbatim)
18932 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18933 (cnt 0)
18934 checkdir-flag)
18935 (goto-char (or beg (point-min)))
18936 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18937 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18938 (overlay-recenter (or end (point-max))))
18939 (while (re-search-forward math-regexp end t)
18940 (unless (and overlays
18941 (eq (get-char-property (point) 'org-overlay-type)
18942 'org-latex-overlay))
18943 (let* ((context (org-element-context))
18944 (type (org-element-type context)))
18945 (when (memq type '(latex-environment latex-fragment))
18946 (let ((block-type (eq type 'latex-environment))
18947 (value (org-element-property :value context))
18948 (beg (org-element-property :begin context))
18949 (end (save-excursion
18950 (goto-char (org-element-property :end context))
18951 (skip-chars-backward " \r\t\n")
18952 (point))))
18953 (cond
18954 ((eq processing-type 'mathjax)
18955 ;; Prepare for MathJax processing.
18956 (if (not (string-match "\\`\\$\\$?" value))
18957 (goto-char end)
18958 (delete-region beg end)
18959 (if (string= (match-string 0 value) "$$")
18960 (insert "\\[" (substring value 2 -2) "\\]")
18961 (insert "\\(" (substring value 1 -1) "\\)"))))
18962 ((assq processing-type org-preview-latex-process-alist)
18963 ;; Process to an image.
18964 (cl-incf cnt)
18965 (goto-char beg)
18966 (let* ((processing-info
18967 (cdr (assq processing-type org-preview-latex-process-alist)))
18968 (face (face-at-point))
18969 ;; Get the colors from the face at point.
18971 (let ((color (plist-get org-format-latex-options
18972 :foreground)))
18973 (if (and forbuffer (eq color 'auto))
18974 (face-attribute face :foreground nil 'default)
18975 color)))
18977 (let ((color (plist-get org-format-latex-options
18978 :background)))
18979 (if (and forbuffer (eq color 'auto))
18980 (face-attribute face :background nil 'default)
18981 color)))
18982 (hash (sha1 (prin1-to-string
18983 (list org-format-latex-header
18984 org-latex-default-packages-alist
18985 org-latex-packages-alist
18986 org-format-latex-options
18987 forbuffer value fg bg))))
18988 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18989 (absprefix (expand-file-name prefix dir))
18990 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18991 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18992 (sep (and block-type "\n\n"))
18993 (link (concat sep "[[file:" linkfile "]]" sep))
18994 (options
18995 (org-combine-plists
18996 org-format-latex-options
18997 `(:foreground ,fg :background ,bg))))
18998 (when msg (message msg cnt))
18999 (unless checkdir-flag ; Ensure the directory exists.
19000 (setq checkdir-flag t)
19001 (let ((todir (file-name-directory absprefix)))
19002 (unless (file-directory-p todir)
19003 (make-directory todir t))))
19004 (unless (file-exists-p movefile)
19005 (org-create-formula-image
19006 value movefile options forbuffer processing-type))
19007 (if overlays
19008 (progn
19009 (dolist (o (overlays-in beg end))
19010 (when (eq (overlay-get o 'org-overlay-type)
19011 'org-latex-overlay)
19012 (delete-overlay o)))
19013 (org--format-latex-make-overlay beg end movefile imagetype)
19014 (goto-char end))
19015 (delete-region beg end)
19016 (insert
19017 (org-add-props link
19018 (list 'org-latex-src
19019 (replace-regexp-in-string "\"" "" value)
19020 'org-latex-src-embed-type
19021 (if block-type 'paragraph 'character)))))))
19022 ((eq processing-type 'mathml)
19023 ;; Process to MathML.
19024 (unless (org-format-latex-mathml-available-p)
19025 (user-error "LaTeX to MathML converter not configured"))
19026 (cl-incf cnt)
19027 (when msg (message msg cnt))
19028 (goto-char beg)
19029 (delete-region beg end)
19030 (insert (org-format-latex-as-mathml
19031 value block-type prefix dir)))
19033 (error "Unknown conversion process %s for LaTeX fragments"
19034 processing-type)))))))))))
19036 (defun org-create-math-formula (latex-frag &optional mathml-file)
19037 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19038 Use `org-latex-to-mathml-convert-command'. If the conversion is
19039 sucessful, return the portion between \"<math...> </math>\"
19040 elements otherwise return nil. When MATHML-FILE is specified,
19041 write the results in to that file. When invoked as an
19042 interactive command, prompt for LATEX-FRAG, with initial value
19043 set to the current active region and echo the results for user
19044 inspection."
19045 (interactive (list (let ((frag (when (org-region-active-p)
19046 (buffer-substring-no-properties
19047 (region-beginning) (region-end)))))
19048 (read-string "LaTeX Fragment: " frag nil frag))))
19049 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19050 (let* ((tmp-in-file
19051 (let ((file (file-relative-name
19052 (make-temp-name (expand-file-name "ltxmathml-in")))))
19053 (write-region latex-frag nil file)
19054 file))
19055 (tmp-out-file (file-relative-name
19056 (make-temp-name (expand-file-name "ltxmathml-out"))))
19057 (cmd (format-spec
19058 org-latex-to-mathml-convert-command
19059 `((?j . ,(and org-latex-to-mathml-jar-file
19060 (shell-quote-argument
19061 (expand-file-name
19062 org-latex-to-mathml-jar-file))))
19063 (?I . ,(shell-quote-argument tmp-in-file))
19064 (?i . ,latex-frag)
19065 (?o . ,(shell-quote-argument tmp-out-file)))))
19066 mathml shell-command-output)
19067 (when (called-interactively-p 'any)
19068 (unless (org-format-latex-mathml-available-p)
19069 (user-error "LaTeX to MathML converter not configured")))
19070 (message "Running %s" cmd)
19071 (setq shell-command-output (shell-command-to-string cmd))
19072 (setq mathml
19073 (when (file-readable-p tmp-out-file)
19074 (with-current-buffer (find-file-noselect tmp-out-file t)
19075 (goto-char (point-min))
19076 (when (re-search-forward
19077 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19078 (regexp-quote
19079 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19080 nil t)
19081 (prog1 (match-string 0) (kill-buffer))))))
19082 (cond
19083 (mathml
19084 (setq mathml
19085 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19086 (when mathml-file
19087 (write-region mathml nil mathml-file))
19088 (when (called-interactively-p 'any)
19089 (message mathml)))
19090 ((message "LaTeX to MathML conversion failed")
19091 (message shell-command-output)))
19092 (delete-file tmp-in-file)
19093 (when (file-exists-p tmp-out-file)
19094 (delete-file tmp-out-file))
19095 mathml))
19097 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19098 prefix &optional dir)
19099 "Use `org-create-math-formula' but check local cache first."
19100 (let* ((absprefix (expand-file-name prefix dir))
19101 (print-length nil) (print-level nil)
19102 (formula-id (concat
19103 "formula-"
19104 (sha1
19105 (prin1-to-string
19106 (list latex-frag
19107 org-latex-to-mathml-convert-command)))))
19108 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19109 (formula-cache-dir (file-name-directory formula-cache)))
19111 (unless (file-directory-p formula-cache-dir)
19112 (make-directory formula-cache-dir t))
19114 (unless (file-exists-p formula-cache)
19115 (org-create-math-formula latex-frag formula-cache))
19117 (if (file-exists-p formula-cache)
19118 ;; Successful conversion. Return the link to MathML file.
19119 (org-add-props
19120 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19121 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19122 'org-latex-src-embed-type (if latex-frag-type
19123 'paragraph 'character)))
19124 ;; Failed conversion. Return the LaTeX fragment verbatim
19125 latex-frag)))
19127 (defun org--get-display-dpi ()
19128 "Get the DPI of the display.
19129 The function assumes that the display has the same pixel width in
19130 the horizontal and vertical directions."
19131 (if (display-graphic-p)
19132 (round (/ (display-pixel-height)
19133 (/ (display-mm-height) 25.4)))
19134 (error "Attempt to calculate the dpi of a non-graphic display")))
19136 (defun org-create-formula-image
19137 (string tofile options buffer &optional processing-type)
19138 "Create an image from LaTeX source using external processes.
19140 The LaTeX STRING is saved to a temporary LaTeX file, then
19141 converted to an image file by process PROCESSING-TYPE defined in
19142 `org-preview-latex-process-alist'. A nil value defaults to
19143 `org-preview-latex-default-process'.
19145 The generated image file is eventually moved to TOFILE.
19147 The OPTIONS argument controls the size, foreground color and
19148 background color of the generated image.
19150 When BUFFER non-nil, this function is used for LaTeX previewing.
19151 Otherwise, it is used to deal with LaTeX snippets showed in
19152 a HTML file."
19153 (let* ((processing-type (or processing-type
19154 org-preview-latex-default-process))
19155 (processing-info
19156 (cdr (assq processing-type org-preview-latex-process-alist)))
19157 (programs (plist-get processing-info :programs))
19158 (error-message (or (plist-get processing-info :message) ""))
19159 (use-xcolor (plist-get processing-info :use-xcolor))
19160 (image-input-type (plist-get processing-info :image-input-type))
19161 (image-output-type (plist-get processing-info :image-output-type))
19162 (post-clean (or (plist-get processing-info :post-clean)
19163 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19164 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19165 (latex-header
19166 (or (plist-get processing-info :latex-header)
19167 (org-latex-make-preamble
19168 (org-export-get-environment (org-export-get-backend 'latex))
19169 org-format-latex-header
19170 'snippet)))
19171 (latex-compiler (plist-get processing-info :latex-compiler))
19172 (image-converter (plist-get processing-info :image-converter))
19173 (tmpdir temporary-file-directory)
19174 (texfilebase (make-temp-name
19175 (expand-file-name "orgtex" tmpdir)))
19176 (texfile (concat texfilebase ".tex"))
19177 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19178 '(1.0 . 1.0)))
19179 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19180 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19181 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19182 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19183 "Black"))
19184 (bg (or (plist-get options (if buffer :background :html-background))
19185 "Transparent"))
19186 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19187 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19188 (dolist (program programs)
19189 (org-check-external-command program error-message))
19190 (if use-xcolor
19191 (progn (if (eq fg 'default)
19192 (setq fg (org-latex-color :foreground))
19193 (setq fg (org-latex-color-format fg)))
19194 (if (eq bg 'default)
19195 (setq bg (org-latex-color :background))
19196 (setq bg (org-latex-color-format
19197 (if (string= bg "Transparent") "white" bg))))
19198 (with-temp-file texfile
19199 (insert latex-header)
19200 (insert "\n\\begin{document}\n"
19201 "\\definecolor{fg}{rgb}{" fg "}\n"
19202 "\\definecolor{bg}{rgb}{" bg "}\n"
19203 "\n\\pagecolor{bg}\n"
19204 "\n{\\color{fg}\n"
19205 string
19206 "\n}\n"
19207 "\n\\end{document}\n")))
19208 (if (eq fg 'default)
19209 (setq fg (org-dvipng-color :foreground))
19210 (unless (string= fg "Transparent")
19211 (setq fg (org-dvipng-color-format fg))))
19212 (if (eq bg 'default)
19213 (setq bg (org-dvipng-color :background))
19214 (unless (string= bg "Transparent")
19215 (setq bg (org-dvipng-color-format bg))))
19216 (with-temp-file texfile
19217 (insert latex-header)
19218 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19220 (let* ((err-msg (format "Please adjust '%s' part of \
19221 `org-preview-latex-process-alist'."
19222 processing-type))
19223 (image-input-file
19224 (org-compile-file
19225 texfile latex-compiler image-input-type err-msg log-buf))
19226 (image-output-file
19227 (org-compile-file
19228 image-input-file image-converter image-output-type err-msg log-buf
19229 `((?F . ,(shell-quote-argument fg))
19230 (?B . ,(shell-quote-argument bg))
19231 (?D . ,(shell-quote-argument (format "%s" dpi)))
19232 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19233 (copy-file image-output-file tofile 'replace)
19234 (dolist (e post-clean)
19235 (when (file-exists-p (concat texfilebase e))
19236 (delete-file (concat texfilebase e))))
19237 image-output-file)))
19239 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19240 "Fill a LaTeX header template TPL.
19241 In the template, the following place holders will be recognized:
19243 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19244 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19245 [PACKAGES] \\usepackage statements for PKG
19246 [NO-PACKAGES] do not include PKG
19247 [EXTRA] the string EXTRA
19248 [NO-EXTRA] do not include EXTRA
19250 For backward compatibility, if both the positive and the negative place
19251 holder is missing, the positive one (without the \"NO-\") will be
19252 assumed to be present at the end of the template.
19253 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19254 EXTRA is a string.
19255 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19256 (let (rpl (end ""))
19257 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19258 (setq rpl (if (or (match-end 1) (not def-pkg))
19259 "" (org-latex-packages-to-string def-pkg snippets-p t))
19260 tpl (replace-match rpl t t tpl))
19261 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19263 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19264 (setq rpl (if (or (match-end 1) (not pkg))
19265 "" (org-latex-packages-to-string pkg snippets-p t))
19266 tpl (replace-match rpl t t tpl))
19267 (when pkg (setq end
19268 (concat end "\n"
19269 (org-latex-packages-to-string pkg snippets-p)))))
19271 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19272 (setq rpl (if (or (match-end 1) (not extra))
19273 "" (concat extra "\n"))
19274 tpl (replace-match rpl t t tpl))
19275 (when (and extra (string-match "\\S-" extra))
19276 (setq end (concat end "\n" extra))))
19278 (if (string-match "\\S-" end)
19279 (concat tpl "\n" end)
19280 tpl)))
19282 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19283 "Turn an alist of packages into a string with the \\usepackage macros."
19284 (setq pkg (mapconcat (lambda(p)
19285 (cond
19286 ((stringp p) p)
19287 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19288 (format "%% Package %s omitted" (cadr p)))
19289 ((equal "" (car p))
19290 (format "\\usepackage{%s}" (cadr p)))
19292 (format "\\usepackage[%s]{%s}"
19293 (car p) (cadr p)))))
19295 "\n"))
19296 (if newline (concat pkg "\n") pkg))
19298 (defun org-dvipng-color (attr)
19299 "Return a RGB color specification for dvipng."
19300 (org-dvipng-color-format (face-attribute 'default attr nil)))
19302 (defun org-dvipng-color-format (color-name)
19303 "Convert COLOR-NAME to a RGB color value for dvipng."
19304 (apply #'format "rgb %s %s %s"
19305 (mapcar 'org-normalize-color
19306 (color-values color-name))))
19308 (defun org-latex-color (attr)
19309 "Return a RGB color for the LaTeX color package."
19310 (org-latex-color-format (face-attribute 'default attr nil)))
19312 (defun org-latex-color-format (color-name)
19313 "Convert COLOR-NAME to a RGB color value."
19314 (apply #'format "%s,%s,%s"
19315 (mapcar 'org-normalize-color
19316 (color-values color-name))))
19318 (defun org-normalize-color (value)
19319 "Return string to be used as color value for an RGB component."
19320 (format "%g" (/ value 65535.0)))
19324 ;; Image display
19326 (defvar-local org-inline-image-overlays nil)
19328 (defun org-toggle-inline-images (&optional include-linked)
19329 "Toggle the display of inline images.
19330 INCLUDE-LINKED is passed to `org-display-inline-images'."
19331 (interactive "P")
19332 (if org-inline-image-overlays
19333 (progn
19334 (org-remove-inline-images)
19335 (when (called-interactively-p 'interactive)
19336 (message "Inline image display turned off")))
19337 (org-display-inline-images include-linked)
19338 (when (called-interactively-p 'interactive)
19339 (message (if org-inline-image-overlays
19340 (format "%d images displayed inline"
19341 (length org-inline-image-overlays))
19342 "No images to display inline")))))
19344 (defun org-redisplay-inline-images ()
19345 "Refresh the display of inline images."
19346 (interactive)
19347 (if (not org-inline-image-overlays)
19348 (org-toggle-inline-images)
19349 (org-toggle-inline-images)
19350 (org-toggle-inline-images)))
19352 (defun org-display-inline-images (&optional include-linked refresh beg end)
19353 "Display inline images.
19355 An inline image is a link which follows either of these
19356 conventions:
19358 1. Its path is a file with an extension matching return value
19359 from `image-file-name-regexp' and it has no contents.
19361 2. Its description consists in a single link of the previous
19362 type.
19364 When optional argument INCLUDE-LINKED is non-nil, also links with
19365 a text description part will be inlined. This can be nice for
19366 a quick look at those images, but it does not reflect what
19367 exported files will look like.
19369 When optional argument REFRESH is non-nil, refresh existing
19370 images between BEG and END. This will create new image displays
19371 only if necessary. BEG and END default to the buffer
19372 boundaries."
19373 (interactive "P")
19374 (when (display-graphic-p)
19375 (unless refresh
19376 (org-remove-inline-images)
19377 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19378 (org-with-wide-buffer
19379 (goto-char (or beg (point-min)))
19380 (let ((case-fold-search t)
19381 (file-extension-re (image-file-name-regexp)))
19382 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19383 (let ((link (save-match-data (org-element-context))))
19384 ;; Check if we're at an inline image.
19385 (when (and (equal (org-element-property :type link) "file")
19386 (or include-linked
19387 (not (org-element-property :contents-begin link)))
19388 (let ((parent (org-element-property :parent link)))
19389 (or (not (eq (org-element-type parent) 'link))
19390 (not (cdr (org-element-contents parent)))))
19391 (string-match-p file-extension-re
19392 (org-element-property :path link)))
19393 (let ((file (expand-file-name
19394 (org-link-unescape
19395 (org-element-property :path link)))))
19396 (when (file-exists-p file)
19397 (let ((width
19398 ;; Apply `org-image-actual-width' specifications.
19399 (cond
19400 ((not (image-type-available-p 'imagemagick)) nil)
19401 ((eq org-image-actual-width t) nil)
19402 ((listp org-image-actual-width)
19404 ;; First try to find a width among
19405 ;; attributes associated to the paragraph
19406 ;; containing link.
19407 (let ((paragraph
19408 (let ((e link))
19409 (while (and (setq e (org-element-property
19410 :parent e))
19411 (not (eq (org-element-type e)
19412 'paragraph))))
19413 e)))
19414 (when paragraph
19415 (save-excursion
19416 (goto-char (org-element-property :begin paragraph))
19417 (when
19418 (re-search-forward
19419 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19420 (org-element-property
19421 :post-affiliated paragraph)
19423 (string-to-number (match-string 1))))))
19424 ;; Otherwise, fall-back to provided number.
19425 (car org-image-actual-width)))
19426 ((numberp org-image-actual-width)
19427 org-image-actual-width)))
19428 (old (get-char-property-and-overlay
19429 (org-element-property :begin link)
19430 'org-image-overlay)))
19431 (if (and (car-safe old) refresh)
19432 (image-refresh (overlay-get (cdr old) 'display))
19433 (let ((image (create-image file
19434 (and width 'imagemagick)
19436 :width width)))
19437 (when image
19438 (let* ((link
19439 ;; If inline image is the description
19440 ;; of another link, be sure to
19441 ;; consider the latter as the one to
19442 ;; apply the overlay on.
19443 (let ((parent
19444 (org-element-property :parent link)))
19445 (if (eq (org-element-type parent) 'link)
19446 parent
19447 link)))
19448 (ov (make-overlay
19449 (org-element-property :begin link)
19450 (progn
19451 (goto-char
19452 (org-element-property :end link))
19453 (skip-chars-backward " \t")
19454 (point)))))
19455 (overlay-put ov 'display image)
19456 (overlay-put ov 'face 'default)
19457 (overlay-put ov 'org-image-overlay t)
19458 (overlay-put
19459 ov 'modification-hooks
19460 (list 'org-display-inline-remove-overlay))
19461 (push ov org-inline-image-overlays)))))))))))))))
19463 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19464 "Remove inline-display overlay if a corresponding region is modified."
19465 (let ((inhibit-modification-hooks t))
19466 (when (and ov after)
19467 (delete ov org-inline-image-overlays)
19468 (delete-overlay ov))))
19470 (defun org-remove-inline-images ()
19471 "Remove inline display of images."
19472 (interactive)
19473 (mapc #'delete-overlay org-inline-image-overlays)
19474 (setq org-inline-image-overlays nil))
19476 ;;;; Key bindings
19478 ;; Outline functions from `outline-mode-prefix-map'
19479 ;; that can be remapped in Org:
19480 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19481 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19482 (define-key org-mode-map [remap outline-forward-same-level]
19483 'org-forward-heading-same-level)
19484 (define-key org-mode-map [remap outline-backward-same-level]
19485 'org-backward-heading-same-level)
19486 (define-key org-mode-map [remap outline-show-branches]
19487 'org-kill-note-or-show-branches)
19488 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19489 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19490 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19491 (define-key org-mode-map [remap outline-next-visible-heading]
19492 'org-next-visible-heading)
19493 (define-key org-mode-map [remap outline-previous-visible-heading]
19494 'org-previous-visible-heading)
19495 (define-key org-mode-map [remap show-children] 'org-show-children)
19497 ;; Outline functions from `outline-mode-prefix-map' that can not
19498 ;; be remapped in Org:
19500 ;; - the column "key binding" shows whether the Outline function is still
19501 ;; available in Org mode on the same key that it has been bound to in
19502 ;; Outline mode:
19503 ;; - "overridden": key used for a different functionality in Org mode
19504 ;; - else: key still bound to the same Outline function in Org mode
19506 ;; | Outline function | key binding | Org replacement |
19507 ;; |------------------------------------+-------------+--------------------------|
19508 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19509 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19510 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19511 ;; | `show-entry' | overridden | no replacement |
19512 ;; | `show-branches' | `C-c C-k' | still same function |
19513 ;; | `show-subtree' | overridden | visibility cycling |
19514 ;; | `show-all' | overridden | no replacement |
19515 ;; | `hide-subtree' | overridden | visibility cycling |
19516 ;; | `hide-body' | overridden | no replacement |
19517 ;; | `hide-entry' | overridden | visibility cycling |
19518 ;; | `hide-leaves' | overridden | no replacement |
19519 ;; | `hide-sublevels' | overridden | no replacement |
19520 ;; | `hide-other' | overridden | no replacement |
19522 ;; Make `C-c C-x' a prefix key
19523 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19525 ;; TAB key with modifiers
19526 (org-defkey org-mode-map "\C-i" 'org-cycle)
19527 (org-defkey org-mode-map [(tab)] 'org-cycle)
19528 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19529 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19530 ;; The following line is necessary under Suse GNU/Linux
19531 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19532 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19533 (define-key org-mode-map [backtab] 'org-shifttab)
19535 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19536 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19537 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19539 ;; Cursor keys with modifiers
19540 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19541 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19542 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19543 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19545 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19546 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19547 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19548 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19549 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19550 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19552 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19553 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19554 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19555 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19557 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19558 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19559 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19560 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19562 ;; Babel keys
19563 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19564 (dolist (pair org-babel-key-bindings)
19565 (define-key org-babel-map (car pair) (cdr pair)))
19567 ;;; Extra keys for tty access.
19568 ;; We only set them when really needed because otherwise the
19569 ;; menus don't show the simple keys
19571 (when (or org-use-extra-keys (not window-system))
19572 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19573 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19574 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19575 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19576 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19577 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19578 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19579 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19580 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19581 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19582 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19583 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19584 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19585 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19586 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19587 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19588 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19589 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19590 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19591 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19592 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19593 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19594 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19595 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19596 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19597 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19598 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19599 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19601 ;; All the other keys
19603 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19604 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19605 (if (boundp 'narrow-map)
19606 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19607 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19608 (if (boundp 'narrow-map)
19609 (org-defkey narrow-map "b" 'org-narrow-to-block)
19610 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19611 (if (boundp 'narrow-map)
19612 (org-defkey narrow-map "e" 'org-narrow-to-element)
19613 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19614 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19615 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19616 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19617 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19618 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19619 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19620 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19621 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19622 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19623 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19624 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19625 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19626 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19627 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19628 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19629 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19630 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19631 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19632 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19633 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19634 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19635 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19636 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19637 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19638 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19639 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19640 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19641 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19642 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19643 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19644 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19645 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19646 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19647 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19648 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19649 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19650 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19651 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19652 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19653 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19654 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19655 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19656 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19657 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19658 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19659 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19660 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19661 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19662 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19663 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19664 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19665 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19666 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19667 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19668 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19669 (org-defkey org-mode-map "\C-c^" 'org-sort)
19670 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19671 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19672 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19673 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19674 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19675 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19676 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19677 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19678 (org-defkey org-mode-map "\C-m" 'org-return)
19679 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19680 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19681 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19682 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19683 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19684 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19685 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19686 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19687 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19688 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19689 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19690 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19691 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19692 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19693 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19694 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19695 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19696 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19697 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19698 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19699 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19700 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19701 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19702 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19703 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19705 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19706 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19707 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19709 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19710 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19711 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19712 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19713 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19714 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19715 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19716 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19717 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19718 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19719 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19720 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19721 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19722 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19723 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19724 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19725 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19726 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19727 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19728 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19729 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19730 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19732 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19733 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19734 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19735 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19736 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19738 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19740 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19742 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19743 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19745 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19748 (defconst org-speed-commands-default
19750 ("Outline Navigation")
19751 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19752 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19753 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19754 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19755 ("F" . org-next-block)
19756 ("B" . org-previous-block)
19757 ("u" . (org-speed-move-safe 'outline-up-heading))
19758 ("j" . org-goto)
19759 ("g" . (org-refile t))
19760 ("Outline Visibility")
19761 ("c" . org-cycle)
19762 ("C" . org-shifttab)
19763 (" " . org-display-outline-path)
19764 ("s" . org-narrow-to-subtree)
19765 ("=" . org-columns)
19766 ("Outline Structure Editing")
19767 ("U" . org-metaup)
19768 ("D" . org-metadown)
19769 ("r" . org-metaright)
19770 ("l" . org-metaleft)
19771 ("R" . org-shiftmetaright)
19772 ("L" . org-shiftmetaleft)
19773 ("i" . (progn (forward-char 1) (call-interactively
19774 'org-insert-heading-respect-content)))
19775 ("^" . org-sort)
19776 ("w" . org-refile)
19777 ("a" . org-archive-subtree-default-with-confirmation)
19778 ("@" . org-mark-subtree)
19779 ("#" . org-toggle-comment)
19780 ("Clock Commands")
19781 ("I" . org-clock-in)
19782 ("O" . org-clock-out)
19783 ("Meta Data Editing")
19784 ("t" . org-todo)
19785 ("," . (org-priority))
19786 ("0" . (org-priority ?\ ))
19787 ("1" . (org-priority ?A))
19788 ("2" . (org-priority ?B))
19789 ("3" . (org-priority ?C))
19790 (":" . org-set-tags-command)
19791 ("e" . org-set-effort)
19792 ("E" . org-inc-effort)
19793 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19794 (org-entry-put (point) "APPT_WARNTIME" m)))
19795 ("Agenda Views etc")
19796 ("v" . org-agenda)
19797 ("/" . org-sparse-tree)
19798 ("Misc")
19799 ("o" . org-open-at-point)
19800 ("?" . org-speed-command-help)
19801 ("<" . (org-agenda-set-restriction-lock 'subtree))
19802 (">" . (org-agenda-remove-restriction-lock))
19804 "The default speed commands.")
19806 (defun org-print-speed-command (e)
19807 (if (> (length (car e)) 1)
19808 (progn
19809 (princ "\n")
19810 (princ (car e))
19811 (princ "\n")
19812 (princ (make-string (length (car e)) ?-))
19813 (princ "\n"))
19814 (princ (car e))
19815 (princ " ")
19816 (if (symbolp (cdr e))
19817 (princ (symbol-name (cdr e)))
19818 (prin1 (cdr e)))
19819 (princ "\n")))
19821 (defun org-speed-command-help ()
19822 "Show the available speed commands."
19823 (interactive)
19824 (if (not org-use-speed-commands)
19825 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19826 (with-output-to-temp-buffer "*Help*"
19827 (princ "User-defined Speed commands\n===========================\n")
19828 (mapc #'org-print-speed-command org-speed-commands-user)
19829 (princ "\n")
19830 (princ "Built-in Speed commands\n=======================\n")
19831 (mapc #'org-print-speed-command org-speed-commands-default))
19832 (with-current-buffer "*Help*"
19833 (setq truncate-lines t))))
19835 (defun org-speed-move-safe (cmd)
19836 "Execute CMD, but make sure that the cursor always ends up in a headline.
19837 If not, return to the original position and throw an error."
19838 (interactive)
19839 (let ((pos (point)))
19840 (call-interactively cmd)
19841 (unless (and (bolp) (org-at-heading-p))
19842 (goto-char pos)
19843 (error "Boundary reached while executing %s" cmd))))
19845 (defvar org-self-insert-command-undo-counter 0)
19847 (defvar org-table-auto-blank-field) ; defined in org-table.el
19848 (defvar org-speed-command nil)
19850 (defun org-speed-command-activate (keys)
19851 "Hook for activating single-letter speed commands.
19852 `org-speed-commands-default' specifies a minimal command set.
19853 Use `org-speed-commands-user' for further customization."
19854 (when (or (and (bolp) (looking-at org-outline-regexp))
19855 (and (functionp org-use-speed-commands)
19856 (funcall org-use-speed-commands)))
19857 (cdr (assoc keys (append org-speed-commands-user
19858 org-speed-commands-default)))))
19860 (defun org-babel-speed-command-activate (keys)
19861 "Hook for activating single-letter code block commands."
19862 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19863 (cdr (assoc keys org-babel-key-bindings))))
19865 (defcustom org-speed-command-hook
19866 '(org-speed-command-activate org-babel-speed-command-activate)
19867 "Hook for activating speed commands at strategic locations.
19868 Hook functions are called in sequence until a valid handler is
19869 found.
19871 Each hook takes a single argument, a user-pressed command key
19872 which is also a `self-insert-command' from the global map.
19874 Within the hook, examine the cursor position and the command key
19875 and return nil or a valid handler as appropriate. Handler could
19876 be one of an interactive command, a function, or a form.
19878 Set `org-use-speed-commands' to non-nil value to enable this
19879 hook. The default setting is `org-speed-command-activate'."
19880 :group 'org-structure
19881 :version "24.1"
19882 :type 'hook)
19884 (defun org-self-insert-command (N)
19885 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19886 If the cursor is in a table looking at whitespace, the whitespace is
19887 overwritten, and the table is not marked as requiring realignment."
19888 (interactive "p")
19889 (org-check-before-invisible-edit 'insert)
19890 (cond
19891 ((and org-use-speed-commands
19892 (let ((kv (this-command-keys-vector)))
19893 (setq org-speed-command
19894 (run-hook-with-args-until-success
19895 'org-speed-command-hook
19896 (make-string 1 (aref kv (1- (length kv))))))))
19897 (cond
19898 ((commandp org-speed-command)
19899 (setq this-command org-speed-command)
19900 (call-interactively org-speed-command))
19901 ((functionp org-speed-command)
19902 (funcall org-speed-command))
19903 ((and org-speed-command (listp org-speed-command))
19904 (eval org-speed-command))
19905 (t (let (org-use-speed-commands)
19906 (call-interactively 'org-self-insert-command)))))
19907 ((and
19908 (org-at-table-p)
19909 (progn
19910 ;; Check if we blank the field, and if that triggers align.
19911 (and (featurep 'org-table) org-table-auto-blank-field
19912 (memq last-command
19913 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19914 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19915 ;; Got extra space, this field does not determine
19916 ;; column width.
19917 (let (org-table-may-need-update) (org-table-blank-field))
19918 ;; No extra space, this field may determine column
19919 ;; width.
19920 (org-table-blank-field)))
19922 (eq N 1)
19923 (looking-at "[^|\n]* \\( \\)|"))
19924 ;; There is room for insertion without re-aligning the table.
19925 (delete-region (match-beginning 1) (match-end 1))
19926 (self-insert-command N))
19928 (setq org-table-may-need-update t)
19929 (self-insert-command N)
19930 (org-fix-tags-on-the-fly)
19931 (when org-self-insert-cluster-for-undo
19932 (if (not (eq last-command 'org-self-insert-command))
19933 (setq org-self-insert-command-undo-counter 1)
19934 (if (>= org-self-insert-command-undo-counter 20)
19935 (setq org-self-insert-command-undo-counter 1)
19936 (and (> org-self-insert-command-undo-counter 0)
19937 buffer-undo-list (listp buffer-undo-list)
19938 (not (cadr buffer-undo-list)) ; remove nil entry
19939 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19940 (setq org-self-insert-command-undo-counter
19941 (1+ org-self-insert-command-undo-counter))))))))
19943 (defun org-check-before-invisible-edit (kind)
19944 "Check is editing if kind KIND would be dangerous with invisible text around.
19945 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19946 ;; First, try to get out of here as quickly as possible, to reduce overhead
19947 (when (and org-catch-invisible-edits
19948 (or (not (boundp 'visible-mode)) (not visible-mode))
19949 (or (get-char-property (point) 'invisible)
19950 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19951 ;; OK, we need to take a closer look
19952 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19953 (invisible-before-point (unless (bobp) (get-char-property
19954 (1- (point)) 'invisible)))
19955 (border-and-ok-direction
19957 ;; Check if we are acting predictably before invisible text
19958 (and invisible-at-point (not invisible-before-point)
19959 (memq kind '(insert delete-backward)))
19960 ;; Check if we are acting predictably after invisible text
19961 ;; This works not well, and I have turned it off. It seems
19962 ;; better to always show and stop after invisible text.
19963 ;; (and (not invisible-at-point) invisible-before-point
19964 ;; (memq kind '(insert delete)))
19966 (when (or (memq invisible-at-point '(outline org-hide-block t))
19967 (memq invisible-before-point '(outline org-hide-block t)))
19968 (when (eq org-catch-invisible-edits 'error)
19969 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19970 (if (and org-custom-properties-overlays
19971 (y-or-n-p "Display invisible properties in this buffer? "))
19972 (org-toggle-custom-properties-visibility)
19973 ;; Make the area visible
19974 (save-excursion
19975 (when invisible-before-point
19976 (goto-char (previous-single-char-property-change
19977 (point) 'invisible)))
19978 (outline-show-subtree))
19979 (cond
19980 ((eq org-catch-invisible-edits 'show)
19981 ;; That's it, we do the edit after showing
19982 (message
19983 "Unfolding invisible region around point before editing")
19984 (sit-for 1))
19985 ((and (eq org-catch-invisible-edits 'smart)
19986 border-and-ok-direction)
19987 (message "Unfolding invisible region around point before editing"))
19989 ;; Don't do the edit, make the user repeat it in full visibility
19990 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19992 (defun org-fix-tags-on-the-fly ()
19993 "Align tags in headline at point.
19994 Unlike to `org-set-tags', it ignores region and sorting."
19995 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19996 (org-at-heading-p))
19997 (let ((org-ignore-region t)
19998 (org-tags-sort-function nil))
19999 (org-set-tags nil t))))
20001 (defun org-delete-backward-char (N)
20002 "Like `delete-backward-char', insert whitespace at field end in tables.
20003 When deleting backwards, in tables this function will insert whitespace in
20004 front of the next \"|\" separator, to keep the table aligned. The table will
20005 still be marked for re-alignment if the field did fill the entire column,
20006 because, in this case the deletion might narrow the column."
20007 (interactive "p")
20008 (save-match-data
20009 (org-check-before-invisible-edit 'delete-backward)
20010 (if (and (org-at-table-p)
20011 (eq N 1)
20012 (string-match "|" (buffer-substring (point-at-bol) (point)))
20013 (looking-at ".*?|"))
20014 (let ((pos (point))
20015 (noalign (looking-at "[^|\n\r]* |"))
20016 (c org-table-may-need-update))
20017 (backward-delete-char N)
20018 (unless overwrite-mode
20019 (skip-chars-forward "^|")
20020 (insert " ")
20021 (goto-char (1- pos)))
20022 ;; noalign: if there were two spaces at the end, this field
20023 ;; does not determine the width of the column.
20024 (when noalign (setq org-table-may-need-update c)))
20025 (backward-delete-char N)
20026 (org-fix-tags-on-the-fly))))
20028 (defun org-delete-char (N)
20029 "Like `delete-char', but insert whitespace at field end in tables.
20030 When deleting characters, in tables this function will insert whitespace in
20031 front of the next \"|\" separator, to keep the table aligned. The table will
20032 still be marked for re-alignment if the field did fill the entire column,
20033 because, in this case the deletion might narrow the column."
20034 (interactive "p")
20035 (save-match-data
20036 (org-check-before-invisible-edit 'delete)
20037 (if (and (org-at-table-p)
20038 (not (bolp))
20039 (not (= (char-after) ?|))
20040 (eq N 1))
20041 (if (looking-at ".*?|")
20042 (let ((pos (point))
20043 (noalign (looking-at "[^|\n\r]* |"))
20044 (c org-table-may-need-update))
20045 (replace-match
20046 (concat (substring (match-string 0) 1 -1) " |") nil t)
20047 (goto-char pos)
20048 ;; noalign: if there were two spaces at the end, this field
20049 ;; does not determine the width of the column.
20050 (when noalign (setq org-table-may-need-update c)))
20051 (delete-char N))
20052 (delete-char N)
20053 (org-fix-tags-on-the-fly))))
20055 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20056 (put 'org-self-insert-command 'delete-selection
20057 (lambda ()
20058 (not (run-hook-with-args-until-success
20059 'self-insert-uses-region-functions))))
20060 (put 'orgtbl-self-insert-command 'delete-selection
20061 (lambda ()
20062 (not (run-hook-with-args-until-success
20063 'self-insert-uses-region-functions))))
20064 (put 'org-delete-char 'delete-selection 'supersede)
20065 (put 'org-delete-backward-char 'delete-selection 'supersede)
20066 (put 'org-yank 'delete-selection 'yank)
20068 ;; Make `flyspell-mode' delay after some commands
20069 (put 'org-self-insert-command 'flyspell-delayed t)
20070 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20071 (put 'org-delete-char 'flyspell-delayed t)
20072 (put 'org-delete-backward-char 'flyspell-delayed t)
20074 ;; Make pabbrev-mode expand after Org mode commands
20075 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20076 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20078 (defun org-remap (map &rest commands)
20079 "In MAP, remap the functions given in COMMANDS.
20080 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20081 (let (new old)
20082 (while commands
20083 (setq old (pop commands) new (pop commands))
20084 (org-defkey map (vector 'remap old) new))))
20086 (defun org-transpose-words ()
20087 "Transpose words for Org.
20088 This uses the `org-mode-transpose-word-syntax-table' syntax
20089 table, which interprets characters in `org-emphasis-alist' as
20090 word constituents."
20091 (interactive)
20092 (with-syntax-table org-mode-transpose-word-syntax-table
20093 (call-interactively 'transpose-words)))
20094 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20096 (when (eq org-enable-table-editor 'optimized)
20097 ;; If the user wants maximum table support, we need to hijack
20098 ;; some standard editing functions
20099 (org-remap org-mode-map
20100 'self-insert-command 'org-self-insert-command
20101 'delete-char 'org-delete-char
20102 'delete-backward-char 'org-delete-backward-char)
20103 (org-defkey org-mode-map "|" 'org-force-self-insert))
20105 (defvar org-ctrl-c-ctrl-c-hook nil
20106 "Hook for functions attaching themselves to `C-c C-c'.
20108 This can be used to add additional functionality to the C-c C-c
20109 key which executes context-dependent commands. This hook is run
20110 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20111 run after the last test.
20113 Each function will be called with no arguments. The function
20114 must check if the context is appropriate for it to act. If yes,
20115 it should do its thing and then return a non-nil value. If the
20116 context is wrong, just do nothing and return nil.")
20118 (defvar org-ctrl-c-ctrl-c-final-hook nil
20119 "Hook for functions attaching themselves to `C-c C-c'.
20121 This can be used to add additional functionality to the C-c C-c
20122 key which executes context-dependent commands. This hook is run
20123 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20124 before the first test.
20126 Each function will be called with no arguments. The function
20127 must check if the context is appropriate for it to act. If yes,
20128 it should do its thing and then return a non-nil value. If the
20129 context is wrong, just do nothing and return nil.")
20131 (defvar org-tab-first-hook nil
20132 "Hook for functions to attach themselves to TAB.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.
20134 This hook runs as the first action when TAB is pressed, even before
20135 `org-cycle' messes around with the `outline-regexp' to cater for
20136 inline tasks and plain list item folding.
20137 If any function in this hook returns t, any other actions that
20138 would have been caused by TAB (such as table field motion or visibility
20139 cycling) will not occur.")
20141 (defvar org-tab-after-check-for-table-hook nil
20142 "Hook for functions to attach themselves to TAB.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.
20144 This hook runs after it has been established that the cursor is not in a
20145 table, but before checking if the cursor is in a headline or if global cycling
20146 should be done.
20147 If any function in this hook returns t, not other actions like visibility
20148 cycling will be done.")
20150 (defvar org-tab-after-check-for-cycling-hook nil
20151 "Hook for functions to attach themselves to TAB.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.
20153 This hook runs after it has been established that not table field motion and
20154 not visibility should be done because of current context. This is probably
20155 the place where a package like yasnippets can hook in.")
20157 (defvar org-tab-before-tab-emulation-hook nil
20158 "Hook for functions to attach themselves to TAB.
20159 See `org-ctrl-c-ctrl-c-hook' for more information.
20160 This hook runs after every other options for TAB have been exhausted, but
20161 before indentation and \t insertion takes place.")
20163 (defvar org-metaleft-hook nil
20164 "Hook for functions attaching themselves to `M-left'.
20165 See `org-ctrl-c-ctrl-c-hook' for more information.")
20166 (defvar org-metaright-hook nil
20167 "Hook for functions attaching themselves to `M-right'.
20168 See `org-ctrl-c-ctrl-c-hook' for more information.")
20169 (defvar org-metaup-hook nil
20170 "Hook for functions attaching themselves to `M-up'.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.")
20172 (defvar org-metadown-hook nil
20173 "Hook for functions attaching themselves to `M-down'.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.")
20175 (defvar org-shiftmetaleft-hook nil
20176 "Hook for functions attaching themselves to `M-S-left'.
20177 See `org-ctrl-c-ctrl-c-hook' for more information.")
20178 (defvar org-shiftmetaright-hook nil
20179 "Hook for functions attaching themselves to `M-S-right'.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.")
20181 (defvar org-shiftmetaup-hook nil
20182 "Hook for functions attaching themselves to `M-S-up'.
20183 See `org-ctrl-c-ctrl-c-hook' for more information.")
20184 (defvar org-shiftmetadown-hook nil
20185 "Hook for functions attaching themselves to `M-S-down'.
20186 See `org-ctrl-c-ctrl-c-hook' for more information.")
20187 (defvar org-metareturn-hook nil
20188 "Hook for functions attaching themselves to `M-RET'.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftup-hook nil
20191 "Hook for functions attaching themselves to `S-up'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftup-final-hook nil
20194 "Hook for functions attaching themselves to `S-up'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-shiftdown-hook nil
20198 "Hook for functions attaching themselves to `S-down'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftdown-final-hook nil
20201 "Hook for functions attaching themselves to `S-down'.
20202 This one runs after all other options except shift-select have been excluded.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20204 (defvar org-shiftleft-hook nil
20205 "Hook for functions attaching themselves to `S-left'.
20206 See `org-ctrl-c-ctrl-c-hook' for more information.")
20207 (defvar org-shiftleft-final-hook nil
20208 "Hook for functions attaching themselves to `S-left'.
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-shiftright-hook nil
20212 "Hook for functions attaching themselves to `S-right'.
20213 See `org-ctrl-c-ctrl-c-hook' for more information.")
20214 (defvar org-shiftright-final-hook nil
20215 "Hook for functions attaching themselves to `S-right'.
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.")
20219 (defun org-modifier-cursor-error ()
20220 "Throw an error, a modified cursor command was applied in wrong context."
20221 (user-error "This command is active in special context like tables, headlines or items"))
20223 (defun org-shiftselect-error ()
20224 "Throw an error because Shift-Cursor command was applied in wrong context."
20225 (if (and (boundp 'shift-select-mode) shift-select-mode)
20226 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20227 (user-error "This command works only in special context like headlines or timestamps")))
20229 (defun org-call-for-shift-select (cmd)
20230 (let ((this-command-keys-shift-translated t))
20231 (call-interactively cmd)))
20233 (defun org-shifttab (&optional arg)
20234 "Global visibility cycling or move to previous table field.
20235 Call `org-table-previous-field' within a table.
20236 When ARG is nil, cycle globally through visibility states.
20237 When ARG is a numeric prefix, show contents of this level."
20238 (interactive "P")
20239 (cond
20240 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20241 ((integerp arg)
20242 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20243 (message "Content view to level: %d" arg)
20244 (org-content (prefix-numeric-value arg2))
20245 (org-cycle-show-empty-lines t)
20246 (setq org-cycle-global-status 'overview)))
20247 (t (call-interactively 'org-global-cycle))))
20249 (defun org-shiftmetaleft ()
20250 "Promote subtree or delete table column.
20251 Calls `org-promote-subtree', `org-outdent-item-tree', or
20252 `org-table-delete-column', depending on context. See the
20253 individual commands for more information."
20254 (interactive)
20255 (cond
20256 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20257 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20258 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20259 ((if (not (org-region-active-p)) (org-at-item-p)
20260 (save-excursion (goto-char (region-beginning))
20261 (org-at-item-p)))
20262 (call-interactively 'org-outdent-item-tree))
20263 (t (org-modifier-cursor-error))))
20265 (defun org-shiftmetaright ()
20266 "Demote subtree or insert table column.
20267 Calls `org-demote-subtree', `org-indent-item-tree', or
20268 `org-table-insert-column', depending on context. See the
20269 individual commands for more information."
20270 (interactive)
20271 (cond
20272 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20273 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20274 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20275 ((if (not (org-region-active-p)) (org-at-item-p)
20276 (save-excursion (goto-char (region-beginning))
20277 (org-at-item-p)))
20278 (call-interactively 'org-indent-item-tree))
20279 (t (org-modifier-cursor-error))))
20281 (defun org-shiftmetaup (&optional _arg)
20282 "Drag the line at point up.
20283 In a table, kill the current row.
20284 On a clock timestamp, update the value of the timestamp like `S-<up>'
20285 but also adjust the previous clocked item in the clock history.
20286 Everywhere else, drag the line at point up."
20287 (interactive "P")
20288 (cond
20289 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20290 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20291 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20292 (call-interactively 'org-timestamp-up)))
20293 (t (call-interactively 'org-drag-line-backward))))
20295 (defun org-shiftmetadown (&optional _arg)
20296 "Drag the line at point down.
20297 In a table, insert an empty row at the current line.
20298 On a clock timestamp, update the value of the timestamp like `S-<down>'
20299 but also adjust the previous clocked item in the clock history.
20300 Everywhere else, drag the line at point down."
20301 (interactive "P")
20302 (cond
20303 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20304 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20305 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20306 (call-interactively 'org-timestamp-down)))
20307 (t (call-interactively 'org-drag-line-forward))))
20309 (defsubst org-hidden-tree-error ()
20310 (user-error
20311 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20313 (defun org-metaleft (&optional _arg)
20314 "Promote heading, list item at point or move table column left.
20316 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20317 depending on context. With no specific context, calls the Emacs
20318 default `backward-word'. See the individual commands for more
20319 information.
20321 This function runs the hook `org-metaleft-hook' as a first step,
20322 and returns at first non-nil value."
20323 (interactive "P")
20324 (cond
20325 ((run-hook-with-args-until-success 'org-metaleft-hook))
20326 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20327 ((org-with-limited-levels
20328 (or (org-at-heading-p)
20329 (and (org-region-active-p)
20330 (save-excursion
20331 (goto-char (region-beginning))
20332 (org-at-heading-p)))))
20333 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20334 (call-interactively 'org-do-promote))
20335 ;; At an inline task.
20336 ((org-at-heading-p)
20337 (call-interactively 'org-inlinetask-promote))
20338 ((or (org-at-item-p)
20339 (and (org-region-active-p)
20340 (save-excursion
20341 (goto-char (region-beginning))
20342 (org-at-item-p))))
20343 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20344 (call-interactively 'org-outdent-item))
20345 (t (call-interactively 'backward-word))))
20347 (defun org-metaright (&optional _arg)
20348 "Demote heading, list item at point or move table column right.
20350 In front of a drawer or a block keyword, indent it correctly.
20352 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20353 `org-indent-drawer' or `org-indent-block' depending on context.
20354 With no specific context, calls the Emacs default `forward-word'.
20355 See the individual commands for more information.
20357 This function runs the hook `org-metaright-hook' as a first step,
20358 and returns at first non-nil value."
20359 (interactive "P")
20360 (cond
20361 ((run-hook-with-args-until-success 'org-metaright-hook))
20362 ((org-at-table-p) (call-interactively 'org-table-move-column))
20363 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20364 ((org-at-block-p) (call-interactively 'org-indent-block))
20365 ((org-with-limited-levels
20366 (or (org-at-heading-p)
20367 (and (org-region-active-p)
20368 (save-excursion
20369 (goto-char (region-beginning))
20370 (org-at-heading-p)))))
20371 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20372 (call-interactively 'org-do-demote))
20373 ;; At an inline task.
20374 ((org-at-heading-p)
20375 (call-interactively 'org-inlinetask-demote))
20376 ((or (org-at-item-p)
20377 (and (org-region-active-p)
20378 (save-excursion
20379 (goto-char (region-beginning))
20380 (org-at-item-p))))
20381 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20382 (call-interactively 'org-indent-item))
20383 (t (call-interactively 'forward-word))))
20385 (defun org-check-for-hidden (what)
20386 "Check if there are hidden headlines/items in the current visual line.
20387 WHAT can be either `headlines' or `items'. If the current line is
20388 an outline or item heading and it has a folded subtree below it,
20389 this function returns t, nil otherwise."
20390 (let ((re (cond
20391 ((eq what 'headlines) org-outline-regexp-bol)
20392 ((eq what 'items) (org-item-beginning-re))
20393 (t (error "This should not happen"))))
20394 beg end)
20395 (save-excursion
20396 (catch 'exit
20397 (unless (org-region-active-p)
20398 (setq beg (point-at-bol))
20399 (beginning-of-line 2)
20400 (while (and (not (eobp)) ;; this is like `next-line'
20401 (get-char-property (1- (point)) 'invisible))
20402 (beginning-of-line 2))
20403 (setq end (point))
20404 (goto-char beg)
20405 (goto-char (point-at-eol))
20406 (setq end (max end (point)))
20407 (while (re-search-forward re end t)
20408 (when (get-char-property (match-beginning 0) 'invisible)
20409 (throw 'exit t))))
20410 nil))))
20412 (defun org-metaup (&optional _arg)
20413 "Move subtree up or move table row up.
20414 Calls `org-move-subtree-up' or `org-table-move-row' or
20415 `org-move-item-up', depending on context. See the individual commands
20416 for more information."
20417 (interactive "P")
20418 (cond
20419 ((run-hook-with-args-until-success 'org-metaup-hook))
20420 ((org-region-active-p)
20421 (let* ((a (min (region-beginning) (region-end)))
20422 (b (1- (max (region-beginning) (region-end))))
20423 (c (save-excursion (goto-char a)
20424 (move-beginning-of-line 0)))
20425 (d (save-excursion (goto-char a)
20426 (move-end-of-line 0) (point))))
20427 (transpose-regions a b c d)
20428 (goto-char c)))
20429 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20430 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20431 ((org-at-item-p) (call-interactively 'org-move-item-up))
20432 (t (org-drag-element-backward))))
20434 (defun org-metadown (&optional _arg)
20435 "Move subtree down or move table row down.
20436 Calls `org-move-subtree-down' or `org-table-move-row' or
20437 `org-move-item-down', depending on context. See the individual
20438 commands for more information."
20439 (interactive "P")
20440 (cond
20441 ((run-hook-with-args-until-success 'org-metadown-hook))
20442 ((org-region-active-p)
20443 (let* ((a (min (region-beginning) (region-end)))
20444 (b (max (region-beginning) (region-end)))
20445 (c (save-excursion (goto-char b)
20446 (move-beginning-of-line 1)))
20447 (d (save-excursion (goto-char b)
20448 (move-end-of-line 1) (1+ (point)))))
20449 (transpose-regions a b c d)
20450 (goto-char d)))
20451 ((org-at-table-p) (call-interactively 'org-table-move-row))
20452 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20453 ((org-at-item-p) (call-interactively 'org-move-item-down))
20454 (t (org-drag-element-forward))))
20456 (defun org-shiftup (&optional arg)
20457 "Increase item in timestamp or increase priority of current headline.
20458 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20459 depending on context. See the individual commands for more information."
20460 (interactive "P")
20461 (cond
20462 ((run-hook-with-args-until-success 'org-shiftup-hook))
20463 ((and org-support-shift-select (org-region-active-p))
20464 (org-call-for-shift-select 'previous-line))
20465 ((org-at-timestamp-p t)
20466 (call-interactively (if org-edit-timestamp-down-means-later
20467 'org-timestamp-down 'org-timestamp-up)))
20468 ((and (not (eq org-support-shift-select 'always))
20469 org-enable-priority-commands
20470 (org-at-heading-p))
20471 (call-interactively 'org-priority-up))
20472 ((and (not org-support-shift-select) (org-at-item-p))
20473 (call-interactively 'org-previous-item))
20474 ((org-clocktable-try-shift 'up arg))
20475 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20476 (org-support-shift-select
20477 (org-call-for-shift-select 'previous-line))
20478 (t (org-shiftselect-error))))
20480 (defun org-shiftdown (&optional arg)
20481 "Decrease item in timestamp or decrease priority of current headline.
20482 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20483 depending on context. See the individual commands for more information."
20484 (interactive "P")
20485 (cond
20486 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20487 ((and org-support-shift-select (org-region-active-p))
20488 (org-call-for-shift-select 'next-line))
20489 ((org-at-timestamp-p t)
20490 (call-interactively (if org-edit-timestamp-down-means-later
20491 'org-timestamp-up 'org-timestamp-down)))
20492 ((and (not (eq org-support-shift-select 'always))
20493 org-enable-priority-commands
20494 (org-at-heading-p))
20495 (call-interactively 'org-priority-down))
20496 ((and (not org-support-shift-select) (org-at-item-p))
20497 (call-interactively 'org-next-item))
20498 ((org-clocktable-try-shift 'down arg))
20499 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20500 (org-support-shift-select
20501 (org-call-for-shift-select 'next-line))
20502 (t (org-shiftselect-error))))
20504 (defun org-shiftright (&optional arg)
20505 "Cycle the thing at point or in the current line, depending on context.
20506 Depending on context, this does one of the following:
20508 - switch a timestamp at point one day into the future
20509 - on a headline, switch to the next TODO keyword.
20510 - on an item, switch entire list to the next bullet type
20511 - on a property line, switch to the next allowed value
20512 - on a clocktable definition line, move time block into the future"
20513 (interactive "P")
20514 (cond
20515 ((run-hook-with-args-until-success 'org-shiftright-hook))
20516 ((and org-support-shift-select (org-region-active-p))
20517 (org-call-for-shift-select 'forward-char))
20518 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20519 ((and (not (eq org-support-shift-select 'always))
20520 (org-at-heading-p))
20521 (let ((org-inhibit-logging
20522 (not org-treat-S-cursor-todo-selection-as-state-change))
20523 (org-inhibit-blocking
20524 (not org-treat-S-cursor-todo-selection-as-state-change)))
20525 (org-call-with-arg 'org-todo 'right)))
20526 ((or (and org-support-shift-select
20527 (not (eq org-support-shift-select 'always))
20528 (org-at-item-bullet-p))
20529 (and (not org-support-shift-select) (org-at-item-p)))
20530 (org-call-with-arg 'org-cycle-list-bullet nil))
20531 ((and (not (eq org-support-shift-select 'always))
20532 (org-at-property-p))
20533 (call-interactively 'org-property-next-allowed-value))
20534 ((org-clocktable-try-shift 'right arg))
20535 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20536 (org-support-shift-select
20537 (org-call-for-shift-select 'forward-char))
20538 (t (org-shiftselect-error))))
20540 (defun org-shiftleft (&optional arg)
20541 "Cycle the thing at point or in the current line, depending on context.
20542 Depending on context, this does one of the following:
20544 - switch a timestamp at point one day into the past
20545 - on a headline, switch to the previous TODO keyword.
20546 - on an item, switch entire list to the previous bullet type
20547 - on a property line, switch to the previous allowed value
20548 - on a clocktable definition line, move time block into the past"
20549 (interactive "P")
20550 (cond
20551 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20552 ((and org-support-shift-select (org-region-active-p))
20553 (org-call-for-shift-select 'backward-char))
20554 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20555 ((and (not (eq org-support-shift-select 'always))
20556 (org-at-heading-p))
20557 (let ((org-inhibit-logging
20558 (not org-treat-S-cursor-todo-selection-as-state-change))
20559 (org-inhibit-blocking
20560 (not org-treat-S-cursor-todo-selection-as-state-change)))
20561 (org-call-with-arg 'org-todo 'left)))
20562 ((or (and org-support-shift-select
20563 (not (eq org-support-shift-select 'always))
20564 (org-at-item-bullet-p))
20565 (and (not org-support-shift-select) (org-at-item-p)))
20566 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20567 ((and (not (eq org-support-shift-select 'always))
20568 (org-at-property-p))
20569 (call-interactively 'org-property-previous-allowed-value))
20570 ((org-clocktable-try-shift 'left arg))
20571 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20572 (org-support-shift-select
20573 (org-call-for-shift-select 'backward-char))
20574 (t (org-shiftselect-error))))
20576 (defun org-shiftcontrolright ()
20577 "Switch to next TODO set."
20578 (interactive)
20579 (cond
20580 ((and org-support-shift-select (org-region-active-p))
20581 (org-call-for-shift-select 'forward-word))
20582 ((and (not (eq org-support-shift-select 'always))
20583 (org-at-heading-p))
20584 (org-call-with-arg 'org-todo 'nextset))
20585 (org-support-shift-select
20586 (org-call-for-shift-select 'forward-word))
20587 (t (org-shiftselect-error))))
20589 (defun org-shiftcontrolleft ()
20590 "Switch to previous TODO set."
20591 (interactive)
20592 (cond
20593 ((and org-support-shift-select (org-region-active-p))
20594 (org-call-for-shift-select 'backward-word))
20595 ((and (not (eq org-support-shift-select 'always))
20596 (org-at-heading-p))
20597 (org-call-with-arg 'org-todo 'previousset))
20598 (org-support-shift-select
20599 (org-call-for-shift-select 'backward-word))
20600 (t (org-shiftselect-error))))
20602 (defun org-shiftcontrolup (&optional n)
20603 "Change timestamps synchronously up in CLOCK log lines.
20604 Optional argument N tells to change by that many units."
20605 (interactive "P")
20606 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20607 (let (org-support-shift-select)
20608 (org-clock-timestamps-up n))
20609 (user-error "Not at a clock log")))
20611 (defun org-shiftcontroldown (&optional n)
20612 "Change timestamps synchronously down in CLOCK log lines.
20613 Optional argument N tells to change by that many units."
20614 (interactive "P")
20615 (if (and (org-at-clock-log-p) (org-in-regexp org-ts-regexp-inactive))
20616 (let (org-support-shift-select)
20617 (org-clock-timestamps-down n))
20618 (user-error "Not at a clock log")))
20620 (defun org-increase-number-at-point (&optional inc)
20621 "Increment the number at point.
20622 With an optional prefix numeric argument INC, increment using
20623 this numeric value."
20624 (interactive "p")
20625 (if (not (number-at-point))
20626 (user-error "Not on a number")
20627 (unless inc (setq inc 1))
20628 (let ((pos (point))
20629 (beg (skip-chars-backward "-+^/*0-9eE."))
20630 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20631 (setq nap (buffer-substring-no-properties
20632 (+ pos beg) (+ pos beg end)))
20633 (delete-region (+ pos beg) (+ pos beg end))
20634 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20635 (when (org-at-table-p)
20636 (org-table-align)
20637 (org-table-end-of-field 1))))
20639 (defun org-decrease-number-at-point (&optional inc)
20640 "Decrement the number at point.
20641 With an optional prefix numeric argument INC, decrement using
20642 this numeric value."
20643 (interactive "p")
20644 (org-increase-number-at-point (- (or inc 1))))
20646 (defun org-ctrl-c-ret ()
20647 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20648 (interactive)
20649 (cond
20650 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20651 (t (call-interactively 'org-insert-heading))))
20653 (defun org-find-visible ()
20654 (let ((s (point)))
20655 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20656 (get-char-property s 'invisible)))
20658 (defun org-find-invisible ()
20659 (let ((s (point)))
20660 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20661 (not (get-char-property s 'invisible))))
20664 (defun org-copy-visible (beg end)
20665 "Copy the visible parts of the region."
20666 (interactive "r")
20667 (let (snippets s)
20668 (save-excursion
20669 (save-restriction
20670 (narrow-to-region beg end)
20671 (setq s (goto-char (point-min)))
20672 (while (not (= (point) (point-max)))
20673 (goto-char (org-find-invisible))
20674 (push (buffer-substring s (point)) snippets)
20675 (setq s (goto-char (org-find-visible))))))
20676 (kill-new (apply 'concat (nreverse snippets)))))
20678 (defun org-copy-special ()
20679 "Copy region in table or copy current subtree.
20680 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20681 context. See the individual commands for more information."
20682 (interactive)
20683 (call-interactively
20684 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20686 (defun org-cut-special ()
20687 "Cut region in table or cut current subtree.
20688 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20689 context. See the individual commands for more information."
20690 (interactive)
20691 (call-interactively
20692 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20694 (defun org-paste-special (arg)
20695 "Paste rectangular region into table, or past subtree relative to level.
20696 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20697 See the individual commands for more information."
20698 (interactive "P")
20699 (if (org-at-table-p)
20700 (org-table-paste-rectangle)
20701 (org-paste-subtree arg)))
20703 (defun org-edit-special (&optional arg)
20704 "Call a special editor for the element at point.
20705 When at a table, call the formula editor with `org-table-edit-formulas'.
20706 When in a source code block, call `org-edit-src-code'.
20707 When in a fixed-width region, call `org-edit-fixed-width-region'.
20708 When in an export block, call `org-edit-export-block'.
20709 When in a LaTeX environment, call `org-edit-latex-environment'.
20710 When at an #+INCLUDE keyword, visit the included file.
20711 When at a footnote reference, call `org-edit-footnote-reference'
20712 On a link, call `ffap' to visit the link at point.
20713 Otherwise, return a user error."
20714 (interactive "P")
20715 (let ((element (org-element-at-point)))
20716 (barf-if-buffer-read-only)
20717 (pcase (org-element-type element)
20718 (`src-block
20719 (if (not arg) (org-edit-src-code)
20720 (let* ((info (org-babel-get-src-block-info))
20721 (lang (nth 0 info))
20722 (params (nth 2 info))
20723 (session (cdr (assq :session params))))
20724 (if (not session) (org-edit-src-code)
20725 ;; At a src-block with a session and function called with
20726 ;; an ARG: switch to the buffer related to the inferior
20727 ;; process.
20728 (switch-to-buffer
20729 (funcall (intern (concat "org-babel-prep-session:" lang))
20730 session params))))))
20731 (`keyword
20732 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20733 (org-open-link-from-string
20734 (format "[[%s]]"
20735 (expand-file-name
20736 (let ((value (org-element-property :value element)))
20737 (cond ((not (org-string-nw-p value))
20738 (user-error "No file to edit"))
20739 ((string-match "\\`\"\\(.*?\\)\"" value)
20740 (match-string 1 value))
20741 ((string-match "\\`[^ \t\"]\\S-*" value)
20742 (match-string 0 value))
20743 (t (user-error "No valid file specified")))))))
20744 (user-error "No special environment to edit here")))
20745 (`table
20746 (if (eq (org-element-property :type element) 'table.el)
20747 (org-edit-table.el)
20748 (call-interactively 'org-table-edit-formulas)))
20749 ;; Only Org tables contain `table-row' type elements.
20750 (`table-row (call-interactively 'org-table-edit-formulas))
20751 (`example-block (org-edit-src-code))
20752 (`export-block (org-edit-export-block))
20753 (`fixed-width (org-edit-fixed-width-region))
20754 (`latex-environment (org-edit-latex-environment))
20756 ;; No notable element at point. Though, we may be at a link or
20757 ;; a footnote reference, which are objects. Thus, scan deeper.
20758 (let ((context (org-element-context element)))
20759 (pcase (org-element-type context)
20760 (`footnote-reference (org-edit-footnote-reference))
20761 (`inline-src-block (org-edit-inline-src-code))
20762 (`link (call-interactively #'ffap))
20763 (_ (user-error "No special environment to edit here"))))))))
20765 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20766 (defun org-ctrl-c-ctrl-c (&optional arg)
20767 "Set tags in headline, or update according to changed information at point.
20769 This command does many different things, depending on context:
20771 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20772 this is what we do.
20774 - If the cursor is on a statistics cookie, update it.
20776 - If the cursor is in a headline, prompt for tags and insert them
20777 into the current line, aligned to `org-tags-column'. When called
20778 with prefix arg, realign all tags in the current buffer.
20780 - If the cursor is in one of the special #+KEYWORD lines, this
20781 triggers scanning the buffer for these lines and updating the
20782 information.
20784 - If the cursor is inside a table, realign the table. This command
20785 works even if the automatic table editor has been turned off.
20787 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20788 the entire table.
20790 - If the cursor is at a footnote reference or definition, jump to
20791 the corresponding definition or references, respectively.
20793 - If the cursor is a the beginning of a dynamic block, update it.
20795 - If the current buffer is a capture buffer, close note and file it.
20797 - If the cursor is on a <<<target>>>, update radio targets and
20798 corresponding links in this buffer.
20800 - If the cursor is on a numbered item in a plain list, renumber the
20801 ordered list.
20803 - If the cursor is on a checkbox, toggle it.
20805 - If the cursor is on a code block, evaluate it. The variable
20806 `org-confirm-babel-evaluate' can be used to control prompting
20807 before code block evaluation, by default every code block
20808 evaluation requires confirmation. Code block evaluation can be
20809 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20810 (interactive "P")
20811 (cond
20812 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20813 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20814 (org-remove-occur-highlights)
20815 (message "Temporary highlights/overlays removed from current buffer"))
20816 ((and (local-variable-p 'org-finish-function)
20817 (fboundp org-finish-function))
20818 (funcall org-finish-function))
20819 ((org-babel-hash-at-point))
20820 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20822 (let* ((context
20823 (org-element-lineage
20824 (org-element-context)
20825 ;; Limit to supported contexts.
20826 '(babel-call clock dynamic-block footnote-definition
20827 footnote-reference inline-babel-call inline-src-block
20828 inlinetask item keyword node-property paragraph
20829 plain-list property-drawer radio-target src-block
20830 statistics-cookie table table-cell table-row
20831 timestamp)
20833 (type (org-element-type context)))
20834 ;; For convenience: at the first line of a paragraph on the same
20835 ;; line as an item, apply function on that item instead.
20836 (when (eq type 'paragraph)
20837 (let ((parent (org-element-property :parent context)))
20838 (when (and (eq (org-element-type parent) 'item)
20839 (= (line-beginning-position)
20840 (org-element-property :begin parent)))
20841 (setq context parent)
20842 (setq type 'item))))
20843 ;; Act according to type of element or object at point.
20845 ;; Do nothing on a blank line, except if it is contained in
20846 ;; a src block. Hence, we first check if point is in such
20847 ;; a block and then if it is at a blank line.
20848 (pcase type
20849 ((or `inline-src-block `src-block)
20850 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20851 (org-babel-eval-wipe-error-buffer)
20852 (org-babel-execute-src-block
20853 current-prefix-arg (org-babel-get-src-block-info nil context))))
20854 ((guard (org-match-line "[ \t]*$"))
20855 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20856 (user-error
20857 (substitute-command-keys
20858 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20859 ((or `babel-call `inline-babel-call)
20860 (let ((info (org-babel-lob-get-info context)))
20861 (when info (org-babel-execute-src-block nil info))))
20862 (`clock (org-clock-update-time-maybe))
20863 (`dynamic-block
20864 (save-excursion
20865 (goto-char (org-element-property :post-affiliated context))
20866 (org-update-dblock)))
20867 (`footnote-definition
20868 (goto-char (org-element-property :post-affiliated context))
20869 (call-interactively 'org-footnote-action))
20870 (`footnote-reference (call-interactively #'org-footnote-action))
20871 ((or `headline `inlinetask)
20872 (save-excursion (goto-char (org-element-property :begin context))
20873 (call-interactively #'org-set-tags)))
20874 (`item
20875 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20876 ;; unconditionally, whereas `C-u' will toggle its presence.
20877 ;; Without a universal argument, if the item has a checkbox,
20878 ;; toggle it. Otherwise repair the list.
20879 (let* ((box (org-element-property :checkbox context))
20880 (struct (org-element-property :structure context))
20881 (old-struct (copy-tree struct))
20882 (parents (org-list-parents-alist struct))
20883 (prevs (org-list-prevs-alist struct))
20884 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20885 (org-list-set-checkbox
20886 (org-element-property :begin context) struct
20887 (cond ((equal arg '(16)) "[-]")
20888 ((and (not box) (equal arg '(4))) "[ ]")
20889 ((or (not box) (equal arg '(4))) nil)
20890 ((eq box 'on) "[ ]")
20891 (t "[X]")))
20892 ;; Mimic `org-list-write-struct' but with grabbing a return
20893 ;; value from `org-list-struct-fix-box'.
20894 (org-list-struct-fix-ind struct parents 2)
20895 (org-list-struct-fix-item-end struct)
20896 (org-list-struct-fix-bul struct prevs)
20897 (org-list-struct-fix-ind struct parents)
20898 (let ((block-item
20899 (org-list-struct-fix-box struct parents prevs orderedp)))
20900 (if (and box (equal struct old-struct))
20901 (if (equal arg '(16))
20902 (message "Checkboxes already reset")
20903 (user-error "Cannot toggle this checkbox: %s"
20904 (if (eq box 'on)
20905 "all subitems checked"
20906 "unchecked subitems")))
20907 (org-list-struct-apply-struct struct old-struct)
20908 (org-update-checkbox-count-maybe))
20909 (when block-item
20910 (message "Checkboxes were removed due to empty box at line %d"
20911 (org-current-line block-item))))))
20912 (`keyword
20913 (let ((org-inhibit-startup-visibility-stuff t)
20914 (org-startup-align-all-tables nil))
20915 (when (boundp 'org-table-coordinate-overlays)
20916 (mapc #'delete-overlay org-table-coordinate-overlays)
20917 (setq org-table-coordinate-overlays nil))
20918 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20919 (message "Local setup has been refreshed"))
20920 (`plain-list
20921 ;; At a plain list, with a double C-u argument, set
20922 ;; checkboxes of each item to "[-]", whereas a single one
20923 ;; will toggle their presence according to the state of the
20924 ;; first item in the list. Without an argument, repair the
20925 ;; list.
20926 (let* ((begin (org-element-property :contents-begin context))
20927 (beginm (move-marker (make-marker) begin))
20928 (struct (org-element-property :structure context))
20929 (old-struct (copy-tree struct))
20930 (first-box (save-excursion
20931 (goto-char begin)
20932 (looking-at org-list-full-item-re)
20933 (match-string-no-properties 3)))
20934 (new-box (cond ((equal arg '(16)) "[-]")
20935 ((equal arg '(4)) (unless first-box "[ ]"))
20936 ((equal first-box "[X]") "[ ]")
20937 (t "[X]"))))
20938 (cond
20939 (arg
20940 (dolist (pos
20941 (org-list-get-all-items
20942 begin struct (org-list-prevs-alist struct)))
20943 (org-list-set-checkbox pos struct new-box)))
20944 ((and first-box (eq (point) begin))
20945 ;; For convenience, when point is at bol on the first
20946 ;; item of the list and no argument is provided, simply
20947 ;; toggle checkbox of that item, if any.
20948 (org-list-set-checkbox begin struct new-box)))
20949 (org-list-write-struct
20950 struct (org-list-parents-alist struct) old-struct)
20951 (org-update-checkbox-count-maybe)
20952 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20953 ((or `property-drawer `node-property)
20954 (call-interactively #'org-property-action))
20955 (`radio-target
20956 (call-interactively #'org-update-radio-target-regexp))
20957 (`statistics-cookie
20958 (call-interactively #'org-update-statistics-cookies))
20959 ((or `table `table-cell `table-row)
20960 ;; At a table, recalculate every field and align it. Also
20961 ;; send the table if necessary. If the table has
20962 ;; a `table.el' type, just give up. At a table row or cell,
20963 ;; maybe recalculate line but always align table.
20964 (if (eq (org-element-property :type context) 'table.el)
20965 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20966 Use `\\[org-edit-special]' to edit table.el tables"))
20967 (let ((org-enable-table-editor t))
20968 (if (or (eq type 'table)
20969 ;; Check if point is at a TBLFM line.
20970 (and (eq type 'table-row)
20971 (= (point) (org-element-property :end context))))
20972 (save-excursion
20973 (if (org-at-TBLFM-p)
20974 (progn (require 'org-table)
20975 (org-table-calc-current-TBLFM))
20976 (goto-char (org-element-property :contents-begin context))
20977 (org-call-with-arg 'org-table-recalculate (or arg t))
20978 (orgtbl-send-table 'maybe)))
20979 (org-table-maybe-eval-formula)
20980 (cond (arg (call-interactively #'org-table-recalculate))
20981 ((org-table-maybe-recalculate-line))
20982 (t (org-table-align)))))))
20983 (`timestamp (org-timestamp-change 0 'day))
20984 ((and `nil (guard (org-at-heading-p)))
20985 ;; When point is on an unsupported object type, we can miss
20986 ;; the fact that it also is at a heading. Handle it here.
20987 (call-interactively #'org-set-tags))
20988 ((guard
20989 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20991 (user-error
20992 (substitute-command-keys
20993 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20995 (defun org-mode-restart ()
20996 (interactive)
20997 (let ((indent-status (bound-and-true-p org-indent-mode)))
20998 (funcall major-mode)
20999 (hack-local-variables)
21000 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21001 (org-indent-mode -1)))
21002 (message "%s restarted" major-mode))
21004 (defun org-kill-note-or-show-branches ()
21005 "Abort storing current note, or call `outline-show-branches'."
21006 (interactive)
21007 (if (not org-finish-function)
21008 (progn
21009 (outline-hide-subtree)
21010 (call-interactively 'outline-show-branches))
21011 (let ((org-note-abort t))
21012 (funcall org-finish-function))))
21014 (defun org-delete-indentation (&optional arg)
21015 "Join current line to previous and fix whitespace at join.
21017 If previous line is a headline add to headline title. Otherwise
21018 the function calls `delete-indentation'.
21020 With a non-nil optional argument, join it to the following one."
21021 (interactive "*P")
21022 (if (save-excursion
21023 (beginning-of-line (if arg 1 0))
21024 (let ((case-fold-search nil))
21025 (looking-at org-complex-heading-regexp)))
21026 ;; At headline.
21027 (let ((tags-column (when (match-beginning 5)
21028 (save-excursion (goto-char (match-beginning 5))
21029 (current-column))))
21030 (string (concat " " (progn (when arg (forward-line 1))
21031 (org-trim (delete-and-extract-region
21032 (line-beginning-position)
21033 (line-end-position)))))))
21034 (unless (bobp) (delete-region (point) (1- (point))))
21035 (goto-char (or (match-end 4)
21036 (match-beginning 5)
21037 (match-end 0)))
21038 (skip-chars-backward " \t")
21039 (save-excursion (insert string))
21040 ;; Adjust alignment of tags.
21041 (cond
21042 ((not tags-column)) ;no tags
21043 (org-auto-align-tags (org-set-tags nil t))
21044 (t (org--align-tags-here tags-column)))) ;preserve tags column
21045 (delete-indentation arg)))
21047 (defun org-open-line (n)
21048 "Insert a new row in tables, call `open-line' elsewhere.
21049 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21050 As a special case, when a document starts with a table, allow to
21051 call `open-line' on the very first character."
21052 (interactive "*p")
21053 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21054 (org-table-insert-row)
21055 (open-line n)))
21057 (defun org-return (&optional indent)
21058 "Goto next table row or insert a newline.
21060 Calls `org-table-next-row' or `newline', depending on context.
21062 When optional INDENT argument is non-nil, call
21063 `newline-and-indent' instead of `newline'.
21065 When `org-return-follows-link' is non-nil and point is on
21066 a timestamp or a link, call `org-open-at-point'. However, it
21067 will not happen if point is in a table or on a \"dead\"
21068 object (e.g., within a comment). In these case, you need to use
21069 `org-open-at-point' directly."
21070 (interactive)
21071 (let ((context (if org-return-follows-link (org-element-context)
21072 (org-element-at-point))))
21073 (cond
21074 ;; In a table, call `org-table-next-row'.
21075 ((or (and (eq (org-element-type context) 'table)
21076 (>= (point) (org-element-property :contents-begin context))
21077 (< (point) (org-element-property :contents-end context)))
21078 (org-element-lineage context '(table-row table-cell) t))
21079 (org-table-justify-field-maybe)
21080 (call-interactively #'org-table-next-row))
21081 ;; On a link or a timestamp, call `org-open-at-point' if
21082 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21083 ;; locations, e.g., in a comment, as `org-open-at-point'.
21084 ((and org-return-follows-link
21085 (or (org-in-regexp org-ts-regexp-both nil t)
21086 (org-in-regexp org-tsr-regexp-both nil t)
21087 (org-in-regexp org-any-link-re nil t)))
21088 (call-interactively #'org-open-at-point))
21089 ;; Insert newline in heading, but preserve tags.
21090 ((and (not (bolp))
21091 (save-excursion (beginning-of-line)
21092 (let ((case-fold-search nil))
21093 (looking-at org-complex-heading-regexp))))
21094 ;; At headline. Split line. However, if point is on keyword,
21095 ;; priority cookie or tags, do not break any of them: add
21096 ;; a newline after the headline instead.
21097 (let ((tags-column (and (match-beginning 5)
21098 (save-excursion (goto-char (match-beginning 5))
21099 (current-column))))
21100 (string
21101 (when (and (match-end 4) (org-point-in-group (point) 4))
21102 (delete-and-extract-region (point) (match-end 4)))))
21103 ;; Adjust tag alignment.
21104 (cond
21105 ((not (and tags-column string)))
21106 (org-auto-align-tags (org-set-tags nil t))
21107 (t (org--align-tags-here tags-column))) ;preserve tags column
21108 (end-of-line)
21109 (org-show-entry)
21110 (if indent (newline-and-indent) (newline))
21111 (when string (save-excursion (insert (org-trim string))))))
21112 ;; In a list, make sure indenting keeps trailing text within.
21113 ((and indent
21114 (not (eolp))
21115 (org-element-lineage context '(item)))
21116 (let ((trailing-data
21117 (delete-and-extract-region (point) (line-end-position))))
21118 (newline-and-indent)
21119 (save-excursion (insert trailing-data))))
21120 (t (if indent (newline-and-indent) (newline))))))
21122 (defun org-return-indent ()
21123 "Goto next table row or insert a newline and indent.
21124 Calls `org-table-next-row' or `newline-and-indent', depending on
21125 context. See the individual commands for more information."
21126 (interactive)
21127 (org-return t))
21129 (defun org-ctrl-c-star ()
21130 "Compute table, or change heading status of lines.
21131 Calls `org-table-recalculate' or `org-toggle-heading',
21132 depending on context."
21133 (interactive)
21134 (cond
21135 ((org-at-table-p)
21136 (call-interactively 'org-table-recalculate))
21138 ;; Convert all lines in region to list items
21139 (call-interactively 'org-toggle-heading))))
21141 (defun org-ctrl-c-minus ()
21142 "Insert separator line in table or modify bullet status of line.
21143 Also turns a plain line or a region of lines into list items.
21144 Calls `org-table-insert-hline', `org-toggle-item', or
21145 `org-cycle-list-bullet', depending on context."
21146 (interactive)
21147 (cond
21148 ((org-at-table-p)
21149 (call-interactively 'org-table-insert-hline))
21150 ((org-region-active-p)
21151 (call-interactively 'org-toggle-item))
21152 ((org-in-item-p)
21153 (call-interactively 'org-cycle-list-bullet))
21155 (call-interactively 'org-toggle-item))))
21157 (defun org-toggle-heading (&optional nstars)
21158 "Convert headings to normal text, or items or text to headings.
21159 If there is no active region, only convert the current line.
21161 With a `\\[universal-argument]' prefix, convert the whole list at
21162 point into heading.
21164 In a region:
21166 - If the first non blank line is a headline, remove the stars
21167 from all headlines in the region.
21169 - If it is a normal line, turn each and every normal line (i.e.,
21170 not an heading or an item) in the region into headings. If you
21171 want to convert only the first line of this region, use one
21172 universal prefix argument.
21174 - If it is a plain list item, turn all plain list items into headings.
21176 When converting a line into a heading, the number of stars is chosen
21177 such that the lines become children of the current entry. However,
21178 when a numeric prefix argument is given, its value determines the
21179 number of stars to add."
21180 (interactive "P")
21181 (let ((skip-blanks
21182 (function
21183 ;; Return beginning of first non-blank line, starting from
21184 ;; line at POS.
21185 (lambda (pos)
21186 (save-excursion
21187 (goto-char pos)
21188 (while (org-at-comment-p) (forward-line))
21189 (skip-chars-forward " \r\t\n")
21190 (point-at-bol)))))
21191 beg end toggled)
21192 ;; Determine boundaries of changes. If a universal prefix has
21193 ;; been given, put the list in a region. If region ends at a bol,
21194 ;; do not consider the last line to be in the region.
21196 (when (and current-prefix-arg (org-at-item-p))
21197 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21198 (org-mark-element))
21200 (if (org-region-active-p)
21201 (setq beg (funcall skip-blanks (region-beginning))
21202 end (copy-marker (save-excursion
21203 (goto-char (region-end))
21204 (if (bolp) (point) (point-at-eol)))))
21205 (setq beg (funcall skip-blanks (point-at-bol))
21206 end (copy-marker (point-at-eol))))
21207 ;; Ensure inline tasks don't count as headings.
21208 (org-with-limited-levels
21209 (save-excursion
21210 (goto-char beg)
21211 (cond
21212 ;; Case 1. Started at an heading: de-star headings.
21213 ((org-at-heading-p)
21214 (while (< (point) end)
21215 (when (org-at-heading-p t)
21216 (looking-at org-outline-regexp) (replace-match "")
21217 (setq toggled t))
21218 (forward-line)))
21219 ;; Case 2. Started at an item: change items into headlines.
21220 ;; One star will be added by `org-list-to-subtree'.
21221 ((org-at-item-p)
21222 (while (< (point) end)
21223 (when (org-at-item-p)
21224 ;; Pay attention to cases when region ends before list.
21225 (let* ((struct (org-list-struct))
21226 (list-end
21227 (min (org-list-get-bottom-point struct) (1+ end))))
21228 (save-restriction
21229 (narrow-to-region (point) list-end)
21230 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21231 (setq toggled t))
21232 (forward-line)))
21233 ;; Case 3. Started at normal text: make every line an heading,
21234 ;; skipping headlines and items.
21235 (t (let* ((stars
21236 (make-string
21237 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21238 (add-stars
21239 (cond (nstars "") ; stars from prefix only
21240 ((equal stars "") "*") ; before first heading
21241 (org-odd-levels-only "**") ; inside heading, odd
21242 (t "*"))) ; inside heading, oddeven
21243 (rpl (concat stars add-stars " "))
21244 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21245 (while (< (point) (if (equal nstars '(4)) lend end))
21246 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21247 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21248 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21249 (forward-line)))))))
21250 (unless toggled (message "Cannot toggle heading from here"))))
21252 (defun org-meta-return (&optional arg)
21253 "Insert a new heading or wrap a region in a table.
21254 Calls `org-insert-heading', `org-insert-item' or
21255 `org-table-wrap-region', depending on context. When called with
21256 an argument, unconditionally call `org-insert-heading'."
21257 (interactive "P")
21258 (org-check-before-invisible-edit 'insert)
21259 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21260 (call-interactively (cond (arg #'org-insert-heading)
21261 ((org-at-table-p) #'org-table-wrap-region)
21262 ((org-in-item-p) #'org-insert-item)
21263 (t #'org-insert-heading)))))
21265 ;;; Menu entries
21267 (defsubst org-in-subtree-not-table-p ()
21268 "Are we in a subtree and not in a table?"
21269 (and (not (org-before-first-heading-p))
21270 (not (org-at-table-p))))
21272 ;; Define the Org mode menus
21273 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21274 '("Tbl"
21275 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21276 ["Next Field" org-cycle (org-at-table-p)]
21277 ["Previous Field" org-shifttab (org-at-table-p)]
21278 ["Next Row" org-return (org-at-table-p)]
21279 "--"
21280 ["Blank Field" org-table-blank-field (org-at-table-p)]
21281 ["Edit Field" org-table-edit-field (org-at-table-p)]
21282 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21283 "--"
21284 ("Column"
21285 ["Move Column Left" org-metaleft (org-at-table-p)]
21286 ["Move Column Right" org-metaright (org-at-table-p)]
21287 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21288 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21289 ("Row"
21290 ["Move Row Up" org-metaup (org-at-table-p)]
21291 ["Move Row Down" org-metadown (org-at-table-p)]
21292 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21293 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21294 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21295 "--"
21296 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21297 ("Rectangle"
21298 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21299 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21300 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21301 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21302 "--"
21303 ("Calculate"
21304 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21305 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21306 ["Edit Formulas" org-edit-special (org-at-table-p)]
21307 "--"
21308 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21309 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21310 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21311 "--"
21312 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21313 "--"
21314 ["Sum Column/Rectangle" org-table-sum
21315 (or (org-at-table-p) (org-region-active-p))]
21316 ["Which Column?" org-table-current-column (org-at-table-p)])
21317 ["Debug Formulas"
21318 org-table-toggle-formula-debugger
21319 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21320 ["Show Col/Row Numbers"
21321 org-table-toggle-coordinate-overlays
21322 :style toggle
21323 :selected (bound-and-true-p org-table-overlay-coordinates)]
21324 "--"
21325 ["Create" org-table-create (and (not (org-at-table-p))
21326 org-enable-table-editor)]
21327 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21328 ["Import from File" org-table-import (not (org-at-table-p))]
21329 ["Export to File" org-table-export (org-at-table-p)]
21330 "--"
21331 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21332 "--"
21333 ("Plot"
21334 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21335 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21337 (easy-menu-define org-org-menu org-mode-map "Org menu"
21338 '("Org"
21339 ("Show/Hide"
21340 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21341 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21342 ["Sparse Tree..." org-sparse-tree t]
21343 ["Reveal Context" org-reveal t]
21344 ["Show All" outline-show-all t]
21345 "--"
21346 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21347 "--"
21348 ["New Heading" org-insert-heading t]
21349 ("Navigate Headings"
21350 ["Up" outline-up-heading t]
21351 ["Next" outline-next-visible-heading t]
21352 ["Previous" outline-previous-visible-heading t]
21353 ["Next Same Level" outline-forward-same-level t]
21354 ["Previous Same Level" outline-backward-same-level t]
21355 "--"
21356 ["Jump" org-goto t])
21357 ("Edit Structure"
21358 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21359 "--"
21360 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21361 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21362 "--"
21363 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21364 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21365 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21366 "--"
21367 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21368 "--"
21369 ["Copy visible text" org-copy-visible t]
21370 "--"
21371 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21372 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21373 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21374 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21375 "--"
21376 ["Sort Region/Children" org-sort t]
21377 "--"
21378 ["Convert to odd levels" org-convert-to-odd-levels t]
21379 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21380 ("Editing"
21381 ["Emphasis..." org-emphasize t]
21382 ["Edit Source Example" org-edit-special t]
21383 "--"
21384 ["Footnote new/jump" org-footnote-action t]
21385 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21386 ("Archive"
21387 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21388 "--"
21389 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21390 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21391 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21393 "--"
21394 ("Hyperlinks"
21395 ["Store Link (Global)" org-store-link t]
21396 ["Find existing link to here" org-occur-link-in-agenda-files t]
21397 ["Insert Link" org-insert-link t]
21398 ["Follow Link" org-open-at-point t]
21399 "--"
21400 ["Next link" org-next-link t]
21401 ["Previous link" org-previous-link t]
21402 "--"
21403 ["Descriptive Links"
21404 org-toggle-link-display
21405 :style radio
21406 :selected org-descriptive-links
21408 ["Literal Links"
21409 org-toggle-link-display
21410 :style radio
21411 :selected (not org-descriptive-links)])
21412 "--"
21413 ("TODO Lists"
21414 ["TODO/DONE/-" org-todo t]
21415 ("Select keyword"
21416 ["Next keyword" org-shiftright (org-at-heading-p)]
21417 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21418 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21419 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21420 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21421 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21422 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21423 "--"
21424 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21425 :selected org-enforce-todo-dependencies :style toggle :active t]
21426 "Settings for tree at point"
21427 ["Do Children sequentially" org-toggle-ordered-property :style radio
21428 :selected (org-entry-get nil "ORDERED")
21429 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21430 ["Do Children parallel" org-toggle-ordered-property :style radio
21431 :selected (not (org-entry-get nil "ORDERED"))
21432 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21433 "--"
21434 ["Set Priority" org-priority t]
21435 ["Priority Up" org-shiftup t]
21436 ["Priority Down" org-shiftdown t]
21437 "--"
21438 ["Get news from all feeds" org-feed-update-all t]
21439 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21440 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21441 ("TAGS and Properties"
21442 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21443 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21444 "--"
21445 ["Set property" org-set-property (not (org-before-first-heading-p))]
21446 ["Column view of properties" org-columns t]
21447 ["Insert Column View DBlock" org-columns-insert-dblock t])
21448 ("Dates and Scheduling"
21449 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21450 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21451 ("Change Date"
21452 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21453 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21454 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21455 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21456 ["Compute Time Range" org-evaluate-time-range t]
21457 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21458 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21459 "--"
21460 ["Custom time format" org-toggle-time-stamp-overlays
21461 :style radio :selected org-display-custom-times]
21462 "--"
21463 ["Goto Calendar" org-goto-calendar t]
21464 ["Date from Calendar" org-date-from-calendar t]
21465 "--"
21466 ["Start/Restart Timer" org-timer-start t]
21467 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21468 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21469 ["Insert Timer String" org-timer t]
21470 ["Insert Timer Item" org-timer-item t])
21471 ("Logging work"
21472 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21473 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21474 ["Clock out" org-clock-out t]
21475 ["Clock cancel" org-clock-cancel t]
21476 "--"
21477 ["Mark as default task" org-clock-mark-default-task t]
21478 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21479 ["Goto running clock" org-clock-goto t]
21480 "--"
21481 ["Display times" org-clock-display t]
21482 ["Create clock table" org-clock-report t]
21483 "--"
21484 ["Record DONE time"
21485 (progn (setq org-log-done (not org-log-done))
21486 (message "Switching to %s will %s record a timestamp"
21487 (car org-done-keywords)
21488 (if org-log-done "automatically" "not")))
21489 :style toggle :selected org-log-done])
21490 "--"
21491 ["Agenda Command..." org-agenda t]
21492 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21493 ("File List for Agenda")
21494 ("Special views current file"
21495 ["TODO Tree" org-show-todo-tree t]
21496 ["Check Deadlines" org-check-deadlines t]
21497 ["Tags/Property tree" org-match-sparse-tree t])
21498 "--"
21499 ["Export/Publish..." org-export-dispatch t]
21500 ("LaTeX"
21501 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21502 :selected org-cdlatex-mode]
21503 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21504 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21505 ["Modify math symbol" org-cdlatex-math-modify
21506 (org-inside-LaTeX-fragment-p)]
21507 ["Insert citation" org-reftex-citation t])
21508 "--"
21509 ("MobileOrg"
21510 ["Push Files and Views" org-mobile-push t]
21511 ["Get Captured and Flagged" org-mobile-pull t]
21512 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21513 "--"
21514 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21515 "--"
21516 ("Documentation"
21517 ["Show Version" org-version t]
21518 ["Info Documentation" org-info t])
21519 ("Customize"
21520 ["Browse Org Group" org-customize t]
21521 "--"
21522 ["Expand This Menu" org-create-customize-menu
21523 (fboundp 'customize-menu-create)])
21524 ["Send bug report" org-submit-bug-report t]
21525 "--"
21526 ("Refresh/Reload"
21527 ["Refresh setup current buffer" org-mode-restart t]
21528 ["Reload Org (after update)" org-reload t]
21529 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21532 (defun org-info (&optional node)
21533 "Read documentation for Org in the info system.
21534 With optional NODE, go directly to that node."
21535 (interactive)
21536 (info (format "(org)%s" (or node ""))))
21538 ;;;###autoload
21539 (defun org-submit-bug-report ()
21540 "Submit a bug report on Org via mail.
21542 Don't hesitate to report any problems or inaccurate documentation.
21544 If you don't have setup sending mail from (X)Emacs, please copy the
21545 output buffer into your mail program, as it gives us important
21546 information about your Org version and configuration."
21547 (interactive)
21548 (require 'reporter)
21549 (defvar reporter-prompt-for-summary-p)
21550 (org-load-modules-maybe)
21551 (org-require-autoloaded-modules)
21552 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21553 (reporter-submit-bug-report
21554 "emacs-orgmode@gnu.org"
21555 (org-version nil 'full)
21556 (let (list)
21557 (save-window-excursion
21558 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21559 (delete-other-windows)
21560 (erase-buffer)
21561 (insert "You are about to submit a bug report to the Org mailing list.
21563 We would like to add your full Org and Outline configuration to the
21564 bug report. This greatly simplifies the work of the maintainer and
21565 other experts on the mailing list.
21567 HOWEVER, some variables you have customized may contain private
21568 information. The names of customers, colleagues, or friends, might
21569 appear in the form of file names, tags, todo states, or search strings.
21570 If you answer yes to the prompt, you might want to check and remove
21571 such private information before sending the email.")
21572 (add-text-properties (point-min) (point-max) '(face org-warning))
21573 (when (yes-or-no-p "Include your Org configuration ")
21574 (mapatoms
21575 (lambda (v)
21576 (and (boundp v)
21577 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21578 (or (and (symbol-value v)
21579 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21580 (and
21581 (get v 'custom-type) (get v 'standard-value)
21582 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21583 (push v list)))))
21584 (kill-buffer (get-buffer "*Warn about privacy*"))
21585 list))
21586 nil nil
21587 "Remember to cover the basics, that is, what you expected to happen and
21588 what in fact did happen. You don't know how to make a good report? See
21590 http://orgmode.org/manual/Feedback.html#Feedback
21592 Your bug report will be posted to the Org mailing list.
21593 ------------------------------------------------------------------------")
21594 (save-excursion
21595 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21596 (replace-match "\\1Bug: \\3 [\\2]")))))
21599 (defun org-install-agenda-files-menu ()
21600 (let ((bl (buffer-list)))
21601 (save-excursion
21602 (while bl
21603 (set-buffer (pop bl))
21604 (when (derived-mode-p 'org-mode) (setq bl nil)))
21605 (when (derived-mode-p 'org-mode)
21606 (easy-menu-change
21607 '("Org") "File List for Agenda"
21608 (append
21609 (list
21610 ["Edit File List" (org-edit-agenda-file-list) t]
21611 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21612 ["Remove Current File from List" org-remove-file t]
21613 ["Cycle through agenda files" org-cycle-agenda-files t]
21614 ["Occur in all agenda files" org-occur-in-agenda-files t]
21615 "--")
21616 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21618 ;;;; Documentation
21620 (defun org-require-autoloaded-modules ()
21621 (interactive)
21622 (mapc #'require
21623 '(org-agenda org-archive org-attach org-clock org-colview org-id
21624 org-table org-timer)))
21626 ;;;###autoload
21627 (defun org-reload (&optional uncompiled)
21628 "Reload all org lisp files.
21629 With prefix arg UNCOMPILED, load the uncompiled versions."
21630 (interactive "P")
21631 (require 'loadhist)
21632 (let* ((org-dir (org-find-library-dir "org"))
21633 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21634 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21635 (remove-re (format "\\`%s\\'"
21636 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21637 (feats (delete-dups
21638 (mapcar 'file-name-sans-extension
21639 (mapcar 'file-name-nondirectory
21640 (delq nil
21641 (mapcar 'feature-file
21642 features))))))
21643 (lfeat (append
21644 (sort
21645 (setq feats
21646 (delq nil (mapcar
21647 (lambda (f)
21648 (if (and (string-match feature-re f)
21649 (not (string-match remove-re f)))
21650 f nil))
21651 feats)))
21652 'string-lessp)
21653 (list "org-version" "org")))
21654 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21655 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21656 load-uncore load-misses)
21657 (setq load-misses
21658 (delq 't
21659 (mapcar (lambda (f)
21660 (or (org-load-noerror-mustsuffix (concat org-dir f))
21661 (and (string= org-dir contrib-dir)
21662 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21663 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21664 (add-to-list 'load-uncore f 'append)
21667 lfeat)))
21668 (when load-uncore
21669 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21670 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21671 (if load-misses
21672 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21673 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21674 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21676 ;;;###autoload
21677 (defun org-customize ()
21678 "Call the customize function with org as argument."
21679 (interactive)
21680 (org-load-modules-maybe)
21681 (org-require-autoloaded-modules)
21682 (customize-browse 'org))
21684 (defun org-create-customize-menu ()
21685 "Create a full customization menu for Org mode, insert it into the menu."
21686 (interactive)
21687 (org-load-modules-maybe)
21688 (org-require-autoloaded-modules)
21689 (if (fboundp 'customize-menu-create)
21690 (progn
21691 (easy-menu-change
21692 '("Org") "Customize"
21693 `(["Browse Org group" org-customize t]
21694 "--"
21695 ,(customize-menu-create 'org)
21696 ["Set" Custom-set t]
21697 ["Save" Custom-save t]
21698 ["Reset to Current" Custom-reset-current t]
21699 ["Reset to Saved" Custom-reset-saved t]
21700 ["Reset to Standard Settings" Custom-reset-standard t]))
21701 (message "\"Org\"-menu now contains full customization menu"))
21702 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21704 ;;;; Miscellaneous stuff
21706 ;;; Generally useful functions
21708 (defun org-get-at-eol (property n)
21709 "Get text property PROPERTY at the end of line less N characters."
21710 (get-text-property (- (point-at-eol) n) property))
21712 (defun org-find-text-property-in-string (prop s)
21713 "Return the first non-nil value of property PROP in string S."
21714 (or (get-text-property 0 prop s)
21715 (get-text-property (or (next-single-property-change 0 prop s) 0)
21716 prop s)))
21718 (defun org-display-warning (message)
21719 "Display the given MESSAGE as a warning."
21720 (display-warning 'org message :warning))
21722 (defun org-eval (form)
21723 "Eval FORM and return result."
21724 (condition-case error
21725 (eval form)
21726 (error (format "%%![Error: %s]" error))))
21728 (defun org-in-clocktable-p ()
21729 "Check if the cursor is in a clocktable."
21730 (let ((pos (point)) start)
21731 (save-excursion
21732 (end-of-line 1)
21733 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21734 (setq start (match-beginning 0))
21735 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21736 (>= (match-end 0) pos)
21737 start))))
21739 (defun org-in-verbatim-emphasis ()
21740 (save-match-data
21741 (and (org-in-regexp org-verbatim-re 2)
21742 (>= (point) (match-beginning 3))
21743 (<= (point) (match-end 4)))))
21745 (defun org-overlay-display (ovl text &optional face evap)
21746 "Make overlay OVL display TEXT with face FACE."
21747 (overlay-put ovl 'display text)
21748 (if face (overlay-put ovl 'face face))
21749 (if evap (overlay-put ovl 'evaporate t)))
21751 (defun org-overlay-before-string (ovl text &optional face evap)
21752 "Make overlay OVL display TEXT with face FACE."
21753 (if face (org-add-props text nil 'face face))
21754 (overlay-put ovl 'before-string text)
21755 (if evap (overlay-put ovl 'evaporate t)))
21757 (defun org-find-overlays (prop &optional pos delete)
21758 "Find all overlays specifying PROP at POS or point.
21759 If DELETE is non-nil, delete all those overlays."
21760 (let (found)
21761 (dolist (ov (overlays-at (or pos (point))) found)
21762 (cond ((not (overlay-get ov prop)))
21763 (delete (delete-overlay ov))
21764 (t (push ov found))))))
21766 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21767 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21768 (if (and marker (marker-buffer marker)
21769 (buffer-live-p (marker-buffer marker)))
21770 (progn
21771 (pop-to-buffer-same-window (marker-buffer marker))
21772 (when (or (> marker (point-max)) (< marker (point-min)))
21773 (widen))
21774 (goto-char marker)
21775 (org-show-context 'org-goto))
21776 (if bookmark
21777 (bookmark-jump bookmark)
21778 (error "Cannot find location"))))
21780 (defun org-quote-csv-field (s)
21781 "Quote field for inclusion in CSV material."
21782 (if (string-match "[\",]" s)
21783 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21786 (defun org-force-self-insert (N)
21787 "Needed to enforce self-insert under remapping."
21788 (interactive "p")
21789 (self-insert-command N))
21791 (defun org-string-width (s)
21792 "Compute width of string, ignoring invisible characters.
21793 This ignores character with invisibility property `org-link', and also
21794 characters with property `org-cwidth', because these will become invisible
21795 upon the next fontification round."
21796 (let (b l)
21797 (when (or (eq t buffer-invisibility-spec)
21798 (assq 'org-link buffer-invisibility-spec))
21799 (while (setq b (text-property-any 0 (length s)
21800 'invisible 'org-link s))
21801 (setq s (concat (substring s 0 b)
21802 (substring s (or (next-single-property-change
21803 b 'invisible s)
21804 (length s)))))))
21805 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21806 (setq s (concat (substring s 0 b)
21807 (substring s (or (next-single-property-change
21808 b 'org-cwidth s)
21809 (length s))))))
21810 (setq l (string-width s) b -1)
21811 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21812 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21815 (defun org-shorten-string (s maxlength)
21816 "Shorten string S so that it is no longer than MAXLENGTH characters.
21817 If the string is shorter or has length MAXLENGTH, just return the
21818 original string. If it is longer, the functions finds a space in the
21819 string, breaks this string off at that locations and adds three dots
21820 as ellipsis. Including the ellipsis, the string will not be longer
21821 than MAXLENGTH. If finding a good breaking point in the string does
21822 not work, the string is just chopped off in the middle of a word
21823 if necessary."
21824 (if (<= (length s) maxlength)
21826 (let* ((n (max (- maxlength 4) 1))
21827 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21828 (if (string-match re s)
21829 (concat (match-string 1 s) "...")
21830 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21832 (defun org-get-indentation (&optional line)
21833 "Get the indentation of the current line, interpreting tabs.
21834 When LINE is given, assume it represents a line and compute its indentation."
21835 (if line
21836 (when (string-match "^ *" (org-remove-tabs line))
21837 (match-end 0))
21838 (save-excursion
21839 (beginning-of-line 1)
21840 (skip-chars-forward " \t")
21841 (current-column))))
21843 (defun org-get-string-indentation (s)
21844 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21845 (let ((n -1) (i 0) (w tab-width) c)
21846 (catch 'exit
21847 (while (< (setq n (1+ n)) (length s))
21848 (setq c (aref s n))
21849 (cond ((= c ?\ ) (setq i (1+ i)))
21850 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21851 (t (throw 'exit t)))))
21854 (defun org-remove-tabs (s &optional width)
21855 "Replace tabulators in S with spaces.
21856 Assumes that s is a single line, starting in column 0."
21857 (setq width (or width tab-width))
21858 (while (string-match "\t" s)
21859 (setq s (replace-match
21860 (make-string
21861 (- (* width (/ (+ (match-beginning 0) width) width))
21862 (match-beginning 0)) ?\ )
21863 t t s)))
21866 (defun org-fix-indentation (line ind)
21867 "Fix indentation in LINE.
21868 IND is a cons cell with target and minimum indentation.
21869 If the current indentation in LINE is smaller than the minimum,
21870 leave it alone. If it is larger than ind, set it to the target."
21871 (let* ((l (org-remove-tabs line))
21872 (i (org-get-indentation l))
21873 (i1 (car ind)) (i2 (cdr ind)))
21874 (when (>= i i2) (setq l (substring line i2)))
21875 (if (> i1 0)
21876 (concat (make-string i1 ?\ ) l)
21877 l)))
21879 (defun org-remove-indentation (code &optional n)
21880 "Remove maximum common indentation in string CODE and return it.
21881 N may optionally be the number of columns to remove. Return CODE
21882 as-is if removal failed."
21883 (with-temp-buffer
21884 (insert code)
21885 (if (org-do-remove-indentation n) (buffer-string) code)))
21887 (defun org-do-remove-indentation (&optional n)
21888 "Remove the maximum common indentation from the buffer.
21889 When optional argument N is a positive integer, remove exactly
21890 that much characters from indentation, if possible. Return nil
21891 if it fails."
21892 (catch :exit
21893 (goto-char (point-min))
21894 ;; Find maximum common indentation, if not specified.
21895 (let ((n (or n
21896 (let ((min-ind (point-max)))
21897 (save-excursion
21898 (while (re-search-forward "^[ \t]*\\S-" nil t)
21899 (let ((ind (1- (current-column))))
21900 (if (zerop ind) (throw :exit nil)
21901 (setq min-ind (min min-ind ind))))))
21902 min-ind))))
21903 (if (zerop n) (throw :exit nil)
21904 ;; Remove exactly N indentation, but give up if not possible.
21905 (while (not (eobp))
21906 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21907 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21908 ((< ind n) (throw :exit nil))
21909 (t (indent-line-to (- ind n))))
21910 (forward-line)))
21911 ;; Signal success.
21912 t))))
21914 (defun org-fill-template (template alist)
21915 "Find each %key of ALIST in TEMPLATE and replace it."
21916 (let ((case-fold-search nil))
21917 (dolist (entry (sort (copy-sequence alist)
21918 (lambda (a b) (< (length (car a)) (length (car b))))))
21919 (setq template
21920 (replace-regexp-in-string
21921 (concat "%" (regexp-quote (car entry)))
21922 (or (cdr entry) "") template t t)))
21923 template))
21925 (defun org-base-buffer (buffer)
21926 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21927 (if (not buffer)
21928 buffer
21929 (or (buffer-base-buffer buffer)
21930 buffer)))
21932 (defun org-wrap (string &optional width lines)
21933 "Wrap string to either a number of lines, or a width in characters.
21934 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21935 that costs. If there is a word longer than WIDTH, the text is actually
21936 wrapped to the length of that word.
21937 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21938 many lines, whatever width that takes.
21939 The return value is a list of lines, without newlines at the end."
21940 (let* ((words (org-split-string string "[ \t\n]+"))
21941 (maxword (apply 'max (mapcar 'org-string-width words)))
21942 w ll)
21943 (cond (width
21944 (org-do-wrap words (max maxword width)))
21945 (lines
21946 (setq w maxword)
21947 (setq ll (org-do-wrap words maxword))
21948 (if (<= (length ll) lines)
21950 (setq ll words)
21951 (while (> (length ll) lines)
21952 (setq w (1+ w))
21953 (setq ll (org-do-wrap words w)))
21954 ll))
21955 (t (error "Cannot wrap this")))))
21957 (defun org-do-wrap (words width)
21958 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21959 (let (lines line)
21960 (while words
21961 (setq line (pop words))
21962 (while (and words (< (+ (length line) (length (car words))) width))
21963 (setq line (concat line " " (pop words))))
21964 (setq lines (push line lines)))
21965 (nreverse lines)))
21967 (defun org-split-string (string &optional separators)
21968 "Splits STRING into substrings at SEPARATORS.
21969 SEPARATORS is a regular expression.
21970 No empty strings are returned if there are matches at the beginning
21971 and end of string."
21972 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21973 (let ((start 0) notfirst list)
21974 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21975 (if (and notfirst
21976 (= start (match-beginning 0))
21977 (< start (length string)))
21978 (1+ start) start))
21979 (< (match-beginning 0) (length string)))
21980 (setq notfirst t)
21981 (or (eq (match-beginning 0) 0)
21982 (and (eq (match-beginning 0) (match-end 0))
21983 (eq (match-beginning 0) start))
21984 (push (substring string start (match-beginning 0)) list))
21985 (setq start (match-end 0)))
21986 (or (eq start (length string))
21987 (push (substring string start) list))
21988 (nreverse list)))
21990 (defun org-quote-vert (s)
21991 "Replace \"|\" with \"\\vert\"."
21992 (while (string-match "|" s)
21993 (setq s (replace-match "\\vert" t t s)))
21996 (defun org-uuidgen-p (s)
21997 "Is S an ID created by UUIDGEN?"
21998 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22000 (defun org-in-src-block-p (&optional inside)
22001 "Whether point is in a code source block.
22002 When INSIDE is non-nil, don't consider we are within a src block
22003 when point is at #+BEGIN_SRC or #+END_SRC."
22004 (let ((case-fold-search t))
22005 (or (and (eq (get-char-property (point) 'src-block) t))
22006 (and (not inside)
22007 (save-match-data
22008 (save-excursion
22009 (beginning-of-line)
22010 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22012 (defun org-context ()
22013 "Return a list of contexts of the current cursor position.
22014 If several contexts apply, all are returned.
22015 Each context entry is a list with a symbol naming the context, and
22016 two positions indicating start and end of the context. Possible
22017 contexts are:
22019 :headline anywhere in a headline
22020 :headline-stars on the leading stars in a headline
22021 :todo-keyword on a TODO keyword (including DONE) in a headline
22022 :tags on the TAGS in a headline
22023 :priority on the priority cookie in a headline
22024 :item on the first line of a plain list item
22025 :item-bullet on the bullet/number of a plain list item
22026 :checkbox on the checkbox in a plain list item
22027 :table in an Org table
22028 :table-special on a special filed in a table
22029 :table-table in a table.el table
22030 :clocktable in a clocktable
22031 :src-block in a source block
22032 :link on a hyperlink
22033 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22034 :target on a <<target>>
22035 :radio-target on a <<<radio-target>>>
22036 :latex-fragment on a LaTeX fragment
22037 :latex-preview on a LaTeX fragment with overlaid preview image
22039 This function expects the position to be visible because it uses font-lock
22040 faces as a help to recognize the following contexts: :table-special, :link,
22041 and :keyword."
22042 (let* ((f (get-text-property (point) 'face))
22043 (faces (if (listp f) f (list f)))
22044 (case-fold-search t)
22045 (p (point)) clist o)
22046 ;; First the large context
22047 (cond
22048 ((org-at-heading-p t)
22049 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22050 (when (progn
22051 (beginning-of-line 1)
22052 (looking-at org-todo-line-tags-regexp))
22053 (push (org-point-in-group p 1 :headline-stars) clist)
22054 (push (org-point-in-group p 2 :todo-keyword) clist)
22055 (push (org-point-in-group p 4 :tags) clist))
22056 (goto-char p)
22057 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22058 (when (looking-at "\\[#[A-Z0-9]\\]")
22059 (push (org-point-in-group p 0 :priority) clist)))
22061 ((org-at-item-p)
22062 (push (org-point-in-group p 2 :item-bullet) clist)
22063 (push (list :item (point-at-bol)
22064 (save-excursion (org-end-of-item) (point)))
22065 clist)
22066 (and (org-at-item-checkbox-p)
22067 (push (org-point-in-group p 0 :checkbox) clist)))
22069 ((org-at-table-p)
22070 (push (list :table (org-table-begin) (org-table-end)) clist)
22071 (when (memq 'org-formula faces)
22072 (push (list :table-special
22073 (previous-single-property-change p 'face)
22074 (next-single-property-change p 'face)) clist)))
22075 ((org-at-table-p 'any)
22076 (push (list :table-table) clist)))
22077 (goto-char p)
22079 (let ((case-fold-search t))
22080 ;; New the "medium" contexts: clocktables, source blocks
22081 (cond ((org-in-clocktable-p)
22082 (push (list :clocktable
22083 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22084 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22085 (match-beginning 1))
22086 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22087 (match-end 0))) clist))
22088 ((org-in-src-block-p)
22089 (push (list :src-block
22090 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22091 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22092 (match-beginning 1))
22093 (and (search-forward "#+END_SRC" nil t)
22094 (match-beginning 0))) clist))))
22095 (goto-char p)
22097 ;; Now the small context
22098 (cond
22099 ((org-at-timestamp-p)
22100 (push (org-point-in-group p 0 :timestamp) clist))
22101 ((memq 'org-link faces)
22102 (push (list :link
22103 (previous-single-property-change p 'face)
22104 (next-single-property-change p 'face)) clist))
22105 ((memq 'org-special-keyword faces)
22106 (push (list :keyword
22107 (previous-single-property-change p 'face)
22108 (next-single-property-change p 'face)) clist))
22109 ((org-at-target-p)
22110 (push (org-point-in-group p 0 :target) clist)
22111 (goto-char (1- (match-beginning 0)))
22112 (when (looking-at org-radio-target-regexp)
22113 (push (org-point-in-group p 0 :radio-target) clist))
22114 (goto-char p))
22115 ((setq o (cl-some
22116 (lambda (o)
22117 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22119 (overlays-at (point))))
22120 (push (list :latex-fragment
22121 (overlay-start o) (overlay-end o)) clist)
22122 (push (list :latex-preview
22123 (overlay-start o) (overlay-end o)) clist))
22124 ((org-inside-LaTeX-fragment-p)
22125 ;; FIXME: positions wrong.
22126 (push (list :latex-fragment (point) (point)) clist)))
22128 (setq clist (nreverse (delq nil clist)))
22129 clist))
22131 (defun org-in-regexp (regexp &optional nlines visually)
22132 "Check if point is inside a match of REGEXP.
22134 Normally only the current line is checked, but you can include
22135 NLINES extra lines around point into the search. If VISUALLY is
22136 set, require that the cursor is not after the match but really
22137 on, so that the block visually is on the match.
22139 Return nil or a cons cell (BEG . END) where BEG and END are,
22140 respectively, the positions at the beginning and the end of the
22141 match."
22142 (catch :exit
22143 (let ((pos (point))
22144 (eol (line-end-position (if nlines (1+ nlines) 1))))
22145 (save-excursion
22146 (beginning-of-line (- 1 (or nlines 0)))
22147 (while (and (re-search-forward regexp eol t)
22148 (<= (match-beginning 0) pos))
22149 (let ((end (match-end 0)))
22150 (when (or (> end pos) (and (= end pos) (not visually)))
22151 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22153 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22154 "Non-nil when point is between matches of START-RE and END-RE.
22156 Also return a non-nil value when point is on one of the matches.
22158 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22159 buffer positions. Default values are the positions of headlines
22160 surrounding the point.
22162 The functions returns a cons cell whose car (resp. cdr) is the
22163 position before START-RE (resp. after END-RE)."
22164 (save-match-data
22165 (let ((pos (point))
22166 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22167 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22168 beg end)
22169 (save-excursion
22170 ;; Point is on a block when on START-RE or if START-RE can be
22171 ;; found before it...
22172 (and (or (org-in-regexp start-re)
22173 (re-search-backward start-re limit-up t))
22174 (setq beg (match-beginning 0))
22175 ;; ... and END-RE after it...
22176 (goto-char (match-end 0))
22177 (re-search-forward end-re limit-down t)
22178 (> (setq end (match-end 0)) pos)
22179 ;; ... without another START-RE in-between.
22180 (goto-char (match-beginning 0))
22181 (not (re-search-backward start-re (1+ beg) t))
22182 ;; Return value.
22183 (cons beg end))))))
22185 (defun org-in-block-p (names)
22186 "Non-nil when point belongs to a block whose name belongs to NAMES.
22188 NAMES is a list of strings containing names of blocks.
22190 Return first block name matched, or nil. Beware that in case of
22191 nested blocks, the returned name may not belong to the closest
22192 block from point."
22193 (save-match-data
22194 (catch 'exit
22195 (let ((case-fold-search t)
22196 (lim-up (save-excursion (outline-previous-heading)))
22197 (lim-down (save-excursion (outline-next-heading))))
22198 (dolist (name names)
22199 (let ((n (regexp-quote name)))
22200 (when (org-between-regexps-p
22201 (concat "^[ \t]*#\\+begin_" n)
22202 (concat "^[ \t]*#\\+end_" n)
22203 lim-up lim-down)
22204 (throw 'exit n)))))
22205 nil)))
22207 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22208 "Call `multi-occur' with buffers for all agenda files."
22209 (interactive "sOrg-files matching: ")
22210 (let* ((files (org-agenda-files))
22211 (tnames (mapcar #'file-truename files))
22212 (extra org-agenda-text-search-extra-files))
22213 (when (eq (car extra) 'agenda-archives)
22214 (setq extra (cdr extra))
22215 (setq files (org-add-archive-files files)))
22216 (dolist (f extra)
22217 (unless (member (file-truename f) tnames)
22218 (unless (member f files) (setq files (append files (list f))))
22219 (setq tnames (append tnames (list (file-truename f))))))
22220 (multi-occur
22221 (mapcar (lambda (x)
22222 (with-current-buffer
22223 ;; FIXME: Why not just (find-file-noselect x)?
22224 ;; Is it to avoid the "revert buffer" prompt?
22225 (or (get-file-buffer x) (find-file-noselect x))
22226 (widen)
22227 (current-buffer)))
22228 files)
22229 regexp)))
22231 (add-hook 'occur-mode-find-occurrence-hook
22232 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22234 (defun org-occur-link-in-agenda-files ()
22235 "Create a link and search for it in the agendas.
22236 The link is not stored in `org-stored-links', it is just created
22237 for the search purpose."
22238 (interactive)
22239 (let ((link (condition-case nil
22240 (org-store-link nil)
22241 (error "Unable to create a link to here"))))
22242 (org-occur-in-agenda-files (regexp-quote link))))
22244 (defun org-reverse-string (string)
22245 "Return the reverse of STRING."
22246 (apply 'string (reverse (string-to-list string))))
22248 ;; defsubst org-uniquify must be defined before first use
22250 (defun org-uniquify-alist (alist)
22251 "Merge elements of ALIST with the same key.
22253 For example, in this alist:
22255 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22256 => \\='((a 1 3) (b 2))
22258 merge (a 1) and (a 3) into (a 1 3).
22260 The function returns the new ALIST."
22261 (let (rtn)
22262 (dolist (e alist rtn)
22263 (let (n)
22264 (if (not (assoc (car e) rtn))
22265 (push e rtn)
22266 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22267 (setq rtn (assq-delete-all (car e) rtn))
22268 (push n rtn))))))
22270 (defun org-delete-all (elts list)
22271 "Remove all elements in ELTS from LIST.
22272 Comparison is done with `equal'. It is a destructive operation
22273 that may remove elements by altering the list structure."
22274 (while elts
22275 (setq list (delete (pop elts) list)))
22276 list)
22278 (defun org-back-over-empty-lines ()
22279 "Move backwards over whitespace, to the beginning of the first empty line.
22280 Returns the number of empty lines passed."
22281 (let ((pos (point)))
22282 (if (cdr (assq 'heading org-blank-before-new-entry))
22283 (skip-chars-backward " \t\n\r")
22284 (unless (eobp)
22285 (forward-line -1)))
22286 (beginning-of-line 2)
22287 (goto-char (min (point) pos))
22288 (count-lines (point) pos)))
22290 (defun org-skip-whitespace ()
22291 (skip-chars-forward " \t\n\r"))
22293 (defun org-point-in-group (point group &optional context)
22294 "Check if POINT is in match-group GROUP.
22295 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22296 match. If the match group does not exist or point is not inside it,
22297 return nil."
22298 (and (match-beginning group)
22299 (>= point (match-beginning group))
22300 (<= point (match-end group))
22301 (if context
22302 (list context (match-beginning group) (match-end group))
22303 t)))
22305 (defun org-switch-to-buffer-other-window (&rest args)
22306 "Switch to buffer in a second window on the current frame.
22307 In particular, do not allow pop-up frames.
22308 Returns the newly created buffer."
22309 (org-no-popups
22310 (apply 'switch-to-buffer-other-window args)))
22312 (defun org-combine-plists (&rest plists)
22313 "Create a single property list from all plists in PLISTS.
22314 The process starts by copying the first list, and then setting properties
22315 from the other lists. Settings in the last list are the most significant
22316 ones and overrule settings in the other lists."
22317 (let ((rtn (copy-sequence (pop plists)))
22318 p v ls)
22319 (while plists
22320 (setq ls (pop plists))
22321 (while ls
22322 (setq p (pop ls) v (pop ls))
22323 (setq rtn (plist-put rtn p v))))
22324 rtn))
22326 (defun org-replace-escapes (string table)
22327 "Replace %-escapes in STRING with values in TABLE.
22328 TABLE is an association list with keys like \"%a\" and string values.
22329 The sequences in STRING may contain normal field width and padding information,
22330 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22331 so values can contain further %-escapes if they are define later in TABLE."
22332 (let ((tbl (copy-alist table))
22333 (case-fold-search nil)
22334 (pchg 0)
22335 re rpl)
22336 (dolist (e tbl)
22337 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22338 (when (and (cdr e) (string-match re (cdr e)))
22339 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22340 (safe "SREF"))
22341 (add-text-properties 0 3 (list 'sref sref) safe)
22342 (setcdr e (replace-match safe t t (cdr e)))))
22343 (while (string-match re string)
22344 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22345 (cdr e)))
22346 (setq string (replace-match rpl t t string))))
22347 (while (setq pchg (next-property-change pchg string))
22348 (let ((sref (get-text-property pchg 'sref string)))
22349 (when (and sref (string-match "SREF" string pchg))
22350 (setq string (replace-match sref t t string)))))
22351 string))
22353 (defun org-find-base-buffer-visiting (file)
22354 "Like `find-buffer-visiting' but always return the base buffer and
22355 not an indirect buffer."
22356 (let ((buf (or (get-file-buffer file)
22357 (find-buffer-visiting file))))
22358 (if buf
22359 (or (buffer-base-buffer buf) buf)
22360 nil)))
22362 ;;; TODO: Only called once, from ox-odt which should probably use
22363 ;;; org-export-inline-image-p or something.
22364 (defun org-file-image-p (file)
22365 "Return non-nil if FILE is an image."
22366 (save-match-data
22367 (string-match (image-file-name-regexp) file)))
22369 (defun org-get-cursor-date (&optional with-time)
22370 "Return the date at cursor in as a time.
22371 This works in the calendar and in the agenda, anywhere else it just
22372 returns the current time.
22373 If WITH-TIME is non-nil, returns the time of the event at point (in
22374 the agenda) or the current time of the day."
22375 (let (date day defd tp hod mod)
22376 (when with-time
22377 (setq tp (get-text-property (point) 'time))
22378 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22379 (setq hod (string-to-number (match-string 1 tp))
22380 mod (string-to-number (match-string 2 tp))))
22381 (or tp (let ((now (decode-time)))
22382 (setq hod (nth 2 now)
22383 mod (nth 1 now)))))
22384 (cond
22385 ((eq major-mode 'calendar-mode)
22386 (setq date (calendar-cursor-to-date)
22387 defd (encode-time 0 (or mod 0) (or hod 0)
22388 (nth 1 date) (nth 0 date) (nth 2 date))))
22389 ((eq major-mode 'org-agenda-mode)
22390 (setq day (get-text-property (point) 'day))
22391 (when day
22392 (setq date (calendar-gregorian-from-absolute day)
22393 defd (encode-time 0 (or mod 0) (or hod 0)
22394 (nth 1 date) (nth 0 date) (nth 2 date))))))
22395 (or defd (current-time))))
22397 (defun org-mark-subtree (&optional up)
22398 "Mark the current subtree.
22399 This puts point at the start of the current subtree, and mark at
22400 the end. If a numeric prefix UP is given, move up into the
22401 hierarchy of headlines by UP levels before marking the subtree."
22402 (interactive "P")
22403 (org-with-limited-levels
22404 (cond ((org-at-heading-p) (beginning-of-line))
22405 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22406 (t (outline-previous-visible-heading 1))))
22407 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22408 (if (called-interactively-p 'any)
22409 (call-interactively 'org-mark-element)
22410 (org-mark-element)))
22412 (defun org-file-newer-than-p (file time)
22413 "Non-nil if FILE is newer than TIME.
22414 FILE is a filename, as a string, TIME is a list of integers, as
22415 returned by, e.g., `current-time'."
22416 (and (file-exists-p file)
22417 ;; Only compare times up to whole seconds as some file-systems
22418 ;; (e.g. HFS+) do not retain any finer granularity. As
22419 ;; a consequence, make sure we return non-nil when the two
22420 ;; times are equal.
22421 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22422 (cl-subseq time 0 2)))))
22424 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22425 "Compile a SOURCE file using PROCESS.
22427 PROCESS is either a function or a list of shell commands, as
22428 strings. EXT is a file extension, without the leading dot, as
22429 a string. It is used to check if the process actually succeeded.
22431 PROCESS must create a file with the same base name and directory
22432 as SOURCE, but ending with EXT. The function then returns its
22433 filename. Otherwise, it raises an error. The error message can
22434 then be refined by providing string ERR-MSG, which is appended to
22435 the standard message.
22437 If PROCESS is a function, it is called with a single argument:
22438 the SOURCE file.
22440 If it is a list of commands, each of them is called using
22441 `shell-command'. By default, in each command, %b, %f, %F, %o and
22442 %O are replaced with, respectively, SOURCE base name, name, full
22443 name, directory and absolute output file name. It is possible,
22444 however, to use more place-holders by specifying them in optional
22445 argument SPEC, as an alist following the pattern
22447 (CHARACTER . REPLACEMENT-STRING).
22449 When PROCESS is a list of commands, optional argument LOG-BUF can
22450 be set to a buffer or a buffer name. `shell-command' then uses
22451 it for output."
22452 (let* ((base-name (file-name-base source))
22453 (full-name (file-truename source))
22454 (out-dir (or (file-name-directory source) "./"))
22455 (output (expand-file-name (concat base-name "." ext) out-dir))
22456 (time (current-time))
22457 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22458 (save-window-excursion
22459 (pcase process
22460 ((pred functionp) (funcall process (shell-quote-argument source)))
22461 ((pred consp)
22462 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22463 (spec (append spec
22464 `((?b . ,(shell-quote-argument base-name))
22465 (?f . ,(shell-quote-argument source))
22466 (?F . ,(shell-quote-argument full-name))
22467 (?o . ,(shell-quote-argument out-dir))
22468 (?O . ,(shell-quote-argument output))))))
22469 (dolist (command process)
22470 (shell-command (format-spec command spec) log-buf))
22471 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22472 (_ (error "No valid command to process %S%s" source err-msg))))
22473 ;; Check for process failure. Output file is expected to be
22474 ;; located in the same directory as SOURCE.
22475 (unless (org-file-newer-than-p output time)
22476 (error (format "File %S wasn't produced%s" output err-msg)))
22477 output))
22479 ;;; Indentation
22481 (defun org--get-expected-indentation (element contentsp)
22482 "Expected indentation column for current line, according to ELEMENT.
22483 ELEMENT is an element containing point. CONTENTSP is non-nil
22484 when indentation is to be computed according to contents of
22485 ELEMENT."
22486 (let ((type (org-element-type element))
22487 (start (org-element-property :begin element))
22488 (post-affiliated (org-element-property :post-affiliated element)))
22489 (org-with-wide-buffer
22490 (cond
22491 (contentsp
22492 (cl-case type
22493 ((diary-sexp footnote-definition) 0)
22494 ((headline inlinetask nil)
22495 (if (not org-adapt-indentation) 0
22496 (let ((level (org-current-level)))
22497 (if level (1+ level) 0))))
22498 ((item plain-list) (org-list-item-body-column post-affiliated))
22500 (goto-char start)
22501 (org-get-indentation))))
22502 ((memq type '(headline inlinetask nil))
22503 (if (org-match-line "[ \t]*$")
22504 (org--get-expected-indentation element t)
22506 ((memq type '(diary-sexp footnote-definition)) 0)
22507 ;; First paragraph of a footnote definition or an item.
22508 ;; Indent like parent.
22509 ((< (line-beginning-position) start)
22510 (org--get-expected-indentation
22511 (org-element-property :parent element) t))
22512 ;; At first line: indent according to previous sibling, if any,
22513 ;; ignoring footnote definitions and inline tasks, or parent's
22514 ;; contents.
22515 ((= (line-beginning-position) start)
22516 (catch 'exit
22517 (while t
22518 (if (= (point-min) start) (throw 'exit 0)
22519 (goto-char (1- start))
22520 (let* ((previous (org-element-at-point))
22521 (parent previous))
22522 (while (and parent (<= (org-element-property :end parent) start))
22523 (setq previous parent
22524 parent (org-element-property :parent parent)))
22525 (cond
22526 ((not previous) (throw 'exit 0))
22527 ((> (org-element-property :end previous) start)
22528 (throw 'exit (org--get-expected-indentation previous t)))
22529 ((memq (org-element-type previous)
22530 '(footnote-definition inlinetask))
22531 (setq start (org-element-property :begin previous)))
22532 (t (goto-char (org-element-property :begin previous))
22533 (throw 'exit
22534 (if (bolp) (org-get-indentation)
22535 ;; At first paragraph in an item or
22536 ;; a footnote definition.
22537 (org--get-expected-indentation
22538 (org-element-property :parent previous) t))))))))))
22539 ;; Otherwise, move to the first non-blank line above.
22541 (beginning-of-line)
22542 (let ((pos (point)))
22543 (skip-chars-backward " \r\t\n")
22544 (cond
22545 ;; Two blank lines end a footnote definition or a plain
22546 ;; list. When we indent an empty line after them, the
22547 ;; containing list or footnote definition is over, so it
22548 ;; qualifies as a previous sibling. Therefore, we indent
22549 ;; like its first line.
22550 ((and (memq type '(footnote-definition plain-list))
22551 (> (count-lines (point) pos) 2))
22552 (goto-char start)
22553 (org-get-indentation))
22554 ;; Line above is the first one of a paragraph at the
22555 ;; beginning of an item or a footnote definition. Indent
22556 ;; like parent.
22557 ((< (line-beginning-position) start)
22558 (org--get-expected-indentation
22559 (org-element-property :parent element) t))
22560 ;; Line above is the beginning of an element, i.e., point
22561 ;; was originally on the blank lines between element's start
22562 ;; and contents.
22563 ((= (line-beginning-position) post-affiliated)
22564 (org--get-expected-indentation element t))
22565 ;; POS is after contents in a greater element. Indent like
22566 ;; the beginning of the element.
22568 ;; As a special case, if point is at the end of a footnote
22569 ;; definition or an item, indent like the very last element
22570 ;; within. If that last element is an item, indent like its
22571 ;; contents.
22572 ((and (not (eq type 'paragraph))
22573 (let ((cend (org-element-property :contents-end element)))
22574 (and cend (<= cend pos))))
22575 (if (memq type '(footnote-definition item plain-list))
22576 (let ((last (org-element-at-point)))
22577 (org--get-expected-indentation
22578 last (eq (org-element-type last) 'item)))
22579 (goto-char start)
22580 (org-get-indentation)))
22581 ;; In any other case, indent like the current line.
22582 (t (org-get-indentation)))))))))
22584 (defun org--align-node-property ()
22585 "Align node property at point.
22586 Alignment is done according to `org-property-format', which see."
22587 (when (save-excursion
22588 (beginning-of-line)
22589 (looking-at org-property-re))
22590 (replace-match
22591 (concat (match-string 4)
22592 (org-trim
22593 (format org-property-format (match-string 1) (match-string 3))))
22594 t t)))
22596 (defun org-indent-line ()
22597 "Indent line depending on context.
22599 Indentation is done according to the following rules:
22601 - Footnote definitions, diary sexps, headlines and inline tasks
22602 have to start at column 0.
22604 - On the very first line of an element, consider, in order, the
22605 next rules until one matches:
22607 1. If there's a sibling element before, ignoring footnote
22608 definitions and inline tasks, indent like its first line.
22610 2. If element has a parent, indent like its contents. More
22611 precisely, if parent is an item, indent after the
22612 description part, if any, or the bullet (see
22613 `org-list-description-max-indent'). Else, indent like
22614 parent's first line.
22616 3. Otherwise, indent relatively to current level, if
22617 `org-adapt-indentation' is non-nil, or to left margin.
22619 - On a blank line at the end of an element, indent according to
22620 the type of the element. More precisely
22622 1. If element is a plain list, an item, or a footnote
22623 definition, indent like the very last element within.
22625 2. If element is a paragraph, indent like its last non blank
22626 line.
22628 3. Otherwise, indent like its very first line.
22630 - In the code part of a source block, use language major mode
22631 to indent current line if `org-src-tab-acts-natively' is
22632 non-nil. If it is nil, do nothing.
22634 - Otherwise, indent like the first non-blank line above.
22636 The function doesn't indent an item as it could break the whole
22637 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22638 `\\[org-shiftmetaright]'.
22640 Also align node properties according to `org-property-format'."
22641 (interactive)
22642 (cond
22643 (orgstruct-is-++
22644 (let ((indent-line-function
22645 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22646 (indent-according-to-mode)))
22647 ((org-at-heading-p) 'noindent)
22649 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22650 (type (org-element-type element)))
22651 (cond ((and (memq type '(plain-list item))
22652 (= (line-beginning-position)
22653 (org-element-property :post-affiliated element)))
22654 'noindent)
22655 ((and (eq type 'latex-environment)
22656 (>= (point) (org-element-property :post-affiliated element))
22657 (< (point) (org-with-wide-buffer
22658 (goto-char (org-element-property :end element))
22659 (skip-chars-backward " \r\t\n")
22660 (line-beginning-position 2))))
22661 'noindent)
22662 ((and (eq type 'src-block)
22663 org-src-tab-acts-natively
22664 (> (line-beginning-position)
22665 (org-element-property :post-affiliated element))
22666 (< (line-beginning-position)
22667 (org-with-wide-buffer
22668 (goto-char (org-element-property :end element))
22669 (skip-chars-backward " \r\t\n")
22670 (line-beginning-position))))
22671 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22673 (let ((column (org--get-expected-indentation element nil)))
22674 ;; Preserve current column.
22675 (if (<= (current-column) (current-indentation))
22676 (indent-line-to column)
22677 (save-excursion (indent-line-to column))))
22678 ;; Align node property. Also preserve current column.
22679 (when (eq type 'node-property)
22680 (let ((column (current-column)))
22681 (org--align-node-property)
22682 (org-move-to-column column)))))))))
22684 (defun org-indent-region (start end)
22685 "Indent each non-blank line in the region.
22686 Called from a program, START and END specify the region to
22687 indent. The function will not indent contents of example blocks,
22688 verse blocks and export blocks as leading white spaces are
22689 assumed to be significant there."
22690 (interactive "r")
22691 (save-excursion
22692 (goto-char start)
22693 (skip-chars-forward " \r\t\n")
22694 (unless (eobp) (beginning-of-line))
22695 (let ((indent-to
22696 (lambda (ind pos)
22697 ;; Set IND as indentation for all lines between point and
22698 ;; POS. Blank lines are ignored. Leave point after POS
22699 ;; once done.
22700 (let ((limit (copy-marker pos)))
22701 (while (< (point) limit)
22702 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22703 (forward-line))
22704 (set-marker limit nil))))
22705 (end (copy-marker end)))
22706 (while (< (point) end)
22707 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22708 (let* ((element (org-element-at-point))
22709 (type (org-element-type element))
22710 (element-end (copy-marker (org-element-property :end element)))
22711 (ind (org--get-expected-indentation element nil)))
22712 (cond
22713 ;; Element indented as a single block. Example blocks
22714 ;; preserving indentation are a special case since the
22715 ;; "contents" must not be indented whereas the block
22716 ;; boundaries can.
22717 ((or (memq type '(export-block latex-environment))
22718 (and (eq type 'example-block)
22719 (not
22720 (or org-src-preserve-indentation
22721 (org-element-property :preserve-indent element)))))
22722 (let ((offset (- ind (org-get-indentation))))
22723 (unless (zerop offset)
22724 (indent-rigidly (org-element-property :begin element)
22725 (org-element-property :end element)
22726 offset)))
22727 (goto-char element-end))
22728 ;; Elements indented line wise. Be sure to exclude
22729 ;; example blocks (preserving indentation) and source
22730 ;; blocks from this category as they are treated
22731 ;; specially later.
22732 ((or (memq type '(paragraph table table-row))
22733 (not (or (org-element-property :contents-begin element)
22734 (memq type '(example-block src-block)))))
22735 (when (eq type 'node-property)
22736 (org--align-node-property)
22737 (beginning-of-line))
22738 (funcall indent-to ind (min element-end end)))
22739 ;; Elements consisting of three parts: before the
22740 ;; contents, the contents, and after the contents. The
22741 ;; contents are treated specially, according to the
22742 ;; element type, or not indented at all. Other parts are
22743 ;; indented as a single block.
22745 (let* ((post (copy-marker
22746 (org-element-property :post-affiliated element)))
22747 (cbeg
22748 (copy-marker
22749 (cond
22750 ((not (org-element-property :contents-begin element))
22751 ;; Fake contents for source blocks.
22752 (org-with-wide-buffer
22753 (goto-char post)
22754 (line-beginning-position 2)))
22755 ((memq type '(footnote-definition item plain-list))
22756 ;; Contents in these elements could start on
22757 ;; the same line as the beginning of the
22758 ;; element. Make sure we start indenting
22759 ;; from the second line.
22760 (org-with-wide-buffer
22761 (goto-char post)
22762 (end-of-line)
22763 (skip-chars-forward " \r\t\n")
22764 (if (eobp) (point) (line-beginning-position))))
22765 (t (org-element-property :contents-begin element)))))
22766 (cend (copy-marker
22767 (or (org-element-property :contents-end element)
22768 ;; Fake contents for source blocks.
22769 (org-with-wide-buffer
22770 (goto-char element-end)
22771 (skip-chars-backward " \r\t\n")
22772 (line-beginning-position)))
22773 t)))
22774 ;; Do not change items indentation individually as it
22775 ;; might break the list as a whole. On the other
22776 ;; hand, when at a plain list, indent it as a whole.
22777 (cond ((eq type 'plain-list)
22778 (let ((offset (- ind (org-get-indentation))))
22779 (unless (zerop offset)
22780 (indent-rigidly (org-element-property :begin element)
22781 (org-element-property :end element)
22782 offset))
22783 (goto-char cbeg)))
22784 ((eq type 'item) (goto-char cbeg))
22785 (t (funcall indent-to ind (min cbeg end))))
22786 (when (< (point) end)
22787 (cl-case type
22788 ((example-block verse-block))
22789 (src-block
22790 ;; In a source block, indent source code
22791 ;; according to language major mode, but only if
22792 ;; `org-src-tab-acts-natively' is non-nil.
22793 (when (and (< (point) end) org-src-tab-acts-natively)
22794 (ignore-errors
22795 (org-babel-do-in-edit-buffer
22796 (indent-region (point-min) (point-max))))))
22797 (t (org-indent-region (point) (min cend end))))
22798 (goto-char (min cend end))
22799 (when (< (point) end)
22800 (funcall indent-to ind (min element-end end))))
22801 (set-marker post nil)
22802 (set-marker cbeg nil)
22803 (set-marker cend nil))))
22804 (set-marker element-end nil))))
22805 (set-marker end nil))))
22807 (defun org-indent-drawer ()
22808 "Indent the drawer at point."
22809 (interactive)
22810 (unless (save-excursion
22811 (beginning-of-line)
22812 (looking-at-p org-drawer-regexp))
22813 (user-error "Not at a drawer"))
22814 (let ((element (org-element-at-point)))
22815 (unless (memq (org-element-type element) '(drawer property-drawer))
22816 (user-error "Not at a drawer"))
22817 (org-with-wide-buffer
22818 (org-indent-region (org-element-property :begin element)
22819 (org-element-property :end element))))
22820 (message "Drawer at point indented"))
22822 (defun org-indent-block ()
22823 "Indent the block at point."
22824 (interactive)
22825 (unless (save-excursion
22826 (beginning-of-line)
22827 (let ((case-fold-search t))
22828 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22829 (user-error "Not at a block"))
22830 (let ((element (org-element-at-point)))
22831 (unless (memq (org-element-type element)
22832 '(comment-block center-block dynamic-block example-block
22833 export-block quote-block special-block
22834 src-block verse-block))
22835 (user-error "Not at a block"))
22836 (org-with-wide-buffer
22837 (org-indent-region (org-element-property :begin element)
22838 (org-element-property :end element))))
22839 (message "Block at point indented"))
22842 ;;; Filling
22844 ;; We use our own fill-paragraph and auto-fill functions.
22846 ;; `org-fill-paragraph' relies on adaptive filling and context
22847 ;; checking. Appropriate `fill-prefix' is computed with
22848 ;; `org-adaptive-fill-function'.
22850 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22851 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22852 ;; `org-adaptive-fill-function' value. Internally,
22853 ;; `org-comment-line-break-function' breaks the line.
22855 ;; `org-setup-filling' installs filling and auto-filling related
22856 ;; variables during `org-mode' initialization.
22858 (defvar org-element-paragraph-separate) ; org-element.el
22859 (defun org-setup-filling ()
22860 (require 'org-element)
22861 ;; Prevent auto-fill from inserting unwanted new items.
22862 (when (boundp 'fill-nobreak-predicate)
22863 (setq-local
22864 fill-nobreak-predicate
22865 (org-uniquify
22866 (append fill-nobreak-predicate
22867 '(org-fill-line-break-nobreak-p
22868 org-fill-paragraph-with-timestamp-nobreak-p)))))
22869 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22870 (setq-local paragraph-start paragraph-ending)
22871 (setq-local paragraph-separate paragraph-ending))
22872 (setq-local fill-paragraph-function 'org-fill-paragraph)
22873 (setq-local auto-fill-inhibit-regexp nil)
22874 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22875 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22876 (setq-local comment-line-break-function 'org-comment-line-break-function))
22878 (defun org-fill-line-break-nobreak-p ()
22879 "Non-nil when a new line at point would create an Org line break."
22880 (save-excursion
22881 (skip-chars-backward "[ \t]")
22882 (skip-chars-backward "\\\\")
22883 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22885 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22886 "Non-nil when a new line at point would split a timestamp."
22887 (and (org-at-timestamp-p t)
22888 (not (looking-at org-ts-regexp-both))))
22890 (declare-function message-in-body-p "message" ())
22891 (defvar orgtbl-line-start-regexp) ; From org-table.el
22892 (defun org-adaptive-fill-function ()
22893 "Compute a fill prefix for the current line.
22894 Return fill prefix, as a string, or nil if current line isn't
22895 meant to be filled. For convenience, if `adaptive-fill-regexp'
22896 matches in paragraphs or comments, use it."
22897 (catch 'exit
22898 (when (derived-mode-p 'message-mode)
22899 (save-excursion
22900 (beginning-of-line)
22901 (cond ((not (message-in-body-p)) (throw 'exit nil))
22902 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22903 ((looking-at message-cite-prefix-regexp)
22904 (throw 'exit (match-string-no-properties 0)))
22905 ((looking-at org-outline-regexp)
22906 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22907 (org-with-wide-buffer
22908 (unless (org-at-heading-p)
22909 (let* ((p (line-beginning-position))
22910 (element (save-excursion
22911 (beginning-of-line)
22912 (org-element-at-point)))
22913 (type (org-element-type element))
22914 (post-affiliated (org-element-property :post-affiliated element)))
22915 (unless (< p post-affiliated)
22916 (cl-case type
22917 (comment
22918 (save-excursion
22919 (beginning-of-line)
22920 (looking-at "[ \t]*")
22921 (concat (match-string 0) "# ")))
22922 (footnote-definition "")
22923 ((item plain-list)
22924 (make-string (org-list-item-body-column post-affiliated) ?\s))
22925 (paragraph
22926 ;; Fill prefix is usually the same as the current line,
22927 ;; unless the paragraph is at the beginning of an item.
22928 (let ((parent (org-element-property :parent element)))
22929 (save-excursion
22930 (beginning-of-line)
22931 (cond ((eq (org-element-type parent) 'item)
22932 (make-string (org-list-item-body-column
22933 (org-element-property :begin parent))
22934 ?\s))
22935 ((and adaptive-fill-regexp
22936 ;; Locally disable
22937 ;; `adaptive-fill-function' to let
22938 ;; `fill-context-prefix' handle
22939 ;; `adaptive-fill-regexp' variable.
22940 (let (adaptive-fill-function)
22941 (fill-context-prefix
22942 post-affiliated
22943 (org-element-property :end element)))))
22944 ((looking-at "[ \t]+") (match-string 0))
22945 (t "")))))
22946 (comment-block
22947 ;; Only fill contents if P is within block boundaries.
22948 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22949 (forward-line)
22950 (point)))
22951 (cend (save-excursion
22952 (goto-char (org-element-property :end element))
22953 (skip-chars-backward " \r\t\n")
22954 (line-beginning-position))))
22955 (when (and (>= p cbeg) (< p cend))
22956 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22957 (match-string 0)
22958 "")))))))))))
22960 (declare-function message-goto-body "message" ())
22961 (defvar message-cite-prefix-regexp) ; From message.el
22962 (defun org-fill-paragraph (&optional justify)
22963 "Fill element at point, when applicable.
22965 This function only applies to comment blocks, comments, example
22966 blocks and paragraphs. Also, as a special case, re-align table
22967 when point is at one.
22969 If JUSTIFY is non-nil (interactively, with prefix argument),
22970 justify as well. If `sentence-end-double-space' is non-nil, then
22971 period followed by one space does not end a sentence, so don't
22972 break a line there. The variable `fill-column' controls the
22973 width for filling.
22975 For convenience, when point is at a plain list, an item or
22976 a footnote definition, try to fill the first paragraph within."
22977 (interactive)
22978 (if (and (derived-mode-p 'message-mode)
22979 (or (not (message-in-body-p))
22980 (save-excursion (move-beginning-of-line 1)
22981 (looking-at message-cite-prefix-regexp))))
22982 ;; First ensure filling is correct in message-mode.
22983 (let ((fill-paragraph-function
22984 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22985 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22986 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22987 (paragraph-separate
22988 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22989 (fill-paragraph nil))
22990 (with-syntax-table org-mode-transpose-word-syntax-table
22991 ;; Move to end of line in order to get the first paragraph
22992 ;; within a plain list or a footnote definition.
22993 (let ((element (save-excursion
22994 (end-of-line)
22995 (or (ignore-errors (org-element-at-point))
22996 (user-error "An element cannot be parsed line %d"
22997 (line-number-at-pos (point)))))))
22998 ;; First check if point is in a blank line at the beginning of
22999 ;; the buffer. In that case, ignore filling.
23000 (cl-case (org-element-type element)
23001 ;; Use major mode filling function is src blocks.
23002 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23003 ;; Align Org tables, leave table.el tables as-is.
23004 (table-row (org-table-align) t)
23005 (table
23006 (when (eq (org-element-property :type element) 'org)
23007 (save-excursion
23008 (goto-char (org-element-property :post-affiliated element))
23009 (org-table-align)))
23011 (paragraph
23012 ;; Paragraphs may contain `line-break' type objects.
23013 (let ((beg (max (point-min)
23014 (org-element-property :contents-begin element)))
23015 (end (min (point-max)
23016 (org-element-property :contents-end element))))
23017 ;; Do nothing if point is at an affiliated keyword.
23018 (if (< (line-end-position) beg) t
23019 (when (derived-mode-p 'message-mode)
23020 ;; In `message-mode', do not fill following citation
23021 ;; in current paragraph nor text before message body.
23022 (let ((body-start (save-excursion (message-goto-body))))
23023 (when body-start (setq beg (max body-start beg))))
23024 (when (save-excursion
23025 (re-search-forward
23026 (concat "^" message-cite-prefix-regexp) end t))
23027 (setq end (match-beginning 0))))
23028 ;; Fill paragraph, taking line breaks into account.
23029 (save-excursion
23030 (goto-char beg)
23031 (let ((cuts (list beg)))
23032 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23033 (when (eq 'line-break
23034 (org-element-type
23035 (save-excursion (backward-char)
23036 (org-element-context))))
23037 (push (point) cuts)))
23038 (dolist (c (delq end cuts))
23039 (fill-region-as-paragraph c end justify)
23040 (setq end c))))
23041 t)))
23042 ;; Contents of `comment-block' type elements should be
23043 ;; filled as plain text, but only if point is within block
23044 ;; markers.
23045 (comment-block
23046 (let* ((case-fold-search t)
23047 (beg (save-excursion
23048 (goto-char (org-element-property :begin element))
23049 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23050 (forward-line)
23051 (point)))
23052 (end (save-excursion
23053 (goto-char (org-element-property :end element))
23054 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23055 (line-beginning-position))))
23056 (if (or (< (point) beg) (> (point) end)) t
23057 (fill-region-as-paragraph
23058 (save-excursion (end-of-line)
23059 (re-search-backward "^[ \t]*$" beg 'move)
23060 (line-beginning-position))
23061 (save-excursion (beginning-of-line)
23062 (re-search-forward "^[ \t]*$" end 'move)
23063 (line-beginning-position))
23064 justify))))
23065 ;; Fill comments.
23066 (comment
23067 (let ((begin (org-element-property :post-affiliated element))
23068 (end (org-element-property :end element)))
23069 (when (and (>= (point) begin) (<= (point) end))
23070 (let ((begin (save-excursion
23071 (end-of-line)
23072 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23073 (progn (forward-line) (point))
23074 begin)))
23075 (end (save-excursion
23076 (end-of-line)
23077 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23078 (1- (line-beginning-position))
23079 (skip-chars-backward " \r\t\n")
23080 (line-end-position)))))
23081 ;; Do not fill comments when at a blank line.
23082 (when (> end begin)
23083 (let ((fill-prefix
23084 (save-excursion
23085 (beginning-of-line)
23086 (looking-at "[ \t]*#")
23087 (let ((comment-prefix (match-string 0)))
23088 (goto-char (match-end 0))
23089 (if (looking-at adaptive-fill-regexp)
23090 (concat comment-prefix (match-string 0))
23091 (concat comment-prefix " "))))))
23092 (save-excursion
23093 (fill-region-as-paragraph begin end justify))))))
23095 ;; Ignore every other element.
23096 (otherwise t))))))
23098 (defun org-auto-fill-function ()
23099 "Auto-fill function."
23100 ;; Check if auto-filling is meaningful.
23101 (let ((fc (current-fill-column)))
23102 (when (and fc (> (current-column) fc))
23103 (let* ((fill-prefix (org-adaptive-fill-function))
23104 ;; Enforce empty fill prefix, if required. Otherwise, it
23105 ;; will be computed again.
23106 (adaptive-fill-mode (not (equal fill-prefix ""))))
23107 (when fill-prefix (do-auto-fill))))))
23109 (defun org-comment-line-break-function (&optional soft)
23110 "Break line at point and indent, continuing comment if within one.
23111 The inserted newline is marked hard if variable
23112 `use-hard-newlines' is true, unless optional argument SOFT is
23113 non-nil."
23114 (if soft (insert-and-inherit ?\n) (newline 1))
23115 (save-excursion (forward-char -1) (delete-horizontal-space))
23116 (delete-horizontal-space)
23117 (indent-to-left-margin)
23118 (insert-before-markers-and-inherit fill-prefix))
23121 ;;; Fixed Width Areas
23123 (defun org-toggle-fixed-width ()
23124 "Toggle fixed-width markup.
23126 Add or remove fixed-width markup on current line, whenever it
23127 makes sense. Return an error otherwise.
23129 If a region is active and if it contains only fixed-width areas
23130 or blank lines, remove all fixed-width markup in it. If the
23131 region contains anything else, convert all non-fixed-width lines
23132 to fixed-width ones.
23134 Blank lines at the end of the region are ignored unless the
23135 region only contains such lines."
23136 (interactive)
23137 (if (not (org-region-active-p))
23138 ;; No region:
23140 ;; Remove fixed width marker only in a fixed-with element.
23142 ;; Add fixed width maker in paragraphs, in blank lines after
23143 ;; elements or at the beginning of a headline or an inlinetask,
23144 ;; and before any one-line elements (e.g., a clock).
23145 (progn
23146 (beginning-of-line)
23147 (let* ((element (org-element-at-point))
23148 (type (org-element-type element)))
23149 (cond
23150 ((and (eq type 'fixed-width)
23151 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23152 (replace-match
23153 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23154 ((and (memq type '(babel-call clock comment diary-sexp headline
23155 horizontal-rule keyword paragraph
23156 planning))
23157 (<= (org-element-property :post-affiliated element) (point)))
23158 (skip-chars-forward " \t")
23159 (insert ": "))
23160 ((and (looking-at-p "[ \t]*$")
23161 (or (eq type 'inlinetask)
23162 (save-excursion
23163 (skip-chars-forward " \r\t\n")
23164 (<= (org-element-property :end element) (point)))))
23165 (delete-region (point) (line-end-position))
23166 (org-indent-line)
23167 (insert ": "))
23168 (t (user-error "Cannot insert a fixed-width line here")))))
23169 ;; Region active.
23170 (let* ((begin (save-excursion
23171 (goto-char (region-beginning))
23172 (line-beginning-position)))
23173 (end (copy-marker
23174 (save-excursion
23175 (goto-char (region-end))
23176 (unless (eolp) (beginning-of-line))
23177 (if (save-excursion (re-search-backward "\\S-" begin t))
23178 (progn (skip-chars-backward " \r\t\n") (point))
23179 (point)))))
23180 (all-fixed-width-p
23181 (catch 'not-all-p
23182 (save-excursion
23183 (goto-char begin)
23184 (skip-chars-forward " \r\t\n")
23185 (when (eobp) (throw 'not-all-p nil))
23186 (while (< (point) end)
23187 (let ((element (org-element-at-point)))
23188 (if (eq (org-element-type element) 'fixed-width)
23189 (goto-char (org-element-property :end element))
23190 (throw 'not-all-p nil))))
23191 t))))
23192 (if all-fixed-width-p
23193 (save-excursion
23194 (goto-char begin)
23195 (while (< (point) end)
23196 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23197 (replace-match
23198 "" nil nil nil
23199 (if (= (line-end-position) (match-end 0)) 0 1)))
23200 (forward-line)))
23201 (let ((min-ind (point-max)))
23202 ;; Find minimum indentation across all lines.
23203 (save-excursion
23204 (goto-char begin)
23205 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23206 (setq min-ind 0)
23207 (catch 'zerop
23208 (while (< (point) end)
23209 (unless (looking-at-p "[ \t]*$")
23210 (let ((ind (org-get-indentation)))
23211 (setq min-ind (min min-ind ind))
23212 (when (zerop ind) (throw 'zerop t))))
23213 (forward-line)))))
23214 ;; Loop over all lines and add fixed-width markup everywhere
23215 ;; but in fixed-width lines.
23216 (save-excursion
23217 (goto-char begin)
23218 (while (< (point) end)
23219 (cond
23220 ((org-at-heading-p)
23221 (insert ": ")
23222 (forward-line)
23223 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23224 (insert ":")
23225 (forward-line)))
23226 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23227 (let* ((element (org-element-at-point))
23228 (element-end (org-element-property :end element)))
23229 (if (eq (org-element-type element) 'fixed-width)
23230 (progn (goto-char element-end)
23231 (skip-chars-backward " \r\t\n")
23232 (forward-line))
23233 (let ((limit (min end element-end)))
23234 (while (< (point) limit)
23235 (org-move-to-column min-ind t)
23236 (insert ": ")
23237 (forward-line))))))
23239 (org-move-to-column min-ind t)
23240 (insert ": ")
23241 (forward-line)))))))
23242 (set-marker end nil))))
23245 ;;; Comments
23247 ;; Org comments syntax is quite complex. It requires the entire line
23248 ;; to be just a comment. Also, even with the right syntax at the
23249 ;; beginning of line, some some elements (i.e. verse-block or
23250 ;; example-block) don't accept comments. Usual Emacs comment commands
23251 ;; cannot cope with those requirements. Therefore, Org replaces them.
23253 ;; Org still relies on `comment-dwim', but cannot trust
23254 ;; `comment-only-p'. So, `comment-region-function' and
23255 ;; `uncomment-region-function' both point
23256 ;; to`org-comment-or-uncomment-region'. Eventually,
23257 ;; `org-insert-comment' takes care of insertion of comments at the
23258 ;; beginning of line.
23260 ;; `org-setup-comments-handling' install comments related variables
23261 ;; during `org-mode' initialization.
23263 (defun org-setup-comments-handling ()
23264 (interactive)
23265 (setq-local comment-use-syntax nil)
23266 (setq-local comment-start "# ")
23267 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23268 (setq-local comment-insert-comment-function 'org-insert-comment)
23269 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23270 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23272 (defun org-insert-comment ()
23273 "Insert an empty comment above current line.
23274 If the line is empty, insert comment at its beginning. When
23275 point is within a source block, comment according to the related
23276 major mode."
23277 (if (let ((element (org-element-at-point)))
23278 (and (eq (org-element-type element) 'src-block)
23279 (< (save-excursion
23280 (goto-char (org-element-property :post-affiliated element))
23281 (line-end-position))
23282 (point))
23283 (> (save-excursion
23284 (goto-char (org-element-property :end element))
23285 (skip-chars-backward " \r\t\n")
23286 (line-beginning-position))
23287 (point))))
23288 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23289 (beginning-of-line)
23290 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23291 (open-line 1))
23292 (org-indent-line)
23293 (insert "# ")))
23295 (defvar comment-empty-lines) ; From newcomment.el.
23296 (defun org-comment-or-uncomment-region (beg end &rest _)
23297 "Comment or uncomment each non-blank line in the region.
23298 Uncomment each non-blank line between BEG and END if it only
23299 contains commented lines. Otherwise, comment them. If region is
23300 strictly within a source block, use appropriate comment syntax."
23301 (if (let ((element (org-element-at-point)))
23302 (and (eq (org-element-type element) 'src-block)
23303 (< (save-excursion
23304 (goto-char (org-element-property :post-affiliated element))
23305 (line-end-position))
23306 beg)
23307 (>= (save-excursion
23308 (goto-char (org-element-property :end element))
23309 (skip-chars-backward " \r\t\n")
23310 (line-beginning-position))
23311 end)))
23312 ;; Translate region boundaries for the Org buffer to the source
23313 ;; buffer.
23314 (let ((offset (- end beg)))
23315 (save-excursion
23316 (goto-char beg)
23317 (org-babel-do-in-edit-buffer
23318 (comment-or-uncomment-region (point) (+ offset (point))))))
23319 (save-restriction
23320 ;; Restrict region
23321 (narrow-to-region (save-excursion (goto-char beg)
23322 (skip-chars-forward " \r\t\n" end)
23323 (line-beginning-position))
23324 (save-excursion (goto-char end)
23325 (skip-chars-backward " \r\t\n" beg)
23326 (line-end-position)))
23327 (let ((uncommentp
23328 ;; UNCOMMENTP is non-nil when every non blank line between
23329 ;; BEG and END is a comment.
23330 (save-excursion
23331 (goto-char (point-min))
23332 (while (and (not (eobp))
23333 (let ((element (org-element-at-point)))
23334 (and (eq (org-element-type element) 'comment)
23335 (goto-char (min (point-max)
23336 (org-element-property
23337 :end element)))))))
23338 (eobp))))
23339 (if uncommentp
23340 ;; Only blank lines and comments in region: uncomment it.
23341 (save-excursion
23342 (goto-char (point-min))
23343 (while (not (eobp))
23344 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23345 (replace-match "" nil nil nil 1))
23346 (forward-line)))
23347 ;; Comment each line in region.
23348 (let ((min-indent (point-max)))
23349 ;; First find the minimum indentation across all lines.
23350 (save-excursion
23351 (goto-char (point-min))
23352 (while (and (not (eobp)) (not (zerop min-indent)))
23353 (unless (looking-at "[ \t]*$")
23354 (setq min-indent (min min-indent (current-indentation))))
23355 (forward-line)))
23356 ;; Then loop over all lines.
23357 (save-excursion
23358 (goto-char (point-min))
23359 (while (not (eobp))
23360 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23361 ;; Don't get fooled by invisible text (e.g. link path)
23362 ;; when moving to column MIN-INDENT.
23363 (let ((buffer-invisibility-spec nil))
23364 (org-move-to-column min-indent t))
23365 (insert comment-start))
23366 (forward-line)))))))))
23368 (defun org-comment-dwim (_arg)
23369 "Call `comment-dwim' within a source edit buffer if needed."
23370 (interactive "*P")
23371 (if (org-in-src-block-p)
23372 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23373 (call-interactively 'comment-dwim)))
23376 ;;; Timestamps API
23378 ;; This section contains tools to operate on timestamp objects, as
23379 ;; returned by, e.g. `org-element-context'.
23381 (defun org-timestamp--to-internal-time (timestamp &optional end)
23382 "Encode TIMESTAMP object into Emacs internal time.
23383 Use end of date range or time range when END is non-nil."
23384 (apply #'encode-time
23385 (cons 0
23386 (mapcar
23387 (lambda (prop) (or (org-element-property prop timestamp) 0))
23388 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23389 '(:minute-start :hour-start :day-start :month-start
23390 :year-start))))))
23392 (defun org-timestamp-has-time-p (timestamp)
23393 "Non-nil when TIMESTAMP has a time specified."
23394 (org-element-property :hour-start timestamp))
23396 (defun org-timestamp-format (timestamp format &optional end utc)
23397 "Format a TIMESTAMP object into a string.
23399 FORMAT is a format specifier to be passed to
23400 `format-time-string'.
23402 When optional argument END is non-nil, use end of date-range or
23403 time-range, if possible.
23405 When optional argument UTC is non-nil, time will be expressed as
23406 Universal Time."
23407 (format-time-string
23408 format (org-timestamp--to-internal-time timestamp end)
23409 (and utc t)))
23411 (defun org-timestamp-split-range (timestamp &optional end)
23412 "Extract a TIMESTAMP object from a date or time range.
23414 END, when non-nil, means extract the end of the range.
23415 Otherwise, extract its start.
23417 Return a new timestamp object."
23418 (let ((type (org-element-property :type timestamp)))
23419 (if (memq type '(active inactive diary)) timestamp
23420 (let ((split-ts (org-element-copy timestamp)))
23421 ;; Set new type.
23422 (org-element-put-property
23423 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23424 ;; Copy start properties over end properties if END is
23425 ;; non-nil. Otherwise, copy end properties over `start' ones.
23426 (let ((p-alist '((:minute-start . :minute-end)
23427 (:hour-start . :hour-end)
23428 (:day-start . :day-end)
23429 (:month-start . :month-end)
23430 (:year-start . :year-end))))
23431 (dolist (p-cell p-alist)
23432 (org-element-put-property
23433 split-ts
23434 (funcall (if end #'car #'cdr) p-cell)
23435 (org-element-property
23436 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23437 ;; Eventually refresh `:raw-value'.
23438 (org-element-put-property split-ts :raw-value nil)
23439 (org-element-put-property
23440 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23442 (defun org-timestamp-translate (timestamp &optional boundary)
23443 "Translate TIMESTAMP object to custom format.
23445 Format string is defined in `org-time-stamp-custom-formats',
23446 which see.
23448 When optional argument BOUNDARY is non-nil, it is either the
23449 symbol `start' or `end'. In this case, only translate the
23450 starting or ending part of TIMESTAMP if it is a date or time
23451 range. Otherwise, translate both parts.
23453 Return timestamp as-is if `org-display-custom-times' is nil or if
23454 it has a `diary' type."
23455 (let ((type (org-element-property :type timestamp)))
23456 (if (or (not org-display-custom-times) (eq type 'diary))
23457 (org-element-interpret-data timestamp)
23458 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23459 org-time-stamp-custom-formats)))
23460 (if (and (not boundary) (memq type '(active-range inactive-range)))
23461 (concat (org-timestamp-format timestamp fmt)
23462 "--"
23463 (org-timestamp-format timestamp fmt t))
23464 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23468 ;;; Other stuff.
23470 (defvar reftex-docstruct-symbol)
23471 (defvar org--rds)
23473 (defun org-reftex-citation ()
23474 "Use reftex-citation to insert a citation into the buffer.
23475 This looks for a line like
23477 #+BIBLIOGRAPHY: foo plain option:-d
23479 and derives from it that foo.bib is the bibliography file relevant
23480 for this document. It then installs the necessary environment for RefTeX
23481 to work in this buffer and calls `reftex-citation' to insert a citation
23482 into the buffer.
23484 Export of such citations to both LaTeX and HTML is handled by the contributed
23485 package ox-bibtex by Taru Karttunen."
23486 (interactive)
23487 (let ((reftex-docstruct-symbol 'org--rds)
23488 org--rds bib)
23489 (org-with-wide-buffer
23490 (let ((case-fold-search t)
23491 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23492 (if (not (save-excursion
23493 (or (re-search-forward re nil t)
23494 (re-search-backward re nil t))))
23495 (user-error "No bibliography defined in file")
23496 (setq bib (concat (match-string 1) ".bib")
23497 org--rds (list (list 'bib bib))))))
23498 (call-interactively 'reftex-citation)))
23500 ;;;; Functions extending outline functionality
23502 (defun org-beginning-of-line (&optional n)
23503 "Go to the beginning of the current visible line.
23505 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23506 tags on the first attempt, and only move to after the tags when
23507 the cursor is already beyond the end of the headline.
23509 With argument N not nil or 1, move forward N - 1 lines first."
23510 (interactive "^p")
23511 (let ((origin (point))
23512 (special (pcase org-special-ctrl-a/e
23513 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23514 deactivate-mark)
23515 ;; First move to a visible line.
23516 (if (bound-and-true-p visual-line-mode)
23517 (beginning-of-visual-line n)
23518 (move-beginning-of-line n)
23519 ;; `move-beginning-of-line' may leave point after invisible
23520 ;; characters if line starts with such of these (e.g., with
23521 ;; a link at column 0). Really move to the beginning of the
23522 ;; current visible line.
23523 (beginning-of-line))
23524 (cond
23525 ;; No special behavior. Point is already at the beginning of
23526 ;; a line, logical or visual.
23527 ((not special))
23528 ;; `beginning-of-visual-line' left point before logical beginning
23529 ;; of line: point is at the beginning of a visual line. Bail
23530 ;; out.
23531 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23532 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23533 ;; At a headline, special position is before the title, but
23534 ;; after any TODO keyword or priority cookie.
23535 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23536 (line-end-position)))
23537 (bol (point)))
23538 (if (eq special 'reversed)
23539 (when (and (= origin bol) (eq last-command this-command))
23540 (goto-char refpos))
23541 (when (or (> origin refpos) (= origin bol))
23542 (goto-char refpos)))))
23543 ((and (looking-at org-list-full-item-re)
23544 (memq (org-element-type (save-match-data (org-element-at-point)))
23545 '(item plain-list)))
23546 ;; Set special position at first white space character after
23547 ;; bullet, and check-box, if any.
23548 (let ((after-bullet
23549 (let ((box (match-end 3)))
23550 (cond ((not box) (match-end 1))
23551 ((eq (char-after box) ?\s) (1+ box))
23552 (t box)))))
23553 (if (eq special 'reversed)
23554 (when (and (= (point) origin) (eq last-command this-command))
23555 (goto-char after-bullet))
23556 (when (or (> origin after-bullet) (= (point) origin))
23557 (goto-char after-bullet)))))
23558 ;; No special context. Point is already at beginning of line.
23559 (t nil))))
23561 (defun org-end-of-line (&optional n)
23562 "Go to the end of the line, but before ellipsis, if any.
23564 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23565 tags on the first attempt, and only move to after the tags when
23566 the cursor is already beyond the end of the headline.
23568 With argument N not nil or 1, move forward N - 1 lines first."
23569 (interactive "^p")
23570 (let ((origin (point))
23571 (special (pcase org-special-ctrl-a/e
23572 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23573 deactivate-mark)
23574 ;; First move to a visible line.
23575 (if (bound-and-true-p visual-line-mode)
23576 (beginning-of-visual-line n)
23577 (move-beginning-of-line n))
23578 (cond
23579 ;; At a headline, with tags.
23580 ((and special
23581 (save-excursion
23582 (beginning-of-line)
23583 (let ((case-fold-search nil))
23584 (looking-at org-complex-heading-regexp)))
23585 (match-end 5))
23586 (let ((tags (save-excursion
23587 (goto-char (match-beginning 5))
23588 (skip-chars-backward " \t")
23589 (point)))
23590 (visual-end (and (bound-and-true-p visual-line-mode)
23591 (save-excursion
23592 (end-of-visual-line)
23593 (point)))))
23594 ;; If `end-of-visual-line' brings us before end of line or
23595 ;; even tags, i.e., the headline spans over multiple visual
23596 ;; lines, move there.
23597 (cond ((and visual-end
23598 (< visual-end tags)
23599 (<= origin visual-end))
23600 (goto-char visual-end))
23601 ((eq special 'reversed)
23602 (if (and (= origin (line-end-position))
23603 (eq this-command last-command))
23604 (goto-char tags)
23605 (end-of-line)))
23607 (if (or (< origin tags) (= origin (line-end-position)))
23608 (goto-char tags)
23609 (end-of-line))))))
23610 ((bound-and-true-p visual-line-mode)
23611 (let ((bol (line-beginning-position)))
23612 (end-of-visual-line)
23613 ;; If `end-of-visual-line' gets us past the ellipsis at the
23614 ;; end of a line, backtrack and use `end-of-line' instead.
23615 (when (/= bol (line-beginning-position))
23616 (goto-char bol)
23617 (end-of-line))))
23618 (t (end-of-line)))))
23620 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23621 (define-key org-mode-map "\C-e" 'org-end-of-line)
23623 (defun org-backward-sentence (&optional _arg)
23624 "Go to beginning of sentence, or beginning of table field.
23625 This will call `backward-sentence' or `org-table-beginning-of-field',
23626 depending on context."
23627 (interactive)
23628 (let* ((element (org-element-at-point))
23629 (contents-begin (org-element-property :contents-begin element))
23630 (table (org-element-lineage element '(table) t)))
23631 (if (and table
23632 (> (point) contents-begin)
23633 (<= (point) (org-element-property :contents-end table)))
23634 (call-interactively #'org-table-beginning-of-field)
23635 (save-restriction
23636 (when (and contents-begin
23637 (< (point-min) contents-begin)
23638 (> (point) contents-begin))
23639 (narrow-to-region contents-begin
23640 (org-element-property :contents-end element)))
23641 (call-interactively #'backward-sentence)))))
23643 (defun org-forward-sentence (&optional _arg)
23644 "Go to end of sentence, or end of table field.
23645 This will call `forward-sentence' or `org-table-end-of-field',
23646 depending on context."
23647 (interactive)
23648 (let* ((element (org-element-at-point))
23649 (contents-end (org-element-property :contents-end element))
23650 (table (org-element-lineage element '(table) t)))
23651 (if (and table
23652 (>= (point) (org-element-property :contents-begin table))
23653 (< (point) contents-end))
23654 (call-interactively #'org-table-end-of-field)
23655 (save-restriction
23656 (when (and contents-end
23657 (> (point-max) contents-end)
23658 ;; Skip blank lines between elements.
23659 (< (org-element-property :end element)
23660 (save-excursion (goto-char contents-end)
23661 (skip-chars-forward " \r\t\n"))))
23662 (narrow-to-region (org-element-property :contents-begin element)
23663 contents-end))
23664 (call-interactively #'forward-sentence)))))
23666 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23667 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23669 (defun org-kill-line (&optional _arg)
23670 "Kill line, to tags or end of line."
23671 (interactive)
23672 (cond
23673 ((or (not org-special-ctrl-k)
23674 (bolp)
23675 (not (org-at-heading-p)))
23676 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23677 org-ctrl-k-protect-subtree
23678 (or (eq org-ctrl-k-protect-subtree 'error)
23679 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23680 (user-error "C-k aborted as it would kill a hidden subtree"))
23681 (call-interactively
23682 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23683 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23684 (kill-region (point) (match-beginning 1))
23685 (org-set-tags nil t))
23686 (t (kill-region (point) (point-at-eol)))))
23688 (define-key org-mode-map "\C-k" 'org-kill-line)
23690 (defun org-yank (&optional arg)
23691 "Yank. If the kill is a subtree, treat it specially.
23692 This command will look at the current kill and check if is a single
23693 subtree, or a series of subtrees[1]. If it passes the test, and if the
23694 cursor is at the beginning of a line or after the stars of a currently
23695 empty headline, then the yank is handled specially. How exactly depends
23696 on the value of the following variables.
23698 `org-yank-folded-subtrees'
23699 By default, this variable is non-nil, which results in
23700 subtree(s) being folded after insertion, except if doing so
23701 would swallow text after the yanked text.
23703 `org-yank-adjusted-subtrees'
23704 When non-nil (the default value is nil), the subtree will be
23705 promoted or demoted in order to fit into the local outline tree
23706 structure, which means that the level will be adjusted so that it
23707 becomes the smaller one of the two *visible* surrounding headings.
23709 Any prefix to this command will cause `yank' to be called directly with
23710 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23711 will just
23712 plainly yank the text as it is.
23714 \[1] The test checks if the first non-white line is a heading
23715 and if there are no other headings with fewer stars."
23716 (interactive "P")
23717 (org-yank-generic 'yank arg))
23719 (defun org-yank-generic (command arg)
23720 "Perform some yank-like command.
23722 This function implements the behavior described in the `org-yank'
23723 documentation. However, it has been generalized to work for any
23724 interactive command with similar behavior."
23726 ;; pretend to be command COMMAND
23727 (setq this-command command)
23729 (if arg
23730 (call-interactively command)
23732 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23733 (and (org-kill-is-subtree-p)
23734 (or (bolp)
23735 (and (looking-at "[ \t]*$")
23736 (string-match
23737 "\\`\\*+\\'"
23738 (buffer-substring (point-at-bol) (point)))))))
23739 swallowp)
23740 (cond
23741 ((and subtreep org-yank-folded-subtrees)
23742 (let ((beg (point))
23743 end)
23744 (if (and subtreep org-yank-adjusted-subtrees)
23745 (org-paste-subtree nil nil 'for-yank)
23746 (call-interactively command))
23748 (setq end (point))
23749 (goto-char beg)
23750 (when (and (bolp) subtreep
23751 (not (setq swallowp
23752 (org-yank-folding-would-swallow-text beg end))))
23753 (org-with-limited-levels
23754 (or (looking-at org-outline-regexp)
23755 (re-search-forward org-outline-regexp-bol end t))
23756 (while (and (< (point) end) (looking-at org-outline-regexp))
23757 (outline-hide-subtree)
23758 (org-cycle-show-empty-lines 'folded)
23759 (condition-case nil
23760 (outline-forward-same-level 1)
23761 (error (goto-char end))))))
23762 (when swallowp
23763 (message
23764 "Inserted text not folded because that would swallow text"))
23766 (goto-char end)
23767 (skip-chars-forward " \t\n\r")
23768 (beginning-of-line 1)
23769 (push-mark beg 'nomsg)))
23770 ((and subtreep org-yank-adjusted-subtrees)
23771 (let ((beg (point-at-bol)))
23772 (org-paste-subtree nil nil 'for-yank)
23773 (push-mark beg 'nomsg)))
23775 (call-interactively command))))))
23777 (defun org-yank-folding-would-swallow-text (beg end)
23778 "Would hide-subtree at BEG swallow any text after END?"
23779 (let (level)
23780 (org-with-limited-levels
23781 (save-excursion
23782 (goto-char beg)
23783 (when (or (looking-at org-outline-regexp)
23784 (re-search-forward org-outline-regexp-bol end t))
23785 (setq level (org-outline-level)))
23786 (goto-char end)
23787 (skip-chars-forward " \t\r\n\v\f")
23788 (not (or (eobp)
23789 (and (bolp) (looking-at-p org-outline-regexp)
23790 (<= (org-outline-level) level))))))))
23792 (define-key org-mode-map "\C-y" 'org-yank)
23794 (defun org-truely-invisible-p ()
23795 "Check if point is at a character currently not visible.
23796 This version does not only check the character property, but also
23797 `visible-mode'."
23798 ;; Early versions of noutline don't have `outline-invisible-p'.
23799 (unless (bound-and-true-p visible-mode)
23800 (outline-invisible-p)))
23802 (defun org-invisible-p2 ()
23803 "Check if point is at a character currently not visible."
23804 (save-excursion
23805 (when (and (eolp) (not (bobp))) (backward-char 1))
23806 ;; Early versions of noutline don't have `outline-invisible-p'.
23807 (outline-invisible-p)))
23809 (defun org-back-to-heading (&optional invisible-ok)
23810 "Call `outline-back-to-heading', but provide a better error message."
23811 (condition-case nil
23812 (outline-back-to-heading invisible-ok)
23813 (error (error "Before first headline at position %d in buffer %s"
23814 (point) (current-buffer)))))
23816 (defun org-before-first-heading-p ()
23817 "Before first heading?"
23818 (save-excursion
23819 (end-of-line)
23820 (null (re-search-backward org-outline-regexp-bol nil t))))
23822 (defun org-at-heading-p (&optional ignored)
23823 (outline-on-heading-p t))
23825 (defun org-in-commented-heading-p (&optional no-inheritance)
23826 "Non-nil if point is under a commented heading.
23827 This function also checks ancestors of the current headline,
23828 unless optional argument NO-INHERITANCE is non-nil."
23829 (cond
23830 ((org-before-first-heading-p) nil)
23831 ((let ((headline (nth 4 (org-heading-components))))
23832 (and headline
23833 (let ((case-fold-search nil))
23834 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23835 headline)))))
23836 (no-inheritance nil)
23838 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23840 (defun org-at-comment-p nil
23841 "Is cursor in a commented line?"
23842 (save-excursion
23843 (save-match-data
23844 (beginning-of-line)
23845 (looking-at "^[ \t]*# "))))
23847 (defun org-at-drawer-p nil
23848 "Is cursor at a drawer keyword?"
23849 (save-excursion
23850 (move-beginning-of-line 1)
23851 (looking-at org-drawer-regexp)))
23853 (defun org-at-block-p nil
23854 "Is cursor at a block keyword?"
23855 (save-excursion
23856 (move-beginning-of-line 1)
23857 (looking-at org-block-regexp)))
23859 (defun org-point-at-end-of-empty-headline ()
23860 "If point is at the end of an empty headline, return t, else nil.
23861 If the heading only contains a TODO keyword, it is still still considered
23862 empty."
23863 (let ((case-fold-search nil))
23864 (and (looking-at "[ \t]*$")
23865 org-todo-line-regexp
23866 (save-excursion
23867 (beginning-of-line)
23868 (looking-at org-todo-line-regexp)
23869 (string= (match-string 3) "")))))
23871 (defun org-at-heading-or-item-p ()
23872 (or (org-at-heading-p) (org-at-item-p)))
23874 (defun org-at-target-p ()
23875 (or (org-in-regexp org-radio-target-regexp)
23876 (org-in-regexp org-target-regexp)))
23877 ;; Compatibility alias with Org versions < 7.8.03
23878 (defalias 'org-on-target-p 'org-at-target-p)
23880 (defun org-up-heading-all (arg)
23881 "Move to the heading line of which the present line is a subheading.
23882 This function considers both visible and invisible heading lines.
23883 With argument, move up ARG levels."
23884 (outline-up-heading arg t))
23886 (defun org-up-heading-safe ()
23887 "Move to the heading line of which the present line is a subheading.
23888 This version will not throw an error. It will return the level of the
23889 headline found, or nil if no higher level is found.
23891 Also, this function will be a lot faster than `outline-up-heading',
23892 because it relies on stars being the outline starters. This can really
23893 make a significant difference in outlines with very many siblings."
23894 (when (ignore-errors (org-back-to-heading t))
23895 (let ((level-up (1- (funcall outline-level))))
23896 (and (> level-up 0)
23897 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23898 (funcall outline-level)))))
23900 (defun org-first-sibling-p ()
23901 "Is this heading the first child of its parents?"
23902 (interactive)
23903 (let ((re org-outline-regexp-bol)
23904 level l)
23905 (unless (org-at-heading-p t)
23906 (user-error "Not at a heading"))
23907 (setq level (funcall outline-level))
23908 (save-excursion
23909 (if (not (re-search-backward re nil t))
23911 (setq l (funcall outline-level))
23912 (< l level)))))
23914 (defun org-goto-sibling (&optional previous)
23915 "Goto the next sibling, even if it is invisible.
23916 When PREVIOUS is set, go to the previous sibling instead. Returns t
23917 when a sibling was found. When none is found, return nil and don't
23918 move point."
23919 (let ((fun (if previous 're-search-backward 're-search-forward))
23920 (pos (point))
23921 (re org-outline-regexp-bol)
23922 level l)
23923 (when (ignore-errors (org-back-to-heading t))
23924 (setq level (funcall outline-level))
23925 (catch 'exit
23926 (or previous (forward-char 1))
23927 (while (funcall fun re nil t)
23928 (setq l (funcall outline-level))
23929 (when (< l level) (goto-char pos) (throw 'exit nil))
23930 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23931 (goto-char pos)
23932 nil))))
23934 (defun org-show-siblings ()
23935 "Show all siblings of the current headline."
23936 (save-excursion
23937 (while (org-goto-sibling) (org-flag-heading nil)))
23938 (save-excursion
23939 (while (org-goto-sibling 'previous)
23940 (org-flag-heading nil))))
23942 (defun org-goto-first-child ()
23943 "Goto the first child, even if it is invisible.
23944 Return t when a child was found. Otherwise don't move point and
23945 return nil."
23946 (let (level (pos (point)) (re org-outline-regexp-bol))
23947 (when (ignore-errors (org-back-to-heading t))
23948 (setq level (outline-level))
23949 (forward-char 1)
23950 (if (and (re-search-forward re nil t) (> (outline-level) level))
23951 (progn (goto-char (match-beginning 0)) t)
23952 (goto-char pos) nil))))
23954 (defun org-show-hidden-entry ()
23955 "Show an entry where even the heading is hidden."
23956 (save-excursion
23957 (org-show-entry)))
23959 (defun org-flag-heading (flag &optional entry)
23960 "Flag the current heading. FLAG non-nil means make invisible.
23961 When ENTRY is non-nil, show the entire entry."
23962 (save-excursion
23963 (org-back-to-heading t)
23964 ;; Check if we should show the entire entry
23965 (if entry
23966 (progn
23967 (org-show-entry)
23968 (save-excursion
23969 (and (outline-next-heading)
23970 (org-flag-heading nil))))
23971 (outline-flag-region (max (point-min) (1- (point)))
23972 (save-excursion (outline-end-of-heading) (point))
23973 flag))))
23975 (defun org-get-next-sibling ()
23976 "Move to next heading of the same level, and return point.
23977 If there is no such heading, return nil.
23978 This is like outline-next-sibling, but invisible headings are ok."
23979 (let ((level (funcall outline-level)))
23980 (outline-next-heading)
23981 (while (and (not (eobp)) (> (funcall outline-level) level))
23982 (outline-next-heading))
23983 (unless (or (eobp) (< (funcall outline-level) level))
23984 (point))))
23986 (defun org-get-last-sibling ()
23987 "Move to previous heading of the same level, and return point.
23988 If there is no such heading, return nil."
23989 (let ((opoint (point))
23990 (level (funcall outline-level)))
23991 (outline-previous-heading)
23992 (when (and (/= (point) opoint) (outline-on-heading-p t))
23993 (while (and (> (funcall outline-level) level)
23994 (not (bobp)))
23995 (outline-previous-heading))
23996 (unless (< (funcall outline-level) level)
23997 (point)))))
23999 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24000 "Goto to the end of a subtree."
24001 ;; This contains an exact copy of the original function, but it uses
24002 ;; `org-back-to-heading', to make it work also in invisible
24003 ;; trees. And is uses an invisible-ok argument.
24004 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24005 ;; Furthermore, when used inside Org, finding the end of a large subtree
24006 ;; with many children and grandchildren etc, this can be much faster
24007 ;; than the outline version.
24008 (org-back-to-heading invisible-ok)
24009 (let ((first t)
24010 (level (funcall outline-level)))
24011 (if (and (derived-mode-p 'org-mode) (< level 1000))
24012 ;; A true heading (not a plain list item), in Org
24013 ;; This means we can easily find the end by looking
24014 ;; only for the right number of stars. Using a regexp to do
24015 ;; this is so much faster than using a Lisp loop.
24016 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24017 (forward-char 1)
24018 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24019 ;; something else, do it the slow way
24020 (while (and (not (eobp))
24021 (or first (> (funcall outline-level) level)))
24022 (setq first nil)
24023 (outline-next-heading)))
24024 (unless to-heading
24025 (when (memq (preceding-char) '(?\n ?\^M))
24026 ;; Go to end of line before heading
24027 (forward-char -1)
24028 (when (memq (preceding-char) '(?\n ?\^M))
24029 ;; leave blank line before heading
24030 (forward-char -1)))))
24031 (point))
24033 (defun org-end-of-meta-data (&optional full)
24034 "Skip planning line and properties drawer in current entry.
24035 When optional argument FULL is non-nil, also skip empty lines,
24036 clocking lines and regular drawers at the beginning of the
24037 entry."
24038 (org-back-to-heading t)
24039 (forward-line)
24040 (when (looking-at-p org-planning-line-re) (forward-line))
24041 (when (looking-at org-property-drawer-re)
24042 (goto-char (match-end 0))
24043 (forward-line))
24044 (when (and full (not (org-at-heading-p)))
24045 (catch 'exit
24046 (let ((end (save-excursion (outline-next-heading) (point)))
24047 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24048 (while (not (eobp))
24049 (cond ((looking-at-p org-drawer-regexp)
24050 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24051 (forward-line)
24052 (throw 'exit t)))
24053 ((looking-at-p re) (forward-line))
24054 (t (throw 'exit t))))))))
24056 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24057 "Move forward to the ARG'th subheading at same level as this one.
24058 Stop at the first and last subheadings of a superior heading.
24059 Normally this only looks at visible headings, but when INVISIBLE-OK is
24060 non-nil it will also look at invisible ones."
24061 (interactive "p")
24062 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24063 (if (and arg (< arg 0))
24064 (goto-char (point-min))
24065 (outline-next-heading))
24066 (org-at-heading-p)
24067 (let ((level (- (match-end 0) (match-beginning 0) 1))
24068 (f (if (and arg (< arg 0))
24069 're-search-backward
24070 're-search-forward))
24071 (count (if arg (abs arg) 1))
24072 (result (point)))
24073 (while (and (prog1 (> count 0)
24074 (forward-char (if (and arg (< arg 0)) -1 1)))
24075 (funcall f org-outline-regexp-bol nil 'move))
24076 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24077 (cond ((< l level) (setq count 0))
24078 ((and (= l level)
24079 (or invisible-ok
24080 (progn
24081 (goto-char (line-beginning-position))
24082 (not (outline-invisible-p)))))
24083 (setq count (1- count))
24084 (when (eq l level)
24085 (setq result (point)))))))
24086 (goto-char result))
24087 (beginning-of-line 1)))
24089 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24090 "Move backward to the ARG'th subheading at same level as this one.
24091 Stop at the first and last subheadings of a superior heading."
24092 (interactive "p")
24093 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24095 (defun org-next-visible-heading (arg)
24096 "Move to the next visible heading.
24098 This function wraps `outline-next-visible-heading' with
24099 `org-with-limited-levels' in order to skip over inline tasks and
24100 respect customization of `org-odd-levels-only'."
24101 (interactive "p")
24102 (org-with-limited-levels
24103 (outline-next-visible-heading arg)))
24105 (defun org-previous-visible-heading (arg)
24106 "Move to the previous visible heading.
24108 This function wraps `outline-previous-visible-heading' with
24109 `org-with-limited-levels' in order to skip over inline tasks and
24110 respect customization of `org-odd-levels-only'."
24111 (interactive "p")
24112 (org-with-limited-levels
24113 (outline-previous-visible-heading arg)))
24115 (defun org-next-block (arg &optional backward block-regexp)
24116 "Jump to the next block.
24118 With a prefix argument ARG, jump forward ARG many blocks.
24120 When BACKWARD is non-nil, jump to the previous block.
24122 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24123 Match data is set according to this regexp when the function
24124 returns.
24126 Return point at beginning of the opening line of found block.
24127 Throw an error if no block is found."
24128 (interactive "p")
24129 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24130 (case-fold-search t)
24131 (search-fn (if backward #'re-search-backward #'re-search-forward))
24132 (count (or arg 1))
24133 (origin (point))
24134 last-element)
24135 (if backward (beginning-of-line) (end-of-line))
24136 (while (and (> count 0) (funcall search-fn re nil t))
24137 (let ((element (save-excursion
24138 (goto-char (match-beginning 0))
24139 (save-match-data (org-element-at-point)))))
24140 (when (and (memq (org-element-type element)
24141 '(center-block comment-block dynamic-block
24142 example-block export-block quote-block
24143 special-block src-block verse-block))
24144 (<= (match-beginning 0)
24145 (org-element-property :post-affiliated element)))
24146 (setq last-element element)
24147 (cl-decf count))))
24148 (if (= count 0)
24149 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24150 (save-match-data (org-show-context)))
24151 (goto-char origin)
24152 (user-error "No %s code blocks" (if backward "previous" "further")))))
24154 (defun org-previous-block (arg &optional block-regexp)
24155 "Jump to the previous block.
24156 With a prefix argument ARG, jump backward ARG many source blocks.
24157 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24158 (interactive "p")
24159 (org-next-block arg t block-regexp))
24161 (defun org-forward-paragraph ()
24162 "Move forward to beginning of next paragraph or equivalent.
24164 The function moves point to the beginning of the next visible
24165 structural element, which can be a paragraph, a table, a list
24166 item, etc. It also provides some special moves for convenience:
24168 - On an affiliated keyword, jump to the beginning of the
24169 relative element.
24170 - On an item or a footnote definition, move to the second
24171 element inside, if any.
24172 - On a table or a property drawer, jump after it.
24173 - On a verse or source block, stop after blank lines."
24174 (interactive)
24175 (when (eobp) (user-error "Cannot move further down"))
24176 (let* ((deactivate-mark nil)
24177 (element (org-element-at-point))
24178 (type (org-element-type element))
24179 (post-affiliated (org-element-property :post-affiliated element))
24180 (contents-begin (org-element-property :contents-begin element))
24181 (contents-end (org-element-property :contents-end element))
24182 (end (let ((end (org-element-property :end element)) (parent element))
24183 (while (and (setq parent (org-element-property :parent parent))
24184 (= (org-element-property :contents-end parent) end))
24185 (setq end (org-element-property :end parent)))
24186 end)))
24187 (cond ((not element)
24188 (skip-chars-forward " \r\t\n")
24189 (or (eobp) (beginning-of-line)))
24190 ;; On affiliated keywords, move to element's beginning.
24191 ((< (point) post-affiliated)
24192 (goto-char post-affiliated))
24193 ;; At a table row, move to the end of the table. Similarly,
24194 ;; at a node property, move to the end of the property
24195 ;; drawer.
24196 ((memq type '(node-property table-row))
24197 (goto-char (org-element-property
24198 :end (org-element-property :parent element))))
24199 ((memq type '(property-drawer table)) (goto-char end))
24200 ;; Consider blank lines as separators in verse and source
24201 ;; blocks to ease editing.
24202 ((memq type '(src-block verse-block))
24203 (when (eq type 'src-block)
24204 (setq contents-end
24205 (save-excursion (goto-char end)
24206 (skip-chars-backward " \r\t\n")
24207 (line-beginning-position))))
24208 (beginning-of-line)
24209 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24210 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24211 (goto-char end)
24212 (skip-chars-forward " \r\t\n")
24213 (if (= (point) contents-end) (goto-char end)
24214 (beginning-of-line))))
24215 ;; With no contents, just skip element.
24216 ((not contents-begin) (goto-char end))
24217 ;; If contents are invisible, skip the element altogether.
24218 ((outline-invisible-p (line-end-position))
24219 (cl-case type
24220 (headline
24221 (org-with-limited-levels (outline-next-visible-heading 1)))
24222 ;; At a plain list, make sure we move to the next item
24223 ;; instead of skipping the whole list.
24224 (plain-list (forward-char)
24225 (org-forward-paragraph))
24226 (otherwise (goto-char end))))
24227 ((>= (point) contents-end) (goto-char end))
24228 ((>= (point) contents-begin)
24229 ;; This can only happen on paragraphs and plain lists.
24230 (cl-case type
24231 (paragraph (goto-char end))
24232 ;; At a plain list, try to move to second element in
24233 ;; first item, if possible.
24234 (plain-list (end-of-line)
24235 (org-forward-paragraph))))
24236 ;; When contents start on the middle of a line (e.g. in
24237 ;; items and footnote definitions), try to reach first
24238 ;; element starting after current line.
24239 ((> (line-end-position) contents-begin)
24240 (end-of-line)
24241 (org-forward-paragraph))
24242 (t (goto-char contents-begin)))))
24244 (defun org-backward-paragraph ()
24245 "Move backward to start of previous paragraph or equivalent.
24247 The function moves point to the beginning of the current
24248 structural element, which can be a paragraph, a table, a list
24249 item, etc., or to the beginning of the previous visible one if
24250 point is already there. It also provides some special moves for
24251 convenience:
24253 - On an affiliated keyword, jump to the first one.
24254 - On a table or a property drawer, move to its beginning.
24255 - On a verse or source block, stop before blank lines."
24256 (interactive)
24257 (when (bobp) (user-error "Cannot move further up"))
24258 (let* ((deactivate-mark nil)
24259 (element (org-element-at-point))
24260 (type (org-element-type element))
24261 (contents-begin (org-element-property :contents-begin element))
24262 (contents-end (org-element-property :contents-end element))
24263 (post-affiliated (org-element-property :post-affiliated element))
24264 (begin (org-element-property :begin element)))
24265 (cond
24266 ((not element) (goto-char (point-min)))
24267 ((= (point) begin)
24268 (backward-char)
24269 (org-backward-paragraph))
24270 ((<= (point) post-affiliated) (goto-char begin))
24271 ((memq type '(node-property table-row))
24272 (goto-char (org-element-property
24273 :post-affiliated (org-element-property :parent element))))
24274 ((memq type '(property-drawer table)) (goto-char begin))
24275 ((memq type '(src-block verse-block))
24276 (when (eq type 'src-block)
24277 (setq contents-begin
24278 (save-excursion (goto-char begin) (forward-line) (point))))
24279 (if (= (point) contents-begin) (goto-char post-affiliated)
24280 ;; Inside a verse block, see blank lines as paragraph
24281 ;; separators.
24282 (let ((origin (point)))
24283 (skip-chars-backward " \r\t\n" contents-begin)
24284 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24285 (skip-chars-forward " \r\t\n" origin)
24286 (if (= (point) origin) (goto-char contents-begin)
24287 (beginning-of-line))))))
24288 ((not contents-begin) (goto-char (or post-affiliated begin)))
24289 ((eq type 'paragraph)
24290 (goto-char contents-begin)
24291 ;; When at first paragraph in an item or a footnote definition,
24292 ;; move directly to beginning of line.
24293 (let ((parent-contents
24294 (org-element-property
24295 :contents-begin (org-element-property :parent element))))
24296 (when (and parent-contents (= parent-contents contents-begin))
24297 (beginning-of-line))))
24298 ;; At the end of a greater element, move to the beginning of the
24299 ;; last element within.
24300 ((>= (point) contents-end)
24301 (goto-char (1- contents-end))
24302 (org-backward-paragraph))
24303 (t (goto-char (or post-affiliated begin))))
24304 ;; Ensure we never leave point invisible.
24305 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24307 (defun org-forward-element ()
24308 "Move forward by one element.
24309 Move to the next element at the same level, when possible."
24310 (interactive)
24311 (cond ((eobp) (user-error "Cannot move further down"))
24312 ((org-with-limited-levels (org-at-heading-p))
24313 (let ((origin (point)))
24314 (goto-char (org-end-of-subtree nil t))
24315 (unless (org-with-limited-levels (org-at-heading-p))
24316 (goto-char origin)
24317 (user-error "Cannot move further down"))))
24319 (let* ((elem (org-element-at-point))
24320 (end (org-element-property :end elem))
24321 (parent (org-element-property :parent elem)))
24322 (cond ((and parent (= (org-element-property :contents-end parent) end))
24323 (goto-char (org-element-property :end parent)))
24324 ((integer-or-marker-p end) (goto-char end))
24325 (t (message "No element at point")))))))
24327 (defun org-backward-element ()
24328 "Move backward by one element.
24329 Move to the previous element at the same level, when possible."
24330 (interactive)
24331 (cond ((bobp) (user-error "Cannot move further up"))
24332 ((org-with-limited-levels (org-at-heading-p))
24333 ;; At a headline, move to the previous one, if any, or stay
24334 ;; here.
24335 (let ((origin (point)))
24336 (org-with-limited-levels (org-backward-heading-same-level 1))
24337 ;; When current headline has no sibling above, move to its
24338 ;; parent.
24339 (when (= (point) origin)
24340 (or (org-with-limited-levels (org-up-heading-safe))
24341 (progn (goto-char origin)
24342 (user-error "Cannot move further up"))))))
24344 (let* ((elem (org-element-at-point))
24345 (beg (org-element-property :begin elem)))
24346 (cond
24347 ;; Move to beginning of current element if point isn't
24348 ;; there already.
24349 ((null beg) (message "No element at point"))
24350 ((/= (point) beg) (goto-char beg))
24351 (t (goto-char beg)
24352 (skip-chars-backward " \r\t\n")
24353 (unless (bobp)
24354 (let ((prev (org-element-at-point)))
24355 (goto-char (org-element-property :begin prev))
24356 (while (and (setq prev (org-element-property :parent prev))
24357 (<= (org-element-property :end prev) beg))
24358 (goto-char (org-element-property :begin prev)))))))))))
24360 (defun org-up-element ()
24361 "Move to upper element."
24362 (interactive)
24363 (if (org-with-limited-levels (org-at-heading-p))
24364 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24365 (let* ((elem (org-element-at-point))
24366 (parent (org-element-property :parent elem)))
24367 (if parent (goto-char (org-element-property :begin parent))
24368 (if (org-with-limited-levels (org-before-first-heading-p))
24369 (user-error "No surrounding element")
24370 (org-with-limited-levels (org-back-to-heading)))))))
24372 (defvar org-element-greater-elements)
24373 (defun org-down-element ()
24374 "Move to inner element."
24375 (interactive)
24376 (let ((element (org-element-at-point)))
24377 (cond
24378 ((memq (org-element-type element) '(plain-list table))
24379 (goto-char (org-element-property :contents-begin element))
24380 (forward-char))
24381 ((memq (org-element-type element) org-element-greater-elements)
24382 ;; If contents are hidden, first disclose them.
24383 (when (outline-invisible-p (line-end-position)) (org-cycle))
24384 (goto-char (or (org-element-property :contents-begin element)
24385 (user-error "No content for this element"))))
24386 (t (user-error "No inner element")))))
24388 (defun org-drag-element-backward ()
24389 "Move backward element at point."
24390 (interactive)
24391 (let ((elem (or (org-element-at-point)
24392 (user-error "No element at point"))))
24393 (if (eq (org-element-type elem) 'headline)
24394 ;; Preserve point when moving a whole tree, even if point was
24395 ;; on blank lines below the headline.
24396 (let ((offset (skip-chars-backward " \t\n")))
24397 (unwind-protect (org-move-subtree-up)
24398 (forward-char (- offset))))
24399 (let ((prev-elem
24400 (save-excursion
24401 (goto-char (org-element-property :begin elem))
24402 (skip-chars-backward " \r\t\n")
24403 (unless (bobp)
24404 (let* ((beg (org-element-property :begin elem))
24405 (prev (org-element-at-point))
24406 (up prev))
24407 (while (and (setq up (org-element-property :parent up))
24408 (<= (org-element-property :end up) beg))
24409 (setq prev up))
24410 prev)))))
24411 ;; Error out if no previous element or previous element is
24412 ;; a parent of the current one.
24413 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24414 (user-error "Cannot drag element backward")
24415 (let ((pos (point)))
24416 (org-element-swap-A-B prev-elem elem)
24417 (goto-char (+ (org-element-property :begin prev-elem)
24418 (- pos (org-element-property :begin elem))))))))))
24420 (defun org-drag-element-forward ()
24421 "Move forward element at point."
24422 (interactive)
24423 (let* ((pos (point))
24424 (elem (or (org-element-at-point)
24425 (user-error "No element at point"))))
24426 (when (= (point-max) (org-element-property :end elem))
24427 (user-error "Cannot drag element forward"))
24428 (goto-char (org-element-property :end elem))
24429 (let ((next-elem (org-element-at-point)))
24430 (when (or (org-element-nested-p elem next-elem)
24431 (and (eq (org-element-type next-elem) 'headline)
24432 (not (eq (org-element-type elem) 'headline))))
24433 (goto-char pos)
24434 (user-error "Cannot drag element forward"))
24435 ;; Compute new position of point: it's shifted by NEXT-ELEM
24436 ;; body's length (without final blanks) and by the length of
24437 ;; blanks between ELEM and NEXT-ELEM.
24438 (let ((size-next (- (save-excursion
24439 (goto-char (org-element-property :end next-elem))
24440 (skip-chars-backward " \r\t\n")
24441 (forward-line)
24442 ;; Small correction if buffer doesn't end
24443 ;; with a newline character.
24444 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24445 (org-element-property :begin next-elem)))
24446 (size-blank (- (org-element-property :end elem)
24447 (save-excursion
24448 (goto-char (org-element-property :end elem))
24449 (skip-chars-backward " \r\t\n")
24450 (forward-line)
24451 (point)))))
24452 (org-element-swap-A-B elem next-elem)
24453 (goto-char (+ pos size-next size-blank))))))
24455 (defun org-drag-line-forward (arg)
24456 "Drag the line at point ARG lines forward."
24457 (interactive "p")
24458 (dotimes (_ (abs arg))
24459 (let ((c (current-column)))
24460 (if (< 0 arg)
24461 (progn
24462 (beginning-of-line 2)
24463 (transpose-lines 1)
24464 (beginning-of-line 0))
24465 (transpose-lines 1)
24466 (beginning-of-line -1))
24467 (org-move-to-column c))))
24469 (defun org-drag-line-backward (arg)
24470 "Drag the line at point ARG lines backward."
24471 (interactive "p")
24472 (org-drag-line-forward (- arg)))
24474 (defun org-mark-element ()
24475 "Put point at beginning of this element, mark at end.
24477 Interactively, if this command is repeated or (in Transient Mark
24478 mode) if the mark is active, it marks the next element after the
24479 ones already marked."
24480 (interactive)
24481 (let (deactivate-mark)
24482 (if (and (called-interactively-p 'any)
24483 (or (and (eq last-command this-command) (mark t))
24484 (and transient-mark-mode mark-active)))
24485 (set-mark
24486 (save-excursion
24487 (goto-char (mark))
24488 (goto-char (org-element-property :end (org-element-at-point)))))
24489 (let ((element (org-element-at-point)))
24490 (end-of-line)
24491 (push-mark (org-element-property :end element) t t)
24492 (goto-char (org-element-property :begin element))))))
24494 (defun org-narrow-to-element ()
24495 "Narrow buffer to current element."
24496 (interactive)
24497 (let ((elem (org-element-at-point)))
24498 (cond
24499 ((eq (car elem) 'headline)
24500 (narrow-to-region
24501 (org-element-property :begin elem)
24502 (org-element-property :end elem)))
24503 ((memq (car elem) org-element-greater-elements)
24504 (narrow-to-region
24505 (org-element-property :contents-begin elem)
24506 (org-element-property :contents-end elem)))
24508 (narrow-to-region
24509 (org-element-property :begin elem)
24510 (org-element-property :end elem))))))
24512 (defun org-transpose-element ()
24513 "Transpose current and previous elements, keeping blank lines between.
24514 Point is moved after both elements."
24515 (interactive)
24516 (org-skip-whitespace)
24517 (let ((end (org-element-property :end (org-element-at-point))))
24518 (org-drag-element-backward)
24519 (goto-char end)))
24521 (defun org-unindent-buffer ()
24522 "Un-indent the visible part of the buffer.
24523 Relative indentation (between items, inside blocks, etc.) isn't
24524 modified."
24525 (interactive)
24526 (unless (eq major-mode 'org-mode)
24527 (user-error "Cannot un-indent a buffer not in Org mode"))
24528 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24529 (unindent-tree
24530 (lambda (contents)
24531 (dolist (element (reverse contents))
24532 (if (memq (org-element-type element) '(headline section))
24533 (funcall unindent-tree (org-element-contents element))
24534 (save-excursion
24535 (save-restriction
24536 (narrow-to-region
24537 (org-element-property :begin element)
24538 (org-element-property :end element))
24539 (org-do-remove-indentation))))))))
24540 (funcall unindent-tree (org-element-contents parse-tree))))
24542 (defun org-show-children (&optional level)
24543 "Show all direct subheadings of this heading.
24544 Prefix arg LEVEL is how many levels below the current level
24545 should be shown. Default is enough to cause the following
24546 heading to appear."
24547 (interactive "p")
24548 ;; If `orgstruct-mode' is active, use the slower version.
24549 (if orgstruct-mode (call-interactively #'outline-show-children)
24550 (save-excursion
24551 (org-back-to-heading t)
24552 (let* ((current-level (funcall outline-level))
24553 (max-level (org-get-valid-level
24554 current-level
24555 (if level (prefix-numeric-value level) 1)))
24556 (end (save-excursion (org-end-of-subtree t t)))
24557 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24558 (past-first-child nil)
24559 ;; Make sure to skip inlinetasks.
24560 (re (format regexp-fmt
24561 current-level
24562 (cond
24563 ((not (featurep 'org-inlinetask)) "")
24564 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24566 (t (1- org-inlinetask-min-level))))))
24567 ;; Display parent heading.
24568 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24569 (forward-line)
24570 ;; Display children. First child may be deeper than expected
24571 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24572 ;; MAX-LEVEL accordingly.
24573 (while (re-search-forward re end t)
24574 (unless past-first-child
24575 (setq re (format regexp-fmt
24576 current-level
24577 (max (funcall outline-level) max-level)))
24578 (setq past-first-child t))
24579 (outline-flag-region
24580 (line-end-position 0) (line-end-position) nil))))))
24582 (defun org-show-subtree ()
24583 "Show everything after this heading at deeper levels."
24584 (interactive)
24585 (outline-flag-region
24586 (point)
24587 (save-excursion
24588 (org-end-of-subtree t t))
24589 nil))
24591 (defun org-show-entry ()
24592 "Show the body directly following this heading.
24593 Show the heading too, if it is currently invisible."
24594 (interactive)
24595 (save-excursion
24596 (ignore-errors
24597 (org-back-to-heading t)
24598 (outline-flag-region
24599 (max (point-min) (1- (point)))
24600 (save-excursion
24601 (if (re-search-forward
24602 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24603 (match-beginning 1)
24604 (point-max)))
24605 nil)
24606 (org-cycle-hide-drawers 'children))))
24608 (defun org-make-options-regexp (kwds &optional extra)
24609 "Make a regular expression for keyword lines.
24610 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24611 when non-nil, is a regexp matching keywords names."
24612 (concat "^[ \t]*#\\+\\("
24613 (regexp-opt kwds)
24614 (and extra (concat (and kwds "\\|") extra))
24615 "\\):[ \t]*\\(.*\\)"))
24617 ;;;; Integration with and fixes for other packages
24619 ;;; Imenu support
24621 (defvar-local org-imenu-markers nil
24622 "All markers currently used by Imenu.")
24624 (defun org-imenu-new-marker (&optional pos)
24625 "Return a new marker for use by Imenu, and remember the marker."
24626 (let ((m (make-marker)))
24627 (move-marker m (or pos (point)))
24628 (push m org-imenu-markers)
24631 (defun org-imenu-get-tree ()
24632 "Produce the index for Imenu."
24633 (dolist (x org-imenu-markers) (move-marker x nil))
24634 (setq org-imenu-markers nil)
24635 (let* ((case-fold-search nil)
24636 (n org-imenu-depth)
24637 (re (concat "^" (org-get-limited-outline-regexp)))
24638 (subs (make-vector (1+ n) nil))
24639 (last-level 0)
24640 m level head0 head)
24641 (org-with-wide-buffer
24642 (goto-char (point-max))
24643 (while (re-search-backward re nil t)
24644 (setq level (org-reduced-level (funcall outline-level)))
24645 (when (and (<= level n)
24646 (looking-at org-complex-heading-regexp)
24647 (setq head0 (match-string-no-properties 4)))
24648 (setq head (org-link-display-format head0)
24649 m (org-imenu-new-marker))
24650 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24651 (if (>= level last-level)
24652 (push (cons head m) (aref subs level))
24653 (push (cons head (aref subs (1+ level))) (aref subs level))
24654 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24655 (setq last-level level))))
24656 (aref subs 1)))
24658 (eval-after-load "imenu"
24659 '(progn
24660 (add-hook 'imenu-after-jump-hook
24661 (lambda ()
24662 (when (derived-mode-p 'org-mode)
24663 (org-show-context 'org-goto))))))
24665 (defun org-link-display-format (s)
24666 "Replace links in string S with their description.
24667 If there is no description, use the link target."
24668 (save-match-data
24669 (replace-regexp-in-string
24670 org-bracket-link-analytic-regexp
24671 (lambda (m)
24672 (if (match-end 5) (match-string 5 m)
24673 (concat (match-string 1 m) (match-string 3 m))))
24674 s nil t)))
24676 (defun org-toggle-link-display ()
24677 "Toggle the literal or descriptive display of links."
24678 (interactive)
24679 (if org-descriptive-links
24680 (progn (org-remove-from-invisibility-spec '(org-link))
24681 (org-restart-font-lock)
24682 (setq org-descriptive-links nil))
24683 (progn (add-to-invisibility-spec '(org-link))
24684 (org-restart-font-lock)
24685 (setq org-descriptive-links t))))
24687 ;; Speedbar support
24689 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24690 "Overlay marking the agenda restriction line in speedbar.")
24691 (overlay-put org-speedbar-restriction-lock-overlay
24692 'face 'org-agenda-restriction-lock)
24693 (overlay-put org-speedbar-restriction-lock-overlay
24694 'help-echo "Agendas are currently limited to this item.")
24695 (delete-overlay org-speedbar-restriction-lock-overlay)
24697 (defun org-speedbar-set-agenda-restriction ()
24698 "Restrict future agenda commands to the location at point in speedbar.
24699 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24700 (interactive)
24701 (require 'org-agenda)
24702 (let (p m tp np dir txt)
24703 (cond
24704 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24705 'org-imenu t))
24706 (setq m (get-text-property p 'org-imenu-marker))
24707 (with-current-buffer (marker-buffer m)
24708 (goto-char m)
24709 (org-agenda-set-restriction-lock 'subtree)))
24710 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24711 'speedbar-function 'speedbar-find-file))
24712 (setq tp (previous-single-property-change
24713 (1+ p) 'speedbar-function)
24714 np (next-single-property-change
24715 tp 'speedbar-function)
24716 dir (speedbar-line-directory)
24717 txt (buffer-substring-no-properties (or tp (point-min))
24718 (or np (point-max))))
24719 (with-current-buffer (find-file-noselect
24720 (let ((default-directory dir))
24721 (expand-file-name txt)))
24722 (unless (derived-mode-p 'org-mode)
24723 (user-error "Cannot restrict to non-Org mode file"))
24724 (org-agenda-set-restriction-lock 'file)))
24725 (t (user-error "Don't know how to restrict Org mode agenda")))
24726 (move-overlay org-speedbar-restriction-lock-overlay
24727 (point-at-bol) (point-at-eol))
24728 (setq current-prefix-arg nil)
24729 (org-agenda-maybe-redo)))
24731 (defvar speedbar-file-key-map)
24732 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24733 (eval-after-load "speedbar"
24734 '(progn
24735 (speedbar-add-supported-extension ".org")
24736 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24737 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24738 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24739 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24740 (add-hook 'speedbar-visiting-tag-hook
24741 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24743 ;;; Fixes and Hacks for problems with other packages
24745 (defun org--flyspell-object-check-p (element)
24746 "Non-nil when Flyspell can check object at point.
24747 ELEMENT is the element at point."
24748 (let ((object (save-excursion
24749 (when (looking-at-p "\\>") (backward-char))
24750 (org-element-context element))))
24751 (cl-case (org-element-type object)
24752 ;; Prevent checks in links due to keybinding conflict with
24753 ;; Flyspell.
24754 ((code entity export-snippet inline-babel-call
24755 inline-src-block line-break latex-fragment link macro
24756 statistics-cookie target timestamp verbatim)
24757 nil)
24758 (footnote-reference
24759 ;; Only in inline footnotes, within the definition.
24760 (and (eq (org-element-property :type object) 'inline)
24761 (< (save-excursion
24762 (goto-char (org-element-property :begin object))
24763 (search-forward ":" nil t 2))
24764 (point))))
24765 (otherwise t))))
24767 (defun org-mode-flyspell-verify ()
24768 "Function used for `flyspell-generic-check-word-predicate'."
24769 (if (org-at-heading-p)
24770 ;; At a headline or an inlinetask, check title only. This is
24771 ;; faster than relying on `org-element-at-point'.
24772 (and (save-excursion (beginning-of-line)
24773 (and (let ((case-fold-search t))
24774 (not (looking-at-p "\\*+ END[ \t]*$")))
24775 (let ((case-fold-search nil))
24776 (looking-at org-complex-heading-regexp))))
24777 (match-beginning 4)
24778 (>= (point) (match-beginning 4))
24779 (or (not (match-beginning 5))
24780 (< (point) (match-beginning 5))))
24781 (let* ((element (org-element-at-point))
24782 (post-affiliated (org-element-property :post-affiliated element)))
24783 (cond
24784 ;; Ignore checks in all affiliated keywords but captions.
24785 ((< (point) post-affiliated)
24786 (and (save-excursion
24787 (beginning-of-line)
24788 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24789 (> (point) (match-end 0))
24790 (org--flyspell-object-check-p element)))
24791 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24792 ((let ((log (org-log-into-drawer)))
24793 (and log
24794 (let ((drawer (org-element-lineage element '(drawer))))
24795 (and drawer
24796 (eq (compare-strings
24797 log nil nil
24798 (org-element-property :drawer-name drawer) nil nil t)
24799 t)))))
24800 nil)
24802 (cl-case (org-element-type element)
24803 ((comment quote-section) t)
24804 (comment-block
24805 ;; Allow checks between block markers, not on them.
24806 (and (> (line-beginning-position) post-affiliated)
24807 (save-excursion
24808 (end-of-line)
24809 (skip-chars-forward " \r\t\n")
24810 (< (point) (org-element-property :end element)))))
24811 ;; Arbitrary list of keywords where checks are meaningful.
24812 ;; Make sure point is on the value part of the element.
24813 (keyword
24814 (and (member (org-element-property :key element)
24815 '("DESCRIPTION" "TITLE"))
24816 (save-excursion
24817 (search-backward ":" (line-beginning-position) t))))
24818 ;; Check is globally allowed in paragraphs verse blocks and
24819 ;; table rows (after affiliated keywords) but some objects
24820 ;; must not be affected.
24821 ((paragraph table-row verse-block)
24822 (let ((cbeg (org-element-property :contents-begin element))
24823 (cend (org-element-property :contents-end element)))
24824 (and cbeg (>= (point) cbeg) (< (point) cend)
24825 (org--flyspell-object-check-p element))))))))))
24826 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24828 (defun org-remove-flyspell-overlays-in (beg end)
24829 "Remove flyspell overlays in region."
24830 (and (bound-and-true-p flyspell-mode)
24831 (fboundp 'flyspell-delete-region-overlays)
24832 (flyspell-delete-region-overlays beg end)))
24834 (defvar flyspell-delayed-commands)
24835 (eval-after-load "flyspell"
24836 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24838 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24839 (eval-after-load "bookmark"
24840 '(if (boundp 'bookmark-after-jump-hook)
24841 ;; We can use the hook
24842 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24843 ;; Hook not available, use advice
24844 (defadvice bookmark-jump (after org-make-visible activate)
24845 "Make the position visible."
24846 (org-bookmark-jump-unhide))))
24848 ;; Make sure saveplace shows the location if it was hidden
24849 (eval-after-load "saveplace"
24850 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24851 "Make the position visible."
24852 (org-bookmark-jump-unhide)))
24854 ;; Make sure ecb shows the location if it was hidden
24855 (eval-after-load "ecb"
24856 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24857 "Make hierarchy visible when jumping into location from ECB tree buffer."
24858 (when (derived-mode-p 'org-mode)
24859 (org-show-context))))
24861 (defun org-bookmark-jump-unhide ()
24862 "Unhide the current position, to show the bookmark location."
24863 (and (derived-mode-p 'org-mode)
24864 (or (outline-invisible-p)
24865 (save-excursion (goto-char (max (point-min) (1- (point))))
24866 (outline-invisible-p)))
24867 (org-show-context 'bookmark-jump)))
24869 (defun org-mark-jump-unhide ()
24870 "Make the point visible with `org-show-context' after jumping to the mark."
24871 (when (and (derived-mode-p 'org-mode)
24872 (outline-invisible-p))
24873 (org-show-context 'mark-goto)))
24875 (eval-after-load "simple"
24876 '(defadvice pop-to-mark-command (after org-make-visible activate)
24877 "Make the point visible with `org-show-context'."
24878 (org-mark-jump-unhide)))
24880 (eval-after-load "simple"
24881 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24882 "Make the point visible with `org-show-context'."
24883 (org-mark-jump-unhide)))
24885 (eval-after-load "simple"
24886 '(defadvice pop-global-mark (after org-make-visible activate)
24887 "Make the point visible with `org-show-context'."
24888 (org-mark-jump-unhide)))
24890 ;; Make session.el ignore our circular variable
24891 (defvar session-globals-exclude)
24892 (eval-after-load "session"
24893 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24895 ;;;; Finish up
24897 (provide 'org)
24899 (run-hooks 'org-load-hook)
24901 ;;; org.el ends here