Fix last commit
[org-mode.git] / lisp / org.el
blob9ebba6d0220eb455933389defc25dd3ab2114890
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp)
188 (defvar org-element-paragraph-separate)
190 ;; load languages based on value of `org-babel-load-languages'
191 (defvar org-babel-load-languages)
193 ;;;###autoload
194 (defun org-babel-do-load-languages (sym value)
195 "Load the languages defined in `org-babel-load-languages'."
196 (set-default sym value)
197 (dolist (pair org-babel-load-languages)
198 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
199 (if active
200 (require (intern (concat "ob-" lang)))
201 (funcall 'fmakunbound
202 (intern (concat "org-babel-execute:" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-expand-body:" lang)))))))
206 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
207 ;;;###autoload
208 (defun org-babel-load-file (file &optional compile)
209 "Load Emacs Lisp source code blocks in the Org FILE.
210 This function exports the source code using `org-babel-tangle'
211 and then loads the resulting file using `load-file'. With prefix
212 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
213 file to byte-code before it is loaded."
214 (interactive "fFile to load: \nP")
215 (let* ((age (lambda (file)
216 (float-time
217 (time-subtract (current-time)
218 (nth 5 (or (file-attributes (file-truename file))
219 (file-attributes file)))))))
220 (base-name (file-name-sans-extension file))
221 (exported-file (concat base-name ".el")))
222 ;; tangle if the Org file is newer than the elisp file
223 (unless (and (file-exists-p exported-file)
224 (> (funcall age file) (funcall age exported-file)))
225 ;; Tangle-file traversal returns reversed list of tangled files
226 ;; and we want to evaluate the first target.
227 (setq exported-file
228 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
229 (message "%s %s"
230 (if compile
231 (progn (byte-compile-file exported-file 'load)
232 "Compiled and loaded")
233 (progn (load-file exported-file) "Loaded"))
234 exported-file)))
236 (defcustom org-babel-load-languages '((emacs-lisp . t))
237 "Languages which can be evaluated in Org buffers.
238 This list can be used to load support for any of the languages
239 below, note that each language will depend on a different set of
240 system executables and/or Emacs modes. When a language is
241 \"loaded\", then code blocks in that language can be evaluated
242 with `org-babel-execute-src-block' bound by default to C-c
243 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
244 be set to remove code block evaluation from the C-c C-c
245 keybinding. By default only Emacs Lisp (which has no
246 requirements) is loaded."
247 :group 'org-babel
248 :set 'org-babel-do-load-languages
249 :version "24.1"
250 :type '(alist :tag "Babel Languages"
251 :key-type
252 (choice
253 (const :tag "Awk" awk)
254 (const :tag "C" C)
255 (const :tag "R" R)
256 (const :tag "Asymptote" asymptote)
257 (const :tag "Calc" calc)
258 (const :tag "Clojure" clojure)
259 (const :tag "CSS" css)
260 (const :tag "Ditaa" ditaa)
261 (const :tag "Dot" dot)
262 (const :tag "Ebnf2ps" ebnf2ps)
263 (const :tag "Emacs Lisp" emacs-lisp)
264 (const :tag "Forth" forth)
265 (const :tag "Fortran" fortran)
266 (const :tag "Gnuplot" gnuplot)
267 (const :tag "Haskell" haskell)
268 (const :tag "hledger" hledger)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "Vala" vala))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (eval-and-compile
526 (defconst org-comment-string "COMMENT"
527 "Entries starting with this keyword will never be exported.
528 \\<org-mode-map>
529 An entry can be toggled between COMMENT and normal with
530 `\\[org-toggle-comment]'."))
533 ;;;; LaTeX Environments and Fragments
535 (defconst org-latex-regexps
536 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
537 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
538 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
539 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
541 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
542 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
543 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
544 "Regular expressions for matching embedded LaTeX.")
546 ;;;; Node Property
548 (defconst org-effort-property "Effort"
549 "The property that is being used to keep track of effort estimates.
550 Effort estimates given in this property need to have the format H:MM.")
552 ;;;; Table
554 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
555 "Detect an org-type or table-type table.")
557 (defconst org-table-line-regexp "^[ \t]*|"
558 "Detect an org-type table line.")
560 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
561 "Detect an org-type table line.")
563 (defconst org-table-hline-regexp "^[ \t]*|-"
564 "Detect an org-type table hline.")
566 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
567 "Detect a table-type table hline.")
569 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
570 "Detect the first line outside a table when searching from within it.
571 This works for both table types.")
573 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
574 "Detect a #+TBLFM line.")
576 ;;;; Timestamp
578 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
579 "Regular expression for fast time stamp matching.")
581 (defconst org-ts-regexp-inactive
582 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
583 "Regular expression for fast inactive time stamp matching.")
585 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
586 "Regular expression for fast time stamp matching.")
588 (defconst org-ts-regexp0
589 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
590 "Regular expression matching time strings for analysis.
591 This one does not require the space after the date, so it can be used
592 on a string that terminates immediately after the date.")
594 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
595 "Regular expression matching time strings for analysis.")
597 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
598 "Regular expression matching time stamps, with groups.")
600 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
601 "Regular expression matching time stamps (also [..]), with groups.")
603 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
604 "Regular expression matching a time stamp range.")
606 (defconst org-tr-regexp-both
607 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
608 "Regular expression matching a time stamp range.")
610 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
611 org-ts-regexp "\\)?")
612 "Regular expression matching a time stamp or time stamp range.")
614 (defconst org-tsr-regexp-both
615 (concat org-ts-regexp-both "\\(--?-?"
616 org-ts-regexp-both "\\)?")
617 "Regular expression matching a time stamp or time stamp range.
618 The time stamps may be either active or inactive.")
620 (defconst org-repeat-re
621 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
622 "Regular expression for specifying repeated events.
623 After a match, group 1 contains the repeat expression.")
625 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
626 "Formats for `format-time-string' which are used for time stamps.")
629 ;;; The custom variables
631 (defgroup org nil
632 "Outline-based notes management and organizer."
633 :tag "Org"
634 :group 'outlines
635 :group 'calendar)
637 (defcustom org-mode-hook nil
638 "Mode hook for Org mode, run after the mode was turned on."
639 :group 'org
640 :type 'hook)
642 (defcustom org-load-hook nil
643 "Hook that is run after org.el has been loaded."
644 :group 'org
645 :type 'hook)
647 (defcustom org-log-buffer-setup-hook nil
648 "Hook that is run after an Org log buffer is created."
649 :group 'org
650 :version "24.1"
651 :type 'hook)
653 (defvar org-modules) ; defined below
654 (defvar org-modules-loaded nil
655 "Have the modules been loaded already?")
657 (defun org-load-modules-maybe (&optional force)
658 "Load all extensions listed in `org-modules'."
659 (when (or force (not org-modules-loaded))
660 (dolist (ext org-modules)
661 (condition-case nil (require ext)
662 (error (message "Problems while trying to load feature `%s'" ext))))
663 (setq org-modules-loaded t)))
665 (defun org-set-modules (var value)
666 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
667 (set var value)
668 (when (featurep 'org)
669 (org-load-modules-maybe 'force)
670 (org-element-cache-reset 'all)))
672 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
673 "Modules that should always be loaded together with org.el.
675 If a description starts with <C>, the file is not part of Emacs
676 and loading it will require that you have downloaded and properly
677 installed the Org mode distribution.
679 You can also use this system to load external packages (i.e. neither Org
680 core modules, nor modules from the CONTRIB directory). Just add symbols
681 to the end of the list. If the package is called org-xyz.el, then you need
682 to add the symbol `xyz', and the package must have a call to:
684 (provide \\='org-xyz)
686 For export specific modules, see also `org-export-backends'."
687 :group 'org
688 :set 'org-set-modules
689 :version "24.4"
690 :package-version '(Org . "8.0")
691 :type
692 '(set :greedy t
693 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
694 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
695 (const :tag " crypt: Encryption of subtrees" org-crypt)
696 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
697 (const :tag " docview: Links to doc-view buffers" org-docview)
698 (const :tag " eww: Store link to url of eww" org-eww)
699 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
700 (const :tag " habit: Track your consistency with habits" org-habit)
701 (const :tag " id: Global IDs for identifying entries" org-id)
702 (const :tag " info: Links to Info nodes" org-info)
703 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
704 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
705 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
706 (const :tag " mouse: Additional mouse support" org-mouse)
707 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
708 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
709 (const :tag " tempo: Fast completion for structures" org-tempo)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
715 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
716 (const :tag "C collector: Collect properties into tables" org-collector)
717 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
718 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
719 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
720 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
721 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
722 (const :tag "C eval: Include command output as text" org-eval)
723 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
724 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
725 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
726 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
727 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
728 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
729 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
730 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
731 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
732 (const :tag "C man: Support for links to manpages in Org mode" org-man)
733 (const :tag "C mew: Links to Mew folders/messages" org-mew)
734 (const :tag "C mtags: Support for muse-like tags" org-mtags)
735 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
736 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
737 (const :tag "C registry: A registry for Org links" org-registry)
738 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
739 (const :tag "C secretary: Team management with org-mode" org-secretary)
740 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
741 (const :tag "C toc: Table of contents for Org buffer" org-toc)
742 (const :tag "C track: Keep up with Org mode development" org-track)
743 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
744 (const :tag "C vm: Links to VM folders/messages" org-vm)
745 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
746 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
747 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
749 (defvar org-export-registered-backends) ; From ox.el.
750 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
751 (declare-function org-export-backend-name "ox" (backend) t)
752 (defcustom org-export-backends '(ascii html icalendar latex odt)
753 "List of export back-ends that should be always available.
755 If a description starts with <C>, the file is not part of Emacs
756 and loading it will require that you have downloaded and properly
757 installed the Org mode distribution.
759 Unlike to `org-modules', libraries in this list will not be
760 loaded along with Org, but only once the export framework is
761 needed.
763 This variable needs to be set before org.el is loaded. If you
764 need to make a change while Emacs is running, use the customize
765 interface or run the following code, where VAL stands for the new
766 value of the variable, after updating it:
768 (progn
769 (setq org-export-registered-backends
770 (cl-remove-if-not
771 (lambda (backend)
772 (let ((name (org-export-backend-name backend)))
773 (or (memq name val)
774 (catch \\='parentp
775 (dolist (b val)
776 (and (org-export-derived-backend-p b name)
777 (throw \\='parentp t)))))))
778 org-export-registered-backends))
779 (let ((new-list (mapcar #\\='org-export-backend-name
780 org-export-registered-backends)))
781 (dolist (backend val)
782 (cond
783 ((not (load (format \"ox-%s\" backend) t t))
784 (message \"Problems while trying to load export back-end \\=`%s\\='\"
785 backend))
786 ((not (memq backend new-list)) (push backend new-list))))
787 (set-default \\='org-export-backends new-list)))
789 Adding a back-end to this list will also pull the back-end it
790 depends on, if any."
791 :group 'org
792 :group 'org-export
793 :version "26.1"
794 :package-version '(Org . "9.0")
795 :initialize 'custom-initialize-set
796 :set (lambda (var val)
797 (if (not (featurep 'ox)) (set-default var val)
798 ;; Any back-end not required anymore (not present in VAL and not
799 ;; a parent of any back-end in the new value) is removed from the
800 ;; list of registered back-ends.
801 (setq org-export-registered-backends
802 (cl-remove-if-not
803 (lambda (backend)
804 (let ((name (org-export-backend-name backend)))
805 (or (memq name val)
806 (catch 'parentp
807 (dolist (b val)
808 (and (org-export-derived-backend-p b name)
809 (throw 'parentp t)))))))
810 org-export-registered-backends))
811 ;; Now build NEW-LIST of both new back-ends and required
812 ;; parents.
813 (let ((new-list (mapcar #'org-export-backend-name
814 org-export-registered-backends)))
815 (dolist (backend val)
816 (cond
817 ((not (load (format "ox-%s" backend) t t))
818 (message "Problems while trying to load export back-end `%s'"
819 backend))
820 ((not (memq backend new-list)) (push backend new-list))))
821 ;; Set VAR to that list with fixed dependencies.
822 (set-default var new-list))))
823 :type '(set :greedy t
824 (const :tag " ascii Export buffer to ASCII format" ascii)
825 (const :tag " beamer Export buffer to Beamer presentation" beamer)
826 (const :tag " html Export buffer to HTML format" html)
827 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
828 (const :tag " latex Export buffer to LaTeX format" latex)
829 (const :tag " man Export buffer to MAN format" man)
830 (const :tag " md Export buffer to Markdown format" md)
831 (const :tag " odt Export buffer to ODT format" odt)
832 (const :tag " org Export buffer to Org format" org)
833 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
834 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
835 (const :tag "C deck Export buffer to deck.js presentations" deck)
836 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
837 (const :tag "C groff Export buffer to Groff format" groff)
838 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
839 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
840 (const :tag "C s5 Export buffer to s5 presentations" s5)
841 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
843 (eval-after-load 'ox
844 '(dolist (backend org-export-backends)
845 (condition-case nil (require (intern (format "ox-%s" backend)))
846 (error (message "Problems while trying to load export back-end `%s'"
847 backend)))))
849 (defcustom org-support-shift-select nil
850 "Non-nil means make shift-cursor commands select text when possible.
851 \\<org-mode-map>\
853 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
854 start selecting a region, or enlarge regions started in this way.
855 In Org mode, in special contexts, these same keys are used for
856 other purposes, important enough to compete with shift selection.
857 Org tries to balance these needs by supporting `shift-select-mode'
858 outside these special contexts, under control of this variable.
860 The default of this variable is nil, to avoid confusing behavior. Shifted
861 cursor keys will then execute Org commands in the following contexts:
862 - on a headline, changing TODO state (left/right) and priority (up/down)
863 - on a time stamp, changing the time
864 - in a plain list item, changing the bullet type
865 - in a property definition line, switching between allowed values
866 - in the BEGIN line of a clock table (changing the time block).
867 Outside these contexts, the commands will throw an error.
869 When this variable is t and the cursor is not in a special
870 context, Org mode will support shift-selection for making and
871 enlarging regions. To make this more effective, the bullet
872 cycling will no longer happen anywhere in an item line, but only
873 if the cursor is exactly on the bullet.
875 If you set this variable to the symbol `always', then the keys
876 will not be special in headlines, property lines, and item lines,
877 to make shift selection work there as well. If this is what you
878 want, you can use the following alternative commands:
879 `\\[org-todo]' and `\\[org-priority]' \
880 to change TODO state and priority,
881 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
882 can be used to switch TODO sets,
883 `\\[org-ctrl-c-minus]' to cycle item bullet types,
884 and properties can be edited by hand or in column view.
886 However, when the cursor is on a timestamp, shift-cursor commands
887 will still edit the time stamp - this is just too good to give up."
888 :group 'org
889 :type '(choice
890 (const :tag "Never" nil)
891 (const :tag "When outside special context" t)
892 (const :tag "Everywhere except timestamps" always)))
894 (defcustom org-loop-over-headlines-in-active-region nil
895 "Shall some commands act upon headlines in the active region?
897 When set to t, some commands will be performed in all headlines
898 within the active region.
900 When set to `start-level', some commands will be performed in all
901 headlines within the active region, provided that these headlines
902 are of the same level than the first one.
904 When set to a string, those commands will be performed on the
905 matching headlines within the active region. Such string must be
906 a tags/property/todo match as it is used in the agenda tags view.
908 The list of commands is: `org-schedule', `org-deadline',
909 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
910 `org-archive-to-archive-sibling'. The archiving commands skip
911 already archived entries."
912 :type '(choice (const :tag "Don't loop" nil)
913 (const :tag "All headlines in active region" t)
914 (const :tag "In active region, headlines at the same level than the first one" start-level)
915 (string :tag "Tags/Property/Todo matcher"))
916 :version "24.1"
917 :group 'org-todo
918 :group 'org-archive)
920 (defcustom org-startup-folded t
921 "Non-nil means entering Org mode will switch to OVERVIEW.
923 This can also be configured on a per-file basis by adding one of
924 the following lines anywhere in the buffer:
926 #+STARTUP: fold (or `overview', this is equivalent)
927 #+STARTUP: nofold (or `showall', this is equivalent)
928 #+STARTUP: content
929 #+STARTUP: showeverything
931 Set `org-agenda-inhibit-startup' to a non-nil value if you want
932 to ignore this option when Org opens agenda files for the first
933 time."
934 :group 'org-startup
935 :type '(choice
936 (const :tag "nofold: show all" nil)
937 (const :tag "fold: overview" t)
938 (const :tag "content: all headlines" content)
939 (const :tag "show everything, even drawers" showeverything)))
941 (defcustom org-startup-truncated t
942 "Non-nil means entering Org mode will set `truncate-lines'.
943 This is useful since some lines containing links can be very long and
944 uninteresting. Also tables look terrible when wrapped.
946 The variable `org-startup-truncated' allows to configure
947 truncation for Org mode different to the other modes that use the
948 variable `truncate-lines' and as a shortcut instead of putting
949 the variable `truncate-lines' into the `org-mode-hook'. If one
950 wants to configure truncation for Org mode not statically but
951 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
952 the variable `truncate-lines' has to be used because in such a
953 case it is too late to set the variable `org-startup-truncated'."
954 :group 'org-startup
955 :type 'boolean)
957 (defcustom org-startup-indented nil
958 "Non-nil means turn on `org-indent-mode' on startup.
959 This can also be configured on a per-file basis by adding one of
960 the following lines anywhere in the buffer:
962 #+STARTUP: indent
963 #+STARTUP: noindent"
964 :group 'org-structure
965 :type '(choice
966 (const :tag "Not" nil)
967 (const :tag "Globally (slow on startup in large files)" t)))
969 (defcustom org-use-sub-superscripts t
970 "Non-nil means interpret \"_\" and \"^\" for display.
972 If you want to control how Org exports those characters, see
973 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
974 used to be an alias for `org-export-with-sub-superscripts' in
975 Org <8.0, it is not anymore.
977 When this option is turned on, you can use TeX-like syntax for
978 sub- and superscripts within the buffer. Several characters after
979 \"_\" or \"^\" will be considered as a single item - so grouping
980 with {} is normally not needed. For example, the following things
981 will be parsed as single sub- or superscripts:
983 10^24 or 10^tau several digits will be considered 1 item.
984 10^-12 or 10^-tau a leading sign with digits or a word
985 x^2-y^3 will be read as x^2 - y^3, because items are
986 terminated by almost any nonword/nondigit char.
987 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
989 Still, ambiguity is possible. So when in doubt, use {} to enclose
990 the sub/superscript. If you set this variable to the symbol `{}',
991 the braces are *required* in order to trigger interpretations as
992 sub/superscript. This can be helpful in documents that need \"_\"
993 frequently in plain text."
994 :group 'org-startup
995 :version "24.4"
996 :package-version '(Org . "8.0")
997 :type '(choice
998 (const :tag "Always interpret" t)
999 (const :tag "Only with braces" {})
1000 (const :tag "Never interpret" nil)))
1002 (defcustom org-startup-with-beamer-mode nil
1003 "Non-nil means turn on `org-beamer-mode' on startup.
1004 This can also be configured on a per-file basis by adding one of
1005 the following lines anywhere in the buffer:
1007 #+STARTUP: beamer"
1008 :group 'org-startup
1009 :version "24.1"
1010 :type 'boolean)
1012 (defcustom org-startup-align-all-tables nil
1013 "Non-nil means align all tables when visiting a file.
1014 This can also be configured on a per-file basis by adding one of
1015 the following lines anywhere in the buffer:
1016 #+STARTUP: align
1017 #+STARTUP: noalign"
1018 :group 'org-startup
1019 :type 'boolean)
1021 (defcustom org-startup-shrink-all-tables nil
1022 "Non-nil means shrink all table columns with a width cookie.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: shrink"
1026 :group 'org-startup
1027 :type 'boolean
1028 :version "27.1"
1029 :package-version '(Org . "9.2")
1030 :safe #'booleanp)
1032 (defcustom org-startup-with-inline-images nil
1033 "Non-nil means show inline images when loading a new Org file.
1034 This can also be configured on a per-file basis by adding one of
1035 the following lines anywhere in the buffer:
1036 #+STARTUP: inlineimages
1037 #+STARTUP: noinlineimages"
1038 :group 'org-startup
1039 :version "24.1"
1040 :type 'boolean)
1042 (defcustom org-startup-with-latex-preview nil
1043 "Non-nil means preview LaTeX fragments when loading a new Org file.
1045 This can also be configured on a per-file basis by adding one of
1046 the following lines anywhere in the buffer:
1047 #+STARTUP: latexpreview
1048 #+STARTUP: nolatexpreview"
1049 :group 'org-startup
1050 :version "24.4"
1051 :package-version '(Org . "8.0")
1052 :type 'boolean)
1054 (defcustom org-insert-mode-line-in-empty-file nil
1055 "Non-nil means insert the first line setting Org mode in empty files.
1056 When the function `org-mode' is called interactively in an empty file, this
1057 normally means that the file name does not automatically trigger Org mode.
1058 To ensure that the file will always be in Org mode in the future, a
1059 line enforcing Org mode will be inserted into the buffer, if this option
1060 has been set."
1061 :group 'org-startup
1062 :type 'boolean)
1064 (defcustom org-replace-disputed-keys nil
1065 "Non-nil means use alternative key bindings for some keys.
1066 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1067 These keys are also used by other packages like shift-selection-mode'
1068 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1069 If you want to use Org mode together with one of these other modes,
1070 or more generally if you would like to move some Org mode commands to
1071 other keys, set this variable and configure the keys with the variable
1072 `org-disputed-keys'.
1074 This option is only relevant at load-time of Org mode, and must be set
1075 *before* org.el is loaded. Changing it requires a restart of Emacs to
1076 become effective."
1077 :group 'org-startup
1078 :type 'boolean)
1080 (defcustom org-use-extra-keys nil
1081 "Non-nil means use extra key sequence definitions for certain commands.
1082 This happens automatically if `window-system' is nil. This
1083 variable lets you do the same manually. You must set it before
1084 loading Org."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1090 (defcustom org-disputed-keys
1091 '(([(shift up)] . [(meta p)])
1092 ([(shift down)] . [(meta n)])
1093 ([(shift left)] . [(meta -)])
1094 ([(shift right)] . [(meta +)])
1095 ([(control shift right)] . [(meta shift +)])
1096 ([(control shift left)] . [(meta shift -)]))
1097 "Keys for which Org mode and other modes compete.
1098 This is an alist, cars are the default keys, second element specifies
1099 the alternative to use when `org-replace-disputed-keys' is t.
1101 Keys can be specified in any syntax supported by `define-key'.
1102 The value of this option takes effect only at Org mode startup,
1103 therefore you'll have to restart Emacs to apply it after changing."
1104 :group 'org-startup
1105 :type 'alist)
1107 (defun org-key (key)
1108 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1109 Or return the original if not disputed."
1110 (when org-replace-disputed-keys
1111 (let* ((nkey (key-description key))
1112 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1113 org-disputed-keys)))
1114 (setq key (if x (cdr x) key))))
1115 key)
1117 (defun org-defkey (keymap key def)
1118 "Define a key, possibly translated, as returned by `org-key'."
1119 (define-key keymap (org-key key) def))
1121 (defcustom org-ellipsis nil
1122 "The ellipsis to use in the Org mode outline.
1124 When nil, just use the standard three dots. When a non-empty string,
1125 use that string instead.
1127 The change affects only Org mode (which will then use its own display table).
1128 Changing this requires executing `\\[org-mode]' in a buffer to become
1129 effective."
1130 :group 'org-startup
1131 :type '(choice (const :tag "Default" nil)
1132 (string :tag "String" :value "...#"))
1133 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1135 (defvar org-display-table nil
1136 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1138 (defgroup org-keywords nil
1139 "Keywords in Org mode."
1140 :tag "Org Keywords"
1141 :group 'org)
1143 (defcustom org-closed-keep-when-no-todo nil
1144 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1145 :group 'org-todo
1146 :group 'org-keywords
1147 :version "24.4"
1148 :package-version '(Org . "8.0")
1149 :type 'boolean)
1151 (defgroup org-structure nil
1152 "Options concerning the general structure of Org files."
1153 :tag "Org Structure"
1154 :group 'org)
1156 (defgroup org-reveal-location nil
1157 "Options about how to make context of a location visible."
1158 :tag "Org Reveal Location"
1159 :group 'org-structure)
1161 (defcustom org-show-context-detail '((agenda . local)
1162 (bookmark-jump . lineage)
1163 (isearch . lineage)
1164 (default . ancestors))
1165 "Alist between context and visibility span when revealing a location.
1167 \\<org-mode-map>Some actions may move point into invisible
1168 locations. As a consequence, Org always expose a neighborhood
1169 around point. How much is shown depends on the initial action,
1170 or context. Valid contexts are
1172 agenda when exposing an entry from the agenda
1173 org-goto when using the command `org-goto' (`\\[org-goto]')
1174 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1175 tags-tree when constructing a sparse tree based on tags matches
1176 link-search when exposing search matches associated with a link
1177 mark-goto when exposing the jump goal of a mark
1178 bookmark-jump when exposing a bookmark location
1179 isearch when exiting from an incremental search
1180 default default for all contexts not set explicitly
1182 Allowed visibility spans are
1184 minimal show current headline; if point is not on headline,
1185 also show entry
1187 local show current headline, entry and next headline
1189 ancestors show current headline and its direct ancestors; if
1190 point is not on headline, also show entry
1192 lineage show current headline, its direct ancestors and all
1193 their children; if point is not on headline, also show
1194 entry and first child
1196 tree show current headline, its direct ancestors and all
1197 their children; if point is not on headline, also show
1198 entry and all children
1200 canonical show current headline, its direct ancestors along with
1201 their entries and children; if point is not located on
1202 the headline, also show current entry and all children
1204 As special cases, a nil or t value means show all contexts in
1205 `minimal' or `canonical' view, respectively.
1207 Some views can make displayed information very compact, but also
1208 make it harder to edit the location of the match. In such
1209 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1210 more context."
1211 :group 'org-reveal-location
1212 :version "26.1"
1213 :package-version '(Org . "9.0")
1214 :type '(choice
1215 (const :tag "Canonical" t)
1216 (const :tag "Minimal" nil)
1217 (repeat :greedy t :tag "Individual contexts"
1218 (cons
1219 (choice :tag "Context"
1220 (const agenda)
1221 (const org-goto)
1222 (const occur-tree)
1223 (const tags-tree)
1224 (const link-search)
1225 (const mark-goto)
1226 (const bookmark-jump)
1227 (const isearch)
1228 (const default))
1229 (choice :tag "Detail level"
1230 (const minimal)
1231 (const local)
1232 (const ancestors)
1233 (const lineage)
1234 (const tree)
1235 (const canonical))))))
1237 (defcustom org-indirect-buffer-display 'other-window
1238 "How should indirect tree buffers be displayed?
1240 This applies to indirect buffers created with the commands
1241 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1243 Valid values are:
1244 current-window Display in the current window
1245 other-window Just display in another window.
1246 dedicated-frame Create one new frame, and re-use it each time.
1247 new-frame Make a new frame each time. Note that in this case
1248 previously-made indirect buffers are kept, and you need to
1249 kill these buffers yourself."
1250 :group 'org-structure
1251 :group 'org-agenda-windows
1252 :type '(choice
1253 (const :tag "In current window" current-window)
1254 (const :tag "In current frame, other window" other-window)
1255 (const :tag "Each time a new frame" new-frame)
1256 (const :tag "One dedicated frame" dedicated-frame)))
1258 (defcustom org-use-speed-commands nil
1259 "Non-nil means activate single letter commands at beginning of a headline.
1260 This may also be a function to test for appropriate locations where speed
1261 commands should be active.
1263 For example, to activate speed commands when the point is on any
1264 star at the beginning of the headline, you can do this:
1266 (setq org-use-speed-commands
1267 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1268 :group 'org-structure
1269 :type '(choice
1270 (const :tag "Never" nil)
1271 (const :tag "At beginning of headline stars" t)
1272 (function)))
1274 (defcustom org-speed-commands-user nil
1275 "Alist of additional speed commands.
1276 This list will be checked before `org-speed-commands-default'
1277 when the variable `org-use-speed-commands' is non-nil
1278 and when the cursor is at the beginning of a headline.
1279 The car of each entry is a string with a single letter, which must
1280 be assigned to `self-insert-command' in the global map.
1281 The cdr is either a command to be called interactively, a function
1282 to be called, or a form to be evaluated.
1283 An entry that is just a list with a single string will be interpreted
1284 as a descriptive headline that will be added when listing the speed
1285 commands in the Help buffer using the `?' speed command."
1286 :group 'org-structure
1287 :type '(repeat :value ("k" . ignore)
1288 (choice :value ("k" . ignore)
1289 (list :tag "Descriptive Headline" (string :tag "Headline"))
1290 (cons :tag "Letter and Command"
1291 (string :tag "Command letter")
1292 (choice
1293 (function)
1294 (sexp))))))
1296 (defcustom org-bookmark-names-plist
1297 '(:last-capture "org-capture-last-stored"
1298 :last-refile "org-refile-last-stored"
1299 :last-capture-marker "org-capture-last-stored-marker")
1300 "Names for bookmarks automatically set by some Org commands.
1301 This can provide strings as names for a number of bookmarks Org sets
1302 automatically. The following keys are currently implemented:
1303 :last-capture
1304 :last-capture-marker
1305 :last-refile
1306 When a key does not show up in the property list, the corresponding bookmark
1307 is not set."
1308 :group 'org-structure
1309 :type 'plist)
1311 (defgroup org-cycle nil
1312 "Options concerning visibility cycling in Org mode."
1313 :tag "Org Cycle"
1314 :group 'org-structure)
1316 (defcustom org-cycle-skip-children-state-if-no-children t
1317 "Non-nil means skip CHILDREN state in entries that don't have any."
1318 :group 'org-cycle
1319 :type 'boolean)
1321 (defcustom org-cycle-max-level nil
1322 "Maximum level which should still be subject to visibility cycling.
1323 Levels higher than this will, for cycling, be treated as text, not a headline.
1324 When `org-odd-levels-only' is set, a value of N in this variable actually
1325 means 2N-1 stars as the limiting headline.
1326 When nil, cycle all levels.
1327 Note that the limiting level of cycling is also influenced by
1328 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1329 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1330 than its value."
1331 :group 'org-cycle
1332 :type '(choice
1333 (const :tag "No limit" nil)
1334 (integer :tag "Maximum level")))
1336 (defcustom org-hide-block-startup nil
1337 "Non-nil means entering Org mode will fold all blocks.
1338 This can also be set in on a per-file basis with
1340 #+STARTUP: hideblocks
1341 #+STARTUP: showblocks"
1342 :group 'org-startup
1343 :group 'org-cycle
1344 :type 'boolean)
1346 (defcustom org-cycle-global-at-bob nil
1347 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1349 This makes it possible to do global cycling without having to use `S-TAB'
1350 or `\\[universal-argument] TAB'. For this special case to work, the first \
1351 line of the buffer
1352 must not be a headline -- it may be empty or some other text.
1354 When used in this way, `org-cycle-hook' is disabled temporarily to make
1355 sure the cursor stays at the beginning of the buffer.
1357 When this option is nil, don't do anything special at the beginning of
1358 the buffer."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-level-after-item/entry-creation t
1363 "Non-nil means cycle entry level or item indentation in new empty entries.
1365 When the cursor is at the end of an empty headline, i.e., with only stars
1366 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1367 and then all possible ancestor states, before returning to the original state.
1368 This makes data entry extremely fast: M-RET to create a new headline,
1369 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1371 When the cursor is at the end of an empty plain list item, one TAB will
1372 make it a subitem, two or more tabs will back up to make this an item
1373 higher up in the item hierarchy."
1374 :group 'org-cycle
1375 :type 'boolean)
1377 (defcustom org-cycle-emulate-tab t
1378 "Where should `org-cycle' emulate TAB.
1379 nil Never
1380 white Only in completely white lines
1381 whitestart Only at the beginning of lines, before the first non-white char
1382 t Everywhere except in headlines
1383 exc-hl-bol Everywhere except at the start of a headline
1384 If TAB is used in a place where it does not emulate TAB, the current subtree
1385 visibility is cycled."
1386 :group 'org-cycle
1387 :type '(choice (const :tag "Never" nil)
1388 (const :tag "Only in completely white lines" white)
1389 (const :tag "Before first char in a line" whitestart)
1390 (const :tag "Everywhere except in headlines" t)
1391 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1393 (defcustom org-cycle-separator-lines 2
1394 "Number of empty lines needed to keep an empty line between collapsed trees.
1395 If you leave an empty line between the end of a subtree and the following
1396 headline, this empty line is hidden when the subtree is folded.
1397 Org mode will leave (exactly) one empty line visible if the number of
1398 empty lines is equal or larger to the number given in this variable.
1399 So the default 2 means at least 2 empty lines after the end of a subtree
1400 are needed to produce free space between a collapsed subtree and the
1401 following headline.
1403 If the number is negative, and the number of empty lines is at least -N,
1404 all empty lines are shown.
1406 Special case: when 0, never leave empty lines in collapsed view."
1407 :group 'org-cycle
1408 :type 'integer)
1409 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1411 (defcustom org-pre-cycle-hook nil
1412 "Hook that is run before visibility cycling is happening.
1413 The function(s) in this hook must accept a single argument which indicates
1414 the new state that will be set right after running this hook. The
1415 argument is a symbol. Before a global state change, it can have the values
1416 `overview', `content', or `all'. Before a local state change, it can have
1417 the values `folded', `children', or `subtree'."
1418 :group 'org-cycle
1419 :type 'hook)
1421 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1422 org-cycle-hide-drawers
1423 org-cycle-show-empty-lines
1424 org-optimize-window-after-visibility-change)
1425 "Hook that is run after `org-cycle' has changed the buffer visibility.
1426 The function(s) in this hook must accept a single argument which indicates
1427 the new state that was set by the most recent `org-cycle' command. The
1428 argument is a symbol. After a global state change, it can have the values
1429 `overview', `contents', or `all'. After a local state change, it can have
1430 the values `folded', `children', or `subtree'."
1431 :group 'org-cycle
1432 :type 'hook
1433 :version "26.1"
1434 :package-version '(Org . "8.3"))
1436 (defgroup org-edit-structure nil
1437 "Options concerning structure editing in Org mode."
1438 :tag "Org Edit Structure"
1439 :group 'org-structure)
1441 (defcustom org-odd-levels-only nil
1442 "Non-nil means skip even levels and only use odd levels for the outline.
1443 This has the effect that two stars are being added/taken away in
1444 promotion/demotion commands. It also influences how levels are
1445 handled by the exporters.
1446 Changing it requires restart of `font-lock-mode' to become effective
1447 for fontification also in regions already fontified.
1448 You may also set this on a per-file basis by adding one of the following
1449 lines to the buffer:
1451 #+STARTUP: odd
1452 #+STARTUP: oddeven"
1453 :group 'org-edit-structure
1454 :group 'org-appearance
1455 :type 'boolean)
1457 (defcustom org-adapt-indentation t
1458 "Non-nil means adapt indentation to outline node level.
1460 When this variable is set, Org assumes that you write outlines by
1461 indenting text in each node to align with the headline (after the
1462 stars). The following issues are influenced by this variable:
1464 - The indentation is increased by one space in a demotion
1465 command, and decreased by one in a promotion command. However,
1466 in the latter case, if shifting some line in the entry body
1467 would alter document structure (e.g., insert a new headline),
1468 indentation is not changed at all.
1470 - Property drawers and planning information is inserted indented
1471 when this variable is set. When nil, they will not be indented.
1473 - TAB indents a line relative to current level. The lines below
1474 a headline will be indented when this variable is set.
1476 Note that this is all about true indentation, by adding and
1477 removing space characters. See also `org-indent.el' which does
1478 level-dependent indentation in a virtual way, i.e. at display
1479 time in Emacs."
1480 :group 'org-edit-structure
1481 :type 'boolean)
1483 (defcustom org-special-ctrl-a/e nil
1484 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1486 When t, `C-a' will bring back the cursor to the beginning of the
1487 headline text, i.e. after the stars and after a possible TODO
1488 keyword. In an item, this will be the position after bullet and
1489 check-box, if any. When the cursor is already at that position,
1490 another `C-a' will bring it to the beginning of the line.
1492 `C-e' will jump to the end of the headline, ignoring the presence
1493 of tags in the headline. A second `C-e' will then jump to the
1494 true end of the line, after any tags. This also means that, when
1495 this variable is non-nil, `C-e' also will never jump beyond the
1496 end of the heading of a folded section, i.e. not after the
1497 ellipses.
1499 When set to the symbol `reversed', the first `C-a' or `C-e' works
1500 normally, going to the true line boundary first. Only a directly
1501 following, identical keypress will bring the cursor to the
1502 special positions.
1504 This may also be a cons cell where the behavior for `C-a' and
1505 `C-e' is set separately."
1506 :group 'org-edit-structure
1507 :type '(choice
1508 (const :tag "off" nil)
1509 (const :tag "on: after stars/bullet and before tags first" t)
1510 (const :tag "reversed: true line boundary first" reversed)
1511 (cons :tag "Set C-a and C-e separately"
1512 (choice :tag "Special C-a"
1513 (const :tag "off" nil)
1514 (const :tag "on: after stars/bullet first" t)
1515 (const :tag "reversed: before stars/bullet first" reversed))
1516 (choice :tag "Special C-e"
1517 (const :tag "off" nil)
1518 (const :tag "on: before tags first" t)
1519 (const :tag "reversed: after tags first" reversed)))))
1520 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1522 (defcustom org-special-ctrl-k nil
1523 "Non-nil means `C-k' will behave specially in headlines.
1524 When nil, `C-k' will call the default `kill-line' command.
1525 When t, the following will happen while the cursor is in the headline:
1527 - When the cursor is at the beginning of a headline, kill the entire
1528 line and possible the folded subtree below the line.
1529 - When in the middle of the headline text, kill the headline up to the tags.
1530 - When after the headline text, kill the tags."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-ctrl-k-protect-subtree nil
1535 "Non-nil means, do not delete a hidden subtree with C-k.
1536 When set to the symbol `error', simply throw an error when C-k is
1537 used to kill (part-of) a headline that has hidden text behind it.
1538 Any other non-nil value will result in a query to the user, if it is
1539 OK to kill that hidden subtree. When nil, kill without remorse."
1540 :group 'org-edit-structure
1541 :version "24.1"
1542 :type '(choice
1543 (const :tag "Do not protect hidden subtrees" nil)
1544 (const :tag "Protect hidden subtrees with a security query" t)
1545 (const :tag "Never kill a hidden subtree with C-k" error)))
1547 (defcustom org-special-ctrl-o t
1548 "Non-nil means, make `C-o' insert a row in tables."
1549 :group 'org-edit-structure
1550 :type 'boolean)
1552 (defcustom org-catch-invisible-edits nil
1553 "Check if in invisible region before inserting or deleting a character.
1554 Valid values are:
1556 nil Do not check, so just do invisible edits.
1557 error Throw an error and do nothing.
1558 show Make point visible, and do the requested edit.
1559 show-and-error Make point visible, then throw an error and abort the edit.
1560 smart Make point visible, and do insertion/deletion if it is
1561 adjacent to visible text and the change feels predictable.
1562 Never delete a previously invisible character or add in the
1563 middle or right after an invisible region. Basically, this
1564 allows insertion and backward-delete right before ellipses.
1565 FIXME: maybe in this case we should not even show?"
1566 :group 'org-edit-structure
1567 :version "24.1"
1568 :type '(choice
1569 (const :tag "Do not check" nil)
1570 (const :tag "Throw error when trying to edit" error)
1571 (const :tag "Unhide, but do not do the edit" show-and-error)
1572 (const :tag "Show invisible part and do the edit" show)
1573 (const :tag "Be smart and do the right thing" smart)))
1575 (defcustom org-yank-folded-subtrees t
1576 "Non-nil means when yanking subtrees, fold them.
1577 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1578 it starts with a heading and all other headings in it are either children
1579 or siblings, then fold all the subtrees. However, do this only if no
1580 text after the yank would be swallowed into a folded tree by this action."
1581 :group 'org-edit-structure
1582 :type 'boolean)
1584 (defcustom org-yank-adjusted-subtrees nil
1585 "Non-nil means when yanking subtrees, adjust the level.
1586 With this setting, `org-paste-subtree' is used to insert the subtree, see
1587 this function for details."
1588 :group 'org-edit-structure
1589 :type 'boolean)
1591 (defcustom org-M-RET-may-split-line '((default . t))
1592 "Non-nil means M-RET will split the line at the cursor position.
1593 When nil, it will go to the end of the line before making a
1594 new line.
1595 You may also set this option in a different way for different
1596 contexts. Valid contexts are:
1598 headline when creating a new headline
1599 item when creating a new item
1600 table in a table field
1601 default the value to be used for all contexts not explicitly
1602 customized"
1603 :group 'org-structure
1604 :group 'org-table
1605 :type '(choice
1606 (const :tag "Always" t)
1607 (const :tag "Never" nil)
1608 (repeat :greedy t :tag "Individual contexts"
1609 (cons
1610 (choice :tag "Context"
1611 (const headline)
1612 (const item)
1613 (const table)
1614 (const default))
1615 (boolean)))))
1618 (defcustom org-insert-heading-respect-content nil
1619 "Non-nil means insert new headings after the current subtree.
1620 \\<org-mode-map>
1621 When nil, the new heading is created directly after the current line.
1622 The commands `\\[org-insert-heading-respect-content]' and \
1623 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1624 for the duration of the command."
1625 :group 'org-structure
1626 :type 'boolean)
1628 (defcustom org-blank-before-new-entry '((heading . auto)
1629 (plain-list-item . auto))
1630 "Should `org-insert-heading' leave a blank line before new heading/item?
1631 The value is an alist, with `heading' and `plain-list-item' as CAR,
1632 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1633 which case Org will look at the surrounding headings/items and try to
1634 make an intelligent decision whether to insert a blank line or not."
1635 :group 'org-edit-structure
1636 :type '(list
1637 (cons (const heading)
1638 (choice (const :tag "Never" nil)
1639 (const :tag "Always" t)
1640 (const :tag "Auto" auto)))
1641 (cons (const plain-list-item)
1642 (choice (const :tag "Never" nil)
1643 (const :tag "Always" t)
1644 (const :tag "Auto" auto)))))
1646 (defcustom org-insert-heading-hook nil
1647 "Hook being run after inserting a new heading."
1648 :group 'org-edit-structure
1649 :type 'hook)
1651 (defcustom org-enable-fixed-width-editor t
1652 "Non-nil means lines starting with \":\" are treated as fixed-width.
1653 This currently only means they are never auto-wrapped.
1654 When nil, such lines will be treated like ordinary lines."
1655 :group 'org-edit-structure
1656 :type 'boolean)
1658 (defgroup org-sparse-trees nil
1659 "Options concerning sparse trees in Org mode."
1660 :tag "Org Sparse Trees"
1661 :group 'org-structure)
1663 (defcustom org-highlight-sparse-tree-matches t
1664 "Non-nil means highlight all matches that define a sparse tree.
1665 The highlights will automatically disappear the next time the buffer is
1666 changed by an edit command."
1667 :group 'org-sparse-trees
1668 :type 'boolean)
1670 (defcustom org-remove-highlights-with-change t
1671 "Non-nil means any change to the buffer will remove temporary highlights.
1672 \\<org-mode-map>\
1673 Such highlights are created by `org-occur' and `org-clock-display'.
1674 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1675 to get rid of the highlights.
1676 The highlights created by `org-toggle-latex-fragment' always need
1677 `\\[org-toggle-latex-fragment]' to be removed."
1678 :group 'org-sparse-trees
1679 :group 'org-time
1680 :type 'boolean)
1682 (defcustom org-occur-case-fold-search t
1683 "Non-nil means `org-occur' should be case-insensitive.
1684 If set to `smart' the search will be case-insensitive only if it
1685 doesn't specify any upper case character."
1686 :group 'org-sparse-trees
1687 :version "26.1"
1688 :type '(choice
1689 (const :tag "Case-sensitive" nil)
1690 (const :tag "Case-insensitive" t)
1691 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1693 (defcustom org-occur-hook '(org-first-headline-recenter)
1694 "Hook that is run after `org-occur' has constructed a sparse tree.
1695 This can be used to recenter the window to show as much of the structure
1696 as possible."
1697 :group 'org-sparse-trees
1698 :type 'hook)
1700 (defgroup org-table nil
1701 "Options concerning tables in Org mode."
1702 :tag "Org Table"
1703 :group 'org)
1705 (defcustom org-self-insert-cluster-for-undo nil
1706 "Non-nil means cluster self-insert commands for undo when possible.
1707 If this is set, then, like in the Emacs command loop, 20 consecutive
1708 characters will be undone together.
1709 This is configurable, because there is some impact on typing performance."
1710 :group 'org-table
1711 :type 'boolean)
1713 (defcustom org-table-tab-recognizes-table.el t
1714 "Non-nil means TAB will automatically notice a table.el table.
1715 When it sees such a table, it moves point into it and - if necessary -
1716 calls `table-recognize-table'."
1717 :group 'org-table-editing
1718 :type 'boolean)
1720 (defgroup org-link nil
1721 "Options concerning links in Org mode."
1722 :tag "Org Link"
1723 :group 'org)
1725 (defvar-local org-link-abbrev-alist-local nil
1726 "Buffer-local version of `org-link-abbrev-alist', which see.
1727 The value of this is taken from the #+LINK lines.")
1729 (defcustom org-link-parameters
1730 '(("doi" :follow org--open-doi-link)
1731 ("elisp" :follow org--open-elisp-link)
1732 ("file" :complete org-file-complete-link)
1733 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1734 ("help" :follow org--open-help-link)
1735 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1736 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1737 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1738 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1739 ("shell" :follow org--open-shell-link))
1740 "An alist of properties that defines all the links in Org mode.
1741 The key in each association is a string of the link type.
1742 Subsequent optional elements make up a p-list of link properties.
1744 :follow - A function that takes the link path as an argument.
1746 :export - A function that takes the link path, description and
1747 export-backend as arguments.
1749 :store - A function responsible for storing the link. See the
1750 function `org-store-link-functions'.
1752 :complete - A function that inserts a link with completion. The
1753 function takes one optional prefix arg.
1755 :face - A face for the link, or a function that returns a face.
1756 The function takes one argument which is the link path. The
1757 default face is `org-link'.
1759 :mouse-face - The mouse-face. The default is `highlight'.
1761 :display - `full' will not fold the link in descriptive
1762 display. Default is `org-link'.
1764 :help-echo - A string or function that takes (window object position)
1765 as arguments and returns a string.
1767 :keymap - A keymap that is active on the link. The default is
1768 `org-mouse-map'.
1770 :htmlize-link - A function for the htmlize-link. Defaults
1771 to (list :uri \"type:path\")
1773 :activate-func - A function to run at the end of font-lock
1774 activation. The function must accept (link-start link-end path bracketp)
1775 as arguments."
1776 :group 'org-link
1777 :type '(alist :tag "Link display parameters"
1778 :value-type plist)
1779 :version "26.1"
1780 :package-version '(Org . "9.1"))
1782 (defun org-link-get-parameter (type key)
1783 "Get TYPE link property for KEY.
1784 TYPE is a string and KEY is a plist keyword."
1785 (plist-get
1786 (cdr (assoc type org-link-parameters))
1787 key))
1789 (defun org-link-set-parameters (type &rest parameters)
1790 "Set link TYPE properties to PARAMETERS.
1791 PARAMETERS should be :key val pairs."
1792 (let ((data (assoc type org-link-parameters)))
1793 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1794 (push (cons type parameters) org-link-parameters)
1795 (org-make-link-regexps)
1796 (org-element-update-syntax))))
1798 (defun org-link-types ()
1799 "Return a list of known link types."
1800 (mapcar #'car org-link-parameters))
1802 (defcustom org-link-abbrev-alist nil
1803 "Alist of link abbreviations.
1804 The car of each element is a string, to be replaced at the start of a link.
1805 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1806 links in Org buffers can have an optional tag after a double colon, e.g.,
1808 [[linkkey:tag][description]]
1810 The `linkkey' must be a single word, starting with a letter, followed
1811 by letters, numbers, `-' or `_'.
1813 If REPLACE is a string, the tag will simply be appended to create the link.
1814 If the string contains \"%s\", the tag will be inserted there. If the string
1815 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1816 at that point (see the function `url-hexify-string'). If the string contains
1817 the specifier \"%(my-function)\", then the custom function `my-function' will
1818 be invoked: this function takes the tag as its only argument and must return
1819 a string.
1821 REPLACE may also be a function that will be called with the tag as the
1822 only argument to create the link, which should be returned as a string.
1824 See the manual for examples."
1825 :group 'org-link
1826 :type '(repeat
1827 (cons
1828 (string :tag "Protocol")
1829 (choice
1830 (string :tag "Format")
1831 (function)))))
1833 (defcustom org-descriptive-links t
1834 "Non-nil means Org will display descriptive links.
1835 E.g. [[http://orgmode.org][Org website]] will be displayed as
1836 \"Org Website\", hiding the link itself and just displaying its
1837 description. When set to nil, Org will display the full links
1838 literally.
1840 You can interactively set the value of this variable by calling
1841 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1842 :group 'org-link
1843 :type 'boolean)
1845 (defcustom org-link-file-path-type 'adaptive
1846 "How the path name in file links should be stored.
1847 Valid values are:
1849 relative Relative to the current directory, i.e. the directory of the file
1850 into which the link is being inserted.
1851 absolute Absolute path, if possible with ~ for home directory.
1852 noabbrev Absolute path, no abbreviation of home directory.
1853 adaptive Use relative path for files in the current directory and sub-
1854 directories of it. For other files, use an absolute path."
1855 :group 'org-link
1856 :type '(choice
1857 (const relative)
1858 (const absolute)
1859 (const noabbrev)
1860 (const adaptive)))
1862 (defvaralias 'org-activate-links 'org-highlight-links)
1863 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1864 "Types of links that should be highlighted in Org files.
1866 This is a list of symbols, each one of them leading to the
1867 highlighting of a certain link type.
1869 You can still open links that are not highlighted.
1871 In principle, it does not hurt to turn on highlighting for all
1872 link types. There may be a small gain when turning off unused
1873 link types. The types are:
1875 bracket The recommended [[link][description]] or [[link]] links with hiding.
1876 angle Links in angular brackets that may contain whitespace like
1877 <bbdb:Carsten Dominik>.
1878 plain Plain links in normal text, no whitespace, like http://google.com.
1879 radio Text that is matched by a radio target, see manual for details.
1880 tag Tag settings in a headline (link to tag search).
1881 date Time stamps (link to calendar).
1882 footnote Footnote labels.
1884 If you set this variable during an Emacs session, use `org-mode-restart'
1885 in the Org buffer so that the change takes effect."
1886 :group 'org-link
1887 :group 'org-appearance
1888 :type '(set :greedy t
1889 (const :tag "Double bracket links" bracket)
1890 (const :tag "Angular bracket links" angle)
1891 (const :tag "Plain text links" plain)
1892 (const :tag "Radio target matches" radio)
1893 (const :tag "Tags" tag)
1894 (const :tag "Timestamps" date)
1895 (const :tag "Footnotes" footnote)))
1897 (defcustom org-make-link-description-function nil
1898 "Function to use for generating link descriptions from links.
1899 This function must take two parameters: the first one is the
1900 link, the second one is the description generated by
1901 `org-insert-link'. The function should return the description to
1902 use."
1903 :group 'org-link
1904 :type '(choice (const nil) (function)))
1906 (defgroup org-link-store nil
1907 "Options concerning storing links in Org mode."
1908 :tag "Org Store Link"
1909 :group 'org-link)
1911 (defcustom org-url-hexify-p t
1912 "When non-nil, hexify URL when creating a link."
1913 :type 'boolean
1914 :version "24.3"
1915 :group 'org-link-store)
1917 (defcustom org-email-link-description-format "Email %c: %.30s"
1918 "Format of the description part of a link to an email or usenet message.
1919 The following %-escapes will be replaced by corresponding information:
1921 %F full \"From\" field
1922 %f name, taken from \"From\" field, address if no name
1923 %T full \"To\" field
1924 %t first name in \"To\" field, address if no name
1925 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1926 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1927 %s subject
1928 %d date
1929 %m message-id.
1931 You may use normal field width specification between the % and the letter.
1932 This is for example useful to limit the length of the subject.
1934 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1935 :group 'org-link-store
1936 :type 'string)
1938 (defcustom org-from-is-user-regexp
1939 (let (r1 r2)
1940 (when (and user-mail-address (not (string= user-mail-address "")))
1941 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1942 (when (and user-full-name (not (string= user-full-name "")))
1943 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1944 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1945 "Regexp matched against the \"From:\" header of an email or usenet message.
1946 It should match if the message is from the user him/herself."
1947 :group 'org-link-store
1948 :type 'regexp)
1950 (defcustom org-context-in-file-links t
1951 "Non-nil means file links from `org-store-link' contain context.
1952 \\<org-mode-map>
1953 A search string will be added to the file name with :: as separator
1954 and used to find the context when the link is activated by the command
1955 `org-open-at-point'. When this option is t, the entire active region
1956 will be placed in the search string of the file link. If set to a
1957 positive integer, only the first n lines of context will be stored.
1959 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1960 \\[org-store-link]')
1961 negates this setting for the duration of the command."
1962 :group 'org-link-store
1963 :type '(choice boolean integer))
1965 (defcustom org-keep-stored-link-after-insertion nil
1966 "Non-nil means keep link in list for entire session.
1967 \\<org-mode-map>
1968 The command `org-store-link' adds a link pointing to the current
1969 location to an internal list. These links accumulate during a session.
1970 The command `org-insert-link' can be used to insert links into any
1971 Org file (offering completion for all stored links).
1973 When this option is nil, every link which has been inserted once using
1974 `\\[org-insert-link]' will be removed from the list, to make completing the \
1975 unused
1976 links more efficient."
1977 :group 'org-link-store
1978 :type 'boolean)
1980 (defgroup org-link-follow nil
1981 "Options concerning following links in Org mode."
1982 :tag "Org Follow Link"
1983 :group 'org-link)
1985 (defcustom org-link-translation-function nil
1986 "Function to translate links with different syntax to Org syntax.
1987 This can be used to translate links created for example by the Planner
1988 or emacs-wiki packages to Org syntax.
1989 The function must accept two parameters, a TYPE containing the link
1990 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1991 which is everything after the link protocol. It should return a cons
1992 with possibly modified values of type and path.
1993 Org contains a function for this, so if you set this variable to
1994 `org-translate-link-from-planner', you should be able follow many
1995 links created by planner."
1996 :group 'org-link-follow
1997 :type '(choice (const nil) (function)))
1999 (defcustom org-follow-link-hook nil
2000 "Hook that is run after a link has been followed."
2001 :group 'org-link-follow
2002 :type 'hook)
2004 (defcustom org-tab-follows-link nil
2005 "Non-nil means on links TAB will follow the link.
2006 Needs to be set before org.el is loaded.
2007 This really should not be used, it does not make sense, and the
2008 implementation is bad."
2009 :group 'org-link-follow
2010 :type 'boolean)
2012 (defcustom org-return-follows-link nil
2013 "Non-nil means on links RET will follow the link.
2014 In tables, the special behavior of RET has precedence."
2015 :group 'org-link-follow
2016 :type 'boolean)
2018 (defcustom org-mouse-1-follows-link
2019 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2020 "Non-nil means mouse-1 on a link will follow the link.
2021 A longer mouse click will still set point. Needs to be set
2022 before org.el is loaded."
2023 :group 'org-link-follow
2024 :version "26.1"
2025 :package-version '(Org . "8.3")
2026 :type '(choice
2027 (const :tag "A double click follows the link" double)
2028 (const :tag "Unconditionally follow the link with mouse-1" t)
2029 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2031 (defcustom org-mark-ring-length 4
2032 "Number of different positions to be recorded in the ring.
2033 Changing this requires a restart of Emacs to work correctly."
2034 :group 'org-link-follow
2035 :type 'integer)
2037 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2038 "Non-nil means internal fuzzy links can only match headlines.
2040 When nil, the a fuzzy link may point to a target or a named
2041 construct in the document. When set to the special value
2042 `query-to-create', offer to create a new headline when none
2043 matched.
2045 Spaces and statistics cookies are ignored during heading searches."
2046 :group 'org-link-follow
2047 :version "24.1"
2048 :type '(choice
2049 (const :tag "Use fuzzy text search" nil)
2050 (const :tag "Match only exact headline" t)
2051 (const :tag "Match exact headline or query to create it"
2052 query-to-create))
2053 :safe #'symbolp)
2055 (defcustom org-link-frame-setup
2056 '((vm . vm-visit-folder-other-frame)
2057 (vm-imap . vm-visit-imap-folder-other-frame)
2058 (gnus . org-gnus-no-new-news)
2059 (file . find-file-other-window)
2060 (wl . wl-other-frame))
2061 "Setup the frame configuration for following links.
2062 When following a link with Emacs, it may often be useful to display
2063 this link in another window or frame. This variable can be used to
2064 set this up for the different types of links.
2065 For VM, use any of
2066 `vm-visit-folder'
2067 `vm-visit-folder-other-window'
2068 `vm-visit-folder-other-frame'
2069 For Gnus, use any of
2070 `gnus'
2071 `gnus-other-frame'
2072 `org-gnus-no-new-news'
2073 For FILE, use any of
2074 `find-file'
2075 `find-file-other-window'
2076 `find-file-other-frame'
2077 For Wanderlust use any of
2078 `wl'
2079 `wl-other-frame'
2080 For the calendar, use the variable `calendar-setup'.
2081 For BBDB, it is currently only possible to display the matches in
2082 another window."
2083 :group 'org-link-follow
2084 :type '(list
2085 (cons (const vm)
2086 (choice
2087 (const vm-visit-folder)
2088 (const vm-visit-folder-other-window)
2089 (const vm-visit-folder-other-frame)))
2090 (cons (const vm-imap)
2091 (choice
2092 (const vm-visit-imap-folder)
2093 (const vm-visit-imap-folder-other-window)
2094 (const vm-visit-imap-folder-other-frame)))
2095 (cons (const gnus)
2096 (choice
2097 (const gnus)
2098 (const gnus-other-frame)
2099 (const org-gnus-no-new-news)))
2100 (cons (const file)
2101 (choice
2102 (const find-file)
2103 (const find-file-other-window)
2104 (const find-file-other-frame)))
2105 (cons (const wl)
2106 (choice
2107 (const wl)
2108 (const wl-other-frame)))))
2110 (defcustom org-display-internal-link-with-indirect-buffer nil
2111 "Non-nil means use indirect buffer to display infile links.
2112 Activating internal links (from one location in a file to another location
2113 in the same file) normally just jumps to the location. When the link is
2114 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2115 is displayed in
2116 another window. When this option is set, the other window actually displays
2117 an indirect buffer clone of the current buffer, to avoid any visibility
2118 changes to the current buffer."
2119 :group 'org-link-follow
2120 :type 'boolean)
2122 (defcustom org-open-non-existing-files nil
2123 "Non-nil means `org-open-file' will open non-existing files.
2124 When nil, an error will be generated.
2125 This variable applies only to external applications because they
2126 might choke on non-existing files. If the link is to a file that
2127 will be opened in Emacs, the variable is ignored."
2128 :group 'org-link-follow
2129 :type 'boolean)
2131 (defcustom org-open-directory-means-index-dot-org nil
2132 "Non-nil means a link to a directory really means to index.org.
2133 When nil, following a directory link will run dired or open a finder/explorer
2134 window on that directory."
2135 :group 'org-link-follow
2136 :type 'boolean)
2138 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2139 "Non-nil means ask for confirmation before executing shell links.
2140 Shell links can be dangerous: just think about a link
2142 [[shell:rm -rf ~/*][Google Search]]
2144 This link would show up in your Org document as \"Google Search\",
2145 but really it would remove your entire home directory.
2146 Therefore we advise against setting this variable to nil.
2147 Just change it to `y-or-n-p' if you want to confirm with a
2148 single keystroke rather than having to type \"yes\"."
2149 :group 'org-link-follow
2150 :type '(choice
2151 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2152 (const :tag "with y-or-n (faster)" y-or-n-p)
2153 (const :tag "no confirmation (dangerous)" nil)))
2154 (put 'org-confirm-shell-link-function
2155 'safe-local-variable
2156 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2158 (defcustom org-confirm-shell-link-not-regexp ""
2159 "A regexp to skip confirmation for shell links."
2160 :group 'org-link-follow
2161 :version "24.1"
2162 :type 'regexp)
2164 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2165 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2166 Elisp links can be dangerous: just think about a link
2168 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2170 This link would show up in your Org document as \"Google Search\",
2171 but really it would remove your entire home directory.
2172 Therefore we advise against setting this variable to nil.
2173 Just change it to `y-or-n-p' if you want to confirm with a
2174 single keystroke rather than having to type \"yes\"."
2175 :group 'org-link-follow
2176 :type '(choice
2177 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2178 (const :tag "with y-or-n (faster)" y-or-n-p)
2179 (const :tag "no confirmation (dangerous)" nil)))
2180 (put 'org-confirm-shell-link-function
2181 'safe-local-variable
2182 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2184 (defcustom org-confirm-elisp-link-not-regexp ""
2185 "A regexp to skip confirmation for Elisp links."
2186 :group 'org-link-follow
2187 :version "24.1"
2188 :type 'regexp)
2190 (defconst org-file-apps-defaults-gnu
2191 '((remote . emacs)
2192 (system . mailcap)
2193 (t . mailcap))
2194 "Default file applications on a UNIX or GNU/Linux system.
2195 See `org-file-apps'.")
2197 (defconst org-file-apps-defaults-macosx
2198 '((remote . emacs)
2199 (system . "open %s")
2200 ("ps.gz" . "gv %s")
2201 ("eps.gz" . "gv %s")
2202 ("dvi" . "xdvi %s")
2203 ("fig" . "xfig %s")
2204 (t . "open %s"))
2205 "Default file applications on a macOS system.
2206 The system \"open\" is known as a default, but we use X11 applications
2207 for some files for which the OS does not have a good default.
2208 See `org-file-apps'.")
2210 (defconst org-file-apps-defaults-windowsnt
2211 (list '(remote . emacs)
2212 (cons 'system (lambda (file _path)
2213 (with-no-warnings (w32-shell-execute "open" file))))
2214 (cons t (lambda (file _path)
2215 (with-no-warnings (w32-shell-execute "open" file)))))
2216 "Default file applications on a Windows NT system.
2217 The system \"open\" is used for most files.
2218 See `org-file-apps'.")
2220 (defcustom org-file-apps
2221 '((auto-mode . emacs)
2222 ("\\.mm\\'" . default)
2223 ("\\.x?html?\\'" . default)
2224 ("\\.pdf\\'" . default))
2225 "External applications for opening `file:path' items in a document.
2226 \\<org-mode-map>\
2228 Org mode uses system defaults for different file types, but
2229 you can use this variable to set the application for a given file
2230 extension. The entries in this list are cons cells where the car identifies
2231 files and the cdr the corresponding command.
2233 Possible values for the file identifier are:
2235 \"string\" A string as a file identifier can be interpreted in different
2236 ways, depending on its contents:
2238 - Alphanumeric characters only:
2239 Match links with this file extension.
2240 Example: (\"pdf\" . \"evince %s\")
2241 to open PDFs with evince.
2243 - Regular expression: Match links where the
2244 filename matches the regexp. If you want to
2245 use groups here, use shy groups.
2247 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2248 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2249 to open *.html and *.xhtml with firefox.
2251 - Regular expression which contains (non-shy) groups:
2252 Match links where the whole link, including \"::\", and
2253 anything after that, matches the regexp.
2254 In a custom command string, %1, %2, etc. are replaced with
2255 the parts of the link that were matched by the groups.
2256 For backwards compatibility, if a command string is given
2257 that does not use any of the group matches, this case is
2258 handled identically to the second one (i.e. match against
2259 file name only).
2260 In a custom function, you can access the group matches with
2261 (match-string n link).
2263 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2264 \"evince -p %1 %s\")
2265 to open [[file:document.pdf::5]] with evince at page 5.
2267 `directory' Matches a directory
2268 `remote' Matches a remote file, accessible through tramp or efs.
2269 Remote files most likely should be visited through Emacs
2270 because external applications cannot handle such paths.
2271 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2272 so all files Emacs knows how to handle. Using this with
2273 command `emacs' will open most files in Emacs. Beware that this
2274 will also open html files inside Emacs, unless you add
2275 (\"html\" . default) to the list as well.
2276 `system' The system command to open files, like `open' on Windows
2277 and macOS, and mailcap under GNU/Linux. This is the command
2278 that will be selected if you call `org-open-at-point' with a
2279 double prefix argument (`\\[universal-argument] \
2280 \\[universal-argument] \\[org-open-at-point]').
2281 t Default for files not matched by any of the other options.
2283 Possible values for the command are:
2285 `emacs' The file will be visited by the current Emacs process.
2286 `default' Use the default application for this file type, which is the
2287 association for t in the list, most likely in the system-specific
2288 part. This can be used to overrule an unwanted setting in the
2289 system-specific variable.
2290 `system' Use the system command for opening files, like \"open\".
2291 This command is specified by the entry whose car is `system'.
2292 Most likely, the system-specific version of this variable
2293 does define this command, but you can overrule/replace it
2294 here.
2295 `mailcap' Use command specified in the mailcaps.
2296 string A command to be executed by a shell; %s will be replaced
2297 by the path to the file.
2298 function A Lisp function, which will be called with two arguments:
2299 the file path and the original link string, without the
2300 \"file:\" prefix.
2302 For more examples, see the system specific constants
2303 `org-file-apps-defaults-macosx'
2304 `org-file-apps-defaults-windowsnt'
2305 `org-file-apps-defaults-gnu'."
2306 :group 'org-link-follow
2307 :type '(repeat
2308 (cons (choice :value ""
2309 (string :tag "Extension")
2310 (const :tag "System command to open files" system)
2311 (const :tag "Default for unrecognized files" t)
2312 (const :tag "Remote file" remote)
2313 (const :tag "Links to a directory" directory)
2314 (const :tag "Any files that have Emacs modes"
2315 auto-mode))
2316 (choice :value ""
2317 (const :tag "Visit with Emacs" emacs)
2318 (const :tag "Use default" default)
2319 (const :tag "Use the system command" system)
2320 (string :tag "Command")
2321 (function :tag "Function")))))
2323 (defcustom org-doi-server-url "http://dx.doi.org/"
2324 "The URL of the DOI server."
2325 :type 'string
2326 :version "24.3"
2327 :group 'org-link-follow)
2329 (defgroup org-refile nil
2330 "Options concerning refiling entries in Org mode."
2331 :tag "Org Refile"
2332 :group 'org)
2334 (defcustom org-directory "~/org"
2335 "Directory with Org files.
2336 This is just a default location to look for Org files. There is no need
2337 at all to put your files into this directory. It is used in the
2338 following situations:
2340 1. When a capture template specifies a target file that is not an
2341 absolute path. The path will then be interpreted relative to
2342 `org-directory'
2343 2. When the value of variable `org-agenda-files' is a single file, any
2344 relative paths in this file will be taken as relative to
2345 `org-directory'."
2346 :group 'org-refile
2347 :group 'org-capture
2348 :type 'directory)
2350 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2351 "Default target for storing notes.
2352 Used as a fall back file for org-capture.el, for templates that
2353 do not specify a target file."
2354 :group 'org-refile
2355 :group 'org-capture
2356 :type 'file)
2358 (defcustom org-reverse-note-order nil
2359 "Non-nil means store new notes at the beginning of a file or entry.
2360 When nil, new notes will be filed to the end of a file or entry.
2361 This can also be a list with cons cells of regular expressions that
2362 are matched against file names, and values."
2363 :group 'org-capture
2364 :group 'org-refile
2365 :type '(choice
2366 (const :tag "Reverse always" t)
2367 (const :tag "Reverse never" nil)
2368 (repeat :tag "By file name regexp"
2369 (cons regexp boolean))))
2371 (defcustom org-log-refile nil
2372 "Information to record when a task is refiled.
2374 Possible values are:
2376 nil Don't add anything
2377 time Add a time stamp to the task
2378 note Prompt for a note and add it with template `org-log-note-headings'
2380 This option can also be set with on a per-file-basis with
2382 #+STARTUP: nologrefile
2383 #+STARTUP: logrefile
2384 #+STARTUP: lognoterefile
2386 You can have local logging settings for a subtree by setting the LOGGING
2387 property to one or more of these keywords.
2389 When bulk-refiling from the agenda, the value `note' is forbidden and
2390 will temporarily be changed to `time'."
2391 :group 'org-refile
2392 :group 'org-progress
2393 :version "24.1"
2394 :type '(choice
2395 (const :tag "No logging" nil)
2396 (const :tag "Record timestamp" time)
2397 (const :tag "Record timestamp with note." note)))
2399 (defcustom org-refile-targets nil
2400 "Targets for refiling entries with `\\[org-refile]'.
2401 This is a list of cons cells. Each cell contains:
2402 - a specification of the files to be considered, either a list of files,
2403 or a symbol whose function or variable value will be used to retrieve
2404 a file name or a list of file names. If you use `org-agenda-files' for
2405 that, all agenda files will be scanned for targets. Nil means consider
2406 headings in the current buffer.
2407 - A specification of how to find candidate refile targets. This may be
2408 any of:
2409 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2410 This tag has to be present in all target headlines, inheritance will
2411 not be considered.
2412 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2413 todo keyword.
2414 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2415 headlines that are refiling targets.
2416 - a cons cell (:level . N). Any headline of level N is considered a target.
2417 Note that, when `org-odd-levels-only' is set, level corresponds to
2418 order in hierarchy, not to the number of stars.
2419 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2420 Note that, when `org-odd-levels-only' is set, level corresponds to
2421 order in hierarchy, not to the number of stars.
2423 Each element of this list generates a set of possible targets.
2424 The union of these sets is presented (with completion) to
2425 the user by `org-refile'.
2427 You can set the variable `org-refile-target-verify-function' to a function
2428 to verify each headline found by the simple criteria above.
2430 When this variable is nil, all top-level headlines in the current buffer
2431 are used, equivalent to the value `((nil . (:level . 1))'."
2432 :group 'org-refile
2433 :type '(repeat
2434 (cons
2435 (choice :value org-agenda-files
2436 (const :tag "All agenda files" org-agenda-files)
2437 (const :tag "Current buffer" nil)
2438 (function) (variable) (file))
2439 (choice :tag "Identify target headline by"
2440 (cons :tag "Specific tag" (const :value :tag) (string))
2441 (cons :tag "TODO keyword" (const :value :todo) (string))
2442 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2443 (cons :tag "Level number" (const :value :level) (integer))
2444 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2446 (defcustom org-refile-target-verify-function nil
2447 "Function to verify if the headline at point should be a refile target.
2448 The function will be called without arguments, with point at the
2449 beginning of the headline. It should return t and leave point
2450 where it is if the headline is a valid target for refiling.
2452 If the target should not be selected, the function must return nil.
2453 In addition to this, it may move point to a place from where the search
2454 should be continued. For example, the function may decide that the entire
2455 subtree of the current entry should be excluded and move point to the end
2456 of the subtree."
2457 :group 'org-refile
2458 :type '(choice
2459 (const nil)
2460 (function)))
2462 (defcustom org-refile-use-cache nil
2463 "Non-nil means cache refile targets to speed up the process.
2464 \\<org-mode-map>\
2465 The cache for a particular file will be updated automatically when
2466 the buffer has been killed, or when any of the marker used for flagging
2467 refile targets no longer points at a live buffer.
2468 If you have added new entries to a buffer that might themselves be targets,
2469 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2470 if you find that easier, \
2471 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2472 \\[org-refile]'."
2473 :group 'org-refile
2474 :version "24.1"
2475 :type 'boolean)
2477 (defcustom org-refile-use-outline-path nil
2478 "Non-nil means provide refile targets as paths.
2479 So a level 3 headline will be available as level1/level2/level3.
2481 When the value is `file', also include the file name (without directory)
2482 into the path. In this case, you can also stop the completion after
2483 the file name, to get entries inserted as top level in the file.
2485 When `full-file-path', include the full file path.
2487 When `buffer-name', use the buffer name."
2488 :group 'org-refile
2489 :type '(choice
2490 (const :tag "Not" nil)
2491 (const :tag "Yes" t)
2492 (const :tag "Start with file name" file)
2493 (const :tag "Start with full file path" full-file-path)
2494 (const :tag "Start with buffer name" buffer-name)))
2496 (defcustom org-outline-path-complete-in-steps t
2497 "Non-nil means complete the outline path in hierarchical steps.
2498 When Org uses the refile interface to select an outline path (see
2499 `org-refile-use-outline-path'), the completion of the path can be
2500 done in a single go, or it can be done in steps down the headline
2501 hierarchy. Going in steps is probably the best if you do not use
2502 a special completion package like `ido' or `icicles'. However,
2503 when using these packages, going in one step can be very fast,
2504 while still showing the whole path to the entry."
2505 :group 'org-refile
2506 :type 'boolean)
2508 (defcustom org-refile-allow-creating-parent-nodes nil
2509 "Non-nil means allow the creation of new nodes as refile targets.
2510 New nodes are then created by adding \"/new node name\" to the completion
2511 of an existing node. When the value of this variable is `confirm',
2512 new node creation must be confirmed by the user (recommended).
2513 When nil, the completion must match an existing entry.
2515 Note that, if the new heading is not seen by the criteria
2516 listed in `org-refile-targets', multiple instances of the same
2517 heading would be created by trying again to file under the new
2518 heading."
2519 :group 'org-refile
2520 :type '(choice
2521 (const :tag "Never" nil)
2522 (const :tag "Always" t)
2523 (const :tag "Prompt for confirmation" confirm)))
2525 (defcustom org-refile-active-region-within-subtree nil
2526 "Non-nil means also refile active region within a subtree.
2528 By default `org-refile' doesn't allow refiling regions if they
2529 don't contain a set of subtrees, but it might be convenient to
2530 do so sometimes: in that case, the first line of the region is
2531 converted to a headline before refiling."
2532 :group 'org-refile
2533 :version "24.1"
2534 :type 'boolean)
2536 (defgroup org-todo nil
2537 "Options concerning TODO items in Org mode."
2538 :tag "Org TODO"
2539 :group 'org)
2541 (defgroup org-progress nil
2542 "Options concerning Progress logging in Org mode."
2543 :tag "Org Progress"
2544 :group 'org-time)
2546 (defvar org-todo-interpretation-widgets
2547 '((:tag "Sequence (cycling hits every state)" sequence)
2548 (:tag "Type (cycling directly to DONE)" type))
2549 "The available interpretation symbols for customizing `org-todo-keywords'.
2550 Interested libraries should add to this list.")
2552 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2553 "List of TODO entry keyword sequences and their interpretation.
2554 \\<org-mode-map>This is a list of sequences.
2556 Each sequence starts with a symbol, either `sequence' or `type',
2557 indicating if the keywords should be interpreted as a sequence of
2558 action steps, or as different types of TODO items. The first
2559 keywords are states requiring action - these states will select a headline
2560 for inclusion into the global TODO list Org produces. If one of the
2561 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2562 signify that no further action is necessary. If \"|\" is not found,
2563 the last keyword is treated as the only DONE state of the sequence.
2565 The command `\\[org-todo]' cycles an entry through these states, and one
2566 additional state where no keyword is present. For details about this
2567 cycling, see the manual.
2569 TODO keywords and interpretation can also be set on a per-file basis with
2570 the special #+SEQ_TODO and #+TYP_TODO lines.
2572 Each keyword can optionally specify a character for fast state selection
2573 \(in combination with the variable `org-use-fast-todo-selection')
2574 and specifiers for state change logging, using the same syntax that
2575 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2576 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2577 indicates to record a time stamp each time this state is selected.
2579 Each keyword may also specify if a timestamp or a note should be
2580 recorded when entering or leaving the state, by adding additional
2581 characters in the parenthesis after the keyword. This looks like this:
2582 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2583 record only the time of the state change. With X and Y being either
2584 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2585 Y when leaving the state if and only if the *target* state does not
2586 define X. You may omit any of the fast-selection key or X or /Y,
2587 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2589 For backward compatibility, this variable may also be just a list
2590 of keywords. In this case the interpretation (sequence or type) will be
2591 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2592 :group 'org-todo
2593 :group 'org-keywords
2594 :type '(choice
2595 (repeat :tag "Old syntax, just keywords"
2596 (string :tag "Keyword"))
2597 (repeat :tag "New syntax"
2598 (cons
2599 (choice
2600 :tag "Interpretation"
2601 ;;Quick and dirty way to see
2602 ;;`org-todo-interpretations'. This takes the
2603 ;;place of item arguments
2604 :convert-widget
2605 (lambda (widget)
2606 (widget-put widget
2607 :args (mapcar
2608 (lambda (x)
2609 (widget-convert
2610 (cons 'const x)))
2611 org-todo-interpretation-widgets))
2612 widget))
2613 (repeat
2614 (string :tag "Keyword"))))))
2616 (defvar-local org-todo-keywords-1 nil
2617 "All TODO and DONE keywords active in a buffer.")
2618 (defvar org-todo-keywords-for-agenda nil)
2619 (defvar org-done-keywords-for-agenda nil)
2620 (defvar org-todo-keyword-alist-for-agenda nil)
2621 (defvar org-tag-alist-for-agenda nil
2622 "Alist of all tags from all agenda files.")
2623 (defvar org-tag-groups-alist-for-agenda nil
2624 "Alist of all groups tags from all current agenda files.")
2625 (defvar-local org-tag-groups-alist nil)
2626 (defvar org-agenda-contributing-files nil)
2627 (defvar-local org-current-tag-alist nil
2628 "Alist of all tag groups in current buffer.
2629 This variable takes into consideration `org-tag-alist',
2630 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2631 (defvar-local org-not-done-keywords nil)
2632 (defvar-local org-done-keywords nil)
2633 (defvar-local org-todo-heads nil)
2634 (defvar-local org-todo-sets nil)
2635 (defvar-local org-todo-log-states nil)
2636 (defvar-local org-todo-kwd-alist nil)
2637 (defvar-local org-todo-key-alist nil)
2638 (defvar-local org-todo-key-trigger nil)
2640 (defcustom org-todo-interpretation 'sequence
2641 "Controls how TODO keywords are interpreted.
2642 This variable is in principle obsolete and is only used for
2643 backward compatibility, if the interpretation of todo keywords is
2644 not given already in `org-todo-keywords'. See that variable for
2645 more information."
2646 :group 'org-todo
2647 :group 'org-keywords
2648 :type '(choice (const sequence)
2649 (const type)))
2651 (defcustom org-use-fast-todo-selection t
2652 "\\<org-mode-map>\
2653 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2654 This variable describes if and under what circumstances the cycling
2655 mechanism for TODO keywords will be replaced by a single-key, direct
2656 selection scheme.
2658 When nil, fast selection is never used.
2660 When the symbol `prefix', it will be used when `org-todo' is called
2661 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2662 in an Org buffer, and
2663 `\\[universal-argument] t' in an agenda buffer.
2665 When t, fast selection is used by default. In this case, the prefix
2666 argument forces cycling instead.
2668 In all cases, the special interface is only used if access keys have
2669 actually been assigned by the user, i.e. if keywords in the configuration
2670 are followed by a letter in parenthesis, like TODO(t)."
2671 :group 'org-todo
2672 :type '(choice
2673 (const :tag "Never" nil)
2674 (const :tag "By default" t)
2675 (const :tag "Only with C-u C-c C-t" prefix)))
2677 (defcustom org-provide-todo-statistics t
2678 "Non-nil means update todo statistics after insert and toggle.
2679 ALL-HEADLINES means update todo statistics by including headlines
2680 with no TODO keyword as well, counting them as not done.
2681 A list of TODO keywords means the same, but skip keywords that are
2682 not in this list.
2683 When set to a list of two lists, the first list contains keywords
2684 to consider as TODO keywords, the second list contains keywords
2685 to consider as DONE keywords.
2687 When this is set, todo statistics is updated in the parent of the
2688 current entry each time a todo state is changed."
2689 :group 'org-todo
2690 :type '(choice
2691 (const :tag "Yes, only for TODO entries" t)
2692 (const :tag "Yes, including all entries" all-headlines)
2693 (repeat :tag "Yes, for TODOs in this list"
2694 (string :tag "TODO keyword"))
2695 (list :tag "Yes, for TODOs and DONEs in these lists"
2696 (repeat (string :tag "TODO keyword"))
2697 (repeat (string :tag "DONE keyword")))
2698 (other :tag "No TODO statistics" nil)))
2700 (defcustom org-hierarchical-todo-statistics t
2701 "Non-nil means TODO statistics covers just direct children.
2702 When nil, all entries in the subtree are considered.
2703 This has only an effect if `org-provide-todo-statistics' is set.
2704 To set this to nil for only a single subtree, use a COOKIE_DATA
2705 property and include the word \"recursive\" into the value."
2706 :group 'org-todo
2707 :type 'boolean)
2709 (defcustom org-after-todo-state-change-hook nil
2710 "Hook which is run after the state of a TODO item was changed.
2711 The new state (a string with a TODO keyword, or nil) is available in the
2712 Lisp variable `org-state'."
2713 :group 'org-todo
2714 :type 'hook)
2716 (defvar org-blocker-hook nil
2717 "Hook for functions that are allowed to block a state change.
2719 Functions in this hook should not modify the buffer.
2720 Each function gets as its single argument a property list,
2721 see `org-trigger-hook' for more information about this list.
2723 If any of the functions in this hook returns nil, the state change
2724 is blocked.")
2726 (defvar org-trigger-hook nil
2727 "Hook for functions that are triggered by a state change.
2729 Each function gets as its single argument a property list with at
2730 least the following elements:
2732 (:type type-of-change :position pos-at-entry-start
2733 :from old-state :to new-state)
2735 Depending on the type, more properties may be present.
2737 This mechanism is currently implemented for:
2739 TODO state changes
2740 ------------------
2741 :type todo-state-change
2742 :from previous state (keyword as a string), or nil, or a symbol
2743 `todo' or `done', to indicate the general type of state.
2744 :to new state, like in :from")
2746 (defcustom org-enforce-todo-dependencies nil
2747 "Non-nil means undone TODO entries will block switching the parent to DONE.
2748 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2749 be blocked if any prior sibling is not yet done.
2750 Finally, if the parent is blocked because of ordered siblings of its own,
2751 the child will also be blocked."
2752 :set (lambda (var val)
2753 (set var val)
2754 (if val
2755 (add-hook 'org-blocker-hook
2756 'org-block-todo-from-children-or-siblings-or-parent)
2757 (remove-hook 'org-blocker-hook
2758 'org-block-todo-from-children-or-siblings-or-parent)))
2759 :group 'org-todo
2760 :type 'boolean)
2762 (defcustom org-enforce-todo-checkbox-dependencies nil
2763 "Non-nil means unchecked boxes will block switching the parent to DONE.
2764 When this is nil, checkboxes have no influence on switching TODO states.
2765 When non-nil, you first need to check off all check boxes before the TODO
2766 entry can be switched to DONE.
2767 This variable needs to be set before org.el is loaded, and you need to
2768 restart Emacs after a change to make the change effective. The only way
2769 to change is while Emacs is running is through the customize interface."
2770 :set (lambda (var val)
2771 (set var val)
2772 (if val
2773 (add-hook 'org-blocker-hook
2774 'org-block-todo-from-checkboxes)
2775 (remove-hook 'org-blocker-hook
2776 'org-block-todo-from-checkboxes)))
2777 :group 'org-todo
2778 :type 'boolean)
2780 (defcustom org-treat-insert-todo-heading-as-state-change nil
2781 "Non-nil means inserting a TODO heading is treated as state change.
2782 So when the command `\\[org-insert-todo-heading]' is used, state change
2783 logging will apply if appropriate. When nil, the new TODO item will
2784 be inserted directly, and no logging will take place."
2785 :group 'org-todo
2786 :type 'boolean)
2788 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2789 "Non-nil means switching TODO states with S-cursor counts as state change.
2790 This is the default behavior. However, setting this to nil allows a
2791 convenient way to select a TODO state and bypass any logging associated
2792 with that."
2793 :group 'org-todo
2794 :type 'boolean)
2796 (defcustom org-todo-state-tags-triggers nil
2797 "Tag changes that should be triggered by TODO state changes.
2798 This is a list. Each entry is
2800 (state-change (tag . flag) .......)
2802 State-change can be a string with a state, and empty string to indicate the
2803 state that has no TODO keyword, or it can be one of the symbols `todo'
2804 or `done', meaning any not-done or done state, respectively."
2805 :group 'org-todo
2806 :group 'org-tags
2807 :type '(repeat
2808 (cons (choice :tag "When changing to"
2809 (const :tag "Not-done state" todo)
2810 (const :tag "Done state" done)
2811 (string :tag "State"))
2812 (repeat
2813 (cons :tag "Tag action"
2814 (string :tag "Tag")
2815 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2817 (defcustom org-log-done nil
2818 "Information to record when a task moves to the DONE state.
2820 Possible values are:
2822 nil Don't add anything, just change the keyword
2823 time Add a time stamp to the task
2824 note Prompt for a note and add it with template `org-log-note-headings'
2826 This option can also be set with on a per-file-basis with
2828 #+STARTUP: nologdone
2829 #+STARTUP: logdone
2830 #+STARTUP: lognotedone
2832 You can have local logging settings for a subtree by setting the LOGGING
2833 property to one or more of these keywords."
2834 :group 'org-todo
2835 :group 'org-progress
2836 :type '(choice
2837 (const :tag "No logging" nil)
2838 (const :tag "Record CLOSED timestamp" time)
2839 (const :tag "Record CLOSED timestamp with note." note)))
2841 ;; Normalize old uses of org-log-done.
2842 (cond
2843 ((eq org-log-done t) (setq org-log-done 'time))
2844 ((and (listp org-log-done) (memq 'done org-log-done))
2845 (setq org-log-done 'note)))
2847 (defcustom org-log-reschedule nil
2848 "Information to record when the scheduling date of a tasks is modified.
2850 Possible values are:
2852 nil Don't add anything, just change the date
2853 time Add a time stamp to the task
2854 note Prompt for a note and add it with template `org-log-note-headings'
2856 This option can also be set with on a per-file-basis with
2858 #+STARTUP: nologreschedule
2859 #+STARTUP: logreschedule
2860 #+STARTUP: lognotereschedule"
2861 :group 'org-todo
2862 :group 'org-progress
2863 :type '(choice
2864 (const :tag "No logging" nil)
2865 (const :tag "Record timestamp" time)
2866 (const :tag "Record timestamp with note." note)))
2868 (defcustom org-log-redeadline nil
2869 "Information to record when the deadline date of a tasks is modified.
2871 Possible values are:
2873 nil Don't add anything, just change the date
2874 time Add a time stamp to the task
2875 note Prompt for a note and add it with template `org-log-note-headings'
2877 This option can also be set with on a per-file-basis with
2879 #+STARTUP: nologredeadline
2880 #+STARTUP: logredeadline
2881 #+STARTUP: lognoteredeadline
2883 You can have local logging settings for a subtree by setting the LOGGING
2884 property to one or more of these keywords."
2885 :group 'org-todo
2886 :group 'org-progress
2887 :type '(choice
2888 (const :tag "No logging" nil)
2889 (const :tag "Record timestamp" time)
2890 (const :tag "Record timestamp with note." note)))
2892 (defcustom org-log-note-clock-out nil
2893 "Non-nil means record a note when clocking out of an item.
2894 This can also be configured on a per-file basis by adding one of
2895 the following lines anywhere in the buffer:
2897 #+STARTUP: lognoteclock-out
2898 #+STARTUP: nolognoteclock-out"
2899 :group 'org-todo
2900 :group 'org-progress
2901 :type 'boolean)
2903 (defcustom org-log-done-with-time t
2904 "Non-nil means the CLOSED time stamp will contain date and time.
2905 When nil, only the date will be recorded."
2906 :group 'org-progress
2907 :type 'boolean)
2909 (defcustom org-log-note-headings
2910 '((done . "CLOSING NOTE %t")
2911 (state . "State %-12s from %-12S %t")
2912 (note . "Note taken on %t")
2913 (reschedule . "Rescheduled from %S on %t")
2914 (delschedule . "Not scheduled, was %S on %t")
2915 (redeadline . "New deadline from %S on %t")
2916 (deldeadline . "Removed deadline, was %S on %t")
2917 (refile . "Refiled on %t")
2918 (clock-out . ""))
2919 "Headings for notes added to entries.
2921 The value is an alist, with the car being a symbol indicating the
2922 note context, and the cdr is the heading to be used. The heading
2923 may also be the empty string. The following placeholders can be
2924 used:
2926 %t a time stamp.
2927 %T an active time stamp instead the default inactive one
2928 %d a short-format time stamp.
2929 %D an active short-format time stamp.
2930 %s the new TODO state or time stamp (inactive), in double quotes.
2931 %S the old TODO state or time stamp (inactive), in double quotes.
2932 %u the user name.
2933 %U full user name.
2935 In fact, it is not a good idea to change the `state' entry,
2936 because Agenda Log mode depends on the format of these entries."
2937 :group 'org-todo
2938 :group 'org-progress
2939 :type '(list :greedy t
2940 (cons (const :tag "Heading when closing an item" done) string)
2941 (cons (const :tag
2942 "Heading when changing todo state (todo sequence only)"
2943 state) string)
2944 (cons (const :tag "Heading when just taking a note" note) string)
2945 (cons (const :tag "Heading when rescheduling" reschedule) string)
2946 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2947 (cons (const :tag "Heading when changing deadline" redeadline) string)
2948 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2949 (cons (const :tag "Heading when refiling" refile) string)
2950 (cons (const :tag "Heading when clocking out" clock-out) string)))
2952 (unless (assq 'note org-log-note-headings)
2953 (push '(note . "%t") org-log-note-headings))
2955 (defcustom org-log-into-drawer nil
2956 "Non-nil means insert state change notes and time stamps into a drawer.
2957 When nil, state changes notes will be inserted after the headline and
2958 any scheduling and clock lines, but not inside a drawer.
2960 The value of this variable should be the name of the drawer to use.
2961 LOGBOOK is proposed as the default drawer for this purpose, you can
2962 also set this to a string to define the drawer of your choice.
2964 A value of t is also allowed, representing \"LOGBOOK\".
2966 A value of t or nil can also be set with on a per-file-basis with
2968 #+STARTUP: logdrawer
2969 #+STARTUP: nologdrawer
2971 If this variable is set, `org-log-state-notes-insert-after-drawers'
2972 will be ignored.
2974 You can set the property LOG_INTO_DRAWER to overrule this setting for
2975 a subtree.
2977 Do not check directly this variable in a Lisp program. Call
2978 function `org-log-into-drawer' instead."
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type '(choice
2982 (const :tag "Not into a drawer" nil)
2983 (const :tag "LOGBOOK" t)
2984 (string :tag "Other")))
2986 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2988 (defun org-log-into-drawer ()
2989 "Name of the log drawer, as a string, or nil.
2990 This is the value of `org-log-into-drawer'. However, if the
2991 current entry has or inherits a LOG_INTO_DRAWER property, it will
2992 be used instead of the default value."
2993 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2994 (cond ((equal p "nil") nil)
2995 ((equal p "t") "LOGBOOK")
2996 ((stringp p) p)
2997 (p "LOGBOOK")
2998 ((stringp org-log-into-drawer) org-log-into-drawer)
2999 (org-log-into-drawer "LOGBOOK"))))
3001 (defcustom org-log-state-notes-insert-after-drawers nil
3002 "Non-nil means insert state change notes after any drawers in entry.
3003 Only the drawers that *immediately* follow the headline and the
3004 deadline/scheduled line are skipped.
3005 When nil, insert notes right after the heading and perhaps the line
3006 with deadline/scheduling if present.
3008 This variable will have no effect if `org-log-into-drawer' is
3009 set."
3010 :group 'org-todo
3011 :group 'org-progress
3012 :type 'boolean)
3014 (defcustom org-log-states-order-reversed t
3015 "Non-nil means the latest state note will be directly after heading.
3016 When nil, the state change notes will be ordered according to time.
3018 This option can also be set with on a per-file-basis with
3020 #+STARTUP: logstatesreversed
3021 #+STARTUP: nologstatesreversed"
3022 :group 'org-todo
3023 :group 'org-progress
3024 :type 'boolean)
3026 (defcustom org-todo-repeat-to-state nil
3027 "The TODO state to which a repeater should return the repeating task.
3028 By default this is the first task in a TODO sequence, or the previous state
3029 in a TODO_TYP set. But you can specify another task here.
3030 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3031 :group 'org-todo
3032 :version "24.1"
3033 :type '(choice (const :tag "Head of sequence" nil)
3034 (string :tag "Specific state")))
3036 (defcustom org-log-repeat 'time
3037 "Non-nil means record moving through the DONE state when triggering repeat.
3038 An auto-repeating task is immediately switched back to TODO when
3039 marked DONE. If you are not logging state changes (by adding \"@\"
3040 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3041 record a closing note, there will be no record of the task moving
3042 through DONE. This variable forces taking a note anyway.
3044 nil Don't force a record
3045 time Record a time stamp
3046 note Prompt for a note and add it with template `org-log-note-headings'
3048 This option can also be set with on a per-file-basis with
3050 #+STARTUP: nologrepeat
3051 #+STARTUP: logrepeat
3052 #+STARTUP: lognoterepeat
3054 You can have local logging settings for a subtree by setting the LOGGING
3055 property to one or more of these keywords."
3056 :group 'org-todo
3057 :group 'org-progress
3058 :type '(choice
3059 (const :tag "Don't force a record" nil)
3060 (const :tag "Force recording the DONE state" time)
3061 (const :tag "Force recording a note with the DONE state" note)))
3064 (defgroup org-priorities nil
3065 "Priorities in Org mode."
3066 :tag "Org Priorities"
3067 :group 'org-todo)
3069 (defcustom org-enable-priority-commands t
3070 "Non-nil means priority commands are active.
3071 When nil, these commands will be disabled, so that you never accidentally
3072 set a priority."
3073 :group 'org-priorities
3074 :type 'boolean)
3076 (defcustom org-highest-priority ?A
3077 "The highest priority of TODO items. A character like ?A, ?B etc.
3078 Must have a smaller ASCII number than `org-lowest-priority'."
3079 :group 'org-priorities
3080 :type 'character)
3082 (defcustom org-lowest-priority ?C
3083 "The lowest priority of TODO items. A character like ?A, ?B etc.
3084 Must have a larger ASCII number than `org-highest-priority'."
3085 :group 'org-priorities
3086 :type 'character)
3088 (defcustom org-default-priority ?B
3089 "The default priority of TODO items.
3090 This is the priority an item gets if no explicit priority is given.
3091 When starting to cycle on an empty priority the first step in the cycle
3092 depends on `org-priority-start-cycle-with-default'. The resulting first
3093 step priority must not exceed the range from `org-highest-priority' to
3094 `org-lowest-priority' which means that `org-default-priority' has to be
3095 in this range exclusive or inclusive the range boundaries. Else the
3096 first step refuses to set the default and the second will fall back
3097 to (depending on the command used) the highest or lowest priority."
3098 :group 'org-priorities
3099 :type 'character)
3101 (defcustom org-priority-start-cycle-with-default t
3102 "Non-nil means start with default priority when starting to cycle.
3103 When this is nil, the first step in the cycle will be (depending on the
3104 command used) one higher or lower than the default priority.
3105 See also `org-default-priority'."
3106 :group 'org-priorities
3107 :type 'boolean)
3109 (defcustom org-get-priority-function nil
3110 "Function to extract the priority from a string.
3111 The string is normally the headline. If this is nil Org computes the
3112 priority from the priority cookie like [#A] in the headline. It returns
3113 an integer, increasing by 1000 for each priority level.
3114 The user can set a different function here, which should take a string
3115 as an argument and return the numeric priority."
3116 :group 'org-priorities
3117 :version "24.1"
3118 :type '(choice
3119 (const nil)
3120 (function)))
3122 (defgroup org-time nil
3123 "Options concerning time stamps and deadlines in Org mode."
3124 :tag "Org Time"
3125 :group 'org)
3127 (defcustom org-time-stamp-rounding-minutes '(0 5)
3128 "Number of minutes to round time stamps to.
3129 \\<org-mode-map>\
3130 These are two values, the first applies when first creating a time stamp.
3131 The second applies when changing it with the commands `S-up' and `S-down'.
3132 When changing the time stamp, this means that it will change in steps
3133 of N minutes, as given by the second value.
3135 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3136 numbers should be factors of 60, so for example 5, 10, 15.
3138 When this is larger than 1, you can still force an exact time stamp by using
3139 a double prefix argument to a time stamp command like \
3140 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3141 and by using a prefix arg to `S-up/down' to specify the exact number
3142 of minutes to shift."
3143 :group 'org-time
3144 :get (lambda (var) ; Make sure both elements are there
3145 (if (integerp (default-value var))
3146 (list (default-value var) 5)
3147 (default-value var)))
3148 :type '(list
3149 (integer :tag "when inserting times")
3150 (integer :tag "when modifying times")))
3152 ;; Normalize old customizations of this variable.
3153 (when (integerp org-time-stamp-rounding-minutes)
3154 (setq org-time-stamp-rounding-minutes
3155 (list org-time-stamp-rounding-minutes
3156 org-time-stamp-rounding-minutes)))
3158 (defcustom org-display-custom-times nil
3159 "Non-nil means overlay custom formats over all time stamps.
3160 The formats are defined through the variable `org-time-stamp-custom-formats'.
3161 To turn this on on a per-file basis, insert anywhere in the file:
3162 #+STARTUP: customtime"
3163 :group 'org-time
3164 :set 'set-default
3165 :type 'sexp)
3166 (make-variable-buffer-local 'org-display-custom-times)
3168 (defcustom org-time-stamp-custom-formats
3169 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3170 "Custom formats for time stamps. See `format-time-string' for the syntax.
3171 These are overlaid over the default ISO format if the variable
3172 `org-display-custom-times' is set. Time like %H:%M should be at the
3173 end of the second format. The custom formats are also honored by export
3174 commands, if custom time display is turned on at the time of export."
3175 :group 'org-time
3176 :type 'sexp)
3178 (defun org-time-stamp-format (&optional long inactive)
3179 "Get the right format for a time string."
3180 (let ((f (if long (cdr org-time-stamp-formats)
3181 (car org-time-stamp-formats))))
3182 (if inactive
3183 (concat "[" (substring f 1 -1) "]")
3184 f)))
3186 (defcustom org-deadline-warning-days 14
3187 "Number of days before expiration during which a deadline becomes active.
3188 This variable governs the display in sparse trees and in the agenda.
3189 When 0 or negative, it means use this number (the absolute value of it)
3190 even if a deadline has a different individual lead time specified.
3192 Custom commands can set this variable in the options section."
3193 :group 'org-time
3194 :group 'org-agenda-daily/weekly
3195 :type 'integer)
3197 (defcustom org-scheduled-delay-days 0
3198 "Number of days before a scheduled item becomes active.
3199 This variable governs the display in sparse trees and in the agenda.
3200 The default value (i.e. 0) means: don't delay scheduled item.
3201 When negative, it means use this number (the absolute value of it)
3202 even if a scheduled item has a different individual delay time
3203 specified.
3205 Custom commands can set this variable in the options section."
3206 :group 'org-time
3207 :group 'org-agenda-daily/weekly
3208 :version "24.4"
3209 :package-version '(Org . "8.0")
3210 :type 'integer)
3212 (defcustom org-read-date-prefer-future t
3213 "Non-nil means assume future for incomplete date input from user.
3214 This affects the following situations:
3215 1. The user gives a month but not a year.
3216 For example, if it is April and you enter \"feb 2\", this will be read
3217 as Feb 2, *next* year. \"May 5\", however, will be this year.
3218 2. The user gives a day, but no month.
3219 For example, if today is the 15th, and you enter \"3\", Org will read
3220 this as the third of *next* month. However, if you enter \"17\",
3221 it will be considered as *this* month.
3223 If you set this variable to the symbol `time', then also the following
3224 will work:
3226 3. If the user gives a time.
3227 If the time is before now, it will be interpreted as tomorrow.
3229 Currently none of this works for ISO week specifications.
3231 When this option is nil, the current day, month and year will always be
3232 used as defaults.
3234 See also `org-agenda-jump-prefer-future'."
3235 :group 'org-time
3236 :type '(choice
3237 (const :tag "Never" nil)
3238 (const :tag "Check month and day" t)
3239 (const :tag "Check month, day, and time" time)))
3241 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3242 "Should the agenda jump command prefer the future for incomplete dates?
3243 The default is to do the same as configured in `org-read-date-prefer-future'.
3244 But you can also set a deviating value here.
3245 This may t or nil, or the symbol `org-read-date-prefer-future'."
3246 :group 'org-agenda
3247 :group 'org-time
3248 :version "24.1"
3249 :type '(choice
3250 (const :tag "Use org-read-date-prefer-future"
3251 org-read-date-prefer-future)
3252 (const :tag "Never" nil)
3253 (const :tag "Always" t)))
3255 (defcustom org-read-date-force-compatible-dates t
3256 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3258 Depending on the system Emacs is running on, certain dates cannot
3259 be represented with the type used internally to represent time.
3260 Dates between 1970-1-1 and 2038-1-1 can always be represented
3261 correctly. Some systems allow for earlier dates, some for later,
3262 some for both. One way to find out it to insert any date into an
3263 Org buffer, putting the cursor on the year and hitting S-up and
3264 S-down to test the range.
3266 When this variable is set to t, the date/time prompt will not let
3267 you specify dates outside the 1970-2037 range, so it is certain that
3268 these dates will work in whatever version of Emacs you are
3269 running, and also that you can move a file from one Emacs implementation
3270 to another. WHenever Org is forcing the year for you, it will display
3271 a message and beep.
3273 When this variable is nil, Org will check if the date is
3274 representable in the specific Emacs implementation you are using.
3275 If not, it will force a year, usually the current year, and beep
3276 to remind you. Currently this setting is not recommended because
3277 the likelihood that you will open your Org files in an Emacs that
3278 has limited date range is not negligible.
3280 A workaround for this problem is to use diary sexp dates for time
3281 stamps outside of this range."
3282 :group 'org-time
3283 :version "24.1"
3284 :type 'boolean)
3286 (defcustom org-read-date-display-live t
3287 "Non-nil means display current interpretation of date prompt live.
3288 This display will be in an overlay, in the minibuffer."
3289 :group 'org-time
3290 :type 'boolean)
3292 (defcustom org-read-date-popup-calendar t
3293 "Non-nil means pop up a calendar when prompting for a date.
3294 In the calendar, the date can be selected with mouse-1. However, the
3295 minibuffer will also be active, and you can simply enter the date as well.
3296 When nil, only the minibuffer will be available."
3297 :group 'org-time
3298 :type 'boolean)
3299 (defvaralias 'org-popup-calendar-for-date-prompt
3300 'org-read-date-popup-calendar)
3302 (defcustom org-extend-today-until 0
3303 "The hour when your day really ends. Must be an integer.
3304 This has influence for the following applications:
3305 - When switching the agenda to \"today\". It it is still earlier than
3306 the time given here, the day recognized as TODAY is actually yesterday.
3307 - When a date is read from the user and it is still before the time given
3308 here, the current date and time will be assumed to be yesterday, 23:59.
3309 Also, timestamps inserted in capture templates follow this rule.
3311 IMPORTANT: This is a feature whose implementation is and likely will
3312 remain incomplete. Really, it is only here because past midnight seems to
3313 be the favorite working time of John Wiegley :-)"
3314 :group 'org-time
3315 :type 'integer)
3317 (defcustom org-use-effective-time nil
3318 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3319 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3320 \"effective time\" of any timestamps between midnight and 8am will be
3321 23:59 of the previous day."
3322 :group 'org-time
3323 :version "24.1"
3324 :type 'boolean)
3326 (defcustom org-use-last-clock-out-time-as-effective-time nil
3327 "When non-nil, use the last clock out time for `org-todo'.
3328 Note that this option has precedence over the combined use of
3329 `org-use-effective-time' and `org-extend-today-until'."
3330 :group 'org-time
3331 :version "24.4"
3332 :package-version '(Org . "8.0")
3333 :type 'boolean)
3335 (defcustom org-edit-timestamp-down-means-later nil
3336 "Non-nil means S-down will increase the time in a time stamp.
3337 When nil, S-up will increase."
3338 :group 'org-time
3339 :type 'boolean)
3341 (defcustom org-calendar-follow-timestamp-change t
3342 "Non-nil means make the calendar window follow timestamp changes.
3343 When a timestamp is modified and the calendar window is visible, it will be
3344 moved to the new date."
3345 :group 'org-time
3346 :type 'boolean)
3348 (defgroup org-tags nil
3349 "Options concerning tags in Org mode."
3350 :tag "Org Tags"
3351 :group 'org)
3353 (defcustom org-tag-alist nil
3354 "Default tags available in Org files.
3356 The value of this variable is an alist. Associations either:
3358 (TAG)
3359 (TAG . SELECT)
3360 (SPECIAL)
3362 where TAG is a tag as a string, SELECT is character, used to
3363 select that tag through the fast tag selection interface, and
3364 SPECIAL is one of the following keywords: `:startgroup',
3365 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3366 `:newline'. These keywords are used to define a hierarchy of
3367 tags. See manual for details.
3369 When this variable is nil, Org mode bases tag input on what is
3370 already in the buffer. The value can be overridden locally by
3371 using a TAGS keyword, e.g.,
3373 #+TAGS: tag1 tag2
3375 See also `org-tag-persistent-alist' to sidestep this behavior."
3376 :group 'org-tags
3377 :type '(repeat
3378 (choice
3379 (cons :tag "Tag with key"
3380 (string :tag "Tag name")
3381 (character :tag "Access char"))
3382 (list :tag "Tag" (string :tag "Tag name"))
3383 (const :tag "Start radio group" (:startgroup))
3384 (const :tag "Start tag group, non distinct" (:startgrouptag))
3385 (const :tag "Group tags delimiter" (:grouptags))
3386 (const :tag "End radio group" (:endgroup))
3387 (const :tag "End tag group, non distinct" (:endgrouptag))
3388 (const :tag "New line" (:newline)))))
3390 (defcustom org-tag-persistent-alist nil
3391 "Tags always available in Org files.
3393 The value of this variable is an alist. Associations either:
3395 (TAG)
3396 (TAG . SELECT)
3397 (SPECIAL)
3399 where TAG is a tag as a string, SELECT is a character, used to
3400 select that tag through the fast tag selection interface, and
3401 SPECIAL is one of the following keywords: `:startgroup',
3402 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3403 `:newline'. These keywords are used to define a hierarchy of
3404 tags. See manual for details.
3406 Unlike to `org-tag-alist', tags defined in this variable do not
3407 depend on a local TAGS keyword. Instead, to disable these tags
3408 on a per-file basis, insert anywhere in the file:
3410 #+STARTUP: noptag"
3411 :group 'org-tags
3412 :type '(repeat
3413 (choice
3414 (cons :tag "Tag with key"
3415 (string :tag "Tag name")
3416 (character :tag "Access char"))
3417 (list :tag "Tag" (string :tag "Tag name"))
3418 (const :tag "Start radio group" (:startgroup))
3419 (const :tag "Start tag group, non distinct" (:startgrouptag))
3420 (const :tag "Group tags delimiter" (:grouptags))
3421 (const :tag "End radio group" (:endgroup))
3422 (const :tag "End tag group, non distinct" (:endgrouptag))
3423 (const :tag "New line" (:newline)))))
3425 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3426 "If non-nil, always offer completion for all tags of all agenda files.
3427 Instead of customizing this variable directly, you might want to
3428 set it locally for capture buffers, because there no list of
3429 tags in that file can be created dynamically (there are none).
3431 (add-hook \\='org-capture-mode-hook
3432 (lambda ()
3433 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3434 :group 'org-tags
3435 :version "24.1"
3436 :type 'boolean)
3438 (defvar org-file-tags nil
3439 "List of tags that can be inherited by all entries in the file.
3440 The tags will be inherited if the variable `org-use-tag-inheritance'
3441 says they should be.
3442 This variable is populated from #+FILETAGS lines.")
3444 (defcustom org-use-fast-tag-selection 'auto
3445 "Non-nil means use fast tag selection scheme.
3446 This is a special interface to select and deselect tags with single keys.
3447 When nil, fast selection is never used.
3448 When the symbol `auto', fast selection is used if and only if selection
3449 characters for tags have been configured, either through the variable
3450 `org-tag-alist' or through a #+TAGS line in the buffer.
3451 When t, fast selection is always used and selection keys are assigned
3452 automatically if necessary."
3453 :group 'org-tags
3454 :type '(choice
3455 (const :tag "Always" t)
3456 (const :tag "Never" nil)
3457 (const :tag "When selection characters are configured" auto)))
3459 (defcustom org-fast-tag-selection-single-key nil
3460 "Non-nil means fast tag selection exits after first change.
3461 When nil, you have to press RET to exit it.
3462 During fast tag selection, you can toggle this flag with `C-c'.
3463 This variable can also have the value `expert'. In this case, the window
3464 displaying the tags menu is not even shown, until you press C-c again."
3465 :group 'org-tags
3466 :type '(choice
3467 (const :tag "No" nil)
3468 (const :tag "Yes" t)
3469 (const :tag "Expert" expert)))
3471 (defvar org-fast-tag-selection-include-todo nil
3472 "Non-nil means fast tags selection interface will also offer TODO states.
3473 This is an undocumented feature, you should not rely on it.")
3475 (defcustom org-tags-column -77
3476 "The column to which tags should be indented in a headline.
3477 If this number is positive, it specifies the column. If it is negative,
3478 it means that the tags should be flushright to that column. For example,
3479 -80 works well for a normal 80 character screen.
3480 When 0, place tags directly after headline text, with only one space in
3481 between."
3482 :group 'org-tags
3483 :type 'integer)
3485 (defcustom org-auto-align-tags t
3486 "Non-nil keeps tags aligned when modifying headlines.
3487 Some operations (i.e. demoting) change the length of a headline and
3488 therefore shift the tags around. With this option turned on, after
3489 each such operation the tags are again aligned to `org-tags-column'."
3490 :group 'org-tags
3491 :type 'boolean)
3493 (defcustom org-use-tag-inheritance t
3494 "Non-nil means tags in levels apply also for sublevels.
3495 When nil, only the tags directly given in a specific line apply there.
3496 This may also be a list of tags that should be inherited, or a regexp that
3497 matches tags that should be inherited. Additional control is possible
3498 with the variable `org-tags-exclude-from-inheritance' which gives an
3499 explicit list of tags to be excluded from inheritance, even if the value of
3500 `org-use-tag-inheritance' would select it for inheritance.
3502 If this option is t, a match early-on in a tree can lead to a large
3503 number of matches in the subtree when constructing the agenda or creating
3504 a sparse tree. If you only want to see the first match in a tree during
3505 a search, check out the variable `org-tags-match-list-sublevels'."
3506 :group 'org-tags
3507 :type '(choice
3508 (const :tag "Not" nil)
3509 (const :tag "Always" t)
3510 (repeat :tag "Specific tags" (string :tag "Tag"))
3511 (regexp :tag "Tags matched by regexp")))
3513 (defcustom org-tags-exclude-from-inheritance nil
3514 "List of tags that should never be inherited.
3515 This is a way to exclude a few tags from inheritance. For way to do
3516 the opposite, to actively allow inheritance for selected tags,
3517 see the variable `org-use-tag-inheritance'."
3518 :group 'org-tags
3519 :type '(repeat (string :tag "Tag")))
3521 (defun org-tag-inherit-p (tag)
3522 "Check if TAG is one that should be inherited."
3523 (cond
3524 ((member tag org-tags-exclude-from-inheritance) nil)
3525 ((eq org-use-tag-inheritance t) t)
3526 ((not org-use-tag-inheritance) nil)
3527 ((stringp org-use-tag-inheritance)
3528 (string-match org-use-tag-inheritance tag))
3529 ((listp org-use-tag-inheritance)
3530 (member tag org-use-tag-inheritance))
3531 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3533 (defcustom org-tags-match-list-sublevels t
3534 "Non-nil means list also sublevels of headlines matching a search.
3535 This variable applies to tags/property searches, and also to stuck
3536 projects because this search is based on a tags match as well.
3538 When set to the symbol `indented', sublevels are indented with
3539 leading dots.
3541 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3542 the sublevels of a headline matching a tag search often also match
3543 the same search. Listing all of them can create very long lists.
3544 Setting this variable to nil causes subtrees of a match to be skipped.
3546 This variable is semi-obsolete and probably should always be true. It
3547 is better to limit inheritance to certain tags using the variables
3548 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "No, don't list them" nil)
3552 (const :tag "Yes, do list them" t)
3553 (const :tag "List them, indented with leading dots" indented)))
3555 (defcustom org-tags-sort-function nil
3556 "When set, tags are sorted using this function as a comparator."
3557 :group 'org-tags
3558 :type '(choice
3559 (const :tag "No sorting" nil)
3560 (const :tag "Alphabetical" string<)
3561 (const :tag "Reverse alphabetical" string>)
3562 (function :tag "Custom function" nil)))
3564 (defvar org-tags-history nil
3565 "History of minibuffer reads for tags.")
3566 (defvar org-last-tags-completion-table nil
3567 "The last used completion table for tags.")
3568 (defvar org-after-tags-change-hook nil
3569 "Hook that is run after the tags in a line have changed.")
3571 (defgroup org-properties nil
3572 "Options concerning properties in Org mode."
3573 :tag "Org Properties"
3574 :group 'org)
3576 (defcustom org-property-format "%-10s %s"
3577 "How property key/value pairs should be formatted by `indent-line'.
3578 When `indent-line' hits a property definition, it will format the line
3579 according to this format, mainly to make sure that the values are
3580 lined-up with respect to each other."
3581 :group 'org-properties
3582 :type 'string)
3584 (defcustom org-properties-postprocess-alist nil
3585 "Alist of properties and functions to adjust inserted values.
3586 Elements of this alist must be of the form
3588 ([string] [function])
3590 where [string] must be a property name and [function] must be a
3591 lambda expression: this lambda expression must take one argument,
3592 the value to adjust, and return the new value as a string.
3594 For example, this element will allow the property \"Remaining\"
3595 to be updated wrt the relation between the \"Effort\" property
3596 and the clock summary:
3598 ((\"Remaining\" (lambda(value)
3599 (let ((clocksum (org-clock-sum-current-item))
3600 (effort (org-duration-to-minutes
3601 (org-entry-get (point) \"Effort\"))))
3602 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3603 :group 'org-properties
3604 :version "24.1"
3605 :type '(alist :key-type (string :tag "Property")
3606 :value-type (function :tag "Function")))
3608 (defcustom org-use-property-inheritance nil
3609 "Non-nil means properties apply also for sublevels.
3611 This setting is chiefly used during property searches. Turning it on can
3612 cause significant overhead when doing a search, which is why it is not
3613 on by default.
3615 When nil, only the properties directly given in the current entry count.
3616 When t, every property is inherited. The value may also be a list of
3617 properties that should have inheritance, or a regular expression matching
3618 properties that should be inherited.
3620 However, note that some special properties use inheritance under special
3621 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3622 and the properties ending in \"_ALL\" when they are used as descriptor
3623 for valid values of a property.
3625 Note for programmers:
3626 When querying an entry with `org-entry-get', you can control if inheritance
3627 should be used. By default, `org-entry-get' looks only at the local
3628 properties. You can request inheritance by setting the inherit argument
3629 to t (to force inheritance) or to `selective' (to respect the setting
3630 in this variable)."
3631 :group 'org-properties
3632 :type '(choice
3633 (const :tag "Not" nil)
3634 (const :tag "Always" t)
3635 (repeat :tag "Specific properties" (string :tag "Property"))
3636 (regexp :tag "Properties matched by regexp")))
3638 (defun org-property-inherit-p (property)
3639 "Return a non-nil value if PROPERTY should be inherited."
3640 (cond
3641 ((eq org-use-property-inheritance t) t)
3642 ((not org-use-property-inheritance) nil)
3643 ((stringp org-use-property-inheritance)
3644 (string-match org-use-property-inheritance property))
3645 ((listp org-use-property-inheritance)
3646 (member-ignore-case property org-use-property-inheritance))
3647 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3649 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3650 "The default column format, if no other format has been defined.
3651 This variable can be set on the per-file basis by inserting a line
3653 #+COLUMNS: %25ITEM ....."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-columns-ellipses ".."
3658 "The ellipses to be used when a field in column view is truncated.
3659 When this is the empty string, as many characters as possible are shown,
3660 but then there will be no visual indication that the field has been truncated.
3661 When this is a string of length N, the last N characters of a truncated
3662 field are replaced by this string. If the column is narrower than the
3663 ellipses string, only part of the ellipses string will be shown."
3664 :group 'org-properties
3665 :type 'string)
3667 (defconst org-global-properties-fixed
3668 '(("VISIBILITY_ALL" . "folded children content all")
3669 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3670 "List of property/value pairs that can be inherited by any entry.
3672 These are fixed values, for the preset properties. The user variable
3673 that can be used to add to this list is `org-global-properties'.
3675 The entries in this list are cons cells where the car is a property
3676 name and cdr is a string with the value. If the value represents
3677 multiple items like an \"_ALL\" property, separate the items by
3678 spaces.")
3680 (defcustom org-global-properties nil
3681 "List of property/value pairs that can be inherited by any entry.
3683 This list will be combined with the constant `org-global-properties-fixed'.
3685 The entries in this list are cons cells where the car is a property
3686 name and cdr is a string with the value.
3688 You can set buffer-local values for the same purpose in the variable
3689 `org-file-properties' this by adding lines like
3691 #+PROPERTY: NAME VALUE"
3692 :group 'org-properties
3693 :type '(repeat
3694 (cons (string :tag "Property")
3695 (string :tag "Value"))))
3697 (defvar-local org-file-properties nil
3698 "List of property/value pairs that can be inherited by any entry.
3699 Valid for the current buffer.
3700 This variable is populated from #+PROPERTY lines.")
3702 (defgroup org-agenda nil
3703 "Options concerning agenda views in Org mode."
3704 :tag "Org Agenda"
3705 :group 'org)
3707 (defvar-local org-category nil
3708 "Variable used by org files to set a category for agenda display.
3709 Such files should use a file variable to set it, for example
3711 # -*- mode: org; org-category: \"ELisp\"
3713 or contain a special line
3715 #+CATEGORY: ELisp
3717 If the file does not specify a category, then file's base name
3718 is used instead.")
3719 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3721 (defcustom org-agenda-files nil
3722 "The files to be used for agenda display.
3724 If an entry is a directory, all files in that directory that are matched
3725 by `org-agenda-file-regexp' will be part of the file list.
3727 If the value of the variable is not a list but a single file name, then
3728 the list of agenda files is actually stored and maintained in that file,
3729 one agenda file per line. In this file paths can be given relative to
3730 `org-directory'. Tilde expansion and environment variable substitution
3731 are also made.
3733 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3734 and removed with `\\[org-remove-file]'."
3735 :group 'org-agenda
3736 :type '(choice
3737 (repeat :tag "List of files and directories" file)
3738 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3740 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3741 "Regular expression to match files for `org-agenda-files'.
3742 If any element in the list in that variable contains a directory instead
3743 of a normal file, all files in that directory that are matched by this
3744 regular expression will be included."
3745 :group 'org-agenda
3746 :type 'regexp)
3748 (defcustom org-agenda-text-search-extra-files nil
3749 "List of extra files to be searched by text search commands.
3750 These files will be searched in addition to the agenda files by the
3751 commands `org-search-view' (`\\[org-agenda] s') \
3752 and `org-occur-in-agenda-files'.
3753 Note that these files will only be searched for text search commands,
3754 not for the other agenda views like todo lists, tag searches or the weekly
3755 agenda. This variable is intended to list notes and possibly archive files
3756 that should also be searched by these two commands.
3757 In fact, if the first element in the list is the symbol `agenda-archives',
3758 then all archive files of all agenda files will be added to the search
3759 scope."
3760 :group 'org-agenda
3761 :type '(set :greedy t
3762 (const :tag "Agenda Archives" agenda-archives)
3763 (repeat :inline t (file))))
3765 (defvaralias 'org-agenda-multi-occur-extra-files
3766 'org-agenda-text-search-extra-files)
3768 (defcustom org-agenda-skip-unavailable-files nil
3769 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3770 A nil value means to remove them, after a query, from the list."
3771 :group 'org-agenda
3772 :type 'boolean)
3774 (defcustom org-calendar-to-agenda-key [?c]
3775 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3776 The command `org-calendar-goto-agenda' will be bound to this key. The
3777 default is the character `c' because then `c' can be used to switch back and
3778 forth between agenda and calendar."
3779 :group 'org-agenda
3780 :type 'sexp)
3782 (defcustom org-calendar-insert-diary-entry-key [?i]
3783 "The key to be installed in `calendar-mode-map' for adding diary entries.
3784 This option is irrelevant until `org-agenda-diary-file' has been configured
3785 to point to an Org file. When that is the case, the command
3786 `org-agenda-diary-entry' will be bound to the key given here, by default
3787 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3788 if you want to continue doing this, you need to change this to a different
3789 key."
3790 :group 'org-agenda
3791 :type 'sexp)
3793 (defcustom org-agenda-diary-file 'diary-file
3794 "File to which to add new entries with the `i' key in agenda and calendar.
3795 When this is the symbol `diary-file', the functionality in the Emacs
3796 calendar will be used to add entries to the `diary-file'. But when this
3797 points to a file, `org-agenda-diary-entry' will be used instead."
3798 :group 'org-agenda
3799 :type '(choice
3800 (const :tag "The standard Emacs diary file" diary-file)
3801 (file :tag "Special Org file diary entries")))
3803 (eval-after-load "calendar"
3804 '(progn
3805 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3806 'org-calendar-goto-agenda)
3807 (add-hook 'calendar-mode-hook
3808 (lambda ()
3809 (unless (eq org-agenda-diary-file 'diary-file)
3810 (define-key calendar-mode-map
3811 org-calendar-insert-diary-entry-key
3812 'org-agenda-diary-entry))))))
3814 (defgroup org-latex nil
3815 "Options for embedding LaTeX code into Org mode."
3816 :tag "Org LaTeX"
3817 :group 'org)
3819 (defcustom org-format-latex-options
3820 '(:foreground default :background default :scale 1.0
3821 :html-foreground "Black" :html-background "Transparent"
3822 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3823 "Options for creating images from LaTeX fragments.
3824 This is a property list with the following properties:
3825 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3826 `default' means use the foreground of the default face.
3827 `auto' means use the foreground from the text face.
3828 :background the background color, or \"Transparent\".
3829 `default' means use the background of the default face.
3830 `auto' means use the background from the text face.
3831 :scale a scaling factor for the size of the images, to get more pixels
3832 :html-foreground, :html-background, :html-scale
3833 the same numbers for HTML export.
3834 :matchers a list indicating which matchers should be used to
3835 find LaTeX fragments. Valid members of this list are:
3836 \"begin\" find environments
3837 \"$1\" find single characters surrounded by $.$
3838 \"$\" find math expressions surrounded by $...$
3839 \"$$\" find math expressions surrounded by $$....$$
3840 \"\\(\" find math expressions surrounded by \\(...\\)
3841 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3842 :group 'org-latex
3843 :type 'plist)
3845 (defcustom org-format-latex-signal-error t
3846 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3847 When nil, just push out a message."
3848 :group 'org-latex
3849 :version "24.1"
3850 :type 'boolean)
3852 (defcustom org-latex-to-mathml-jar-file nil
3853 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3854 Use this to specify additional executable file say a jar file.
3856 When using MathToWeb as the converter, specify the full-path to
3857 your mathtoweb.jar file."
3858 :group 'org-latex
3859 :version "24.1"
3860 :type '(choice
3861 (const :tag "None" nil)
3862 (file :tag "JAR file" :must-match t)))
3864 (defcustom org-latex-to-mathml-convert-command nil
3865 "Command to convert LaTeX fragments to MathML.
3866 Replace format-specifiers in the command as noted below and use
3867 `shell-command' to convert LaTeX to MathML.
3868 %j: Executable file in fully expanded form as specified by
3869 `org-latex-to-mathml-jar-file'.
3870 %I: Input LaTeX file in fully expanded form.
3871 %i: The latex fragment to be converted.
3872 %o: Output MathML file.
3874 This command is used by `org-create-math-formula'.
3876 When using MathToWeb as the converter, set this option to
3877 \"java -jar %j -unicode -force -df %o %I\".
3879 When using LaTeXML set this option to
3880 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3881 :group 'org-latex
3882 :version "24.1"
3883 :type '(choice
3884 (const :tag "None" nil)
3885 (string :tag "\nShell command")))
3887 (defcustom org-preview-latex-default-process 'dvipng
3888 "The default process to convert LaTeX fragments to image files.
3889 All available processes and theirs documents can be found in
3890 `org-preview-latex-process-alist', which see."
3891 :group 'org-latex
3892 :version "26.1"
3893 :package-version '(Org . "9.0")
3894 :type 'symbol)
3896 (defcustom org-preview-latex-process-alist
3897 '((dvipng
3898 :programs ("latex" "dvipng")
3899 :description "dvi > png"
3900 :message "you need to install the programs: latex and dvipng."
3901 :image-input-type "dvi"
3902 :image-output-type "png"
3903 :image-size-adjust (1.0 . 1.0)
3904 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3905 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3906 (dvisvgm
3907 :programs ("latex" "dvisvgm")
3908 :description "dvi > svg"
3909 :message "you need to install the programs: latex and dvisvgm."
3910 :use-xcolor t
3911 :image-input-type "dvi"
3912 :image-output-type "svg"
3913 :image-size-adjust (1.7 . 1.5)
3914 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3915 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3916 (imagemagick
3917 :programs ("latex" "convert")
3918 :description "pdf > png"
3919 :message "you need to install the programs: latex and imagemagick."
3920 :use-xcolor t
3921 :image-input-type "pdf"
3922 :image-output-type "png"
3923 :image-size-adjust (1.0 . 1.0)
3924 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3925 :image-converter
3926 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3927 "Definitions of external processes for LaTeX previewing.
3928 Org mode can use some external commands to generate TeX snippet's images for
3929 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3930 `org-create-formula-image' how to call them.
3932 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3933 PROPERTIES accepts the following attributes:
3935 :programs list of strings, required programs.
3936 :description string, describe the process.
3937 :message string, message it when required programs cannot be found.
3938 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3939 :image-output-type string, output file type of image converter (e.g., \"png\").
3940 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3941 deal with background and foreground color of image.
3942 Otherwise, dvipng style background and foreground color
3943 format are generated. You may then refer to them in
3944 command options with \"%F\" and \"%B\".
3945 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3946 image size showed in buffer and the cdr element is for
3947 HTML file. This option is only useful for process
3948 developers, users should use variable
3949 `org-format-latex-options' instead.
3950 :post-clean list of strings, files matched are to be cleaned up once
3951 the image is generated. When nil, the files with \".dvi\",
3952 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3953 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3954 be cleaned up.
3955 :latex-header list of strings, the LaTeX header of the snippet file.
3956 When nil, the fallback value is used instead, which is
3957 controlled by `org-format-latex-header',
3958 `org-latex-default-packages-alist' and
3959 `org-latex-packages-alist', which see.
3960 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3961 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3962 replaced with values defined below.
3963 :image-converter list of image converter commands strings. Each of them is
3964 given to the shell and supports any of the following
3965 place-holders defined below.
3967 Place-holders used by `:image-converter' and `:latex-compiler':
3969 %f input file name
3970 %b base name of input file
3971 %o base directory of input file
3972 %O absolute output file name
3974 Place-holders only used by `:image-converter':
3976 %F foreground of image
3977 %B background of image
3978 %D dpi, which is used to adjust image size by some processing commands.
3979 %S the image size scale ratio, which is used to adjust image size by some
3980 processing commands."
3981 :group 'org-latex
3982 :version "26.1"
3983 :package-version '(Org . "9.0")
3984 :type '(alist :tag "LaTeX to image backends"
3985 :value-type (plist)))
3987 (defcustom org-preview-latex-image-directory "ltximg/"
3988 "Path to store latex preview images.
3989 A relative path here creates many directories relative to the
3990 processed org files paths. An absolute path puts all preview
3991 images at the same place."
3992 :group 'org-latex
3993 :version "26.1"
3994 :package-version '(Org . "9.0")
3995 :type 'string)
3997 (defun org-format-latex-mathml-available-p ()
3998 "Return t if `org-latex-to-mathml-convert-command' is usable."
3999 (save-match-data
4000 (when (and (boundp 'org-latex-to-mathml-convert-command)
4001 org-latex-to-mathml-convert-command)
4002 (let ((executable (car (split-string
4003 org-latex-to-mathml-convert-command))))
4004 (when (executable-find executable)
4005 (if (string-match
4006 "%j" org-latex-to-mathml-convert-command)
4007 (file-readable-p org-latex-to-mathml-jar-file)
4008 t))))))
4010 (defcustom org-format-latex-header "\\documentclass{article}
4011 \\usepackage[usenames]{color}
4012 \[PACKAGES]
4013 \[DEFAULT-PACKAGES]
4014 \\pagestyle{empty} % do not remove
4015 % The settings below are copied from fullpage.sty
4016 \\setlength{\\textwidth}{\\paperwidth}
4017 \\addtolength{\\textwidth}{-3cm}
4018 \\setlength{\\oddsidemargin}{1.5cm}
4019 \\addtolength{\\oddsidemargin}{-2.54cm}
4020 \\setlength{\\evensidemargin}{\\oddsidemargin}
4021 \\setlength{\\textheight}{\\paperheight}
4022 \\addtolength{\\textheight}{-\\headheight}
4023 \\addtolength{\\textheight}{-\\headsep}
4024 \\addtolength{\\textheight}{-\\footskip}
4025 \\addtolength{\\textheight}{-3cm}
4026 \\setlength{\\topmargin}{1.5cm}
4027 \\addtolength{\\topmargin}{-2.54cm}"
4028 "The document header used for processing LaTeX fragments.
4029 It is imperative that this header make sure that no page number
4030 appears on the page. The package defined in the variables
4031 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4032 will either replace the placeholder \"[PACKAGES]\" in this
4033 header, or they will be appended."
4034 :group 'org-latex
4035 :type 'string)
4037 (defun org-set-packages-alist (var val)
4038 "Set the packages alist and make sure it has 3 elements per entry."
4039 (set var (mapcar (lambda (x)
4040 (if (and (consp x) (= (length x) 2))
4041 (list (car x) (nth 1 x) t)
4043 val)))
4045 (defun org-get-packages-alist (var)
4046 "Get the packages alist and make sure it has 3 elements per entry."
4047 (mapcar (lambda (x)
4048 (if (and (consp x) (= (length x) 2))
4049 (list (car x) (nth 1 x) t)
4051 (default-value var)))
4053 (defcustom org-latex-default-packages-alist
4054 '(("AUTO" "inputenc" t ("pdflatex"))
4055 ("T1" "fontenc" t ("pdflatex"))
4056 ("" "graphicx" t)
4057 ("" "grffile" t)
4058 ("" "longtable" nil)
4059 ("" "wrapfig" nil)
4060 ("" "rotating" nil)
4061 ("normalem" "ulem" t)
4062 ("" "amsmath" t)
4063 ("" "textcomp" t)
4064 ("" "amssymb" t)
4065 ("" "capt-of" nil)
4066 ("" "hyperref" nil))
4067 "Alist of default packages to be inserted in the header.
4069 Change this only if one of the packages here causes an
4070 incompatibility with another package you are using.
4072 The packages in this list are needed by one part or another of
4073 Org mode to function properly:
4075 - inputenc, fontenc: for basic font and character selection
4076 - graphicx: for including images
4077 - grffile: allow periods and spaces in graphics file names
4078 - longtable: For multipage tables
4079 - wrapfig: for figure placement
4080 - rotating: for sideways figures and tables
4081 - ulem: for underline and strike-through
4082 - amsmath: for subscript and superscript and math environments
4083 - textcomp, amssymb: for various symbols used
4084 for interpreting the entities in `org-entities'. You can skip
4085 some of these packages if you don't use any of their symbols.
4086 - capt-of: for captions outside of floats
4087 - hyperref: for cross references
4089 Therefore you should not modify this variable unless you know
4090 what you are doing. The one reason to change it anyway is that
4091 you might be loading some other package that conflicts with one
4092 of the default packages. Each element is either a cell or
4093 a string.
4095 A cell is of the format
4097 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4099 If SNIPPET-FLAG is non-nil, the package also needs to be included
4100 when compiling LaTeX snippets into images for inclusion into
4101 non-LaTeX output. COMPILERS is a list of compilers that should
4102 include the package, see `org-latex-compiler'. If the document
4103 compiler is not in the list, and the list is non-nil, the package
4104 will not be inserted in the final document.
4106 A string will be inserted as-is in the header of the document."
4107 :group 'org-latex
4108 :group 'org-export-latex
4109 :set 'org-set-packages-alist
4110 :get 'org-get-packages-alist
4111 :version "26.1"
4112 :package-version '(Org . "8.3")
4113 :type '(repeat
4114 (choice
4115 (list :tag "options/package pair"
4116 (string :tag "options")
4117 (string :tag "package")
4118 (boolean :tag "Snippet"))
4119 (string :tag "A line of LaTeX"))))
4121 (defcustom org-latex-packages-alist nil
4122 "Alist of packages to be inserted in every LaTeX header.
4124 These will be inserted after `org-latex-default-packages-alist'.
4125 Each element is either a cell or a string.
4127 A cell is of the format:
4129 (\"options\" \"package\" SNIPPET-FLAG)
4131 SNIPPET-FLAG, when non-nil, indicates that this package is also
4132 needed when turning LaTeX snippets into images for inclusion into
4133 non-LaTeX output.
4135 A string will be inserted as-is in the header of the document.
4137 Make sure that you only list packages here which:
4139 - you want in every file;
4140 - do not conflict with the setup in `org-format-latex-header';
4141 - do not conflict with the default packages in
4142 `org-latex-default-packages-alist'."
4143 :group 'org-latex
4144 :group 'org-export-latex
4145 :set 'org-set-packages-alist
4146 :get 'org-get-packages-alist
4147 :type '(repeat
4148 (choice
4149 (list :tag "options/package pair"
4150 (string :tag "options")
4151 (string :tag "package")
4152 (boolean :tag "Snippet"))
4153 (string :tag "A line of LaTeX"))))
4155 (defgroup org-appearance nil
4156 "Settings for Org mode appearance."
4157 :tag "Org Appearance"
4158 :group 'org)
4160 (defcustom org-level-color-stars-only nil
4161 "Non-nil means fontify only the stars in each headline.
4162 When nil, the entire headline is fontified.
4163 Changing it requires restart of `font-lock-mode' to become effective
4164 also in regions already fontified."
4165 :group 'org-appearance
4166 :type 'boolean)
4168 (defcustom org-hide-leading-stars nil
4169 "Non-nil means hide the first N-1 stars in a headline.
4170 This works by using the face `org-hide' for these stars. This
4171 face is white for a light background, and black for a dark
4172 background. You may have to customize the face `org-hide' to
4173 make this work.
4174 Changing it requires restart of `font-lock-mode' to become effective
4175 also in regions already fontified.
4176 You may also set this on a per-file basis by adding one of the following
4177 lines to the buffer:
4179 #+STARTUP: hidestars
4180 #+STARTUP: showstars"
4181 :group 'org-appearance
4182 :type 'boolean)
4184 (defcustom org-hidden-keywords nil
4185 "List of symbols corresponding to keywords to be hidden the org buffer.
4186 For example, a value \\='(title) for this list will make the document's title
4187 appear in the buffer without the initial #+TITLE: keyword."
4188 :group 'org-appearance
4189 :version "24.1"
4190 :type '(set (const :tag "#+AUTHOR" author)
4191 (const :tag "#+DATE" date)
4192 (const :tag "#+EMAIL" email)
4193 (const :tag "#+TITLE" title)))
4195 (defcustom org-custom-properties nil
4196 "List of properties (as strings) with a special meaning.
4197 The default use of these custom properties is to let the user
4198 hide them with `org-toggle-custom-properties-visibility'."
4199 :group 'org-properties
4200 :group 'org-appearance
4201 :version "24.3"
4202 :type '(repeat (string :tag "Property Name")))
4204 (defcustom org-fontify-done-headline nil
4205 "Non-nil means change the face of a headline if it is marked DONE.
4206 Normally, only the TODO/DONE keyword indicates the state of a headline.
4207 When this is non-nil, the headline after the keyword is set to the
4208 `org-headline-done' as an additional indication."
4209 :group 'org-appearance
4210 :type 'boolean)
4212 (defcustom org-fontify-emphasized-text t
4213 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4214 Changing this variable requires a restart of Emacs to take effect."
4215 :group 'org-appearance
4216 :type 'boolean)
4218 (defcustom org-fontify-whole-heading-line nil
4219 "Non-nil means fontify the whole line for headings.
4220 This is useful when setting a background color for the
4221 org-level-* faces."
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-highlight-latex-and-related nil
4226 "Non-nil means highlight LaTeX related syntax in the buffer.
4227 When non nil, the value should be a list containing any of the
4228 following symbols:
4229 `latex' Highlight LaTeX snippets and environments.
4230 `script' Highlight subscript and superscript.
4231 `entities' Highlight entities."
4232 :group 'org-appearance
4233 :version "24.4"
4234 :package-version '(Org . "8.0")
4235 :type '(choice
4236 (const :tag "No highlighting" nil)
4237 (set :greedy t :tag "Highlight"
4238 (const :tag "LaTeX snippets and environments" latex)
4239 (const :tag "Subscript and superscript" script)
4240 (const :tag "Entities" entities))))
4242 (defcustom org-hide-emphasis-markers nil
4243 "Non-nil mean font-lock should hide the emphasis marker characters."
4244 :group 'org-appearance
4245 :type 'boolean)
4247 (defcustom org-hide-macro-markers nil
4248 "Non-nil mean font-lock should hide the brackets marking macro calls."
4249 :group 'org-appearance
4250 :type 'boolean)
4252 (defcustom org-pretty-entities nil
4253 "Non-nil means show entities as UTF8 characters.
4254 When nil, the \\name form remains in the buffer."
4255 :group 'org-appearance
4256 :version "24.1"
4257 :type 'boolean)
4259 (defcustom org-pretty-entities-include-sub-superscripts t
4260 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4261 :group 'org-appearance
4262 :version "24.1"
4263 :type 'boolean)
4265 (defvar org-emph-re nil
4266 "Regular expression for matching emphasis.
4267 After a match, the match groups contain these elements:
4268 0 The match of the full regular expression, including the characters
4269 before and after the proper match
4270 1 The character before the proper match, or empty at beginning of line
4271 2 The proper match, including the leading and trailing markers
4272 3 The leading marker like * or /, indicating the type of highlighting
4273 4 The text between the emphasis markers, not including the markers
4274 5 The character after the match, empty at the end of a line")
4276 (defvar org-verbatim-re nil
4277 "Regular expression for matching verbatim text.")
4279 (defvar org-emphasis-regexp-components) ; defined just below
4280 (defvar org-emphasis-alist) ; defined just below
4281 (defun org-set-emph-re (var val)
4282 "Set variable and compute the emphasis regular expression."
4283 (set var val)
4284 (when (and (boundp 'org-emphasis-alist)
4285 (boundp 'org-emphasis-regexp-components)
4286 org-emphasis-alist org-emphasis-regexp-components)
4287 (pcase-let*
4288 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4289 (body (if (<= nl 0) body
4290 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4291 (template
4292 (format (concat "\\([%s]\\|^\\)" ;before markers
4293 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4294 "\\([%s]\\|$\\)") ;after markers
4295 pre border border body border post)))
4296 (setq org-emph-re (format template "*/_+"))
4297 (setq org-verbatim-re (format template "=~")))))
4299 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4300 ;; set this option proved cumbersome. See this message/thread:
4301 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4302 (defvar org-emphasis-regexp-components
4303 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4304 "Components used to build the regular expression for emphasis.
4305 This is a list with five entries. Terminology: In an emphasis string
4306 like \" *strong word* \", we call the initial space PREMATCH, the final
4307 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4308 and \"trong wor\" is the body. The different components in this variable
4309 specify what is allowed/forbidden in each part:
4311 pre Chars allowed as prematch. Beginning of line will be allowed too.
4312 post Chars allowed as postmatch. End of line will be allowed too.
4313 border The chars *forbidden* as border characters.
4314 body-regexp A regexp like \".\" to match a body character. Don't use
4315 non-shy groups here, and don't allow newline here.
4316 newline The maximum number of newlines allowed in an emphasis exp.
4318 You need to reload Org or to restart Emacs after setting this.")
4320 (defcustom org-emphasis-alist
4321 '(("*" bold)
4322 ("/" italic)
4323 ("_" underline)
4324 ("=" org-verbatim verbatim)
4325 ("~" org-code verbatim)
4326 ("+" (:strike-through t)))
4327 "Alist of characters and faces to emphasize text.
4328 Text starting and ending with a special character will be emphasized,
4329 for example *bold*, _underlined_ and /italic/. This variable sets the
4330 marker characters and the face to be used by font-lock for highlighting
4331 in Org buffers.
4333 You need to reload Org or to restart Emacs after customizing this."
4334 :group 'org-appearance
4335 :set 'org-set-emph-re
4336 :version "24.4"
4337 :package-version '(Org . "8.0")
4338 :type '(repeat
4339 (list
4340 (string :tag "Marker character")
4341 (choice
4342 (face :tag "Font-lock-face")
4343 (plist :tag "Face property list"))
4344 (option (const verbatim)))))
4346 (defvar org-protecting-blocks '("src" "example" "export")
4347 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4348 This is needed for font-lock setup.")
4350 ;;; Functions and variables from their packages
4351 ;; Declared here to avoid compiler warnings
4352 (defvar mark-active)
4354 ;; Various packages
4355 (declare-function calc-eval "calc" (str &optional separator &rest args))
4356 (declare-function calendar-forward-day "cal-move" (arg))
4357 (declare-function calendar-goto-date "cal-move" (date))
4358 (declare-function calendar-goto-today "cal-move" ())
4359 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4360 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4361 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4362 (declare-function cdlatex-tab "ext:cdlatex" ())
4363 (declare-function dired-get-filename
4364 "dired"
4365 (&optional localp no-error-if-not-filep))
4366 (declare-function iswitchb-read-buffer
4367 "iswitchb"
4368 (prompt &optional
4369 default require-match _predicate start matches-set))
4370 (declare-function org-agenda-change-all-lines
4371 "org-agenda"
4372 (newhead hdmarker &optional fixface just-this))
4373 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4374 "org-agenda"
4375 (&optional end))
4376 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4377 (declare-function org-agenda-format-item
4378 "org-agenda"
4379 (extra txt &optional level category tags dotime
4380 remove-re habitp))
4381 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4382 (declare-function org-agenda-save-markers-for-cut-and-paste
4383 "org-agenda"
4384 (beg end))
4385 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4386 (declare-function org-agenda-skip "org-agenda" ())
4387 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4388 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4389 (declare-function org-indent-mode "org-indent" (&optional arg))
4390 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4391 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4392 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4393 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4394 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4395 (declare-function parse-time-string "parse-time" (string))
4397 (defvar align-mode-rules-list)
4398 (defvar calc-embedded-close-formula)
4399 (defvar calc-embedded-open-formula)
4400 (defvar calc-embedded-open-mode)
4401 (defvar font-lock-unfontify-region-function)
4402 (defvar iswitchb-temp-buflist)
4403 (defvar org-agenda-tags-todo-honor-ignore-options)
4404 (defvar remember-data-file)
4405 (defvar texmathp-why)
4407 ;;;###autoload
4408 (defun turn-on-orgtbl ()
4409 "Unconditionally turn on `orgtbl-mode'."
4410 (require 'org-table)
4411 (orgtbl-mode 1))
4413 (defun org-at-table-p (&optional table-type)
4414 "Non-nil if the cursor is inside an Org table.
4415 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4416 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4417 (or (not (derived-mode-p 'org-mode))
4418 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4419 (and e (or table-type
4420 (eq 'org (org-element-property :type e))))))))
4422 (defun org-at-table.el-p ()
4423 "Non-nil when point is at a table.el table."
4424 (and (org-match-line "[ \t]*[|+]")
4425 (let ((element (org-element-at-point)))
4426 (and (eq (org-element-type element) 'table)
4427 (eq (org-element-property :type element) 'table.el)))))
4429 (defun org-at-table-hline-p ()
4430 "Non-nil when point is inside a hline in a table.
4431 Assume point is already in a table."
4432 (org-match-line org-table-hline-regexp))
4434 (defun org-table-map-tables (function &optional quietly)
4435 "Apply FUNCTION to the start of all tables in the buffer."
4436 (org-with-wide-buffer
4437 (goto-char (point-min))
4438 (while (re-search-forward org-table-any-line-regexp nil t)
4439 (unless quietly
4440 (message "Mapping tables: %d%%"
4441 (floor (* 100.0 (point)) (buffer-size))))
4442 (beginning-of-line 1)
4443 (when (and (looking-at org-table-line-regexp)
4444 ;; Exclude tables in src/example/verbatim/clocktable blocks
4445 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4446 (save-excursion (funcall function))
4447 (or (looking-at org-table-line-regexp)
4448 (forward-char 1)))
4449 (re-search-forward org-table-any-border-regexp nil 1)))
4450 (unless quietly (message "Mapping tables: done")))
4452 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4453 (declare-function org-clock-update-mode-line "org-clock" ())
4454 (declare-function org-resolve-clocks "org-clock"
4455 (&optional also-non-dangling-p prompt last-valid))
4457 (defun org-at-TBLFM-p (&optional pos)
4458 "Non-nil when point (or POS) is in #+TBLFM line."
4459 (save-excursion
4460 (goto-char (or pos (point)))
4461 (beginning-of-line)
4462 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4463 (eq (org-element-type (org-element-at-point)) 'table))))
4465 (defvar org-clock-start-time)
4466 (defvar org-clock-marker (make-marker)
4467 "Marker recording the last clock-in.")
4468 (defvar org-clock-hd-marker (make-marker)
4469 "Marker recording the last clock-in, but the headline position.")
4470 (defvar org-clock-heading ""
4471 "The heading of the current clock entry.")
4472 (defun org-clock-is-active ()
4473 "Return the buffer where the clock is currently running.
4474 Return nil if no clock is running."
4475 (marker-buffer org-clock-marker))
4477 (defun org-check-running-clock ()
4478 "Check if the current buffer contains the running clock.
4479 If yes, offer to stop it and to save the buffer with the changes."
4480 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4481 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4482 (buffer-name))))
4483 (org-clock-out)
4484 (when (y-or-n-p "Save changed buffer?")
4485 (save-buffer))))
4487 (defun org-clocktable-try-shift (dir n)
4488 "Check if this line starts a clock table, if yes, shift the time block."
4489 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4490 (org-clocktable-shift dir n)))
4492 ;;;###autoload
4493 (defun org-clock-persistence-insinuate ()
4494 "Set up hooks for clock persistence."
4495 (require 'org-clock)
4496 (add-hook 'org-mode-hook 'org-clock-load)
4497 (add-hook 'kill-emacs-hook 'org-clock-save))
4499 (defgroup org-archive nil
4500 "Options concerning archiving in Org mode."
4501 :tag "Org Archive"
4502 :group 'org-structure)
4504 (defcustom org-archive-location "%s_archive::"
4505 "The location where subtrees should be archived.
4507 The value of this variable is a string, consisting of two parts,
4508 separated by a double-colon. The first part is a filename and
4509 the second part is a headline.
4511 When the filename is omitted, archiving happens in the same file.
4512 %s in the filename will be replaced by the current file
4513 name (without the directory part). Archiving to a different file
4514 is useful to keep archived entries from contributing to the
4515 Org Agenda.
4517 The archived entries will be filed as subtrees of the specified
4518 headline. When the headline is omitted, the subtrees are simply
4519 filed away at the end of the file, as top-level entries. Also in
4520 the heading you can use %s to represent the file name, this can be
4521 useful when using the same archive for a number of different files.
4523 Here are a few examples:
4524 \"%s_archive::\"
4525 If the current file is Projects.org, archive in file
4526 Projects.org_archive, as top-level trees. This is the default.
4528 \"::* Archived Tasks\"
4529 Archive in the current file, under the top-level headline
4530 \"* Archived Tasks\".
4532 \"~/org/archive.org::\"
4533 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4535 \"~/org/archive.org::* From %s\"
4536 Archive in file ~/org/archive.org (absolute path), under headlines
4537 \"From FILENAME\" where file name is the current file name.
4539 \"~/org/datetree.org::datetree/* Finished Tasks\"
4540 The \"datetree/\" string is special, signifying to archive
4541 items to the datetree. Items are placed in either the CLOSED
4542 date of the item, or the current date if there is no CLOSED date.
4543 The heading will be a subentry to the current date. There doesn't
4544 need to be a heading, but there always needs to be a slash after
4545 datetree. For example, to store archived items directly in the
4546 datetree, use \"~/org/datetree.org::datetree/\".
4548 \"basement::** Finished Tasks\"
4549 Archive in file ./basement (relative path), as level 3 trees
4550 below the level 2 heading \"** Finished Tasks\".
4552 You may set this option on a per-file basis by adding to the buffer a
4553 line like
4555 #+ARCHIVE: basement::** Finished Tasks
4557 You may also define it locally for a subtree by setting an ARCHIVE property
4558 in the entry. If such a property is found in an entry, or anywhere up
4559 the hierarchy, it will be used."
4560 :group 'org-archive
4561 :type 'string)
4563 (defcustom org-agenda-skip-archived-trees t
4564 "Non-nil means the agenda will skip any items located in archived trees.
4565 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4566 variable is no longer recommended, you should leave it at the value t.
4567 Instead, use the key `v' to cycle the archives-mode in the agenda."
4568 :group 'org-archive
4569 :group 'org-agenda-skip
4570 :type 'boolean)
4572 (defcustom org-columns-skip-archived-trees t
4573 "Non-nil means ignore archived trees when creating column view."
4574 :group 'org-archive
4575 :group 'org-properties
4576 :type 'boolean)
4578 (defcustom org-cycle-open-archived-trees nil
4579 "Non-nil means `org-cycle' will open archived trees.
4580 An archived tree is a tree marked with the tag ARCHIVE.
4581 When nil, archived trees will stay folded. You can still open them with
4582 normal outline commands like `show-all', but not with the cycling commands."
4583 :group 'org-archive
4584 :group 'org-cycle
4585 :type 'boolean)
4587 (defcustom org-sparse-tree-open-archived-trees nil
4588 "Non-nil means sparse tree construction shows matches in archived trees.
4589 When nil, matches in these trees are highlighted, but the trees are kept in
4590 collapsed state."
4591 :group 'org-archive
4592 :group 'org-sparse-trees
4593 :type 'boolean)
4595 (defcustom org-sparse-tree-default-date-type nil
4596 "The default date type when building a sparse tree.
4597 When this is nil, a date is a scheduled or a deadline timestamp.
4598 Otherwise, these types are allowed:
4600 all: all timestamps
4601 active: only active timestamps (<...>)
4602 inactive: only inactive timestamps ([...])
4603 scheduled: only scheduled timestamps
4604 deadline: only deadline timestamps"
4605 :type '(choice (const :tag "Scheduled or deadline" nil)
4606 (const :tag "All timestamps" all)
4607 (const :tag "Only active timestamps" active)
4608 (const :tag "Only inactive timestamps" inactive)
4609 (const :tag "Only scheduled timestamps" scheduled)
4610 (const :tag "Only deadline timestamps" deadline)
4611 (const :tag "Only closed timestamps" closed))
4612 :version "26.1"
4613 :package-version '(Org . "8.3")
4614 :group 'org-sparse-trees)
4616 (defun org-cycle-hide-archived-subtrees (state)
4617 "Re-hide all archived subtrees after a visibility state change.
4618 STATE should be one of the symbols listed in the docstring of
4619 `org-cycle-hook'."
4620 (when (and (not org-cycle-open-archived-trees)
4621 (not (memq state '(overview folded))))
4622 (save-excursion
4623 (let* ((globalp (memq state '(contents all)))
4624 (beg (if globalp (point-min) (point)))
4625 (end (if globalp (point-max) (org-end-of-subtree t))))
4626 (org-hide-archived-subtrees beg end)
4627 (goto-char beg)
4628 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4629 (message "%s" (substitute-command-keys
4630 "Subtree is archived and stays closed. Use \
4631 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4633 (defun org-force-cycle-archived ()
4634 "Cycle subtree even if it is archived."
4635 (interactive)
4636 (setq this-command 'org-cycle)
4637 (let ((org-cycle-open-archived-trees t))
4638 (call-interactively 'org-cycle)))
4640 (defun org-hide-archived-subtrees (beg end)
4641 "Re-hide all archived subtrees after a visibility state change."
4642 (org-with-wide-buffer
4643 (let ((case-fold-search nil)
4644 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4645 (goto-char beg)
4646 ;; Include headline point is currently on.
4647 (beginning-of-line)
4648 (while (and (< (point) end) (re-search-forward re end t))
4649 (when (member org-archive-tag (org-get-tags))
4650 (org-flag-subtree t)
4651 (org-end-of-subtree t))))))
4653 (declare-function outline-end-of-heading "outline" ())
4654 (declare-function outline-flag-region "outline" (from to flag))
4655 (defun org-flag-subtree (flag)
4656 (save-excursion
4657 (org-back-to-heading t)
4658 (outline-end-of-heading)
4659 (outline-flag-region (point)
4660 (progn (org-end-of-subtree t) (point))
4661 flag)))
4663 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4665 ;; Declare Column View Code
4667 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4668 (declare-function org-columns-compute "org-colview" (property))
4670 ;; Declare ID code
4672 (declare-function org-id-store-link "org-id")
4673 (declare-function org-id-locations-load "org-id")
4674 (declare-function org-id-locations-save "org-id")
4675 (defvar org-id-track-globally)
4677 ;;; Variables for pre-computed regular expressions, all buffer local
4679 (defvar-local org-todo-regexp nil
4680 "Matches any of the TODO state keywords.
4681 Since TODO keywords are case-sensitive, `case-fold-search' is
4682 expected to be bound to nil when matching against this regexp.")
4684 (defvar-local org-not-done-regexp nil
4685 "Matches any of the TODO state keywords except the last one.
4686 Since TODO keywords are case-sensitive, `case-fold-search' is
4687 expected to be bound to nil when matching against this regexp.")
4689 (defvar-local org-not-done-heading-regexp nil
4690 "Matches a TODO headline that is not done.
4691 Since TODO keywords are case-sensitive, `case-fold-search' is
4692 expected to be bound to nil when matching against this regexp.")
4694 (defvar-local org-todo-line-regexp nil
4695 "Matches a headline and puts TODO state into group 2 if present.
4696 Since TODO keywords are case-sensitive, `case-fold-search' is
4697 expected to be bound to nil when matching against this regexp.")
4699 (defvar-local org-complex-heading-regexp nil
4700 "Matches a headline and puts everything into groups:
4702 group 1: Stars
4703 group 2: The TODO keyword, maybe
4704 group 3: Priority cookie
4705 group 4: True headline
4706 group 5: Tags
4708 Since TODO keywords are case-sensitive, `case-fold-search' is
4709 expected to be bound to nil when matching against this regexp.")
4711 (defvar-local org-complex-heading-regexp-format nil
4712 "Printf format to make regexp to match an exact headline.
4713 This regexp will match the headline of any node which has the
4714 exact headline text that is put into the format, but may have any
4715 TODO state, priority and tags.")
4717 (defvar-local org-todo-line-tags-regexp nil
4718 "Matches a headline and puts TODO state into group 2 if present.
4719 Also put tags into group 4 if tags are present.")
4721 (defconst org-plain-time-of-day-regexp
4722 (concat
4723 "\\(\\<[012]?[0-9]"
4724 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4725 "\\(--?"
4726 "\\(\\<[012]?[0-9]"
4727 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4728 "\\)?")
4729 "Regular expression to match a plain time or time range.
4730 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4731 groups carry important information:
4732 0 the full match
4733 1 the first time, range or not
4734 8 the second time, if it is a range.")
4736 (defconst org-plain-time-extension-regexp
4737 (concat
4738 "\\(\\<[012]?[0-9]"
4739 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4740 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4741 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4742 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4743 groups carry important information:
4744 0 the full match
4745 7 hours of duration
4746 9 minutes of duration")
4748 (defconst org-stamp-time-of-day-regexp
4749 (concat
4750 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4751 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4752 "\\(--?"
4753 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4754 "Regular expression to match a timestamp time or time range.
4755 After a match, the following groups carry important information:
4756 0 the full match
4757 1 date plus weekday, for back referencing to make sure both times are on the same day
4758 2 the first time, range or not
4759 4 the second time, if it is a range.")
4761 (defconst org-startup-options
4762 '(("fold" org-startup-folded t)
4763 ("overview" org-startup-folded t)
4764 ("nofold" org-startup-folded nil)
4765 ("showall" org-startup-folded nil)
4766 ("showeverything" org-startup-folded showeverything)
4767 ("content" org-startup-folded content)
4768 ("indent" org-startup-indented t)
4769 ("noindent" org-startup-indented nil)
4770 ("hidestars" org-hide-leading-stars t)
4771 ("showstars" org-hide-leading-stars nil)
4772 ("odd" org-odd-levels-only t)
4773 ("oddeven" org-odd-levels-only nil)
4774 ("align" org-startup-align-all-tables t)
4775 ("noalign" org-startup-align-all-tables nil)
4776 ("shrink" org-startup-shrink-all-tables t)
4777 ("inlineimages" org-startup-with-inline-images t)
4778 ("noinlineimages" org-startup-with-inline-images nil)
4779 ("latexpreview" org-startup-with-latex-preview t)
4780 ("nolatexpreview" org-startup-with-latex-preview nil)
4781 ("customtime" org-display-custom-times t)
4782 ("logdone" org-log-done time)
4783 ("lognotedone" org-log-done note)
4784 ("nologdone" org-log-done nil)
4785 ("lognoteclock-out" org-log-note-clock-out t)
4786 ("nolognoteclock-out" org-log-note-clock-out nil)
4787 ("logrepeat" org-log-repeat state)
4788 ("lognoterepeat" org-log-repeat note)
4789 ("logdrawer" org-log-into-drawer t)
4790 ("nologdrawer" org-log-into-drawer nil)
4791 ("logstatesreversed" org-log-states-order-reversed t)
4792 ("nologstatesreversed" org-log-states-order-reversed nil)
4793 ("nologrepeat" org-log-repeat nil)
4794 ("logreschedule" org-log-reschedule time)
4795 ("lognotereschedule" org-log-reschedule note)
4796 ("nologreschedule" org-log-reschedule nil)
4797 ("logredeadline" org-log-redeadline time)
4798 ("lognoteredeadline" org-log-redeadline note)
4799 ("nologredeadline" org-log-redeadline nil)
4800 ("logrefile" org-log-refile time)
4801 ("lognoterefile" org-log-refile note)
4802 ("nologrefile" org-log-refile nil)
4803 ("fninline" org-footnote-define-inline t)
4804 ("nofninline" org-footnote-define-inline nil)
4805 ("fnlocal" org-footnote-section nil)
4806 ("fnauto" org-footnote-auto-label t)
4807 ("fnprompt" org-footnote-auto-label nil)
4808 ("fnconfirm" org-footnote-auto-label confirm)
4809 ("fnplain" org-footnote-auto-label plain)
4810 ("fnadjust" org-footnote-auto-adjust t)
4811 ("nofnadjust" org-footnote-auto-adjust nil)
4812 ("constcgs" constants-unit-system cgs)
4813 ("constSI" constants-unit-system SI)
4814 ("noptag" org-tag-persistent-alist nil)
4815 ("hideblocks" org-hide-block-startup t)
4816 ("nohideblocks" org-hide-block-startup nil)
4817 ("beamer" org-startup-with-beamer-mode t)
4818 ("entitiespretty" org-pretty-entities t)
4819 ("entitiesplain" org-pretty-entities nil))
4820 "Variable associated with STARTUP options for org-mode.
4821 Each element is a list of three items: the startup options (as written
4822 in the #+STARTUP line), the corresponding variable, and the value to set
4823 this variable to if the option is found. An optional forth element PUSH
4824 means to push this value onto the list in the variable.")
4826 (defcustom org-group-tags t
4827 "When non-nil (the default), use group tags.
4828 This can be turned on/off through `org-toggle-tags-groups'."
4829 :group 'org-tags
4830 :group 'org-startup
4831 :type 'boolean)
4833 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4835 (defun org-toggle-tags-groups ()
4836 "Toggle support for group tags.
4837 Support for group tags is controlled by the option
4838 `org-group-tags', which is non-nil by default."
4839 (interactive)
4840 (setq org-group-tags (not org-group-tags))
4841 (cond ((and (derived-mode-p 'org-agenda-mode)
4842 org-group-tags)
4843 (org-agenda-redo))
4844 ((derived-mode-p 'org-mode)
4845 (let ((org-inhibit-startup t)) (org-mode))))
4846 (message "Groups tags support has been turned %s"
4847 (if org-group-tags "on" "off")))
4849 (defun org-set-regexps-and-options (&optional tags-only)
4850 "Precompute regular expressions used in the current buffer.
4851 When optional argument TAGS-ONLY is non-nil, only compute tags
4852 related expressions."
4853 (when (derived-mode-p 'org-mode)
4854 (let ((alist (org--setup-collect-keywords
4855 (org-make-options-regexp
4856 (append '("FILETAGS" "TAGS" "SETUPFILE")
4857 (and (not tags-only)
4858 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4859 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4860 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4861 ;; Startup options. Get this early since it does change
4862 ;; behavior for other options (e.g., tags).
4863 (let ((startup (cdr (assq 'startup alist))))
4864 (dolist (option startup)
4865 (let ((entry (assoc-string option org-startup-options t)))
4866 (when entry
4867 (let ((var (nth 1 entry))
4868 (val (nth 2 entry)))
4869 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4870 (unless (listp (symbol-value var))
4871 (set (make-local-variable var) nil))
4872 (add-to-list var val)))))))
4873 (setq-local org-file-tags
4874 (mapcar #'org-add-prop-inherited
4875 (cdr (assq 'filetags alist))))
4876 (setq org-current-tag-alist
4877 (append org-tag-persistent-alist
4878 (let ((tags (cdr (assq 'tags alist))))
4879 (if tags (org-tag-string-to-alist tags)
4880 org-tag-alist))))
4881 (setq org-tag-groups-alist
4882 (org-tag-alist-to-groups org-current-tag-alist))
4883 (unless tags-only
4884 ;; File properties.
4885 (setq-local org-file-properties (cdr (assq 'property alist)))
4886 ;; Archive location.
4887 (let ((archive (cdr (assq 'archive alist))))
4888 (when archive (setq-local org-archive-location archive)))
4889 ;; Category.
4890 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4891 (when cat
4892 (setq-local org-category (intern cat))
4893 (setq-local org-file-properties
4894 (org--update-property-plist
4895 "CATEGORY" cat org-file-properties))))
4896 ;; Columns.
4897 (let ((column (cdr (assq 'columns alist))))
4898 (when column (setq-local org-columns-default-format column)))
4899 ;; Constants.
4900 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4901 ;; Link abbreviations.
4902 (let ((links (cdr (assq 'link alist))))
4903 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4904 ;; Priorities.
4905 (let ((priorities (cdr (assq 'priorities alist))))
4906 (when priorities
4907 (setq-local org-highest-priority (nth 0 priorities))
4908 (setq-local org-lowest-priority (nth 1 priorities))
4909 (setq-local org-default-priority (nth 2 priorities))))
4910 ;; Scripts.
4911 (let ((scripts (assq 'scripts alist)))
4912 (when scripts
4913 (setq-local org-use-sub-superscripts (cdr scripts))))
4914 ;; TODO keywords.
4915 (setq-local org-todo-kwd-alist nil)
4916 (setq-local org-todo-key-alist nil)
4917 (setq-local org-todo-key-trigger nil)
4918 (setq-local org-todo-keywords-1 nil)
4919 (setq-local org-done-keywords nil)
4920 (setq-local org-todo-heads nil)
4921 (setq-local org-todo-sets nil)
4922 (setq-local org-todo-log-states nil)
4923 (let ((todo-sequences
4924 (or (nreverse (cdr (assq 'todo alist)))
4925 (let ((d (default-value 'org-todo-keywords)))
4926 (if (not (stringp (car d))) d
4927 ;; XXX: Backward compatibility code.
4928 (list (cons org-todo-interpretation d)))))))
4929 (dolist (sequence todo-sequences)
4930 (let* ((sequence (or (run-hook-with-args-until-success
4931 'org-todo-setup-filter-hook sequence)
4932 sequence))
4933 (sequence-type (car sequence))
4934 (keywords (cdr sequence))
4935 (sep (member "|" keywords))
4936 names alist)
4937 (dolist (k (remove "|" keywords))
4938 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4940 (error "Invalid TODO keyword %s" k))
4941 (let ((name (match-string 1 k))
4942 (key (match-string 2 k))
4943 (log (org-extract-log-state-settings k)))
4944 (push name names)
4945 (push (cons name (and key (string-to-char key))) alist)
4946 (when log (push log org-todo-log-states))))
4947 (let* ((names (nreverse names))
4948 (done (if sep (org-remove-keyword-keys (cdr sep))
4949 (last names)))
4950 (head (car names))
4951 (tail (list sequence-type head (car done) (org-last done))))
4952 (add-to-list 'org-todo-heads head 'append)
4953 (push names org-todo-sets)
4954 (setq org-done-keywords (append org-done-keywords done nil))
4955 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4956 (setq org-todo-key-alist
4957 (append org-todo-key-alist
4958 (and alist
4959 (append '((:startgroup))
4960 (nreverse alist)
4961 '((:endgroup))))))
4962 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4963 (setq org-todo-sets (nreverse org-todo-sets)
4964 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4965 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4966 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4967 ;; Compute the regular expressions and other local variables.
4968 ;; Using `org-outline-regexp-bol' would complicate them much,
4969 ;; because of the fixed white space at the end of that string.
4970 (unless org-done-keywords
4971 (setq org-done-keywords
4972 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4973 (setq org-not-done-keywords
4974 (org-delete-all org-done-keywords
4975 (copy-sequence org-todo-keywords-1))
4976 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4977 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4978 org-not-done-heading-regexp
4979 (format org-heading-keyword-regexp-format org-not-done-regexp)
4980 org-todo-line-regexp
4981 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4982 org-complex-heading-regexp
4983 (concat "^\\(\\*+\\)"
4984 "\\(?: +" org-todo-regexp "\\)?"
4985 "\\(?: +\\(\\[#.\\]\\)\\)?"
4986 "\\(?: +\\(.*?\\)\\)??"
4987 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4988 "[ \t]*$")
4989 org-complex-heading-regexp-format
4990 (concat "^\\(\\*+\\)"
4991 "\\(?: +" org-todo-regexp "\\)?"
4992 "\\(?: +\\(\\[#.\\]\\)\\)?"
4993 "\\(?: +"
4994 ;; Stats cookies can be stuck to body.
4995 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4996 "\\(%s\\)"
4997 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4998 "\\)"
4999 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5000 "[ \t]*$")
5001 org-todo-line-tags-regexp
5002 (concat "^\\(\\*+\\)"
5003 "\\(?: +" org-todo-regexp "\\)?"
5004 "\\(?: +\\(.*?\\)\\)??"
5005 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5006 "[ \t]*$"))
5007 (org-compute-latex-and-related-regexp)))))
5009 (defun org--setup-collect-keywords (regexp &optional files alist)
5010 "Return setup keywords values as an alist.
5012 REGEXP matches a subset of setup keywords. FILES is a list of
5013 file names already visited. It is used to avoid circular setup
5014 files. ALIST, when non-nil, is the alist computed so far.
5016 Return value contains the following keys: `archive', `category',
5017 `columns', `constants', `filetags', `link', `priorities',
5018 `property', `scripts', `startup', `tags' and `todo'."
5019 (org-with-wide-buffer
5020 (goto-char (point-min))
5021 (let ((case-fold-search t))
5022 (while (re-search-forward regexp nil t)
5023 (let ((element (org-element-at-point)))
5024 (when (eq (org-element-type element) 'keyword)
5025 (let ((key (org-element-property :key element))
5026 (value (org-element-property :value element)))
5027 (cond
5028 ((equal key "ARCHIVE")
5029 (when (org-string-nw-p value)
5030 (push (cons 'archive value) alist)))
5031 ((equal key "CATEGORY") (push (cons 'category value) alist))
5032 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5033 ((equal key "CONSTANTS")
5034 (let* ((constants (assq 'constants alist))
5035 (store (cdr constants)))
5036 (dolist (pair (split-string value))
5037 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5038 pair)
5039 (let* ((name (match-string 1 pair))
5040 (value (match-string 2 pair))
5041 (old (assoc name store)))
5042 (if old (setcdr old value)
5043 (push (cons name value) store)))))
5044 (if constants (setcdr constants store)
5045 (push (cons 'constants store) alist))))
5046 ((equal key "FILETAGS")
5047 (when (org-string-nw-p value)
5048 (let ((old (assq 'filetags alist))
5049 (new (apply #'nconc
5050 (mapcar (lambda (x) (org-split-string x ":"))
5051 (split-string value)))))
5052 (if old (setcdr old (append new (cdr old)))
5053 (push (cons 'filetags new) alist)))))
5054 ((equal key "LINK")
5055 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5056 (let ((links (assq 'link alist))
5057 (pair (cons (match-string-no-properties 1 value)
5058 (match-string-no-properties 2 value))))
5059 (if links (push pair (cdr links))
5060 (push (list 'link pair) alist)))))
5061 ((equal key "OPTIONS")
5062 (when (and (org-string-nw-p value)
5063 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5064 (push (cons 'scripts (read (match-string 1 value))) alist)))
5065 ((equal key "PRIORITIES")
5066 (push (cons 'priorities
5067 (let ((prio (split-string value)))
5068 (if (< (length prio) 3) '(?A ?C ?B)
5069 (mapcar #'string-to-char prio))))
5070 alist))
5071 ((equal key "PROPERTY")
5072 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5073 (let* ((property (assq 'property alist))
5074 (value (org--update-property-plist
5075 (match-string-no-properties 1 value)
5076 (match-string-no-properties 2 value)
5077 (cdr property))))
5078 (if property (setcdr property value)
5079 (push (cons 'property value) alist)))))
5080 ((equal key "STARTUP")
5081 (let ((startup (assq 'startup alist)))
5082 (if startup
5083 (setcdr startup
5084 (append (cdr startup) (split-string value)))
5085 (push (cons 'startup (split-string value)) alist))))
5086 ((equal key "TAGS")
5087 (let ((tag-cell (assq 'tags alist)))
5088 (if tag-cell
5089 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5090 (push (cons 'tags value) alist))))
5091 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5092 (let ((todo (assq 'todo alist))
5093 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5094 (split-string value))))
5095 (if todo (push value (cdr todo))
5096 (push (list 'todo value) alist))))
5097 ((equal key "SETUPFILE")
5098 (unless buffer-read-only ; Do not check in Gnus messages.
5099 (let ((f (and (org-string-nw-p value)
5100 (expand-file-name
5101 (org-unbracket-string "\"" "\"" value)))))
5102 (when (and f (file-readable-p f) (not (member f files)))
5103 (with-temp-buffer
5104 (setq default-directory (file-name-directory f))
5105 (insert-file-contents f)
5106 (setq alist
5107 ;; Fake Org mode to benefit from cache
5108 ;; without recurring needlessly.
5109 (let ((major-mode 'org-mode))
5110 (org--setup-collect-keywords
5111 regexp (cons f files) alist)))))))))))))))
5112 alist)
5114 (defun org-tag-string-to-alist (s)
5115 "Return tag alist associated to string S.
5116 S is a value for TAGS keyword or produced with
5117 `org-tag-alist-to-string'. Return value is an alist suitable for
5118 `org-tag-alist' or `org-tag-persistent-alist'."
5119 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5120 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5121 "\\|{.+?}\\)" ; regular expression
5122 "\\(?:(\\(.\\))\\)?\\'"))
5123 alist group-flag)
5124 (dolist (tokens lines (cdr (nreverse alist)))
5125 (push '(:newline) alist)
5126 (while tokens
5127 (let ((token (pop tokens)))
5128 (pcase token
5129 ("{"
5130 (push '(:startgroup) alist)
5131 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5132 ("}"
5133 (push '(:endgroup) alist)
5134 (setq group-flag nil))
5135 ("["
5136 (push '(:startgrouptag) alist)
5137 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5138 ("]"
5139 (push '(:endgrouptag) alist)
5140 (setq group-flag nil))
5141 (":"
5142 (push '(:grouptags) alist))
5143 ((guard (string-match tag-re token))
5144 (let ((tag (match-string 1 token))
5145 (key (and (match-beginning 2)
5146 (string-to-char (match-string 2 token)))))
5147 ;; Push all tags in groups, no matter if they already
5148 ;; appear somewhere else in the list.
5149 (when (or group-flag (not (assoc tag alist)))
5150 (push (cons tag key) alist))))))))))
5152 (defun org-tag-alist-to-string (alist &optional skip-key)
5153 "Return tag string associated to ALIST.
5155 ALIST is an alist, as defined in `org-tag-alist' or
5156 `org-tag-persistent-alist', or produced with
5157 `org-tag-string-to-alist'.
5159 Return value is a string suitable as a value for \"TAGS\"
5160 keyword.
5162 When optional argument SKIP-KEY is non-nil, skip selection keys
5163 next to tags."
5164 (mapconcat (lambda (token)
5165 (pcase token
5166 (`(:startgroup) "{")
5167 (`(:endgroup) "}")
5168 (`(:startgrouptag) "[")
5169 (`(:endgrouptag) "]")
5170 (`(:grouptags) ":")
5171 (`(:newline) "\\n")
5172 ((and
5173 (guard (not skip-key))
5174 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5175 (format "%s(%c)" tag key))
5176 (`(,(and tag (pred stringp)) . ,_) tag)
5177 (_ (user-error "Invalid tag token: %S" token))))
5178 alist
5179 " "))
5181 (defun org-tag-alist-to-groups (alist)
5182 "Return group alist from tag ALIST.
5183 ALIST is an alist, as defined in `org-tag-alist' or
5184 `org-tag-persistent-alist', or produced with
5185 `org-tag-string-to-alist'. Return value is an alist following
5186 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5187 a string, summarizing TAGS, as a list of strings."
5188 (let (groups group-status current-group)
5189 (dolist (token alist (nreverse groups))
5190 (pcase token
5191 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5192 (`(,(or :endgroup :endgrouptag))
5193 (when (eq group-status 'append)
5194 (push (nreverse current-group) groups))
5195 (setq group-status nil))
5196 (`(:grouptags) (setq group-status 'append))
5197 ((and `(,tag . ,_) (guard group-status))
5198 (if (eq group-status 'append) (push tag current-group)
5199 (setq current-group (list tag))))
5200 (_ nil)))))
5202 (defvar org--file-cache (make-hash-table :test #'equal)
5203 "Hash table to store contents of files referenced via a URL.
5204 This is the cache of file URLs read using `org-file-contents'.")
5206 (defun org-reset-file-cache ()
5207 "Reset the cache of files downloaded by `org-file-contents'."
5208 (clrhash org--file-cache))
5210 (defun org-file-url-p (file)
5211 "Non-nil if FILE is a URL."
5212 (require 'ffap)
5213 (string-match-p ffap-url-regexp file))
5215 (defun org-file-contents (file &optional noerror nocache)
5216 "Return the contents of FILE, as a string.
5218 FILE can be a file name or URL.
5220 If FILE is a URL, download the contents. If the URL contents are
5221 already cached in the `org--file-cache' hash table, the download step
5222 is skipped.
5224 If NOERROR is non-nil, ignore the error when unable to read the FILE
5225 from file or URL.
5227 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5228 is available. This option applies only if FILE is a URL."
5229 (let* ((is-url (org-file-url-p file))
5230 (cache (and is-url
5231 (not nocache)
5232 (gethash file org--file-cache))))
5233 (cond
5234 (cache)
5235 (is-url
5236 (with-current-buffer (url-retrieve-synchronously file)
5237 (goto-char (point-min))
5238 ;; Move point to after the url-retrieve header.
5239 (search-forward "\n\n" nil :move)
5240 ;; Search for the success code only in the url-retrieve header.
5241 (if (save-excursion
5242 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5243 ;; Update the cache `org--file-cache' and return contents.
5244 (puthash file
5245 (buffer-substring-no-properties (point) (point-max))
5246 org--file-cache)
5247 (funcall (if noerror #'message #'user-error)
5248 "Unable to fetch file from %S"
5249 file))))
5251 (with-temp-buffer
5252 (condition-case nil
5253 (progn
5254 (insert-file-contents file)
5255 (buffer-string))
5256 (file-error
5257 (funcall (if noerror #'message #'user-error)
5258 "Unable to read file %S"
5259 file))))))))
5261 (defun org-extract-log-state-settings (x)
5262 "Extract the log state setting from a TODO keyword string.
5263 This will extract info from a string like \"WAIT(w@/!)\"."
5264 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5265 (let ((kw (match-string 1 x))
5266 (log1 (and (match-end 3) (match-string 3 x)))
5267 (log2 (and (match-end 4) (match-string 4 x))))
5268 (and (or log1 log2)
5269 (list kw
5270 (and log1 (if (equal log1 "!") 'time 'note))
5271 (and log2 (if (equal log2 "!") 'time 'note)))))))
5273 (defun org-remove-keyword-keys (list)
5274 "Remove a pair of parenthesis at the end of each string in LIST."
5275 (mapcar (lambda (x)
5276 (if (string-match "(.*)$" x)
5277 (substring x 0 (match-beginning 0))
5279 list))
5281 (defun org-assign-fast-keys (alist)
5282 "Assign fast keys to a keyword-key alist.
5283 Respect keys that are already there."
5284 (let (new e (alt ?0))
5285 (while (setq e (pop alist))
5286 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5287 (cdr e)) ;; Key already assigned.
5288 (push e new)
5289 (let ((clist (string-to-list (downcase (car e))))
5290 (used (append new alist)))
5291 (when (= (car clist) ?@)
5292 (pop clist))
5293 (while (and clist (rassoc (car clist) used))
5294 (pop clist))
5295 (unless clist
5296 (while (rassoc alt used)
5297 (cl-incf alt)))
5298 (push (cons (car e) (or (car clist) alt)) new))))
5299 (nreverse new)))
5301 ;;; Some variables used in various places
5303 (defvar org-window-configuration nil
5304 "Used in various places to store a window configuration.")
5305 (defvar org-selected-window nil
5306 "Used in various places to store a window configuration.")
5307 (defvar org-finish-function nil
5308 "Function to be called when `C-c C-c' is used.
5309 This is for getting out of special buffers like capture.")
5310 (defvar org-last-state)
5312 ;; Defined somewhere in this file, but used before definition.
5313 (defvar org-entities) ;; defined in org-entities.el
5314 (defvar org-struct-menu)
5315 (defvar org-org-menu)
5316 (defvar org-tbl-menu)
5318 ;;;; Define the Org mode
5320 ;; We use a before-change function to check if a table might need
5321 ;; an update.
5322 (defvar org-table-may-need-update t
5323 "Indicates that a table might need an update.
5324 This variable is set by `org-before-change-function'.
5325 `org-table-align' sets it back to nil.")
5326 (defun org-before-change-function (_beg _end)
5327 "Every change indicates that a table might need an update."
5328 (setq org-table-may-need-update t))
5329 (defvar org-mode-map)
5330 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5331 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5332 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5333 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5334 (defvar org-table-buffer-is-an nil)
5336 (defvar bidi-paragraph-direction)
5337 (defvar buffer-face-mode-face)
5339 (require 'outline)
5341 ;; Other stuff we need.
5342 (require 'time-date)
5343 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5344 (require 'easymenu)
5345 (autoload 'easy-menu-add "easymenu")
5346 (require 'overlay)
5348 ;; (require 'org-macs) moved higher up in the file before it is first used
5349 (require 'org-entities)
5350 ;; (require 'org-compat) moved higher up in the file before it is first used
5351 (require 'org-faces)
5352 (require 'org-list)
5353 (require 'org-pcomplete)
5354 (require 'org-src)
5355 (require 'org-footnote)
5356 (require 'org-macro)
5358 ;; babel
5359 (require 'ob)
5361 ;;;###autoload
5362 (define-derived-mode org-mode outline-mode "Org"
5363 "Outline-based notes management and organizer, alias
5364 \"Carsten's outline-mode for keeping track of everything.\"
5366 Org mode develops organizational tasks around a NOTES file which
5367 contains information about projects as plain text. Org mode is
5368 implemented on top of Outline mode, which is ideal to keep the content
5369 of large files well structured. It supports ToDo items, deadlines and
5370 time stamps, which magically appear in the diary listing of the Emacs
5371 calendar. Tables are easily created with a built-in table editor.
5372 Plain text URL-like links connect to websites, emails (VM), Usenet
5373 messages (Gnus), BBDB entries, and any files related to the project.
5374 For printing and sharing of notes, an Org file (or a part of it)
5375 can be exported as a structured ASCII or HTML file.
5377 The following commands are available:
5379 \\{org-mode-map}"
5381 ;; Get rid of Outline menus, they are not needed
5382 ;; Need to do this here because define-derived-mode sets up
5383 ;; the keymap so late. Still, it is a waste to call this each time
5384 ;; we switch another buffer into Org mode.
5385 (define-key org-mode-map [menu-bar headings] 'undefined)
5386 (define-key org-mode-map [menu-bar hide] 'undefined)
5387 (define-key org-mode-map [menu-bar show] 'undefined)
5389 (org-load-modules-maybe)
5390 (org-install-agenda-files-menu)
5391 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5392 (add-to-invisibility-spec '(org-hide-block . t))
5393 (setq-local outline-regexp org-outline-regexp)
5394 (setq-local outline-level 'org-outline-level)
5395 (setq bidi-paragraph-direction 'left-to-right)
5396 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5397 (unless org-display-table
5398 (setq org-display-table (make-display-table)))
5399 (set-display-table-slot
5400 org-display-table 4
5401 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5402 org-ellipsis)))
5403 (setq buffer-display-table org-display-table))
5404 (org-set-regexps-and-options)
5405 (org-set-font-lock-defaults)
5406 (when (and org-tag-faces (not org-tags-special-faces-re))
5407 ;; tag faces set outside customize.... force initialization.
5408 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5409 ;; Calc embedded
5410 (setq-local calc-embedded-open-mode "# ")
5411 ;; Modify a few syntax entries
5412 (modify-syntax-entry ?@ "w")
5413 (modify-syntax-entry ?\" "\"")
5414 (modify-syntax-entry ?\\ "_")
5415 (modify-syntax-entry ?~ "_")
5416 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5417 ;; Activate before-change-function
5418 (setq-local org-table-may-need-update t)
5419 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5420 ;; Check for running clock before killing a buffer
5421 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5422 ;; Initialize macros templates.
5423 (org-macro-initialize-templates)
5424 ;; Initialize radio targets.
5425 (org-update-radio-target-regexp)
5426 ;; Indentation.
5427 (setq-local indent-line-function 'org-indent-line)
5428 (setq-local indent-region-function 'org-indent-region)
5429 ;; Filling and auto-filling.
5430 (org-setup-filling)
5431 ;; Comments.
5432 (org-setup-comments-handling)
5433 ;; Initialize cache.
5434 (org-element-cache-reset)
5435 ;; Beginning/end of defun
5436 (setq-local beginning-of-defun-function 'org-backward-element)
5437 (setq-local end-of-defun-function
5438 (lambda ()
5439 (if (not (org-at-heading-p))
5440 (org-forward-element)
5441 (org-forward-element)
5442 (forward-char -1))))
5443 ;; Next error for sparse trees
5444 (setq-local next-error-function 'org-occur-next-match)
5445 ;; Make sure dependence stuff works reliably, even for users who set it
5446 ;; too late :-(
5447 (if org-enforce-todo-dependencies
5448 (add-hook 'org-blocker-hook
5449 'org-block-todo-from-children-or-siblings-or-parent)
5450 (remove-hook 'org-blocker-hook
5451 'org-block-todo-from-children-or-siblings-or-parent))
5452 (if org-enforce-todo-checkbox-dependencies
5453 (add-hook 'org-blocker-hook
5454 'org-block-todo-from-checkboxes)
5455 (remove-hook 'org-blocker-hook
5456 'org-block-todo-from-checkboxes))
5458 ;; Align options lines
5459 (setq-local
5460 align-mode-rules-list
5461 '((org-in-buffer-settings
5462 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5463 (modes . '(org-mode)))))
5465 ;; Imenu
5466 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5468 ;; Make isearch reveal context
5469 (setq-local outline-isearch-open-invisible-function
5470 (lambda (&rest _) (org-show-context 'isearch)))
5472 ;; Setup the pcomplete hooks
5473 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5474 (setq-local pcomplete-command-name-function 'org-command-at-point)
5475 (setq-local pcomplete-default-completion-function 'ignore)
5476 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5477 (setq-local pcomplete-termination-string "")
5478 (setq-local buffer-face-mode-face 'org-default)
5480 ;; If empty file that did not turn on Org mode automatically, make
5481 ;; it to.
5482 (when (and org-insert-mode-line-in-empty-file
5483 (called-interactively-p 'any)
5484 (= (point-min) (point-max)))
5485 (insert "# -*- mode: org -*-\n\n"))
5486 (unless org-inhibit-startup
5487 (org-unmodified
5488 (when org-startup-with-beamer-mode (org-beamer-mode))
5489 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5490 (org-table-map-tables
5491 (cond ((and org-startup-align-all-tables
5492 org-startup-shrink-all-tables)
5493 (lambda () (org-table-align) (org-table-shrink)))
5494 (org-startup-align-all-tables #'org-table-align)
5495 (t #'org-table-shrink))
5497 (when org-startup-with-inline-images (org-display-inline-images))
5498 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5499 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5500 (when org-startup-truncated (setq truncate-lines t))
5501 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5502 (org-refresh-effort-properties)))
5503 ;; Try to set `org-hide' face correctly.
5504 (let ((foreground (org-find-invisible-foreground)))
5505 (when foreground
5506 (set-face-foreground 'org-hide foreground))))
5508 ;; Update `customize-package-emacs-version-alist'
5509 (add-to-list 'customize-package-emacs-version-alist
5510 '(Org ("8.0" . "24.4")
5511 ("8.1" . "24.4")
5512 ("8.2" . "24.4")
5513 ("8.2.7" . "24.4")
5514 ("8.3" . "26.1")
5515 ("9.0" . "26.1")
5516 ("9.1" . "26.1")
5517 ("9.2" . "27.1")))
5519 (defvar org-mode-transpose-word-syntax-table
5520 (let ((st (make-syntax-table text-mode-syntax-table)))
5521 (dolist (c org-emphasis-alist st)
5522 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5524 (when (fboundp 'abbrev-table-put)
5525 (abbrev-table-put org-mode-abbrev-table
5526 :parents (list text-mode-abbrev-table)))
5528 (defun org-find-invisible-foreground ()
5529 (let ((candidates (remove
5530 "unspecified-bg"
5531 (nconc
5532 (list (face-background 'default)
5533 (face-background 'org-default))
5534 (mapcar
5535 (lambda (alist)
5536 (when (boundp alist)
5537 (cdr (assq 'background-color (symbol-value alist)))))
5538 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5539 (list (face-foreground 'org-hide))))))
5540 (car (remove nil candidates))))
5542 (defun org-current-time (&optional rounding-minutes past)
5543 "Current time, possibly rounded to ROUNDING-MINUTES.
5544 When ROUNDING-MINUTES is not an integer, fall back on the car of
5545 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5546 the rounding returns a past time."
5547 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5548 (car org-time-stamp-rounding-minutes)))
5549 (time (decode-time)) res)
5550 (if (< r 1)
5551 (current-time)
5552 (setq res
5553 (apply 'encode-time
5554 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5555 (nthcdr 2 time))))
5556 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5557 (seconds-to-time (- (float-time res) (* r 60)))
5558 res))))
5560 (defun org-today ()
5561 "Return today date, considering `org-extend-today-until'."
5562 (time-to-days
5563 (time-subtract (current-time)
5564 (list 0 (* 3600 org-extend-today-until) 0))))
5566 ;;;; Font-Lock stuff, including the activators
5568 (defvar org-mouse-map (make-sparse-keymap))
5569 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5570 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5571 (when org-mouse-1-follows-link
5572 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5573 (when org-tab-follows-link
5574 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5575 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5577 (require 'font-lock)
5579 (defconst org-non-link-chars "]\t\n\r<>")
5580 (defvar org-link-types-re nil
5581 "Matches a link that has a url-like prefix like \"http:\"")
5582 (defvar org-link-re-with-space nil
5583 "Matches a link with spaces, optional angular brackets around it.")
5584 (defvar org-link-re-with-space2 nil
5585 "Matches a link with spaces, optional angular brackets around it.")
5586 (defvar org-link-re-with-space3 nil
5587 "Matches a link with spaces, only for internal part in bracket links.")
5588 (defvar org-angle-link-re nil
5589 "Matches link with angular brackets, spaces are allowed.")
5590 (defvar org-plain-link-re nil
5591 "Matches plain link, without spaces.")
5592 (defvar org-bracket-link-regexp nil
5593 "Matches a link in double brackets.")
5594 (defvar org-bracket-link-analytic-regexp nil
5595 "Regular expression used to analyze links.
5596 Here is what the match groups contain after a match:
5597 1: http:
5598 2: http
5599 3: path
5600 4: [desc]
5601 5: desc")
5602 (defvar org-bracket-link-analytic-regexp++ nil
5603 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5604 (defvar org-any-link-re nil
5605 "Regular expression matching any link.")
5607 (defconst org-match-sexp-depth 3
5608 "Number of stacked braces for sub/superscript matching.")
5610 (defun org-create-multibrace-regexp (left right n)
5611 "Create a regular expression which will match a balanced sexp.
5612 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5613 as single character strings.
5614 The regexp returned will match the entire expression including the
5615 delimiters. It will also define a single group which contains the
5616 match except for the outermost delimiters. The maximum depth of
5617 stacked delimiters is N. Escaping delimiters is not possible."
5618 (let* ((nothing (concat "[^" left right "]*?"))
5619 (or "\\|")
5620 (re nothing)
5621 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5622 (while (> n 1)
5623 (setq n (1- n)
5624 re (concat re or next)
5625 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5626 (concat left "\\(" re "\\)" right)))
5628 (defconst org-match-substring-regexp
5629 (concat
5630 "\\(\\S-\\)\\([_^]\\)\\("
5631 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5632 "\\|"
5633 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5634 "\\|"
5635 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5636 "The regular expression matching a sub- or superscript.")
5638 (defconst org-match-substring-with-braces-regexp
5639 (concat
5640 "\\(\\S-\\)\\([_^]\\)"
5641 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5642 "The regular expression matching a sub- or superscript, forcing braces.")
5644 (defun org-make-link-regexps ()
5645 "Update the link regular expressions.
5646 This should be called after the variable `org-link-parameters' has changed."
5647 (let ((types-re (regexp-opt (org-link-types) t)))
5648 (setq org-link-types-re
5649 (concat "\\`" types-re ":")
5650 org-link-re-with-space
5651 (concat "<?" types-re ":"
5652 "\\([^" org-non-link-chars " ]"
5653 "[^" org-non-link-chars "]*"
5654 "[^" org-non-link-chars " ]\\)>?")
5655 org-link-re-with-space2
5656 (concat "<?" types-re ":"
5657 "\\([^" org-non-link-chars " ]"
5658 "[^\t\n\r]*"
5659 "[^" org-non-link-chars " ]\\)>?")
5660 org-link-re-with-space3
5661 (concat "<?" types-re ":"
5662 "\\([^" org-non-link-chars " ]"
5663 "[^\t\n\r]*\\)")
5664 org-angle-link-re
5665 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5666 types-re)
5667 org-plain-link-re
5668 (concat
5669 "\\<" types-re ":"
5670 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5671 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5672 org-bracket-link-regexp
5673 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5674 org-bracket-link-analytic-regexp
5675 (concat
5676 "\\[\\["
5677 "\\(" types-re ":\\)?"
5678 "\\([^]]+\\)"
5679 "\\]"
5680 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5681 "\\]")
5682 org-bracket-link-analytic-regexp++
5683 (concat
5684 "\\[\\["
5685 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5686 "\\([^]]+\\)"
5687 "\\]"
5688 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5689 "\\]")
5690 org-any-link-re
5691 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5692 org-angle-link-re "\\)\\|\\("
5693 org-plain-link-re "\\)"))))
5695 (org-make-link-regexps)
5697 (defvar org-emph-face nil)
5699 (defun org-do-emphasis-faces (limit)
5700 "Run through the buffer and emphasize strings."
5701 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5702 (car org-emphasis-regexp-components))))
5703 (catch :exit
5704 (while (re-search-forward quick-re limit t)
5705 (let* ((marker (match-string 2))
5706 (verbatim? (member marker '("~" "="))))
5707 (when (save-excursion
5708 (goto-char (match-beginning 0))
5709 (and
5710 ;; Do not match table hlines.
5711 (not (and (equal marker "+")
5712 (org-match-line
5713 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5714 ;; Do not match headline stars. Do not consider
5715 ;; stars of a headline as closing marker for bold
5716 ;; markup either.
5717 (not (and (equal marker "*")
5718 (save-excursion
5719 (forward-char)
5720 (skip-chars-backward "*")
5721 (looking-at-p org-outline-regexp-bol))))
5722 ;; Match full emphasis markup regexp.
5723 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5724 ;; Do not span over paragraph boundaries.
5725 (not (string-match-p org-element-paragraph-separate
5726 (match-string 2)))
5727 ;; Do not span over cells in table rows.
5728 (not (and (save-match-data (org-match-line "[ \t]*|"))
5729 (string-match-p "|" (match-string 4))))))
5730 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5731 (font-lock-prepend-text-property
5732 (match-beginning 2) (match-end 2) 'face face)
5733 (when verbatim?
5734 (org-remove-flyspell-overlays-in
5735 (match-beginning 0) (match-end 0)))
5736 (add-text-properties (match-beginning 2) (match-end 2)
5737 '(font-lock-multiline t org-emphasis t))
5738 (when org-hide-emphasis-markers
5739 (add-text-properties (match-end 4) (match-beginning 5)
5740 '(invisible org-link))
5741 (add-text-properties (match-beginning 3) (match-end 3)
5742 '(invisible org-link)))
5743 (throw :exit t))))))))
5745 (defun org-emphasize (&optional char)
5746 "Insert or change an emphasis, i.e. a font like bold or italic.
5747 If there is an active region, change that region to a new emphasis.
5748 If there is no region, just insert the marker characters and position
5749 the cursor between them.
5750 CHAR should be the marker character. If it is a space, it means to
5751 remove the emphasis of the selected region.
5752 If CHAR is not given (for example in an interactive call) it will be
5753 prompted for."
5754 (interactive)
5755 (let ((erc org-emphasis-regexp-components)
5756 (string "") beg end move s)
5757 (if (org-region-active-p)
5758 (setq beg (region-beginning)
5759 end (region-end)
5760 string (buffer-substring beg end))
5761 (setq move t))
5763 (unless char
5764 (message "Emphasis marker or tag: [%s]"
5765 (mapconcat #'car org-emphasis-alist ""))
5766 (setq char (read-char-exclusive)))
5767 (if (equal char ?\s)
5768 (setq s ""
5769 move nil)
5770 (unless (assoc (char-to-string char) org-emphasis-alist)
5771 (user-error "No such emphasis marker: \"%c\"" char))
5772 (setq s (char-to-string char)))
5773 (while (and (> (length string) 1)
5774 (equal (substring string 0 1) (substring string -1))
5775 (assoc (substring string 0 1) org-emphasis-alist))
5776 (setq string (substring string 1 -1)))
5777 (setq string (concat s string s))
5778 (when beg (delete-region beg end))
5779 (unless (or (bolp)
5780 (string-match (concat "[" (nth 0 erc) "\n]")
5781 (char-to-string (char-before (point)))))
5782 (insert " "))
5783 (unless (or (eobp)
5784 (string-match (concat "[" (nth 1 erc) "\n]")
5785 (char-to-string (char-after (point)))))
5786 (insert " ") (backward-char 1))
5787 (insert string)
5788 (and move (backward-char 1))))
5790 (defconst org-nonsticky-props
5791 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5793 (defsubst org-rear-nonsticky-at (pos)
5794 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5796 (defun org-activate-links (limit)
5797 "Add link properties to links.
5798 This includes angle, plain, and bracket links."
5799 (catch :exit
5800 (while (re-search-forward org-any-link-re limit t)
5801 (let* ((start (match-beginning 0))
5802 (end (match-end 0))
5803 (style (cond ((eq ?< (char-after start)) 'angle)
5804 ((eq ?\[ (char-after (1+ start))) 'bracket)
5805 (t 'plain))))
5806 (when (and (memq style org-highlight-links)
5807 ;; Do not confuse plain links with tags.
5808 (not (and (eq style 'plain)
5809 (let ((face (get-text-property
5810 (max (1- start) (point-min)) 'face)))
5811 (if (consp face) (memq 'org-tag face)
5812 (eq 'org-tag face))))))
5813 (let* ((link-object (save-excursion
5814 (goto-char start)
5815 (save-match-data (org-element-link-parser))))
5816 (link (org-element-property :raw-link link-object))
5817 (type (org-element-property :type link-object))
5818 (path (org-element-property :path link-object))
5819 (properties ;for link's visible part
5820 (list
5821 'face (pcase (org-link-get-parameter type :face)
5822 ((and (pred functionp) face) (funcall face path))
5823 ((and (pred facep) face) face)
5824 ((and (pred consp) face) face) ;anonymous
5825 (_ 'org-link))
5826 'mouse-face (or (org-link-get-parameter type :mouse-face)
5827 'highlight)
5828 'keymap (or (org-link-get-parameter type :keymap)
5829 org-mouse-map)
5830 'help-echo (pcase (org-link-get-parameter type :help-echo)
5831 ((and (pred stringp) echo) echo)
5832 ((and (pred functionp) echo) echo)
5833 (_ (concat "LINK: " link)))
5834 'htmlize-link (pcase (org-link-get-parameter type
5835 :htmlize-link)
5836 ((and (pred functionp) f) (funcall f))
5837 (_ `(:uri ,link)))
5838 'font-lock-multiline t)))
5839 (org-remove-flyspell-overlays-in start end)
5840 (org-rear-nonsticky-at end)
5841 (if (not (eq 'bracket style))
5842 (add-text-properties start end properties)
5843 ;; Handle invisible parts in bracket links.
5844 (remove-text-properties start end '(invisible nil))
5845 (let ((hidden
5846 (append `(invisible
5847 ,(or (org-link-get-parameter type :display)
5848 'org-link))
5849 properties))
5850 (visible-start (or (match-beginning 4) (match-beginning 2)))
5851 (visible-end (or (match-end 4) (match-end 2))))
5852 (add-text-properties start visible-start hidden)
5853 (add-text-properties visible-start visible-end properties)
5854 (add-text-properties visible-end end hidden)
5855 (org-rear-nonsticky-at visible-start)
5856 (org-rear-nonsticky-at visible-end)))
5857 (let ((f (org-link-get-parameter type :activate-func)))
5858 (when (functionp f)
5859 (funcall f start end path (eq style 'bracket))))
5860 (throw :exit t))))) ;signal success
5861 nil))
5863 (defun org-activate-code (limit)
5864 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5865 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5866 (remove-text-properties (match-beginning 0) (match-end 0)
5867 '(display t invisible t intangible t))
5870 (defcustom org-src-fontify-natively t
5871 "When non-nil, fontify code in code blocks.
5872 See also the `org-block' face."
5873 :type 'boolean
5874 :version "26.1"
5875 :package-version '(Org . "8.3")
5876 :group 'org-appearance
5877 :group 'org-babel)
5879 (defcustom org-allow-promoting-top-level-subtree nil
5880 "When non-nil, allow promoting a top level subtree.
5881 The leading star of the top level headline will be replaced
5882 by a #."
5883 :type 'boolean
5884 :version "24.1"
5885 :group 'org-appearance)
5887 (defun org-fontify-meta-lines-and-blocks (limit)
5888 (condition-case nil
5889 (org-fontify-meta-lines-and-blocks-1 limit)
5890 (error (message "org-mode fontification error in %S at %d"
5891 (current-buffer)
5892 (line-number-at-pos)))))
5894 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5895 "Fontify #+ lines and blocks."
5896 (let ((case-fold-search t))
5897 (when (re-search-forward
5898 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5899 limit t)
5900 (let ((beg (match-beginning 0))
5901 (block-start (match-end 0))
5902 (block-end nil)
5903 (lang (match-string 7))
5904 (beg1 (line-beginning-position 2))
5905 (dc1 (downcase (match-string 2)))
5906 (dc3 (downcase (match-string 3)))
5907 end end1 quoting block-type)
5908 (cond
5909 ((and (match-end 4) (equal dc3 "+begin"))
5910 ;; Truly a block
5911 (setq block-type (downcase (match-string 5))
5912 quoting (member block-type org-protecting-blocks))
5913 (when (re-search-forward
5914 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5915 nil t) ;; on purpose, we look further than LIMIT
5916 (setq end (min (point-max) (match-end 0))
5917 end1 (min (point-max) (1- (match-beginning 0))))
5918 (setq block-end (match-beginning 0))
5919 (when quoting
5920 (org-remove-flyspell-overlays-in beg1 end1)
5921 (remove-text-properties beg end
5922 '(display t invisible t intangible t)))
5923 (add-text-properties
5924 beg end '(font-lock-fontified t font-lock-multiline t))
5925 (add-text-properties beg beg1 '(face org-meta-line))
5926 (org-remove-flyspell-overlays-in beg beg1)
5927 (add-text-properties ; For end_src
5928 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5929 (org-remove-flyspell-overlays-in end1 end)
5930 (cond
5931 ((and lang (not (string= lang "")) org-src-fontify-natively)
5932 (org-src-font-lock-fontify-block lang block-start block-end)
5933 (add-text-properties beg1 block-end '(src-block t)))
5934 (quoting
5935 (add-text-properties beg1 (min (point-max) (1+ end1))
5936 (list 'face
5937 (list :inherit
5938 (let ((face-name
5939 (intern (format "org-block-%s" lang))))
5940 (append (and (facep face-name) (list face-name))
5941 '(org-block))))))) ; end of source block
5942 ((not org-fontify-quote-and-verse-blocks))
5943 ((string= block-type "quote")
5944 (add-face-text-property
5945 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5946 ((string= block-type "verse")
5947 (add-face-text-property
5948 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5949 (add-text-properties beg beg1 '(face org-block-begin-line))
5950 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5951 '(face org-block-end-line))
5953 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5954 (org-remove-flyspell-overlays-in
5955 (match-beginning 0)
5956 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5957 (add-text-properties
5958 beg (match-end 3)
5959 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5960 '(font-lock-fontified t invisible t)
5961 '(font-lock-fontified t face org-document-info-keyword)))
5962 (add-text-properties
5963 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5964 (if (string-equal dc1 "+title:")
5965 '(font-lock-fontified t face org-document-title)
5966 '(font-lock-fontified t face org-document-info))))
5967 ((string-prefix-p "+caption" dc1)
5968 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5969 (remove-text-properties (match-beginning 0) (match-end 0)
5970 '(display t invisible t intangible t))
5971 ;; Handle short captions.
5972 (save-excursion
5973 (beginning-of-line)
5974 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5975 (add-text-properties (line-beginning-position) (match-end 1)
5976 '(font-lock-fontified t face org-meta-line))
5977 (add-text-properties (match-end 0) (line-end-position)
5978 '(font-lock-fontified t face org-block))
5980 ((member dc3 '(" " ""))
5981 (org-remove-flyspell-overlays-in beg (match-end 0))
5982 (add-text-properties
5983 beg (match-end 0)
5984 '(font-lock-fontified t face font-lock-comment-face)))
5985 (t ;; just any other in-buffer setting, but not indented
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (remove-text-properties (match-beginning 0) (match-end 0)
5988 '(display t invisible t intangible t))
5989 (add-text-properties beg (match-end 0)
5990 '(font-lock-fontified t face org-meta-line))
5991 t))))))
5993 (defun org-fontify-drawers (limit)
5994 "Fontify drawers."
5995 (when (re-search-forward org-drawer-regexp limit t)
5996 (add-text-properties
5997 (match-beginning 0) (match-end 0)
5998 '(font-lock-fontified t face org-special-keyword))
5999 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6002 (defun org-fontify-macros (limit)
6003 "Fontify macros."
6004 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6005 (add-text-properties
6006 (match-beginning 0) (match-end 0)
6007 '(font-lock-fontified t face org-macro))
6008 (when org-hide-macro-markers
6009 (add-text-properties (match-end 2) (match-beginning 2)
6010 '(invisible t))
6011 (add-text-properties (match-beginning 1) (match-end 1)
6012 '(invisible t)))
6013 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (defun org-activate-footnote-links (limit)
6017 "Add text properties for footnotes."
6018 (let ((fn (org-footnote-next-reference-or-definition limit)))
6019 (when fn
6020 (let* ((beg (nth 1 fn))
6021 (end (nth 2 fn))
6022 (label (car fn))
6023 (referencep (/= (line-beginning-position) beg)))
6024 (when (and referencep (nth 3 fn))
6025 (save-excursion
6026 (goto-char beg)
6027 (search-forward (or label "fn:"))
6028 (org-remove-flyspell-overlays-in beg (match-end 0))))
6029 (add-text-properties beg end
6030 (list 'mouse-face 'highlight
6031 'keymap org-mouse-map
6032 'help-echo
6033 (if referencep "Footnote reference"
6034 "Footnote definition")
6035 'font-lock-fontified t
6036 'font-lock-multiline t
6037 'face 'org-footnote))))))
6039 (defun org-activate-dates (limit)
6040 "Add text properties for dates."
6041 (when (and (re-search-forward org-tsr-regexp-both limit t)
6042 (not (equal (char-before (match-beginning 0)) 91)))
6043 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6044 (add-text-properties (match-beginning 0) (match-end 0)
6045 (list 'mouse-face 'highlight
6046 'keymap org-mouse-map))
6047 (org-rear-nonsticky-at (match-end 0))
6048 (when org-display-custom-times
6049 ;; If it's a date range, activate custom time for second date.
6050 (when (match-end 3)
6051 (org-display-custom-time (match-beginning 3) (match-end 3)))
6052 (org-display-custom-time (match-beginning 1) (match-end 1)))
6055 (defvar-local org-target-link-regexp nil
6056 "Regular expression matching radio targets in plain text.")
6058 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6059 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6060 border border border))
6061 "Regular expression matching a link target.")
6063 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6064 "Regular expression matching a radio target.")
6066 (defconst org-any-target-regexp
6067 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6068 "Regular expression matching any target.")
6070 (defun org-activate-target-links (limit)
6071 "Add text properties for target matches."
6072 (when org-target-link-regexp
6073 (let ((case-fold-search t))
6074 (when (re-search-forward org-target-link-regexp limit t)
6075 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6076 (add-text-properties (match-beginning 1) (match-end 1)
6077 (list 'mouse-face 'highlight
6078 'keymap org-mouse-map
6079 'help-echo "Radio target link"
6080 'org-linked-text t))
6081 (org-rear-nonsticky-at (match-end 1))
6082 t))))
6084 (defun org-update-radio-target-regexp ()
6085 "Find all radio targets in this file and update the regular expression.
6086 Also refresh fontification if needed."
6087 (interactive)
6088 (let ((old-regexp org-target-link-regexp)
6089 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6090 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6091 (targets
6092 (org-with-wide-buffer
6093 (goto-char (point-min))
6094 (let (rtn)
6095 (while (re-search-forward org-radio-target-regexp nil t)
6096 ;; Make sure point is really within the object.
6097 (backward-char)
6098 (let ((obj (org-element-context)))
6099 (when (eq (org-element-type obj) 'radio-target)
6100 (cl-pushnew (org-element-property :value obj) rtn
6101 :test #'equal))))
6102 rtn))))
6103 (setq org-target-link-regexp
6104 (and targets
6105 (concat before-re
6106 (mapconcat
6107 (lambda (x)
6108 (replace-regexp-in-string
6109 " +" "\\s-+" (regexp-quote x) t t))
6110 targets
6111 "\\|")
6112 after-re)))
6113 (unless (equal old-regexp org-target-link-regexp)
6114 ;; Clean-up cache.
6115 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6116 ((not org-target-link-regexp) old-regexp)
6118 (concat before-re
6119 (mapconcat
6120 (lambda (re)
6121 (substring re (length before-re)
6122 (- (length after-re))))
6123 (list old-regexp org-target-link-regexp)
6124 "\\|")
6125 after-re)))))
6126 (org-with-wide-buffer
6127 (goto-char (point-min))
6128 (while (re-search-forward regexp nil t)
6129 (org-element-cache-refresh (match-beginning 1)))))
6130 ;; Re fontify buffer.
6131 (when (memq 'radio org-highlight-links)
6132 (org-restart-font-lock)))))
6134 (defvar org-latex-and-related-regexp nil
6135 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6137 (defun org-compute-latex-and-related-regexp ()
6138 "Compute regular expression for LaTeX, entities and sub/superscript.
6139 Result depends on variable `org-highlight-latex-and-related'."
6140 (setq-local
6141 org-latex-and-related-regexp
6142 (let* ((re-sub
6143 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6144 ((eq org-use-sub-superscripts '{})
6145 (list org-match-substring-with-braces-regexp))
6146 (org-use-sub-superscripts (list org-match-substring-regexp))))
6147 (re-latex
6148 (when (memq 'latex org-highlight-latex-and-related)
6149 (let ((matchers (plist-get org-format-latex-options :matchers)))
6150 (delq nil
6151 (mapcar (lambda (x)
6152 (and (member (car x) matchers) (nth 1 x)))
6153 org-latex-regexps)))))
6154 (re-entities
6155 (when (memq 'entities org-highlight-latex-and-related)
6156 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6157 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6159 (defun org-do-latex-and-related (limit)
6160 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6161 LIMIT bounds the search for syntax to highlight. Stop at first
6162 highlighted object, if any. Return t if some highlighting was
6163 done, nil otherwise."
6164 (when (org-string-nw-p org-latex-and-related-regexp)
6165 (catch 'found
6166 (while (re-search-forward org-latex-and-related-regexp limit t)
6167 (unless
6168 (cl-some
6169 (lambda (f)
6170 (memq f '(org-code org-verbatim underline org-special-keyword)))
6171 (save-excursion
6172 (goto-char (1+ (match-beginning 0)))
6173 (face-at-point nil t)))
6174 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6175 '(?_ ?^))
6177 0)))
6178 (font-lock-prepend-text-property
6179 (+ offset (match-beginning 0)) (match-end 0)
6180 'face 'org-latex-and-related)
6181 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6182 '(font-lock-multiline t)))
6183 (throw 'found t)))
6184 nil)))
6186 (defun org-restart-font-lock ()
6187 "Restart `font-lock-mode', to force refontification."
6188 (when (and (boundp 'font-lock-mode) font-lock-mode)
6189 (font-lock-mode -1)
6190 (font-lock-mode 1)))
6192 (defun org-activate-tags (limit)
6193 (when (re-search-forward
6194 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6195 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6196 (add-text-properties (match-beginning 1) (match-end 1)
6197 (list 'mouse-face 'highlight
6198 'keymap org-mouse-map))
6199 (org-rear-nonsticky-at (match-end 1))
6202 (defun org-outline-level ()
6203 "Compute the outline level of the heading at point.
6205 If this is called at a normal headline, the level is the number
6206 of stars. Use `org-reduced-level' to remove the effect of
6207 `org-odd-levels'. Unlike to `org-current-level', this function
6208 takes into consideration inlinetasks."
6209 (org-with-wide-buffer
6210 (end-of-line)
6211 (if (re-search-backward org-outline-regexp-bol nil t)
6212 (1- (- (match-end 0) (match-beginning 0)))
6213 0)))
6215 (defvar org-font-lock-keywords nil)
6217 (defsubst org-re-property (property &optional literal allow-null value)
6218 "Return a regexp matching a PROPERTY line.
6220 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6221 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6222 non-nil, match properties even without a value.
6224 Match group 3 is set to the value when it exists. If there is no
6225 value and ALLOW-NULL is non-nil, it is set to the empty string.
6227 With optional argument VALUE, match only property lines with
6228 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6229 unless LITERAL is non-nil."
6230 (concat
6231 "^\\(?4:[ \t]*\\)"
6232 (format "\\(?1::\\(?2:%s\\):\\)"
6233 (if literal property (regexp-quote property)))
6234 (cond (value
6235 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6236 (if literal value (regexp-quote value))))
6237 (allow-null
6238 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6240 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6242 (defconst org-property-re
6243 (org-re-property "\\S-+" 'literal t)
6244 "Regular expression matching a property line.
6245 There are four matching groups:
6246 1: :PROPKEY: including the leading and trailing colon,
6247 2: PROPKEY without the leading and trailing colon,
6248 3: PROPVAL without leading or trailing spaces,
6249 4: the indentation of the current line,
6250 5: trailing whitespace.")
6252 (defvar org-font-lock-hook nil
6253 "Functions to be called for special font lock stuff.")
6255 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6257 (defvar org-font-lock-set-keywords-hook nil
6258 "Functions that can manipulate `org-font-lock-extra-keywords'.
6259 This is called after `org-font-lock-extra-keywords' is defined, but before
6260 it is installed to be used by font lock. This can be useful if something
6261 needs to be inserted at a specific position in the font-lock sequence.")
6263 (defun org-font-lock-hook (limit)
6264 "Run `org-font-lock-hook' within LIMIT."
6265 (run-hook-with-args 'org-font-lock-hook limit))
6267 (defun org-set-font-lock-defaults ()
6268 "Set font lock defaults for the current buffer."
6269 (let* ((em org-fontify-emphasized-text)
6270 (lk org-highlight-links)
6271 (org-font-lock-extra-keywords
6272 (list
6273 ;; Call the hook
6274 '(org-font-lock-hook)
6275 ;; Headlines
6276 `(,(if org-fontify-whole-heading-line
6277 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6278 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6279 (1 (org-get-level-face 1))
6280 (2 (org-get-level-face 2))
6281 (3 (org-get-level-face 3)))
6282 ;; Table lines
6283 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6284 (1 'org-table t))
6285 ;; Table internals
6286 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6287 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6288 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6289 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6290 ;; Drawers
6291 '(org-fontify-drawers)
6292 ;; Properties
6293 (list org-property-re
6294 '(1 'org-special-keyword t)
6295 '(3 'org-property-value t))
6296 ;; Link related fontification.
6297 '(org-activate-links)
6298 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6299 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6300 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6301 (when (memq 'footnote lk) '(org-activate-footnote-links))
6302 ;; Targets.
6303 (list org-any-target-regexp '(0 'org-target t))
6304 ;; Diary sexps.
6305 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6306 ;; Macro
6307 '(org-fontify-macros)
6308 ;; TODO keyword
6309 (list (format org-heading-keyword-regexp-format
6310 org-todo-regexp)
6311 '(2 (org-get-todo-face 2) t))
6312 ;; DONE
6313 (if org-fontify-done-headline
6314 (list (format org-heading-keyword-regexp-format
6315 (concat
6316 "\\(?:"
6317 (mapconcat 'regexp-quote org-done-keywords "\\|")
6318 "\\)"))
6319 '(2 'org-headline-done t))
6320 nil)
6321 ;; Priorities
6322 '(org-font-lock-add-priority-faces)
6323 ;; Tags
6324 '(org-font-lock-add-tag-faces)
6325 ;; Tags groups
6326 (when (and org-group-tags org-tag-groups-alist)
6327 (list (concat org-outline-regexp-bol ".+\\(:"
6328 (regexp-opt (mapcar 'car org-tag-groups-alist))
6329 ":\\).*$")
6330 '(1 'org-tag-group prepend)))
6331 ;; Special keywords
6332 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6333 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6334 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6335 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6336 ;; Emphasis
6337 (when em '(org-do-emphasis-faces))
6338 ;; Checkboxes
6339 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6340 1 'org-checkbox prepend)
6341 (when (cdr (assq 'checkbox org-list-automatic-rules))
6342 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6343 (0 (org-get-checkbox-statistics-face) t)))
6344 ;; Description list items
6345 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6346 1 'org-list-dt prepend)
6347 ;; ARCHIVEd headings
6348 (list (concat
6349 org-outline-regexp-bol
6350 "\\(.*:" org-archive-tag ":.*\\)")
6351 '(1 'org-archived prepend))
6352 ;; Specials
6353 '(org-do-latex-and-related)
6354 '(org-fontify-entities)
6355 '(org-raise-scripts)
6356 ;; Code
6357 '(org-activate-code (1 'org-code t))
6358 ;; COMMENT
6359 (list (format
6360 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6361 org-todo-regexp
6362 org-comment-string)
6363 '(9 'org-special-keyword t))
6364 ;; Blocks and meta lines
6365 '(org-fontify-meta-lines-and-blocks))))
6366 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6367 (run-hooks 'org-font-lock-set-keywords-hook)
6368 ;; Now set the full font-lock-keywords
6369 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6370 (setq-local font-lock-defaults
6371 '(org-font-lock-keywords t nil nil backward-paragraph))
6372 (kill-local-variable 'font-lock-keywords)
6373 nil))
6375 (defun org-toggle-pretty-entities ()
6376 "Toggle the composition display of entities as UTF8 characters."
6377 (interactive)
6378 (setq-local org-pretty-entities (not org-pretty-entities))
6379 (org-restart-font-lock)
6380 (if org-pretty-entities
6381 (message "Entities are now displayed as UTF8 characters")
6382 (save-restriction
6383 (widen)
6384 (decompose-region (point-min) (point-max))
6385 (message "Entities are now displayed as plain text"))))
6387 (defvar-local org-custom-properties-overlays nil
6388 "List of overlays used for custom properties.")
6390 (defun org-toggle-custom-properties-visibility ()
6391 "Display or hide properties in `org-custom-properties'."
6392 (interactive)
6393 (if org-custom-properties-overlays
6394 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6395 (setq org-custom-properties-overlays nil))
6396 (when org-custom-properties
6397 (org-with-wide-buffer
6398 (goto-char (point-min))
6399 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6400 (while (re-search-forward regexp nil t)
6401 (let ((end (cdr (save-match-data (org-get-property-block)))))
6402 (when (and end (< (point) end))
6403 ;; Hide first custom property in current drawer.
6404 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6405 (overlay-put o 'invisible t)
6406 (overlay-put o 'org-custom-property t)
6407 (push o org-custom-properties-overlays))
6408 ;; Hide additional custom properties in the same drawer.
6409 (while (re-search-forward regexp end t)
6410 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6411 (overlay-put o 'invisible t)
6412 (overlay-put o 'org-custom-property t)
6413 (push o org-custom-properties-overlays)))))
6414 ;; Each entry is limited to a single property drawer.
6415 (outline-next-heading)))))))
6417 (defun org-fontify-entities (limit)
6418 "Find an entity to fontify."
6419 (let (ee)
6420 (when org-pretty-entities
6421 (catch 'match
6422 ;; "\_ "-family is left out on purpose. Only the first one,
6423 ;; i.e., "\_ ", could be fontified anyway, and it would be
6424 ;; confusing when adding a second white space character.
6425 (while (re-search-forward
6426 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6427 limit t)
6428 (when (and (not (org-at-comment-p))
6429 (setq ee (org-entity-get (match-string 1)))
6430 (= (length (nth 6 ee)) 1))
6431 (let* ((end (if (equal (match-string 2) "{}")
6432 (match-end 2)
6433 (match-end 1))))
6434 (add-text-properties
6435 (match-beginning 0) end
6436 (list 'font-lock-fontified t))
6437 (compose-region (match-beginning 0) end
6438 (nth 6 ee) nil)
6439 (backward-char 1)
6440 (throw 'match t))))
6441 nil))))
6443 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6444 "Fontify string S like in Org mode."
6445 (with-temp-buffer
6446 (insert s)
6447 (let ((org-odd-levels-only odd-levels))
6448 (org-mode)
6449 (org-font-lock-ensure)
6450 (buffer-string))))
6452 (defvar org-m nil)
6453 (defvar org-l nil)
6454 (defvar org-f nil)
6455 (defun org-get-level-face (n)
6456 "Get the right face for match N in font-lock matching of headlines."
6457 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6458 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6459 (if org-cycle-level-faces
6460 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6461 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6462 (cond
6463 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6464 ((eq n 2) org-f)
6465 (t (unless org-level-color-stars-only org-f))))
6467 (defun org-face-from-face-or-color (context inherit face-or-color)
6468 "Create a face list that inherits INHERIT, but sets the foreground color.
6469 When FACE-OR-COLOR is not a string, just return it."
6470 (if (stringp face-or-color)
6471 (list :inherit inherit
6472 (cdr (assoc context org-faces-easy-properties))
6473 face-or-color)
6474 face-or-color))
6476 (defun org-get-todo-face (kwd)
6477 "Get the right face for a TODO keyword KWD.
6478 If KWD is a number, get the corresponding match group."
6479 (when (numberp kwd) (setq kwd (match-string kwd)))
6480 (or (org-face-from-face-or-color
6481 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6482 (and (member kwd org-done-keywords) 'org-done)
6483 'org-todo))
6485 (defun org-get-priority-face (priority)
6486 "Get the right face for PRIORITY.
6487 PRIORITY is a character."
6488 (or (org-face-from-face-or-color
6489 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6490 'org-priority))
6492 (defun org-get-tag-face (tag)
6493 "Get the right face for TAG.
6494 If TAG is a number, get the corresponding match group."
6495 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6496 (or (org-face-from-face-or-color
6497 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6498 'org-tag)))
6500 (defun org-font-lock-add-priority-faces (limit)
6501 "Add the special priority faces."
6502 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6503 (add-text-properties
6504 (match-beginning 1) (match-end 1)
6505 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6506 'font-lock-fontified t))))
6508 (defun org-font-lock-add-tag-faces (limit)
6509 "Add the special tag faces."
6510 (when (and org-tag-faces org-tags-special-faces-re)
6511 (while (re-search-forward org-tags-special-faces-re limit t)
6512 (add-text-properties (match-beginning 1) (match-end 1)
6513 (list 'face (org-get-tag-face 1)
6514 'font-lock-fontified t))
6515 (backward-char 1))))
6517 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6518 "Remove fontification and activation overlays from links."
6519 (font-lock-default-unfontify-region beg end)
6520 (let* ((buffer-undo-list t)
6521 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6522 (inhibit-modification-hooks t)
6523 deactivate-mark buffer-file-name buffer-file-truename)
6524 (decompose-region beg end)
6525 (remove-text-properties beg end
6526 '(mouse-face t keymap t org-linked-text t
6527 invisible t intangible t
6528 org-emphasis t))
6529 (org-remove-font-lock-display-properties beg end)))
6531 (defconst org-script-display '(((raise -0.3) (height 0.7))
6532 ((raise 0.3) (height 0.7))
6533 ((raise -0.5))
6534 ((raise 0.5)))
6535 "Display properties for showing superscripts and subscripts.")
6537 (defun org-remove-font-lock-display-properties (beg end)
6538 "Remove specific display properties that have been added by font lock.
6539 The will remove the raise properties that are used to show superscripts
6540 and subscripts."
6541 (let (next prop)
6542 (while (< beg end)
6543 (setq next (next-single-property-change beg 'display nil end)
6544 prop (get-text-property beg 'display))
6545 (when (member prop org-script-display)
6546 (put-text-property beg next 'display nil))
6547 (setq beg next))))
6549 (defun org-raise-scripts (limit)
6550 "Add raise properties to sub/superscripts."
6551 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6552 (re-search-forward
6553 (if (eq org-use-sub-superscripts t)
6554 org-match-substring-regexp
6555 org-match-substring-with-braces-regexp)
6556 limit t))
6557 (let* ((pos (point)) table-p comment-p
6558 (mpos (match-beginning 3))
6559 (emph-p (get-text-property mpos 'org-emphasis))
6560 (link-p (get-text-property mpos 'mouse-face))
6561 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6562 (goto-char (point-at-bol))
6563 (setq table-p (looking-at-p org-table-dataline-regexp)
6564 comment-p (looking-at-p "^[ \t]*#[ +]"))
6565 (goto-char pos)
6566 ;; Handle a_b^c
6567 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6568 (unless (or comment-p emph-p link-p keyw-p)
6569 (put-text-property (match-beginning 3) (match-end 0)
6570 'display
6571 (if (equal (char-after (match-beginning 2)) ?^)
6572 (nth (if table-p 3 1) org-script-display)
6573 (nth (if table-p 2 0) org-script-display)))
6574 (add-text-properties (match-beginning 2) (match-end 2)
6575 (list 'invisible t))
6576 (when (and (eq (char-after (match-beginning 3)) ?{)
6577 (eq (char-before (match-end 3)) ?}))
6578 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6579 (list 'invisible t))
6580 (add-text-properties (1- (match-end 3)) (match-end 3)
6581 (list 'invisible t))))
6582 t)))
6584 ;;;; Visibility cycling, including org-goto and indirect buffer
6586 ;;; Cycling
6588 (defvar-local org-cycle-global-status nil)
6589 (put 'org-cycle-global-status 'org-state t)
6590 (defvar-local org-cycle-subtree-status nil)
6591 (put 'org-cycle-subtree-status 'org-state t)
6593 (defvar org-inlinetask-min-level)
6595 ;;;###autoload
6596 (defun org-cycle (&optional arg)
6597 "TAB-action and visibility cycling for Org mode.
6599 This is the command invoked in Org mode by the `TAB' key. Its main
6600 purpose is outline visibility cycling, but it also invokes other actions
6601 in special contexts.
6603 When this function is called with a `\\[universal-argument]' prefix, rotate \
6604 the entire
6605 buffer through 3 states (global cycling)
6606 1. OVERVIEW: Show only top-level headlines.
6607 2. CONTENTS: Show all headlines of all levels, but no body text.
6608 3. SHOW ALL: Show everything.
6610 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6611 switch to the startup visibility,
6612 determined by the variable `org-startup-folded', and by any VISIBILITY
6613 properties in the buffer.
6615 With a `\\[universal-argument] \\[universal-argument] \
6616 \\[universal-argument]' prefix argument, show the entire buffer, including
6617 any drawers.
6619 When inside a table, re-align the table and move to the next field.
6621 When point is at the beginning of a headline, rotate the subtree started
6622 by this line through 3 different states (local cycling)
6623 1. FOLDED: Only the main headline is shown.
6624 2. CHILDREN: The main headline and the direct children are shown.
6625 From this state, you can move to one of the children
6626 and zoom in further.
6627 3. SUBTREE: Show the entire subtree, including body text.
6628 If there is no subtree, switch directly from CHILDREN to FOLDED.
6630 When point is at the beginning of an empty headline and the variable
6631 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6632 of the headline by demoting and promoting it to likely levels. This
6633 speeds up creation document structure by pressing `TAB' once or several
6634 times right after creating a new headline.
6636 When there is a numeric prefix, go up to a heading with level ARG, do
6637 a `show-subtree' and return to the previous cursor position. If ARG
6638 is negative, go up that many levels.
6640 When point is not at the beginning of a headline, execute the global
6641 binding for `TAB', which is re-indenting the line. See the option
6642 `org-cycle-emulate-tab' for details.
6644 As a special case, if point is at the beginning of the buffer and there is
6645 no headline in line 1, this function will act as if called with prefix arg
6646 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6647 prefix arg, but only
6648 if the variable `org-cycle-global-at-bob' is t."
6649 (interactive "P")
6650 (org-load-modules-maybe)
6651 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6652 (and org-cycle-level-after-item/entry-creation
6653 (or (org-cycle-level)
6654 (org-cycle-item-indentation))))
6655 (let* ((limit-level
6656 (or org-cycle-max-level
6657 (and (boundp 'org-inlinetask-min-level)
6658 org-inlinetask-min-level
6659 (1- org-inlinetask-min-level))))
6660 (nstars (and limit-level
6661 (if org-odd-levels-only
6662 (and limit-level (1- (* limit-level 2)))
6663 limit-level)))
6664 (org-outline-regexp
6665 (if (not (derived-mode-p 'org-mode))
6666 outline-regexp
6667 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6668 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6669 (not (looking-at org-outline-regexp))))
6670 (org-cycle-hook
6671 (if bob-special
6672 (delq 'org-optimize-window-after-visibility-change
6673 (copy-sequence org-cycle-hook))
6674 org-cycle-hook))
6675 (pos (point)))
6677 (cond
6679 ((equal arg '(16))
6680 (setq last-command 'dummy)
6681 (org-set-startup-visibility)
6682 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6684 ((equal arg '(64))
6685 (outline-show-all)
6686 (org-unlogged-message "Entire buffer visible, including drawers"))
6688 ((equal arg '(4)) (org-cycle-internal-global))
6690 ;; Try hiding block at point.
6691 ((org-hide-block-toggle-maybe))
6693 ;; Try cdlatex TAB completion
6694 ((org-try-cdlatex-tab))
6696 ;; Table: enter it or move to the next field.
6697 ((org-at-table-p 'any)
6698 (if (org-at-table.el-p)
6699 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6700 Use `\\[org-edit-special]' to edit table.el tables"))
6701 (if arg (org-table-edit-field t)
6702 (org-table-justify-field-maybe)
6703 (call-interactively 'org-table-next-field))))
6705 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6707 ;; Global cycling: delegate to `org-cycle-internal-global'.
6708 (bob-special (org-cycle-internal-global))
6710 ;; Drawers: delegate to `org-flag-drawer'.
6711 ((save-excursion
6712 (beginning-of-line 1)
6713 (looking-at org-drawer-regexp))
6714 (org-flag-drawer ; toggle block visibility
6715 (not (get-char-property (match-end 0) 'invisible))))
6717 ;; Show-subtree, ARG levels up from here.
6718 ((integerp arg)
6719 (save-excursion
6720 (org-back-to-heading)
6721 (outline-up-heading (if (< arg 0) (- arg)
6722 (- (funcall outline-level) arg)))
6723 (org-show-subtree)))
6725 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6726 ((and (featurep 'org-inlinetask)
6727 (org-inlinetask-at-task-p)
6728 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6729 (org-inlinetask-toggle-visibility))
6731 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6732 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6733 (save-excursion (move-beginning-of-line 1)
6734 (looking-at org-outline-regexp)))
6735 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6736 (org-cycle-internal-local))
6738 ;; From there: TAB emulation and template completion.
6739 (buffer-read-only (org-back-to-heading))
6741 ((run-hook-with-args-until-success
6742 'org-tab-after-check-for-cycling-hook))
6744 ((run-hook-with-args-until-success
6745 'org-tab-before-tab-emulation-hook))
6747 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6748 (or (not (bolp))
6749 (not (looking-at org-outline-regexp))))
6750 (call-interactively (global-key-binding "\t")))
6752 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6753 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6754 (or (and (eq org-cycle-emulate-tab 'white)
6755 (= (match-end 0) (point-at-eol)))
6756 (and (eq org-cycle-emulate-tab 'whitestart)
6757 (>= (match-end 0) pos))))
6759 (eq org-cycle-emulate-tab t))
6760 (call-interactively (global-key-binding "\t")))
6762 (t (save-excursion
6763 (org-back-to-heading)
6764 (org-cycle)))))))
6766 (defun org-cycle-internal-global ()
6767 "Do the global cycling action."
6768 ;; Hack to avoid display of messages for .org attachments in Gnus
6769 (let ((ga (string-match "\\*fontification" (buffer-name))))
6770 (cond
6771 ((and (eq last-command this-command)
6772 (eq org-cycle-global-status 'overview))
6773 ;; We just created the overview - now do table of contents
6774 ;; This can be slow in very large buffers, so indicate action
6775 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6776 (unless ga (org-unlogged-message "CONTENTS..."))
6777 (org-content)
6778 (unless ga (org-unlogged-message "CONTENTS...done"))
6779 (setq org-cycle-global-status 'contents)
6780 (run-hook-with-args 'org-cycle-hook 'contents))
6782 ((and (eq last-command this-command)
6783 (eq org-cycle-global-status 'contents))
6784 ;; We just showed the table of contents - now show everything
6785 (run-hook-with-args 'org-pre-cycle-hook 'all)
6786 (outline-show-all)
6787 (unless ga (org-unlogged-message "SHOW ALL"))
6788 (setq org-cycle-global-status 'all)
6789 (run-hook-with-args 'org-cycle-hook 'all))
6792 ;; Default action: go to overview
6793 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6794 (org-overview)
6795 (unless ga (org-unlogged-message "OVERVIEW"))
6796 (setq org-cycle-global-status 'overview)
6797 (run-hook-with-args 'org-cycle-hook 'overview)))))
6799 (defvar org-called-with-limited-levels nil
6800 "Non-nil when `org-with-limited-levels' is currently active.")
6802 (defun org-cycle-internal-local ()
6803 "Do the local cycling action."
6804 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6805 ;; First, determine end of headline (EOH), end of subtree or item
6806 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6807 (save-excursion
6808 (if (org-at-item-p)
6809 (progn
6810 (beginning-of-line)
6811 (setq struct (org-list-struct))
6812 (setq eoh (point-at-eol))
6813 (setq eos (org-list-get-item-end-before-blank (point) struct))
6814 (setq has-children (org-list-has-child-p (point) struct)))
6815 (org-back-to-heading)
6816 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6817 (setq eos (save-excursion (org-end-of-subtree t t)
6818 (when (bolp) (backward-char)) (point)))
6819 (setq has-children
6820 (or (save-excursion
6821 (let ((level (funcall outline-level)))
6822 (outline-next-heading)
6823 (and (org-at-heading-p t)
6824 (> (funcall outline-level) level))))
6825 (save-excursion
6826 (org-list-search-forward (org-item-beginning-re) eos t)))))
6827 ;; Determine end invisible part of buffer (EOL)
6828 (beginning-of-line 2)
6829 (while (and (not (eobp)) ;This is like `next-line'.
6830 (get-char-property (1- (point)) 'invisible))
6831 (goto-char (next-single-char-property-change (point) 'invisible))
6832 (and (eolp) (beginning-of-line 2)))
6833 (setq eol (point)))
6834 ;; Find out what to do next and set `this-command'
6835 (cond
6836 ((= eos eoh)
6837 ;; Nothing is hidden behind this heading
6838 (unless (org-before-first-heading-p)
6839 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6840 (org-unlogged-message "EMPTY ENTRY")
6841 (setq org-cycle-subtree-status nil)
6842 (save-excursion
6843 (goto-char eos)
6844 (outline-next-heading)
6845 (when (org-invisible-p) (org-flag-heading nil))))
6846 ((and (or (>= eol eos)
6847 (not (string-match "\\S-" (buffer-substring eol eos))))
6848 (or has-children
6849 (not (setq children-skipped
6850 org-cycle-skip-children-state-if-no-children))))
6851 ;; Entire subtree is hidden in one line: children view
6852 (unless (org-before-first-heading-p)
6853 (run-hook-with-args 'org-pre-cycle-hook 'children))
6854 (if (org-at-item-p)
6855 (org-list-set-item-visibility (point-at-bol) struct 'children)
6856 (org-show-entry)
6857 (org-with-limited-levels (org-show-children))
6858 ;; FIXME: This slows down the func way too much.
6859 ;; How keep drawers hidden in subtree anyway?
6860 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6861 ;; (org-cycle-hide-drawers 'subtree))
6863 ;; Fold every list in subtree to top-level items.
6864 (when (eq org-cycle-include-plain-lists 'integrate)
6865 (save-excursion
6866 (org-back-to-heading)
6867 (while (org-list-search-forward (org-item-beginning-re) eos t)
6868 (beginning-of-line 1)
6869 (let* ((struct (org-list-struct))
6870 (prevs (org-list-prevs-alist struct))
6871 (end (org-list-get-bottom-point struct)))
6872 (dolist (e (org-list-get-all-items (point) struct prevs))
6873 (org-list-set-item-visibility e struct 'folded))
6874 (goto-char (if (< end eos) end eos)))))))
6875 (org-unlogged-message "CHILDREN")
6876 (save-excursion
6877 (goto-char eos)
6878 (outline-next-heading)
6879 (when (org-invisible-p) (org-flag-heading nil)))
6880 (setq org-cycle-subtree-status 'children)
6881 (unless (org-before-first-heading-p)
6882 (run-hook-with-args 'org-cycle-hook 'children)))
6883 ((or children-skipped
6884 (and (eq last-command this-command)
6885 (eq org-cycle-subtree-status 'children)))
6886 ;; We just showed the children, or no children are there,
6887 ;; now show everything.
6888 (unless (org-before-first-heading-p)
6889 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6890 (outline-flag-region eoh eos nil)
6891 (org-unlogged-message
6892 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6893 (setq org-cycle-subtree-status 'subtree)
6894 (unless (org-before-first-heading-p)
6895 (run-hook-with-args 'org-cycle-hook 'subtree)))
6897 ;; Default action: hide the subtree.
6898 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6899 (outline-flag-region eoh eos t)
6900 (org-unlogged-message "FOLDED")
6901 (setq org-cycle-subtree-status 'folded)
6902 (unless (org-before-first-heading-p)
6903 (run-hook-with-args 'org-cycle-hook 'folded))))))
6905 ;;;###autoload
6906 (defun org-global-cycle (&optional arg)
6907 "Cycle the global visibility. For details see `org-cycle'.
6908 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6909 With a numeric prefix, show all headlines up to that level."
6910 (interactive "P")
6911 (let ((org-cycle-include-plain-lists
6912 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6913 (cond
6914 ((integerp arg)
6915 (outline-show-all)
6916 (outline-hide-sublevels arg)
6917 (setq org-cycle-global-status 'contents))
6918 ((equal arg '(4))
6919 (org-set-startup-visibility)
6920 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6922 (org-cycle '(4))))))
6924 (defun org-set-startup-visibility ()
6925 "Set the visibility required by startup options and properties."
6926 (cond
6927 ((eq org-startup-folded t)
6928 (org-overview))
6929 ((eq org-startup-folded 'content)
6930 (org-content))
6931 ((or (eq org-startup-folded 'showeverything)
6932 (eq org-startup-folded nil))
6933 (outline-show-all)))
6934 (unless (eq org-startup-folded 'showeverything)
6935 (when org-hide-block-startup (org-hide-block-all))
6936 (org-set-visibility-according-to-property 'no-cleanup)
6937 (org-cycle-hide-archived-subtrees 'all)
6938 (org-cycle-hide-drawers 'all)
6939 (org-cycle-show-empty-lines t)))
6941 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6942 "Switch subtree visibilities according to :VISIBILITY: property."
6943 (interactive)
6944 (org-with-wide-buffer
6945 (goto-char (point-min))
6946 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6947 (if (not (org-at-property-p)) (outline-next-heading)
6948 (let ((state (match-string 3)))
6949 (save-excursion
6950 (org-back-to-heading t)
6951 (outline-hide-subtree)
6952 (org-reveal)
6953 (cond
6954 ((equal state "folded")
6955 (outline-hide-subtree))
6956 ((equal state "children")
6957 (org-show-hidden-entry)
6958 (org-show-children))
6959 ((equal state "content")
6960 (save-excursion
6961 (save-restriction
6962 (org-narrow-to-subtree)
6963 (org-content))))
6964 ((member state '("all" "showall"))
6965 (outline-show-subtree)))))))
6966 (unless no-cleanup
6967 (org-cycle-hide-archived-subtrees 'all)
6968 (org-cycle-hide-drawers 'all)
6969 (org-cycle-show-empty-lines 'all))))
6971 ;; This function uses outline-regexp instead of the more fundamental
6972 ;; org-outline-regexp so that org-cycle-global works outside of Org
6973 ;; buffers, where outline-regexp is needed.
6974 (defun org-overview ()
6975 "Switch to overview mode, showing only top-level headlines.
6976 This shows all headlines with a level equal or greater than the level
6977 of the first headline in the buffer. This is important, because if the
6978 first headline is not level one, then (hide-sublevels 1) gives confusing
6979 results."
6980 (interactive)
6981 (save-excursion
6982 (let ((level
6983 (save-excursion
6984 (goto-char (point-min))
6985 (when (re-search-forward (concat "^" outline-regexp) nil t)
6986 (goto-char (match-beginning 0))
6987 (funcall outline-level)))))
6988 (and level (outline-hide-sublevels level)))))
6990 (defun org-content (&optional arg)
6991 "Show all headlines in the buffer, like a table of contents.
6992 With numerical argument N, show content up to level N."
6993 (interactive "P")
6994 (org-overview)
6995 (save-excursion
6996 ;; Visit all headings and show their offspring
6997 (and (integerp arg) (org-overview))
6998 (goto-char (point-max))
6999 (catch 'exit
7000 (while (and (progn (condition-case nil
7001 (outline-previous-visible-heading 1)
7002 (error (goto-char (point-min))))
7004 (looking-at org-outline-regexp))
7005 (if (integerp arg)
7006 (org-show-children (1- arg))
7007 (outline-show-branches))
7008 (when (bobp) (throw 'exit nil))))))
7010 (defun org-optimize-window-after-visibility-change (state)
7011 "Adjust the window after a change in outline visibility.
7012 This function is the default value of the hook `org-cycle-hook'."
7013 (when (get-buffer-window (current-buffer))
7014 (cond
7015 ((eq state 'content) nil)
7016 ((eq state 'all) nil)
7017 ((eq state 'folded) nil)
7018 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7019 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7021 (defun org-remove-empty-overlays-at (pos)
7022 "Remove outline overlays that do not contain non-white stuff."
7023 (dolist (o (overlays-at pos))
7024 (and (eq 'outline (overlay-get o 'invisible))
7025 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7026 (overlay-end o))))
7027 (delete-overlay o))))
7029 (defun org-clean-visibility-after-subtree-move ()
7030 "Fix visibility issues after moving a subtree."
7031 ;; First, find a reasonable region to look at:
7032 ;; Start two siblings above, end three below
7033 (let* ((beg (save-excursion
7034 (and (org-get-last-sibling)
7035 (org-get-last-sibling))
7036 (point)))
7037 (end (save-excursion
7038 (and (org-get-next-sibling)
7039 (org-get-next-sibling)
7040 (org-get-next-sibling))
7041 (if (org-at-heading-p)
7042 (point-at-eol)
7043 (point))))
7044 (level (looking-at "\\*+"))
7045 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7046 (save-excursion
7047 (save-restriction
7048 (narrow-to-region beg end)
7049 (when re
7050 ;; Properly fold already folded siblings
7051 (goto-char (point-min))
7052 (while (re-search-forward re nil t)
7053 (when (and (not (org-invisible-p))
7054 (save-excursion
7055 (goto-char (point-at-eol)) (org-invisible-p)))
7056 (outline-hide-entry))))
7057 (org-cycle-show-empty-lines 'overview)
7058 (org-cycle-hide-drawers 'overview)))))
7060 (defun org-cycle-show-empty-lines (state)
7061 "Show empty lines above all visible headlines.
7062 The region to be covered depends on STATE when called through
7063 `org-cycle-hook'. Lisp program can use t for STATE to get the
7064 entire buffer covered. Note that an empty line is only shown if there
7065 are at least `org-cycle-separator-lines' empty lines before the headline."
7066 (when (/= org-cycle-separator-lines 0)
7067 (save-excursion
7068 (let* ((n (abs org-cycle-separator-lines))
7069 (re (cond
7070 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7071 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7072 (t (let ((ns (number-to-string (- n 2))))
7073 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7074 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7075 beg end)
7076 (cond
7077 ((memq state '(overview contents t))
7078 (setq beg (point-min) end (point-max)))
7079 ((memq state '(children folded))
7080 (setq beg (point)
7081 end (progn (org-end-of-subtree t t)
7082 (line-beginning-position 2)))))
7083 (when beg
7084 (goto-char beg)
7085 (while (re-search-forward re end t)
7086 (unless (get-char-property (match-end 1) 'invisible)
7087 (let ((e (match-end 1))
7088 (b (if (>= org-cycle-separator-lines 0)
7089 (match-beginning 1)
7090 (save-excursion
7091 (goto-char (match-beginning 0))
7092 (skip-chars-backward " \t\n")
7093 (line-end-position)))))
7094 (outline-flag-region b e nil))))))))
7095 ;; Never hide empty lines at the end of the file.
7096 (save-excursion
7097 (goto-char (point-max))
7098 (outline-previous-heading)
7099 (outline-end-of-heading)
7100 (when (and (looking-at "[ \t\n]+")
7101 (= (match-end 0) (point-max)))
7102 (outline-flag-region (point) (match-end 0) nil))))
7104 (defun org-show-empty-lines-in-parent ()
7105 "Move to the parent and re-show empty lines before visible headlines."
7106 (save-excursion
7107 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7108 (org-cycle-show-empty-lines context))))
7110 (defun org-files-list ()
7111 "Return `org-agenda-files' list, plus all open Org files.
7112 This is useful for operations that need to scan all of a user's
7113 open and agenda-wise Org files."
7114 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7115 (dolist (buf (buffer-list))
7116 (with-current-buffer buf
7117 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7118 (cl-pushnew (expand-file-name (buffer-file-name)) files
7119 :test #'equal))))
7120 files))
7122 (defsubst org-entry-beginning-position ()
7123 "Return the beginning position of the current entry."
7124 (save-excursion (org-back-to-heading t) (point)))
7126 (defsubst org-entry-end-position ()
7127 "Return the end position of the current entry."
7128 (save-excursion (outline-next-heading) (point)))
7130 (defun org-cycle-hide-drawers (state &optional exceptions)
7131 "Re-hide all drawers after a visibility state change.
7132 STATE should be one of the symbols listed in the docstring of
7133 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7134 a list of strings specifying which drawers should not be hidden."
7135 (when (and (derived-mode-p 'org-mode)
7136 (not (memq state '(overview folded contents))))
7137 (save-excursion
7138 (let* ((globalp (eq state 'all))
7139 (beg (if globalp (point-min) (point)))
7140 (end (if globalp (point-max)
7141 (if (eq state 'children)
7142 (save-excursion (outline-next-heading) (point))
7143 (org-end-of-subtree t)))))
7144 (goto-char beg)
7145 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7146 (unless (member-ignore-case (match-string 1) exceptions)
7147 (let ((drawer (org-element-at-point)))
7148 (when (memq (org-element-type drawer) '(drawer property-drawer))
7149 (org-flag-drawer t drawer)
7150 ;; Make sure to skip drawer entirely or we might flag
7151 ;; it another time when matching its ending line with
7152 ;; `org-drawer-regexp'.
7153 (goto-char (org-element-property :end drawer))))))))))
7155 (defun org-flag-drawer (flag &optional element)
7156 "When FLAG is non-nil, hide the drawer we are at.
7157 Otherwise make it visible. When optional argument ELEMENT is
7158 a parsed drawer, as returned by `org-element-at-point', hide or
7159 show that drawer instead."
7160 (let ((drawer (or element
7161 (and (save-excursion
7162 (beginning-of-line)
7163 (looking-at-p org-drawer-regexp))
7164 (org-element-at-point)))))
7165 (when (memq (org-element-type drawer) '(drawer property-drawer))
7166 (let ((post (org-element-property :post-affiliated drawer)))
7167 (save-excursion
7168 (outline-flag-region
7169 (progn (goto-char post) (line-end-position))
7170 (progn (goto-char (org-element-property :end drawer))
7171 (skip-chars-backward " \r\t\n")
7172 (line-end-position))
7173 flag))
7174 ;; When the drawer is hidden away, make sure point lies in
7175 ;; a visible part of the buffer.
7176 (when (and flag (> (line-beginning-position) post))
7177 (goto-char post))))))
7179 (defun org-subtree-end-visible-p ()
7180 "Is the end of the current subtree visible?"
7181 (pos-visible-in-window-p
7182 (save-excursion (org-end-of-subtree t) (point))))
7184 (defun org-first-headline-recenter ()
7185 "Move cursor to the first headline and recenter the headline."
7186 (let ((window (get-buffer-window)))
7187 (when window
7188 (goto-char (point-min))
7189 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7190 (set-window-start window (line-beginning-position))))))
7192 ;;; Saving and restoring visibility
7194 (defun org-outline-overlay-data (&optional use-markers)
7195 "Return a list of the locations of all outline overlays.
7196 These are overlays with the `invisible' property value `outline'.
7197 The return value is a list of cons cells, with start and stop
7198 positions for each overlay.
7199 If USE-MARKERS is set, return the positions as markers."
7200 (let (beg end)
7201 (org-with-wide-buffer
7202 (delq nil
7203 (mapcar (lambda (o)
7204 (when (eq (overlay-get o 'invisible) 'outline)
7205 (setq beg (overlay-start o)
7206 end (overlay-end o))
7207 (and beg end (> end beg)
7208 (if use-markers
7209 (cons (copy-marker beg)
7210 (copy-marker end t))
7211 (cons beg end)))))
7212 (overlays-in (point-min) (point-max)))))))
7214 (defun org-set-outline-overlay-data (data)
7215 "Create visibility overlays for all positions in DATA.
7216 DATA should have been made by `org-outline-overlay-data'."
7217 (org-with-wide-buffer
7218 (outline-show-all)
7219 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7221 ;;; Folding of blocks
7223 (defvar-local org-hide-block-overlays nil
7224 "Overlays hiding blocks.")
7226 (defun org-block-map (function &optional start end)
7227 "Call FUNCTION at the head of all source blocks in the current buffer.
7228 Optional arguments START and END can be used to limit the range."
7229 (let ((start (or start (point-min)))
7230 (end (or end (point-max))))
7231 (save-excursion
7232 (goto-char start)
7233 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7234 (save-excursion
7235 (save-match-data
7236 (goto-char (match-beginning 0))
7237 (funcall function)))))))
7239 (defun org-hide-block-toggle-all ()
7240 "Toggle the visibility of all blocks in the current buffer."
7241 (org-block-map 'org-hide-block-toggle))
7243 (defun org-hide-block-all ()
7244 "Fold all blocks in the current buffer."
7245 (interactive)
7246 (org-show-block-all)
7247 (org-block-map 'org-hide-block-toggle-maybe))
7249 (defun org-show-block-all ()
7250 "Unfold all blocks in the current buffer."
7251 (interactive)
7252 (mapc #'delete-overlay org-hide-block-overlays)
7253 (setq org-hide-block-overlays nil))
7255 (defun org-hide-block-toggle-maybe ()
7256 "Toggle visibility of block at point.
7257 Unlike to `org-hide-block-toggle', this function does not throw
7258 an error. Return a non-nil value when toggling is successful."
7259 (interactive)
7260 (ignore-errors (org-hide-block-toggle)))
7262 (defun org-hide-block-toggle (&optional force)
7263 "Toggle the visibility of the current block.
7264 When optional argument FORCE is `off', make block visible. If it
7265 is non-nil, hide it unconditionally. Throw an error when not at
7266 a block. Return a non-nil value when toggling is successful."
7267 (interactive)
7268 (let ((element (org-element-at-point)))
7269 (unless (memq (org-element-type element)
7270 '(center-block comment-block dynamic-block example-block
7271 export-block quote-block special-block
7272 src-block verse-block))
7273 (user-error "Not at a block"))
7274 (let* ((start (save-excursion
7275 (goto-char (org-element-property :post-affiliated element))
7276 (line-end-position)))
7277 (end (save-excursion
7278 (goto-char (org-element-property :end element))
7279 (skip-chars-backward " \r\t\n")
7280 (line-end-position)))
7281 (overlays (overlays-at start)))
7282 (cond
7283 ;; Do nothing when not before or at the block opening line or
7284 ;; at the block closing line.
7285 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7286 ((and (not (eq force 'off))
7287 (not (memq t (mapcar
7288 (lambda (o)
7289 (eq (overlay-get o 'invisible) 'org-hide-block))
7290 overlays))))
7291 (let ((ov (make-overlay start end)))
7292 (overlay-put ov 'invisible 'org-hide-block)
7293 ;; Make the block accessible to `isearch'.
7294 (overlay-put
7295 ov 'isearch-open-invisible
7296 (lambda (ov)
7297 (when (memq ov org-hide-block-overlays)
7298 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7299 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7300 (delete-overlay ov))))
7301 (push ov org-hide-block-overlays)
7302 ;; When the block is hidden away, make sure point is left in
7303 ;; a visible part of the buffer.
7304 (when (> (line-beginning-position) start)
7305 (goto-char start)
7306 (beginning-of-line))
7307 ;; Signal successful toggling.
7309 ((or (not force) (eq force 'off))
7310 (dolist (ov overlays t)
7311 (when (memq ov org-hide-block-overlays)
7312 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7313 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7314 (delete-overlay ov))))))))
7316 ;; Remove overlays when changing major mode
7317 (add-hook 'org-mode-hook
7318 (lambda () (add-hook 'change-major-mode-hook
7319 'org-show-block-all 'append 'local)))
7321 ;;; Indirect buffer display of subtrees
7323 (defvar org-indirect-dedicated-frame nil
7324 "This is the frame being used for indirect tree display.")
7325 (defvar org-last-indirect-buffer nil)
7327 (defun org-tree-to-indirect-buffer (&optional arg)
7328 "Create indirect buffer and narrow it to current subtree.
7330 With a numerical prefix ARG, go up to this level and then take that tree.
7331 If ARG is negative, go up that many levels.
7333 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7334 indirect buffer previously made with this command, to avoid proliferation of
7335 indirect buffers. However, when you call the command with a \
7336 `\\[universal-argument]' prefix, or
7337 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7338 so that you can work with several indirect buffers at the same time. If
7339 `org-indirect-buffer-display' is `dedicated-frame', the \
7340 `\\[universal-argument]' prefix also
7341 requests that a new frame be made for the new buffer, so that the dedicated
7342 frame is not changed."
7343 (interactive "P")
7344 (let ((cbuf (current-buffer))
7345 (cwin (selected-window))
7346 (pos (point))
7347 beg end level heading ibuf)
7348 (save-excursion
7349 (org-back-to-heading t)
7350 (when (numberp arg)
7351 (setq level (org-outline-level))
7352 (when (< arg 0) (setq arg (+ level arg)))
7353 (while (> (setq level (org-outline-level)) arg)
7354 (org-up-heading-safe)))
7355 (setq beg (point)
7356 heading (org-get-heading 'no-tags))
7357 (org-end-of-subtree t t)
7358 (when (org-at-heading-p) (backward-char 1))
7359 (setq end (point)))
7360 (when (and (buffer-live-p org-last-indirect-buffer)
7361 (not (eq org-indirect-buffer-display 'new-frame))
7362 (not arg))
7363 (kill-buffer org-last-indirect-buffer))
7364 (setq ibuf (org-get-indirect-buffer cbuf heading)
7365 org-last-indirect-buffer ibuf)
7366 (cond
7367 ((or (eq org-indirect-buffer-display 'new-frame)
7368 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7369 (select-frame (make-frame))
7370 (delete-other-windows)
7371 (pop-to-buffer-same-window ibuf)
7372 (org-set-frame-title heading))
7373 ((eq org-indirect-buffer-display 'dedicated-frame)
7374 (raise-frame
7375 (select-frame (or (and org-indirect-dedicated-frame
7376 (frame-live-p org-indirect-dedicated-frame)
7377 org-indirect-dedicated-frame)
7378 (setq org-indirect-dedicated-frame (make-frame)))))
7379 (delete-other-windows)
7380 (pop-to-buffer-same-window ibuf)
7381 (org-set-frame-title (concat "Indirect: " heading)))
7382 ((eq org-indirect-buffer-display 'current-window)
7383 (pop-to-buffer-same-window ibuf))
7384 ((eq org-indirect-buffer-display 'other-window)
7385 (pop-to-buffer ibuf))
7386 (t (error "Invalid value")))
7387 (narrow-to-region beg end)
7388 (outline-show-all)
7389 (goto-char pos)
7390 (run-hook-with-args 'org-cycle-hook 'all)
7391 (and (window-live-p cwin) (select-window cwin))))
7393 (defun org-get-indirect-buffer (&optional buffer heading)
7394 (setq buffer (or buffer (current-buffer)))
7395 (let ((n 1) (base (buffer-name buffer)) bname)
7396 (while (buffer-live-p
7397 (get-buffer
7398 (setq bname
7399 (concat base "-"
7400 (if heading (concat heading "-" (number-to-string n))
7401 (number-to-string n))))))
7402 (setq n (1+ n)))
7403 (condition-case nil
7404 (make-indirect-buffer buffer bname 'clone)
7405 (error (make-indirect-buffer buffer bname)))))
7407 (defun org-set-frame-title (title)
7408 "Set the title of the current frame to the string TITLE."
7409 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7411 ;;;; Structure editing
7413 ;;; Inserting headlines
7415 (defun org--line-empty-p (n)
7416 "Is the Nth next line empty?
7418 Counts the current line as N = 1 and the previous line as N = 0;
7419 see `beginning-of-line'."
7420 (save-excursion
7421 (and (not (bobp))
7422 (or (beginning-of-line n) t)
7423 (save-match-data
7424 (looking-at "[ \t]*$")))))
7426 (defun org-previous-line-empty-p ()
7427 "Is the previous line a blank line?
7428 When NEXT is non-nil, check the next line instead."
7429 (org--line-empty-p 0))
7431 (defun org-next-line-empty-p ()
7432 "Is the previous line a blank line?
7433 When NEXT is non-nil, check the next line instead."
7434 (org--line-empty-p 2))
7436 (defun org--blank-before-heading-p (&optional parent)
7437 "Non-nil when an empty line should precede a new heading here.
7438 When optional argument PARENT is non-nil, consider parent
7439 headline instead of current one."
7440 (pcase (assq 'heading org-blank-before-new-entry)
7441 (`(heading . auto)
7442 (save-excursion
7443 (org-with-limited-levels
7444 (unless (and (org-before-first-heading-p)
7445 (not (outline-next-heading)))
7446 (org-back-to-heading t)
7447 (when parent (org-up-heading-safe))
7448 (cond ((not (bobp))
7449 (org-previous-line-empty-p))
7450 ((outline-next-heading)
7451 (org-previous-line-empty-p))
7452 ;; Ignore trailing spaces on last buffer line.
7453 ((progn (skip-chars-backward " \t") (bolp))
7454 (org-previous-line-empty-p))
7455 (t nil))))))
7456 (`(heading . ,value) value)
7457 (_ nil)))
7459 (defun org-insert-heading (&optional arg invisible-ok top)
7460 "Insert a new heading or an item with the same depth at point.
7462 If point is at the beginning of a heading, insert a new heading
7463 or a new headline above the current one. When at the beginning
7464 of a regular line of text, turn it into a heading.
7466 If point is in the middle of a line, split it and create a new
7467 headline with the text in the current line after point (see
7468 `org-M-RET-may-split-line' on how to modify this behavior). As
7469 a special case, on a headline, splitting can only happen on the
7470 title itself. E.g., this excludes breaking stars or tags.
7472 With a `\\[universal-argument]' prefix, set \
7473 `org-insert-heading-respect-content' to
7474 a non-nil value for the duration of the command. This forces the
7475 insertion of a heading after the current subtree, independently
7476 on the location of point.
7478 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7479 insert the heading at the end of the tree
7480 above the current heading. For example, if point is within a
7481 2nd-level heading, then it will insert a 2nd-level heading at
7482 the end of the 1st-level parent subtree.
7484 When INVISIBLE-OK is set, stop at invisible headlines when going
7485 back. This is important for non-interactive uses of the
7486 command.
7488 When optional argument TOP is non-nil, insert a level 1 heading,
7489 unconditionally."
7490 (interactive "P")
7491 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7492 (level (org-current-level))
7493 (stars (make-string (if (and level (not top)) level 1) ?*)))
7494 (cond
7495 ((or org-insert-heading-respect-content
7496 (member arg '((4) (16)))
7497 (and (not invisible-ok)
7498 (invisible-p (max (1- (point)) (point-min)))))
7499 ;; Position point at the location of insertion.
7500 (if (not level) ;before first headline
7501 (org-with-limited-levels (outline-next-heading))
7502 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7503 ;; is nil.
7504 (org-with-limited-levels (org-back-to-heading invisible-ok))
7505 (cond ((equal arg '(16))
7506 (org-up-heading-safe)
7507 (org-end-of-subtree t t))
7509 (org-end-of-subtree t t))))
7510 (unless (bolp) (insert "\n")) ;ensure final newline
7511 (unless (and blank? (org-previous-line-empty-p))
7512 (org-N-empty-lines-before-current (if blank? 1 0)))
7513 (insert stars " \n")
7514 (forward-char -1))
7515 ;; At a headline...
7516 ((org-at-heading-p)
7517 (cond ((bolp)
7518 (when blank? (save-excursion (insert "\n")))
7519 (save-excursion (insert stars " \n"))
7520 (unless (and blank? (org-previous-line-empty-p))
7521 (org-N-empty-lines-before-current (if blank? 1 0)))
7522 (end-of-line))
7523 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7524 (org-match-line org-complex-heading-regexp)
7525 (org-pos-in-match-range (point) 4))
7526 ;; Grab the text that should moved to the new headline.
7527 ;; Preserve tags.
7528 (let ((split (delete-and-extract-region (point) (match-end 4))))
7529 (if (looking-at "[ \t]*$") (replace-match "")
7530 (org-set-tags nil t))
7531 (end-of-line)
7532 (when blank? (insert "\n"))
7533 (insert "\n" stars " ")
7534 (when (org-string-nw-p split) (insert split))
7535 (when (eobp) (save-excursion (insert "\n")))))
7537 (end-of-line)
7538 (when blank? (insert "\n"))
7539 (insert "\n" stars " ")
7540 (when (eobp) (save-excursion (insert "\n"))))))
7541 ;; On regular text, turn line into a headline or split, if
7542 ;; appropriate.
7543 ((bolp)
7544 (insert stars " ")
7545 (unless (and blank? (org-previous-line-empty-p))
7546 (org-N-empty-lines-before-current (if blank? 1 0))))
7548 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7549 (end-of-line))
7550 (insert "\n" stars " ")
7551 (unless (and blank? (org-previous-line-empty-p))
7552 (org-N-empty-lines-before-current (if blank? 1 0))))))
7553 (run-hooks 'org-insert-heading-hook))
7555 (defun org-N-empty-lines-before-current (n)
7556 "Make the number of empty lines before current exactly N.
7557 So this will delete or add empty lines."
7558 (let ((column (current-column)))
7559 (beginning-of-line)
7560 (unless (bobp)
7561 (let ((start (save-excursion
7562 (skip-chars-backward " \r\t\n")
7563 (line-end-position))))
7564 (delete-region start (line-end-position 0))))
7565 (insert (make-string n ?\n))
7566 (move-to-column column)))
7568 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7569 "Return the heading of the current entry, without the stars.
7570 When NO-TAGS is non-nil, don't include tags.
7571 When NO-TODO is non-nil, don't include TODO keywords.
7572 When NO-PRIORITY is non-nil, don't include priority cookie.
7573 When NO-COMMENT is non-nil, don't include COMMENT string."
7574 (save-excursion
7575 (org-back-to-heading t)
7576 (let ((case-fold-search nil))
7577 (looking-at org-complex-heading-regexp)
7578 (let ((todo (and (not no-todo) (match-string 2)))
7579 (priority (and (not no-priority) (match-string 3)))
7580 (headline (pcase (match-string 4)
7581 (`nil "")
7582 ((and (guard no-comment) h)
7583 (replace-regexp-in-string
7584 (eval-when-compile
7585 (format "\\`%s[ \t]+" org-comment-string))
7586 "" h))
7587 (h h)))
7588 (tags (and (not no-tags) (match-string 5))))
7589 (mapconcat #'identity
7590 (delq nil (list todo priority headline tags))
7591 " ")))))
7593 (defvar orgstruct-mode) ; defined below
7595 (defun org-heading-components ()
7596 "Return the components of the current heading.
7597 This is a list with the following elements:
7598 - the level as an integer
7599 - the reduced level, different if `org-odd-levels-only' is set.
7600 - the TODO keyword, or nil
7601 - the priority character, like ?A, or nil if no priority is given
7602 - the headline text itself, or the tags string if no headline text
7603 - the tags string, or nil."
7604 (save-excursion
7605 (org-back-to-heading t)
7606 (when (let (case-fold-search)
7607 (looking-at
7608 (if orgstruct-mode
7609 org-heading-regexp
7610 org-complex-heading-regexp)))
7611 (if orgstruct-mode
7612 (list (length (match-string 1))
7613 (org-reduced-level (length (match-string 1)))
7616 (match-string 2)
7617 nil)
7618 (list (length (match-string 1))
7619 (org-reduced-level (length (match-string 1)))
7620 (match-string-no-properties 2)
7621 (and (match-end 3) (aref (match-string 3) 2))
7622 (match-string-no-properties 4)
7623 (match-string-no-properties 5))))))
7625 (defun org-get-entry ()
7626 "Get the entry text, after heading, entire subtree."
7627 (save-excursion
7628 (org-back-to-heading t)
7629 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7631 (defun org-edit-headline (&optional heading)
7632 "Edit the current headline.
7633 Set it to HEADING when provided."
7634 (interactive)
7635 (org-with-wide-buffer
7636 (org-back-to-heading t)
7637 (let ((case-fold-search nil))
7638 (when (looking-at org-complex-heading-regexp)
7639 (let* ((old (match-string-no-properties 4))
7640 (new (save-match-data
7641 (org-trim (or heading (read-string "Edit: " old))))))
7642 (unless (equal old new)
7643 (if old (replace-match new t t nil 4)
7644 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7645 (insert " " new))
7646 (org-set-tags nil t)
7647 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7649 (defun org-insert-heading-after-current ()
7650 "Insert a new heading with same level as current, after current subtree."
7651 (interactive)
7652 (org-back-to-heading)
7653 (org-insert-heading)
7654 (org-move-subtree-down)
7655 (end-of-line 1))
7657 (defun org-insert-heading-respect-content (&optional invisible-ok)
7658 "Insert heading with `org-insert-heading-respect-content' set to t."
7659 (interactive)
7660 (org-insert-heading '(4) invisible-ok))
7662 (defun org-insert-todo-heading-respect-content (&optional force-state)
7663 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7664 (interactive)
7665 (org-insert-todo-heading force-state '(4)))
7667 (defun org-insert-todo-heading (arg &optional force-heading)
7668 "Insert a new heading with the same level and TODO state as current heading.
7670 If the heading has no TODO state, or if the state is DONE, use
7671 the first state (TODO by default). Also with one prefix arg,
7672 force first state. With two prefix args, force inserting at the
7673 end of the parent subtree.
7675 When called at a plain list item, insert a new item with an
7676 unchecked check box."
7677 (interactive "P")
7678 (when (or force-heading (not (org-insert-item 'checkbox)))
7679 (org-insert-heading (or (and (equal arg '(16)) '(16))
7680 force-heading))
7681 (save-excursion
7682 (org-forward-heading-same-level -1)
7683 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7684 (let* ((new-mark-x
7685 (if (or (equal arg '(4))
7686 (not (match-beginning 2))
7687 (member (match-string 2) org-done-keywords))
7688 (car org-todo-keywords-1)
7689 (match-string 2)))
7690 (new-mark
7692 (run-hook-with-args-until-success
7693 'org-todo-get-default-hook new-mark-x nil)
7694 new-mark-x)))
7695 (beginning-of-line 1)
7696 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7697 (if org-treat-insert-todo-heading-as-state-change
7698 (org-todo new-mark)
7699 (insert new-mark " "))))
7700 (when org-provide-todo-statistics
7701 (org-update-parent-todo-statistics))))
7703 (defun org-insert-subheading (arg)
7704 "Insert a new subheading and demote it.
7705 Works for outline headings and for plain lists alike."
7706 (interactive "P")
7707 (org-insert-heading arg)
7708 (cond
7709 ((org-at-heading-p) (org-do-demote))
7710 ((org-at-item-p) (org-indent-item))))
7712 (defun org-insert-todo-subheading (arg)
7713 "Insert a new subheading with TODO keyword or checkbox and demote it.
7714 Works for outline headings and for plain lists alike."
7715 (interactive "P")
7716 (org-insert-todo-heading arg)
7717 (cond
7718 ((org-at-heading-p) (org-do-demote))
7719 ((org-at-item-p) (org-indent-item))))
7721 ;;; Promotion and Demotion
7723 (defvar org-after-demote-entry-hook nil
7724 "Hook run after an entry has been demoted.
7725 The cursor will be at the beginning of the entry.
7726 When a subtree is being demoted, the hook will be called for each node.")
7728 (defvar org-after-promote-entry-hook nil
7729 "Hook run after an entry has been promoted.
7730 The cursor will be at the beginning of the entry.
7731 When a subtree is being promoted, the hook will be called for each node.")
7733 (defun org-promote-subtree ()
7734 "Promote the entire subtree.
7735 See also `org-promote'."
7736 (interactive)
7737 (save-excursion
7738 (org-with-limited-levels (org-map-tree 'org-promote)))
7739 (org-fix-position-after-promote))
7741 (defun org-demote-subtree ()
7742 "Demote the entire subtree.
7743 See `org-demote' and `org-promote'."
7744 (interactive)
7745 (save-excursion
7746 (org-with-limited-levels (org-map-tree 'org-demote)))
7747 (org-fix-position-after-promote))
7749 (defun org-do-promote ()
7750 "Promote the current heading higher up the tree.
7751 If the region is active in `transient-mark-mode', promote all
7752 headings in the region."
7753 (interactive)
7754 (save-excursion
7755 (if (org-region-active-p)
7756 (org-map-region 'org-promote (region-beginning) (region-end))
7757 (org-promote)))
7758 (org-fix-position-after-promote))
7760 (defun org-do-demote ()
7761 "Demote the current heading lower down the tree.
7762 If the region is active in `transient-mark-mode', demote all
7763 headings in the region."
7764 (interactive)
7765 (save-excursion
7766 (if (org-region-active-p)
7767 (org-map-region 'org-demote (region-beginning) (region-end))
7768 (org-demote)))
7769 (org-fix-position-after-promote))
7771 (defun org-fix-position-after-promote ()
7772 "Fix cursor position and indentation after demoting/promoting."
7773 (let ((pos (point)))
7774 (when (save-excursion
7775 (beginning-of-line)
7776 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7777 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7778 (cond ((eobp) (insert " "))
7779 ((eolp) (insert " "))
7780 ((equal (char-after) ?\s) (forward-char 1))))))
7782 (defun org-current-level ()
7783 "Return the level of the current entry, or nil if before the first headline.
7784 The level is the number of stars at the beginning of the
7785 headline. Use `org-reduced-level' to remove the effect of
7786 `org-odd-levels'. Unlike to `org-outline-level', this function
7787 ignores inlinetasks."
7788 (let ((level (org-with-limited-levels (org-outline-level))))
7789 (and (> level 0) level)))
7791 (defun org-get-previous-line-level ()
7792 "Return the outline depth of the last headline before the current line.
7793 Returns 0 for the first headline in the buffer, and nil if before the
7794 first headline."
7795 (and (org-current-level)
7796 (or (and (/= (line-beginning-position) (point-min))
7797 (save-excursion (beginning-of-line 0) (org-current-level)))
7798 0)))
7800 (defun org-reduced-level (l)
7801 "Compute the effective level of a heading.
7802 This takes into account the setting of `org-odd-levels-only'."
7803 (cond
7804 ((zerop l) 0)
7805 (org-odd-levels-only (1+ (floor (/ l 2))))
7806 (t l)))
7808 (defun org-level-increment ()
7809 "Return the number of stars that will be added or removed at a
7810 time to headlines when structure editing, based on the value of
7811 `org-odd-levels-only'."
7812 (if org-odd-levels-only 2 1))
7814 (defun org-get-valid-level (level &optional change)
7815 "Rectify a level change under the influence of `org-odd-levels-only'.
7816 LEVEL is a current level, CHANGE is by how much the level should
7817 be modified. Even if CHANGE is nil, LEVEL may be returned
7818 modified because even level numbers will become the next higher
7819 odd number. Returns values greater than 0."
7820 (if org-odd-levels-only
7821 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7822 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7823 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7824 (max 1 (+ level (or change 0)))))
7826 (defun org-promote ()
7827 "Promote the current heading higher up the tree."
7828 (org-with-wide-buffer
7829 (org-back-to-heading t)
7830 (let* ((after-change-functions (remq 'flyspell-after-change-function
7831 after-change-functions))
7832 (level (save-match-data (funcall outline-level)))
7833 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7834 (diff (abs (- level (length up-head) -1))))
7835 (cond
7836 ((and (= level 1) org-allow-promoting-top-level-subtree)
7837 (replace-match "# " nil t))
7838 ((= level 1)
7839 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7840 (t (replace-match up-head nil t)))
7841 (unless (= level 1)
7842 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7843 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7844 (run-hooks 'org-after-promote-entry-hook))))
7846 (defun org-demote ()
7847 "Demote the current heading lower down the tree."
7848 (org-with-wide-buffer
7849 (org-back-to-heading t)
7850 (let* ((after-change-functions (remq 'flyspell-after-change-function
7851 after-change-functions))
7852 (level (save-match-data (funcall outline-level)))
7853 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7854 (diff (abs (- level (length down-head) -1))))
7855 (replace-match down-head nil t)
7856 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7857 (when org-adapt-indentation (org-fixup-indentation diff))
7858 (run-hooks 'org-after-demote-entry-hook))))
7860 (defun org-cycle-level ()
7861 "Cycle the level of an empty headline through possible states.
7862 This goes first to child, then to parent, level, then up the hierarchy.
7863 After top level, it switches back to sibling level."
7864 (interactive)
7865 (let ((org-adapt-indentation nil))
7866 (when (org-point-at-end-of-empty-headline)
7867 (setq this-command 'org-cycle-level) ; Only needed for caching
7868 (let ((cur-level (org-current-level))
7869 (prev-level (org-get-previous-line-level)))
7870 (cond
7871 ;; If first headline in file, promote to top-level.
7872 ((= prev-level 0)
7873 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7874 do (org-do-promote)))
7875 ;; If same level as prev, demote one.
7876 ((= prev-level cur-level)
7877 (org-do-demote))
7878 ;; If parent is top-level, promote to top level if not already.
7879 ((= prev-level 1)
7880 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7881 do (org-do-promote)))
7882 ;; If top-level, return to prev-level.
7883 ((= cur-level 1)
7884 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7885 do (org-do-demote)))
7886 ;; If less than prev-level, promote one.
7887 ((< cur-level prev-level)
7888 (org-do-promote))
7889 ;; If deeper than prev-level, promote until higher than
7890 ;; prev-level.
7891 ((> cur-level prev-level)
7892 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7893 do (org-do-promote))))
7894 t))))
7896 (defun org-map-tree (fun)
7897 "Call FUN for every heading underneath the current one."
7898 (org-back-to-heading t)
7899 (let ((level (funcall outline-level)))
7900 (save-excursion
7901 (funcall fun)
7902 (while (and (progn
7903 (outline-next-heading)
7904 (> (funcall outline-level) level))
7905 (not (eobp)))
7906 (funcall fun)))))
7908 (defun org-map-region (fun beg end)
7909 "Call FUN for every heading between BEG and END."
7910 (let ((org-ignore-region t))
7911 (save-excursion
7912 (setq end (copy-marker end))
7913 (goto-char beg)
7914 (when (and (re-search-forward org-outline-regexp-bol nil t)
7915 (< (point) end))
7916 (funcall fun))
7917 (while (and (progn
7918 (outline-next-heading)
7919 (< (point) end))
7920 (not (eobp)))
7921 (funcall fun)))))
7923 (defun org-fixup-indentation (diff)
7924 "Change the indentation in the current entry by DIFF.
7926 DIFF is an integer. Indentation is done according to the
7927 following rules:
7929 - Planning information and property drawers are always indented
7930 according to the new level of the headline;
7932 - Footnote definitions and their contents are ignored;
7934 - Inlinetasks' boundaries are not shifted;
7936 - Empty lines are ignored;
7938 - Other lines' indentation are shifted by DIFF columns, unless
7939 it would introduce a structural change in the document, in
7940 which case no shifting is done at all.
7942 Assume point is at a heading or an inlinetask beginning."
7943 (org-with-wide-buffer
7944 (narrow-to-region (line-beginning-position)
7945 (save-excursion
7946 (if (org-with-limited-levels (org-at-heading-p))
7947 (org-with-limited-levels (outline-next-heading))
7948 (org-inlinetask-goto-end))
7949 (point)))
7950 (forward-line)
7951 ;; Indent properly planning info and property drawer.
7952 (when (looking-at-p org-planning-line-re)
7953 (org-indent-line)
7954 (forward-line))
7955 (when (looking-at org-property-drawer-re)
7956 (goto-char (match-end 0))
7957 (forward-line)
7958 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7959 (catch 'no-shift
7960 (when (zerop diff) (throw 'no-shift nil))
7961 ;; If DIFF is negative, first check if a shift is possible at all
7962 ;; (e.g., it doesn't break structure). This can only happen if
7963 ;; some contents are not properly indented.
7964 (let ((case-fold-search t))
7965 (when (< diff 0)
7966 (let ((diff (- diff))
7967 (forbidden-re (concat org-outline-regexp
7968 "\\|"
7969 (substring org-footnote-definition-re 1))))
7970 (save-excursion
7971 (while (not (eobp))
7972 (cond
7973 ((looking-at-p "[ \t]*$") (forward-line))
7974 ((and (looking-at-p org-footnote-definition-re)
7975 (let ((e (org-element-at-point)))
7976 (and (eq (org-element-type e) 'footnote-definition)
7977 (goto-char (org-element-property :end e))))))
7978 ((looking-at-p org-outline-regexp) (forward-line))
7979 ;; Give up if shifting would move before column 0 or
7980 ;; if it would introduce a headline or a footnote
7981 ;; definition.
7983 (skip-chars-forward " \t")
7984 (let ((ind (current-column)))
7985 (when (or (< ind diff)
7986 (and (= ind diff) (looking-at-p forbidden-re)))
7987 (throw 'no-shift nil)))
7988 ;; Ignore contents of example blocks and source
7989 ;; blocks if their indentation is meant to be
7990 ;; preserved. Jump to block's closing line.
7991 (beginning-of-line)
7992 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7993 (let ((e (org-element-at-point)))
7994 (and (memq (org-element-type e)
7995 '(example-block src-block))
7996 (or org-src-preserve-indentation
7997 (org-element-property :preserve-indent e))
7998 (goto-char (org-element-property :end e))
7999 (progn (skip-chars-backward " \r\t\n")
8000 (beginning-of-line)
8001 t))))
8002 (forward-line))))))))
8003 ;; Shift lines but footnote definitions, inlinetasks boundaries
8004 ;; by DIFF. Also skip contents of source or example blocks
8005 ;; when indentation is meant to be preserved.
8006 (while (not (eobp))
8007 (cond
8008 ((and (looking-at-p org-footnote-definition-re)
8009 (let ((e (org-element-at-point)))
8010 (and (eq (org-element-type e) 'footnote-definition)
8011 (goto-char (org-element-property :end e))))))
8012 ((looking-at-p org-outline-regexp) (forward-line))
8013 ((looking-at-p "[ \t]*$") (forward-line))
8015 (indent-line-to (+ (org-get-indentation) diff))
8016 (beginning-of-line)
8017 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8018 (let ((e (org-element-at-point)))
8019 (and (memq (org-element-type e)
8020 '(example-block src-block))
8021 (or org-src-preserve-indentation
8022 (org-element-property :preserve-indent e))
8023 (goto-char (org-element-property :end e))
8024 (progn (skip-chars-backward " \r\t\n")
8025 (beginning-of-line)
8026 t))))
8027 (forward-line)))))))))
8029 (defun org-convert-to-odd-levels ()
8030 "Convert an Org file with all levels allowed to one with odd levels.
8031 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8032 level 5 etc."
8033 (interactive)
8034 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8035 (let ((outline-level 'org-outline-level)
8036 (org-odd-levels-only nil) n)
8037 (save-excursion
8038 (goto-char (point-min))
8039 (while (re-search-forward "^\\*\\*+ " nil t)
8040 (setq n (- (length (match-string 0)) 2))
8041 (while (>= (setq n (1- n)) 0)
8042 (org-demote))
8043 (end-of-line 1))))))
8045 (defun org-convert-to-oddeven-levels ()
8046 "Convert an Org file with only odd levels to one with odd/even levels.
8047 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8048 file contains a section with an even level, conversion would
8049 destroy the structure of the file. An error is signaled in this
8050 case."
8051 (interactive)
8052 (goto-char (point-min))
8053 ;; First check if there are no even levels
8054 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8055 (org-show-set-visibility 'canonical)
8056 (error "Not all levels are odd in this file. Conversion not possible"))
8057 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8058 (let ((outline-regexp org-outline-regexp)
8059 (outline-level 'org-outline-level)
8060 (org-odd-levels-only nil) n)
8061 (save-excursion
8062 (goto-char (point-min))
8063 (while (re-search-forward "^\\*\\*+ " nil t)
8064 (setq n (/ (1- (length (match-string 0))) 2))
8065 (while (>= (setq n (1- n)) 0)
8066 (org-promote))
8067 (end-of-line 1))))))
8069 (defun org-tr-level (n)
8070 "Make N odd if required."
8071 (if org-odd-levels-only (1+ (/ n 2)) n))
8073 ;;; Vertical tree motion, cutting and pasting of subtrees
8075 (defun org-move-subtree-up (&optional arg)
8076 "Move the current subtree up past ARG headlines of the same level."
8077 (interactive "p")
8078 (org-move-subtree-down (- (prefix-numeric-value arg))))
8080 (defun org-move-subtree-down (&optional arg)
8081 "Move the current subtree down past ARG headlines of the same level."
8082 (interactive "p")
8083 (setq arg (prefix-numeric-value arg))
8084 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8085 'org-get-last-sibling))
8086 (ins-point (make-marker))
8087 (cnt (abs arg))
8088 (col (current-column))
8089 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8090 ;; Select the tree
8091 (org-back-to-heading)
8092 (setq beg0 (point))
8093 (save-excursion
8094 (setq ne-beg (org-back-over-empty-lines))
8095 (setq beg (point)))
8096 (save-match-data
8097 (save-excursion (outline-end-of-heading)
8098 (setq folded (org-invisible-p)))
8099 (progn (org-end-of-subtree nil t)
8100 (unless (eobp) (backward-char))))
8101 (outline-next-heading)
8102 (setq ne-end (org-back-over-empty-lines))
8103 (setq end (point))
8104 (goto-char beg0)
8105 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8106 ;; include less whitespace
8107 (save-excursion
8108 (goto-char beg)
8109 (forward-line (- ne-beg ne-end))
8110 (setq beg (point))))
8111 ;; Find insertion point, with error handling
8112 (while (> cnt 0)
8113 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8114 (progn (goto-char beg0)
8115 (user-error "Cannot move past superior level or buffer limit")))
8116 (setq cnt (1- cnt)))
8117 (when (> arg 0)
8118 ;; Moving forward - still need to move over subtree
8119 (org-end-of-subtree t t)
8120 (save-excursion
8121 (org-back-over-empty-lines)
8122 (or (bolp) (newline))))
8123 (setq ne-ins (org-back-over-empty-lines))
8124 (move-marker ins-point (point))
8125 (setq txt (buffer-substring beg end))
8126 (org-save-markers-in-region beg end)
8127 (delete-region beg end)
8128 (org-remove-empty-overlays-at beg)
8129 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8130 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8131 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8132 (let ((bbb (point)))
8133 (insert-before-markers txt)
8134 (org-reinstall-markers-in-region bbb)
8135 (move-marker ins-point bbb))
8136 (or (bolp) (insert "\n"))
8137 (setq ins-end (point))
8138 (goto-char ins-point)
8139 (org-skip-whitespace)
8140 (when (and (< arg 0)
8141 (org-first-sibling-p)
8142 (> ne-ins ne-beg))
8143 ;; Move whitespace back to beginning
8144 (save-excursion
8145 (goto-char ins-end)
8146 (let ((kill-whole-line t))
8147 (kill-line (- ne-ins ne-beg)) (point)))
8148 (insert (make-string (- ne-ins ne-beg) ?\n)))
8149 (move-marker ins-point nil)
8150 (if folded
8151 (outline-hide-subtree)
8152 (org-show-entry)
8153 (org-show-children)
8154 (org-cycle-hide-drawers 'children))
8155 (org-clean-visibility-after-subtree-move)
8156 ;; move back to the initial column we were at
8157 (move-to-column col)))
8159 (defvar org-subtree-clip ""
8160 "Clipboard for cut and paste of subtrees.
8161 This is actually only a copy of the kill, because we use the normal kill
8162 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8164 (defvar org-subtree-clip-folded nil
8165 "Was the last copied subtree folded?
8166 This is used to fold the tree back after pasting.")
8168 (defun org-cut-subtree (&optional n)
8169 "Cut the current subtree into the clipboard.
8170 With prefix arg N, cut this many sequential subtrees.
8171 This is a short-hand for marking the subtree and then cutting it."
8172 (interactive "p")
8173 (org-copy-subtree n 'cut))
8175 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8176 "Copy the current subtree it in the clipboard.
8177 With prefix arg N, copy this many sequential subtrees.
8178 This is a short-hand for marking the subtree and then copying it.
8179 If CUT is non-nil, actually cut the subtree.
8180 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8181 of some markers in the region, even if CUT is non-nil. This is
8182 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8183 (interactive "p")
8184 (let (beg end folded (beg0 (point)))
8185 (if (called-interactively-p 'any)
8186 (org-back-to-heading nil) ; take what looks like a subtree
8187 (org-back-to-heading t)) ; take what is really there
8188 (setq beg (point))
8189 (skip-chars-forward " \t\r\n")
8190 (save-match-data
8191 (if nosubtrees
8192 (outline-next-heading)
8193 (save-excursion (outline-end-of-heading)
8194 (setq folded (org-invisible-p)))
8195 (ignore-errors (org-forward-heading-same-level (1- n) t))
8196 (org-end-of-subtree t t)))
8197 ;; Include the end of an inlinetask
8198 (when (and (featurep 'org-inlinetask)
8199 (looking-at-p (concat (org-inlinetask-outline-regexp)
8200 "END[ \t]*$")))
8201 (end-of-line))
8202 (setq end (point))
8203 (goto-char beg0)
8204 (when (> end beg)
8205 (setq org-subtree-clip-folded folded)
8206 (when (or cut force-store-markers)
8207 (org-save-markers-in-region beg end))
8208 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8209 (setq org-subtree-clip (current-kill 0))
8210 (message "%s: Subtree(s) with %d characters"
8211 (if cut "Cut" "Copied")
8212 (length org-subtree-clip)))))
8214 (defun org-paste-subtree (&optional level tree for-yank remove)
8215 "Paste the clipboard as a subtree, with modification of headline level.
8216 The entire subtree is promoted or demoted in order to match a new headline
8217 level.
8219 If the cursor is at the beginning of a headline, the same level as
8220 that headline is used to paste the tree.
8222 If not, the new level is derived from the *visible* headings
8223 before and after the insertion point, and taken to be the inferior headline
8224 level of the two. So if the previous visible heading is level 3 and the
8225 next is level 4 (or vice versa), level 4 will be used for insertion.
8226 This makes sure that the subtree remains an independent subtree and does
8227 not swallow low level entries.
8229 You can also force a different level, either by using a numeric prefix
8230 argument, or by inserting the heading marker by hand. For example, if the
8231 cursor is after \"*****\", then the tree will be shifted to level 5.
8233 If optional TREE is given, use this text instead of the kill ring.
8235 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8236 move back over whitespace before inserting, and move point to the end of
8237 the inserted text when done.
8239 When REMOVE is non-nil, remove the subtree from the clipboard."
8240 (interactive "P")
8241 (setq tree (or tree (and kill-ring (current-kill 0))))
8242 (unless (org-kill-is-subtree-p tree)
8243 (user-error "%s"
8244 (substitute-command-keys
8245 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8246 (org-with-limited-levels
8247 (let* ((visp (not (org-invisible-p)))
8248 (txt tree)
8249 (^re_ "\\(\\*+\\)[ \t]*")
8250 (old-level (if (string-match org-outline-regexp-bol txt)
8251 (- (match-end 0) (match-beginning 0) 1)
8252 -1))
8253 (force-level (cond (level (prefix-numeric-value level))
8254 ((and (looking-at "[ \t]*$")
8255 (string-match
8256 "^\\*+$" (buffer-substring
8257 (point-at-bol) (point))))
8258 (- (match-end 0) (match-beginning 0)))
8259 ((and (bolp)
8260 (looking-at org-outline-regexp))
8261 (- (match-end 0) (point) 1))))
8262 (previous-level (save-excursion
8263 (condition-case nil
8264 (progn
8265 (outline-previous-visible-heading 1)
8266 (if (looking-at ^re_)
8267 (- (match-end 0) (match-beginning 0) 1)
8269 (error 1))))
8270 (next-level (save-excursion
8271 (condition-case nil
8272 (progn
8273 (or (looking-at org-outline-regexp)
8274 (outline-next-visible-heading 1))
8275 (if (looking-at ^re_)
8276 (- (match-end 0) (match-beginning 0) 1)
8278 (error 1))))
8279 (new-level (or force-level (max previous-level next-level)))
8280 (shift (if (or (= old-level -1)
8281 (= new-level -1)
8282 (= old-level new-level))
8284 (- new-level old-level)))
8285 (delta (if (> shift 0) -1 1))
8286 (func (if (> shift 0) 'org-demote 'org-promote))
8287 (org-odd-levels-only nil)
8288 beg end newend)
8289 ;; Remove the forced level indicator
8290 (when force-level
8291 (delete-region (point-at-bol) (point)))
8292 ;; Paste
8293 (beginning-of-line (if (bolp) 1 2))
8294 (setq beg (point))
8295 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8296 (insert-before-markers txt)
8297 (unless (string-suffix-p "\n" txt) (insert "\n"))
8298 (setq newend (point))
8299 (org-reinstall-markers-in-region beg)
8300 (setq end (point))
8301 (goto-char beg)
8302 (skip-chars-forward " \t\n\r")
8303 (setq beg (point))
8304 (when (and (org-invisible-p) visp)
8305 (save-excursion (outline-show-heading)))
8306 ;; Shift if necessary
8307 (unless (= shift 0)
8308 (save-restriction
8309 (narrow-to-region beg end)
8310 (while (not (= shift 0))
8311 (org-map-region func (point-min) (point-max))
8312 (setq shift (+ delta shift)))
8313 (goto-char (point-min))
8314 (setq newend (point-max))))
8315 (when (or (called-interactively-p 'interactive) for-yank)
8316 (message "Clipboard pasted as level %d subtree" new-level))
8317 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8318 kill-ring
8319 (eq org-subtree-clip (current-kill 0))
8320 org-subtree-clip-folded)
8321 ;; The tree was folded before it was killed/copied
8322 (outline-hide-subtree))
8323 (and for-yank (goto-char newend))
8324 (and remove (setq kill-ring (cdr kill-ring))))))
8326 (defun org-kill-is-subtree-p (&optional txt)
8327 "Check if the current kill is an outline subtree, or a set of trees.
8328 Returns nil if kill does not start with a headline, or if the first
8329 headline level is not the largest headline level in the tree.
8330 So this will actually accept several entries of equal levels as well,
8331 which is OK for `org-paste-subtree'.
8332 If optional TXT is given, check this string instead of the current kill."
8333 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8334 (re (org-get-limited-outline-regexp))
8335 (^re (concat "^" re))
8336 (start-level (and kill
8337 (string-match
8338 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8339 kill)
8340 (- (match-end 2) (match-beginning 2) 1)))
8341 (start (1+ (or (match-beginning 2) -1))))
8342 (if (not start-level)
8343 (progn
8344 nil) ;; does not even start with a heading
8345 (catch 'exit
8346 (while (setq start (string-match ^re kill (1+ start)))
8347 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8348 (throw 'exit nil)))
8349 t))))
8351 (defvar org-markers-to-move nil
8352 "Markers that should be moved with a cut-and-paste operation.
8353 Those markers are stored together with their positions relative to
8354 the start of the region.")
8356 (defun org-save-markers-in-region (beg end)
8357 "Check markers in region.
8358 If these markers are between BEG and END, record their position relative
8359 to BEG, so that after moving the block of text, we can put the markers back
8360 into place.
8361 This function gets called just before an entry or tree gets cut from the
8362 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8363 called immediately, to move the markers with the entries."
8364 (setq org-markers-to-move nil)
8365 (when (featurep 'org-clock)
8366 (org-clock-save-markers-for-cut-and-paste beg end))
8367 (when (featurep 'org-agenda)
8368 (org-agenda-save-markers-for-cut-and-paste beg end)))
8370 (defun org-check-and-save-marker (marker beg end)
8371 "Check if MARKER is between BEG and END.
8372 If yes, remember the marker and the distance to BEG."
8373 (when (and (marker-buffer marker)
8374 (equal (marker-buffer marker) (current-buffer))
8375 (>= marker beg) (< marker end))
8376 (push (cons marker (- marker beg)) org-markers-to-move)))
8378 (defun org-reinstall-markers-in-region (beg)
8379 "Move all remembered markers to their position relative to BEG."
8380 (dolist (x org-markers-to-move)
8381 (move-marker (car x) (+ beg (cdr x))))
8382 (setq org-markers-to-move nil))
8384 (defun org-narrow-to-subtree ()
8385 "Narrow buffer to the current subtree."
8386 (interactive)
8387 (save-excursion
8388 (save-match-data
8389 (org-with-limited-levels
8390 (narrow-to-region
8391 (progn (org-back-to-heading t) (point))
8392 (progn (org-end-of-subtree t t)
8393 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8394 (point)))))))
8396 (defun org-narrow-to-block ()
8397 "Narrow buffer to the current block."
8398 (interactive)
8399 (let* ((case-fold-search t)
8400 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8401 "^[ \t]*#\\+end_.*")))
8402 (if blockp
8403 (narrow-to-region (car blockp) (cdr blockp))
8404 (user-error "Not in a block"))))
8406 (defun org-clone-subtree-with-time-shift (n &optional shift)
8407 "Clone the task (subtree) at point N times.
8408 The clones will be inserted as siblings.
8410 In interactive use, the user will be prompted for the number of
8411 clones to be produced. If the entry has a timestamp, the user
8412 will also be prompted for a time shift, which may be a repeater
8413 as used in time stamps, for example `+3d'. To disable this,
8414 you can call the function with a universal prefix argument.
8416 When a valid repeater is given and the entry contains any time
8417 stamps, the clones will become a sequence in time, with time
8418 stamps in the subtree shifted for each clone produced. If SHIFT
8419 is nil or the empty string, time stamps will be left alone. The
8420 ID property of the original subtree is removed.
8422 In each clone, all the CLOCK entries will be removed. This
8423 prevents Org from considering that the clocked times overlap.
8425 If the original subtree did contain time stamps with a repeater,
8426 the following will happen:
8427 - the repeater will be removed in each clone
8428 - an additional clone will be produced, with the current, unshifted
8429 date(s) in the entry.
8430 - the original entry will be placed *after* all the clones, with
8431 repeater intact.
8432 - the start days in the repeater in the original entry will be shifted
8433 to past the last clone.
8434 In this way you can spell out a number of instances of a repeating task,
8435 and still retain the repeater to cover future instances of the task.
8437 As described above, N+1 clones are produced when the original
8438 subtree has a repeater. Setting N to 0, then, can be used to
8439 remove the repeater from a subtree and create a shifted clone
8440 with the original repeater."
8441 (interactive "nNumber of clones to produce: ")
8442 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8443 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8444 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8445 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8446 (shift
8447 (or shift
8448 (if (and (not (equal current-prefix-arg '(4)))
8449 (save-excursion
8450 (goto-char beg)
8451 (re-search-forward org-ts-regexp-both end-of-tree t)))
8452 (read-from-minibuffer
8453 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8454 ""))) ;No time shift
8455 (doshift
8456 (and (org-string-nw-p shift)
8457 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8458 shift)
8459 (user-error "Invalid shift specification %s" shift)))))
8460 (goto-char end-of-tree)
8461 (unless (bolp) (insert "\n"))
8462 (let* ((end (point))
8463 (template (buffer-substring beg end))
8464 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8465 (shift-what (pcase (and doshift (match-string 2 shift))
8466 (`nil nil)
8467 ("d" 'day)
8468 ("w" (setq shift-n (* 7 shift-n)) 'day)
8469 ("m" 'month)
8470 ("y" 'year)
8471 (_ (error "Unsupported time unit"))))
8472 (nmin 1)
8473 (nmax n)
8474 (n-no-remove -1)
8475 (idprop (org-entry-get nil "ID")))
8476 (when (and doshift
8477 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8478 template))
8479 (delete-region beg end)
8480 (setq end beg)
8481 (setq nmin 0)
8482 (setq nmax (1+ nmax))
8483 (setq n-no-remove nmax))
8484 (goto-char end)
8485 (cl-loop for n from nmin to nmax do
8486 (insert
8487 ;; Prepare clone.
8488 (with-temp-buffer
8489 (insert template)
8490 (org-mode)
8491 (goto-char (point-min))
8492 (org-show-subtree)
8493 (and idprop (if org-clone-delete-id
8494 (org-entry-delete nil "ID")
8495 (org-id-get-create t)))
8496 (unless (= n 0)
8497 (while (re-search-forward org-clock-line-re nil t)
8498 (delete-region (line-beginning-position)
8499 (line-beginning-position 2)))
8500 (goto-char (point-min))
8501 (while (re-search-forward org-drawer-regexp nil t)
8502 (org-remove-empty-drawer-at (point))))
8503 (goto-char (point-min))
8504 (when doshift
8505 (while (re-search-forward org-ts-regexp-both nil t)
8506 (org-timestamp-change (* n shift-n) shift-what))
8507 (unless (= n n-no-remove)
8508 (goto-char (point-min))
8509 (while (re-search-forward org-ts-regexp nil t)
8510 (save-excursion
8511 (goto-char (match-beginning 0))
8512 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8513 (delete-region (match-beginning 1) (match-end 1)))))))
8514 (buffer-string)))))
8515 (goto-char beg)))
8517 ;;; Outline Sorting
8519 (defun org-sort (&optional with-case)
8520 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8521 Optional argument WITH-CASE means sort case-sensitively."
8522 (interactive "P")
8523 (org-call-with-arg
8524 (cond ((org-at-table-p) #'org-table-sort-lines)
8525 ((org-at-item-p) #'org-sort-list)
8526 (t #'org-sort-entries))
8527 with-case))
8529 (defun org-sort-remove-invisible (s)
8530 "Remove invisible part of links and emphasis markers from string S."
8531 (remove-text-properties 0 (length s) org-rm-props s)
8532 (replace-regexp-in-string
8533 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8534 (replace-regexp-in-string
8535 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8536 (org-link-display-format s)
8537 t t) t t))
8539 (defvar org-priority-regexp) ; defined later in the file
8541 (defvar org-after-sorting-entries-or-items-hook nil
8542 "Hook that is run after a bunch of entries or items have been sorted.
8543 When children are sorted, the cursor is in the parent line when this
8544 hook gets called. When a region or a plain list is sorted, the cursor
8545 will be in the first entry of the sorted region/list.")
8547 (defun org-sort-entries
8548 (&optional with-case sorting-type getkey-func compare-func property
8549 interactive?)
8550 "Sort entries on a certain level of an outline tree.
8551 If there is an active region, the entries in the region are sorted.
8552 Else, if the cursor is before the first entry, sort the top-level items.
8553 Else, the children of the entry at point are sorted.
8555 Sorting can be alphabetically, numerically, by date/time as given by
8556 a time stamp, by a property, by priority order, or by a custom function.
8558 The command prompts for the sorting type unless it has been given to the
8559 function through the SORTING-TYPE argument, which needs to be a character,
8560 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8561 the precise meaning of each character:
8563 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8564 c By creation time, which is assumed to be the first inactive time stamp
8565 at the beginning of a line.
8566 d By deadline date/time.
8567 k By clocking time.
8568 n Numerically, by converting the beginning of the entry/item to a number.
8569 o By order of TODO keywords.
8570 p By priority according to the cookie.
8571 r By the value of a property.
8572 s By scheduled date/time.
8573 t By date/time, either the first active time stamp in the entry, or, if
8574 none exist, by the first inactive one.
8576 Capital letters will reverse the sort order.
8578 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8579 called with point at the beginning of the record. It must return a
8580 value that is compatible with COMPARE-FUNC, the function used to
8581 compare entries.
8583 Comparing entries ignores case by default. However, with an optional argument
8584 WITH-CASE, the sorting considers case as well.
8586 Sorting is done against the visible part of the headlines, it ignores hidden
8587 links.
8589 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8591 A non-nil value for INTERACTIVE? is used to signal that this
8592 function is being called interactively."
8593 (interactive (list current-prefix-arg nil nil nil nil t))
8594 (let ((case-func (if with-case 'identity 'downcase))
8595 start beg end stars re re2
8596 txt what tmp)
8597 ;; Find beginning and end of region to sort
8598 (cond
8599 ((org-region-active-p)
8600 ;; we will sort the region
8601 (setq end (region-end)
8602 what "region")
8603 (goto-char (region-beginning))
8604 (unless (org-at-heading-p) (outline-next-heading))
8605 (setq start (point)))
8606 ((or (org-at-heading-p)
8607 (ignore-errors (progn (org-back-to-heading) t)))
8608 ;; we will sort the children of the current headline
8609 (org-back-to-heading)
8610 (setq start (point)
8611 end (progn (org-end-of-subtree t t)
8612 (or (bolp) (insert "\n"))
8613 (when (>= (org-back-over-empty-lines) 1)
8614 (forward-line 1))
8615 (point))
8616 what "children")
8617 (goto-char start)
8618 (outline-show-subtree)
8619 (outline-next-heading))
8621 ;; we will sort the top-level entries in this file
8622 (goto-char (point-min))
8623 (or (org-at-heading-p) (outline-next-heading))
8624 (setq start (point))
8625 (goto-char (point-max))
8626 (beginning-of-line 1)
8627 (when (looking-at ".*?\\S-")
8628 ;; File ends in a non-white line
8629 (end-of-line 1)
8630 (insert "\n"))
8631 (setq end (point-max))
8632 (setq what "top-level")
8633 (goto-char start)
8634 (outline-show-all)))
8636 (setq beg (point))
8637 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8639 (looking-at "\\(\\*+\\)")
8640 (setq stars (match-string 1)
8641 re (concat "^" (regexp-quote stars) " +")
8642 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8643 txt (buffer-substring beg end))
8644 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8645 (when (and (not (equal stars "*")) (string-match re2 txt))
8646 (user-error "Region to sort contains a level above the first entry"))
8648 (unless sorting-type
8649 (message
8650 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8651 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8652 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8653 what)
8654 (setq sorting-type (read-char-exclusive)))
8656 (unless getkey-func
8657 (and (= (downcase sorting-type) ?f)
8658 (setq getkey-func
8659 (or (and interactive?
8660 (org-read-function
8661 "Function for extracting keys: "))
8662 (error "Missing key extractor")))))
8664 (and (= (downcase sorting-type) ?r)
8665 (not property)
8666 (setq property
8667 (completing-read "Property: "
8668 (mapcar #'list (org-buffer-property-keys t))
8669 nil t)))
8671 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8672 (message "Sorting entries...")
8674 (save-restriction
8675 (narrow-to-region start end)
8676 (let ((restore-clock?
8677 ;; The clock marker is lost when using `sort-subr'; mark
8678 ;; the clock with temporary `:org-clock-marker-backup'
8679 ;; text property.
8680 (when (and (eq (org-clock-is-active) (current-buffer))
8681 (<= start (marker-position org-clock-marker))
8682 (>= end (marker-position org-clock-marker)))
8683 (org-with-silent-modifications
8684 (put-text-property (1- org-clock-marker) org-clock-marker
8685 :org-clock-marker-backup t))
8687 (dcst (downcase sorting-type))
8688 (case-fold-search nil)
8689 (now (current-time)))
8690 (sort-subr
8691 (/= dcst sorting-type)
8692 ;; This function moves to the beginning character of the "record" to
8693 ;; be sorted.
8694 (lambda nil
8695 (if (re-search-forward re nil t)
8696 (goto-char (match-beginning 0))
8697 (goto-char (point-max))))
8698 ;; This function moves to the last character of the "record" being
8699 ;; sorted.
8700 (lambda nil
8701 (save-match-data
8702 (condition-case nil
8703 (outline-forward-same-level 1)
8704 (error
8705 (goto-char (point-max))))))
8706 ;; This function returns the value that gets sorted against.
8707 (lambda nil
8708 (cond
8709 ((= dcst ?n)
8710 (if (looking-at org-complex-heading-regexp)
8711 (string-to-number (org-sort-remove-invisible (match-string 4)))
8712 nil))
8713 ((= dcst ?a)
8714 (if (looking-at org-complex-heading-regexp)
8715 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8716 nil))
8717 ((= dcst ?k)
8718 (or (get-text-property (point) :org-clock-minutes) 0))
8719 ((= dcst ?t)
8720 (let ((end (save-excursion (outline-next-heading) (point))))
8721 (if (or (re-search-forward org-ts-regexp end t)
8722 (re-search-forward org-ts-regexp-both end t))
8723 (org-time-string-to-seconds (match-string 0))
8724 (float-time now))))
8725 ((= dcst ?c)
8726 (let ((end (save-excursion (outline-next-heading) (point))))
8727 (if (re-search-forward
8728 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8729 end t)
8730 (org-time-string-to-seconds (match-string 0))
8731 (float-time now))))
8732 ((= dcst ?s)
8733 (let ((end (save-excursion (outline-next-heading) (point))))
8734 (if (re-search-forward org-scheduled-time-regexp end t)
8735 (org-time-string-to-seconds (match-string 1))
8736 (float-time now))))
8737 ((= dcst ?d)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward org-deadline-time-regexp end t)
8740 (org-time-string-to-seconds (match-string 1))
8741 (float-time now))))
8742 ((= dcst ?p)
8743 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8744 (string-to-char (match-string 2))
8745 org-default-priority))
8746 ((= dcst ?r)
8747 (or (org-entry-get nil property) ""))
8748 ((= dcst ?o)
8749 (when (looking-at org-complex-heading-regexp)
8750 (let* ((m (match-string 2))
8751 (s (if (member m org-done-keywords) '- '+)))
8752 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8753 ((= dcst ?f)
8754 (if getkey-func
8755 (progn
8756 (setq tmp (funcall getkey-func))
8757 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8758 tmp)
8759 (error "Invalid key function `%s'" getkey-func)))
8760 (t (error "Invalid sorting type `%c'" sorting-type))))
8762 (cond
8763 ((= dcst ?a) 'string<)
8764 ((= dcst ?f)
8765 (or compare-func
8766 (and interactive?
8767 (org-read-function
8768 (concat "Function for comparing keys "
8769 "(empty for default `sort-subr' predicate): ")
8770 'allow-empty))))
8771 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
8772 (when restore-clock?
8773 (move-marker org-clock-marker
8774 (1+ (next-single-property-change
8775 start :org-clock-marker-backup)))
8776 (remove-text-properties (1- org-clock-marker) org-clock-marker
8777 '(:org-clock-marker-backup t)))))
8778 (run-hooks 'org-after-sorting-entries-or-items-hook)
8779 (message "Sorting entries...done")))
8781 ;;; The orgstruct minor mode
8783 ;; Define a minor mode which can be used in other modes in order to
8784 ;; integrate the Org mode structure editing commands.
8786 ;; This is really a hack, because the Org mode structure commands use
8787 ;; keys which normally belong to the major mode. Here is how it
8788 ;; works: The minor mode defines all the keys necessary to operate the
8789 ;; structure commands, but wraps the commands into a function which
8790 ;; tests if the cursor is currently at a headline or a plain list
8791 ;; item. If that is the case, the structure command is used,
8792 ;; temporarily setting many Org mode variables like regular
8793 ;; expressions for filling etc. However, when any of those keys is
8794 ;; used at a different location, function uses `key-binding' to look
8795 ;; up if the key has an associated command in another currently active
8796 ;; keymap (minor modes, major mode, global), and executes that
8797 ;; command. There might be problems if any of the keys is otherwise
8798 ;; used as a prefix key.
8800 (defcustom orgstruct-heading-prefix-regexp ""
8801 "Regexp that matches the custom prefix of Org headlines in
8802 orgstruct(++)-mode."
8803 :group 'org
8804 :version "26.1"
8805 :package-version '(Org . "8.3")
8806 :type 'regexp)
8807 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8809 (defcustom orgstruct-setup-hook nil
8810 "Hook run after orgstruct-mode-map is filled."
8811 :group 'org
8812 :version "24.4"
8813 :package-version '(Org . "8.0")
8814 :type 'hook)
8816 (defvar orgstruct-initialized nil)
8818 (defvar org-local-vars nil
8819 "List of local variables, for use by `orgstruct-mode'.")
8821 ;;;###autoload
8822 (define-minor-mode orgstruct-mode
8823 "Toggle the minor mode `orgstruct-mode'.
8824 This mode is for using Org mode structure commands in other
8825 modes. The following keys behave as if Org mode were active, if
8826 the cursor is on a headline, or on a plain list item (both as
8827 defined by Org mode)."
8828 nil " OrgStruct" (make-sparse-keymap)
8829 (funcall (if orgstruct-mode
8830 'add-to-invisibility-spec
8831 'remove-from-invisibility-spec)
8832 '(outline . t))
8833 (when orgstruct-mode
8834 (org-load-modules-maybe)
8835 (unless orgstruct-initialized
8836 (orgstruct-setup)
8837 (setq orgstruct-initialized t))))
8839 ;;;###autoload
8840 (defun turn-on-orgstruct ()
8841 "Unconditionally turn on `orgstruct-mode'."
8842 (orgstruct-mode 1))
8844 (defvar-local orgstruct-is-++ nil
8845 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8846 (defvar-local org-fb-vars nil)
8847 (defun orgstruct++-mode (&optional arg)
8848 "Toggle `orgstruct-mode', the enhanced version of it.
8849 In addition to setting orgstruct-mode, this also exports all
8850 indentation and autofilling variables from Org mode into the
8851 buffer. It will also recognize item context in multiline items."
8852 (interactive "P")
8853 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8854 (if (< arg 1)
8855 (progn (orgstruct-mode -1)
8856 (dolist (v org-fb-vars)
8857 (set (make-local-variable (car v))
8858 (if (eq (car-safe (cadr v)) 'quote)
8859 (cl-cadadr v)
8860 (nth 1 v)))))
8861 (orgstruct-mode 1)
8862 (setq org-fb-vars nil)
8863 (unless org-local-vars
8864 (setq org-local-vars (org-get-local-variables)))
8865 (let (var val)
8866 (dolist (x org-local-vars)
8867 (when (string-match
8868 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8869 \\|fill-prefix\\|indent-\\)"
8870 (symbol-name (car x)))
8871 (setq var (car x) val (nth 1 x))
8872 (push (list var `(quote ,(eval var))) org-fb-vars)
8873 (set (make-local-variable var)
8874 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8875 (setq-local orgstruct-is-++ t))))
8877 ;;;###autoload
8878 (defun turn-on-orgstruct++ ()
8879 "Unconditionally turn on `orgstruct++-mode'."
8880 (orgstruct++-mode 1))
8882 (defun orgstruct-error ()
8883 "Error when there is no default binding for a structure key."
8884 (interactive)
8885 (funcall (if (fboundp 'user-error)
8886 'user-error
8887 'error)
8888 "This key has no function outside structure elements"))
8890 (defun orgstruct-setup ()
8891 "Setup orgstruct keymap."
8892 (dolist (cell '((org-demote . t)
8893 (org-metaleft . t)
8894 (org-metaright . t)
8895 (org-promote . t)
8896 (org-shiftmetaleft . t)
8897 (org-shiftmetaright . t)
8898 org-backward-element
8899 org-backward-heading-same-level
8900 org-ctrl-c-ret
8901 org-ctrl-c-minus
8902 org-ctrl-c-star
8903 org-cycle
8904 org-force-cycle-archived
8905 org-forward-heading-same-level
8906 org-insert-heading
8907 org-insert-heading-respect-content
8908 org-kill-note-or-show-branches
8909 org-mark-subtree
8910 org-meta-return
8911 org-metadown
8912 org-metaup
8913 org-narrow-to-subtree
8914 org-promote-subtree
8915 org-reveal
8916 org-shiftdown
8917 org-shiftleft
8918 org-shiftmetadown
8919 org-shiftmetaup
8920 org-shiftright
8921 org-shifttab
8922 org-shifttab
8923 org-shiftup
8924 org-show-children
8925 org-show-subtree
8926 org-sort
8927 org-up-element
8928 outline-demote
8929 outline-next-visible-heading
8930 outline-previous-visible-heading
8931 outline-promote
8932 outline-up-heading))
8933 (let ((f (or (car-safe cell) cell))
8934 (disable-when-heading-prefix (cdr-safe cell)))
8935 (when (fboundp f)
8936 (let ((new-bindings))
8937 (dolist (binding (nconc (where-is-internal f org-mode-map)
8938 (where-is-internal f outline-mode-map)))
8939 (push binding new-bindings)
8940 ;; TODO use local-function-key-map
8941 (dolist (rep '(("<tab>" . "TAB")
8942 ("<return>" . "RET")
8943 ("<escape>" . "ESC")
8944 ("<delete>" . "DEL")))
8945 (setq binding (read-kbd-macro
8946 (let ((case-fold-search))
8947 (replace-regexp-in-string
8948 (regexp-quote (cdr rep))
8949 (car rep)
8950 (key-description binding)))))
8951 (cl-pushnew binding new-bindings :test 'equal)))
8952 (dolist (binding new-bindings)
8953 (let ((key (lookup-key orgstruct-mode-map binding)))
8954 (when (or (not key) (numberp key))
8955 (ignore-errors
8956 (org-defkey orgstruct-mode-map
8957 binding
8958 (orgstruct-make-binding
8959 f binding disable-when-heading-prefix))))))))))
8960 (run-hooks 'orgstruct-setup-hook))
8962 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8963 "Create a function for binding in the structure minor mode.
8964 FUN is the command to call inside a table. KEY is the key that
8965 should be checked in for a command to execute outside of tables.
8966 Non-nil `disable-when-heading-prefix' means to disable the command
8967 if `orgstruct-heading-prefix-regexp' is not empty."
8968 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8969 (let ((nname name)
8970 (i 0))
8971 (while (fboundp (intern nname))
8972 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8973 (setq name (intern nname)))
8974 (eval
8975 (let ((bindings '((org-heading-regexp
8976 (concat "^"
8977 orgstruct-heading-prefix-regexp
8978 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8979 (org-outline-regexp
8980 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8981 (org-outline-regexp-bol
8982 (concat "^" org-outline-regexp))
8983 (outline-regexp org-outline-regexp)
8984 (outline-heading-end-regexp "\n")
8985 (outline-level 'org-outline-level)
8986 (outline-heading-alist))))
8987 `(defun ,name (arg)
8988 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8989 "Outside of structure, run the binding of `"
8990 (key-description key) "'."
8991 (when disable-when-heading-prefix
8992 (concat
8993 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
8994 "back to the default binding due to limitations of Org's implementation of\n"
8995 "`" (symbol-name fun) "'.")))
8996 (interactive "p")
8997 (let* ((disable
8998 ,(and disable-when-heading-prefix
8999 '(not (string= orgstruct-heading-prefix-regexp ""))))
9000 (fallback
9001 (or disable
9002 (not
9003 (let* ,bindings
9004 (org-context-p 'headline 'item
9005 ,(when (memq fun
9006 '(org-insert-heading
9007 org-insert-heading-respect-content
9008 org-meta-return))
9009 '(when orgstruct-is-++
9010 'item-body))))))))
9011 (if fallback
9012 (let* ((orgstruct-mode)
9013 (binding
9014 (let ((key ,key))
9015 (catch 'exit
9016 (dolist
9017 (rep
9018 '(nil
9019 ("<\\([^>]*\\)tab>" . "\\1TAB")
9020 ("<\\([^>]*\\)return>" . "\\1RET")
9021 ("<\\([^>]*\\)escape>" . "\\1ESC")
9022 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9023 nil)
9024 (when rep
9025 (setq key (read-kbd-macro
9026 (let ((case-fold-search))
9027 (replace-regexp-in-string
9028 (car rep)
9029 (cdr rep)
9030 (key-description key))))))
9031 (when (key-binding key)
9032 (throw 'exit (key-binding key))))))))
9033 (if (keymapp binding)
9034 (org-set-transient-map binding)
9035 (let ((func (or binding
9036 (unless disable
9037 'orgstruct-error))))
9038 (when func
9039 (call-interactively func)))))
9040 (org-run-like-in-org-mode
9041 (lambda ()
9042 (interactive)
9043 (let* ,bindings
9044 (call-interactively ',fun)))))))))
9045 name))
9047 (defun org-contextualize-keys (alist contexts)
9048 "Return valid elements in ALIST depending on CONTEXTS.
9050 `org-agenda-custom-commands' or `org-capture-templates' are the
9051 values used for ALIST, and `org-agenda-custom-commands-contexts'
9052 or `org-capture-templates-contexts' are the associated contexts
9053 definitions."
9054 (let ((contexts
9055 ;; normalize contexts
9056 (mapcar
9057 (lambda(c) (cond ((listp (cadr c))
9058 (list (car c) (car c) (nth 1 c)))
9059 ((string= "" (cadr c))
9060 (list (car c) (car c) (nth 2 c)))
9061 (t c)))
9062 contexts))
9063 (a alist) r s)
9064 ;; loop over all commands or templates
9065 (dolist (c a)
9066 (let (vrules repl)
9067 (cond
9068 ((not (assoc (car c) contexts))
9069 (push c r))
9070 ((and (assoc (car c) contexts)
9071 (setq vrules (org-contextualize-validate-key
9072 (car c) contexts)))
9073 (mapc (lambda (vr)
9074 (unless (equal (car vr) (cadr vr))
9075 (setq repl vr)))
9076 vrules)
9077 (if (not repl) (push c r)
9078 (push (cadr repl) s)
9079 (push
9080 (cons (car c)
9081 (cdr (or (assoc (cadr repl) alist)
9082 (error "Undefined key `%s' as contextual replacement for `%s'"
9083 (cadr repl) (car c)))))
9084 r))))))
9085 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9086 (delq
9088 (delete-dups
9089 (mapcar (lambda (x)
9090 (let ((tpl (car x)))
9091 (unless (delq
9093 (mapcar (lambda (y)
9094 (equal y tpl))
9096 x)))
9097 (reverse r))))))
9099 (defun org-contextualize-validate-key (key contexts)
9100 "Check CONTEXTS for agenda or capture KEY."
9101 (let (res)
9102 (dolist (r contexts)
9103 (dolist (rr (car (last r)))
9104 (when
9105 (and (equal key (car r))
9106 (if (functionp rr) (funcall rr)
9107 (or (and (eq (car rr) 'in-file)
9108 (buffer-file-name)
9109 (string-match (cdr rr) (buffer-file-name)))
9110 (and (eq (car rr) 'in-mode)
9111 (string-match (cdr rr) (symbol-name major-mode)))
9112 (and (eq (car rr) 'in-buffer)
9113 (string-match (cdr rr) (buffer-name)))
9114 (when (and (eq (car rr) 'not-in-file)
9115 (buffer-file-name))
9116 (not (string-match (cdr rr) (buffer-file-name))))
9117 (when (eq (car rr) 'not-in-mode)
9118 (not (string-match (cdr rr) (symbol-name major-mode))))
9119 (when (eq (car rr) 'not-in-buffer)
9120 (not (string-match (cdr rr) (buffer-name)))))))
9121 (push r res))))
9122 (delete-dups (delq nil res))))
9124 (defun org-context-p (&rest contexts)
9125 "Check if local context is any of CONTEXTS.
9126 Possible values in the list of contexts are `table', `headline', and `item'."
9127 (let ((pos (point)))
9128 (goto-char (point-at-bol))
9129 (prog1 (or (and (memq 'table contexts)
9130 (looking-at "[ \t]*|"))
9131 (and (memq 'headline contexts)
9132 (looking-at org-outline-regexp))
9133 (and (memq 'item contexts)
9134 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9135 (and (memq 'item-body contexts)
9136 (org-in-item-p)))
9137 (goto-char pos))))
9139 ;;;###autoload
9140 (defun org-run-like-in-org-mode (cmd)
9141 "Run a command, pretending that the current buffer is in Org mode.
9142 This will temporarily bind local variables that are typically bound in
9143 Org mode to the values they have in Org mode, and then interactively
9144 call CMD."
9145 (org-load-modules-maybe)
9146 (unless org-local-vars
9147 (setq org-local-vars (org-get-local-variables)))
9148 (let (binds)
9149 (dolist (var org-local-vars)
9150 (when (or (not (boundp (car var)))
9151 (eq (symbol-value (car var))
9152 (default-value (car var))))
9153 (push (list (car var) `(quote ,(cadr var))) binds)))
9154 (eval `(let ,binds
9155 (call-interactively (quote ,cmd))))))
9157 (defun org-get-category (&optional pos force-refresh)
9158 "Get the category applying to position POS."
9159 (save-match-data
9160 (when force-refresh (org-refresh-category-properties))
9161 (let ((pos (or pos (point))))
9162 (or (get-text-property pos 'org-category)
9163 (progn (org-refresh-category-properties)
9164 (get-text-property pos 'org-category))))))
9166 ;;; Refresh properties
9168 (defun org-refresh-properties (dprop tprop)
9169 "Refresh buffer text properties.
9170 DPROP is the drawer property and TPROP is either the
9171 corresponding text property to set, or an alist with each element
9172 being a text property (as a symbol) and a function to apply to
9173 the value of the drawer property."
9174 (let* ((case-fold-search t)
9175 (inhibit-read-only t)
9176 (inherit? (org-property-inherit-p dprop))
9177 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9178 (global (and inherit? (org--property-global-value dprop nil))))
9179 (org-with-silent-modifications
9180 (org-with-point-at 1
9181 ;; Set global values (e.g., values defined through
9182 ;; "#+PROPERTY:" keywords) to the whole buffer.
9183 (when global (put-text-property (point-min) (point-max) tprop global))
9184 ;; Set local values.
9185 (while (re-search-forward property-re nil t)
9186 (when (org-at-property-p)
9187 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9188 (outline-next-heading))))))
9190 (defun org-refresh-property (tprop p &optional inherit)
9191 "Refresh the buffer text property TPROP from the drawer property P.
9192 The refresh happens only for the current headline, or the whole
9193 sub-tree if optional argument INHERIT is non-nil."
9194 (unless (org-before-first-heading-p)
9195 (save-excursion
9196 (org-back-to-heading t)
9197 (let ((start (point))
9198 (end (save-excursion
9199 (if inherit (org-end-of-subtree t t)
9200 (or (outline-next-heading) (point-max))))))
9201 (if (symbolp tprop)
9202 ;; TPROP is a text property symbol.
9203 (put-text-property start end tprop p)
9204 ;; TPROP is an alist with (property . function) elements.
9205 (pcase-dolist (`(,prop . ,f) tprop)
9206 (put-text-property start end prop (funcall f p))))))))
9208 (defun org-refresh-category-properties ()
9209 "Refresh category text properties in the buffer."
9210 (let ((case-fold-search t)
9211 (inhibit-read-only t)
9212 (default-category
9213 (cond ((null org-category)
9214 (if buffer-file-name
9215 (file-name-sans-extension
9216 (file-name-nondirectory buffer-file-name))
9217 "???"))
9218 ((symbolp org-category) (symbol-name org-category))
9219 (t org-category))))
9220 (org-with-silent-modifications
9221 (org-with-wide-buffer
9222 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9223 ;; This is the default category for the buffer. If none is
9224 ;; found, fall-back to `org-category' or buffer file name.
9225 (put-text-property
9226 (point-min) (point-max)
9227 'org-category
9228 (catch 'buffer-category
9229 (goto-char (point-max))
9230 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9231 (let ((element (org-element-at-point)))
9232 (when (eq (org-element-type element) 'keyword)
9233 (throw 'buffer-category
9234 (org-element-property :value element)))))
9235 default-category))
9236 ;; Set sub-tree specific categories.
9237 (goto-char (point-min))
9238 (let ((regexp (org-re-property "CATEGORY")))
9239 (while (re-search-forward regexp nil t)
9240 (let ((value (match-string-no-properties 3)))
9241 (when (org-at-property-p)
9242 (put-text-property
9243 (save-excursion (org-back-to-heading t) (point))
9244 (save-excursion (org-end-of-subtree t t) (point))
9245 'org-category
9246 value)))))))))
9248 (defun org-refresh-stats-properties ()
9249 "Refresh stats text properties in the buffer."
9250 (org-with-silent-modifications
9251 (org-with-point-at 1
9252 (let ((regexp (concat org-outline-regexp-bol
9253 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9254 (while (re-search-forward regexp nil t)
9255 (let* ((numerator (string-to-number (match-string 1)))
9256 (denominator (and (match-end 2)
9257 (string-to-number (match-string 2))))
9258 (stats (cond ((not denominator) numerator) ;percent
9259 ((= denominator 0) 0)
9260 (t (/ (* numerator 100) denominator)))))
9261 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9262 'org-stats stats)))))))
9264 (defun org-refresh-effort-properties ()
9265 "Refresh effort properties"
9266 (org-refresh-properties
9267 org-effort-property
9268 '((effort . identity)
9269 (effort-minutes . org-duration-to-minutes))))
9271 ;;;; Link Stuff
9273 ;;; Link abbreviations
9275 (defun org-link-expand-abbrev (link)
9276 "Apply replacements as defined in `org-link-abbrev-alist'."
9277 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9278 (let* ((key (match-string 1 link))
9279 (as (or (assoc key org-link-abbrev-alist-local)
9280 (assoc key org-link-abbrev-alist)))
9281 (tag (and (match-end 2) (match-string 3 link)))
9282 rpl)
9283 (if (not as)
9284 link
9285 (setq rpl (cdr as))
9286 (cond
9287 ((symbolp rpl) (funcall rpl tag))
9288 ((string-match "%(\\([^)]+\\))" rpl)
9289 (replace-match
9290 (save-match-data
9291 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9292 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9293 ((string-match "%h" rpl)
9294 (replace-match (url-hexify-string (or tag "")) t t rpl))
9295 (t (concat rpl tag)))))
9296 link))
9298 ;;; Storing and inserting links
9300 (defvar org-insert-link-history nil
9301 "Minibuffer history for links inserted with `org-insert-link'.")
9303 (defvar org-stored-links nil
9304 "Contains the links stored with `org-store-link'.")
9306 (defvar org-store-link-plist nil
9307 "Plist with info about the most recently link created with `org-store-link'.")
9309 (defun org-store-link-functions ()
9310 "Return a list of functions that are called to create and store a link.
9311 The functions defined in the :store property of
9312 `org-link-parameters'.
9314 Each function will be called in turn until one returns a non-nil
9315 value. Each function should check if it is responsible for
9316 creating this link (for example by looking at the major mode).
9317 If not, it must exit and return nil. If yes, it should return
9318 a non-nil value after calling `org-store-link-props' with a list
9319 of properties and values. Special properties are:
9321 :type The link prefix, like \"http\". This must be given.
9322 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9323 This is obligatory as well.
9324 :description Optional default description for the second pair
9325 of brackets in an Org mode link. The user can still change
9326 this when inserting this link into an Org mode buffer.
9328 In addition to these, any additional properties can be specified
9329 and then used in capture templates."
9330 (cl-loop for link in org-link-parameters
9331 with store-func
9332 do (setq store-func (org-link-get-parameter (car link) :store))
9333 if store-func
9334 collect store-func))
9336 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9337 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9339 ;;;###autoload
9340 (defun org-store-link (arg)
9341 "Store an org-link to the current location.
9342 \\<org-mode-map>
9343 This link is added to `org-stored-links' and can later be inserted
9344 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9346 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9347 A single
9348 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9349 `org-gnus-prefer-web-links' for links to Usenet articles.
9351 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9352 skipping storing functions that are not
9353 part of Org core.
9355 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9356 prefix ARG forces storing a link for each line in the
9357 active region."
9358 (interactive "P")
9359 (org-load-modules-maybe)
9360 (if (and (equal arg '(64)) (org-region-active-p))
9361 (save-excursion
9362 (let ((end (region-end)))
9363 (goto-char (region-beginning))
9364 (set-mark (point))
9365 (while (< (point-at-eol) end)
9366 (move-end-of-line 1) (activate-mark)
9367 (let (current-prefix-arg)
9368 (call-interactively 'org-store-link))
9369 (move-beginning-of-line 2)
9370 (set-mark (point)))))
9371 (setq org-store-link-plist nil)
9372 (let (link cpltxt desc description search txt custom-id agenda-link)
9373 (cond
9374 ;; Store a link using an external link type, if any function is
9375 ;; available. If more than one can generate a link from current
9376 ;; location, ask which one to use.
9377 ((and (not (equal arg '(16)))
9378 (let ((results-alist nil))
9379 (dolist (f (org-store-link-functions))
9380 (when (funcall f)
9381 ;; XXX: return value is not link's plist, so we
9382 ;; store the new value before it is modified. It
9383 ;; would be cleaner to ask store link functions to
9384 ;; return the plist instead.
9385 (push (cons f (copy-sequence org-store-link-plist))
9386 results-alist)))
9387 (pcase results-alist
9388 (`nil nil)
9389 (`((,_ . ,_)) t) ;single choice: nothing to do
9390 (`((,name . ,_) . ,_)
9391 ;; Reinstate link plist associated to the chosen
9392 ;; function.
9393 (apply #'org-store-link-props
9394 (cdr (assoc-string
9395 (completing-read
9396 "Which function for creating the link? "
9397 (mapcar #'car results-alist) nil t name)
9398 results-alist)))
9399 t))))
9400 (setq link (plist-get org-store-link-plist :link))
9401 (setq desc (or (plist-get org-store-link-plist :description)
9402 link)))
9404 ;; Store a link from a source code buffer.
9405 ((org-src-edit-buffer-p)
9406 (let ((coderef-format (org-src-coderef-format)))
9407 (cond ((save-excursion
9408 (beginning-of-line)
9409 (looking-at (org-src-coderef-regexp coderef-format)))
9410 (setq link (format "(%s)" (match-string-no-properties 3))))
9411 ((called-interactively-p 'any)
9412 (let ((label (read-string "Code line label: ")))
9413 (end-of-line)
9414 (setq link (format coderef-format label))
9415 (let ((gc (- 79 (length link))))
9416 (if (< (current-column) gc)
9417 (org-move-to-column gc t)
9418 (insert " ")))
9419 (insert link)
9420 (setq link (concat "(" label ")"))
9421 (setq desc nil)))
9422 (t (setq link nil)))))
9424 ;; We are in the agenda, link to referenced location
9425 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9426 (let ((m (or (get-text-property (point) 'org-hd-marker)
9427 (get-text-property (point) 'org-marker))))
9428 (when m
9429 (org-with-point-at m
9430 (setq agenda-link
9431 (if (called-interactively-p 'any)
9432 (call-interactively 'org-store-link)
9433 (org-store-link nil)))))))
9435 ((eq major-mode 'calendar-mode)
9436 (let ((cd (calendar-cursor-to-date)))
9437 (setq link
9438 (format-time-string
9439 (car org-time-stamp-formats)
9440 (apply 'encode-time
9441 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9442 nil nil nil))))
9443 (org-store-link-props :type "calendar" :date cd)))
9445 ((eq major-mode 'help-mode)
9446 (setq link (concat "help:" (save-excursion
9447 (goto-char (point-min))
9448 (looking-at "^[^ ]+")
9449 (match-string 0))))
9450 (org-store-link-props :type "help"))
9452 ((eq major-mode 'w3-mode)
9453 (setq cpltxt (if (and (buffer-name)
9454 (not (string-match "Untitled" (buffer-name))))
9455 (buffer-name)
9456 (url-view-url t))
9457 link (url-view-url t))
9458 (org-store-link-props :type "w3" :url (url-view-url t)))
9460 ((eq major-mode 'image-mode)
9461 (setq cpltxt (concat "file:"
9462 (abbreviate-file-name buffer-file-name))
9463 link cpltxt)
9464 (org-store-link-props :type "image" :file buffer-file-name))
9466 ;; In dired, store a link to the file of the current line
9467 ((derived-mode-p 'dired-mode)
9468 (let ((file (dired-get-filename nil t)))
9469 (setq file (if file
9470 (abbreviate-file-name
9471 (expand-file-name (dired-get-filename nil t)))
9472 ;; otherwise, no file so use current directory.
9473 default-directory))
9474 (setq cpltxt (concat "file:" file)
9475 link cpltxt)))
9477 ((setq search (run-hook-with-args-until-success
9478 'org-create-file-search-functions))
9479 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9480 "::" search))
9481 (setq cpltxt (or description link)))
9483 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9484 (org-with-limited-levels
9485 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9486 (cond
9487 ;; Store a link using the target at point
9488 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9489 (setq cpltxt
9490 (concat "file:"
9491 (abbreviate-file-name
9492 (buffer-file-name (buffer-base-buffer)))
9493 "::" (match-string 1))
9494 link cpltxt))
9495 ((and (featurep 'org-id)
9496 (or (eq org-id-link-to-org-use-id t)
9497 (and (called-interactively-p 'any)
9498 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9499 (and (eq org-id-link-to-org-use-id
9500 'create-if-interactive-and-no-custom-id)
9501 (not custom-id))))
9502 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9503 ;; Store a link using the ID at point
9504 (setq link (condition-case nil
9505 (prog1 (org-id-store-link)
9506 (setq desc (or (plist-get org-store-link-plist
9507 :description)
9508 "")))
9509 (error
9510 ;; Probably before first headline, link only to file
9511 (concat "file:"
9512 (abbreviate-file-name
9513 (buffer-file-name (buffer-base-buffer))))))))
9515 ;; Just link to current headline
9516 (setq cpltxt (concat "file:"
9517 (abbreviate-file-name
9518 (buffer-file-name (buffer-base-buffer)))))
9519 ;; Add a context search string
9520 (when (org-xor org-context-in-file-links
9521 (equal arg '(4)))
9522 (let* ((element (org-element-at-point))
9523 (name (org-element-property :name element)))
9524 (setq txt (cond
9525 ((org-at-heading-p) nil)
9526 (name)
9527 ((org-region-active-p)
9528 (buffer-substring (region-beginning) (region-end)))))
9529 (when (or (null txt) (string-match "\\S-" txt))
9530 (setq cpltxt
9531 (concat cpltxt "::"
9532 (condition-case nil
9533 (org-make-org-heading-search-string txt)
9534 (error "")))
9535 desc (or name
9536 (nth 4 (ignore-errors (org-heading-components)))
9537 "NONE")))))
9538 (when (string-match "::\\'" cpltxt)
9539 (setq cpltxt (substring cpltxt 0 -2)))
9540 (setq link cpltxt)))))
9542 ((buffer-file-name (buffer-base-buffer))
9543 ;; Just link to this file here.
9544 (setq cpltxt (concat "file:"
9545 (abbreviate-file-name
9546 (buffer-file-name (buffer-base-buffer)))))
9547 ;; Add a context string.
9548 (when (org-xor org-context-in-file-links
9549 (equal arg '(4)))
9550 (setq txt (if (org-region-active-p)
9551 (buffer-substring (region-beginning) (region-end))
9552 (buffer-substring (point-at-bol) (point-at-eol))))
9553 ;; Only use search option if there is some text.
9554 (when (string-match "\\S-" txt)
9555 (setq cpltxt
9556 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9557 desc "NONE")))
9558 (setq link cpltxt))
9560 ((called-interactively-p 'interactive)
9561 (user-error "No method for storing a link from this buffer"))
9563 (t (setq link nil)))
9565 ;; We're done setting link and desc, clean up
9566 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9567 (setq link (or link cpltxt)
9568 desc (or desc cpltxt))
9569 (cond ((not desc))
9570 ((equal desc "NONE") (setq desc nil))
9571 (t (setq desc
9572 (replace-regexp-in-string
9573 org-bracket-link-analytic-regexp
9574 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9575 desc))))
9576 ;; Return the link
9577 (if (not (and (or (called-interactively-p 'any)
9578 executing-kbd-macro)
9579 link))
9580 (or agenda-link (and link (org-make-link-string link desc)))
9581 (push (list link desc) org-stored-links)
9582 (message "Stored: %s" (or desc link))
9583 (when custom-id
9584 (setq link (concat "file:" (abbreviate-file-name
9585 (buffer-file-name)) "::#" custom-id))
9586 (push (list link desc) org-stored-links))
9587 (car org-stored-links)))))
9589 (defun org-store-link-props (&rest plist)
9590 "Store link properties.
9591 The properties are pre-processed by extracting names, addresses
9592 and dates."
9593 (let ((x (plist-get plist :from)))
9594 (when x
9595 (let ((adr (mail-extract-address-components x)))
9596 (setq plist (plist-put plist :fromname (car adr)))
9597 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9598 (let ((x (plist-get plist :to)))
9599 (when x
9600 (let ((adr (mail-extract-address-components x)))
9601 (setq plist (plist-put plist :toname (car adr)))
9602 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9603 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9604 (when x
9605 (setq plist (plist-put plist :date-timestamp
9606 (format-time-string
9607 (org-time-stamp-format t) x)))
9608 (setq plist (plist-put plist :date-timestamp-inactive
9609 (format-time-string
9610 (org-time-stamp-format t t) x)))))
9611 (let ((from (plist-get plist :from))
9612 (to (plist-get plist :to)))
9613 (when (and from to org-from-is-user-regexp)
9614 (setq plist
9615 (plist-put plist :fromto
9616 (if (string-match org-from-is-user-regexp from)
9617 (concat "to %t")
9618 (concat "from %f"))))))
9619 (setq org-store-link-plist plist))
9621 (defun org-add-link-props (&rest plist)
9622 "Add these properties to the link property list."
9623 (let (key value)
9624 (while plist
9625 (setq key (pop plist) value (pop plist))
9626 (setq org-store-link-plist
9627 (plist-put org-store-link-plist key value)))))
9629 (defun org-email-link-description (&optional fmt)
9630 "Return the description part of an email link.
9631 This takes information from `org-store-link-plist' and formats it
9632 according to FMT (default from `org-email-link-description-format')."
9633 (setq fmt (or fmt org-email-link-description-format))
9634 (let* ((p org-store-link-plist)
9635 (to (plist-get p :toaddress))
9636 (from (plist-get p :fromaddress))
9637 (table
9638 (list
9639 (cons "%c" (plist-get p :fromto))
9640 (cons "%F" (plist-get p :from))
9641 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9642 (cons "%T" (plist-get p :to))
9643 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9644 (cons "%s" (plist-get p :subject))
9645 (cons "%d" (plist-get p :date))
9646 (cons "%m" (plist-get p :message-id)))))
9647 (when (string-match "%c" fmt)
9648 ;; Check if the user wrote this message
9649 (if (and org-from-is-user-regexp from to
9650 (save-match-data (string-match org-from-is-user-regexp from)))
9651 (setq fmt (replace-match "to %t" t t fmt))
9652 (setq fmt (replace-match "from %f" t t fmt))))
9653 (org-replace-escapes fmt table)))
9655 (defun org-make-org-heading-search-string (&optional string)
9656 "Make search string for the current headline or STRING."
9657 (let ((s (or string
9658 (and (derived-mode-p 'org-mode)
9659 (save-excursion
9660 (org-back-to-heading t)
9661 (org-element-property :raw-value (org-element-at-point))))))
9662 (lines org-context-in-file-links))
9663 (unless string (setq s (concat "*" s))) ;Add * for headlines
9664 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9665 (when (and string (integerp lines) (> lines 0))
9666 (let ((slines (org-split-string s "\n")))
9667 (when (< lines (length slines))
9668 (setq s (mapconcat
9669 'identity
9670 (reverse (nthcdr (- (length slines) lines)
9671 (reverse slines))) "\n")))))
9672 (mapconcat #'identity (split-string s) " ")))
9674 (defun org-make-link-string (link &optional description)
9675 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9676 (unless (org-string-nw-p link) (error "Empty link"))
9677 (let ((uri (cond ((string-match org-link-types-re link)
9678 (concat (match-string 1 link)
9679 (org-link-escape (substring link (match-end 1)))))
9680 ;; For readability, url-encode internal links only
9681 ;; when absolutely needed (i.e, when they contain
9682 ;; square brackets). File links however, are
9683 ;; encoded since, e.g., spaces are significant.
9684 ((or (file-name-absolute-p link)
9685 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9686 (org-link-escape link))
9687 (t link)))
9688 (description
9689 (and (org-string-nw-p description)
9690 ;; Remove brackets from description, as they are fatal.
9691 (replace-regexp-in-string
9692 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9693 (org-trim description)))))
9694 (format "[[%s]%s]"
9696 (if description (format "[%s]" description) ""))))
9698 (defconst org-link-escape-chars
9699 ;;%20 %5B %5D %25
9700 '(?\s ?\[ ?\] ?%)
9701 "List of characters that should be escaped in a link when stored to Org.
9702 This is the list that is used for internal purposes.")
9704 (defun org-link-escape (text &optional table merge)
9705 "Return percent escaped representation of TEXT.
9706 TEXT is a string with the text to escape.
9707 Optional argument TABLE is a list with characters that should be
9708 escaped. When nil, `org-link-escape-chars' is used.
9709 If optional argument MERGE is set, merge TABLE into
9710 `org-link-escape-chars'."
9711 (let ((characters-to-encode
9712 (cond ((null table) org-link-escape-chars)
9713 (merge (append org-link-escape-chars table))
9714 (t table))))
9715 (mapconcat
9716 (lambda (c)
9717 (if (or (memq c characters-to-encode)
9718 (and org-url-hexify-p (or (< c 32) (> c 126))))
9719 (mapconcat (lambda (e) (format "%%%.2X" e))
9720 (or (encode-coding-char c 'utf-8)
9721 (error "Unable to percent escape character: %c" c))
9723 (char-to-string c)))
9724 text "")))
9726 (defun org-link-unescape (str)
9727 "Unhex hexified Unicode parts in string STR.
9728 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9729 reciprocal of `org-link-escape', which see."
9730 (if (org-string-nw-p str)
9731 (replace-regexp-in-string
9732 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9733 str))
9735 (defun org-link-unescape-compound (hex)
9736 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9737 Note: this function also decodes single byte encodings like
9738 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9739 (save-match-data
9740 (let* ((bytes (cdr (split-string hex "%")))
9741 (ret "")
9742 (eat 0)
9743 (sum 0))
9744 (while bytes
9745 (let* ((val (string-to-number (pop bytes) 16))
9746 (shift-xor
9747 (if (= 0 eat)
9748 (cond
9749 ((>= val 252) (cons 6 252))
9750 ((>= val 248) (cons 5 248))
9751 ((>= val 240) (cons 4 240))
9752 ((>= val 224) (cons 3 224))
9753 ((>= val 192) (cons 2 192))
9754 (t (cons 0 0)))
9755 (cons 6 128))))
9756 (when (>= val 192) (setq eat (car shift-xor)))
9757 (setq val (logxor val (cdr shift-xor)))
9758 (setq sum (+ (lsh sum (car shift-xor)) val))
9759 (when (> eat 0) (setq eat (- eat 1)))
9760 (cond
9761 ((= 0 eat) ;multi byte
9762 (setq ret (concat ret (char-to-string sum)))
9763 (setq sum 0))
9764 ((not bytes) ; single byte(s)
9765 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9766 ret)))
9768 (defun org-link-unescape-single-byte-sequence (hex)
9769 "Unhexify hex-encoded single byte character sequences."
9770 (mapconcat (lambda (byte)
9771 (char-to-string (string-to-number byte 16)))
9772 (cdr (split-string hex "%")) ""))
9774 (defun org-fixup-message-id-for-http (s)
9775 "Replace special characters in a message id, so it can be used in an http query."
9776 (when (string-match "%" s)
9777 (setq s (mapconcat (lambda (c)
9778 (if (eq c ?%)
9779 "%25"
9780 (char-to-string c)))
9781 s "")))
9782 (while (string-match "<" s)
9783 (setq s (replace-match "%3C" t t s)))
9784 (while (string-match ">" s)
9785 (setq s (replace-match "%3E" t t s)))
9786 (while (string-match "@" s)
9787 (setq s (replace-match "%40" t t s)))
9790 (defun org-link-prettify (link)
9791 "Return a human-readable representation of LINK.
9792 The car of LINK must be a raw link.
9793 The cdr of LINK must be either a link description or nil."
9794 (let ((desc (or (cadr link) "<no description>")))
9795 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9796 "<" (car link) ">")))
9798 ;;;###autoload
9799 (defun org-insert-link-global ()
9800 "Insert a link like Org mode does.
9801 This command can be called in any mode to insert a link in Org syntax."
9802 (interactive)
9803 (org-load-modules-maybe)
9804 (org-run-like-in-org-mode 'org-insert-link))
9806 (defun org-insert-all-links (arg &optional pre post)
9807 "Insert all links in `org-stored-links'.
9808 When a universal prefix, do not delete the links from `org-stored-links'.
9809 When `ARG' is a number, insert the last N link(s).
9810 `PRE' and `POST' are optional arguments to define a string to
9811 prepend or to append."
9812 (interactive "P")
9813 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9814 (links (copy-sequence org-stored-links))
9815 (pr (or pre "- "))
9816 (po (or post "\n"))
9817 (cnt 1) l)
9818 (if (null org-stored-links)
9819 (message "No link to insert")
9820 (while (and (or (listp arg) (>= arg cnt))
9821 (setq l (if (listp arg)
9822 (pop links)
9823 (pop org-stored-links))))
9824 (setq cnt (1+ cnt))
9825 (insert pr)
9826 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9827 (insert po)))))
9829 (defun org-insert-last-stored-link (arg)
9830 "Insert the last link stored in `org-stored-links'."
9831 (interactive "p")
9832 (org-insert-all-links arg "" "\n"))
9834 (defun org-link-fontify-links-to-this-file ()
9835 "Fontify links to the current file in `org-stored-links'."
9836 (let ((f (buffer-file-name)) a b)
9837 (setq a (mapcar (lambda(l)
9838 (let ((ll (car l)))
9839 (when (and (string-match "^file:\\(.+\\)::" ll)
9840 (equal f (expand-file-name (match-string 1 ll))))
9841 ll)))
9842 org-stored-links))
9843 (when (featurep 'org-id)
9844 (setq b (mapcar (lambda(l)
9845 (let ((ll (car l)))
9846 (when (and (string-match "^id:\\(.+\\)$" ll)
9847 (equal f (expand-file-name
9848 (or (org-id-find-id-file
9849 (match-string 1 ll)) ""))))
9850 ll)))
9851 org-stored-links)))
9852 (mapcar (lambda(l)
9853 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9854 (delq nil (append a b)))))
9856 (defvar org--links-history nil)
9857 (defun org-insert-link (&optional complete-file link-location default-description)
9858 "Insert a link. At the prompt, enter the link.
9860 Completion can be used to insert any of the link protocol prefixes in use.
9862 The history can be used to select a link previously stored with
9863 `org-store-link'. When the empty string is entered (i.e. if you just
9864 press `RET' at the prompt), the link defaults to the most recently
9865 stored link. As `SPC' triggers completion in the minibuffer, you need to
9866 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9868 You will also be prompted for a description, and if one is given, it will
9869 be displayed in the buffer instead of the link.
9871 If there is already a link at point, this command will allow you to edit
9872 link and description parts.
9874 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9875 file name can be
9876 selected using completion. The path to the file will be relative to the
9877 current directory if the file is in the current directory or a subdirectory.
9878 Otherwise, the link will be the absolute path as completed in the minibuffer
9879 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9880 option `org-link-file-path-type'.
9882 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9883 absolute path even if the file is in
9884 the current directory or below.
9886 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9887 prefix negates `org-keep-stored-link-after-insertion'.
9889 If the LINK-LOCATION parameter is non-nil, this value will be used as
9890 the link location instead of reading one interactively.
9892 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9893 be used as the default description. Otherwise, if
9894 `org-make-link-description-function' is non-nil, this function
9895 will be called with the link target, and the result will be the
9896 default link description."
9897 (interactive "P")
9898 (let* ((wcf (current-window-configuration))
9899 (origbuf (current-buffer))
9900 (region (when (org-region-active-p)
9901 (buffer-substring (region-beginning) (region-end))))
9902 (remove (and region (list (region-beginning) (region-end))))
9903 (desc region)
9904 (link link-location)
9905 (abbrevs org-link-abbrev-alist-local)
9906 entry all-prefixes auto-desc)
9907 (cond
9908 (link-location) ; specified by arg, just use it.
9909 ((org-in-regexp org-bracket-link-regexp 1)
9910 ;; We do have a link at point, and we are going to edit it.
9911 (setq remove (list (match-beginning 0) (match-end 0)))
9912 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9913 (setq link (read-string "Link: "
9914 (org-link-unescape
9915 (match-string-no-properties 1)))))
9916 ((or (org-in-regexp org-angle-link-re)
9917 (org-in-regexp org-plain-link-re))
9918 ;; Convert to bracket link
9919 (setq remove (list (match-beginning 0) (match-end 0))
9920 link (read-string "Link: "
9921 (org-unbracket-string "<" ">" (match-string 0)))))
9922 ((member complete-file '((4) (16)))
9923 ;; Completing read for file names.
9924 (setq link (org-file-complete-link complete-file)))
9926 ;; Read link, with completion for stored links.
9927 (org-link-fontify-links-to-this-file)
9928 (org-switch-to-buffer-other-window "*Org Links*")
9929 (with-current-buffer "*Org Links*"
9930 (erase-buffer)
9931 (insert "Insert a link.
9932 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9933 (when org-stored-links
9934 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9935 (insert (mapconcat 'org-link-prettify
9936 (reverse org-stored-links) "\n")))
9937 (goto-char (point-min)))
9938 (let ((cw (selected-window)))
9939 (select-window (get-buffer-window "*Org Links*" 'visible))
9940 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9941 (unless (pos-visible-in-window-p (point-max))
9942 (org-fit-window-to-buffer))
9943 (and (window-live-p cw) (select-window cw)))
9944 (setq all-prefixes (append (mapcar 'car abbrevs)
9945 (mapcar 'car org-link-abbrev-alist)
9946 (org-link-types)))
9947 (unwind-protect
9948 ;; Fake a link history, containing the stored links.
9949 (let ((org--links-history
9950 (append (mapcar #'car org-stored-links)
9951 org-insert-link-history)))
9952 (setq link
9953 (org-completing-read
9954 "Link: "
9955 (append
9956 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9957 (mapcar #'car org-stored-links))
9958 nil nil nil
9959 'org--links-history
9960 (caar org-stored-links)))
9961 (unless (org-string-nw-p link) (user-error "No link selected"))
9962 (dolist (l org-stored-links)
9963 (when (equal link (cadr l))
9964 (setq link (car l))
9965 (setq auto-desc t)))
9966 (when (or (member link all-prefixes)
9967 (and (equal ":" (substring link -1))
9968 (member (substring link 0 -1) all-prefixes)
9969 (setq link (substring link 0 -1))))
9970 (setq link (with-current-buffer origbuf
9971 (org-link-try-special-completion link)))))
9972 (set-window-configuration wcf)
9973 (kill-buffer "*Org Links*"))
9974 (setq entry (assoc link org-stored-links))
9975 (or entry (push link org-insert-link-history))
9976 (setq desc (or desc (nth 1 entry)))))
9978 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9979 (not org-keep-stored-link-after-insertion))
9980 (setq org-stored-links (delq (assoc link org-stored-links)
9981 org-stored-links)))
9983 (when (and (string-match org-plain-link-re link)
9984 (not (string-match org-ts-regexp link)))
9985 ;; URL-like link, normalize the use of angular brackets.
9986 (setq link (org-unbracket-string "<" ">" link)))
9988 ;; Check if we are linking to the current file with a search
9989 ;; option If yes, simplify the link by using only the search
9990 ;; option.
9991 (when (and buffer-file-name
9992 (let ((case-fold-search nil))
9993 (string-match "\\`file:\\(.+?\\)::" link)))
9994 (let ((path (match-string-no-properties 1 link))
9995 (search (substring-no-properties link (match-end 0))))
9996 (save-match-data
9997 (when (equal (file-truename buffer-file-name) (file-truename path))
9998 ;; We are linking to this same file, with a search option
9999 (setq link search)))))
10001 ;; Check if we can/should use a relative path. If yes, simplify the link
10002 (let ((case-fold-search nil))
10003 (when (string-match "\\`\\(file\\|docview\\):" link)
10004 (let* ((type (match-string-no-properties 0 link))
10005 (path (substring-no-properties link (match-end 0)))
10006 (origpath path))
10007 (cond
10008 ((or (eq org-link-file-path-type 'absolute)
10009 (equal complete-file '(16)))
10010 (setq path (abbreviate-file-name (expand-file-name path))))
10011 ((eq org-link-file-path-type 'noabbrev)
10012 (setq path (expand-file-name path)))
10013 ((eq org-link-file-path-type 'relative)
10014 (setq path (file-relative-name path)))
10016 (save-match-data
10017 (if (string-match (concat "^" (regexp-quote
10018 (expand-file-name
10019 (file-name-as-directory
10020 default-directory))))
10021 (expand-file-name path))
10022 ;; We are linking a file with relative path name.
10023 (setq path (substring (expand-file-name path)
10024 (match-end 0)))
10025 (setq path (abbreviate-file-name (expand-file-name path)))))))
10026 (setq link (concat type path))
10027 (when (equal desc origpath)
10028 (setq desc path)))))
10030 (unless auto-desc
10031 (let ((initial-input
10032 (cond
10033 (default-description)
10034 ((not org-make-link-description-function) desc)
10035 (t (condition-case nil
10036 (funcall org-make-link-description-function link desc)
10037 (error
10038 (message "Can't get link description from `%s'"
10039 (symbol-name org-make-link-description-function))
10040 (sit-for 2)
10041 nil))))))
10042 (setq desc (read-string "Description: " initial-input))))
10044 (unless (string-match "\\S-" desc) (setq desc nil))
10045 (when remove (apply 'delete-region remove))
10046 (insert (org-make-link-string link desc))
10047 ;; Redisplay so as the new link has proper invisible characters.
10048 (sit-for 0)))
10050 (defun org-link-try-special-completion (type)
10051 "If there is completion support for link type TYPE, offer it."
10052 (let ((fun (org-link-get-parameter type :complete)))
10053 (if (functionp fun)
10054 (funcall fun)
10055 (read-string "Link (no completion support): " (concat type ":")))))
10057 (defun org-file-complete-link (&optional arg)
10058 "Create a file link using completion."
10059 (let ((file (read-file-name "File: "))
10060 (pwd (file-name-as-directory (expand-file-name ".")))
10061 (pwd1 (file-name-as-directory (abbreviate-file-name
10062 (expand-file-name ".")))))
10063 (cond ((equal arg '(16))
10064 (concat "file:"
10065 (abbreviate-file-name (expand-file-name file))))
10066 ((string-match
10067 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10068 (concat "file:" (match-string 1 file)))
10069 ((string-match
10070 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10071 (expand-file-name file))
10072 (concat "file:"
10073 (match-string 1 (expand-file-name file))))
10074 (t (concat "file:" file)))))
10077 ;;; Opening/following a link
10079 (defvar org-link-search-failed nil)
10081 (defvar org-open-link-functions nil
10082 "Hook for functions finding a plain text link.
10083 These functions must take a single argument, the link content.
10084 They will be called for links that look like [[link text][description]]
10085 when LINK TEXT does not have a protocol like \"http:\" and does not look
10086 like a filename (e.g. \"./blue.png\").
10088 These functions will be called *before* Org attempts to resolve the
10089 link by doing text searches in the current buffer - so if you want a
10090 link \"[[target]]\" to still find \"<<target>>\", your function should
10091 handle this as a special case.
10093 When the function does handle the link, it must return a non-nil value.
10094 If it decides that it is not responsible for this link, it must return
10095 nil to indicate that that Org can continue with other options like
10096 exact and fuzzy text search.")
10098 (defun org-next-link (&optional search-backward)
10099 "Move forward to the next link.
10100 If the link is in hidden text, expose it."
10101 (interactive "P")
10102 (when (and org-link-search-failed (eq this-command last-command))
10103 (goto-char (point-min))
10104 (message "Link search wrapped back to beginning of buffer"))
10105 (setq org-link-search-failed nil)
10106 (let* ((pos (point))
10107 (ct (org-context))
10108 (a (assq :link ct))
10109 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10110 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10111 ((looking-at org-any-link-re)
10112 ;; Don't stay stuck at link without an org-link face
10113 (forward-char (if search-backward -1 1))))
10114 (if (funcall srch-fun org-any-link-re nil t)
10115 (progn
10116 (goto-char (match-beginning 0))
10117 (when (org-invisible-p) (org-show-context)))
10118 (goto-char pos)
10119 (setq org-link-search-failed t)
10120 (message "No further link found"))))
10122 (defun org-previous-link ()
10123 "Move backward to the previous link.
10124 If the link is in hidden text, expose it."
10125 (interactive)
10126 (funcall 'org-next-link t))
10128 (defun org-translate-link (s)
10129 "Translate a link string if a translation function has been defined."
10130 (with-temp-buffer
10131 (insert (org-trim s))
10132 (org-trim (org-element-interpret-data (org-element-context)))))
10134 (defun org-translate-link-from-planner (type path)
10135 "Translate a link from Emacs Planner syntax so that Org can follow it.
10136 This is still an experimental function, your mileage may vary."
10137 (cond
10138 ((member type '("http" "https" "news" "ftp"))
10139 ;; standard Internet links are the same.
10140 nil)
10141 ((and (equal type "irc") (string-match "^//" path))
10142 ;; Planner has two / at the beginning of an irc link, we have 1.
10143 ;; We should have zero, actually....
10144 (setq path (substring path 1)))
10145 ((and (equal type "lisp") (string-match "^/" path))
10146 ;; Planner has a slash, we do not.
10147 (setq type "elisp" path (substring path 1)))
10148 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10149 ;; A typical message link. Planner has the id after the final slash,
10150 ;; we separate it with a hash mark
10151 (setq path (concat (match-string 1 path) "#"
10152 (org-unbracket-string "<" ">" (match-string 2 path))))))
10153 (cons type path))
10155 (defun org-find-file-at-mouse (ev)
10156 "Open file link or URL at mouse."
10157 (interactive "e")
10158 (mouse-set-point ev)
10159 (org-open-at-point 'in-emacs))
10161 (defun org-open-at-mouse (ev)
10162 "Open file link or URL at mouse.
10163 See the docstring of `org-open-file' for details."
10164 (interactive "e")
10165 (mouse-set-point ev)
10166 (when (eq major-mode 'org-agenda-mode)
10167 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10168 (org-open-at-point))
10170 (defvar org-window-config-before-follow-link nil
10171 "The window configuration before following a link.
10172 This is saved in case the need arises to restore it.")
10174 ;;;###autoload
10175 (defun org-open-at-point-global ()
10176 "Follow a link or time-stamp like Org mode does.
10177 This command can be called in any mode to follow an external link
10178 or a time-stamp that has Org mode syntax. Its behavior is
10179 undefined when called on internal links (e.g., fuzzy links).
10180 Raise an error when there is nothing to follow. "
10181 (interactive)
10182 (cond ((org-in-regexp org-any-link-re)
10183 (org-open-link-from-string (match-string-no-properties 0)))
10184 ((or (org-in-regexp org-ts-regexp-both nil t)
10185 (org-in-regexp org-tsr-regexp-both nil t))
10186 (org-follow-timestamp-link))
10187 (t (user-error "No link found"))))
10189 ;;;###autoload
10190 (defun org-open-link-from-string (s &optional arg reference-buffer)
10191 "Open a link in the string S, as if it was in Org mode."
10192 (interactive "sLink: \nP")
10193 (let ((reference-buffer (or reference-buffer (current-buffer))))
10194 (with-temp-buffer
10195 (let ((org-inhibit-startup (not reference-buffer)))
10196 (org-mode)
10197 (insert s)
10198 (goto-char (point-min))
10199 (when reference-buffer
10200 (setq org-link-abbrev-alist-local
10201 (with-current-buffer reference-buffer
10202 org-link-abbrev-alist-local)))
10203 (org-open-at-point arg reference-buffer)))))
10205 (defvar org-open-at-point-functions nil
10206 "Hook that is run when following a link at point.
10208 Functions in this hook must return t if they identify and follow
10209 a link at point. If they don't find anything interesting at point,
10210 they must return nil.")
10212 (defvar org-link-search-inhibit-query nil)
10213 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10214 (defun org--open-doi-link (path)
10215 "Open a \"doi\" type link.
10216 PATH is a the path to search for, as a string."
10217 (browse-url (url-encode-url (concat org-doi-server-url path))))
10219 (defun org--open-elisp-link (path)
10220 "Open a \"elisp\" type link.
10221 PATH is the sexp to evaluate, as a string."
10222 (let ((cmd path))
10223 (if (or (and (org-string-nw-p
10224 org-confirm-elisp-link-not-regexp)
10225 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10226 (not org-confirm-elisp-link-function)
10227 (funcall org-confirm-elisp-link-function
10228 (format "Execute \"%s\" as elisp? "
10229 (org-add-props cmd nil 'face 'org-warning))))
10230 (message "%s => %s" cmd
10231 (if (eq (string-to-char cmd) ?\()
10232 (eval (read cmd))
10233 (call-interactively (read cmd))))
10234 (user-error "Abort"))))
10236 (defun org--open-help-link (path)
10237 "Open a \"help\" type link.
10238 PATH is a symbol name, as a string."
10239 (pcase (intern path)
10240 ((and (pred fboundp) variable) (describe-function variable))
10241 ((and (pred boundp) function) (describe-variable function))
10242 (name (user-error "Unknown function or variable: %s" name))))
10244 (defun org--open-shell-link (path)
10245 "Open a \"shell\" type link.
10246 PATH is the command to execute, as a string."
10247 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10248 (cmd path))
10249 (if (or (and (org-string-nw-p
10250 org-confirm-shell-link-not-regexp)
10251 (string-match
10252 org-confirm-shell-link-not-regexp cmd))
10253 (not org-confirm-shell-link-function)
10254 (funcall org-confirm-shell-link-function
10255 (format "Execute \"%s\" in shell? "
10256 (org-add-props cmd nil
10257 'face 'org-warning))))
10258 (progn
10259 (message "Executing %s" cmd)
10260 (shell-command cmd buf)
10261 (when (featurep 'midnight)
10262 (setq clean-buffer-list-kill-buffer-names
10263 (cons (buffer-name buf)
10264 clean-buffer-list-kill-buffer-names))))
10265 (user-error "Abort"))))
10267 (defun org-open-at-point (&optional arg reference-buffer)
10268 "Open link, timestamp, footnote or tags at point.
10270 When point is on a link, follow it. Normally, files will be
10271 opened by an appropriate application. If the optional prefix
10272 argument ARG is non-nil, Emacs will visit the file. With
10273 a double prefix argument, try to open outside of Emacs, in the
10274 application the system uses for this file type.
10276 When point is on a timestamp, open the agenda at the day
10277 specified.
10279 When point is a footnote definition, move to the first reference
10280 found. If it is on a reference, move to the associated
10281 definition.
10283 When point is on a headline, display a list of every link in the
10284 entry, so it is possible to pick one, or all, of them. If point
10285 is on a tag, call `org-tags-view' instead.
10287 When optional argument REFERENCE-BUFFER is non-nil, it should
10288 specify a buffer from where the link search should happen. This
10289 is used internally by `org-open-link-from-string'.
10291 On top of syntactically correct links, this function will also
10292 try to open links and time-stamps in comments, example
10293 blocks... i.e., whenever point is on something looking like
10294 a timestamp or a link."
10295 (interactive "P")
10296 ;; On a code block, open block's results.
10297 (unless (call-interactively 'org-babel-open-src-block-result)
10298 (org-load-modules-maybe)
10299 (setq org-window-config-before-follow-link (current-window-configuration))
10300 (org-remove-occur-highlights nil nil t)
10301 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10302 (let* ((context
10303 ;; Only consider supported types, even if they are not
10304 ;; the closest one.
10305 (org-element-lineage
10306 (org-element-context)
10307 '(clock footnote-definition footnote-reference headline
10308 inlinetask link timestamp)
10310 (type (org-element-type context))
10311 (value (org-element-property :value context)))
10312 (cond
10313 ;; On a headline or an inlinetask, but not on a timestamp,
10314 ;; a link, a footnote reference.
10315 ((memq type '(headline inlinetask))
10316 (org-match-line org-complex-heading-regexp)
10317 (if (and (match-beginning 5)
10318 (>= (point) (match-beginning 5))
10319 (< (point) (match-end 5)))
10320 ;; On tags.
10321 (org-tags-view arg (substring (match-string 5) 0 -1))
10322 ;; Not on tags.
10323 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10324 (`(nil . ,_)
10325 (require 'org-attach)
10326 (org-attach-reveal 'if-exists))
10327 (`(,links . ,links-end)
10328 (dolist (link (if (stringp links) (list links) links))
10329 (search-forward link nil links-end)
10330 (goto-char (match-beginning 0))
10331 (org-open-at-point))))))
10332 ;; On a footnote reference or at definition's label.
10333 ((or (eq type 'footnote-reference)
10334 (and (eq type 'footnote-definition)
10335 (save-excursion
10336 ;; Do not validate action when point is on the
10337 ;; spaces right after the footnote label, in
10338 ;; order to be on par with behaviour on links.
10339 (skip-chars-forward " \t")
10340 (let ((begin
10341 (org-element-property :contents-begin context)))
10342 (if begin (< (point) begin)
10343 (= (org-element-property :post-affiliated context)
10344 (line-beginning-position)))))))
10345 (org-footnote-action))
10346 ;; No valid context. Ignore catch-all types like `headline'.
10347 ;; If point is on something looking like a link or
10348 ;; a time-stamp, try opening it. It may be useful in
10349 ;; comments, example blocks...
10350 ((memq type '(footnote-definition headline inlinetask nil))
10351 (call-interactively #'org-open-at-point-global))
10352 ;; On a clock line, make sure point is on the timestamp
10353 ;; before opening it.
10354 ((and (eq type 'clock)
10355 value
10356 (>= (point) (org-element-property :begin value))
10357 (<= (point) (org-element-property :end value)))
10358 (org-follow-timestamp-link))
10359 ;; Do nothing on white spaces after an object.
10360 ((>= (point)
10361 (save-excursion
10362 (goto-char (org-element-property :end context))
10363 (skip-chars-backward " \t")
10364 (point)))
10365 (user-error "No link found"))
10366 ((eq type 'timestamp) (org-follow-timestamp-link))
10367 ((eq type 'link)
10368 (let ((type (org-element-property :type context))
10369 (path (org-link-unescape (org-element-property :path context))))
10370 ;; Switch back to REFERENCE-BUFFER needed when called in
10371 ;; a temporary buffer through `org-open-link-from-string'.
10372 (with-current-buffer (or reference-buffer (current-buffer))
10373 (cond
10374 ((equal type "file")
10375 (if (string-match "[*?{]" (file-name-nondirectory path))
10376 (dired path)
10377 ;; Look into `org-link-parameters' in order to find
10378 ;; a DEDICATED-FUNCTION to open file. The function
10379 ;; will be applied on raw link instead of parsed
10380 ;; link due to the limitation in `org-add-link-type'
10381 ;; ("open" function called with a single argument).
10382 ;; If no such function is found, fallback to
10383 ;; `org-open-file'.
10384 (let* ((option (org-element-property :search-option context))
10385 (app (org-element-property :application context))
10386 (dedicated-function
10387 (org-link-get-parameter
10388 (if app (concat type "+" app) type)
10389 :follow)))
10390 (if dedicated-function
10391 (funcall dedicated-function
10392 (concat path
10393 (and option (concat "::" option))))
10394 (apply #'org-open-file
10395 path
10396 (cond (arg)
10397 ((equal app "emacs") 'emacs)
10398 ((equal app "sys") 'system))
10399 (cond ((not option) nil)
10400 ((string-match-p "\\`[0-9]+\\'" option)
10401 (list (string-to-number option)))
10402 (t (list nil
10403 (org-link-unescape option)))))))))
10404 ((functionp (org-link-get-parameter type :follow))
10405 (funcall (org-link-get-parameter type :follow) path))
10406 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10407 (unless (run-hook-with-args-until-success
10408 'org-open-link-functions path)
10409 (if (not arg) (org-mark-ring-push)
10410 (switch-to-buffer-other-window
10411 (org-get-buffer-for-internal-link (current-buffer))))
10412 (let ((destination
10413 (org-with-wide-buffer
10414 (if (equal type "radio")
10415 (org-search-radio-target
10416 (org-element-property :path context))
10417 (org-link-search
10418 (if (member type '("custom-id" "coderef"))
10419 (org-element-property :raw-link context)
10420 path)
10421 ;; Prevent fuzzy links from matching
10422 ;; themselves.
10423 (and (equal type "fuzzy")
10424 (+ 2 (org-element-property :begin context)))))
10425 (point))))
10426 (unless (and (<= (point-min) destination)
10427 (>= (point-max) destination))
10428 (widen))
10429 (goto-char destination))))
10430 (t (browse-url-at-point))))))
10431 (t (user-error "No link found")))))
10432 (run-hook-with-args 'org-follow-link-hook)))
10434 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10435 "Offer links in the current entry and return the selected link.
10436 If there is only one link, return it.
10437 If NTH is an integer, return the NTH link found.
10438 If ZERO is a string, check also this string for a link, and if
10439 there is one, return it."
10440 (with-current-buffer buffer
10441 (org-with-wide-buffer
10442 (goto-char marker)
10443 (let ((cnt ?0)
10444 have-zero end links link c)
10445 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10446 (push (match-string 0 zero) links)
10447 (setq cnt (1- cnt) have-zero t))
10448 (save-excursion
10449 (org-back-to-heading t)
10450 (setq end (save-excursion (outline-next-heading) (point)))
10451 (while (re-search-forward org-any-link-re end t)
10452 (push (match-string 0) links))
10453 (setq links (org-uniquify (reverse links))))
10454 (cond
10455 ((null links)
10456 (message "No links"))
10457 ((equal (length links) 1)
10458 (setq link (car links)))
10459 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10460 (setq link (nth (if have-zero nth (1- nth)) links)))
10461 (t ; we have to select a link
10462 (save-excursion
10463 (save-window-excursion
10464 (delete-other-windows)
10465 (with-output-to-temp-buffer "*Select Link*"
10466 (dolist (l links)
10467 (cond
10468 ((not (string-match org-bracket-link-regexp l))
10469 (princ (format "[%c] %s\n" (cl-incf cnt)
10470 (org-unbracket-string "<" ">" l))))
10471 ((match-end 3)
10472 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10473 (match-string 3 l) (match-string 1 l))))
10474 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10475 (match-string 1 l)))))))
10476 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10477 (message "Select link to open, RET to open all:")
10478 (setq c (read-char-exclusive))
10479 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10480 (when (equal c ?q) (user-error "Abort"))
10481 (if (equal c ?\C-m)
10482 (setq link links)
10483 (setq nth (- c ?0))
10484 (when have-zero (setq nth (1+ nth)))
10485 (unless (and (integerp nth) (>= (length links) nth))
10486 (user-error "Invalid link selection"))
10487 (setq link (nth (1- nth) links)))))
10488 (cons link end)))))
10490 ;; TODO: These functions are deprecated since `org-open-at-point'
10491 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10492 (defun org-open-file-with-system (path)
10493 "Open file at PATH using the system way of opening it."
10494 (org-open-file path 'system))
10495 (defun org-open-file-with-emacs (path)
10496 "Open file at PATH in Emacs."
10497 (org-open-file path 'emacs))
10500 ;;; File search
10502 (defvar org-create-file-search-functions nil
10503 "List of functions to construct the right search string for a file link.
10504 These functions are called in turn with point at the location to
10505 which the link should point.
10507 A function in the hook should first test if it would like to
10508 handle this file type, for example by checking the `major-mode'
10509 or the file extension. If it decides not to handle this file, it
10510 should just return nil to give other functions a chance. If it
10511 does handle the file, it must return the search string to be used
10512 when following the link. The search string will be part of the
10513 file link, given after a double colon, and `org-open-at-point'
10514 will automatically search for it. If special measures must be
10515 taken to make the search successful, another function should be
10516 added to the companion hook `org-execute-file-search-functions',
10517 which see.
10519 A function in this hook may also use `setq' to set the variable
10520 `description' to provide a suggestion for the descriptive text to
10521 be used for this link when it gets inserted into an Org buffer
10522 with \\[org-insert-link].")
10524 (defvar org-execute-file-search-functions nil
10525 "List of functions to execute a file search triggered by a link.
10527 Functions added to this hook must accept a single argument, the
10528 search string that was part of the file link, the part after the
10529 double colon. The function must first check if it would like to
10530 handle this search, for example by checking the `major-mode' or
10531 the file extension. If it decides not to handle this search, it
10532 should just return nil to give other functions a chance. If it
10533 does handle the search, it must return a non-nil value to keep
10534 other functions from trying.
10536 Each function can access the current prefix argument through the
10537 variable `current-prefix-arg'. Note that a single prefix is used
10538 to force opening a link in Emacs, so it may be good to only use a
10539 numeric or double prefix to guide the search function.
10541 In case this is needed, a function in this hook can also restore
10542 the window configuration before `org-open-at-point' was called using:
10544 (set-window-configuration org-window-config-before-follow-link)")
10546 (defun org-search-radio-target (target)
10547 "Search a radio target matching TARGET in current buffer.
10548 White spaces are not significant."
10549 (let ((re (format "<<<%s>>>"
10550 (mapconcat #'regexp-quote
10551 (split-string target)
10552 "[ \t]+\\(?:\n[ \t]*\\)?")))
10553 (origin (point)))
10554 (goto-char (point-min))
10555 (catch :radio-match
10556 (while (re-search-forward re nil t)
10557 (backward-char)
10558 (let ((object (org-element-context)))
10559 (when (eq (org-element-type object) 'radio-target)
10560 (goto-char (org-element-property :begin object))
10561 (org-show-context 'link-search)
10562 (throw :radio-match nil))))
10563 (goto-char origin)
10564 (user-error "No match for radio target: %s" target))))
10566 (defun org-link-search (s &optional avoid-pos stealth)
10567 "Search for a search string S.
10569 If S starts with \"#\", it triggers a custom ID search.
10571 If S is enclosed within parenthesis, it initiates a coderef
10572 search.
10574 If S is surrounded by forward slashes, it is interpreted as
10575 a regular expression. In Org mode files, this will create an
10576 `org-occur' sparse tree. In ordinary files, `occur' will be used
10577 to list matches. If the current buffer is in `dired-mode', grep
10578 will be used to search in all files.
10580 When AVOID-POS is given, ignore matches near that position.
10582 When optional argument STEALTH is non-nil, do not modify
10583 visibility around point, thus ignoring `org-show-context-detail'
10584 variable.
10586 Search is case-insensitive and ignores white spaces. Return type
10587 of matched result, which is either `dedicated' or `fuzzy'."
10588 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10589 (let* ((case-fold-search t)
10590 (origin (point))
10591 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10592 (starred (eq (string-to-char normalized) ?*))
10593 (words (split-string (if starred (substring s 1) s)))
10594 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10595 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10596 type)
10597 (cond
10598 ;; Check if there are any special search functions.
10599 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10600 ((eq (string-to-char s) ?#)
10601 ;; Look for a custom ID S if S starts with "#".
10602 (let* ((id (substring normalized 1))
10603 (match (org-find-property "CUSTOM_ID" id)))
10604 (if match (progn (goto-char match) (setf type 'dedicated))
10605 (error "No match for custom ID: %s" id))))
10606 ((string-match "\\`(\\(.*\\))\\'" normalized)
10607 ;; Look for coderef targets if S is enclosed within parenthesis.
10608 (let ((coderef (match-string-no-properties 1 normalized))
10609 (re (substring s-single-re 1 -1)))
10610 (goto-char (point-min))
10611 (catch :coderef-match
10612 (while (re-search-forward re nil t)
10613 (let ((element (org-element-at-point)))
10614 (when (and (memq (org-element-type element)
10615 '(example-block src-block))
10616 ;; Build proper regexp according to current
10617 ;; block's label format.
10618 (let ((label-fmt
10619 (regexp-quote
10620 (or (org-element-property :label-fmt element)
10621 org-coderef-label-format))))
10622 (save-excursion
10623 (beginning-of-line)
10624 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10625 (format label-fmt coderef))))))
10626 (setq type 'dedicated)
10627 (goto-char (match-beginning 1))
10628 (throw :coderef-match nil))))
10629 (goto-char origin)
10630 (error "No match for coderef: %s" coderef))))
10631 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10632 ;; Look for a regular expression.
10633 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10634 (match-string 1 s)))
10635 ;; From here, we handle fuzzy links.
10637 ;; Look for targets, only if not in a headline search.
10638 ((and (not starred)
10639 (let ((target (format "<<%s>>" s-multi-re)))
10640 (catch :target-match
10641 (goto-char (point-min))
10642 (while (re-search-forward target nil t)
10643 (backward-char)
10644 (let ((context (org-element-context)))
10645 (when (eq (org-element-type context) 'target)
10646 (setq type 'dedicated)
10647 (goto-char (org-element-property :begin context))
10648 (throw :target-match t))))
10649 nil))))
10650 ;; Look for elements named after S, only if not in a headline
10651 ;; search.
10652 ((and (not starred)
10653 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10654 (catch :name-match
10655 (goto-char (point-min))
10656 (while (re-search-forward name nil t)
10657 (let ((element (org-element-at-point)))
10658 (when (equal words
10659 (split-string
10660 (org-element-property :name element)))
10661 (setq type 'dedicated)
10662 (beginning-of-line)
10663 (throw :name-match t))))
10664 nil))))
10665 ;; Regular text search. Prefer headlines in Org mode buffers.
10666 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10667 ;; statistics cookies and tags.
10668 ((and (derived-mode-p 'org-mode)
10669 (let ((title-re
10670 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10671 org-outline-regexp-bol
10672 org-comment-string
10673 (mapconcat #'regexp-quote words ".+")))
10674 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10675 (comment-re (eval-when-compile
10676 (format "\\`%s[ \t]+" org-comment-string))))
10677 (goto-char (point-min))
10678 (catch :found
10679 (while (re-search-forward title-re nil t)
10680 (when (equal words
10681 (split-string
10682 (replace-regexp-in-string
10683 cookie-re ""
10684 (replace-regexp-in-string
10685 comment-re "" (org-get-heading t t t)))))
10686 (throw :found t)))
10687 nil)))
10688 (beginning-of-line)
10689 (setq type 'dedicated))
10690 ;; Offer to create non-existent headline depending on
10691 ;; `org-link-search-must-match-exact-headline'.
10692 ((and (derived-mode-p 'org-mode)
10693 (not org-link-search-inhibit-query)
10694 (eq org-link-search-must-match-exact-headline 'query-to-create)
10695 (yes-or-no-p "No match - create this as a new heading? "))
10696 (goto-char (point-max))
10697 (unless (bolp) (newline))
10698 (org-insert-heading nil t t)
10699 (insert s "\n")
10700 (beginning-of-line 0))
10701 ;; Only headlines are looked after. No need to process
10702 ;; further: throw an error.
10703 ((and (derived-mode-p 'org-mode)
10704 (or starred org-link-search-must-match-exact-headline))
10705 (goto-char origin)
10706 (error "No match for fuzzy expression: %s" normalized))
10707 ;; Regular text search.
10708 ((catch :fuzzy-match
10709 (goto-char (point-min))
10710 (while (re-search-forward s-multi-re nil t)
10711 ;; Skip match if it contains AVOID-POS or it is included in
10712 ;; a link with a description but outside the description.
10713 (unless (or (and avoid-pos
10714 (<= (match-beginning 0) avoid-pos)
10715 (> (match-end 0) avoid-pos))
10716 (and (save-match-data
10717 (org-in-regexp org-bracket-link-regexp))
10718 (match-beginning 3)
10719 (or (> (match-beginning 3) (point))
10720 (<= (match-end 3) (point)))
10721 (org-element-lineage
10722 (save-match-data (org-element-context))
10723 '(link) t)))
10724 (goto-char (match-beginning 0))
10725 (setq type 'fuzzy)
10726 (throw :fuzzy-match t)))
10727 nil))
10728 ;; All failed. Throw an error.
10729 (t (goto-char origin)
10730 (error "No match for fuzzy expression: %s" normalized)))
10731 ;; Disclose surroundings of match, if appropriate.
10732 (when (and (derived-mode-p 'org-mode) (not stealth))
10733 (org-show-context 'link-search))
10734 type))
10736 (defun org-get-buffer-for-internal-link (buffer)
10737 "Return a buffer to be used for displaying the link target of internal links."
10738 (cond
10739 ((not org-display-internal-link-with-indirect-buffer)
10740 buffer)
10741 ((string-suffix-p "(Clone)" (buffer-name buffer))
10742 (message "Buffer is already a clone, not making another one")
10743 ;; we also do not modify visibility in this case
10744 buffer)
10745 (t ; make a new indirect buffer for displaying the link
10746 (let* ((bn (buffer-name buffer))
10747 (ibn (concat bn "(Clone)"))
10748 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10749 (with-current-buffer ib (org-overview))
10750 ib))))
10752 (defun org-do-occur (regexp &optional cleanup)
10753 "Call the Emacs command `occur'.
10754 If CLEANUP is non-nil, remove the printout of the regular expression
10755 in the *Occur* buffer. This is useful if the regex is long and not useful
10756 to read."
10757 (occur regexp)
10758 (when cleanup
10759 (let ((cwin (selected-window)) win beg end)
10760 (when (setq win (get-buffer-window "*Occur*"))
10761 (select-window win))
10762 (goto-char (point-min))
10763 (when (re-search-forward "match[a-z]+" nil t)
10764 (setq beg (match-end 0))
10765 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10766 (setq end (1- (match-beginning 0)))))
10767 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10768 (goto-char (point-min))
10769 (select-window cwin))))
10771 ;;; The mark ring for links jumps
10773 (defvar org-mark-ring nil
10774 "Mark ring for positions before jumps in Org mode.")
10775 (defvar org-mark-ring-last-goto nil
10776 "Last position in the mark ring used to go back.")
10777 ;; Fill and close the ring
10778 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10779 (dotimes (_ org-mark-ring-length)
10780 (push (make-marker) org-mark-ring))
10781 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10782 org-mark-ring)
10784 (defun org-mark-ring-push (&optional pos buffer)
10785 "Put the current position or POS into the mark ring and rotate it."
10786 (interactive)
10787 (setq pos (or pos (point)))
10788 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10789 (move-marker (car org-mark-ring)
10790 (or pos (point))
10791 (or buffer (current-buffer)))
10792 (message "%s"
10793 (substitute-command-keys
10794 "Position saved to mark ring, go back with \
10795 `\\[org-mark-ring-goto]'.")))
10797 (defun org-mark-ring-goto (&optional n)
10798 "Jump to the previous position in the mark ring.
10799 With prefix arg N, jump back that many stored positions. When
10800 called several times in succession, walk through the entire ring.
10801 Org mode commands jumping to a different position in the current file,
10802 or to another Org file, automatically push the old position onto the ring."
10803 (interactive "p")
10804 (let (p m)
10805 (if (eq last-command this-command)
10806 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10807 (setq p org-mark-ring))
10808 (setq org-mark-ring-last-goto p)
10809 (setq m (car p))
10810 (pop-to-buffer-same-window (marker-buffer m))
10811 (goto-char m)
10812 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10814 (defun org-add-angle-brackets (s)
10815 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10816 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10819 ;;; Following specific links
10821 (defvar org-agenda-buffer-tmp-name)
10822 (defvar org-agenda-start-on-weekday)
10823 (defun org-follow-timestamp-link ()
10824 "Open an agenda view for the time-stamp date/range at point."
10825 (cond
10826 ((org-at-date-range-p t)
10827 (let ((org-agenda-start-on-weekday)
10828 (t1 (match-string 1))
10829 (t2 (match-string 2)) tt1 tt2)
10830 (setq tt1 (time-to-days (org-time-string-to-time t1))
10831 tt2 (time-to-days (org-time-string-to-time t2)))
10832 (let ((org-agenda-buffer-tmp-name
10833 (format "*Org Agenda(a:%s)"
10834 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10835 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10836 ((org-at-timestamp-p 'lax)
10837 (let ((org-agenda-buffer-tmp-name
10838 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10839 (org-agenda-list nil (time-to-days (org-time-string-to-time
10840 (substring (match-string 1) 0 10)))
10841 1)))
10842 (t (error "This should not happen"))))
10845 ;;; Following file links
10846 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10847 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10848 (declare-function mailcap-mime-info
10849 "mailcap" (string &optional request no-decode))
10850 (defvar org-wait nil)
10851 (defun org-open-file (path &optional in-emacs line search)
10852 "Open the file at PATH.
10853 First, this expands any special file name abbreviations. Then the
10854 configuration variable `org-file-apps' is checked if it contains an
10855 entry for this file type, and if yes, the corresponding command is launched.
10857 If no application is found, Emacs simply visits the file.
10859 With optional prefix argument IN-EMACS, Emacs will visit the file.
10860 With a double \\[universal-argument] \\[universal-argument] \
10861 prefix arg, Org tries to avoid opening in Emacs
10862 and to use an external application to visit the file.
10864 Optional LINE specifies a line to go to, optional SEARCH a string
10865 to search for. If LINE or SEARCH is given, the file will be
10866 opened in Emacs, unless an entry from org-file-apps that makes
10867 use of groups in a regexp matches.
10869 If you want to change the way frames are used when following a
10870 link, please customize `org-link-frame-setup'.
10872 If the file does not exist, an error is thrown."
10873 (let* ((file (if (equal path "")
10874 buffer-file-name
10875 (substitute-in-file-name (expand-file-name path))))
10876 (file-apps (append org-file-apps (org-default-apps)))
10877 (apps (cl-remove-if
10878 'org-file-apps-entry-match-against-dlink-p file-apps))
10879 (apps-dlink (cl-remove-if-not
10880 'org-file-apps-entry-match-against-dlink-p file-apps))
10881 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10882 (dirp (unless remp (file-directory-p file)))
10883 (file (if (and dirp org-open-directory-means-index-dot-org)
10884 (concat (file-name-as-directory file) "index.org")
10885 file))
10886 (a-m-a-p (assq 'auto-mode apps))
10887 (dfile (downcase file))
10888 ;; Reconstruct the original link from the PATH, LINE and
10889 ;; SEARCH args.
10890 (link (cond (line (concat file "::" (number-to-string line)))
10891 (search (concat file "::" search))
10892 (t file)))
10893 (dlink (downcase link))
10894 (ext
10895 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10896 (match-string 1 dfile)))
10897 (save-position-maybe
10898 (let ((old-buffer (current-buffer))
10899 (old-pos (point))
10900 (old-mode major-mode))
10901 (lambda ()
10902 (and (derived-mode-p 'org-mode)
10903 (eq old-mode 'org-mode)
10904 (or (not (eq old-buffer (current-buffer)))
10905 (not (eq old-pos (point))))
10906 (org-mark-ring-push old-pos old-buffer)))))
10907 cmd link-match-data)
10908 (cond
10909 ((member in-emacs '((16) system))
10910 (setq cmd (cdr (assq 'system apps))))
10911 (in-emacs (setq cmd 'emacs))
10913 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10914 (and dirp (cdr (assq 'directory apps)))
10915 ;; First, try matching against apps-dlink if we
10916 ;; get a match here, store the match data for
10917 ;; later.
10918 (let ((match (assoc-default dlink apps-dlink
10919 'string-match)))
10920 (if match
10921 (progn (setq link-match-data (match-data))
10922 match)
10923 (progn (setq in-emacs (or in-emacs line search))
10924 nil))) ; if we have no match in apps-dlink,
10925 ; always open the file in emacs if line or search
10926 ; is given (for backwards compatibility)
10927 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10928 'string-match)
10929 (cdr (assoc ext apps))
10930 (cdr (assq t apps))))))
10931 (when (eq cmd 'system)
10932 (setq cmd (cdr (assq 'system apps))))
10933 (when (eq cmd 'default)
10934 (setq cmd (cdr (assoc t apps))))
10935 (when (eq cmd 'mailcap)
10936 (require 'mailcap)
10937 (mailcap-parse-mailcaps)
10938 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10939 (command (mailcap-mime-info mime-type)))
10940 (if (stringp command)
10941 (setq cmd command)
10942 (setq cmd 'emacs))))
10943 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10944 (not (file-exists-p file))
10945 (not org-open-non-existing-files))
10946 (user-error "No such file: %s" file))
10947 (cond
10948 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10949 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10950 (while (string-match "['\"]%s['\"]" cmd)
10951 (setq cmd (replace-match "%s" t t cmd)))
10952 (setq cmd (replace-regexp-in-string
10953 "%s"
10954 (shell-quote-argument (convert-standard-filename file))
10956 nil t))
10958 ;; Replace "%1", "%2" etc. in command with group matches from regex
10959 (save-match-data
10960 (let ((match-index 1)
10961 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10962 (set-match-data link-match-data)
10963 (while (<= match-index number-of-groups)
10964 (let ((regex (concat "%" (number-to-string match-index)))
10965 (replace-with (match-string match-index dlink)))
10966 (while (string-match regex cmd)
10967 (setq cmd (replace-match replace-with t t cmd))))
10968 (setq match-index (+ match-index 1)))))
10970 (save-window-excursion
10971 (message "Running %s...done" cmd)
10972 (start-process-shell-command cmd nil cmd)
10973 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10974 ((or (stringp cmd)
10975 (eq cmd 'emacs))
10976 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10977 (widen)
10978 (cond (line (org-goto-line line)
10979 (when (derived-mode-p 'org-mode) (org-reveal)))
10980 (search (condition-case err
10981 (org-link-search search)
10982 ;; Save position before error-ing out so user
10983 ;; can easily move back to the original buffer.
10984 (error (funcall save-position-maybe)
10985 (error (nth 1 err)))))))
10986 ((functionp cmd)
10987 (save-match-data
10988 (set-match-data link-match-data)
10989 (condition-case nil
10990 (funcall cmd file link)
10991 ;; FIXME: Remove this check when most default installations
10992 ;; of Emacs have at least Org 9.0.
10993 ((debug wrong-number-of-arguments wrong-type-argument
10994 invalid-function)
10995 (user-error "Please see Org News for version 9.0 about \
10996 `org-file-apps'--Lisp error: %S" cmd)))))
10997 ((consp cmd)
10998 ;; FIXME: Remove this check when most default installations of
10999 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11000 ;; fall back to `org-link-frame-setup' for an old usage of
11001 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11002 (user-error "Please see Org News for version 9.0 about \
11003 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11004 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11005 (funcall save-position-maybe)))
11007 (defun org-file-apps-entry-match-against-dlink-p (entry)
11008 "This function returns non-nil if `entry' uses a regular
11009 expression which should be matched against the whole link by
11010 org-open-file.
11012 It assumes that is the case when the entry uses a regular
11013 expression which has at least one grouping construct and the
11014 action is either a lisp form or a command string containing
11015 `%1', i.e. using at least one subexpression match as a
11016 parameter."
11017 (let ((selector (car entry))
11018 (action (cdr entry)))
11019 (if (stringp selector)
11020 (and (> (regexp-opt-depth selector) 0)
11021 (or (and (stringp action)
11022 (string-match "%[0-9]" action))
11023 (consp action)))
11024 nil)))
11026 (defun org-default-apps ()
11027 "Return the default applications for this operating system."
11028 (cond
11029 ((eq system-type 'darwin)
11030 org-file-apps-defaults-macosx)
11031 ((eq system-type 'windows-nt)
11032 org-file-apps-defaults-windowsnt)
11033 (t org-file-apps-defaults-gnu)))
11035 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11036 "Convert extensions to regular expressions in the cars of LIST.
11037 Also, weed out any non-string entries, because the return value is used
11038 only for regexp matching.
11039 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11040 point to the symbol `emacs', indicating that the file should
11041 be opened in Emacs."
11042 (append
11043 (delq nil
11044 (mapcar (lambda (x)
11045 (unless (not (stringp (car x)))
11046 (if (string-match "\\W" (car x))
11048 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11049 list))
11050 (when add-auto-mode
11051 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11053 (defvar ange-ftp-name-format)
11054 (defun org-file-remote-p (file)
11055 "Test whether FILE specifies a location on a remote system.
11056 Return non-nil if the location is indeed remote.
11058 For example, the filename \"/user@host:/foo\" specifies a location
11059 on the system \"/user@host:\"."
11060 (cond ((fboundp 'file-remote-p)
11061 (file-remote-p file))
11062 ((fboundp 'tramp-handle-file-remote-p)
11063 (tramp-handle-file-remote-p file))
11064 ((and (boundp 'ange-ftp-name-format)
11065 (string-match (car ange-ftp-name-format) file))
11066 t)))
11069 ;;;; Refiling
11071 (defun org-get-org-file ()
11072 "Read a filename, with default directory `org-directory'."
11073 (let ((default (or org-default-notes-file remember-data-file)))
11074 (read-file-name (format "File name [%s]: " default)
11075 (file-name-as-directory org-directory)
11076 default)))
11078 (defun org-notes-order-reversed-p ()
11079 "Check if the current file should receive notes in reversed order."
11080 (cond
11081 ((not org-reverse-note-order) nil)
11082 ((eq t org-reverse-note-order) t)
11083 ((not (listp org-reverse-note-order)) nil)
11084 (t (catch 'exit
11085 (dolist (entry org-reverse-note-order)
11086 (when (string-match (car entry) buffer-file-name)
11087 (throw 'exit (cdr entry))))))))
11089 (defvar org-refile-target-table nil
11090 "The list of refile targets, created by `org-refile'.")
11092 (defvar org-agenda-new-buffers nil
11093 "Buffers created to visit agenda files.")
11095 (defvar org-refile-cache nil
11096 "Cache for refile targets.")
11098 (defvar org-refile-markers nil
11099 "All the markers used for caching refile locations.")
11101 (defun org-refile-marker (pos)
11102 "Get a new refile marker, but only if caching is in use."
11103 (if (not org-refile-use-cache)
11105 (let ((m (make-marker)))
11106 (move-marker m pos)
11107 (push m org-refile-markers)
11108 m)))
11110 (defun org-refile-cache-clear ()
11111 "Clear the refile cache and disable all the markers."
11112 (dolist (m org-refile-markers) (move-marker m nil))
11113 (setq org-refile-markers nil)
11114 (setq org-refile-cache nil)
11115 (message "Refile cache has been cleared"))
11117 (defun org-refile-cache-check-set (set)
11118 "Check if all the markers in the cache still have live buffers."
11119 (let (marker)
11120 (catch 'exit
11121 (while (and set (setq marker (nth 3 (pop set))))
11122 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11123 (when (and marker (null (marker-buffer marker)))
11124 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11125 (sit-for 3)
11126 (throw 'exit nil)))
11127 t)))
11129 (defun org-refile-cache-put (set &rest identifiers)
11130 "Push the refile targets SET into the cache, under IDENTIFIERS."
11131 (let* ((key (sha1 (prin1-to-string identifiers)))
11132 (entry (assoc key org-refile-cache)))
11133 (if entry
11134 (setcdr entry set)
11135 (push (cons key set) org-refile-cache))))
11137 (defun org-refile-cache-get (&rest identifiers)
11138 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11139 (cond
11140 ((not org-refile-cache) nil)
11141 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11143 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11144 org-refile-cache))))
11145 (and set (org-refile-cache-check-set set) set)))))
11147 (defvar org-outline-path-cache nil
11148 "Alist between buffer positions and outline paths.
11149 It value is an alist (POSITION . PATH) where POSITION is the
11150 buffer position at the beginning of an entry and PATH is a list
11151 of strings describing the outline path for that entry, in reverse
11152 order.")
11154 (defun org-refile-get-targets (&optional default-buffer)
11155 "Produce a table with refile targets."
11156 (let ((case-fold-search nil)
11157 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11158 (entries (or org-refile-targets '((nil . (:level . 1)))))
11159 targets tgs files desc descre)
11160 (message "Getting targets...")
11161 (with-current-buffer (or default-buffer (current-buffer))
11162 (dolist (entry entries)
11163 (setq files (car entry) desc (cdr entry))
11164 (cond
11165 ((null files) (setq files (list (current-buffer))))
11166 ((eq files 'org-agenda-files)
11167 (setq files (org-agenda-files 'unrestricted)))
11168 ((and (symbolp files) (fboundp files))
11169 (setq files (funcall files)))
11170 ((and (symbolp files) (boundp files))
11171 (setq files (symbol-value files))))
11172 (when (stringp files) (setq files (list files)))
11173 (cond
11174 ((eq (car desc) :tag)
11175 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11176 ((eq (car desc) :todo)
11177 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11178 ((eq (car desc) :regexp)
11179 (setq descre (cdr desc)))
11180 ((eq (car desc) :level)
11181 (setq descre (concat "^\\*\\{" (number-to-string
11182 (if org-odd-levels-only
11183 (1- (* 2 (cdr desc)))
11184 (cdr desc)))
11185 "\\}[ \t]")))
11186 ((eq (car desc) :maxlevel)
11187 (setq descre (concat "^\\*\\{1," (number-to-string
11188 (if org-odd-levels-only
11189 (1- (* 2 (cdr desc)))
11190 (cdr desc)))
11191 "\\}[ \t]")))
11192 (t (error "Bad refiling target description %s" desc)))
11193 (dolist (f files)
11194 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11196 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11197 (progn
11198 (when (bufferp f)
11199 (setq f (buffer-file-name (buffer-base-buffer f))))
11200 (setq f (and f (expand-file-name f)))
11201 (when (eq org-refile-use-outline-path 'file)
11202 (push (list (file-name-nondirectory f) f nil nil) tgs))
11203 (when (eq org-refile-use-outline-path 'buffer-name)
11204 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11205 (when (eq org-refile-use-outline-path 'full-file-path)
11206 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11207 (org-with-wide-buffer
11208 (goto-char (point-min))
11209 (setq org-outline-path-cache nil)
11210 (while (re-search-forward descre nil t)
11211 (beginning-of-line)
11212 (let ((case-fold-search nil))
11213 (looking-at org-complex-heading-regexp))
11214 (let ((begin (point))
11215 (heading (match-string-no-properties 4)))
11216 (unless (or (and
11217 org-refile-target-verify-function
11218 (not
11219 (funcall org-refile-target-verify-function)))
11220 (not heading))
11221 (let ((re (format org-complex-heading-regexp-format
11222 (regexp-quote heading)))
11223 (target
11224 (if (not org-refile-use-outline-path) heading
11225 (mapconcat
11226 #'identity
11227 (append
11228 (pcase org-refile-use-outline-path
11229 (`file (list (file-name-nondirectory
11230 (buffer-file-name
11231 (buffer-base-buffer)))))
11232 (`full-file-path
11233 (list (buffer-file-name
11234 (buffer-base-buffer))))
11235 (`buffer-name
11236 (list (buffer-name
11237 (buffer-base-buffer))))
11238 (_ nil))
11239 (mapcar (lambda (s) (replace-regexp-in-string
11240 "/" "\\/" s nil t))
11241 (org-get-outline-path t t)))
11242 "/"))))
11243 (push (list target f re (org-refile-marker (point)))
11244 tgs)))
11245 (when (= (point) begin)
11246 ;; Verification function has not moved point.
11247 (end-of-line)))))))
11248 (when org-refile-use-cache
11249 (org-refile-cache-put tgs (buffer-file-name) descre))
11250 (setq targets (append tgs targets))))))
11251 (message "Getting targets...done")
11252 (delete-dups (nreverse targets))))
11254 (defun org--get-outline-path-1 (&optional use-cache)
11255 "Return outline path to current headline.
11257 Outline path is a list of strings, in reverse order. When
11258 optional argument USE-CACHE is non-nil, make use of a cache. See
11259 `org-get-outline-path' for details.
11261 Assume buffer is widened and point is on a headline."
11262 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11263 (let ((p (point))
11264 (heading (let ((case-fold-search nil))
11265 (looking-at org-complex-heading-regexp)
11266 (if (not (match-end 4)) ""
11267 ;; Remove statistics cookies.
11268 (org-trim
11269 (org-link-display-format
11270 (replace-regexp-in-string
11271 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11272 (match-string-no-properties 4))))))))
11273 (if (org-up-heading-safe)
11274 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11275 (when use-cache
11276 (push (cons p path) org-outline-path-cache))
11277 path)
11278 ;; This is a new root node. Since we assume we are moving
11279 ;; forward, we can drop previous cache so as to limit number
11280 ;; of associations there.
11281 (let ((path (list heading)))
11282 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11283 path)))))
11285 (defun org-get-outline-path (&optional with-self use-cache)
11286 "Return the outline path to the current entry.
11288 An outline path is a list of ancestors for current headline, as
11289 a list of strings. Statistics cookies are removed and links are
11290 replaced with their description, if any, or their path otherwise.
11292 When optional argument WITH-SELF is non-nil, the path also
11293 includes the current headline.
11295 When optional argument USE-CACHE is non-nil, cache outline paths
11296 between calls to this function so as to avoid backtracking. This
11297 argument is useful when planning to find more than one outline
11298 path in the same document. In that case, there are two
11299 conditions to satisfy:
11300 - `org-outline-path-cache' is set to nil before starting the
11301 process;
11302 - outline paths are computed by increasing buffer positions."
11303 (org-with-wide-buffer
11304 (and (or (and with-self (org-back-to-heading t))
11305 (org-up-heading-safe))
11306 (reverse (org--get-outline-path-1 use-cache)))))
11308 (defun org-format-outline-path (path &optional width prefix separator)
11309 "Format the outline path PATH for display.
11310 WIDTH is the maximum number of characters that is available.
11311 PREFIX is a prefix to be included in the returned string,
11312 such as the file name.
11313 SEPARATOR is inserted between the different parts of the path,
11314 the default is \"/\"."
11315 (setq width (or width 79))
11316 (setq path (delq nil path))
11317 (unless (> width 0)
11318 (user-error "Argument `width' must be positive"))
11319 (setq separator (or separator "/"))
11320 (let* ((org-odd-levels-only nil)
11321 (fpath (concat
11322 prefix (and prefix path separator)
11323 (mapconcat
11324 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11325 (cl-loop for head in path
11326 for n from 0
11327 collect (org-add-props
11328 head nil 'face
11329 (nth (% n org-n-level-faces) org-level-faces)))
11330 separator))))
11331 (when (> (length fpath) width)
11332 (if (< width 7)
11333 ;; It's unlikely that `width' will be this small, but don't
11334 ;; waste characters by adding ".." if it is.
11335 (setq fpath (substring fpath 0 width))
11336 (setf (substring fpath (- width 2)) "..")))
11337 fpath))
11339 (defun org-display-outline-path (&optional file current separator just-return-string)
11340 "Display the current outline path in the echo area.
11342 If FILE is non-nil, prepend the output with the file name.
11343 If CURRENT is non-nil, append the current heading to the output.
11344 SEPARATOR is passed through to `org-format-outline-path'. It separates
11345 the different parts of the path and defaults to \"/\".
11346 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11347 (interactive "P")
11348 (let* (case-fold-search
11349 (bfn (buffer-file-name (buffer-base-buffer)))
11350 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11351 res)
11352 (when current (setq path (append path
11353 (save-excursion
11354 (org-back-to-heading t)
11355 (when (looking-at org-complex-heading-regexp)
11356 (list (match-string 4)))))))
11357 (setq res
11358 (org-format-outline-path
11359 path
11360 (1- (frame-width))
11361 (and file bfn (concat (file-name-nondirectory bfn) separator))
11362 separator))
11363 (if just-return-string
11364 (org-no-properties res)
11365 (org-unlogged-message "%s" res))))
11367 (defvar org-refile-history nil
11368 "History for refiling operations.")
11370 (defvar org-after-refile-insert-hook nil
11371 "Hook run after `org-refile' has inserted its stuff at the new location.
11372 Note that this is still *before* the stuff will be removed from
11373 the *old* location.")
11375 (defvar org-capture-last-stored-marker)
11376 (defvar org-refile-keep nil
11377 "Non-nil means `org-refile' will copy instead of refile.")
11379 (defun org-copy ()
11380 "Like `org-refile', but copy."
11381 (interactive)
11382 (let ((org-refile-keep t))
11383 (funcall 'org-refile nil nil nil "Copy")))
11385 (defun org-refile (&optional arg default-buffer rfloc msg)
11386 "Move the entry or entries at point to another heading.
11388 The list of target headings is compiled using the information in
11389 `org-refile-targets', which see.
11391 At the target location, the entry is filed as a subitem of the
11392 target heading. Depending on `org-reverse-note-order', the new
11393 subitem will either be the first or the last subitem.
11395 If there is an active region, all entries in that region will be
11396 refiled. However, the region must fulfill the requirement that
11397 the first heading sets the top-level of the moved text.
11399 With a `\\[universal-argument]' ARG, the command will only visit the target \
11400 location
11401 and not actually move anything.
11403 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11404 location where the last
11405 refiling operation has put the subtree.
11407 With a numeric prefix argument of `2', refile to the running clock.
11409 With a numeric prefix argument of `3', emulate `org-refile-keep'
11410 being set to t and copy to the target location, don't move it.
11411 Beware that keeping refiled entries may result in duplicated ID
11412 properties.
11414 RFLOC can be a refile location obtained in a different way.
11416 MSG is a string to replace \"Refile\" in the default prompt with
11417 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11419 See also `org-refile-use-outline-path'.
11421 If you are using target caching (see `org-refile-use-cache'), you
11422 have to clear the target cache in order to find new targets.
11423 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11424 prefix argument (`C-u C-u C-u C-c C-w')."
11425 (interactive "P")
11426 (if (member arg '(0 (64)))
11427 (org-refile-cache-clear)
11428 (let* ((actionmsg (cond (msg msg)
11429 ((equal arg 3) "Refile (and keep)")
11430 (t "Refile")))
11431 (regionp (org-region-active-p))
11432 (region-start (and regionp (region-beginning)))
11433 (region-end (and regionp (region-end)))
11434 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11435 pos it nbuf file level reversed)
11436 (setq last-command nil)
11437 (when regionp
11438 (goto-char region-start)
11439 (or (bolp) (goto-char (point-at-bol)))
11440 (setq region-start (point))
11441 (unless (or (org-kill-is-subtree-p
11442 (buffer-substring region-start region-end))
11443 (prog1 org-refile-active-region-within-subtree
11444 (let ((s (point-at-eol)))
11445 (org-toggle-heading)
11446 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11447 (user-error "The region is not a (sequence of) subtree(s)")))
11448 (if (equal arg '(16))
11449 (org-refile-goto-last-stored)
11450 (when (or
11451 (and (equal arg 2)
11452 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11453 (prog1
11454 (setq it (list (or org-clock-heading "running clock")
11455 (buffer-file-name
11456 (marker-buffer org-clock-hd-marker))
11458 (marker-position org-clock-hd-marker)))
11459 (setq arg nil)))
11460 (setq it
11461 (or rfloc
11462 (let (heading-text)
11463 (save-excursion
11464 (unless (and arg (listp arg))
11465 (org-back-to-heading t)
11466 (setq heading-text
11467 (replace-regexp-in-string
11468 org-bracket-link-regexp
11469 "\\3"
11470 (or (nth 4 (org-heading-components))
11471 ""))))
11472 (org-refile-get-location
11473 (cond ((and arg (listp arg)) "Goto")
11474 (regionp (concat actionmsg " region to"))
11475 (t (concat actionmsg " subtree \""
11476 heading-text "\" to")))
11477 default-buffer
11478 (and (not (equal '(4) arg))
11479 org-refile-allow-creating-parent-nodes)))))))
11480 (setq file (nth 1 it)
11481 pos (nth 3 it))
11482 (when (and (not arg)
11484 (equal (buffer-file-name) file)
11485 (if regionp
11486 (and (>= pos region-start)
11487 (<= pos region-end))
11488 (and (>= pos (point))
11489 (< pos (save-excursion
11490 (org-end-of-subtree t t))))))
11491 (error "Cannot refile to position inside the tree or region"))
11492 (setq nbuf (or (find-buffer-visiting file)
11493 (find-file-noselect file)))
11494 (if (and arg (not (equal arg 3)))
11495 (progn
11496 (pop-to-buffer-same-window nbuf)
11497 (goto-char (cond (pos)
11498 ((org-notes-order-reversed-p) (point-min))
11499 (t (point-max))))
11500 (org-show-context 'org-goto))
11501 (if regionp
11502 (progn
11503 (org-kill-new (buffer-substring region-start region-end))
11504 (org-save-markers-in-region region-start region-end))
11505 (org-copy-subtree 1 nil t))
11506 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11507 (find-file-noselect file)))
11508 (setq reversed (org-notes-order-reversed-p))
11509 (org-with-wide-buffer
11510 (if pos
11511 (progn
11512 (goto-char pos)
11513 (setq level (org-get-valid-level (funcall outline-level) 1))
11514 (goto-char
11515 (if reversed
11516 (or (outline-next-heading) (point-max))
11517 (or (save-excursion (org-get-next-sibling))
11518 (org-end-of-subtree t t)
11519 (point-max)))))
11520 (setq level 1)
11521 (if (not reversed)
11522 (goto-char (point-max))
11523 (goto-char (point-min))
11524 (or (outline-next-heading) (goto-char (point-max)))))
11525 (unless (bolp) (newline))
11526 (org-paste-subtree level nil nil t)
11527 (when org-log-refile
11528 (org-add-log-setup 'refile nil nil org-log-refile)
11529 (unless (eq org-log-refile 'note)
11530 (save-excursion (org-add-log-note))))
11531 (and org-auto-align-tags
11532 (let ((org-loop-over-headlines-in-active-region nil))
11533 (org-set-tags nil t)))
11534 (let ((bookmark-name (plist-get org-bookmark-names-plist
11535 :last-refile)))
11536 (when bookmark-name
11537 (with-demoted-errors
11538 (bookmark-set bookmark-name))))
11539 ;; If we are refiling for capture, make sure that the
11540 ;; last-capture pointers point here
11541 (when (bound-and-true-p org-capture-is-refiling)
11542 (let ((bookmark-name (plist-get org-bookmark-names-plist
11543 :last-capture-marker)))
11544 (when bookmark-name
11545 (with-demoted-errors
11546 (bookmark-set bookmark-name))))
11547 (move-marker org-capture-last-stored-marker (point)))
11548 (when (fboundp 'deactivate-mark) (deactivate-mark))
11549 (run-hooks 'org-after-refile-insert-hook)))
11550 (unless org-refile-keep
11551 (if regionp
11552 (delete-region (point) (+ (point) (- region-end region-start)))
11553 (delete-region
11554 (and (org-back-to-heading t) (point))
11555 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11556 (when (featurep 'org-inlinetask)
11557 (org-inlinetask-remove-END-maybe))
11558 (setq org-markers-to-move nil)
11559 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11561 (defun org-refile-goto-last-stored ()
11562 "Go to the location where the last refile was stored."
11563 (interactive)
11564 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11565 (message "This is the location of the last refile"))
11567 (defun org-refile--get-location (refloc tbl)
11568 "When user refile to REFLOC, find the associated target in TBL.
11569 Also check `org-refile-target-table'."
11570 (car (delq
11572 (mapcar
11573 (lambda (r) (or (assoc r tbl)
11574 (assoc r org-refile-target-table)))
11575 (list (replace-regexp-in-string "/$" "" refloc)
11576 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11578 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11579 "Prompt the user for a refile location, using PROMPT.
11580 PROMPT should not be suffixed with a colon and a space, because
11581 this function appends the default value from
11582 `org-refile-history' automatically, if that is not empty."
11583 (let ((org-refile-targets org-refile-targets)
11584 (org-refile-use-outline-path org-refile-use-outline-path))
11585 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11586 (unless org-refile-target-table
11587 (user-error "No refile targets"))
11588 (let* ((cbuf (current-buffer))
11589 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11590 (cfunc (if (and org-refile-use-outline-path
11591 org-outline-path-complete-in-steps)
11592 #'org-olpath-completing-read
11593 #'completing-read))
11594 (extra (if org-refile-use-outline-path "/" ""))
11595 (cbnex (concat (buffer-name) extra))
11596 (filename (and cfn (expand-file-name cfn)))
11597 (tbl (mapcar
11598 (lambda (x)
11599 (if (and (not (member org-refile-use-outline-path
11600 '(file full-file-path)))
11601 (not (equal filename (nth 1 x))))
11602 (cons (concat (car x) extra " ("
11603 (file-name-nondirectory (nth 1 x)) ")")
11604 (cdr x))
11605 (cons (concat (car x) extra) (cdr x))))
11606 org-refile-target-table))
11607 (completion-ignore-case t)
11608 cdef
11609 (prompt (concat prompt
11610 (or (and (car org-refile-history)
11611 (concat " (default " (car org-refile-history) ")"))
11612 (and (assoc cbnex tbl) (setq cdef cbnex)
11613 (concat " (default " cbnex ")"))) ": "))
11614 pa answ parent-target child parent old-hist)
11615 (setq old-hist org-refile-history)
11616 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11617 nil 'org-refile-history (or cdef (car org-refile-history))))
11618 (if (setq pa (org-refile--get-location answ tbl))
11619 (progn
11620 (org-refile-check-position pa)
11621 (when (or (not org-refile-history)
11622 (not (eq old-hist org-refile-history))
11623 (not (equal (car pa) (car org-refile-history))))
11624 (setq org-refile-history
11625 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11626 org-refile-history
11627 (cdr org-refile-history))))
11628 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11629 (pop org-refile-history)))
11631 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11632 (progn
11633 (setq parent (match-string 1 answ)
11634 child (match-string 2 answ))
11635 (setq parent-target (org-refile--get-location parent tbl))
11636 (when (and parent-target
11637 (or (eq new-nodes t)
11638 (and (eq new-nodes 'confirm)
11639 (y-or-n-p (format "Create new node \"%s\"? "
11640 child)))))
11641 (org-refile-new-child parent-target child)))
11642 (user-error "Invalid target location")))))
11644 (declare-function org-string-nw-p "org-macs" (s))
11645 (defun org-refile-check-position (refile-pointer)
11646 "Check if the refile pointer matches the headline to which it points."
11647 (let* ((file (nth 1 refile-pointer))
11648 (re (nth 2 refile-pointer))
11649 (pos (nth 3 refile-pointer))
11650 buffer)
11651 (if (and (not (markerp pos)) (not file))
11652 (user-error "Please indicate a target file in the refile path")
11653 (when (org-string-nw-p re)
11654 (setq buffer (if (markerp pos)
11655 (marker-buffer pos)
11656 (or (find-buffer-visiting file)
11657 (find-file-noselect file))))
11658 (with-current-buffer buffer
11659 (org-with-wide-buffer
11660 (goto-char pos)
11661 (beginning-of-line 1)
11662 (unless (looking-at-p re)
11663 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11665 (defun org-refile-new-child (parent-target child)
11666 "Use refile target PARENT-TARGET to add new CHILD below it."
11667 (unless parent-target
11668 (error "Cannot find parent for new node"))
11669 (let ((file (nth 1 parent-target))
11670 (pos (nth 3 parent-target))
11671 level)
11672 (with-current-buffer (or (find-buffer-visiting file)
11673 (find-file-noselect file))
11674 (org-with-wide-buffer
11675 (if pos
11676 (goto-char pos)
11677 (goto-char (point-max))
11678 (unless (bolp) (newline)))
11679 (when (looking-at org-outline-regexp)
11680 (setq level (funcall outline-level))
11681 (org-end-of-subtree t t))
11682 (org-back-over-empty-lines)
11683 (insert "\n" (make-string
11684 (if pos (org-get-valid-level level 1) 1) ?*)
11685 " " child "\n")
11686 (beginning-of-line 0)
11687 (list (concat (car parent-target) "/" child) file "" (point))))))
11689 (defun org-olpath-completing-read (prompt collection &rest args)
11690 "Read an outline path like a file name."
11691 (let ((thetable collection))
11692 (apply #'completing-read
11693 prompt
11694 (lambda (string predicate &optional flag)
11695 (cond
11696 ((eq flag nil) (try-completion string thetable))
11697 ((eq flag t)
11698 (let ((l (length string)))
11699 (mapcar (lambda (x)
11700 (let ((r (substring x l))
11701 (f (if (string-match " ([^)]*)$" x)
11702 (match-string 0 x)
11703 "")))
11704 (if (string-match "/" r)
11705 (concat string (substring r 0 (match-end 0)) f)
11706 x)))
11707 (all-completions string thetable predicate))))
11708 ;; Exact match?
11709 ((eq flag 'lambda) (assoc string thetable))))
11710 args)))
11712 ;;;; Dynamic blocks
11714 (defun org-find-dblock (name)
11715 "Find the first dynamic block with name NAME in the buffer.
11716 If not found, stay at current position and return nil."
11717 (let ((case-fold-search t) pos)
11718 (save-excursion
11719 (goto-char (point-min))
11720 (setq pos (and (re-search-forward
11721 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11722 (match-beginning 0))))
11723 (when pos (goto-char pos))
11724 pos))
11726 (defun org-create-dblock (plist)
11727 "Create a dynamic block section, with parameters taken from PLIST.
11728 PLIST must contain a :name entry which is used as the name of the block."
11729 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11730 (end-of-line 1)
11731 (newline))
11732 (let ((col (current-column))
11733 (name (plist-get plist :name)))
11734 (insert "#+BEGIN: " name)
11735 (while plist
11736 (if (eq (car plist) :name)
11737 (setq plist (cddr plist))
11738 (insert " " (prin1-to-string (pop plist)))))
11739 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11740 (beginning-of-line -2)))
11742 (defun org-prepare-dblock ()
11743 "Prepare dynamic block for refresh.
11744 This empties the block, puts the cursor at the insert position and returns
11745 the property list including an extra property :name with the block name."
11746 (unless (looking-at org-dblock-start-re)
11747 (user-error "Not at a dynamic block"))
11748 (let* ((begdel (1+ (match-end 0)))
11749 (name (org-no-properties (match-string 1)))
11750 (params (append (list :name name)
11751 (read (concat "(" (match-string 3) ")")))))
11752 (save-excursion
11753 (beginning-of-line 1)
11754 (skip-chars-forward " \t")
11755 (setq params (plist-put params :indentation-column (current-column))))
11756 (unless (re-search-forward org-dblock-end-re nil t)
11757 (error "Dynamic block not terminated"))
11758 (setq params
11759 (append params
11760 (list :content (buffer-substring
11761 begdel (match-beginning 0)))))
11762 (delete-region begdel (match-beginning 0))
11763 (goto-char begdel)
11764 (open-line 1)
11765 params))
11767 (defun org-map-dblocks (&optional command)
11768 "Apply COMMAND to all dynamic blocks in the current buffer.
11769 If COMMAND is not given, use `org-update-dblock'."
11770 (let ((cmd (or command 'org-update-dblock)))
11771 (save-excursion
11772 (goto-char (point-min))
11773 (while (re-search-forward org-dblock-start-re nil t)
11774 (goto-char (match-beginning 0))
11775 (save-excursion
11776 (condition-case nil
11777 (funcall cmd)
11778 (error (message "Error during update of dynamic block"))))
11779 (unless (re-search-forward org-dblock-end-re nil t)
11780 (error "Dynamic block not terminated"))))))
11782 (defun org-dblock-update (&optional arg)
11783 "User command for updating dynamic blocks.
11784 Update the dynamic block at point. With prefix ARG, update all dynamic
11785 blocks in the buffer."
11786 (interactive "P")
11787 (if arg
11788 (org-update-all-dblocks)
11789 (or (looking-at org-dblock-start-re)
11790 (org-beginning-of-dblock))
11791 (org-update-dblock)))
11793 (defun org-update-dblock ()
11794 "Update the dynamic block at point.
11795 This means to empty the block, parse for parameters and then call
11796 the correct writing function."
11797 (interactive)
11798 (save-excursion
11799 (let* ((win (selected-window))
11800 (pos (point))
11801 (line (org-current-line))
11802 (params (org-prepare-dblock))
11803 (name (plist-get params :name))
11804 (indent (plist-get params :indentation-column))
11805 (cmd (intern (concat "org-dblock-write:" name))))
11806 (message "Updating dynamic block `%s' at line %d..." name line)
11807 (funcall cmd params)
11808 (message "Updating dynamic block `%s' at line %d...done" name line)
11809 (goto-char pos)
11810 (when (and indent (> indent 0))
11811 (setq indent (make-string indent ?\ ))
11812 (save-excursion
11813 (select-window win)
11814 (org-beginning-of-dblock)
11815 (forward-line 1)
11816 (while (not (looking-at org-dblock-end-re))
11817 (insert indent)
11818 (beginning-of-line 2))
11819 (when (looking-at org-dblock-end-re)
11820 (and (looking-at "[ \t]+")
11821 (replace-match ""))
11822 (insert indent)))))))
11824 (defun org-beginning-of-dblock ()
11825 "Find the beginning of the dynamic block at point.
11826 Error if there is no such block at point."
11827 (let ((pos (point))
11828 beg)
11829 (end-of-line 1)
11830 (if (and (re-search-backward org-dblock-start-re nil t)
11831 (setq beg (match-beginning 0))
11832 (re-search-forward org-dblock-end-re nil t)
11833 (> (match-end 0) pos))
11834 (goto-char beg)
11835 (goto-char pos)
11836 (error "Not in a dynamic block"))))
11838 (defun org-update-all-dblocks ()
11839 "Update all dynamic blocks in the buffer.
11840 This function can be used in a hook."
11841 (interactive)
11842 (when (derived-mode-p 'org-mode)
11843 (org-map-dblocks 'org-update-dblock)))
11846 ;;;; Completion
11848 (declare-function org-export-backend-options "ox" (cl-x) t)
11849 (defun org-get-export-keywords ()
11850 "Return a list of all currently understood export keywords.
11851 Export keywords include options, block names, attributes and
11852 keywords relative to each registered export back-end."
11853 (let (keywords)
11854 (dolist (backend
11855 (bound-and-true-p org-export-registered-backends)
11856 (delq nil keywords))
11857 ;; Back-end name (for keywords, like #+LATEX:)
11858 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11859 (dolist (option-entry (org-export-backend-options backend))
11860 ;; Back-end options.
11861 (push (nth 1 option-entry) keywords)))))
11863 (defconst org-options-keywords
11864 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11865 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11866 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11867 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11868 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11870 (defcustom org-structure-template-alist
11871 '((?a . "export ascii")
11872 (?c . "center")
11873 (?C . "comment")
11874 (?e . "example")
11875 (?E . "export")
11876 (?h . "export html")
11877 (?l . "export latex")
11878 (?q . "quote")
11879 (?s . "src")
11880 (?v . "verse"))
11881 "Structure completion elements.
11882 This is an alist of characters and values. When
11883 `org-insert-structure-template' is called, an additional key is
11884 read. The key is first looked up in this alist, and the
11885 corresponding structure is inserted, with \"#+BEGIN_\" and
11886 \"#+END_\" added automatically."
11887 :group 'org-completion
11888 :type '(repeat
11889 (cons (character :tag "Key")
11890 (string :tag "Template")))
11891 :package-version '(Org . "9.2"))
11893 (defun org-insert-structure-template (type)
11894 "Insert a block structure of the type #+begin_foo/#+end_foo.
11895 First read a character, which can be one of the keys in
11896 `org-structure-template-alist'. When it is <TAB>, prompt the
11897 user for a string to use. With an active region, wrap the region
11898 in the block. Otherwise, insert an empty block."
11899 (interactive
11900 (list
11901 (let* ((key (read-key "Key: "))
11902 (struct-string
11903 (or (cdr (assq key org-structure-template-alist))
11904 (and (= key ?\t)
11905 (read-string "Structure type: "))
11906 (user-error "`%c' has no structure definition" key))))
11907 struct-string)))
11908 (let* ((region? (use-region-p))
11909 (s (if region? (region-beginning) (point)))
11910 (e (copy-marker (if region? (region-end) (point)) t))
11911 column)
11912 (when (string-match-p
11913 (concat "\\`" (regexp-opt '("example" "export" "src")))
11914 type)
11915 (org-escape-code-in-region s e))
11916 (goto-char s)
11917 (setq column (current-indentation))
11918 (beginning-of-line)
11919 (indent-to column)
11920 (insert (format "#+begin_%s\n" type))
11921 (goto-char e)
11922 (if (bolp)
11923 (progn
11924 (skip-chars-backward " \n\t")
11925 (forward-line))
11926 (end-of-line)
11927 (insert "\n"))
11928 (indent-to column)
11929 (insert (format "#+end_%s\n"
11930 (car (split-string type))))
11931 (when (or (not region?)
11932 (string-match-p "src\\|\\`export\\'" type))
11933 (goto-char s)
11934 (end-of-line))
11935 (set-marker e nil)))
11937 ;;;; TODO, DEADLINE, Comments
11939 (defun org-toggle-comment ()
11940 "Change the COMMENT state of an entry."
11941 (interactive)
11942 (save-excursion
11943 (org-back-to-heading)
11944 (let ((case-fold-search nil))
11945 (looking-at org-complex-heading-regexp))
11946 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11947 (skip-chars-forward " \t")
11948 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11949 (if (org-in-commented-heading-p t)
11950 (delete-region (point)
11951 (progn (search-forward " " (line-end-position) 'move)
11952 (skip-chars-forward " \t")
11953 (point)))
11954 (insert org-comment-string)
11955 (unless (eolp) (insert " ")))))
11957 (defvar org-last-todo-state-is-todo nil
11958 "This is non-nil when the last TODO state change led to a TODO state.
11959 If the last change removed the TODO tag or switched to DONE, then
11960 this is nil.")
11962 (defvar org-setting-tags nil) ; dynamically skipped
11964 (defvar org-todo-setup-filter-hook nil
11965 "Hook for functions that pre-filter todo specs.
11966 Each function takes a todo spec and returns either nil or the spec
11967 transformed into canonical form." )
11969 (defvar org-todo-get-default-hook nil
11970 "Hook for functions that get a default item for todo.
11971 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11972 nil or a string to be used for the todo mark." )
11974 (defvar org-agenda-headline-snapshot-before-repeat)
11976 (defun org-current-effective-time ()
11977 "Return current time adjusted for `org-extend-today-until' variable."
11978 (let* ((ct (org-current-time))
11979 (dct (decode-time ct))
11980 (ct1
11981 (cond
11982 (org-use-last-clock-out-time-as-effective-time
11983 (or (org-clock-get-last-clock-out-time) ct))
11984 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11985 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11986 (t ct))))
11987 ct1))
11989 (defun org-todo-yesterday (&optional arg)
11990 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11991 (interactive "P")
11992 (if (eq major-mode 'org-agenda-mode)
11993 (apply 'org-agenda-todo-yesterday arg)
11994 (let* ((org-use-effective-time t)
11995 (hour (nth 2 (decode-time (org-current-time))))
11996 (org-extend-today-until (1+ hour)))
11997 (org-todo arg))))
11999 (defvar org-block-entry-blocking ""
12000 "First entry preventing the TODO state change.")
12002 (defun org-cancel-repeater ()
12003 "Cancel a repeater by setting its numeric value to zero."
12004 (interactive)
12005 (save-excursion
12006 (org-back-to-heading t)
12007 (let ((bound1 (point))
12008 (bound0 (save-excursion (outline-next-heading) (point))))
12009 (when (and (re-search-forward
12010 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12011 org-deadline-time-regexp "\\)\\|\\("
12012 org-ts-regexp "\\)")
12013 bound0 t)
12014 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12015 bound1 t))
12016 (replace-match "0" t nil nil 1)))))
12018 (defvar org-state)
12019 (defvar org-blocked-by-checkboxes)
12020 (defun org-todo (&optional arg)
12021 "Change the TODO state of an item.
12023 The state of an item is given by a keyword at the start of the heading,
12024 like
12025 *** TODO Write paper
12026 *** DONE Call mom
12028 The different keywords are specified in the variable `org-todo-keywords'.
12029 By default the available states are \"TODO\" and \"DONE\". So, for this
12030 example: when the item starts with TODO, it is changed to DONE.
12031 When it starts with DONE, the DONE is removed. And when neither TODO nor
12032 DONE are present, add TODO at the beginning of the heading.
12034 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12035 state.
12036 With numeric prefix ARG, switch to that state.
12037 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12038 next set of TODO \
12039 keywords (nextset).
12040 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12041 prefix, circumvent any state blocking.
12042 With a numeric prefix arg of 0, inhibit note taking for the change.
12043 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12045 When called through ELisp, arg is also interpreted in the following way:
12046 `none' -> empty state
12047 \"\" -> switch to empty state
12048 `done' -> switch to DONE
12049 `nextset' -> switch to the next set of keywords
12050 `previousset' -> switch to the previous set of keywords
12051 \"WAITING\" -> switch to the specified keyword, but only if it
12052 really is a member of `org-todo-keywords'."
12053 (interactive "P")
12054 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12055 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12056 'region-start-level 'region))
12057 org-loop-over-headlines-in-active-region)
12058 (org-map-entries
12059 `(org-todo ,arg)
12060 org-loop-over-headlines-in-active-region
12061 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12062 (when (equal arg '(16)) (setq arg 'nextset))
12063 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12064 (let ((org-blocker-hook org-blocker-hook)
12065 commentp
12066 case-fold-search)
12067 (when (equal arg '(64))
12068 (setq arg nil org-blocker-hook nil))
12069 (when (and org-blocker-hook
12070 (or org-inhibit-blocking
12071 (org-entry-get nil "NOBLOCKING")))
12072 (setq org-blocker-hook nil))
12073 (save-excursion
12074 (catch 'exit
12075 (org-back-to-heading t)
12076 (when (org-in-commented-heading-p t)
12077 (org-toggle-comment)
12078 (setq commentp t))
12079 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12080 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12081 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12082 (let* ((match-data (match-data))
12083 (startpos (point-at-bol))
12084 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12085 (org-log-done org-log-done)
12086 (org-log-repeat org-log-repeat)
12087 (org-todo-log-states org-todo-log-states)
12088 (org-inhibit-logging
12089 (if (equal arg 0)
12090 (progn (setq arg nil) 'note) org-inhibit-logging))
12091 (this (match-string 1))
12092 (hl-pos (match-beginning 0))
12093 (head (org-get-todo-sequence-head this))
12094 (ass (assoc head org-todo-kwd-alist))
12095 (interpret (nth 1 ass))
12096 (done-word (nth 3 ass))
12097 (final-done-word (nth 4 ass))
12098 (org-last-state (or this ""))
12099 (completion-ignore-case t)
12100 (member (member this org-todo-keywords-1))
12101 (tail (cdr member))
12102 (org-state (cond
12103 ((and org-todo-key-trigger
12104 (or (and (equal arg '(4))
12105 (eq org-use-fast-todo-selection 'prefix))
12106 (and (not arg) org-use-fast-todo-selection
12107 (not (eq org-use-fast-todo-selection
12108 'prefix)))))
12109 ;; Use fast selection.
12110 (org-fast-todo-selection))
12111 ((and (equal arg '(4))
12112 (or (not org-use-fast-todo-selection)
12113 (not org-todo-key-trigger)))
12114 ;; Read a state with completion.
12115 (completing-read
12116 "State: " (mapcar #'list org-todo-keywords-1)
12117 nil t))
12118 ((eq arg 'right)
12119 (if this
12120 (if tail (car tail) nil)
12121 (car org-todo-keywords-1)))
12122 ((eq arg 'left)
12123 (unless (equal member org-todo-keywords-1)
12124 (if this
12125 (nth (- (length org-todo-keywords-1)
12126 (length tail) 2)
12127 org-todo-keywords-1)
12128 (org-last org-todo-keywords-1))))
12129 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12130 (setq arg nil))) ;hack to fall back to cycling
12131 (arg
12132 ;; User or caller requests a specific state.
12133 (cond
12134 ((equal arg "") nil)
12135 ((eq arg 'none) nil)
12136 ((eq arg 'done) (or done-word (car org-done-keywords)))
12137 ((eq arg 'nextset)
12138 (or (car (cdr (member head org-todo-heads)))
12139 (car org-todo-heads)))
12140 ((eq arg 'previousset)
12141 (let ((org-todo-heads (reverse org-todo-heads)))
12142 (or (car (cdr (member head org-todo-heads)))
12143 (car org-todo-heads))))
12144 ((car (member arg org-todo-keywords-1)))
12145 ((stringp arg)
12146 (user-error "State `%s' not valid in this file" arg))
12147 ((nth (1- (prefix-numeric-value arg))
12148 org-todo-keywords-1))))
12149 ((null member) (or head (car org-todo-keywords-1)))
12150 ((equal this final-done-word) nil) ;-> make empty
12151 ((null tail) nil) ;-> first entry
12152 ((memq interpret '(type priority))
12153 (if (eq this-command last-command)
12154 (car tail)
12155 (if (> (length tail) 0)
12156 (or done-word (car org-done-keywords))
12157 nil)))
12159 (car tail))))
12160 (org-state (or
12161 (run-hook-with-args-until-success
12162 'org-todo-get-default-hook org-state org-last-state)
12163 org-state))
12164 (next (if org-state (concat " " org-state " ") " "))
12165 (change-plist (list :type 'todo-state-change :from this :to org-state
12166 :position startpos))
12167 dolog now-done-p)
12168 (when org-blocker-hook
12169 (let (org-blocked-by-checkboxes block-reason)
12170 (setq org-last-todo-state-is-todo
12171 (not (member this org-done-keywords)))
12172 (unless (save-excursion
12173 (save-match-data
12174 (org-with-wide-buffer
12175 (run-hook-with-args-until-failure
12176 'org-blocker-hook change-plist))))
12177 (setq block-reason (if org-blocked-by-checkboxes
12178 "contained checkboxes"
12179 (format "\"%s\"" org-block-entry-blocking)))
12180 (if (called-interactively-p 'interactive)
12181 (user-error "TODO state change from %s to %s blocked (by %s)"
12182 this org-state block-reason)
12183 ;; Fail silently.
12184 (message "TODO state change from %s to %s blocked (by %s)"
12185 this org-state block-reason)
12186 (throw 'exit nil)))))
12187 (store-match-data match-data)
12188 (replace-match next t t)
12189 (cond ((equal this org-state)
12190 (message "TODO state was already %s" (org-trim next)))
12191 ((not (pos-visible-in-window-p hl-pos))
12192 (message "TODO state changed to %s" (org-trim next))))
12193 (unless head
12194 (setq head (org-get-todo-sequence-head org-state)
12195 ass (assoc head org-todo-kwd-alist)
12196 interpret (nth 1 ass)
12197 done-word (nth 3 ass)
12198 final-done-word (nth 4 ass)))
12199 (when (memq arg '(nextset previousset))
12200 (message "Keyword-Set %d/%d: %s"
12201 (- (length org-todo-sets) -1
12202 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12203 (length org-todo-sets)
12204 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12205 (setq org-last-todo-state-is-todo
12206 (not (member org-state org-done-keywords)))
12207 (setq now-done-p (and (member org-state org-done-keywords)
12208 (not (member this org-done-keywords))))
12209 (and logging (org-local-logging logging))
12210 (when (and (or org-todo-log-states org-log-done)
12211 (not (eq org-inhibit-logging t))
12212 (not (memq arg '(nextset previousset))))
12213 ;; We need to look at recording a time and note.
12214 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12215 (nth 2 (assoc this org-todo-log-states))))
12216 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12217 (setq dolog 'time))
12218 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12219 (and org-state
12220 (member org-state org-not-done-keywords)
12221 (not (member this org-not-done-keywords))))
12222 ;; This is now a todo state and was not one before
12223 ;; If there was a CLOSED time stamp, get rid of it.
12224 (org-add-planning-info nil nil 'closed))
12225 (when (and now-done-p org-log-done)
12226 ;; It is now done, and it was not done before.
12227 (org-add-planning-info 'closed (org-current-effective-time))
12228 (when (and (not dolog) (eq 'note org-log-done))
12229 (org-add-log-setup 'done org-state this 'note)))
12230 (when (and org-state dolog)
12231 ;; This is a non-nil state, and we need to log it.
12232 (org-add-log-setup 'state org-state this dolog)))
12233 ;; Fixup tag positioning.
12234 (org-todo-trigger-tag-changes org-state)
12235 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12236 (when org-provide-todo-statistics
12237 (org-update-parent-todo-statistics))
12238 (run-hooks 'org-after-todo-state-change-hook)
12239 (when (and arg (not (member org-state org-done-keywords)))
12240 (setq head (org-get-todo-sequence-head org-state)))
12241 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12242 ;; Do we need to trigger a repeat?
12243 (when now-done-p
12244 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12245 ;; This is for the agenda, take a snapshot of the headline.
12246 (save-match-data
12247 (setq org-agenda-headline-snapshot-before-repeat
12248 (org-get-heading))))
12249 (org-auto-repeat-maybe org-state))
12250 ;; Fixup cursor location if close to the keyword.
12251 (when (and (outline-on-heading-p)
12252 (not (bolp))
12253 (save-excursion (beginning-of-line 1)
12254 (looking-at org-todo-line-regexp))
12255 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12256 (goto-char (or (match-end 2) (match-end 1)))
12257 (and (looking-at " ") (just-one-space)))
12258 (when org-trigger-hook
12259 (save-excursion
12260 (run-hook-with-args 'org-trigger-hook change-plist)))
12261 (when commentp (org-toggle-comment))))))))
12263 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12264 "Block turning an entry into a TODO, using the hierarchy.
12265 This checks whether the current task should be blocked from state
12266 changes. Such blocking occurs when:
12268 1. The task has children which are not all in a completed state.
12270 2. A task has a parent with the property :ORDERED:, and there
12271 are siblings prior to the current task with incomplete
12272 status.
12274 3. The parent of the task is blocked because it has siblings that should
12275 be done first, or is child of a block grandparent TODO entry."
12277 (if (not org-enforce-todo-dependencies)
12278 t ; if locally turned off don't block
12279 (catch 'dont-block
12280 ;; If this is not a todo state change, or if this entry is already DONE,
12281 ;; do not block
12282 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12283 (member (plist-get change-plist :from)
12284 (cons 'done org-done-keywords))
12285 (member (plist-get change-plist :to)
12286 (cons 'todo org-not-done-keywords))
12287 (not (plist-get change-plist :to)))
12288 (throw 'dont-block t))
12289 ;; If this task has children, and any are undone, it's blocked
12290 (save-excursion
12291 (org-back-to-heading t)
12292 (let ((this-level (funcall outline-level)))
12293 (outline-next-heading)
12294 (let ((child-level (funcall outline-level)))
12295 (while (and (not (eobp))
12296 (> child-level this-level))
12297 ;; this todo has children, check whether they are all
12298 ;; completed
12299 (when (and (not (org-entry-is-done-p))
12300 (org-entry-is-todo-p))
12301 (setq org-block-entry-blocking (org-get-heading))
12302 (throw 'dont-block nil))
12303 (outline-next-heading)
12304 (setq child-level (funcall outline-level))))))
12305 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12306 ;; any previous siblings are undone, it's blocked
12307 (save-excursion
12308 (org-back-to-heading t)
12309 (let* ((pos (point))
12310 (parent-pos (and (org-up-heading-safe) (point)))
12311 (case-fold-search nil))
12312 (unless parent-pos (throw 'dont-block t)) ; no parent
12313 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12314 (forward-line 1)
12315 (re-search-forward org-not-done-heading-regexp pos t))
12316 (setq org-block-entry-blocking (match-string 0))
12317 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12318 ;; Search further up the hierarchy, to see if an ancestor is blocked
12319 (while t
12320 (goto-char parent-pos)
12321 (unless (looking-at org-not-done-heading-regexp)
12322 (throw 'dont-block t)) ; do not block, parent is not a TODO
12323 (setq pos (point))
12324 (setq parent-pos (and (org-up-heading-safe) (point)))
12325 (unless parent-pos (throw 'dont-block t)) ; no parent
12326 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12327 (forward-line 1)
12328 (re-search-forward org-not-done-heading-regexp pos t)
12329 (setq org-block-entry-blocking (org-get-heading)))
12330 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12332 (defcustom org-track-ordered-property-with-tag nil
12333 "Should the ORDERED property also be shown as a tag?
12334 The ORDERED property decides if an entry should require subtasks to be
12335 completed in sequence. Since a property is not very visible, setting
12336 this option means that toggling the ORDERED property with the command
12337 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12338 not relevant for the behavior, but it makes things more visible.
12340 Note that toggling the tag with tags commands will not change the property
12341 and therefore not influence behavior!
12343 This can be t, meaning the tag ORDERED should be used, It can also be a
12344 string to select a different tag for this task."
12345 :group 'org-todo
12346 :type '(choice
12347 (const :tag "No tracking" nil)
12348 (const :tag "Track with ORDERED tag" t)
12349 (string :tag "Use other tag")))
12351 (defun org-toggle-ordered-property ()
12352 "Toggle the ORDERED property of the current entry.
12353 For better visibility, you can track the value of this property with a tag.
12354 See variable `org-track-ordered-property-with-tag'."
12355 (interactive)
12356 (let* ((t1 org-track-ordered-property-with-tag)
12357 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12358 (save-excursion
12359 (org-back-to-heading)
12360 (if (org-entry-get nil "ORDERED")
12361 (progn
12362 (org-delete-property "ORDERED")
12363 (and tag (org-toggle-tag tag 'off))
12364 (message "Subtasks can be completed in arbitrary order"))
12365 (org-entry-put nil "ORDERED" "t")
12366 (and tag (org-toggle-tag tag 'on))
12367 (message "Subtasks must be completed in sequence")))))
12369 (defun org-block-todo-from-checkboxes (change-plist)
12370 "Block turning an entry into a TODO, using checkboxes.
12371 This checks whether the current task should be blocked from state
12372 changes because there are unchecked boxes in this entry."
12373 (if (not org-enforce-todo-checkbox-dependencies)
12374 t ; if locally turned off don't block
12375 (catch 'dont-block
12376 ;; If this is not a todo state change, or if this entry is already DONE,
12377 ;; do not block
12378 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12379 (member (plist-get change-plist :from)
12380 (cons 'done org-done-keywords))
12381 (member (plist-get change-plist :to)
12382 (cons 'todo org-not-done-keywords))
12383 (not (plist-get change-plist :to)))
12384 (throw 'dont-block t))
12385 ;; If this task has checkboxes that are not checked, it's blocked
12386 (save-excursion
12387 (org-back-to-heading t)
12388 (let ((beg (point)) end)
12389 (outline-next-heading)
12390 (setq end (point))
12391 (goto-char beg)
12392 (when (org-list-search-forward
12393 (concat (org-item-beginning-re)
12394 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12395 "\\[[- ]\\]")
12396 end t)
12397 (when (boundp 'org-blocked-by-checkboxes)
12398 (setq org-blocked-by-checkboxes t))
12399 (throw 'dont-block nil))))
12400 t))) ; do not block
12402 (defun org-entry-blocked-p ()
12403 "Non-nil if entry at point is blocked."
12404 (and (not (org-entry-get nil "NOBLOCKING"))
12405 (member (org-entry-get nil "TODO") org-not-done-keywords)
12406 (not (run-hook-with-args-until-failure
12407 'org-blocker-hook
12408 (list :type 'todo-state-change
12409 :position (point)
12410 :from 'todo
12411 :to 'done)))))
12413 (defun org-update-statistics-cookies (all)
12414 "Update the statistics cookie, either from TODO or from checkboxes.
12415 This should be called with the cursor in a line with a statistics
12416 cookie. When called with a \\[universal-argument] prefix, update
12417 all statistics cookies in the buffer."
12418 (interactive "P")
12419 (if all
12420 (progn
12421 (org-update-checkbox-count 'all)
12422 (org-map-entries 'org-update-parent-todo-statistics))
12423 (if (not (org-at-heading-p))
12424 (org-update-checkbox-count)
12425 (let ((pos (point-marker))
12426 end l1 l2)
12427 (ignore-errors (org-back-to-heading t))
12428 (if (not (org-at-heading-p))
12429 (org-update-checkbox-count)
12430 (setq l1 (org-outline-level))
12431 (setq end (save-excursion
12432 (outline-next-heading)
12433 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12434 (point)))
12435 (if (and (save-excursion
12436 (re-search-forward
12437 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12438 (not (save-excursion (re-search-forward
12439 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12440 (org-update-checkbox-count)
12441 (if (and l2 (> l2 l1))
12442 (progn
12443 (goto-char end)
12444 (org-update-parent-todo-statistics))
12445 (goto-char pos)
12446 (beginning-of-line 1)
12447 (while (re-search-forward
12448 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12449 (point-at-eol) t)
12450 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12451 (goto-char pos)
12452 (move-marker pos nil)))))
12454 (defvar org-entry-property-inherited-from) ;; defined below
12455 (defun org-update-parent-todo-statistics ()
12456 "Update any statistics cookie in the parent of the current headline.
12457 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12458 the entire subtree and this will travel up the hierarchy and update
12459 statistics everywhere."
12460 (let* ((prop (save-excursion (org-up-heading-safe)
12461 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12462 (recursive (or (not org-hierarchical-todo-statistics)
12463 (and prop (string-match "\\<recursive\\>" prop))))
12464 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12466 (first t)
12467 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12468 level ltoggle l1 new ndel
12469 (cnt-all 0) (cnt-done 0) is-percent kwd
12470 checkbox-beg cookie-present)
12471 (catch 'exit
12472 (save-excursion
12473 (beginning-of-line 1)
12474 (setq ltoggle (funcall outline-level))
12475 ;; Three situations are to consider:
12477 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12478 ;; to the top-level ancestor on the headline;
12480 ;; 2. If parent has "recursive" property, repeat up to the
12481 ;; headline setting that property, taking inheritance into
12482 ;; account;
12484 ;; 3. Else, move up to direct parent and proceed only once.
12485 (while (and (setq level (org-up-heading-safe))
12486 (or recursive first)
12487 (>= (point) lim))
12488 (setq first nil cookie-present nil)
12489 (unless (and level
12490 (not (string-match
12491 "\\<checkbox\\>"
12492 (downcase (or (org-entry-get nil "COOKIE_DATA")
12493 "")))))
12494 (throw 'exit nil))
12495 (while (re-search-forward box-re (point-at-eol) t)
12496 (setq cnt-all 0 cnt-done 0 cookie-present t)
12497 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12498 (save-match-data
12499 (unless (outline-next-heading) (throw 'exit nil))
12500 (while (and (looking-at org-complex-heading-regexp)
12501 (> (setq l1 (length (match-string 1))) level))
12502 (setq kwd (and (or recursive (= l1 ltoggle))
12503 (match-string 2)))
12504 (if (or (eq org-provide-todo-statistics 'all-headlines)
12505 (and (eq org-provide-todo-statistics t)
12506 (or (member kwd org-done-keywords)))
12507 (and (listp org-provide-todo-statistics)
12508 (stringp (car org-provide-todo-statistics))
12509 (or (member kwd org-provide-todo-statistics)
12510 (member kwd org-done-keywords)))
12511 (and (listp org-provide-todo-statistics)
12512 (listp (car org-provide-todo-statistics))
12513 (or (member kwd (car org-provide-todo-statistics))
12514 (and (member kwd org-done-keywords)
12515 (member kwd (cadr org-provide-todo-statistics))))))
12516 (setq cnt-all (1+ cnt-all))
12517 (and (eq org-provide-todo-statistics t)
12519 (setq cnt-all (1+ cnt-all))))
12520 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12521 (member kwd org-done-keywords))
12522 (and (listp org-provide-todo-statistics)
12523 (listp (car org-provide-todo-statistics))
12524 (member kwd org-done-keywords)
12525 (member kwd (cadr org-provide-todo-statistics)))
12526 (and (listp org-provide-todo-statistics)
12527 (stringp (car org-provide-todo-statistics))
12528 (member kwd org-done-keywords)))
12529 (setq cnt-done (1+ cnt-done)))
12530 (outline-next-heading)))
12531 (setq new
12532 (if is-percent
12533 (format "[%d%%]" (floor (* 100.0 cnt-done)
12534 (max 1 cnt-all)))
12535 (format "[%d/%d]" cnt-done cnt-all))
12536 ndel (- (match-end 0) checkbox-beg))
12537 (goto-char checkbox-beg)
12538 (insert new)
12539 (delete-region (point) (+ (point) ndel))
12540 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12541 (when cookie-present
12542 (run-hook-with-args 'org-after-todo-statistics-hook
12543 cnt-done (- cnt-all cnt-done))))))
12544 (run-hooks 'org-todo-statistics-hook)))
12546 (defvar org-after-todo-statistics-hook nil
12547 "Hook that is called after a TODO statistics cookie has been updated.
12548 Each function is called with two arguments: the number of not-done entries
12549 and the number of done entries.
12551 For example, the following function, when added to this hook, will switch
12552 an entry to DONE when all children are done, and back to TODO when new
12553 entries are set to a TODO status. Note that this hook is only called
12554 when there is a statistics cookie in the headline!
12556 (defun org-summary-todo (n-done n-not-done)
12557 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12558 (let (org-log-done org-log-states) ; turn off logging
12559 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12562 (defvar org-todo-statistics-hook nil
12563 "Hook that is run whenever Org thinks TODO statistics should be updated.
12564 This hook runs even if there is no statistics cookie present, in which case
12565 `org-after-todo-statistics-hook' would not run.")
12567 (defun org-todo-trigger-tag-changes (state)
12568 "Apply the changes defined in `org-todo-state-tags-triggers'."
12569 (let ((l org-todo-state-tags-triggers)
12570 changes)
12571 (when (or (not state) (equal state ""))
12572 (setq changes (append changes (cdr (assoc "" l)))))
12573 (when (and (stringp state) (> (length state) 0))
12574 (setq changes (append changes (cdr (assoc state l)))))
12575 (when (member state org-not-done-keywords)
12576 (setq changes (append changes (cdr (assq 'todo l)))))
12577 (when (member state org-done-keywords)
12578 (setq changes (append changes (cdr (assq 'done l)))))
12579 (dolist (c changes)
12580 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12582 (defun org-local-logging (value)
12583 "Get logging settings from a property VALUE."
12584 ;; Directly set the variables, they are already local.
12585 (setq org-log-done nil
12586 org-log-repeat nil
12587 org-todo-log-states nil)
12588 (dolist (w (split-string value))
12589 (let (a)
12590 (cond
12591 ((setq a (assoc w org-startup-options))
12592 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12593 (set (nth 1 a) (nth 2 a))))
12594 ((setq a (org-extract-log-state-settings w))
12595 (and (member (car a) org-todo-keywords-1)
12596 (push a org-todo-log-states)))))))
12598 (defun org-get-todo-sequence-head (kwd)
12599 "Return the head of the TODO sequence to which KWD belongs.
12600 If KWD is not set, check if there is a text property remembering the
12601 right sequence."
12602 (let (p)
12603 (cond
12604 ((not kwd)
12605 (or (get-text-property (point-at-bol) 'org-todo-head)
12606 (progn
12607 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12608 nil (point-at-eol)))
12609 (get-text-property p 'org-todo-head))))
12610 ((not (member kwd org-todo-keywords-1))
12611 (car org-todo-keywords-1))
12612 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12614 (defun org-fast-todo-selection ()
12615 "Fast TODO keyword selection with single keys.
12616 Returns the new TODO keyword, or nil if no state change should occur."
12617 (let* ((fulltable org-todo-key-alist)
12618 (done-keywords org-done-keywords) ;; needed for the faces.
12619 (maxlen (apply 'max (mapcar
12620 (lambda (x)
12621 (if (stringp (car x)) (string-width (car x)) 0))
12622 fulltable)))
12623 (expert nil)
12624 (fwidth (+ maxlen 3 1 3))
12625 (ncol (/ (- (window-width) 4) fwidth))
12626 tg cnt e c tbl
12627 groups ingroup)
12628 (save-excursion
12629 (save-window-excursion
12630 (if expert
12631 (set-buffer (get-buffer-create " *Org todo*"))
12632 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12633 (erase-buffer)
12634 (setq-local org-done-keywords done-keywords)
12635 (setq tbl fulltable cnt 0)
12636 (while (setq e (pop tbl))
12637 (cond
12638 ((equal e '(:startgroup))
12639 (push '() groups) (setq ingroup t)
12640 (unless (= cnt 0)
12641 (setq cnt 0)
12642 (insert "\n"))
12643 (insert "{ "))
12644 ((equal e '(:endgroup))
12645 (setq ingroup nil cnt 0)
12646 (insert "}\n"))
12647 ((equal e '(:newline))
12648 (unless (= cnt 0)
12649 (setq cnt 0)
12650 (insert "\n")
12651 (setq e (car tbl))
12652 (while (equal (car tbl) '(:newline))
12653 (insert "\n")
12654 (setq tbl (cdr tbl)))))
12656 (setq tg (car e) c (cdr e))
12657 (when ingroup (push tg (car groups)))
12658 (setq tg (org-add-props tg nil 'face
12659 (org-get-todo-face tg)))
12660 (when (and (= cnt 0) (not ingroup)) (insert " "))
12661 (insert "[" c "] " tg (make-string
12662 (- fwidth 4 (length tg)) ?\ ))
12663 (when (= (setq cnt (1+ cnt)) ncol)
12664 (insert "\n")
12665 (when ingroup (insert " "))
12666 (setq cnt 0)))))
12667 (insert "\n")
12668 (goto-char (point-min))
12669 (unless expert (org-fit-window-to-buffer))
12670 (message "[a-z..]:Set [SPC]:clear")
12671 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12672 (cond
12673 ((or (= c ?\C-g)
12674 (and (= c ?q) (not (rassoc c fulltable))))
12675 (setq quit-flag t))
12676 ((= c ?\ ) nil)
12677 ((setq e (rassoc c fulltable) tg (car e))
12679 (t (setq quit-flag t)))))))
12681 (defun org-entry-is-todo-p ()
12682 (member (org-get-todo-state) org-not-done-keywords))
12684 (defun org-entry-is-done-p ()
12685 (member (org-get-todo-state) org-done-keywords))
12687 (defun org-get-todo-state ()
12688 "Return the TODO keyword of the current subtree."
12689 (save-excursion
12690 (org-back-to-heading t)
12691 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12692 (match-end 2)
12693 (match-string 2))))
12695 (defun org-at-date-range-p (&optional inactive-ok)
12696 "Non-nil if point is inside a date range.
12698 When optional argument INACTIVE-OK is non-nil, also consider
12699 inactive time ranges.
12701 When this function returns a non-nil value, match data is set
12702 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12703 on INACTIVE-OK."
12704 (interactive)
12705 (save-excursion
12706 (catch 'exit
12707 (let ((pos (point)))
12708 (skip-chars-backward "^[<\r\n")
12709 (skip-chars-backward "<[")
12710 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12711 (>= (match-end 0) pos)
12712 (throw 'exit t))
12713 (skip-chars-backward "^<[\r\n")
12714 (skip-chars-backward "<[")
12715 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12716 (>= (match-end 0) pos)
12717 (throw 'exit t)))
12718 nil)))
12720 (defun org-get-repeat (&optional timestamp)
12721 "Check if there is a time-stamp with repeater in this entry.
12723 Return the repeater, as a string, or nil. Also return nil when
12724 this function is called before first heading.
12726 When optional argument TIMESTAMP is a string, extract the
12727 repeater from there instead."
12728 (save-match-data
12729 (cond (timestamp
12730 (and (string-match org-repeat-re timestamp)
12731 (match-string-no-properties 1 timestamp)))
12732 ((org-before-first-heading-p) nil)
12734 (save-excursion
12735 (org-back-to-heading t)
12736 (let ((end (org-entry-end-position)))
12737 (catch :repeat
12738 (while (re-search-forward org-repeat-re end t)
12739 (when (save-match-data (org-at-timestamp-p 'agenda))
12740 (throw :repeat (match-string-no-properties 1)))))))))))
12742 (defvar org-last-changed-timestamp)
12743 (defvar org-last-inserted-timestamp)
12744 (defvar org-log-post-message)
12745 (defvar org-log-note-purpose)
12746 (defvar org-log-note-how nil)
12747 (defvar org-log-note-extra)
12748 (defun org-auto-repeat-maybe (done-word)
12749 "Check if the current headline contains a repeated time-stamp.
12751 If yes, set TODO state back to what it was and change the base date
12752 of repeating deadline/scheduled time stamps to new date.
12754 This function is run automatically after each state change to a DONE state."
12755 (let* ((repeat (org-get-repeat))
12756 (aa (assoc org-last-state org-todo-kwd-alist))
12757 (interpret (nth 1 aa))
12758 (head (nth 2 aa))
12759 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12760 (msg "Entry repeats: ")
12761 (org-log-done nil)
12762 (org-todo-log-states nil)
12763 (end (copy-marker (org-entry-end-position))))
12764 (unwind-protect
12765 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12766 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12767 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12768 org-todo-repeat-to-state)))
12769 (org-todo (cond
12770 ((and to-state (member to-state org-todo-keywords-1))
12771 to-state)
12772 ((eq interpret 'type) org-last-state)
12773 (head)
12774 (t 'none))))
12775 (org-back-to-heading t)
12776 (org-add-planning-info nil nil 'closed)
12777 ;; When `org-log-repeat' is non-nil or entry contains
12778 ;; a clock, set LAST_REPEAT property.
12779 (when (or org-log-repeat
12780 (catch :clock
12781 (save-excursion
12782 (while (re-search-forward org-clock-line-re end t)
12783 (when (org-at-clock-log-p) (throw :clock t))))))
12784 (org-entry-put nil "LAST_REPEAT" (format-time-string
12785 (org-time-stamp-format t t)
12786 (current-time))))
12787 (when org-log-repeat
12788 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12789 (memq 'org-add-log-note post-command-hook))
12790 ;; We are already setup for some record.
12791 (when (eq org-log-repeat 'note)
12792 ;; Make sure we take a note, not only a time stamp.
12793 (setq org-log-note-how 'note))
12794 ;; Set up for taking a record.
12795 (org-add-log-setup 'state
12796 (or done-word (car org-done-keywords))
12797 org-last-state
12798 org-log-repeat)))
12799 (let ((planning-re (regexp-opt
12800 (list org-scheduled-string org-deadline-string))))
12801 (while (re-search-forward org-ts-regexp end t)
12802 (let* ((ts (match-string 0))
12803 (planning? (org-at-planning-p))
12804 (type (if (not planning?) "Plain:"
12805 (save-excursion
12806 (re-search-backward
12807 planning-re (line-beginning-position) t)
12808 (match-string 0)))))
12809 (cond
12810 ;; Ignore fake time-stamps (e.g., within comments).
12811 ((not (org-at-timestamp-p 'agenda)))
12812 ;; Time-stamps without a repeater are usually
12813 ;; skipped. However, a SCHEDULED time-stamp without
12814 ;; one is removed, as they are no longer relevant.
12815 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12816 ts))
12817 (when (equal type org-scheduled-string)
12818 (org-remove-timestamp-with-keyword type)))
12820 (let ((n (string-to-number (match-string 2 ts)))
12821 (what (match-string 3 ts)))
12822 (when (equal what "w") (setq n (* n 7) what "d"))
12823 (when (and (equal what "h")
12824 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12825 ts)))
12826 (user-error
12827 "Cannot repeat in Repeat in %d hour(s) because no hour \
12828 has been set"
12830 ;; Preparation, see if we need to modify the start
12831 ;; date for the change.
12832 (when (match-end 1)
12833 (let ((time (save-match-data
12834 (org-time-string-to-time ts))))
12835 (cond
12836 ((equal (match-string 1 ts) ".")
12837 ;; Shift starting date to today
12838 (org-timestamp-change
12839 (- (org-today) (time-to-days time))
12840 'day))
12841 ((equal (match-string 1 ts) "+")
12842 (let ((nshiftmax 10)
12843 (nshift 0))
12844 (while (or (= nshift 0)
12845 (not (time-less-p (current-time) time)))
12846 (when (= (cl-incf nshift) nshiftmax)
12847 (or (y-or-n-p
12848 (format "%d repeater intervals were not \
12849 enough to shift date past today. Continue? "
12850 nshift))
12851 (user-error "Abort")))
12852 (org-timestamp-change n (cdr (assoc what whata)))
12853 (org-in-regexp org-ts-regexp3)
12854 (setq ts (match-string 1))
12855 (setq time
12856 (save-match-data
12857 (org-time-string-to-time ts)))))
12858 (org-timestamp-change (- n) (cdr (assoc what whata)))
12859 ;; Rematch, so that we have everything in place
12860 ;; for the real shift.
12861 (org-in-regexp org-ts-regexp3)
12862 (setq ts (match-string 1))
12863 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12864 ts)))))
12865 (save-excursion
12866 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12867 (setq msg
12868 (concat
12869 msg type " " org-last-changed-timestamp " "))))))))
12870 (setq org-log-post-message msg)
12871 (message "%s" msg))
12872 (set-marker end nil))))
12874 (defun org-show-todo-tree (arg)
12875 "Make a compact tree which shows all headlines marked with TODO.
12876 The tree will show the lines where the regexp matches, and all higher
12877 headlines above the match.
12878 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12879 With a numeric prefix N, construct a sparse tree for the Nth element
12880 of `org-todo-keywords-1'."
12881 (interactive "P")
12882 (let ((case-fold-search nil)
12883 (kwd-re
12884 (cond ((null arg) org-not-done-regexp)
12885 ((equal arg '(4))
12886 (let ((kwd
12887 (completing-read "Keyword (or KWD1|KWD2|...): "
12888 (mapcar #'list org-todo-keywords-1))))
12889 (concat "\\("
12890 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12891 "\\)\\>")))
12892 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12893 (regexp-quote (nth (1- (prefix-numeric-value arg))
12894 org-todo-keywords-1)))
12895 (t (user-error "Invalid prefix argument: %s" arg)))))
12896 (message "%d TODO entries found"
12897 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12899 (defun org--deadline-or-schedule (arg type time)
12900 "Insert DEADLINE or SCHEDULE information in current entry.
12901 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12902 `org-schedule' for information about ARG and TIME arguments."
12903 (let* ((deadline? (eq type 'deadline))
12904 (keyword (if deadline? org-deadline-string org-scheduled-string))
12905 (log (if deadline? org-log-redeadline org-log-reschedule))
12906 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12907 (old-date-time (and old-date (org-time-string-to-time old-date)))
12908 ;; Save repeater cookie from either TIME or current scheduled
12909 ;; time stamp. We are going to insert it back at the end of
12910 ;; the process.
12911 (repeater (or (and (org-string-nw-p time)
12912 ;; We use `org-repeat-re' because we need
12913 ;; to tell the difference between a real
12914 ;; repeater and a time delta, e.g. "+2d".
12915 (string-match org-repeat-re time)
12916 (match-string 1 time))
12917 (and (org-string-nw-p old-date)
12918 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12919 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12920 old-date)
12921 (match-string 1 old-date)))))
12922 (pcase arg
12923 (`(4)
12924 (when (and old-date log)
12925 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12926 nil old-date log))
12927 (org-remove-timestamp-with-keyword keyword)
12928 (message (if deadline? "Item no longer has a deadline."
12929 "Item is no longer scheduled.")))
12930 (`(16)
12931 (save-excursion
12932 (org-back-to-heading t)
12933 (let ((regexp (if deadline? org-deadline-time-regexp
12934 org-scheduled-time-regexp)))
12935 (if (not (re-search-forward regexp (line-end-position 2) t))
12936 (user-error (if deadline? "No deadline information to update"
12937 "No scheduled information to update"))
12938 (let* ((rpl0 (match-string 1))
12939 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12940 (msg (if deadline? "Warn starting from" "Delay until")))
12941 (replace-match
12942 (concat keyword
12943 " <" rpl
12944 (format " -%dd"
12945 (abs (- (time-to-days
12946 (save-match-data
12947 (org-read-date
12948 nil t nil msg old-date-time)))
12949 (time-to-days old-date-time))))
12950 ">") t t))))))
12952 (org-add-planning-info type time 'closed)
12953 (when (and old-date
12955 (not (equal old-date org-last-inserted-timestamp)))
12956 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12957 org-last-inserted-timestamp
12958 old-date
12959 log))
12960 (when repeater
12961 (save-excursion
12962 (org-back-to-heading t)
12963 (when (re-search-forward
12964 (concat keyword " " org-last-inserted-timestamp)
12965 (line-end-position 2)
12967 (goto-char (1- (match-end 0)))
12968 (insert " " repeater)
12969 (setq org-last-inserted-timestamp
12970 (concat (substring org-last-inserted-timestamp 0 -1)
12971 " " repeater
12972 (substring org-last-inserted-timestamp -1))))))
12973 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12974 org-last-inserted-timestamp)))))
12976 (defun org-deadline (arg &optional time)
12977 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12978 With one universal prefix argument, remove any deadline from the item.
12979 With two universal prefix arguments, prompt for a warning delay.
12980 With argument TIME, set the deadline at the corresponding date. TIME
12981 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12982 (interactive "P")
12983 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12984 (org-map-entries
12985 (lambda () (org--deadline-or-schedule arg 'deadline time))
12987 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12988 'region-start-level
12989 'region)
12990 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12991 (org--deadline-or-schedule arg 'deadline time)))
12993 (defun org-schedule (arg &optional time)
12994 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12995 With one universal prefix argument, remove any scheduling date from the item.
12996 With two universal prefix arguments, prompt for a delay cookie.
12997 With argument TIME, scheduled at the corresponding date. TIME can
12998 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12999 (interactive "P")
13000 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13001 (org-map-entries
13002 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13004 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13005 'region-start-level
13006 'region)
13007 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13008 (org--deadline-or-schedule arg 'scheduled time)))
13010 (defun org-get-scheduled-time (pom &optional inherit)
13011 "Get the scheduled time as a time tuple, of a format suitable
13012 for calling org-schedule with, or if there is no scheduling,
13013 returns nil."
13014 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13015 (when time
13016 (apply 'encode-time (org-parse-time-string time)))))
13018 (defun org-get-deadline-time (pom &optional inherit)
13019 "Get the deadline as a time tuple, of a format suitable for
13020 calling org-deadline with, or if there is no scheduling, returns
13021 nil."
13022 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13023 (when time
13024 (apply 'encode-time (org-parse-time-string time)))))
13026 (defun org-remove-timestamp-with-keyword (keyword)
13027 "Remove all time stamps with KEYWORD in the current entry."
13028 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13029 beg)
13030 (save-excursion
13031 (org-back-to-heading t)
13032 (setq beg (point))
13033 (outline-next-heading)
13034 (while (re-search-backward re beg t)
13035 (replace-match "")
13036 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13037 (equal (char-before) ?\ ))
13038 (backward-delete-char 1)
13039 (when (string-match "^[ \t]*$" (buffer-substring
13040 (point-at-bol) (point-at-eol)))
13041 (delete-region (point-at-bol)
13042 (min (point-max) (1+ (point-at-eol))))))))))
13044 (defvar org-time-was-given) ; dynamically scoped parameter
13045 (defvar org-end-time-was-given) ; dynamically scoped parameter
13047 (defun org-at-planning-p ()
13048 "Non-nil when point is on a planning info line."
13049 ;; This is as accurate and faster than `org-element-at-point' since
13050 ;; planning info location is fixed in the section.
13051 (org-with-wide-buffer
13052 (beginning-of-line)
13053 (and (looking-at-p org-planning-line-re)
13054 (eq (point)
13055 (ignore-errors
13056 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13057 (org-back-to-heading t)
13058 (org-with-limited-levels (org-back-to-heading t)))
13059 (line-beginning-position 2))))))
13061 (defun org-add-planning-info (what &optional time &rest remove)
13062 "Insert new timestamp with keyword in the planning line.
13063 WHAT indicates what kind of time stamp to add. It is a symbol
13064 among `closed', `deadline', `scheduled' and nil. TIME indicates
13065 the time to use. If none is given, the user is prompted for
13066 a date. REMOVE indicates what kind of entries to remove. An old
13067 WHAT entry will also be removed."
13068 (let (org-time-was-given org-end-time-was-given default-time default-input)
13069 (catch 'exit
13070 (when (and (memq what '(scheduled deadline))
13071 (or (not time)
13072 (and (stringp time)
13073 (string-match "^[-+]+[0-9]" time))))
13074 ;; Try to get a default date/time from existing timestamp
13075 (save-excursion
13076 (org-back-to-heading t)
13077 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13078 (when (re-search-forward (if (eq what 'scheduled)
13079 org-scheduled-time-regexp
13080 org-deadline-time-regexp)
13081 end t)
13082 (setq ts (match-string 1)
13083 default-time (apply 'encode-time (org-parse-time-string ts))
13084 default-input (and ts (org-get-compact-tod ts)))))))
13085 (when what
13086 (setq time
13087 (if (stringp time)
13088 ;; This is a string (relative or absolute), set
13089 ;; proper date.
13090 (apply #'encode-time
13091 (org-read-date-analyze
13092 time default-time (decode-time default-time)))
13093 ;; If necessary, get the time from the user
13094 (or time (org-read-date nil 'to-time nil nil
13095 default-time default-input)))))
13097 (org-with-wide-buffer
13098 (org-back-to-heading t)
13099 (forward-line)
13100 (unless (bolp) (insert "\n"))
13101 (cond ((looking-at-p org-planning-line-re)
13102 ;; Move to current indentation.
13103 (skip-chars-forward " \t")
13104 ;; Check if we have to remove something.
13105 (dolist (type (if what (cons what remove) remove))
13106 (save-excursion
13107 (when (re-search-forward
13108 (cl-case type
13109 (closed org-closed-time-regexp)
13110 (deadline org-deadline-time-regexp)
13111 (scheduled org-scheduled-time-regexp)
13112 (otherwise
13113 (error "Invalid planning type: %s" type)))
13114 (line-end-position) t)
13115 ;; Delete until next keyword or end of line.
13116 (delete-region
13117 (match-beginning 0)
13118 (if (re-search-forward org-keyword-time-not-clock-regexp
13119 (line-end-position)
13121 (match-beginning 0)
13122 (line-end-position))))))
13123 ;; If there is nothing more to add and no more keyword
13124 ;; is left, remove the line completely.
13125 (if (and (looking-at-p "[ \t]*$") (not what))
13126 (delete-region (line-beginning-position)
13127 (line-beginning-position 2))
13128 ;; If we removed last keyword, do not leave trailing
13129 ;; white space at the end of line.
13130 (let ((p (point)))
13131 (save-excursion
13132 (end-of-line)
13133 (unless (= (skip-chars-backward " \t" p) 0)
13134 (delete-region (point) (line-end-position)))))))
13135 ((not what) (throw 'exit nil)) ; Nothing to do.
13136 (t (insert-before-markers "\n")
13137 (backward-char 1)
13138 (when org-adapt-indentation
13139 (indent-to-column (1+ (org-outline-level))))))
13140 (when what
13141 ;; Insert planning keyword.
13142 (insert (cl-case what
13143 (closed org-closed-string)
13144 (deadline org-deadline-string)
13145 (scheduled org-scheduled-string)
13146 (otherwise (error "Invalid planning type: %s" what)))
13147 " ")
13148 ;; Insert associated timestamp.
13149 (let ((ts (org-insert-time-stamp
13150 time
13151 (or org-time-was-given
13152 (and (eq what 'closed) org-log-done-with-time))
13153 (eq what 'closed)
13154 nil nil (list org-end-time-was-given))))
13155 (unless (eolp) (insert " "))
13156 ts))))))
13158 (defvar org-log-note-marker (make-marker)
13159 "Marker pointing at the entry where the note is to be inserted.")
13160 (defvar org-log-note-purpose nil)
13161 (defvar org-log-note-state nil)
13162 (defvar org-log-note-previous-state nil)
13163 (defvar org-log-note-extra nil)
13164 (defvar org-log-note-window-configuration nil)
13165 (defvar org-log-note-return-to (make-marker))
13166 (defvar org-log-note-effective-time nil
13167 "Remembered current time so that dynamically scoped
13168 `org-extend-today-until' affects timestamps in state change log")
13170 (defvar org-log-post-message nil
13171 "Message to be displayed after a log note has been stored.
13172 The auto-repeater uses this.")
13174 (defun org-add-note ()
13175 "Add a note to the current entry.
13176 This is done in the same way as adding a state change note."
13177 (interactive)
13178 (org-add-log-setup 'note))
13180 (defun org-log-beginning (&optional create)
13181 "Return expected start of log notes in current entry.
13182 When optional argument CREATE is non-nil, the function creates
13183 a drawer to store notes, if necessary. Returned position ignores
13184 narrowing."
13185 (org-with-wide-buffer
13186 (let ((drawer (org-log-into-drawer)))
13187 (cond
13188 (drawer
13189 (org-end-of-meta-data)
13190 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13191 (end (if (org-at-heading-p) (point)
13192 (save-excursion (outline-next-heading) (point))))
13193 (case-fold-search t))
13194 (catch 'exit
13195 ;; Try to find existing drawer.
13196 (while (re-search-forward regexp end t)
13197 (let ((element (org-element-at-point)))
13198 (when (eq (org-element-type element) 'drawer)
13199 (let ((cend (org-element-property :contents-end element)))
13200 (when (and (not org-log-states-order-reversed) cend)
13201 (goto-char cend)))
13202 (throw 'exit nil))))
13203 ;; No drawer found. Create one, if permitted.
13204 (when create
13205 (unless (bolp) (insert "\n"))
13206 (let ((beg (point)))
13207 (insert ":" drawer ":\n:END:\n")
13208 (org-indent-region beg (point)))
13209 (end-of-line -1)))))
13211 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13212 (skip-chars-forward " \t\n")
13213 (beginning-of-line)
13214 (unless org-log-states-order-reversed
13215 (org-skip-over-state-notes)
13216 (skip-chars-backward " \t\n")
13217 (forward-line)))))
13218 (if (bolp) (point) (line-beginning-position 2))))
13220 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13221 "Set up the post command hook to take a note.
13222 If this is about to TODO state change, the new state is expected in STATE.
13223 HOW is an indicator what kind of note should be created.
13224 EXTRA is additional text that will be inserted into the notes buffer."
13225 (move-marker org-log-note-marker (point))
13226 (setq org-log-note-purpose purpose
13227 org-log-note-state state
13228 org-log-note-previous-state prev-state
13229 org-log-note-how how
13230 org-log-note-extra extra
13231 org-log-note-effective-time (org-current-effective-time))
13232 (add-hook 'post-command-hook 'org-add-log-note 'append))
13234 (defun org-skip-over-state-notes ()
13235 "Skip past the list of State notes in an entry."
13236 (when (ignore-errors (goto-char (org-in-item-p)))
13237 (let* ((struct (org-list-struct))
13238 (prevs (org-list-prevs-alist struct))
13239 (regexp
13240 (concat "[ \t]*- +"
13241 (replace-regexp-in-string
13242 " +" " +"
13243 (org-replace-escapes
13244 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13245 `(("%d" . ,org-ts-regexp-inactive)
13246 ("%D" . ,org-ts-regexp)
13247 ("%s" . "\"\\S-+\"")
13248 ("%S" . "\"\\S-+\"")
13249 ("%t" . ,org-ts-regexp-inactive)
13250 ("%T" . ,org-ts-regexp)
13251 ("%u" . ".*?")
13252 ("%U" . ".*?")))))))
13253 (while (looking-at-p regexp)
13254 (goto-char (or (org-list-get-next-item (point) struct prevs)
13255 (org-list-get-item-end (point) struct)))))))
13257 (defun org-add-log-note (&optional _purpose)
13258 "Pop up a window for taking a note, and add this note later."
13259 (remove-hook 'post-command-hook 'org-add-log-note)
13260 (setq org-log-note-window-configuration (current-window-configuration))
13261 (delete-other-windows)
13262 (move-marker org-log-note-return-to (point))
13263 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13264 (goto-char org-log-note-marker)
13265 (org-switch-to-buffer-other-window "*Org Note*")
13266 (erase-buffer)
13267 (if (memq org-log-note-how '(time state))
13268 (org-store-log-note)
13269 (let ((org-inhibit-startup t)) (org-mode))
13270 (insert (format "# Insert note for %s.
13271 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13272 (cond
13273 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13274 ((eq org-log-note-purpose 'done) "closed todo item")
13275 ((eq org-log-note-purpose 'state)
13276 (format "state change from \"%s\" to \"%s\""
13277 (or org-log-note-previous-state "")
13278 (or org-log-note-state "")))
13279 ((eq org-log-note-purpose 'reschedule)
13280 "rescheduling")
13281 ((eq org-log-note-purpose 'delschedule)
13282 "no longer scheduled")
13283 ((eq org-log-note-purpose 'redeadline)
13284 "changing deadline")
13285 ((eq org-log-note-purpose 'deldeadline)
13286 "removing deadline")
13287 ((eq org-log-note-purpose 'refile)
13288 "refiling")
13289 ((eq org-log-note-purpose 'note)
13290 "this entry")
13291 (t (error "This should not happen")))))
13292 (when org-log-note-extra (insert org-log-note-extra))
13293 (setq-local org-finish-function 'org-store-log-note)
13294 (run-hooks 'org-log-buffer-setup-hook)))
13296 (defvar org-note-abort nil) ; dynamically scoped
13297 (defun org-store-log-note ()
13298 "Finish taking a log note, and insert it to where it belongs."
13299 (let ((txt (prog1 (buffer-string)
13300 (kill-buffer)))
13301 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13302 lines)
13303 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13304 (setq txt (replace-match "" t t txt)))
13305 (when (string-match "\\s-+\\'" txt)
13306 (setq txt (replace-match "" t t txt)))
13307 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13308 (when (org-string-nw-p note)
13309 (setq note
13310 (org-replace-escapes
13311 note
13312 (list (cons "%u" (user-login-name))
13313 (cons "%U" user-full-name)
13314 (cons "%t" (format-time-string
13315 (org-time-stamp-format 'long 'inactive)
13316 org-log-note-effective-time))
13317 (cons "%T" (format-time-string
13318 (org-time-stamp-format 'long nil)
13319 org-log-note-effective-time))
13320 (cons "%d" (format-time-string
13321 (org-time-stamp-format nil 'inactive)
13322 org-log-note-effective-time))
13323 (cons "%D" (format-time-string
13324 (org-time-stamp-format nil nil)
13325 org-log-note-effective-time))
13326 (cons "%s" (cond
13327 ((not org-log-note-state) "")
13328 ((string-match-p org-ts-regexp
13329 org-log-note-state)
13330 (format "\"[%s]\""
13331 (substring org-log-note-state 1 -1)))
13332 (t (format "\"%s\"" org-log-note-state))))
13333 (cons "%S"
13334 (cond
13335 ((not org-log-note-previous-state) "")
13336 ((string-match-p org-ts-regexp
13337 org-log-note-previous-state)
13338 (format "\"[%s]\""
13339 (substring
13340 org-log-note-previous-state 1 -1)))
13341 (t (format "\"%s\""
13342 org-log-note-previous-state)))))))
13343 (when lines (setq note (concat note " \\\\")))
13344 (push note lines))
13345 (when (and lines (not org-note-abort))
13346 (with-current-buffer (marker-buffer org-log-note-marker)
13347 (org-with-wide-buffer
13348 ;; Find location for the new note.
13349 (goto-char org-log-note-marker)
13350 (set-marker org-log-note-marker nil)
13351 ;; Note associated to a clock is to be located right after
13352 ;; the clock. Do not move point.
13353 (unless (eq org-log-note-purpose 'clock-out)
13354 (goto-char (org-log-beginning t)))
13355 ;; Make sure point is at the beginning of an empty line.
13356 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13357 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13358 ;; In an existing list, add a new item at the top level.
13359 ;; Otherwise, indent line like a regular one.
13360 (let ((itemp (org-in-item-p)))
13361 (if itemp
13362 (indent-line-to
13363 (let ((struct (save-excursion
13364 (goto-char itemp) (org-list-struct))))
13365 (org-list-get-ind (org-list-get-top-point struct) struct)))
13366 (org-indent-line)))
13367 (insert (org-list-bullet-string "-") (pop lines))
13368 (let ((ind (org-list-item-body-column (line-beginning-position))))
13369 (dolist (line lines)
13370 (insert "\n")
13371 (indent-line-to ind)
13372 (insert line)))
13373 (message "Note stored")
13374 (org-back-to-heading t)
13375 (org-cycle-hide-drawers 'children))
13376 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13377 ;; from within `org-add-log-note' because `buffer-undo-list'
13378 ;; is then modified outside of `org-with-remote-undo'.
13379 (when (eq this-command 'org-agenda-todo)
13380 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13381 ;; Don't add undo information when called from `org-agenda-todo'.
13382 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13383 (set-window-configuration org-log-note-window-configuration)
13384 (with-current-buffer (marker-buffer org-log-note-return-to)
13385 (goto-char org-log-note-return-to))
13386 (move-marker org-log-note-return-to nil)
13387 (when org-log-post-message (message "%s" org-log-post-message))))
13389 (defun org-remove-empty-drawer-at (pos)
13390 "Remove an empty drawer at position POS.
13391 POS may also be a marker."
13392 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13393 (org-with-wide-buffer
13394 (goto-char pos)
13395 (let ((drawer (org-element-at-point)))
13396 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13397 (not (org-element-property :contents-begin drawer)))
13398 (delete-region (org-element-property :begin drawer)
13399 (progn (goto-char (org-element-property :end drawer))
13400 (skip-chars-backward " \r\t\n")
13401 (forward-line)
13402 (point))))))))
13404 (defvar org-ts-type nil)
13405 (defun org-sparse-tree (&optional arg type)
13406 "Create a sparse tree, prompt for the details.
13407 This command can create sparse trees. You first need to select the type
13408 of match used to create the tree:
13410 t Show all TODO entries.
13411 T Show entries with a specific TODO keyword.
13412 m Show entries selected by a tags/property match.
13413 p Enter a property name and its value (both with completion on existing
13414 names/values) and show entries with that property.
13415 r Show entries matching a regular expression (`/' can be used as well).
13416 b Show deadlines and scheduled items before a date.
13417 a Show deadlines and scheduled items after a date.
13418 d Show deadlines due within `org-deadline-warning-days'.
13419 D Show deadlines and scheduled items between a date range."
13420 (interactive "P")
13421 (setq type (or type org-sparse-tree-default-date-type))
13422 (setq org-ts-type type)
13423 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13424 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13425 \[c]ycle through date types: %s"
13426 (cl-case type
13427 (all "all timestamps")
13428 (scheduled "only scheduled")
13429 (deadline "only deadline")
13430 (active "only active timestamps")
13431 (inactive "only inactive timestamps")
13432 (closed "with a closed time-stamp")
13433 (otherwise "scheduled/deadline")))
13434 (let ((answer (read-char-exclusive)))
13435 (cl-case answer
13437 (org-sparse-tree
13439 (cadr
13440 (memq type '(nil all scheduled deadline active inactive closed)))))
13441 (?d (call-interactively 'org-check-deadlines))
13442 (?b (call-interactively 'org-check-before-date))
13443 (?a (call-interactively 'org-check-after-date))
13444 (?D (call-interactively 'org-check-dates-range))
13445 (?t (call-interactively 'org-show-todo-tree))
13446 (?T (org-show-todo-tree '(4)))
13447 (?m (call-interactively 'org-match-sparse-tree))
13448 ((?p ?P)
13449 (let* ((kwd (completing-read
13450 "Property: " (mapcar #'list (org-buffer-property-keys))))
13451 (value (completing-read
13452 "Value: " (mapcar #'list (org-property-values kwd)))))
13453 (unless (string-match "\\`{.*}\\'" value)
13454 (setq value (concat "\"" value "\"")))
13455 (org-match-sparse-tree arg (concat kwd "=" value))))
13456 ((?r ?R ?/) (call-interactively 'org-occur))
13457 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13459 (defvar-local org-occur-highlights nil
13460 "List of overlays used for occur matches.")
13461 (defvar-local org-occur-parameters nil
13462 "Parameters of the active org-occur calls.
13463 This is a list, each call to org-occur pushes as cons cell,
13464 containing the regular expression and the callback, onto the list.
13465 The list can contain several entries if `org-occur' has been called
13466 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13467 will only contain one set of parameters. When the highlights are
13468 removed (for example with `C-c C-c', or with the next edit (depending
13469 on `org-remove-highlights-with-change'), this variable is emptied
13470 as well.")
13472 (defun org-occur (regexp &optional keep-previous callback)
13473 "Make a compact tree which shows all matches of REGEXP.
13475 The tree will show the lines where the regexp matches, and any other context
13476 defined in `org-show-context-detail', which see.
13478 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13479 done by a previous call to `org-occur' will be kept, to allow stacking of
13480 calls to this command.
13482 Optional argument CALLBACK can be a function of no argument. In this case,
13483 it is called with point at the end of the match, match data being set
13484 accordingly. Current match is shown only if the return value is non-nil.
13485 The function must neither move point nor alter narrowing."
13486 (interactive "sRegexp: \nP")
13487 (when (equal regexp "")
13488 (user-error "Regexp cannot be empty"))
13489 (unless keep-previous
13490 (org-remove-occur-highlights nil nil t))
13491 (push (cons regexp callback) org-occur-parameters)
13492 (let ((cnt 0))
13493 (save-excursion
13494 (goto-char (point-min))
13495 (when (or (not keep-previous) ; do not want to keep
13496 (not org-occur-highlights)) ; no previous matches
13497 ;; hide everything
13498 (org-overview))
13499 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13500 (isearch-no-upper-case-p regexp t)
13501 org-occur-case-fold-search)))
13502 (while (re-search-forward regexp nil t)
13503 (when (or (not callback)
13504 (save-match-data (funcall callback)))
13505 (setq cnt (1+ cnt))
13506 (when org-highlight-sparse-tree-matches
13507 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13508 (org-show-context 'occur-tree)))))
13509 (when org-remove-highlights-with-change
13510 (add-hook 'before-change-functions 'org-remove-occur-highlights
13511 nil 'local))
13512 (unless org-sparse-tree-open-archived-trees
13513 (org-hide-archived-subtrees (point-min) (point-max)))
13514 (run-hooks 'org-occur-hook)
13515 (when (called-interactively-p 'interactive)
13516 (message "%d match(es) for regexp %s" cnt regexp))
13517 cnt))
13519 (defun org-occur-next-match (&optional n _reset)
13520 "Function for `next-error-function' to find sparse tree matches.
13521 N is the number of matches to move, when negative move backwards.
13522 This function always goes back to the starting point when no
13523 match is found."
13524 (let* ((limit (if (< n 0) (point-min) (point-max)))
13525 (search-func (if (< n 0)
13526 'previous-single-char-property-change
13527 'next-single-char-property-change))
13528 (n (abs n))
13529 (pos (point))
13531 (catch 'exit
13532 (while (setq p1 (funcall search-func (point) 'org-type))
13533 (when (equal p1 limit)
13534 (goto-char pos)
13535 (user-error "No more matches"))
13536 (when (equal (get-char-property p1 'org-type) 'org-occur)
13537 (setq n (1- n))
13538 (when (= n 0)
13539 (goto-char p1)
13540 (throw 'exit (point))))
13541 (goto-char p1))
13542 (goto-char p1)
13543 (user-error "No more matches"))))
13545 (defun org-show-context (&optional key)
13546 "Make sure point and context are visible.
13547 Optional argument KEY, when non-nil, is a symbol. See
13548 `org-show-context-detail' for allowed values and how much is to
13549 be shown."
13550 (org-show-set-visibility
13551 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13552 ((cdr (assq key org-show-context-detail)))
13553 (t (cdr (assq 'default org-show-context-detail))))))
13555 (defun org-show-set-visibility (detail)
13556 "Set visibility around point according to DETAIL.
13557 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13558 `tree', `canonical' or t. See `org-show-context-detail' for more
13559 information."
13560 ;; Show current heading and possibly its entry, following headline
13561 ;; or all children.
13562 (if (and (org-at-heading-p) (not (eq detail 'local)))
13563 (org-flag-heading nil)
13564 (org-show-entry)
13565 ;; If point is hidden within a drawer or a block, make sure to
13566 ;; expose it.
13567 (dolist (o (overlays-at (point)))
13568 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13569 (delete-overlay o)))
13570 (unless (org-before-first-heading-p)
13571 (org-with-limited-levels
13572 (cl-case detail
13573 ((tree canonical t) (org-show-children))
13574 ((nil minimal ancestors))
13575 (t (save-excursion
13576 (outline-next-heading)
13577 (org-flag-heading nil)))))))
13578 ;; Show all siblings.
13579 (when (eq detail 'lineage) (org-show-siblings))
13580 ;; Show ancestors, possibly with their children.
13581 (when (memq detail '(ancestors lineage tree canonical t))
13582 (save-excursion
13583 (while (org-up-heading-safe)
13584 (org-flag-heading nil)
13585 (when (memq detail '(canonical t)) (org-show-entry))
13586 (when (memq detail '(tree canonical t)) (org-show-children))))))
13588 (defvar org-reveal-start-hook nil
13589 "Hook run before revealing a location.")
13591 (defun org-reveal (&optional siblings)
13592 "Show current entry, hierarchy above it, and the following headline.
13594 This can be used to show a consistent set of context around
13595 locations exposed with `org-show-context'.
13597 With optional argument SIBLINGS, on each level of the hierarchy all
13598 siblings are shown. This repairs the tree structure to what it would
13599 look like when opened with hierarchical calls to `org-cycle'.
13601 With a \\[universal-argument] \\[universal-argument] prefix, \
13602 go to the parent and show the entire tree."
13603 (interactive "P")
13604 (run-hooks 'org-reveal-start-hook)
13605 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13606 ((equal siblings '(16))
13607 (save-excursion
13608 (when (org-up-heading-safe)
13609 (org-show-subtree)
13610 (run-hook-with-args 'org-cycle-hook 'subtree))))
13611 (t (org-show-set-visibility 'lineage))))
13613 (defun org-highlight-new-match (beg end)
13614 "Highlight from BEG to END and mark the highlight is an occur headline."
13615 (let ((ov (make-overlay beg end)))
13616 (overlay-put ov 'face 'secondary-selection)
13617 (overlay-put ov 'org-type 'org-occur)
13618 (push ov org-occur-highlights)))
13620 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13621 "Remove the occur highlights from the buffer.
13622 BEG and END are ignored. If NOREMOVE is nil, remove this function
13623 from the `before-change-functions' in the current buffer."
13624 (interactive)
13625 (unless org-inhibit-highlight-removal
13626 (mapc #'delete-overlay org-occur-highlights)
13627 (setq org-occur-highlights nil)
13628 (setq org-occur-parameters nil)
13629 (unless noremove
13630 (remove-hook 'before-change-functions
13631 'org-remove-occur-highlights 'local))))
13633 ;;;; Priorities
13635 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13636 "Regular expression matching the priority indicator.")
13638 (defvar org-remove-priority-next-time nil)
13640 (defun org-priority-up ()
13641 "Increase the priority of the current item."
13642 (interactive)
13643 (org-priority 'up))
13645 (defun org-priority-down ()
13646 "Decrease the priority of the current item."
13647 (interactive)
13648 (org-priority 'down))
13650 (defun org-priority (&optional action _show)
13651 "Change the priority of an item.
13652 ACTION can be `set', `up', `down', or a character."
13653 (interactive "P")
13654 (if (equal action '(4))
13655 (org-show-priority)
13656 (unless org-enable-priority-commands
13657 (user-error "Priority commands are disabled"))
13658 (setq action (or action 'set))
13659 (let (current new news have remove)
13660 (save-excursion
13661 (org-back-to-heading t)
13662 (when (looking-at org-priority-regexp)
13663 (setq current (string-to-char (match-string 2))
13664 have t))
13665 (cond
13666 ((eq action 'remove)
13667 (setq remove t new ?\ ))
13668 ((or (eq action 'set)
13669 (integerp action))
13670 (if (not (eq action 'set))
13671 (setq new action)
13672 (message "Priority %c-%c, SPC to remove: "
13673 org-highest-priority org-lowest-priority)
13674 (save-match-data
13675 (setq new (read-char-exclusive))))
13676 (when (and (= (upcase org-highest-priority) org-highest-priority)
13677 (= (upcase org-lowest-priority) org-lowest-priority))
13678 (setq new (upcase new)))
13679 (cond ((equal new ?\ ) (setq remove t))
13680 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13681 (user-error "Priority must be between `%c' and `%c'"
13682 org-highest-priority org-lowest-priority))))
13683 ((eq action 'up)
13684 (setq new (if have
13685 (1- current) ; normal cycling
13686 ;; last priority was empty
13687 (if (eq last-command this-command)
13688 org-lowest-priority ; wrap around empty to lowest
13689 ;; default
13690 (if org-priority-start-cycle-with-default
13691 org-default-priority
13692 (1- org-default-priority))))))
13693 ((eq action 'down)
13694 (setq new (if have
13695 (1+ current) ; normal cycling
13696 ;; last priority was empty
13697 (if (eq last-command this-command)
13698 org-highest-priority ; wrap around empty to highest
13699 ;; default
13700 (if org-priority-start-cycle-with-default
13701 org-default-priority
13702 (1+ org-default-priority))))))
13703 (t (user-error "Invalid action")))
13704 (when (or (< (upcase new) org-highest-priority)
13705 (> (upcase new) org-lowest-priority))
13706 (if (and (memq action '(up down))
13707 (not have) (not (eq last-command this-command)))
13708 ;; `new' is from default priority
13709 (error
13710 "The default can not be set, see `org-default-priority' why")
13711 ;; normal cycling: `new' is beyond highest/lowest priority
13712 ;; and is wrapped around to the empty priority
13713 (setq remove t)))
13714 (setq news (format "%c" new))
13715 (if have
13716 (if remove
13717 (replace-match "" t t nil 1)
13718 (replace-match news t t nil 2))
13719 (if remove
13720 (user-error "No priority cookie found in line")
13721 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13722 (if (match-end 2)
13723 (progn
13724 (goto-char (match-end 2))
13725 (insert " [#" news "]"))
13726 (goto-char (match-beginning 3))
13727 (insert "[#" news "] "))))
13728 (org-set-tags nil 'align))
13729 (if remove
13730 (message "Priority removed")
13731 (message "Priority of current item set to %s" news)))))
13733 (defun org-show-priority ()
13734 "Show the priority of the current item.
13735 This priority is composed of the main priority given with the [#A] cookies,
13736 and by additional input from the age of a schedules or deadline entry."
13737 (interactive)
13738 (let ((pri (if (eq major-mode 'org-agenda-mode)
13739 (org-get-at-bol 'priority)
13740 (save-excursion
13741 (save-match-data
13742 (beginning-of-line)
13743 (and (looking-at org-heading-regexp)
13744 (org-get-priority (match-string 0))))))))
13745 (message "Priority is %d" (if pri pri -1000))))
13747 (defun org-get-priority (s)
13748 "Find priority cookie and return priority."
13749 (save-match-data
13750 (if (functionp org-get-priority-function)
13751 (funcall org-get-priority-function)
13752 (if (not (string-match org-priority-regexp s))
13753 (* 1000 (- org-lowest-priority org-default-priority))
13754 (* 1000 (- org-lowest-priority
13755 (string-to-char (match-string 2 s))))))))
13757 ;;;; Tags
13759 (defvar org-agenda-archives-mode)
13760 (defvar org-map-continue-from nil
13761 "Position from where mapping should continue.
13762 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13764 (defvar org-scanner-tags nil
13765 "The current tag list while the tags scanner is running.")
13767 (defvar org-trust-scanner-tags nil
13768 "Should `org-get-tags-at' use the tags for the scanner.
13769 This is for internal dynamical scoping only.
13770 When this is non-nil, the function `org-get-tags-at' will return the value
13771 of `org-scanner-tags' instead of building the list by itself. This
13772 can lead to large speed-ups when the tags scanner is used in a file with
13773 many entries, and when the list of tags is retrieved, for example to
13774 obtain a list of properties. Building the tags list for each entry in such
13775 a file becomes an N^2 operation - but with this variable set, it scales
13776 as N.")
13778 (defvar org--matcher-tags-todo-only nil)
13780 (defun org-scan-tags (action matcher todo-only &optional start-level)
13781 "Scan headline tags with inheritance and produce output ACTION.
13783 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13784 or `agenda' to produce an entry list for an agenda view. It can also be
13785 a Lisp form or a function that should be called at each matched headline, in
13786 this case the return value is a list of all return values from these calls.
13788 MATCHER is a function accepting three arguments, returning
13789 a non-nil value whenever a given set of tags qualifies a headline
13790 for inclusion. See `org-make-tags-matcher' for more information.
13791 As a special case, it can also be set to t (respectively nil) in
13792 order to match all (respectively none) headline.
13794 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13795 included in the output.
13797 START-LEVEL can be a string with asterisks, reducing the scope to
13798 headlines matching this string."
13799 (require 'org-agenda)
13800 (let* ((re (concat "^"
13801 (if start-level
13802 ;; Get the correct level to match
13803 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13804 org-outline-regexp)
13805 " *\\(\\<\\("
13806 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13807 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13808 (props (list 'face 'default
13809 'done-face 'org-agenda-done
13810 'undone-face 'default
13811 'mouse-face 'highlight
13812 'org-not-done-regexp org-not-done-regexp
13813 'org-todo-regexp org-todo-regexp
13814 'org-complex-heading-regexp org-complex-heading-regexp
13815 'help-echo
13816 (format "mouse-2 or RET jump to org file %s"
13817 (abbreviate-file-name
13818 (or (buffer-file-name (buffer-base-buffer))
13819 (buffer-name (buffer-base-buffer)))))))
13820 (org-map-continue-from nil)
13821 lspos tags tags-list
13822 (tags-alist (list (cons 0 org-file-tags)))
13823 (llast 0) rtn rtn1 level category i txt
13824 todo marker entry priority
13825 ts-date ts-date-type ts-date-pair)
13826 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13827 (setq action (list 'lambda nil action)))
13828 (save-excursion
13829 (goto-char (point-min))
13830 (when (eq action 'sparse-tree)
13831 (org-overview)
13832 (org-remove-occur-highlights))
13833 (while (let (case-fold-search)
13834 (re-search-forward re nil t))
13835 (setq org-map-continue-from nil)
13836 (catch :skip
13837 (setq todo
13838 ;; TODO: is the 1-2 difference a bug?
13839 (when (match-end 1) (match-string-no-properties 2))
13840 tags (when (match-end 4) (match-string-no-properties 4)))
13841 (goto-char (setq lspos (match-beginning 0)))
13842 (setq level (org-reduced-level (org-outline-level))
13843 category (org-get-category))
13844 (when (eq action 'agenda)
13845 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13846 ts-date (car ts-date-pair)
13847 ts-date-type (cdr ts-date-pair)))
13848 (setq i llast llast level)
13849 ;; remove tag lists from same and sublevels
13850 (while (>= i level)
13851 (when (setq entry (assoc i tags-alist))
13852 (setq tags-alist (delete entry tags-alist)))
13853 (setq i (1- i)))
13854 ;; add the next tags
13855 (when tags
13856 (setq tags (org-split-string tags ":")
13857 tags-alist
13858 (cons (cons level tags) tags-alist)))
13859 ;; compile tags for current headline
13860 (setq tags-list
13861 (if org-use-tag-inheritance
13862 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13863 tags)
13864 org-scanner-tags tags-list)
13865 (when org-use-tag-inheritance
13866 (setcdr (car tags-alist)
13867 (mapcar (lambda (x)
13868 (setq x (copy-sequence x))
13869 (org-add-prop-inherited x))
13870 (cdar tags-alist))))
13871 (when (and tags org-use-tag-inheritance
13872 (or (not (eq t org-use-tag-inheritance))
13873 org-tags-exclude-from-inheritance))
13874 ;; Selective inheritance, remove uninherited ones.
13875 (setcdr (car tags-alist)
13876 (org-remove-uninherited-tags (cdar tags-alist))))
13877 (when (and
13879 ;; eval matcher only when the todo condition is OK
13880 (and (or (not todo-only) (member todo org-todo-keywords-1))
13881 (if (functionp matcher)
13882 (let ((case-fold-search t) (org-trust-scanner-tags t))
13883 (funcall matcher todo tags-list level))
13884 matcher))
13886 ;; Call the skipper, but return t if it does not
13887 ;; skip, so that the `and' form continues evaluating.
13888 (progn
13889 (unless (eq action 'sparse-tree) (org-agenda-skip))
13892 ;; Check if timestamps are deselecting this entry
13893 (or (not todo-only)
13894 (and (member todo org-todo-keywords-1)
13895 (or (not org-agenda-tags-todo-honor-ignore-options)
13896 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13898 ;; select this headline
13899 (cond
13900 ((eq action 'sparse-tree)
13901 (and org-highlight-sparse-tree-matches
13902 (org-get-heading) (match-end 0)
13903 (org-highlight-new-match
13904 (match-beginning 1) (match-end 1)))
13905 (org-show-context 'tags-tree))
13906 ((eq action 'agenda)
13907 (setq txt (org-agenda-format-item
13909 (concat
13910 (if (eq org-tags-match-list-sublevels 'indented)
13911 (make-string (1- level) ?.) "")
13912 (org-get-heading))
13913 (make-string level ?\s)
13914 category
13915 tags-list)
13916 priority (org-get-priority txt))
13917 (goto-char lspos)
13918 (setq marker (org-agenda-new-marker))
13919 (org-add-props txt props
13920 'org-marker marker 'org-hd-marker marker 'org-category category
13921 'todo-state todo
13922 'ts-date ts-date
13923 'priority priority
13924 'type (concat "tagsmatch" ts-date-type))
13925 (push txt rtn))
13926 ((functionp action)
13927 (setq org-map-continue-from nil)
13928 (save-excursion
13929 (setq rtn1 (funcall action))
13930 (push rtn1 rtn)))
13931 (t (user-error "Invalid action")))
13933 ;; if we are to skip sublevels, jump to end of subtree
13934 (unless org-tags-match-list-sublevels
13935 (org-end-of-subtree t)
13936 (backward-char 1))))
13937 ;; Get the correct position from where to continue
13938 (if org-map-continue-from
13939 (goto-char org-map-continue-from)
13940 (and (= (point) lspos) (end-of-line 1)))))
13941 (when (and (eq action 'sparse-tree)
13942 (not org-sparse-tree-open-archived-trees))
13943 (org-hide-archived-subtrees (point-min) (point-max)))
13944 (nreverse rtn)))
13946 (defun org-remove-uninherited-tags (tags)
13947 "Remove all tags that are not inherited from the list TAGS."
13948 (cond
13949 ((eq org-use-tag-inheritance t)
13950 (if org-tags-exclude-from-inheritance
13951 (org-delete-all org-tags-exclude-from-inheritance tags)
13952 tags))
13953 ((not org-use-tag-inheritance) nil)
13954 ((stringp org-use-tag-inheritance)
13955 (delq nil (mapcar
13956 (lambda (x)
13957 (if (and (string-match org-use-tag-inheritance x)
13958 (not (member x org-tags-exclude-from-inheritance)))
13959 x nil))
13960 tags)))
13961 ((listp org-use-tag-inheritance)
13962 (delq nil (mapcar
13963 (lambda (x)
13964 (if (member x org-use-tag-inheritance) x nil))
13965 tags)))))
13967 (defun org-match-sparse-tree (&optional todo-only match)
13968 "Create a sparse tree according to tags string MATCH.
13970 MATCH is a string with match syntax. It can contain a selection
13971 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13972 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13973 those. See the manual for details.
13975 If optional argument TODO-ONLY is non-nil, only select lines that
13976 are also TODO tasks."
13977 (interactive "P")
13978 (org-agenda-prepare-buffers (list (current-buffer)))
13979 (let ((org--matcher-tags-todo-only todo-only))
13980 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13981 org--matcher-tags-todo-only)))
13983 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13985 (defvar org-cached-props nil)
13986 (defun org-cached-entry-get (pom property)
13987 (if (or (eq t org-use-property-inheritance)
13988 (and (stringp org-use-property-inheritance)
13989 (let ((case-fold-search t))
13990 (string-match-p org-use-property-inheritance property)))
13991 (and (listp org-use-property-inheritance)
13992 (member-ignore-case property org-use-property-inheritance)))
13993 ;; Caching is not possible, check it directly.
13994 (org-entry-get pom property 'inherit)
13995 ;; Get all properties, so we can do complicated checks easily.
13996 (cdr (assoc-string property
13997 (or org-cached-props
13998 (setq org-cached-props (org-entry-properties pom)))
13999 t))))
14001 (defun org-global-tags-completion-table (&optional files)
14002 "Return the list of all tags in all agenda buffer/files.
14003 Optional FILES argument is a list of files which can be used
14004 instead of the agenda files."
14005 (save-excursion
14006 (org-uniquify
14007 (delq nil
14008 (apply #'append
14009 (mapcar
14010 (lambda (file)
14011 (set-buffer (find-file-noselect file))
14012 (mapcar (lambda (x)
14013 (and (stringp (car-safe x))
14014 (list (car-safe x))))
14015 (or org-current-tag-alist (org-get-buffer-tags))))
14016 (if (car-safe files) files
14017 (org-agenda-files))))))))
14019 (defun org-make-tags-matcher (match)
14020 "Create the TAGS/TODO matcher form for the selection string MATCH.
14022 Returns a cons of the selection string MATCH and a function
14023 implementing the matcher.
14025 The matcher is to be called at an Org entry, with point on the
14026 headline, and returns non-nil if the entry matches the selection
14027 string MATCH. It must be called with three arguments: the TODO
14028 keyword at the entry (or nil if none), the list of all tags at
14029 the entry including inherited ones and the reduced level of the
14030 headline. Additionally, the category of the entry, if any, must
14031 be specified as the text property `org-category' on the headline.
14033 This function sets the variable `org--matcher-tags-todo-only' to
14034 a non-nil value if the matcher restricts matching to TODO
14035 entries, otherwise it is not touched.
14037 See also `org-scan-tags'."
14038 (unless match
14039 ;; Get a new match request, with completion against the global
14040 ;; tags table and the local tags in current buffer.
14041 (let ((org-last-tags-completion-table
14042 (org-uniquify
14043 (delq nil (append (org-get-buffer-tags)
14044 (org-global-tags-completion-table))))))
14045 (setq match
14046 (completing-read
14047 "Match: "
14048 'org-tags-completion-function nil nil nil 'org-tags-history))))
14050 (let ((match0 match)
14051 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14052 (start 0)
14053 tagsmatch todomatch tagsmatcher todomatcher)
14055 ;; Expand group tags.
14056 (setq match (org-tags-expand match))
14058 ;; Check if there is a TODO part of this match, which would be the
14059 ;; part after a "/". To make sure that this slash is not part of
14060 ;; a property value to be matched against, we also check that
14061 ;; there is no / after that slash. First, find the last slash.
14062 (let ((s 0))
14063 (while (string-match "/+" match s)
14064 (setq start (match-beginning 0))
14065 (setq s (match-end 0))))
14066 (if (and (string-match "/+" match start)
14067 (not (string-match-p "\"" match start)))
14068 ;; Match contains also a TODO-matching request.
14069 (progn
14070 (setq tagsmatch (substring match 0 (match-beginning 0)))
14071 (setq todomatch (substring match (match-end 0)))
14072 (when (string-prefix-p "!" todomatch)
14073 (setq org--matcher-tags-todo-only t)
14074 (setq todomatch (substring todomatch 1)))
14075 (when (string-match "\\`\\s-*\\'" todomatch)
14076 (setq todomatch nil)))
14077 ;; Only matching tags.
14078 (setq tagsmatch match)
14079 (setq todomatch nil))
14081 ;; Make the tags matcher.
14082 (when (org-string-nw-p tagsmatch)
14083 (let ((orlist nil)
14084 (orterms (org-split-string tagsmatch "|"))
14085 term)
14086 (while (setq term (pop orterms))
14087 (while (and (equal (substring term -1) "\\") orterms)
14088 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14089 (while (string-match re term)
14090 (let* ((rest (substring term (match-end 0)))
14091 (minus (and (match-end 1)
14092 (equal (match-string 1 term) "-")))
14093 (tag (save-match-data
14094 (replace-regexp-in-string
14095 "\\\\-" "-" (match-string 2 term))))
14096 (regexp (eq (string-to-char tag) ?{))
14097 (levelp (match-end 4))
14098 (propp (match-end 5))
14100 (cond
14101 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14102 (levelp
14103 `(,(org-op-to-function (match-string 3 term))
14104 level
14105 ,(string-to-number (match-string 4 term))))
14106 (propp
14107 (let* ((gv (pcase (upcase (match-string 5 term))
14108 ("CATEGORY"
14109 '(get-text-property (point) 'org-category))
14110 ("TODO" 'todo)
14111 (p `(org-cached-entry-get nil ,p))))
14112 (pv (match-string 7 term))
14113 (regexp (eq (string-to-char pv) ?{))
14114 (strp (eq (string-to-char pv) ?\"))
14115 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14116 (po (org-op-to-function (match-string 6 term)
14117 (if timep 'time strp))))
14118 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14119 (when timep (setq pv (org-matcher-time pv)))
14120 (cond ((and regexp (eq po 'org<>))
14121 `(not (string-match ,pv (or ,gv ""))))
14122 (regexp `(string-match ,pv (or ,gv "")))
14123 (strp `(,po (or ,gv "") ,pv))
14125 `(,po
14126 (string-to-number (or ,gv ""))
14127 ,(string-to-number pv))))))
14128 (t `(member ,tag tags-list)))))
14129 (push (if minus `(not ,mm) mm) tagsmatcher)
14130 (setq term rest)))
14131 (push `(and ,@tagsmatcher) orlist)
14132 (setq tagsmatcher nil))
14133 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14135 ;; Make the TODO matcher.
14136 (when (org-string-nw-p todomatch)
14137 (let ((orlist nil))
14138 (dolist (term (org-split-string todomatch "|"))
14139 (while (string-match re term)
14140 (let* ((minus (and (match-end 1)
14141 (equal (match-string 1 term) "-")))
14142 (kwd (match-string 2 term))
14143 (regexp (eq (string-to-char kwd) ?{))
14144 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14145 `(equal todo ,kwd))))
14146 (push (if minus `(not ,mm) mm) todomatcher))
14147 (setq term (substring term (match-end 0))))
14148 (push (if (> (length todomatcher) 1)
14149 (cons 'and todomatcher)
14150 (car todomatcher))
14151 orlist)
14152 (setq todomatcher nil))
14153 (setq todomatcher (cons 'or orlist))))
14155 ;; Return the string and function of the matcher. If no
14156 ;; tags-specific or todo-specific matcher exists, match
14157 ;; everything.
14158 (let ((matcher (if (and tagsmatcher todomatcher)
14159 `(and ,tagsmatcher ,todomatcher)
14160 (or tagsmatcher todomatcher t))))
14161 (when org--matcher-tags-todo-only
14162 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14163 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14165 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14166 "Expand group tags in MATCH.
14168 This replaces every group tag in MATCH with a regexp tag search.
14169 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14170 will be replaced like this:
14172 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14173 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14174 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14176 Replacing by a regexp preserves the structure of the match.
14177 E.g., this expansion
14179 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14181 will match anything tagged with \"Lab\" and \"Home\", or tagged
14182 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14184 A group tag in MATCH can contain regular expressions of its own.
14185 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14186 will be replaced like this:
14188 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14190 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14191 assumed to be a single group tag, and the function will return
14192 the list of tags in this group.
14194 When DOWNCASE is non-nil, expand downcased TAGS."
14195 (if org-group-tags
14196 (let* ((case-fold-search t)
14197 (stable org-mode-syntax-table)
14198 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14199 (taggroups (if downcased
14200 (mapcar (lambda (tg) (mapcar #'downcase tg))
14201 taggroups)
14202 taggroups))
14203 (taggroups-keys (mapcar #'car taggroups))
14204 (return-match (if downcased (downcase match) match))
14205 (count 0)
14206 (work-already-expanded tags-already-expanded)
14207 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14208 ;; @ and _ are allowed as word-components in tags.
14209 (modify-syntax-entry ?@ "w" stable)
14210 (modify-syntax-entry ?_ "w" stable)
14211 ;; Temporarily replace regexp-expressions in the match-expression.
14212 (while (string-match "{.+?}" return-match)
14213 (cl-incf count)
14214 (push (match-string 0 return-match) regexps-in-match)
14215 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14216 (while (and taggroups-keys
14217 (with-syntax-table stable
14218 (string-match
14219 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14220 (regexp-opt taggroups-keys) "\\>\\)")
14221 return-match)))
14222 (let* ((dir (match-string 1 return-match))
14223 (tag (match-string 2 return-match))
14224 (tag (if downcased (downcase tag) tag)))
14225 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14226 (member tag work-already-expanded))
14227 (setq tags-in-group (assoc tag taggroups))
14228 (push tag work-already-expanded)
14229 ;; Recursively expand each tag in the group, if the tag hasn't
14230 ;; already been expanded. Restore the match-data after all recursive calls.
14231 (save-match-data
14232 (let (tags-expanded)
14233 (dolist (x (cdr tags-in-group))
14234 (if (and (member x taggroups-keys)
14235 (not (member x work-already-expanded)))
14236 (setq tags-expanded
14237 (delete-dups
14238 (append
14239 (org-tags-expand x t downcased
14240 work-already-expanded)
14241 tags-expanded)))
14242 (setq tags-expanded
14243 (append (list x) tags-expanded)))
14244 (setq work-already-expanded
14245 (delete-dups
14246 (append tags-expanded
14247 work-already-expanded))))
14248 (setq tags-in-group
14249 (delete-dups (cons (car tags-in-group)
14250 tags-expanded)))))
14251 ;; Filter tag-regexps from tags.
14252 (setq regexp-in-group-escaped
14253 (delq nil (mapcar (lambda (x)
14254 (if (stringp x)
14255 (and (equal "{" (substring x 0 1))
14256 (equal "}" (substring x -1))
14259 tags-in-group))
14260 regexp-in-group
14261 (mapcar (lambda (x)
14262 (substring x 1 -1))
14263 regexp-in-group-escaped)
14264 tags-in-group
14265 (delq nil (mapcar (lambda (x)
14266 (if (stringp x)
14267 (and (not (equal "{" (substring x 0 1)))
14268 (not (equal "}" (substring x -1)))
14271 tags-in-group)))
14272 ;; If single-as-list, do no more in the while-loop.
14273 (if (not single-as-list)
14274 (progn
14275 (when regexp-in-group
14276 (setq regexp-in-group
14277 (concat "\\|"
14278 (mapconcat 'identity regexp-in-group
14279 "\\|"))))
14280 (setq tags-in-group
14281 (concat dir
14282 "{\\<"
14283 (regexp-opt tags-in-group)
14284 "\\>"
14285 regexp-in-group
14286 "}"))
14287 (when (stringp tags-in-group)
14288 (org-add-props tags-in-group '(grouptag t)))
14289 (setq return-match
14290 (replace-match tags-in-group t t return-match)))
14291 (setq tags-in-group
14292 (append regexp-in-group-escaped tags-in-group))))
14293 (setq taggroups-keys (delete tag taggroups-keys))))
14294 ;; Add the regular expressions back into the match-expression again.
14295 (while regexps-in-match
14296 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14297 (pop regexps-in-match)
14298 return-match t t))
14299 (cl-decf count))
14300 (if single-as-list
14301 (if tags-in-group tags-in-group (list return-match))
14302 return-match))
14303 (if single-as-list
14304 (list (if downcased (downcase match) match))
14305 match)))
14307 (defun org-op-to-function (op &optional stringp)
14308 "Turn an operator into the appropriate function."
14309 (setq op
14310 (cond
14311 ((equal op "<" ) '(< string< org-time<))
14312 ((equal op ">" ) '(> org-string> org-time>))
14313 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14314 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14315 ((member op '("=" "==")) '(= string= org-time=))
14316 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14317 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14319 (defun org<> (a b) (not (= a b)))
14320 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14321 (defun org-string>= (a b) (not (string< a b)))
14322 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14323 (defun org-string<> (a b) (not (string= a b)))
14324 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14325 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14326 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14327 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14328 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14329 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14330 (defun org-2ft (s)
14331 "Convert S to a floating point time.
14332 If S is already a number, just return it. If it is a string, parse
14333 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14334 (cond
14335 ((numberp s) s)
14336 ((stringp s)
14337 (condition-case nil
14338 (float-time (apply #'encode-time (org-parse-time-string s)))
14339 (error 0.)))
14340 (t 0.)))
14342 (defun org-time-today ()
14343 "Time in seconds today at 0:00.
14344 Returns the float number of seconds since the beginning of the
14345 epoch to the beginning of today (00:00)."
14346 (float-time (apply 'encode-time
14347 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14349 (defun org-matcher-time (s)
14350 "Interpret a time comparison value."
14351 (save-match-data
14352 (cond
14353 ((string= s "<now>") (float-time))
14354 ((string= s "<today>") (org-time-today))
14355 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14356 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14357 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14358 (+ (org-time-today)
14359 (* (string-to-number (match-string 1 s))
14360 (cdr (assoc (match-string 2 s)
14361 '(("d" . 86400.0) ("w" . 604800.0)
14362 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14363 (t (org-2ft s)))))
14365 (defun org-match-any-p (re list)
14366 "Does re match any element of list?"
14367 (setq list (mapcar (lambda (x) (string-match re x)) list))
14368 (delq nil list))
14370 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14371 (defvar org-tags-overlay (make-overlay 1 1))
14372 (delete-overlay org-tags-overlay)
14374 (defun org-get-local-tags-at (&optional pos)
14375 "Get a list of tags defined in the current headline."
14376 (org-get-tags-at pos 'local))
14378 (defun org-get-local-tags ()
14379 "Get a list of tags defined in the current headline."
14380 (org-get-tags-at nil 'local))
14382 (defun org-get-tags-at (&optional pos local)
14383 "Get a list of all headline tags applicable at POS.
14384 POS defaults to point. If tags are inherited, the list contains
14385 the targets in the same sequence as the headlines appear, i.e.
14386 the tags of the current headline come last.
14387 When LOCAL is non-nil, only return tags from the current headline,
14388 ignore inherited ones."
14389 (interactive)
14390 (if (and org-trust-scanner-tags
14391 (or (not pos) (equal pos (point)))
14392 (not local))
14393 org-scanner-tags
14394 (let (tags ltags lastpos parent)
14395 (save-excursion
14396 (save-restriction
14397 (widen)
14398 (goto-char (or pos (point)))
14399 (save-match-data
14400 (catch 'done
14401 (condition-case nil
14402 (progn
14403 (org-back-to-heading t)
14404 (while (not (equal lastpos (point)))
14405 (setq lastpos (point))
14406 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14407 (setq ltags (org-split-string
14408 (match-string-no-properties 1) ":"))
14409 (when parent
14410 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14411 (setq tags (append
14412 (if parent
14413 (org-remove-uninherited-tags ltags)
14414 ltags)
14415 tags)))
14416 (or org-use-tag-inheritance (throw 'done t))
14417 (when local (throw 'done t))
14418 (or (org-up-heading-safe) (error nil))
14419 (setq parent t)))
14420 (error nil)))))
14421 (if local
14422 tags
14423 (reverse (delete-dups
14424 (reverse (append
14425 (org-remove-uninherited-tags
14426 org-file-tags)
14427 tags)))))))))
14429 (defun org-add-prop-inherited (s)
14430 (add-text-properties 0 (length s) '(inherited t) s)
14433 (defun org-toggle-tag (tag &optional onoff)
14434 "Toggle the tag TAG for the current line.
14435 If ONOFF is `on' or `off', don't toggle but set to this state."
14436 (save-excursion
14437 (org-back-to-heading t)
14438 (let ((current
14439 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14440 (line-end-position) t)
14441 (let ((tags (match-string 1)))
14442 ;; Clear current tags.
14443 (replace-match "")
14444 ;; Reverse the tags list so any new tag is appended to
14445 ;; the current list of tags.
14446 (nreverse (org-split-string tags ":")))))
14447 res)
14448 (pcase onoff
14449 (`off (setq current (delete tag current)))
14450 ((or `on (guard (not (member tag current))))
14451 (setq res t)
14452 (cl-pushnew tag current :test #'equal))
14453 (_ (setq current (delete tag current))))
14454 (end-of-line)
14455 (if current
14456 (progn
14457 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14458 (org-set-tags nil t))
14459 (delete-horizontal-space))
14460 (run-hooks 'org-after-tags-change-hook)
14461 res)))
14463 (defun org--align-tags-here (to-col)
14464 "Align tags on the current headline to TO-COL.
14465 Assume point is on a headline."
14466 (let ((pos (point)))
14467 (beginning-of-line)
14468 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14469 (>= pos (match-beginning 2)))
14470 ;; No tags or point within tags: do not align.
14471 (goto-char pos)
14472 (goto-char (match-beginning 1))
14473 (let ((shift (max (- (if (>= to-col 0) to-col
14474 (- (abs to-col) (string-width (match-string 2))))
14475 (current-column))
14476 1)))
14477 (replace-match (make-string shift ?\s) nil nil nil 1)
14478 ;; Preserve initial position, if possible. In any case, stop
14479 ;; before tags.
14480 (when (< pos (point)) (goto-char pos))))))
14482 (defun org-set-tags-command (&optional arg just-align)
14483 "Call the set-tags command for the current entry."
14484 (interactive "P")
14485 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14486 (org-set-tags arg just-align)
14487 (save-excursion
14488 (unless (and (org-region-active-p)
14489 org-loop-over-headlines-in-active-region)
14490 (org-back-to-heading t))
14491 (org-set-tags arg just-align))))
14493 (defun org-set-tags-to (data)
14494 "Set the tags of the current entry to DATA, replacing the current tags.
14495 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14496 If DATA is nil or the empty string, any tags will be removed."
14497 (interactive "sTags: ")
14498 (setq data
14499 (cond
14500 ((eq data nil) "")
14501 ((equal data "") "")
14502 ((stringp data)
14503 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14504 ":"))
14505 ((listp data)
14506 (concat ":" (mapconcat 'identity data ":") ":"))))
14507 (when data
14508 (save-excursion
14509 (org-back-to-heading t)
14510 (when (let ((case-fold-search nil))
14511 (looking-at org-complex-heading-regexp))
14512 (if (match-end 5)
14513 (progn
14514 (goto-char (match-beginning 5))
14515 (insert data)
14516 (delete-region (point) (point-at-eol))
14517 (org-set-tags nil 'align))
14518 (goto-char (point-at-eol))
14519 (insert " " data)
14520 (org-set-tags nil 'align)))
14521 (beginning-of-line 1)
14522 (when (looking-at ".*?\\([ \t]+\\)$")
14523 (delete-region (match-beginning 1) (match-end 1))))))
14525 (defun org-align-all-tags ()
14526 "Align the tags in all headings."
14527 (interactive)
14528 (save-excursion
14529 (or (ignore-errors (org-back-to-heading t))
14530 (outline-next-heading))
14531 (if (org-at-heading-p)
14532 (org-set-tags t)
14533 (message "No headings"))))
14535 (defvar org-indent-indentation-per-level)
14536 (defun org-set-tags (&optional arg just-align)
14537 "Set the tags for the current headline.
14538 With prefix ARG, realign all tags in headings in the current buffer.
14539 When JUST-ALIGN is non-nil, only align tags."
14540 (interactive "P")
14541 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14542 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14543 'region-start-level
14544 'region))
14545 org-loop-over-headlines-in-active-region)
14546 (org-map-entries
14547 ;; We don't use ARG and JUST-ALIGN here because these args
14548 ;; are not useful when looping over headlines.
14549 #'org-set-tags
14550 org-loop-over-headlines-in-active-region
14552 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14553 (let ((org-setting-tags t))
14554 (if arg
14555 (save-excursion
14556 (goto-char (point-min))
14557 (while (re-search-forward org-outline-regexp-bol nil t)
14558 (org-set-tags nil t)
14559 (end-of-line))
14560 (message "All tags realigned to column %d" org-tags-column))
14561 (let* ((current (org-get-tags-string))
14562 (tags
14563 (if just-align current
14564 ;; Get a new set of tags from the user.
14565 (save-excursion
14566 (let* ((seen)
14567 (table
14568 (setq
14569 org-last-tags-completion-table
14570 ;; Uniquify tags in alists, yet preserve
14571 ;; structure (i.e., keywords).
14572 (delq nil
14573 (mapcar
14574 (lambda (pair)
14575 (let ((head (car pair)))
14576 (cond ((symbolp head) pair)
14577 ((member head seen) nil)
14578 (t (push head seen)
14579 pair))))
14580 (append
14581 (or org-current-tag-alist
14582 (org-get-buffer-tags))
14583 (and
14584 org-complete-tags-always-offer-all-agenda-tags
14585 (org-global-tags-completion-table
14586 (org-agenda-files))))))))
14587 (current-tags (org-split-string current ":"))
14588 (inherited-tags
14589 (nreverse (nthcdr (length current-tags)
14590 (nreverse (org-get-tags-at))))))
14591 (replace-regexp-in-string
14592 "\\([-+&]+\\|,\\)"
14594 (if (or (eq t org-use-fast-tag-selection)
14595 (and org-use-fast-tag-selection
14596 (delq nil (mapcar #'cdr table))))
14597 (org-fast-tag-selection
14598 current-tags inherited-tags table
14599 (and org-fast-tag-selection-include-todo
14600 org-todo-key-alist))
14601 (let ((org-add-colon-after-tag-completion
14602 (< 1 (length table))))
14603 (org-trim
14604 (completing-read
14605 "Tags: "
14606 #'org-tags-completion-function
14607 nil nil current 'org-tags-history))))))))))
14609 (when org-tags-sort-function
14610 (setq tags
14611 (mapconcat
14612 #'identity
14613 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14614 org-tags-sort-function)
14615 ":")))
14617 (if (or (string= ":" tags)
14618 (string= "::" tags))
14619 (setq tags ""))
14620 (if (not (org-string-nw-p tags)) (setq tags "")
14621 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14622 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14624 ;; Insert new tags at the correct column.
14625 (unless (equal current tags)
14626 (save-excursion
14627 (beginning-of-line)
14628 (let ((case-fold-search nil))
14629 (looking-at org-complex-heading-regexp))
14630 ;; Remove current tags, if any.
14631 (when (match-end 5) (replace-match "" nil nil nil 5))
14632 ;; Insert new tags, if any. Otherwise, remove trailing
14633 ;; white spaces.
14634 (end-of-line)
14635 (if (not (equal tags ""))
14636 ;; When text is being inserted on an invisible
14637 ;; region boundary, it can be inadvertently sucked
14638 ;; into invisibility.
14639 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14640 (skip-chars-backward " \t")
14641 (delete-region (point) (line-end-position)))))
14642 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14643 ;; is on.
14644 (unless (equal tags "")
14645 (let* ((level (save-excursion
14646 (beginning-of-line)
14647 (skip-chars-forward "\\*")))
14648 (offset (if (bound-and-true-p org-indent-mode)
14649 (* (1- org-indent-indentation-per-level)
14650 (1- level))
14652 (tags-column
14653 (+ org-tags-column
14654 (if (> org-tags-column 0) (- offset) offset))))
14655 (org--align-tags-here tags-column))))
14656 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14658 (defun org-change-tag-in-region (beg end tag off)
14659 "Add or remove TAG for each entry in the region.
14660 This works in the agenda, and also in an Org buffer."
14661 (interactive
14662 (list (region-beginning) (region-end)
14663 (let ((org-last-tags-completion-table
14664 (if (derived-mode-p 'org-mode)
14665 (org-uniquify
14666 (delq nil (append (org-get-buffer-tags)
14667 (org-global-tags-completion-table))))
14668 (org-global-tags-completion-table))))
14669 (completing-read
14670 "Tag: " 'org-tags-completion-function nil nil nil
14671 'org-tags-history))
14672 (progn
14673 (message "[s]et or [r]emove? ")
14674 (equal (read-char-exclusive) ?r))))
14675 (when (fboundp 'deactivate-mark) (deactivate-mark))
14676 (let ((agendap (equal major-mode 'org-agenda-mode))
14677 l1 l2 m buf pos newhead (cnt 0))
14678 (goto-char end)
14679 (setq l2 (1- (org-current-line)))
14680 (goto-char beg)
14681 (setq l1 (org-current-line))
14682 (cl-loop for l from l1 to l2 do
14683 (org-goto-line l)
14684 (setq m (get-text-property (point) 'org-hd-marker))
14685 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14686 (and agendap m))
14687 (setq buf (if agendap (marker-buffer m) (current-buffer))
14688 pos (if agendap m (point)))
14689 (with-current-buffer buf
14690 (save-excursion
14691 (save-restriction
14692 (goto-char pos)
14693 (setq cnt (1+ cnt))
14694 (org-toggle-tag tag (if off 'off 'on))
14695 (setq newhead (org-get-heading)))))
14696 (and agendap (org-agenda-change-all-lines newhead m))))
14697 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14699 (defun org-tags-completion-function (string _predicate &optional flag)
14700 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14701 (confirm (lambda (x) (stringp (car x)))))
14702 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14703 (setq s1 (match-string 1 string)
14704 s2 (match-string 2 string))
14705 (setq s1 "" s2 string))
14706 (cond
14707 ((eq flag nil)
14708 ;; try completion
14709 (setq rtn (try-completion s2 ctable confirm))
14710 (when (stringp rtn)
14711 (setq rtn
14712 (concat s1 s2 (substring rtn (length s2))
14713 (if (and org-add-colon-after-tag-completion
14714 (assoc rtn ctable))
14715 ":" ""))))
14716 rtn)
14717 ((eq flag t)
14718 ;; all-completions
14719 (all-completions s2 ctable confirm))
14720 ((eq flag 'lambda)
14721 ;; exact match?
14722 (assoc s2 ctable)))))
14724 (defun org-fast-tag-insert (kwd tags face &optional end)
14725 "Insert KDW, and the TAGS, the latter with face FACE.
14726 Also insert END."
14727 (insert (format "%-12s" (concat kwd ":"))
14728 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14729 (or end "")))
14731 (defun org-fast-tag-show-exit (flag)
14732 (save-excursion
14733 (org-goto-line 3)
14734 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14735 (replace-match ""))
14736 (when flag
14737 (end-of-line 1)
14738 (org-move-to-column (- (window-width) 19) t)
14739 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14741 (defun org-set-current-tags-overlay (current prefix)
14742 "Add an overlay to CURRENT tag with PREFIX."
14743 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14744 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14745 (org-overlay-display org-tags-overlay (concat prefix s))))
14747 (defvar org-last-tag-selection-key nil)
14748 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14749 "Fast tag selection with single keys.
14750 CURRENT is the current list of tags in the headline, INHERITED is the
14751 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14752 possibly with grouping information. TODO-TABLE is a similar table with
14753 TODO keywords, should these have keys assigned to them.
14754 If the keys are nil, a-z are automatically assigned.
14755 Returns the new tags string, or nil to not change the current settings."
14756 (let* ((fulltable (append table todo-table))
14757 (maxlen (apply 'max (mapcar
14758 (lambda (x)
14759 (if (stringp (car x)) (string-width (car x)) 0))
14760 fulltable)))
14761 (buf (current-buffer))
14762 (expert (eq org-fast-tag-selection-single-key 'expert))
14763 (buffer-tags nil)
14764 (fwidth (+ maxlen 3 1 3))
14765 (ncol (/ (- (window-width) 4) fwidth))
14766 (i-face 'org-done)
14767 (c-face 'org-todo)
14768 tg cnt e c char c1 c2 ntable tbl rtn
14769 ov-start ov-end ov-prefix
14770 (exit-after-next org-fast-tag-selection-single-key)
14771 (done-keywords org-done-keywords)
14772 groups ingroup intaggroup)
14773 (save-excursion
14774 (beginning-of-line 1)
14775 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14776 (setq ov-start (match-beginning 1)
14777 ov-end (match-end 1)
14778 ov-prefix "")
14779 (setq ov-start (1- (point-at-eol))
14780 ov-end (1+ ov-start))
14781 (skip-chars-forward "^\n\r")
14782 (setq ov-prefix
14783 (concat
14784 (buffer-substring (1- (point)) (point))
14785 (if (> (current-column) org-tags-column)
14787 (make-string (- org-tags-column (current-column)) ?\ ))))))
14788 (move-overlay org-tags-overlay ov-start ov-end)
14789 (save-window-excursion
14790 (if expert
14791 (set-buffer (get-buffer-create " *Org tags*"))
14792 (delete-other-windows)
14793 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14794 (org-switch-to-buffer-other-window " *Org tags*"))
14795 (erase-buffer)
14796 (setq-local org-done-keywords done-keywords)
14797 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14798 (org-fast-tag-insert "Current" current c-face "\n\n")
14799 (org-fast-tag-show-exit exit-after-next)
14800 (org-set-current-tags-overlay current ov-prefix)
14801 (setq tbl fulltable char ?a cnt 0)
14802 (while (setq e (pop tbl))
14803 (cond
14804 ((eq (car e) :startgroup)
14805 (push '() groups) (setq ingroup t)
14806 (unless (zerop cnt)
14807 (setq cnt 0)
14808 (insert "\n"))
14809 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14810 ((eq (car e) :endgroup)
14811 (setq ingroup nil cnt 0)
14812 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14813 ((eq (car e) :startgrouptag)
14814 (setq intaggroup t)
14815 (unless (zerop cnt)
14816 (setq cnt 0)
14817 (insert "\n"))
14818 (insert "[ "))
14819 ((eq (car e) :endgrouptag)
14820 (setq intaggroup nil cnt 0)
14821 (insert "]\n"))
14822 ((equal e '(:newline))
14823 (unless (zerop cnt)
14824 (setq cnt 0)
14825 (insert "\n")
14826 (setq e (car tbl))
14827 (while (equal (car tbl) '(:newline))
14828 (insert "\n")
14829 (setq tbl (cdr tbl)))))
14830 ((equal e '(:grouptags)) (insert " : "))
14832 (setq tg (copy-sequence (car e)) c2 nil)
14833 (if (cdr e)
14834 (setq c (cdr e))
14835 ;; automatically assign a character.
14836 (setq c1 (string-to-char
14837 (downcase (substring
14838 tg (if (= (string-to-char tg) ?@) 1 0)))))
14839 (if (or (rassoc c1 ntable) (rassoc c1 table))
14840 (while (or (rassoc char ntable) (rassoc char table))
14841 (setq char (1+ char)))
14842 (setq c2 c1))
14843 (setq c (or c2 char)))
14844 (when ingroup (push tg (car groups)))
14845 (setq tg (org-add-props tg nil 'face
14846 (cond
14847 ((not (assoc tg table))
14848 (org-get-todo-face tg))
14849 ((member tg current) c-face)
14850 ((member tg inherited) i-face))))
14851 (when (equal (caar tbl) :grouptags)
14852 (org-add-props tg nil 'face 'org-tag-group))
14853 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14854 (insert "[" c "] " tg (make-string
14855 (- fwidth 4 (length tg)) ?\ ))
14856 (push (cons tg c) ntable)
14857 (when (= (cl-incf cnt) ncol)
14858 (insert "\n")
14859 (when (or ingroup intaggroup) (insert " "))
14860 (setq cnt 0)))))
14861 (setq ntable (nreverse ntable))
14862 (insert "\n")
14863 (goto-char (point-min))
14864 (unless expert (org-fit-window-to-buffer))
14865 (setq rtn
14866 (catch 'exit
14867 (while t
14868 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14869 (if (not groups) "no " "")
14870 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14871 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14872 (setq org-last-tag-selection-key c)
14873 (cond
14874 ((= c ?\r) (throw 'exit t))
14875 ((= c ?!)
14876 (setq groups (not groups))
14877 (goto-char (point-min))
14878 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14879 ((= c ?\C-c)
14880 (if (not expert)
14881 (org-fast-tag-show-exit
14882 (setq exit-after-next (not exit-after-next)))
14883 (setq expert nil)
14884 (delete-other-windows)
14885 (set-window-buffer (split-window-vertically) " *Org tags*")
14886 (org-switch-to-buffer-other-window " *Org tags*")
14887 (org-fit-window-to-buffer)))
14888 ((or (= c ?\C-g)
14889 (and (= c ?q) (not (rassoc c ntable))))
14890 (delete-overlay org-tags-overlay)
14891 (setq quit-flag t))
14892 ((= c ?\ )
14893 (setq current nil)
14894 (when exit-after-next (setq exit-after-next 'now)))
14895 ((= c ?\t)
14896 (condition-case nil
14897 (setq tg (completing-read
14898 "Tag: "
14899 (or buffer-tags
14900 (with-current-buffer buf
14901 (setq buffer-tags
14902 (org-get-buffer-tags))))))
14903 (quit (setq tg "")))
14904 (when (string-match "\\S-" tg)
14905 (cl-pushnew (list tg) buffer-tags :test #'equal)
14906 (if (member tg current)
14907 (setq current (delete tg current))
14908 (push tg current)))
14909 (when exit-after-next (setq exit-after-next 'now)))
14910 ((setq e (rassoc c todo-table) tg (car e))
14911 (with-current-buffer buf
14912 (save-excursion (org-todo tg)))
14913 (when exit-after-next (setq exit-after-next 'now)))
14914 ((setq e (rassoc c ntable) tg (car e))
14915 (if (member tg current)
14916 (setq current (delete tg current))
14917 (cl-loop for g in groups do
14918 (when (member tg g)
14919 (dolist (x g) (setq current (delete x current)))))
14920 (push tg current))
14921 (when exit-after-next (setq exit-after-next 'now))))
14923 ;; Create a sorted list
14924 (setq current
14925 (sort current
14926 (lambda (a b)
14927 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14928 (when (eq exit-after-next 'now) (throw 'exit t))
14929 (goto-char (point-min))
14930 (beginning-of-line 2)
14931 (delete-region (point) (point-at-eol))
14932 (org-fast-tag-insert "Current" current c-face)
14933 (org-set-current-tags-overlay current ov-prefix)
14934 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14935 (setq tg (match-string 1))
14936 (add-text-properties
14937 (match-beginning 1) (match-end 1)
14938 (list 'face
14939 (cond
14940 ((member tg current) c-face)
14941 ((member tg inherited) i-face)
14942 (t (get-text-property (match-beginning 1) 'face))))))
14943 (goto-char (point-min)))))
14944 (delete-overlay org-tags-overlay)
14945 (if rtn
14946 (mapconcat 'identity current ":")
14947 nil))))
14949 (defun org-get-tags-string ()
14950 "Get the TAGS string in the current headline."
14951 (unless (org-at-heading-p t)
14952 (user-error "Not on a heading"))
14953 (save-excursion
14954 (beginning-of-line 1)
14955 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14956 (match-string-no-properties 1)
14957 "")))
14959 (defun org-get-tags ()
14960 "Get the list of tags specified in the current headline."
14961 (org-split-string (org-get-tags-string) ":"))
14963 (defun org-get-buffer-tags ()
14964 "Get a table of all tags used in the buffer, for completion."
14965 (org-with-wide-buffer
14966 (goto-char (point-min))
14967 (let ((tag-re (concat org-outline-regexp-bol
14968 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14969 tags)
14970 (while (re-search-forward tag-re nil t)
14971 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14972 (push tag tags)))
14973 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14975 ;;;; The mapping API
14977 (defvar org-agenda-skip-comment-trees)
14978 (defvar org-agenda-skip-function)
14979 (defun org-map-entries (func &optional match scope &rest skip)
14980 "Call FUNC at each headline selected by MATCH in SCOPE.
14982 FUNC is a function or a lisp form. The function will be called without
14983 arguments, with the cursor positioned at the beginning of the headline.
14984 The return values of all calls to the function will be collected and
14985 returned as a list.
14987 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14988 does not need to preserve point. After evaluation, the cursor will be
14989 moved to the end of the line (presumably of the headline of the
14990 processed entry) and search continues from there. Under some
14991 circumstances, this may not produce the wanted results. For example,
14992 if you have removed (e.g. archived) the current (sub)tree it could
14993 mean that the next entry will be skipped entirely. In such cases, you
14994 can specify the position from where search should continue by making
14995 FUNC set the variable `org-map-continue-from' to the desired buffer
14996 position.
14998 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14999 Only headlines that are matched by this query will be considered during
15000 the iteration. When MATCH is nil or t, all headlines will be
15001 visited by the iteration.
15003 SCOPE determines the scope of this command. It can be any of:
15005 nil The current buffer, respecting the restriction if any
15006 tree The subtree started with the entry at point
15007 region The entries within the active region, if any
15008 region-start-level
15009 The entries within the active region, but only those at
15010 the same level than the first one.
15011 file The current buffer, without restriction
15012 file-with-archives
15013 The current buffer, and any archives associated with it
15014 agenda All agenda files
15015 agenda-with-archives
15016 All agenda files with any archive files associated with them
15017 \(file1 file2 ...)
15018 If this is a list, all files in the list will be scanned
15020 The remaining args are treated as settings for the skipping facilities of
15021 the scanner. The following items can be given here:
15023 archive skip trees with the archive tag
15024 comment skip trees with the COMMENT keyword
15025 function or Emacs Lisp form:
15026 will be used as value for `org-agenda-skip-function', so
15027 whenever the function returns a position, FUNC will not be
15028 called for that entry and search will continue from the
15029 position returned
15031 If your function needs to retrieve the tags including inherited tags
15032 at the *current* entry, you can use the value of the variable
15033 `org-scanner-tags' which will be much faster than getting the value
15034 with `org-get-tags-at'. If your function gets properties with
15035 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15036 to t around the call to `org-entry-properties' to get the same speedup.
15037 Note that if your function moves around to retrieve tags and properties at
15038 a *different* entry, you cannot use these techniques."
15039 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15040 (not (org-region-active-p)))
15041 (let* ((org-agenda-archives-mode nil) ; just to make sure
15042 (org-agenda-skip-archived-trees (memq 'archive skip))
15043 (org-agenda-skip-comment-trees (memq 'comment skip))
15044 (org-agenda-skip-function
15045 (car (org-delete-all '(comment archive) skip)))
15046 (org-tags-match-list-sublevels t)
15047 (start-level (eq scope 'region-start-level))
15048 matcher res
15049 org-todo-keywords-for-agenda
15050 org-done-keywords-for-agenda
15051 org-todo-keyword-alist-for-agenda
15052 org-tag-alist-for-agenda
15053 org--matcher-tags-todo-only)
15055 (cond
15056 ((eq match t) (setq matcher t))
15057 ((eq match nil) (setq matcher t))
15058 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15060 (save-excursion
15061 (save-restriction
15062 (cond ((eq scope 'tree)
15063 (org-back-to-heading t)
15064 (org-narrow-to-subtree)
15065 (setq scope nil))
15066 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15067 (org-region-active-p))
15068 ;; If needed, set start-level to a string like "2"
15069 (when start-level
15070 (save-excursion
15071 (goto-char (region-beginning))
15072 (unless (org-at-heading-p) (outline-next-heading))
15073 (setq start-level (org-current-level))))
15074 (narrow-to-region (region-beginning)
15075 (save-excursion
15076 (goto-char (region-end))
15077 (unless (and (bolp) (org-at-heading-p))
15078 (outline-next-heading))
15079 (point)))
15080 (setq scope nil)))
15082 (if (not scope)
15083 (progn
15084 (org-agenda-prepare-buffers
15085 (and buffer-file-name (list buffer-file-name)))
15086 (setq res
15087 (org-scan-tags
15088 func matcher org--matcher-tags-todo-only start-level)))
15089 ;; Get the right scope
15090 (cond
15091 ((and scope (listp scope) (symbolp (car scope)))
15092 (setq scope (eval scope)))
15093 ((eq scope 'agenda)
15094 (setq scope (org-agenda-files t)))
15095 ((eq scope 'agenda-with-archives)
15096 (setq scope (org-agenda-files t))
15097 (setq scope (org-add-archive-files scope)))
15098 ((eq scope 'file)
15099 (setq scope (and buffer-file-name (list buffer-file-name))))
15100 ((eq scope 'file-with-archives)
15101 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15102 (org-agenda-prepare-buffers scope)
15103 (dolist (file scope)
15104 (with-current-buffer (org-find-base-buffer-visiting file)
15105 (org-with-wide-buffer
15106 (goto-char (point-min))
15107 (setq res
15108 (append
15110 (org-scan-tags
15111 func matcher org--matcher-tags-todo-only)))))))))
15112 res)))
15114 ;;; Properties API
15116 (defconst org-special-properties
15117 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15118 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15119 "The special properties valid in Org mode.
15120 These are properties that are not defined in the property drawer,
15121 but in some other way.")
15123 (defconst org-default-properties
15124 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15125 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15126 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15127 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15128 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15129 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15130 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15131 "Some properties that are used by Org mode for various purposes.
15132 Being in this list makes sure that they are offered for completion.")
15134 (defun org--valid-property-p (property)
15135 "Non nil when string PROPERTY is a valid property name."
15136 (not
15137 (or (equal property "")
15138 (string-match-p "\\s-" property))))
15140 (defun org--update-property-plist (key val props)
15141 "Associate KEY to VAL in alist PROPS.
15142 Modifications are made by side-effect. Return new alist."
15143 (let* ((appending (string= (substring key -1) "+"))
15144 (key (if appending (substring key 0 -1) key))
15145 (old (assoc-string key props t)))
15146 (if (not old) (cons (cons key val) props)
15147 (setcdr old (if appending (concat (cdr old) " " val) val))
15148 props)))
15150 (defun org-get-property-block (&optional beg force)
15151 "Return the (beg . end) range of the body of the property drawer.
15152 BEG is the beginning of the current subtree, or of the part
15153 before the first headline. If it is not given, it will be found.
15154 If the drawer does not exist, create it if FORCE is non-nil, or
15155 return nil."
15156 (org-with-wide-buffer
15157 (when beg (goto-char beg))
15158 (unless (org-before-first-heading-p)
15159 (let ((beg (cond (beg)
15160 ((or (not (featurep 'org-inlinetask))
15161 (org-inlinetask-in-task-p))
15162 (org-back-to-heading t))
15163 (t (org-with-limited-levels (org-back-to-heading t))))))
15164 (forward-line)
15165 (when (looking-at-p org-planning-line-re) (forward-line))
15166 (cond ((looking-at org-property-drawer-re)
15167 (forward-line)
15168 (cons (point) (progn (goto-char (match-end 0))
15169 (line-beginning-position))))
15170 (force
15171 (goto-char beg)
15172 (org-insert-property-drawer)
15173 (let ((pos (save-excursion (search-forward ":END:")
15174 (line-beginning-position))))
15175 (cons pos pos))))))))
15177 (defun org-at-property-p ()
15178 "Non-nil when point is inside a property drawer.
15179 See `org-property-re' for match data, if applicable."
15180 (save-excursion
15181 (beginning-of-line)
15182 (and (looking-at org-property-re)
15183 (let ((property-drawer (save-match-data (org-get-property-block))))
15184 (and property-drawer
15185 (>= (point) (car property-drawer))
15186 (< (point) (cdr property-drawer)))))))
15188 (defun org-property-action ()
15189 "Do an action on properties."
15190 (interactive)
15191 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15192 (let ((c (read-char-exclusive)))
15193 (cl-case c
15194 (?s (call-interactively #'org-set-property))
15195 (?d (call-interactively #'org-delete-property))
15196 (?D (call-interactively #'org-delete-property-globally))
15197 (?c (call-interactively #'org-compute-property-at-point))
15198 (otherwise (user-error "No such property action %c" c)))))
15200 (defun org-inc-effort ()
15201 "Increment the value of the effort property in the current entry."
15202 (interactive)
15203 (org-set-effort nil t))
15205 (defvar org-clock-effort) ; Defined in org-clock.el.
15206 (defvar org-clock-current-task) ; Defined in org-clock.el.
15207 (defun org-set-effort (&optional value increment)
15208 "Set the effort property of the current entry.
15209 With numerical prefix arg, use the nth allowed value, 0 stands for the
15210 10th allowed value.
15212 When INCREMENT is non-nil, set the property to the next allowed value."
15213 (interactive "P")
15214 (when (equal value 0) (setq value 10))
15215 (let* ((completion-ignore-case t)
15216 (prop org-effort-property)
15217 (cur (org-entry-get nil prop))
15218 (allowed (org-property-get-allowed-values nil prop 'table))
15219 (existing (mapcar 'list (org-property-values prop)))
15220 (heading (nth 4 (org-heading-components)))
15222 (val (cond
15223 ((stringp value) value)
15224 ((and allowed (integerp value))
15225 (or (car (nth (1- value) allowed))
15226 (car (org-last allowed))))
15227 ((and allowed increment)
15228 (or (cl-caadr (member (list cur) allowed))
15229 (user-error "Allowed effort values are not set")))
15230 (allowed
15231 (message "Select 1-9,0, [RET%s]: %s"
15232 (if cur (concat "=" cur) "")
15233 (mapconcat 'car allowed " "))
15234 (setq rpl (read-char-exclusive))
15235 (if (equal rpl ?\r)
15237 (setq rpl (- rpl ?0))
15238 (when (equal rpl 0) (setq rpl 10))
15239 (if (and (> rpl 0) (<= rpl (length allowed)))
15240 (car (nth (1- rpl) allowed))
15241 (org-completing-read "Effort: " allowed nil))))
15243 (org-completing-read
15244 (concat "Effort" (and cur (string-match "\\S-" cur)
15245 (concat " [" cur "]"))
15246 ": ")
15247 existing nil nil "" nil cur)))))
15248 (unless (equal (org-entry-get nil prop) val)
15249 (org-entry-put nil prop val))
15250 (org-refresh-property
15251 '((effort . identity)
15252 (effort-minutes . org-duration-to-minutes))
15253 val)
15254 (when (equal heading (bound-and-true-p org-clock-current-task))
15255 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15256 (org-clock-update-mode-line))
15257 (message "%s is now %s" prop val)))
15259 (defun org-entry-properties (&optional pom which)
15260 "Get all properties of the current entry.
15262 When POM is a buffer position, get all properties from the entry
15263 there instead.
15265 This includes the TODO keyword, the tags, time strings for
15266 deadline, scheduled, and clocking, and any additional properties
15267 defined in the entry.
15269 If WHICH is nil or `all', get all properties. If WHICH is
15270 `special' or `standard', only get that subclass. If WHICH is
15271 a string, only get that property.
15273 Return value is an alist. Keys are properties, as upcased
15274 strings."
15275 (org-with-point-at pom
15276 (when (and (derived-mode-p 'org-mode)
15277 (ignore-errors (org-back-to-heading t)))
15278 (catch 'exit
15279 (let* ((beg (point))
15280 (specific (and (stringp which) (upcase which)))
15281 (which (cond ((not specific) which)
15282 ((member specific org-special-properties) 'special)
15283 (t 'standard)))
15284 props)
15285 ;; Get the special properties, like TODO and TAGS.
15286 (when (memq which '(nil all special))
15287 (when (or (not specific) (string= specific "CLOCKSUM"))
15288 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15289 (when clocksum
15290 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15291 props)))
15292 (when specific (throw 'exit props)))
15293 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15294 (let ((clocksumt (get-text-property (point)
15295 :org-clock-minutes-today)))
15296 (when clocksumt
15297 (push (cons "CLOCKSUM_T"
15298 (org-duration-from-minutes clocksumt))
15299 props)))
15300 (when specific (throw 'exit props)))
15301 (when (or (not specific) (string= specific "ITEM"))
15302 (let ((case-fold-search nil))
15303 (when (looking-at org-complex-heading-regexp)
15304 (push (cons "ITEM"
15305 (let ((title (match-string-no-properties 4)))
15306 (if (org-string-nw-p title)
15307 (org-remove-tabs title)
15308 "")))
15309 props)))
15310 (when specific (throw 'exit props)))
15311 (when (or (not specific) (string= specific "TODO"))
15312 (let ((case-fold-search nil))
15313 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15314 (push (cons "TODO" (match-string-no-properties 2)) props)))
15315 (when specific (throw 'exit props)))
15316 (when (or (not specific) (string= specific "PRIORITY"))
15317 (push (cons "PRIORITY"
15318 (if (looking-at org-priority-regexp)
15319 (match-string-no-properties 2)
15320 (char-to-string org-default-priority)))
15321 props)
15322 (when specific (throw 'exit props)))
15323 (when (or (not specific) (string= specific "FILE"))
15324 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15325 props)
15326 (when specific (throw 'exit props)))
15327 (when (or (not specific) (string= specific "TAGS"))
15328 (let ((value (org-string-nw-p (org-get-tags-string))))
15329 (when value (push (cons "TAGS" value) props)))
15330 (when specific (throw 'exit props)))
15331 (when (or (not specific) (string= specific "ALLTAGS"))
15332 (let ((value (org-get-tags-at)))
15333 (when value
15334 (push (cons "ALLTAGS"
15335 (format ":%s:" (mapconcat #'identity value ":")))
15336 props)))
15337 (when specific (throw 'exit props)))
15338 (when (or (not specific) (string= specific "BLOCKED"))
15339 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15340 (when specific (throw 'exit props)))
15341 (when (or (not specific)
15342 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15343 (forward-line)
15344 (when (looking-at-p org-planning-line-re)
15345 (end-of-line)
15346 (let ((bol (line-beginning-position))
15347 ;; Backward compatibility: time keywords used to
15348 ;; be configurable (before 8.3). Make sure we
15349 ;; get the correct keyword.
15350 (key-assoc `(("CLOSED" . ,org-closed-string)
15351 ("DEADLINE" . ,org-deadline-string)
15352 ("SCHEDULED" . ,org-scheduled-string))))
15353 (dolist (pair (if specific (list (assoc specific key-assoc))
15354 key-assoc))
15355 (save-excursion
15356 (when (search-backward (cdr pair) bol t)
15357 (goto-char (match-end 0))
15358 (skip-chars-forward " \t")
15359 (and (looking-at org-ts-regexp-both)
15360 (push (cons (car pair)
15361 (match-string-no-properties 0))
15362 props)))))))
15363 (when specific (throw 'exit props)))
15364 (when (or (not specific)
15365 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15366 (let ((find-ts
15367 (lambda (end ts)
15368 ;; Fix next time-stamp before END. TS is the
15369 ;; list of time-stamps found so far.
15370 (let ((ts ts)
15371 (regexp (cond
15372 ((string= specific "TIMESTAMP")
15373 org-ts-regexp)
15374 ((string= specific "TIMESTAMP_IA")
15375 org-ts-regexp-inactive)
15376 ((assoc "TIMESTAMP_IA" ts)
15377 org-ts-regexp)
15378 ((assoc "TIMESTAMP" ts)
15379 org-ts-regexp-inactive)
15380 (t org-ts-regexp-both))))
15381 (catch 'next
15382 (while (re-search-forward regexp end t)
15383 (backward-char)
15384 (let ((object (org-element-context)))
15385 ;; Accept to match timestamps in node
15386 ;; properties, too.
15387 (when (memq (org-element-type object)
15388 '(node-property timestamp))
15389 (let ((type
15390 (org-element-property :type object)))
15391 (cond
15392 ((and (memq type '(active active-range))
15393 (not (equal specific "TIMESTAMP_IA")))
15394 (unless (assoc "TIMESTAMP" ts)
15395 (push (cons "TIMESTAMP"
15396 (org-element-property
15397 :raw-value object))
15399 (when specific (throw 'exit ts))))
15400 ((and (memq type '(inactive inactive-range))
15401 (not (string= specific "TIMESTAMP")))
15402 (unless (assoc "TIMESTAMP_IA" ts)
15403 (push (cons "TIMESTAMP_IA"
15404 (org-element-property
15405 :raw-value object))
15407 (when specific (throw 'exit ts))))))
15408 ;; Both timestamp types are found,
15409 ;; move to next part.
15410 (when (= (length ts) 2) (throw 'next ts)))))
15411 ts)))))
15412 (goto-char beg)
15413 ;; First look for timestamps within headline.
15414 (let ((ts (funcall find-ts (line-end-position) nil)))
15415 (if (= (length ts) 2) (setq props (nconc ts props))
15416 ;; Then find timestamps in the section, skipping
15417 ;; planning line.
15418 (let ((end (save-excursion (outline-next-heading))))
15419 (forward-line)
15420 (when (looking-at-p org-planning-line-re) (forward-line))
15421 (setq props (nconc (funcall find-ts end ts) props))))))))
15422 ;; Get the standard properties, like :PROP:.
15423 (when (memq which '(nil all standard))
15424 ;; If we are looking after a specific property, delegate
15425 ;; to `org-entry-get', which is faster. However, make an
15426 ;; exception for "CATEGORY", since it can be also set
15427 ;; through keywords (i.e. #+CATEGORY).
15428 (if (and specific (not (equal specific "CATEGORY")))
15429 (let ((value (org-entry-get beg specific nil t)))
15430 (throw 'exit (and value (list (cons specific value)))))
15431 (let ((range (org-get-property-block beg)))
15432 (when range
15433 (let ((end (cdr range)) seen-base)
15434 (goto-char (car range))
15435 ;; Unlike to `org--update-property-plist', we
15436 ;; handle the case where base values is found
15437 ;; after its extension. We also forbid standard
15438 ;; properties to be named as special properties.
15439 (while (re-search-forward org-property-re end t)
15440 (let* ((key (upcase (match-string-no-properties 2)))
15441 (extendp (string-match-p "\\+\\'" key))
15442 (key-base (if extendp (substring key 0 -1) key))
15443 (value (match-string-no-properties 3)))
15444 (cond
15445 ((member-ignore-case key-base org-special-properties))
15446 (extendp
15447 (setq props
15448 (org--update-property-plist key value props)))
15449 ((member key seen-base))
15450 (t (push key seen-base)
15451 (let ((p (assoc-string key props t)))
15452 (if p (setcdr p (concat value " " (cdr p)))
15453 (push (cons key value) props))))))))))))
15454 (unless (assoc "CATEGORY" props)
15455 (push (cons "CATEGORY" (org-get-category beg)) props)
15456 (when (string= specific "CATEGORY") (throw 'exit props)))
15457 ;; Return value.
15458 props)))))
15460 (defun org--property-local-values (property literal-nil)
15461 "Return value for PROPERTY in current entry.
15462 Value is a list whose car is the base value for PROPERTY and cdr
15463 a list of accumulated values. Return nil if neither is found in
15464 the entry. Also return nil when PROPERTY is set to \"nil\",
15465 unless LITERAL-NIL is non-nil."
15466 (let ((range (org-get-property-block)))
15467 (when range
15468 (goto-char (car range))
15469 (let* ((case-fold-search t)
15470 (end (cdr range))
15471 (value
15472 ;; Base value.
15473 (save-excursion
15474 (let ((v (and (re-search-forward
15475 (org-re-property property nil t) end t)
15476 (match-string-no-properties 3))))
15477 (list (if literal-nil v (org-not-nil v)))))))
15478 ;; Find additional values.
15479 (let* ((property+ (org-re-property (concat property "+") nil t)))
15480 (while (re-search-forward property+ end t)
15481 (push (match-string-no-properties 3) value)))
15482 ;; Return final values.
15483 (and (not (equal value '(nil))) (nreverse value))))))
15485 (defun org--property-global-value (property literal-nil)
15486 "Return value for PROPERTY in current buffer.
15487 Return value is a string. Return nil if property is not set
15488 globally. Also return nil when PROPERTY is set to \"nil\",
15489 unless LITERAL-NIL is non-nil."
15490 (let ((global
15491 (cdr (or (assoc-string property org-file-properties t)
15492 (assoc-string property org-global-properties t)
15493 (assoc-string property org-global-properties-fixed t)))))
15494 (if literal-nil global (org-not-nil global))))
15496 (defun org-entry-get (pom property &optional inherit literal-nil)
15497 "Get value of PROPERTY for entry or content at point-or-marker POM.
15499 If INHERIT is non-nil and the entry does not have the property,
15500 then also check higher levels of the hierarchy. If INHERIT is
15501 the symbol `selective', use inheritance only if the setting in
15502 `org-use-property-inheritance' selects PROPERTY for inheritance.
15504 If the property is present but empty, the return value is the
15505 empty string. If the property is not present at all, nil is
15506 returned. In any other case, return the value as a string.
15507 Search is case-insensitive.
15509 If LITERAL-NIL is set, return the string value \"nil\" as
15510 a string, do not interpret it as the list atom nil. This is used
15511 for inheritance when a \"nil\" value can supersede a non-nil
15512 value higher up the hierarchy."
15513 (org-with-point-at pom
15514 (cond
15515 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15516 ;; We need a special property. Use `org-entry-properties' to
15517 ;; retrieve it, but specify the wanted property.
15518 (cdr (assoc-string property (org-entry-properties nil property))))
15519 ((and inherit
15520 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15521 (org-entry-get-with-inheritance property literal-nil))
15523 (let* ((local (org--property-local-values property literal-nil))
15524 (value (and local (mapconcat #'identity (delq nil local) " "))))
15525 (if literal-nil value (org-not-nil value)))))))
15527 (defun org-property-or-variable-value (var &optional inherit)
15528 "Check if there is a property fixing the value of VAR.
15529 If yes, return this value. If not, return the current value of the variable."
15530 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15531 (if (and prop (stringp prop) (string-match "\\S-" prop))
15532 (read prop)
15533 (symbol-value var))))
15535 (defun org-entry-delete (pom property)
15536 "Delete PROPERTY from entry at point-or-marker POM.
15537 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15538 non-nil when a property was removed."
15539 (org-with-point-at pom
15540 (pcase (org-get-property-block)
15541 (`(,begin . ,origin)
15542 (let* ((end (copy-marker origin))
15543 (re (org-re-property
15544 (concat (regexp-quote property) "\\+?") t t)))
15545 (goto-char begin)
15546 (while (re-search-forward re end t)
15547 (delete-region (match-beginning 0) (line-beginning-position 2)))
15548 ;; If drawer is empty, remove it altogether.
15549 (when (= begin end)
15550 (delete-region (line-beginning-position 0)
15551 (line-beginning-position 2)))
15552 ;; Return non-nil if some property was removed.
15553 (prog1 (/= end origin) (set-marker end nil))))
15554 (_ nil))))
15556 ;; Multi-values properties are properties that contain multiple values
15557 ;; These values are assumed to be single words, separated by whitespace.
15558 (defun org-entry-add-to-multivalued-property (pom property value)
15559 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15560 (let* ((old (org-entry-get pom property))
15561 (values (and old (split-string old))))
15562 (setq value (org-entry-protect-space value))
15563 (unless (member value values)
15564 (setq values (append values (list value)))
15565 (org-entry-put pom property (mapconcat #'identity values " ")))))
15567 (defun org-entry-remove-from-multivalued-property (pom property value)
15568 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15569 (let* ((old (org-entry-get pom property))
15570 (values (and old (split-string old))))
15571 (setq value (org-entry-protect-space value))
15572 (when (member value values)
15573 (setq values (delete value values))
15574 (org-entry-put pom property (mapconcat #'identity values " ")))))
15576 (defun org-entry-member-in-multivalued-property (pom property value)
15577 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15578 (let* ((old (org-entry-get pom property))
15579 (values (and old (split-string old))))
15580 (setq value (org-entry-protect-space value))
15581 (member value values)))
15583 (defun org-entry-get-multivalued-property (pom property)
15584 "Return a list of values in a multivalued property."
15585 (let* ((value (org-entry-get pom property))
15586 (values (and value (split-string value))))
15587 (mapcar #'org-entry-restore-space values)))
15589 (defun org-entry-put-multivalued-property (pom property &rest values)
15590 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15591 VALUES should be a list of strings. Spaces will be protected."
15592 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15593 (let* ((value (org-entry-get pom property))
15594 (values (and value (split-string value))))
15595 (mapcar #'org-entry-restore-space values)))
15597 (defun org-entry-protect-space (s)
15598 "Protect spaces and newline in string S."
15599 (while (string-match " " s)
15600 (setq s (replace-match "%20" t t s)))
15601 (while (string-match "\n" s)
15602 (setq s (replace-match "%0A" t t s)))
15605 (defun org-entry-restore-space (s)
15606 "Restore spaces and newline in string S."
15607 (while (string-match "%20" s)
15608 (setq s (replace-match " " t t s)))
15609 (while (string-match "%0A" s)
15610 (setq s (replace-match "\n" t t s)))
15613 (defvar org-entry-property-inherited-from (make-marker)
15614 "Marker pointing to the entry from where a property was inherited.
15615 Each call to `org-entry-get-with-inheritance' will set this marker to the
15616 location of the entry where the inheritance search matched. If there was
15617 no match, the marker will point nowhere.
15618 Note that also `org-entry-get' calls this function, if the INHERIT flag
15619 is set.")
15621 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15622 "Get PROPERTY of entry or content at point, search higher levels if needed.
15623 The search will stop at the first ancestor which has the property defined.
15624 If the value found is \"nil\", return nil to show that the property
15625 should be considered as undefined (this is the meaning of nil here).
15626 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15627 (move-marker org-entry-property-inherited-from nil)
15628 (org-with-wide-buffer
15629 (let (value)
15630 (catch 'exit
15631 (while t
15632 (let ((v (org--property-local-values property literal-nil)))
15633 (when v
15634 (setq value
15635 (concat (mapconcat #'identity (delq nil v) " ")
15636 (and value " ")
15637 value)))
15638 (cond
15639 ((car v)
15640 (org-back-to-heading t)
15641 (move-marker org-entry-property-inherited-from (point))
15642 (throw 'exit nil))
15643 ((org-up-heading-safe))
15645 (let ((global (org--property-global-value property literal-nil)))
15646 (cond ((not global))
15647 (value (setq value (concat global " " value)))
15648 (t (setq value global))))
15649 (throw 'exit nil))))))
15650 (if literal-nil value (org-not-nil value)))))
15652 (defvar org-property-changed-functions nil
15653 "Hook called when the value of a property has changed.
15654 Each hook function should accept two arguments, the name of the property
15655 and the new value.")
15657 (defun org-entry-put (pom property value)
15658 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15660 If the value is nil, it is converted to the empty string. If it
15661 is not a string, an error is raised. Also raise an error on
15662 invalid property names.
15664 PROPERTY can be any regular property (see
15665 `org-special-properties'). It can also be \"TODO\",
15666 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15668 For the last two properties, VALUE may have any of the special
15669 values \"earlier\" and \"later\". The function then increases or
15670 decreases scheduled or deadline date by one day."
15671 (cond ((null value) (setq value ""))
15672 ((not (stringp value)) (error "Properties values should be strings"))
15673 ((not (org--valid-property-p property))
15674 (user-error "Invalid property name: \"%s\"" property)))
15675 (org-with-point-at pom
15676 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15677 (org-back-to-heading t)
15678 (org-with-limited-levels (org-back-to-heading t)))
15679 (let ((beg (point)))
15680 (cond
15681 ((equal property "TODO")
15682 (cond ((not (org-string-nw-p value)) (setq value 'none))
15683 ((not (member value org-todo-keywords-1))
15684 (user-error "\"%s\" is not a valid TODO state" value)))
15685 (org-todo value)
15686 (org-set-tags nil 'align))
15687 ((equal property "PRIORITY")
15688 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15689 (org-set-tags nil 'align))
15690 ((equal property "SCHEDULED")
15691 (forward-line)
15692 (if (and (looking-at-p org-planning-line-re)
15693 (re-search-forward
15694 org-scheduled-time-regexp (line-end-position) t))
15695 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15696 ((string= value "later") (org-timestamp-change 1 'day))
15697 ((string= value "") (org-schedule '(4)))
15698 (t (org-schedule nil value)))
15699 (if (member value '("earlier" "later" ""))
15700 (call-interactively #'org-schedule)
15701 (org-schedule nil value))))
15702 ((equal property "DEADLINE")
15703 (forward-line)
15704 (if (and (looking-at-p org-planning-line-re)
15705 (re-search-forward
15706 org-deadline-time-regexp (line-end-position) t))
15707 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15708 ((string= value "later") (org-timestamp-change 1 'day))
15709 ((string= value "") (org-deadline '(4)))
15710 (t (org-deadline nil value)))
15711 (if (member value '("earlier" "later" ""))
15712 (call-interactively #'org-deadline)
15713 (org-deadline nil value))))
15714 ((member property org-special-properties)
15715 (error "The %s property cannot be set with `org-entry-put'" property))
15717 (let* ((range (org-get-property-block beg 'force))
15718 (end (cdr range))
15719 (case-fold-search t))
15720 (goto-char (car range))
15721 (if (re-search-forward (org-re-property property nil t) end t)
15722 (progn (delete-region (match-beginning 0) (match-end 0))
15723 (goto-char (match-beginning 0)))
15724 (goto-char end)
15725 (insert "\n")
15726 (backward-char))
15727 (insert ":" property ":")
15728 (when value (insert " " value))
15729 (org-indent-line)))))
15730 (run-hook-with-args 'org-property-changed-functions property value)))
15732 (defun org-buffer-property-keys (&optional specials defaults columns)
15733 "Get all property keys in the current buffer.
15735 When SPECIALS is non-nil, also list the special properties that
15736 reflect things like tags and TODO state.
15738 When DEFAULTS is non-nil, also include properties that has
15739 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15740 DESCRIPTION, LOCATION, and LOGGING and others.
15742 When COLUMNS in non-nil, also include property names given in
15743 COLUMN formats in the current buffer."
15744 (let ((case-fold-search t)
15745 (props (append
15746 (and specials org-special-properties)
15747 (and defaults (cons org-effort-property org-default-properties))
15748 nil)))
15749 (org-with-wide-buffer
15750 (goto-char (point-min))
15751 (while (re-search-forward org-property-start-re nil t)
15752 (catch :skip
15753 (let ((range (org-get-property-block)))
15754 (unless range (throw :skip nil))
15755 (goto-char (car range))
15756 (let ((begin (car range))
15757 (end (cdr range)))
15758 ;; Make sure that found property block is not located
15759 ;; before current point, as it would generate an infloop.
15760 ;; It can happen, for example, in the following
15761 ;; situation:
15763 ;; * Headline
15764 ;; :PROPERTIES:
15765 ;; ...
15766 ;; :END:
15767 ;; *************** Inlinetask
15768 ;; #+BEGIN_EXAMPLE
15769 ;; :PROPERTIES:
15770 ;; #+END_EXAMPLE
15772 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15773 (while (< (point) end)
15774 (let ((p (progn (looking-at org-property-re)
15775 (match-string-no-properties 2))))
15776 ;; Only add true property name, not extension symbol.
15777 (push (if (not (string-match-p "\\+\\'" p)) p
15778 (substring p 0 -1))
15779 props))
15780 (forward-line))))
15781 (outline-next-heading)))
15782 (when columns
15783 (goto-char (point-min))
15784 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15785 (let ((element (org-element-at-point)))
15786 (when (memq (org-element-type element) '(keyword node-property))
15787 (let ((value (org-element-property :value element))
15788 (start 0))
15789 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15790 \\(?:{[^}]+}\\)?"
15791 value start)
15792 (setq start (match-end 0))
15793 (let ((p (match-string-no-properties 1 value)))
15794 (unless (member-ignore-case p org-special-properties)
15795 (push p props))))))))))
15796 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15798 (defun org-property-values (key)
15799 "List all non-nil values of property KEY in current buffer."
15800 (org-with-wide-buffer
15801 (goto-char (point-min))
15802 (let ((case-fold-search t)
15803 (re (org-re-property key))
15804 values)
15805 (while (re-search-forward re nil t)
15806 (push (org-entry-get (point) key) values))
15807 (delete-dups values))))
15809 (defun org-insert-property-drawer ()
15810 "Insert a property drawer into the current entry."
15811 (org-with-wide-buffer
15812 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15813 (org-back-to-heading t)
15814 (org-with-limited-levels (org-back-to-heading t)))
15815 (forward-line)
15816 (when (looking-at-p org-planning-line-re) (forward-line))
15817 (unless (looking-at-p org-property-drawer-re)
15818 ;; Make sure we start editing a line from current entry, not from
15819 ;; next one. It prevents extending text properties or overlays
15820 ;; belonging to the latter.
15821 (when (bolp) (backward-char))
15822 (let ((begin (1+ (point)))
15823 (inhibit-read-only t))
15824 (insert "\n:PROPERTIES:\n:END:")
15825 (when (eobp) (insert "\n"))
15826 (org-indent-region begin (point))))))
15828 (defun org-insert-drawer (&optional arg drawer)
15829 "Insert a drawer at point.
15831 When optional argument ARG is non-nil, insert a property drawer.
15833 Optional argument DRAWER, when non-nil, is a string representing
15834 drawer's name. Otherwise, the user is prompted for a name.
15836 If a region is active, insert the drawer around that region
15837 instead.
15839 Point is left between drawer's boundaries."
15840 (interactive "P")
15841 (let* ((drawer (if arg "PROPERTIES"
15842 (or drawer (read-from-minibuffer "Drawer: ")))))
15843 (cond
15844 ;; With C-u, fall back on `org-insert-property-drawer'
15845 (arg (org-insert-property-drawer))
15846 ;; Check validity of suggested drawer's name.
15847 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15848 (user-error "Invalid drawer name"))
15849 ;; With an active region, insert a drawer at point.
15850 ((not (org-region-active-p))
15851 (progn
15852 (unless (bolp) (insert "\n"))
15853 (insert (format ":%s:\n\n:END:\n" drawer))
15854 (forward-line -2)))
15855 ;; Otherwise, insert the drawer at point
15857 (let ((rbeg (region-beginning))
15858 (rend (copy-marker (region-end))))
15859 (unwind-protect
15860 (progn
15861 (goto-char rbeg)
15862 (beginning-of-line)
15863 (when (save-excursion
15864 (re-search-forward org-outline-regexp-bol rend t))
15865 (user-error "Drawers cannot contain headlines"))
15866 ;; Position point at the beginning of the first
15867 ;; non-blank line in region. Insert drawer's opening
15868 ;; there, then indent it.
15869 (org-skip-whitespace)
15870 (beginning-of-line)
15871 (insert ":" drawer ":\n")
15872 (forward-line -1)
15873 (indent-for-tab-command)
15874 ;; Move point to the beginning of the first blank line
15875 ;; after the last non-blank line in region. Insert
15876 ;; drawer's closing, then indent it.
15877 (goto-char rend)
15878 (skip-chars-backward " \r\t\n")
15879 (insert "\n:END:")
15880 (deactivate-mark t)
15881 (indent-for-tab-command)
15882 (unless (eolp) (insert "\n")))
15883 ;; Clear marker, whatever the outcome of insertion is.
15884 (set-marker rend nil)))))))
15886 (defvar org-property-set-functions-alist nil
15887 "Property set function alist.
15888 Each entry should have the following format:
15890 (PROPERTY . READ-FUNCTION)
15892 The read function will be called with the same argument as
15893 `org-completing-read'.")
15895 (defun org-set-property-function (property)
15896 "Get the function that should be used to set PROPERTY.
15897 This is computed according to `org-property-set-functions-alist'."
15898 (or (cdr (assoc property org-property-set-functions-alist))
15899 'org-completing-read))
15901 (defun org-read-property-value (property)
15902 "Read PROPERTY value from user."
15903 (let* ((completion-ignore-case t)
15904 (allowed (org-property-get-allowed-values nil property 'table))
15905 (cur (org-entry-get nil property))
15906 (prompt (concat property " value"
15907 (if (and cur (string-match "\\S-" cur))
15908 (concat " [" cur "]") "") ": "))
15909 (set-function (org-set-property-function property))
15910 (val (if allowed
15911 (funcall set-function prompt allowed nil
15912 (not (get-text-property 0 'org-unrestricted
15913 (caar allowed))))
15914 (funcall set-function prompt
15915 (mapcar 'list (org-property-values property))
15916 nil nil "" nil cur))))
15917 (org-trim val)))
15919 (defvar org-last-set-property nil)
15920 (defvar org-last-set-property-value nil)
15921 (defun org-read-property-name ()
15922 "Read a property name."
15923 (let ((completion-ignore-case t)
15924 (default-prop (or (and (org-at-property-p)
15925 (match-string-no-properties 2))
15926 org-last-set-property)))
15927 (org-completing-read
15928 (concat "Property"
15929 (if default-prop (concat " [" default-prop "]") "")
15930 ": ")
15931 (mapcar #'list (org-buffer-property-keys nil t t))
15932 nil nil nil nil default-prop)))
15934 (defun org-set-property-and-value (use-last)
15935 "Allow to set [PROPERTY]: [value] direction from prompt.
15936 When use-default, don't even ask, just use the last
15937 \"[PROPERTY]: [value]\" string from the history."
15938 (interactive "P")
15939 (let* ((completion-ignore-case t)
15940 (pv (or (and use-last org-last-set-property-value)
15941 (org-completing-read
15942 "Enter a \"[Property]: [value]\" pair: "
15943 nil nil nil nil nil
15944 org-last-set-property-value)))
15945 prop val)
15946 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15947 (setq prop (match-string 1 pv)
15948 val (match-string 2 pv))
15949 (org-set-property prop val))))
15951 (defun org-set-property (property value)
15952 "In the current entry, set PROPERTY to VALUE.
15954 When called interactively, this will prompt for a property name, offering
15955 completion on existing and default properties. And then it will prompt
15956 for a value, offering completion either on allowed values (via an inherited
15957 xxx_ALL property) or on existing values in other instances of this property
15958 in the current file.
15960 Throw an error when trying to set a property with an invalid name."
15961 (interactive (list nil nil))
15962 (let ((property (or property (org-read-property-name))))
15963 ;; `org-entry-put' also makes the following check, but this one
15964 ;; avoids polluting `org-last-set-property' and
15965 ;; `org-last-set-property-value' needlessly.
15966 (unless (org--valid-property-p property)
15967 (user-error "Invalid property name: \"%s\"" property))
15968 (let ((value (or value (org-read-property-value property)))
15969 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15970 (setq org-last-set-property property)
15971 (setq org-last-set-property-value (concat property ": " value))
15972 ;; Possibly postprocess the inserted value:
15973 (when fn (setq value (funcall fn value)))
15974 (unless (equal (org-entry-get nil property) value)
15975 (org-entry-put nil property value)))))
15977 (defun org-find-property (property &optional value)
15978 "Find first entry in buffer that sets PROPERTY.
15980 When optional argument VALUE is non-nil, only consider an entry
15981 if it contains PROPERTY set to this value. If PROPERTY should be
15982 explicitly set to nil, use string \"nil\" for VALUE.
15984 Return position where the entry begins, or nil if there is no
15985 such entry. If narrowing is in effect, only search the visible
15986 part of the buffer."
15987 (save-excursion
15988 (goto-char (point-min))
15989 (let ((case-fold-search t)
15990 (re (org-re-property property nil (not value) value)))
15991 (catch 'exit
15992 (while (re-search-forward re nil t)
15993 (when (if value (org-at-property-p)
15994 (org-entry-get (point) property nil t))
15995 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15997 (defun org-delete-property (property)
15998 "In the current entry, delete PROPERTY."
15999 (interactive
16000 (let* ((completion-ignore-case t)
16001 (cat (org-entry-get (point) "CATEGORY"))
16002 (props0 (org-entry-properties nil 'standard))
16003 (props (if cat props0
16004 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16005 (prop (if (< 1 (length props))
16006 (completing-read "Property: " props nil t)
16007 (caar props))))
16008 (list prop)))
16009 (if (not property)
16010 (message "No property to delete in this entry")
16011 (org-entry-delete nil property)
16012 (message "Property \"%s\" deleted" property)))
16014 (defun org-delete-property-globally (property)
16015 "Remove PROPERTY globally, from all entries.
16016 This function ignores narrowing, if any."
16017 (interactive
16018 (let* ((completion-ignore-case t)
16019 (prop (completing-read
16020 "Globally remove property: "
16021 (mapcar #'list (org-buffer-property-keys)))))
16022 (list prop)))
16023 (org-with-wide-buffer
16024 (goto-char (point-min))
16025 (let ((count 0)
16026 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16027 (while (re-search-forward re nil t)
16028 (when (org-entry-delete (point) property) (cl-incf count)))
16029 (message "Property \"%s\" removed from %d entries" property count))))
16031 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16033 (defun org-compute-property-at-point ()
16034 "Compute the property at point.
16035 This looks for an enclosing column format, extracts the operator and
16036 then applies it to the property in the column format's scope."
16037 (interactive)
16038 (unless (org-at-property-p)
16039 (user-error "Not at a property"))
16040 (let ((prop (match-string-no-properties 2)))
16041 (org-columns-get-format-and-top-level)
16042 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16043 (user-error "No operator defined for property %s" prop))
16044 (org-columns-compute prop)))
16046 (defvar org-property-allowed-value-functions nil
16047 "Hook for functions supplying allowed values for a specific property.
16048 The functions must take a single argument, the name of the property, and
16049 return a flat list of allowed values. If \":ETC\" is one of
16050 the values, this means that these values are intended as defaults for
16051 completion, but that other values should be allowed too.
16052 The functions must return nil if they are not responsible for this
16053 property.")
16055 (defun org-property-get-allowed-values (pom property &optional table)
16056 "Get allowed values for the property PROPERTY.
16057 When TABLE is non-nil, return an alist that can directly be used for
16058 completion."
16059 (let (vals)
16060 (cond
16061 ((equal property "TODO")
16062 (setq vals (org-with-point-at pom
16063 (append org-todo-keywords-1 '("")))))
16064 ((equal property "PRIORITY")
16065 (let ((n org-lowest-priority))
16066 (while (>= n org-highest-priority)
16067 (push (char-to-string n) vals)
16068 (setq n (1- n)))))
16069 ((equal property "CATEGORY"))
16070 ((member property org-special-properties))
16071 ((setq vals (run-hook-with-args-until-success
16072 'org-property-allowed-value-functions property)))
16074 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16075 (when (and vals (string-match "\\S-" vals))
16076 (setq vals (car (read-from-string (concat "(" vals ")"))))
16077 (setq vals (mapcar (lambda (x)
16078 (cond ((stringp x) x)
16079 ((numberp x) (number-to-string x))
16080 ((symbolp x) (symbol-name x))
16081 (t "???")))
16082 vals)))))
16083 (when (member ":ETC" vals)
16084 (setq vals (remove ":ETC" vals))
16085 (org-add-props (car vals) '(org-unrestricted t)))
16086 (if table (mapcar 'list vals) vals)))
16088 (defun org-property-previous-allowed-value (&optional _previous)
16089 "Switch to the next allowed value for this property."
16090 (interactive)
16091 (org-property-next-allowed-value t))
16093 (defun org-property-next-allowed-value (&optional previous)
16094 "Switch to the next allowed value for this property."
16095 (interactive)
16096 (unless (org-at-property-p)
16097 (user-error "Not at a property"))
16098 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16099 (key (match-string 2))
16100 (value (match-string 3))
16101 (allowed (or (org-property-get-allowed-values (point) key)
16102 (and (member value '("[ ]" "[-]" "[X]"))
16103 '("[ ]" "[X]"))))
16104 (heading (save-match-data (nth 4 (org-heading-components))))
16105 nval)
16106 (unless allowed
16107 (user-error "Allowed values for this property have not been defined"))
16108 (when previous (setq allowed (reverse allowed)))
16109 (when (member value allowed)
16110 (setq nval (car (cdr (member value allowed)))))
16111 (setq nval (or nval (car allowed)))
16112 (when (equal nval value)
16113 (user-error "Only one allowed value for this property"))
16114 (org-at-property-p)
16115 (replace-match (concat " :" key ": " nval) t t)
16116 (org-indent-line)
16117 (beginning-of-line 1)
16118 (skip-chars-forward " \t")
16119 (when (equal prop org-effort-property)
16120 (org-refresh-property
16121 '((effort . identity)
16122 (effort-minutes . org-duration-to-minutes))
16123 nval)
16124 (when (string= org-clock-current-task heading)
16125 (setq org-clock-effort nval)
16126 (org-clock-update-mode-line)))
16127 (run-hook-with-args 'org-property-changed-functions key nval)))
16129 (defun org-find-olp (path &optional this-buffer)
16130 "Return a marker pointing to the entry at outline path OLP.
16131 If anything goes wrong, throw an error.
16132 You can wrap this call to catch the error like this:
16134 (condition-case msg
16135 (org-mobile-locate-entry (match-string 4))
16136 (error (nth 1 msg)))
16138 The return value will then be either a string with the error message,
16139 or a marker if everything is OK.
16141 If THIS-BUFFER is set, the outline path does not contain a file,
16142 only headings."
16143 (let* ((file (if this-buffer buffer-file-name (pop path)))
16144 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16145 (level 1)
16146 (lmin 1)
16147 (lmax 1)
16148 end found flevel)
16149 (unless buffer (error "File not found :%s" file))
16150 (with-current-buffer buffer
16151 (unless (derived-mode-p 'org-mode)
16152 (error "Buffer %s needs to be in Org mode" buffer))
16153 (org-with-wide-buffer
16154 (goto-char (point-min))
16155 (dolist (heading path)
16156 (let ((re (format org-complex-heading-regexp-format
16157 (regexp-quote heading)))
16158 (cnt 0))
16159 (while (re-search-forward re end t)
16160 (setq level (- (match-end 1) (match-beginning 1)))
16161 (when (and (>= level lmin) (<= level lmax))
16162 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16163 (when (= cnt 0)
16164 (error "Heading not found on level %d: %s" lmax heading))
16165 (when (> cnt 1)
16166 (error "Heading not unique on level %d: %s" lmax heading))
16167 (goto-char found)
16168 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16169 (setq end (save-excursion (org-end-of-subtree t t)))))
16170 (when (org-at-heading-p)
16171 (point-marker))))))
16173 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16174 "Find node HEADING in BUFFER.
16175 Return a marker to the heading if it was found, or nil if not.
16176 If POS-ONLY is set, return just the position instead of a marker.
16178 The heading text must match exact, but it may have a TODO keyword,
16179 a priority cookie and tags in the standard locations."
16180 (with-current-buffer (or buffer (current-buffer))
16181 (org-with-wide-buffer
16182 (goto-char (point-min))
16183 (let (case-fold-search)
16184 (when (re-search-forward
16185 (format org-complex-heading-regexp-format
16186 (regexp-quote heading)) nil t)
16187 (if pos-only
16188 (match-beginning 0)
16189 (move-marker (make-marker) (match-beginning 0))))))))
16191 (defun org-find-exact-heading-in-directory (heading &optional dir)
16192 "Find Org node headline HEADING in all .org files in directory DIR.
16193 When the target headline is found, return a marker to this location."
16194 (let ((files (directory-files (or dir default-directory)
16195 t "\\`[^.#].*\\.org\\'"))
16196 visiting m buffer)
16197 (catch 'found
16198 (dolist (file files)
16199 (message "trying %s" file)
16200 (setq visiting (org-find-base-buffer-visiting file))
16201 (setq buffer (or visiting (find-file-noselect file)))
16202 (setq m (org-find-exact-headline-in-buffer
16203 heading buffer))
16204 (when (and (not m) (not visiting)) (kill-buffer buffer))
16205 (and m (throw 'found m))))))
16207 (defun org-find-entry-with-id (ident)
16208 "Locate the entry that contains the ID property with exact value IDENT.
16209 IDENT can be a string, a symbol or a number, this function will search for
16210 the string representation of it.
16211 Return the position where this entry starts, or nil if there is no such entry."
16212 (interactive "sID: ")
16213 (let ((id (cond
16214 ((stringp ident) ident)
16215 ((symbolp ident) (symbol-name ident))
16216 ((numberp ident) (number-to-string ident))
16217 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16218 (org-with-wide-buffer (org-find-property "ID" id))))
16220 ;;;; Timestamps
16222 (defvar org-last-changed-timestamp nil)
16223 (defvar org-last-inserted-timestamp nil
16224 "The last time stamp inserted with `org-insert-time-stamp'.")
16226 (defun org-time-stamp (arg &optional inactive)
16227 "Prompt for a date/time and insert a time stamp.
16229 If the user specifies a time like HH:MM or if this command is
16230 called with at least one prefix argument, the time stamp contains
16231 the date and the time. Otherwise, only the date is included.
16233 All parts of a date not specified by the user are filled in from
16234 the timestamp at point, if any, or the current date/time
16235 otherwise.
16237 If there is already a timestamp at the cursor, it is replaced.
16239 With two universal prefix arguments, insert an active timestamp
16240 with the current time without prompting the user.
16242 When called from lisp, the timestamp is inactive if INACTIVE is
16243 non-nil."
16244 (interactive "P")
16245 (let* ((ts (cond
16246 ((org-at-date-range-p t)
16247 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16248 ((org-at-timestamp-p 'lax) (match-string 0))))
16249 ;; Default time is either the timestamp at point or today.
16250 ;; When entering a range, only the range start is considered.
16251 (default-time (if (not ts) (current-time)
16252 (apply #'encode-time (org-parse-time-string ts))))
16253 (default-input (and ts (org-get-compact-tod ts)))
16254 (repeater (and ts
16255 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16256 (match-string 0 ts)))
16257 org-time-was-given
16258 org-end-time-was-given
16259 (time
16260 (and (if (equal arg '(16)) (current-time)
16261 ;; Preserve `this-command' and `last-command'.
16262 (let ((this-command this-command)
16263 (last-command last-command))
16264 (org-read-date
16265 arg 'totime nil nil default-time default-input
16266 inactive))))))
16267 (cond
16268 ((and ts
16269 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16270 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16271 (insert "--")
16272 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16274 ;; Make sure we're on a timestamp. When in the middle of a date
16275 ;; range, move arbitrarily to range end.
16276 (unless (org-at-timestamp-p 'lax)
16277 (skip-chars-forward "-")
16278 (org-at-timestamp-p 'lax))
16279 (replace-match "")
16280 (setq org-last-changed-timestamp
16281 (org-insert-time-stamp
16282 time (or org-time-was-given arg)
16283 inactive nil nil (list org-end-time-was-given)))
16284 (when repeater
16285 (backward-char)
16286 (insert " " repeater)
16287 (setq org-last-changed-timestamp
16288 (concat (substring org-last-inserted-timestamp 0 -1)
16289 " " repeater ">")))
16290 (message "Timestamp updated"))
16291 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16292 (t (org-insert-time-stamp
16293 time (or org-time-was-given arg) inactive nil nil
16294 (list org-end-time-was-given))))))
16296 ;; FIXME: can we use this for something else, like computing time differences?
16297 (defun org-get-compact-tod (s)
16298 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16299 (let* ((t1 (match-string 1 s))
16300 (h1 (string-to-number (match-string 2 s)))
16301 (m1 (string-to-number (match-string 3 s)))
16302 (t2 (and (match-end 4) (match-string 5 s)))
16303 (h2 (and t2 (string-to-number (match-string 6 s))))
16304 (m2 (and t2 (string-to-number (match-string 7 s))))
16305 dh dm)
16306 (if (not t2)
16308 (setq dh (- h2 h1) dm (- m2 m1))
16309 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16310 (concat t1 "+" (number-to-string dh)
16311 (and (/= 0 dm) (format ":%02d" dm)))))))
16313 (defun org-time-stamp-inactive (&optional arg)
16314 "Insert an inactive time stamp.
16315 An inactive time stamp is enclosed in square brackets instead of angle
16316 brackets. It is inactive in the sense that it does not trigger agenda entries,
16317 does not link to the calendar and cannot be changed with the S-cursor keys.
16318 So these are more for recording a certain time/date."
16319 (interactive "P")
16320 (org-time-stamp arg 'inactive))
16322 (defvar org-date-ovl (make-overlay 1 1))
16323 (overlay-put org-date-ovl 'face 'org-date-selected)
16324 (delete-overlay org-date-ovl)
16326 (defvar org-ans1) ; dynamically scoped parameter
16327 (defvar org-ans2) ; dynamically scoped parameter
16329 (defvar org-plain-time-of-day-regexp) ; defined below
16331 (defvar org-overriding-default-time nil) ; dynamically scoped
16332 (defvar org-read-date-overlay nil)
16333 (defvar org-dcst nil) ; dynamically scoped
16334 (defvar org-read-date-history nil)
16335 (defvar org-read-date-final-answer nil)
16336 (defvar org-read-date-analyze-futurep nil)
16337 (defvar org-read-date-analyze-forced-year nil)
16338 (defvar org-read-date-inactive)
16340 (defvar org-read-date-minibuffer-local-map
16341 (let* ((map (make-sparse-keymap)))
16342 (set-keymap-parent map minibuffer-local-map)
16343 (org-defkey map (kbd ".")
16344 (lambda () (interactive)
16345 ;; Are we at the beginning of the prompt?
16346 (if (looking-back "^[^:]+: "
16347 (let ((inhibit-field-text-motion t))
16348 (line-beginning-position)))
16349 (org-eval-in-calendar '(calendar-goto-today))
16350 (insert "."))))
16351 (org-defkey map (kbd "C-.")
16352 (lambda () (interactive)
16353 (org-eval-in-calendar '(calendar-goto-today))))
16354 (org-defkey map [(meta shift left)]
16355 (lambda () (interactive)
16356 (org-eval-in-calendar '(calendar-backward-month 1))))
16357 (org-defkey map [(meta shift right)]
16358 (lambda () (interactive)
16359 (org-eval-in-calendar '(calendar-forward-month 1))))
16360 (org-defkey map [(meta shift up)]
16361 (lambda () (interactive)
16362 (org-eval-in-calendar '(calendar-backward-year 1))))
16363 (org-defkey map [(meta shift down)]
16364 (lambda () (interactive)
16365 (org-eval-in-calendar '(calendar-forward-year 1))))
16366 (org-defkey map [?\e (shift left)]
16367 (lambda () (interactive)
16368 (org-eval-in-calendar '(calendar-backward-month 1))))
16369 (org-defkey map [?\e (shift right)]
16370 (lambda () (interactive)
16371 (org-eval-in-calendar '(calendar-forward-month 1))))
16372 (org-defkey map [?\e (shift up)]
16373 (lambda () (interactive)
16374 (org-eval-in-calendar '(calendar-backward-year 1))))
16375 (org-defkey map [?\e (shift down)]
16376 (lambda () (interactive)
16377 (org-eval-in-calendar '(calendar-forward-year 1))))
16378 (org-defkey map [(shift up)]
16379 (lambda () (interactive)
16380 (org-eval-in-calendar '(calendar-backward-week 1))))
16381 (org-defkey map [(shift down)]
16382 (lambda () (interactive)
16383 (org-eval-in-calendar '(calendar-forward-week 1))))
16384 (org-defkey map [(shift left)]
16385 (lambda () (interactive)
16386 (org-eval-in-calendar '(calendar-backward-day 1))))
16387 (org-defkey map [(shift right)]
16388 (lambda () (interactive)
16389 (org-eval-in-calendar '(calendar-forward-day 1))))
16390 (org-defkey map "!"
16391 (lambda () (interactive)
16392 (org-eval-in-calendar '(diary-view-entries))
16393 (message "")))
16394 (org-defkey map ">"
16395 (lambda () (interactive)
16396 (org-eval-in-calendar '(calendar-scroll-left 1))))
16397 (org-defkey map "<"
16398 (lambda () (interactive)
16399 (org-eval-in-calendar '(calendar-scroll-right 1))))
16400 (org-defkey map "\C-v"
16401 (lambda () (interactive)
16402 (org-eval-in-calendar
16403 '(calendar-scroll-left-three-months 1))))
16404 (org-defkey map "\M-v"
16405 (lambda () (interactive)
16406 (org-eval-in-calendar
16407 '(calendar-scroll-right-three-months 1))))
16408 map)
16409 "Keymap for minibuffer commands when using `org-read-date'.")
16411 (defvar org-def)
16412 (defvar org-defdecode)
16413 (defvar org-with-time)
16415 (defvar calendar-setup) ; Dynamically scoped.
16416 (defun org-read-date (&optional with-time to-time from-string prompt
16417 default-time default-input inactive)
16418 "Read a date, possibly a time, and make things smooth for the user.
16419 The prompt will suggest to enter an ISO date, but you can also enter anything
16420 which will at least partially be understood by `parse-time-string'.
16421 Unrecognized parts of the date will default to the current day, month, year,
16422 hour and minute. If this command is called to replace a timestamp at point,
16423 or to enter the second timestamp of a range, the default time is taken
16424 from the existing stamp. Furthermore, the command prefers the future,
16425 so if you are giving a date where the year is not given, and the day-month
16426 combination is already past in the current year, it will assume you
16427 mean next year. For details, see the manual. A few examples:
16429 3-2-5 --> 2003-02-05
16430 feb 15 --> currentyear-02-15
16431 2/15 --> currentyear-02-15
16432 sep 12 9 --> 2009-09-12
16433 12:45 --> today 12:45
16434 22 sept 0:34 --> currentyear-09-22 0:34
16435 12 --> currentyear-currentmonth-12
16436 Fri --> nearest Friday after today
16437 -Tue --> last Tuesday
16438 etc.
16440 Furthermore you can specify a relative date by giving, as the *first* thing
16441 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16442 change in days weeks, months, years.
16443 With a single plus or minus, the date is relative to today. With a double
16444 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16445 +4d --> four days from today
16446 +4 --> same as above
16447 +2w --> two weeks from today
16448 ++5 --> five days from default date
16450 The function understands only English month and weekday abbreviations.
16452 While prompting, a calendar is popped up - you can also select the
16453 date with the mouse (button 1). The calendar shows a period of three
16454 months. To scroll it to other months, use the keys `>' and `<'.
16455 If you don't like the calendar, turn it off with
16456 (setq org-read-date-popup-calendar nil)
16458 With optional argument TO-TIME, the date will immediately be converted
16459 to an internal time.
16460 With an optional argument WITH-TIME, the prompt will suggest to
16461 also insert a time. Note that when WITH-TIME is not set, you can
16462 still enter a time, and this function will inform the calling routine
16463 about this change. The calling routine may then choose to change the
16464 format used to insert the time stamp into the buffer to include the time.
16465 With optional argument FROM-STRING, read from this string instead from
16466 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16467 the time/date that is used for everything that is not specified by the
16468 user."
16469 (require 'parse-time)
16470 (let* ((org-with-time with-time)
16471 (org-time-stamp-rounding-minutes
16472 (if (equal org-with-time '(16))
16473 '(0 0)
16474 org-time-stamp-rounding-minutes))
16475 (org-dcst org-display-custom-times)
16476 (ct (org-current-time))
16477 (org-def (or org-overriding-default-time default-time ct))
16478 (org-defdecode (decode-time org-def))
16479 (cur-frame (selected-frame))
16480 (mouse-autoselect-window nil) ; Don't let the mouse jump
16481 (calendar-setup
16482 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16483 (calendar-move-hook nil)
16484 (calendar-view-diary-initially-flag nil)
16485 (calendar-view-holidays-initially-flag nil)
16486 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16487 ;; Rationalize `org-def' and `org-defdecode', if required.
16488 (when (< (nth 2 org-defdecode) org-extend-today-until)
16489 (setf (nth 2 org-defdecode) -1)
16490 (setf (nth 1 org-defdecode) 59)
16491 (setq org-def (apply #'encode-time org-defdecode))
16492 (setq org-defdecode (decode-time org-def)))
16493 (let* ((timestr (format-time-string
16494 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16495 org-def))
16496 (prompt (concat (if prompt (concat prompt " ") "")
16497 (format "Date+time [%s]: " timestr))))
16498 (cond
16499 (from-string (setq ans from-string))
16500 (org-read-date-popup-calendar
16501 (save-excursion
16502 (save-window-excursion
16503 (calendar)
16504 (when (eq calendar-setup 'calendar-only)
16505 (setq cal-frame
16506 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16507 (select-frame cal-frame))
16508 (org-eval-in-calendar '(setq cursor-type nil) t)
16509 (unwind-protect
16510 (progn
16511 (calendar-forward-day (- (time-to-days org-def)
16512 (calendar-absolute-from-gregorian
16513 (calendar-current-date))))
16514 (org-eval-in-calendar nil t)
16515 (let* ((old-map (current-local-map))
16516 (map (copy-keymap calendar-mode-map))
16517 (minibuffer-local-map
16518 (copy-keymap org-read-date-minibuffer-local-map)))
16519 (org-defkey map (kbd "RET") 'org-calendar-select)
16520 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16521 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16522 (unwind-protect
16523 (progn
16524 (use-local-map map)
16525 (setq org-read-date-inactive inactive)
16526 (add-hook 'post-command-hook 'org-read-date-display)
16527 (setq org-ans0
16528 (read-string prompt
16529 default-input
16530 'org-read-date-history
16531 nil))
16532 ;; org-ans0: from prompt
16533 ;; org-ans1: from mouse click
16534 ;; org-ans2: from calendar motion
16535 (setq ans
16536 (concat org-ans0 " " (or org-ans1 org-ans2))))
16537 (remove-hook 'post-command-hook 'org-read-date-display)
16538 (use-local-map old-map)
16539 (when org-read-date-overlay
16540 (delete-overlay org-read-date-overlay)
16541 (setq org-read-date-overlay nil)))))
16542 (bury-buffer "*Calendar*")
16543 (when cal-frame
16544 (delete-frame cal-frame)
16545 (select-frame-set-input-focus cur-frame))))))
16547 (t ; Naked prompt only
16548 (unwind-protect
16549 (setq ans (read-string prompt default-input
16550 'org-read-date-history timestr))
16551 (when org-read-date-overlay
16552 (delete-overlay org-read-date-overlay)
16553 (setq org-read-date-overlay nil))))))
16555 (setq final (org-read-date-analyze ans org-def org-defdecode))
16557 (when org-read-date-analyze-forced-year
16558 (message "Year was forced into %s"
16559 (if org-read-date-force-compatible-dates
16560 "compatible range (1970-2037)"
16561 "range representable on this machine"))
16562 (ding))
16564 ;; One round trip to get rid of 34th of August and stuff like that....
16565 (setq final (decode-time (apply 'encode-time final)))
16567 (setq org-read-date-final-answer ans)
16569 (if to-time
16570 (apply 'encode-time final)
16571 (if (and (boundp 'org-time-was-given) org-time-was-given)
16572 (format "%04d-%02d-%02d %02d:%02d"
16573 (nth 5 final) (nth 4 final) (nth 3 final)
16574 (nth 2 final) (nth 1 final))
16575 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16577 (defun org-read-date-display ()
16578 "Display the current date prompt interpretation in the minibuffer."
16579 (when org-read-date-display-live
16580 (when org-read-date-overlay
16581 (delete-overlay org-read-date-overlay))
16582 (when (minibufferp (current-buffer))
16583 (save-excursion
16584 (end-of-line 1)
16585 (while (not (equal (buffer-substring
16586 (max (point-min) (- (point) 4)) (point))
16587 " "))
16588 (insert " ")))
16589 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16590 " " (or org-ans1 org-ans2)))
16591 (org-end-time-was-given nil)
16592 (f (org-read-date-analyze ans org-def org-defdecode))
16593 (fmts (if org-dcst
16594 org-time-stamp-custom-formats
16595 org-time-stamp-formats))
16596 (fmt (if (or org-with-time
16597 (and (boundp 'org-time-was-given) org-time-was-given))
16598 (cdr fmts)
16599 (car fmts)))
16600 (txt (format-time-string fmt (apply 'encode-time f)))
16601 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16602 (txt (concat "=> " txt)))
16603 (when (and org-end-time-was-given
16604 (string-match org-plain-time-of-day-regexp txt))
16605 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16606 org-end-time-was-given
16607 (substring txt (match-end 0)))))
16608 (when org-read-date-analyze-futurep
16609 (setq txt (concat txt " (=>F)")))
16610 (setq org-read-date-overlay
16611 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16612 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16614 (defun org-read-date-analyze (ans def defdecode)
16615 "Analyze the combined answer of the date prompt."
16616 ;; FIXME: cleanup and comment
16617 ;; Pass `current-time' result to `decode-time' (instead of calling
16618 ;; without arguments) so that only `current-time' has to be
16619 ;; overridden in tests.
16620 (let ((org-def def)
16621 (org-defdecode defdecode)
16622 (nowdecode (decode-time (current-time)))
16623 delta deltan deltaw deltadef year month day
16624 hour minute second wday pm h2 m2 tl wday1
16625 iso-year iso-weekday iso-week iso-date futurep kill-year)
16626 (setq org-read-date-analyze-futurep nil
16627 org-read-date-analyze-forced-year nil)
16628 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16629 (setq ans "+0"))
16631 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16632 (setq ans (replace-match "" t t ans)
16633 deltan (car delta)
16634 deltaw (nth 1 delta)
16635 deltadef (nth 2 delta)))
16637 ;; Check if there is an iso week date in there. If yes, store the
16638 ;; info and postpone interpreting it until the rest of the parsing
16639 ;; is done.
16640 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16641 (setq iso-year (when (match-end 1)
16642 (org-small-year-to-year
16643 (string-to-number (match-string 1 ans))))
16644 iso-weekday (when (match-end 3)
16645 (string-to-number (match-string 3 ans)))
16646 iso-week (string-to-number (match-string 2 ans)))
16647 (setq ans (replace-match "" t t ans)))
16649 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16650 (when (string-match
16651 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16652 (setq year (if (match-end 2)
16653 (string-to-number (match-string 2 ans))
16654 (progn (setq kill-year t)
16655 (string-to-number (format-time-string "%Y"))))
16656 month (string-to-number (match-string 3 ans))
16657 day (string-to-number (match-string 4 ans)))
16658 (setq year (org-small-year-to-year year))
16659 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16660 t nil ans)))
16662 ;; Help matching dotted european dates
16663 (when (string-match
16664 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16665 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16666 (setq kill-year t)
16667 (string-to-number (format-time-string "%Y")))
16668 day (string-to-number (match-string 1 ans))
16669 month (string-to-number (match-string 2 ans))
16670 ans (replace-match (format "%04d-%02d-%02d" year month day)
16671 t nil ans)))
16673 ;; Help matching american dates, like 5/30 or 5/30/7
16674 (when (string-match
16675 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16676 (setq year (if (match-end 4)
16677 (string-to-number (match-string 4 ans))
16678 (progn (setq kill-year t)
16679 (string-to-number (format-time-string "%Y"))))
16680 month (string-to-number (match-string 1 ans))
16681 day (string-to-number (match-string 2 ans)))
16682 (setq year (org-small-year-to-year year))
16683 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16684 t nil ans)))
16685 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16686 ;; If there is a time with am/pm, and *no* time without it, we convert
16687 ;; so that matching will be successful.
16688 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16689 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16690 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16691 (setq hour (string-to-number (match-string 1 ans))
16692 minute (if (match-end 3)
16693 (string-to-number (match-string 3 ans))
16695 pm (equal ?p
16696 (string-to-char (downcase (match-string 4 ans)))))
16697 (if (and (= hour 12) (not pm))
16698 (setq hour 0)
16699 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16700 (setq ans (replace-match (format "%02d:%02d" hour minute)
16701 t t ans))))
16703 ;; Check if a time range is given as a duration
16704 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16705 (setq hour (string-to-number (match-string 1 ans))
16706 h2 (+ hour (string-to-number (match-string 3 ans)))
16707 minute (string-to-number (match-string 2 ans))
16708 m2 (+ minute (if (match-end 5) (string-to-number
16709 (match-string 5 ans))0)))
16710 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16711 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16712 t t ans)))
16714 ;; Check if there is a time range
16715 (when (boundp 'org-end-time-was-given)
16716 (setq org-time-was-given nil)
16717 (when (and (string-match org-plain-time-of-day-regexp ans)
16718 (match-end 8))
16719 (setq org-end-time-was-given (match-string 8 ans))
16720 (setq ans (concat (substring ans 0 (match-beginning 7))
16721 (substring ans (match-end 7))))))
16723 (setq tl (parse-time-string ans)
16724 day (or (nth 3 tl) (nth 3 org-defdecode))
16725 month
16726 (cond ((nth 4 tl))
16727 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16728 ;; Day was specified. Make sure DAY+MONTH
16729 ;; combination happens in the future.
16730 ((nth 3 tl)
16731 (setq futurep t)
16732 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16733 (nth 4 nowdecode)))
16734 (t (nth 4 org-defdecode)))
16735 year
16736 (cond ((and (not kill-year) (nth 5 tl)))
16737 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16738 ;; Month was guessed in the future and is at least
16739 ;; equal to NOWDECODE's. Fix year accordingly.
16740 (futurep
16741 (if (or (> month (nth 4 nowdecode))
16742 (>= day (nth 3 nowdecode)))
16743 (nth 5 nowdecode)
16744 (1+ (nth 5 nowdecode))))
16745 ;; Month was specified. Make sure MONTH+YEAR
16746 ;; combination happens in the future.
16747 ((nth 4 tl)
16748 (setq futurep t)
16749 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16750 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16751 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16752 (t (nth 5 nowdecode))))
16753 (t (nth 5 org-defdecode)))
16754 hour (or (nth 2 tl) (nth 2 org-defdecode))
16755 minute (or (nth 1 tl) (nth 1 org-defdecode))
16756 second (or (nth 0 tl) 0)
16757 wday (nth 6 tl))
16759 (when (and (eq org-read-date-prefer-future 'time)
16760 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16761 (equal day (nth 3 nowdecode))
16762 (equal month (nth 4 nowdecode))
16763 (equal year (nth 5 nowdecode))
16764 (nth 2 tl)
16765 (or (< (nth 2 tl) (nth 2 nowdecode))
16766 (and (= (nth 2 tl) (nth 2 nowdecode))
16767 (nth 1 tl)
16768 (< (nth 1 tl) (nth 1 nowdecode)))))
16769 (setq day (1+ day)
16770 futurep t))
16772 ;; Special date definitions below
16773 (cond
16774 (iso-week
16775 ;; There was an iso week
16776 (require 'cal-iso)
16777 (setq futurep nil)
16778 (setq year (or iso-year year)
16779 day (or iso-weekday wday 1)
16780 wday nil ; to make sure that the trigger below does not match
16781 iso-date (calendar-gregorian-from-absolute
16782 (calendar-iso-to-absolute
16783 (list iso-week day year))))
16784 ; FIXME: Should we also push ISO weeks into the future?
16785 ; (when (and org-read-date-prefer-future
16786 ; (not iso-year)
16787 ; (< (calendar-absolute-from-gregorian iso-date)
16788 ; (time-to-days (current-time))))
16789 ; (setq year (1+ year)
16790 ; iso-date (calendar-gregorian-from-absolute
16791 ; (calendar-iso-to-absolute
16792 ; (list iso-week day year)))))
16793 (setq month (car iso-date)
16794 year (nth 2 iso-date)
16795 day (nth 1 iso-date)))
16796 (deltan
16797 (setq futurep nil)
16798 (unless deltadef
16799 ;; Pass `current-time' result to `decode-time' (instead of
16800 ;; calling without arguments) so that only `current-time' has
16801 ;; to be overridden in tests.
16802 (let ((now (decode-time (current-time))))
16803 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16804 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16805 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16806 ((equal deltaw "m") (setq month (+ month deltan)))
16807 ((equal deltaw "y") (setq year (+ year deltan)))))
16808 ((and wday (not (nth 3 tl)))
16809 ;; Weekday was given, but no day, so pick that day in the week
16810 ;; on or after the derived date.
16811 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16812 (unless (equal wday wday1)
16813 (setq day (+ day (% (- wday wday1 -7) 7))))))
16814 (when (and (boundp 'org-time-was-given)
16815 (nth 2 tl))
16816 (setq org-time-was-given t))
16817 (when (< year 100) (setq year (+ 2000 year)))
16818 ;; Check of the date is representable
16819 (if org-read-date-force-compatible-dates
16820 (progn
16821 (when (< year 1970)
16822 (setq year 1970 org-read-date-analyze-forced-year t))
16823 (when (> year 2037)
16824 (setq year 2037 org-read-date-analyze-forced-year t)))
16825 (condition-case nil
16826 (ignore (encode-time second minute hour day month year))
16827 (error
16828 (setq year (nth 5 org-defdecode))
16829 (setq org-read-date-analyze-forced-year t))))
16830 (setq org-read-date-analyze-futurep futurep)
16831 (list second minute hour day month year)))
16833 (defvar parse-time-weekdays)
16834 (defun org-read-date-get-relative (s today default)
16835 "Check string S for special relative date string.
16836 TODAY and DEFAULT are internal times, for today and for a default.
16837 Return shift list (N what def-flag)
16838 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16839 N is the number of WHATs to shift.
16840 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16841 the DEFAULT date rather than TODAY."
16842 (require 'parse-time)
16843 (when (and
16844 (string-match
16845 (concat
16846 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16847 "\\([0-9]+\\)?"
16848 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16849 "\\([ \t]\\|$\\)") s)
16850 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16851 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16852 (string-to-char (substring (match-string 1 s) -1))
16853 ?+))
16854 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16855 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16856 (what (if (match-end 3) (match-string 3 s) "d"))
16857 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16858 (date (if rel default today))
16859 (wday (nth 6 (decode-time date)))
16860 delta)
16861 (if wday1
16862 (progn
16863 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16864 (when (= delta 0) (setq delta 7))
16865 (when (= dir ?-)
16866 (setq delta (- delta 7))
16867 (when (= delta 0) (setq delta -7)))
16868 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16869 (list delta "d" rel))
16870 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16872 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16873 "Turn a user-specified date into the internal representation.
16874 The internal representation needed by the calendar is (month day year).
16875 This is a wrapper to handle the brain-dead convention in calendar that
16876 user function argument order change dependent on argument order."
16877 (pcase calendar-date-style
16878 (`american (list arg1 arg2 arg3))
16879 (`european (list arg2 arg1 arg3))
16880 (`iso (list arg2 arg3 arg1))))
16882 (defun org-eval-in-calendar (form &optional keepdate)
16883 "Eval FORM in the calendar window and return to current window.
16884 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16885 (let ((sf (selected-frame))
16886 (sw (selected-window)))
16887 (select-window (get-buffer-window "*Calendar*" t))
16888 (eval form)
16889 (when (and (not keepdate) (calendar-cursor-to-date))
16890 (let* ((date (calendar-cursor-to-date))
16891 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16892 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16893 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16894 (select-window sw)
16895 (select-frame-set-input-focus sf)))
16897 (defun org-calendar-select ()
16898 "Return to `org-read-date' with the date currently selected.
16899 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16900 (interactive)
16901 (when (calendar-cursor-to-date)
16902 (let* ((date (calendar-cursor-to-date))
16903 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16904 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16905 (when (active-minibuffer-window) (exit-minibuffer))))
16907 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16908 "Insert a date stamp for the date given by the internal TIME.
16909 See `format-time-string' for the format of TIME.
16910 WITH-HM means use the stamp format that includes the time of the day.
16911 INACTIVE means use square brackets instead of angular ones, so that the
16912 stamp will not contribute to the agenda.
16913 PRE and POST are optional strings to be inserted before and after the
16914 stamp.
16915 The command returns the inserted time stamp."
16916 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16917 stamp)
16918 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16919 (insert-before-markers (or pre ""))
16920 (when (listp extra)
16921 (setq extra (car extra))
16922 (if (and (stringp extra)
16923 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16924 (setq extra (format "-%02d:%02d"
16925 (string-to-number (match-string 1 extra))
16926 (string-to-number (match-string 2 extra))))
16927 (setq extra nil)))
16928 (when extra
16929 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16930 (insert-before-markers (setq stamp (format-time-string fmt time)))
16931 (insert-before-markers (or post ""))
16932 (setq org-last-inserted-timestamp stamp)))
16934 (defun org-toggle-time-stamp-overlays ()
16935 "Toggle the use of custom time stamp formats."
16936 (interactive)
16937 (setq org-display-custom-times (not org-display-custom-times))
16938 (unless org-display-custom-times
16939 (let ((p (point-min)) (bmp (buffer-modified-p)))
16940 (while (setq p (next-single-property-change p 'display))
16941 (when (and (get-text-property p 'display)
16942 (eq (get-text-property p 'face) 'org-date))
16943 (remove-text-properties
16944 p (setq p (next-single-property-change p 'display))
16945 '(display t))))
16946 (set-buffer-modified-p bmp)))
16947 (org-restart-font-lock)
16948 (setq org-table-may-need-update t)
16949 (if org-display-custom-times
16950 (message "Time stamps are overlaid with custom format")
16951 (message "Time stamp overlays removed")))
16953 (defun org-display-custom-time (beg end)
16954 "Overlay modified time stamp format over timestamp between BEG and END."
16955 (let* ((ts (buffer-substring beg end))
16956 t1 with-hm tf time str (off 0))
16957 (save-match-data
16958 (setq t1 (org-parse-time-string ts t))
16959 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16960 (setq off (- (match-end 0) (match-beginning 0)))))
16961 (setq end (- end off))
16962 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16963 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16964 time (org-fix-decoded-time t1)
16965 str (org-add-props
16966 (format-time-string
16967 (substring tf 1 -1) (apply 'encode-time time))
16968 nil 'mouse-face 'highlight))
16969 (put-text-property beg end 'display str)))
16971 (defun org-fix-decoded-time (time)
16972 "Set 0 instead of nil for the first 6 elements of time.
16973 Don't touch the rest."
16974 (let ((n 0))
16975 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16977 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16978 "Difference between TIMESTAMP-STRING and now in days.
16979 If SECONDS is non-nil, return the difference in seconds."
16980 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16981 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16982 (funcall fdiff (current-time)))))
16984 (defun org-deadline-close-p (timestamp-string &optional ndays)
16985 "Is the time in TIMESTAMP-STRING close to the current date?"
16986 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16987 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16988 (not (org-entry-is-done-p))))
16990 (defun org-get-wdays (ts &optional delay zero-delay)
16991 "Get the deadline lead time appropriate for timestring TS.
16992 When DELAY is non-nil, get the delay time for scheduled items
16993 instead of the deadline lead time. When ZERO-DELAY is non-nil
16994 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16995 don't try to find the delay cookie in the scheduled timestamp."
16996 (let ((tv (if delay org-scheduled-delay-days
16997 org-deadline-warning-days)))
16998 (cond
16999 ((or (and delay (< tv 0))
17000 (and delay zero-delay (<= tv 0))
17001 (and (not delay) (<= tv 0)))
17002 ;; Enforce this value no matter what
17003 (- tv))
17004 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17005 ;; lead time is specified.
17006 (floor (* (string-to-number (match-string 1 ts))
17007 (cdr (assoc (match-string 2 ts)
17008 '(("d" . 1) ("w" . 7)
17009 ("m" . 30.4) ("y" . 365.25)
17010 ("h" . 0.041667)))))))
17011 ;; go for the default.
17012 (t tv))))
17014 (defun org-calendar-select-mouse (ev)
17015 "Return to `org-read-date' with the date currently selected.
17016 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17017 (interactive "e")
17018 (mouse-set-point ev)
17019 (when (calendar-cursor-to-date)
17020 (let* ((date (calendar-cursor-to-date))
17021 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17022 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17023 (when (active-minibuffer-window) (exit-minibuffer))))
17025 (defun org-check-deadlines (ndays)
17026 "Check if there are any deadlines due or past due.
17027 A deadline is considered due if it happens within `org-deadline-warning-days'
17028 days from today's date. If the deadline appears in an entry marked DONE,
17029 it is not shown. A numeric prefix argument NDAYS can be used to test that
17030 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17031 are shown."
17032 (interactive "P")
17033 (let* ((org-warn-days
17034 (cond
17035 ((equal ndays '(4)) 100000)
17036 (ndays (prefix-numeric-value ndays))
17037 (t (abs org-deadline-warning-days))))
17038 (case-fold-search nil)
17039 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17040 (callback
17041 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17042 (message "%d deadlines past-due or due within %d days"
17043 (org-occur regexp nil callback)
17044 org-warn-days)))
17046 (defsubst org-re-timestamp (type)
17047 "Return a regexp for timestamp TYPE.
17048 Allowed values for TYPE are:
17050 all: all timestamps
17051 active: only active timestamps (<...>)
17052 inactive: only inactive timestamps ([...])
17053 scheduled: only scheduled timestamps
17054 deadline: only deadline timestamps
17055 closed: only closed time-stamps
17057 When TYPE is nil, fall back on returning a regexp that matches
17058 both scheduled and deadline timestamps."
17059 (cl-case type
17060 (all org-ts-regexp-both)
17061 (active org-ts-regexp)
17062 (inactive org-ts-regexp-inactive)
17063 (scheduled org-scheduled-time-regexp)
17064 (deadline org-deadline-time-regexp)
17065 (closed org-closed-time-regexp)
17066 (otherwise
17067 (concat "\\<"
17068 (regexp-opt (list org-deadline-string org-scheduled-string))
17069 " *<\\([^>]+\\)>"))))
17071 (defun org-check-before-date (d)
17072 "Check if there are deadlines or scheduled entries before date D."
17073 (interactive (list (org-read-date)))
17074 (let* ((case-fold-search nil)
17075 (regexp (org-re-timestamp org-ts-type))
17076 (ts-type org-ts-type)
17077 (callback
17078 (lambda ()
17079 (let ((match (match-string 1)))
17080 (and (if (memq ts-type '(active inactive all))
17081 (eq (org-element-type (save-excursion
17082 (backward-char)
17083 (org-element-context)))
17084 'timestamp)
17085 (org-at-planning-p))
17086 (time-less-p
17087 (org-time-string-to-time match)
17088 (org-time-string-to-time d)))))))
17089 (message "%d entries before %s"
17090 (org-occur regexp nil callback)
17091 d)))
17093 (defun org-check-after-date (d)
17094 "Check if there are deadlines or scheduled entries after date D."
17095 (interactive (list (org-read-date)))
17096 (let* ((case-fold-search nil)
17097 (regexp (org-re-timestamp org-ts-type))
17098 (ts-type org-ts-type)
17099 (callback
17100 (lambda ()
17101 (let ((match (match-string 1)))
17102 (and (if (memq ts-type '(active inactive all))
17103 (eq (org-element-type (save-excursion
17104 (backward-char)
17105 (org-element-context)))
17106 'timestamp)
17107 (org-at-planning-p))
17108 (not (time-less-p
17109 (org-time-string-to-time match)
17110 (org-time-string-to-time d))))))))
17111 (message "%d entries after %s"
17112 (org-occur regexp nil callback)
17113 d)))
17115 (defun org-check-dates-range (start-date end-date)
17116 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17117 (interactive (list (org-read-date nil nil nil "Range starts")
17118 (org-read-date nil nil nil "Range end")))
17119 (let ((case-fold-search nil)
17120 (regexp (org-re-timestamp org-ts-type))
17121 (callback
17122 (let ((type org-ts-type))
17123 (lambda ()
17124 (let ((match (match-string 1)))
17125 (and
17126 (if (memq type '(active inactive all))
17127 (eq (org-element-type (save-excursion
17128 (backward-char)
17129 (org-element-context)))
17130 'timestamp)
17131 (org-at-planning-p))
17132 (not (time-less-p
17133 (org-time-string-to-time match)
17134 (org-time-string-to-time start-date)))
17135 (time-less-p
17136 (org-time-string-to-time match)
17137 (org-time-string-to-time end-date))))))))
17138 (message "%d entries between %s and %s"
17139 (org-occur regexp nil callback) start-date end-date)))
17141 (defun org-evaluate-time-range (&optional to-buffer)
17142 "Evaluate a time range by computing the difference between start and end.
17143 Normally the result is just printed in the echo area, but with prefix arg
17144 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17145 If the time range is actually in a table, the result is inserted into the
17146 next column.
17147 For time difference computation, a year is assumed to be exactly 365
17148 days in order to avoid rounding problems."
17149 (interactive "P")
17151 (org-clock-update-time-maybe)
17152 (save-excursion
17153 (unless (org-at-date-range-p t)
17154 (goto-char (point-at-bol))
17155 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17156 (unless (org-at-date-range-p t)
17157 (user-error "Not at a time-stamp range, and none found in current line")))
17158 (let* ((ts1 (match-string 1))
17159 (ts2 (match-string 2))
17160 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17161 (match-end (match-end 0))
17162 (time1 (org-time-string-to-time ts1))
17163 (time2 (org-time-string-to-time ts2))
17164 (t1 (float-time time1))
17165 (t2 (float-time time2))
17166 (diff (abs (- t2 t1)))
17167 (negative (< (- t2 t1) 0))
17168 ;; (ys (floor (* 365 24 60 60)))
17169 (ds (* 24 60 60))
17170 (hs (* 60 60))
17171 (fy "%dy %dd %02d:%02d")
17172 (fy1 "%dy %dd")
17173 (fd "%dd %02d:%02d")
17174 (fd1 "%dd")
17175 (fh "%02d:%02d")
17176 y d h m align)
17177 (if havetime
17178 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17180 d (floor (/ diff ds)) diff (mod diff ds)
17181 h (floor (/ diff hs)) diff (mod diff hs)
17182 m (floor (/ diff 60)))
17183 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17185 d (floor (+ (/ diff ds) 0.5))
17186 h 0 m 0))
17187 (if (not to-buffer)
17188 (message "%s" (org-make-tdiff-string y d h m))
17189 (if (org-at-table-p)
17190 (progn
17191 (goto-char match-end)
17192 (setq align t)
17193 (and (looking-at " *|") (goto-char (match-end 0))))
17194 (goto-char match-end))
17195 (when (looking-at
17196 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17197 (replace-match ""))
17198 (when negative (insert " -"))
17199 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17200 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17201 (insert " " (format fh h m))))
17202 (when align (org-table-align))
17203 (message "Time difference inserted")))))
17205 (defun org-make-tdiff-string (y d h m)
17206 (let ((fmt "")
17207 (l nil))
17208 (when (> y 0)
17209 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17210 (push y l))
17211 (when (> d 0)
17212 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17213 (push d l))
17214 (when (> h 0)
17215 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17216 (push h l))
17217 (when (> m 0)
17218 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17219 (push m l))
17220 (apply 'format fmt (nreverse l))))
17222 (defun org-time-string-to-time (s)
17223 "Convert timestamp string S into internal time."
17224 (apply #'encode-time (org-parse-time-string s)))
17226 (defun org-time-string-to-seconds (s)
17227 "Convert a timestamp string S into a number of seconds."
17228 (float-time (org-time-string-to-time s)))
17230 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17232 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17233 "Convert time stamp S to an absolute day number.
17235 If DAYNR in non-nil, and there is a specifier for a cyclic time
17236 stamp, get the closest date to DAYNR. If PREFER is
17237 `past' (respectively `future') return a date past (respectively
17238 after) or equal to DAYNR.
17240 POS is the location of time stamp S, as a buffer position in
17241 BUFFER.
17243 Diary sexp timestamps are matched against DAYNR, when non-nil.
17244 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17245 signaled."
17246 (cond
17247 ((string-match "\\`%%\\((.*)\\)" s)
17248 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17249 ;; only able to match individual dates. If it fails, raise an
17250 ;; error.
17251 (if (and daynr
17252 (org-diary-sexp-entry
17253 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17254 daynr
17255 (signal 'org-diary-sexp-no-match (list s))))
17256 (daynr (org-closest-date s daynr prefer))
17257 (t (time-to-days
17258 (condition-case errdata
17259 (apply #'encode-time (org-parse-time-string s))
17260 (error (error "Bad timestamp `%s'%s\nError was: %s"
17262 (if (not (and buffer pos)) ""
17263 (format-message " at %d in buffer `%s'" pos buffer))
17264 (cdr errdata))))))))
17266 (defun org-days-to-iso-week (days)
17267 "Return the iso week number."
17268 (require 'cal-iso)
17269 (car (calendar-iso-from-absolute days)))
17271 (defun org-small-year-to-year (year)
17272 "Convert 2-digit years into 4-digit years.
17273 YEAR is expanded into one of the 30 next years, if possible, or
17274 into a past one. Any year larger than 99 is returned unchanged."
17275 (if (>= year 100) year
17276 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17277 (century (/ current 100))
17278 (offset (- year (% current 100))))
17279 (cond ((> offset 30) (+ (* (1- century) 100) year))
17280 ((> offset -70) (+ (* century 100) year))
17281 (t (+ (* (1+ century) 100) year))))))
17283 (defun org-time-from-absolute (d)
17284 "Return the time corresponding to date D.
17285 D may be an absolute day number, or a calendar-type list (month day year)."
17286 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17287 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17289 (defvar org-agenda-current-date)
17290 (defun org-calendar-holiday ()
17291 "List of holidays, for Diary display in Org mode."
17292 (require 'holidays)
17293 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17294 (and hl (mapconcat #'identity hl "; "))))
17296 (defun org-diary-sexp-entry (sexp entry d)
17297 "Process a SEXP diary ENTRY for date D."
17298 (require 'diary-lib)
17299 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17300 ;; dynamically.
17301 (let* ((sexp `(let ((entry ,entry)
17302 (date ',d))
17303 ,(car (read-from-string sexp))))
17304 (result (if calendar-debug-sexp (eval sexp)
17305 (condition-case nil
17306 (eval sexp)
17307 (error
17308 (beep)
17309 (message "Bad sexp at line %d in %s: %s"
17310 (org-current-line)
17311 (buffer-file-name) sexp)
17312 (sleep-for 2))))))
17313 (cond ((stringp result) (split-string result "; "))
17314 ((and (consp result)
17315 (not (consp (cdr result)))
17316 (stringp (cdr result))) (cdr result))
17317 ((and (consp result)
17318 (stringp (car result))) result)
17319 (result entry))))
17321 (defun org-diary-to-ical-string (frombuf)
17322 "Get iCalendar entries from diary entries in buffer FROMBUF.
17323 This uses the icalendar.el library."
17324 (let* ((tmpdir temporary-file-directory)
17325 (tmpfile (make-temp-name
17326 (expand-file-name "orgics" tmpdir)))
17327 buf rtn b e)
17328 (with-current-buffer frombuf
17329 (icalendar-export-region (point-min) (point-max) tmpfile)
17330 (setq buf (find-buffer-visiting tmpfile))
17331 (set-buffer buf)
17332 (goto-char (point-min))
17333 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17334 (setq b (match-beginning 0)))
17335 (goto-char (point-max))
17336 (when (re-search-backward "^END:VEVENT" nil t)
17337 (setq e (match-end 0)))
17338 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17339 (kill-buffer buf)
17340 (delete-file tmpfile)
17341 rtn))
17343 (defun org-closest-date (start current prefer)
17344 "Return closest date to CURRENT starting from START.
17346 CURRENT and START are both time stamps.
17348 When PREFER is `past', return a date that is either CURRENT or
17349 past. When PREFER is `future', return a date that is either
17350 CURRENT or future.
17352 Only time stamps with a repeater are modified. Any other time
17353 stamp stay unchanged. In any case, return value is an absolute
17354 day number."
17355 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17356 ;; No repeater. Do not shift time stamp.
17357 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17358 (let ((value (string-to-number (match-string 1 start)))
17359 (type (match-string 2 start)))
17360 (if (= 0 value)
17361 ;; Repeater with a 0-value is considered as void.
17362 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17363 (let* ((base (org-date-to-gregorian start))
17364 (target (org-date-to-gregorian current))
17365 (sday (calendar-absolute-from-gregorian base))
17366 (cday (calendar-absolute-from-gregorian target))
17367 n1 n2)
17368 ;; If START is already past CURRENT, just return START.
17369 (if (<= cday sday) sday
17370 ;; Compute closest date before (N1) and closest date past
17371 ;; (N2) CURRENT.
17372 (pcase type
17373 ("h"
17374 (let ((missing-hours
17375 (mod (+ (- (* 24 (- cday sday))
17376 (nth 2 (org-parse-time-string start)))
17377 org-extend-today-until)
17378 value)))
17379 (setf n1 (if (= missing-hours 0) cday
17380 (- cday (1+ (/ missing-hours 24)))))
17381 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17382 ((or "d" "w")
17383 (let ((value (if (equal type "w") (* 7 value) value)))
17384 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17385 (setf n2 (+ n1 value))))
17386 ("m"
17387 (let* ((add-months
17388 (lambda (d n)
17389 ;; Add N months to gregorian date D, i.e.,
17390 ;; a list (MONTH DAY YEAR). Return a valid
17391 ;; gregorian date.
17392 (let ((m (+ (nth 0 d) n)))
17393 (list (mod m 12)
17394 (nth 1 d)
17395 (+ (/ m 12) (nth 2 d))))))
17396 (months ; Complete months to TARGET.
17397 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17398 (- (nth 0 target) (nth 0 base))
17399 ;; If START's day is greater than
17400 ;; TARGET's, remove incomplete month.
17401 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17402 value)
17403 value))
17404 (before (funcall add-months base months)))
17405 (setf n1 (calendar-absolute-from-gregorian before))
17406 (setf n2
17407 (calendar-absolute-from-gregorian
17408 (funcall add-months before value)))))
17410 (let* ((d (nth 1 base))
17411 (m (nth 0 base))
17412 (y (nth 2 base))
17413 (years ; Complete years to TARGET.
17414 (* (/ (- (nth 2 target)
17416 ;; If START's month and day are
17417 ;; greater than TARGET's, remove
17418 ;; incomplete year.
17419 (if (or (> (nth 0 target) m)
17420 (and (= (nth 0 target) m)
17421 (> (nth 1 target) d)))
17424 value)
17425 value))
17426 (before (list m d (+ y years))))
17427 (setf n1 (calendar-absolute-from-gregorian before))
17428 (setf n2 (calendar-absolute-from-gregorian
17429 (list m d (+ (nth 2 before) value)))))))
17430 ;; Handle PREFER parameter, if any.
17431 (cond
17432 ((eq prefer 'past) (if (= cday n2) n2 n1))
17433 ((eq prefer 'future) (if (= cday n1) n1 n2))
17434 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17436 (defun org-date-to-gregorian (d)
17437 "Turn any specification of date D into a Gregorian date for the calendar."
17438 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17439 ((and (listp d) (= (length d) 3)) d)
17440 ((stringp d)
17441 (let ((d (org-parse-time-string d)))
17442 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17443 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17445 (defun org-parse-time-string (s &optional nodefault)
17446 "Parse the standard Org time string.
17448 This should be a lot faster than the normal `parse-time-string'.
17450 If time is not given, defaults to 0:00. However, with optional
17451 NODEFAULT, hour and minute fields will be nil if not given."
17452 (cond ((string-match org-ts-regexp0 s)
17453 (list 0
17454 (when (or (match-beginning 8) (not nodefault))
17455 (string-to-number (or (match-string 8 s) "0")))
17456 (when (or (match-beginning 7) (not nodefault))
17457 (string-to-number (or (match-string 7 s) "0")))
17458 (string-to-number (match-string 4 s))
17459 (string-to-number (match-string 3 s))
17460 (string-to-number (match-string 2 s))
17461 nil nil nil))
17462 ((string-match "^<[^>]+>$" s)
17463 ;; FIXME: `decode-time' needs to be called with ZONE as its
17464 ;; second argument. However, this requires at least Emacs
17465 ;; 25.1. We can do it when we switch to this version as our
17466 ;; minimal requirement.
17467 (decode-time (seconds-to-time (org-matcher-time s))))
17468 (t (error "Not a standard Org time string: %s" s))))
17470 (defun org-timestamp-up (&optional arg)
17471 "Increase the date item at the cursor by one.
17472 If the cursor is on the year, change the year. If it is on the month,
17473 the day or the time, change that.
17474 With prefix ARG, change by that many units."
17475 (interactive "p")
17476 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17478 (defun org-timestamp-down (&optional arg)
17479 "Decrease the date item at the cursor by one.
17480 If the cursor is on the year, change the year. If it is on the month,
17481 the day or the time, change that.
17482 With prefix ARG, change by that many units."
17483 (interactive "p")
17484 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17486 (defun org-timestamp-up-day (&optional arg)
17487 "Increase the date in the time stamp by one day.
17488 With prefix ARG, change that many days."
17489 (interactive "p")
17490 (if (and (not (org-at-timestamp-p 'lax))
17491 (org-at-heading-p))
17492 (org-todo 'up)
17493 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17495 (defun org-timestamp-down-day (&optional arg)
17496 "Decrease the date in the time stamp by one day.
17497 With prefix ARG, change that many days."
17498 (interactive "p")
17499 (if (and (not (org-at-timestamp-p 'lax))
17500 (org-at-heading-p))
17501 (org-todo 'down)
17502 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17504 (defun org-at-timestamp-p (&optional extended)
17505 "Non-nil if point is inside a timestamp.
17507 By default, the function only consider syntactically valid active
17508 timestamps. However, the caller may have a broader definition
17509 for timestamps. As a consequence, optional argument EXTENDED can
17510 be set to the following values
17512 `inactive'
17514 Include also syntactically valid inactive timestamps.
17516 `agenda'
17518 Include timestamps allowed in Agenda, i.e., those in
17519 properties drawers, planning lines and clock lines.
17521 `lax'
17523 Ignore context. The function matches any part of the
17524 document looking like a timestamp. This includes comments,
17525 example blocks...
17527 For backward-compatibility with Org 9.0, every other non-nil
17528 value is equivalent to `inactive'.
17530 When at a timestamp, return the position of the point as a symbol
17531 among `bracket', `after', `year', `month', `hour', `minute',
17532 `day' or a number of character from the last know part of the
17533 time stamp.
17535 When matching, the match groups are the following:
17536 group 1: year
17537 group 2: month
17538 group 3: day number
17539 group 4: day name
17540 group 5: hours, if any
17541 group 6: minutes, if any"
17542 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17543 (pos (point))
17544 (match?
17545 (let ((boundaries (org-in-regexp regexp)))
17546 (save-match-data
17547 (cond ((null boundaries) nil)
17548 ((eq extended 'lax) t)
17550 (or (and (eq extended 'agenda)
17551 (or (org-at-planning-p)
17552 (org-at-property-p)
17553 (and (bound-and-true-p
17554 org-agenda-include-inactive-timestamps)
17555 (org-at-clock-log-p))))
17556 (eq 'timestamp
17557 (save-excursion
17558 (when (= pos (cdr boundaries)) (forward-char -1))
17559 (org-element-type (org-element-context)))))))))))
17560 (cond
17561 ((not match?) nil)
17562 ((= pos (match-beginning 0)) 'bracket)
17563 ;; Distinguish location right before the closing bracket from
17564 ;; right after it.
17565 ((= pos (1- (match-end 0))) 'bracket)
17566 ((= pos (match-end 0)) 'after)
17567 ((org-pos-in-match-range pos 2) 'year)
17568 ((org-pos-in-match-range pos 3) 'month)
17569 ((org-pos-in-match-range pos 7) 'hour)
17570 ((org-pos-in-match-range pos 8) 'minute)
17571 ((or (org-pos-in-match-range pos 4)
17572 (org-pos-in-match-range pos 5)) 'day)
17573 ((and (> pos (or (match-end 8) (match-end 5)))
17574 (< pos (match-end 0)))
17575 (- pos (or (match-end 8) (match-end 5))))
17576 (t 'day))))
17578 (defun org-toggle-timestamp-type ()
17579 "Toggle the type (<active> or [inactive]) of a time stamp."
17580 (interactive)
17581 (when (org-at-timestamp-p 'lax)
17582 (let ((beg (match-beginning 0)) (end (match-end 0))
17583 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17584 (save-excursion
17585 (goto-char beg)
17586 (while (re-search-forward "[][<>]" end t)
17587 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17588 t t)))
17589 (message "Timestamp is now %sactive"
17590 (if (equal (char-after beg) ?<) "" "in")))))
17592 (defun org-at-clock-log-p ()
17593 "Non-nil if point is on a clock log line."
17594 (and (org-match-line org-clock-line-re)
17595 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17597 (defvar org-clock-history) ; defined in org-clock.el
17598 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17599 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17600 "Change the date in the time stamp at point.
17601 The date will be changed by N times WHAT. WHAT can be `day', `month',
17602 `year', `minute', `second'. If WHAT is not given, the cursor position
17603 in the timestamp determines what will be changed.
17604 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17605 (let ((origin (point))
17606 (timestamp? (org-at-timestamp-p 'lax))
17607 origin-cat
17608 with-hm inactive
17609 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17610 extra rem
17611 ts time time0 fixnext clrgx)
17612 (unless timestamp? (user-error "Not at a timestamp"))
17613 (if (and (not what) (eq timestamp? 'bracket))
17614 (org-toggle-timestamp-type)
17615 ;; Point isn't on brackets. Remember the part of the time-stamp
17616 ;; the point was in. Indeed, size of time-stamps may change,
17617 ;; but point must be kept in the same category nonetheless.
17618 (setq origin-cat timestamp?)
17619 (when (and (not what) (not (eq timestamp? 'day))
17620 org-display-custom-times
17621 (get-text-property (point) 'display)
17622 (not (get-text-property (1- (point)) 'display)))
17623 (setq timestamp? 'day))
17624 (setq timestamp? (or what timestamp?)
17625 inactive (= (char-after (match-beginning 0)) ?\[)
17626 ts (match-string 0))
17627 (replace-match "")
17628 (when (string-match
17629 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17631 (setq extra (match-string 1 ts))
17632 (when suppress-tmp-delay
17633 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17634 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17635 (setq with-hm t))
17636 (setq time0 (org-parse-time-string ts))
17637 (when (and updown
17638 (eq timestamp? 'minute)
17639 (not current-prefix-arg))
17640 ;; This looks like s-up and s-down. Change by one rounding step.
17641 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17642 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17643 (setcar (cdr time0) (+ (nth 1 time0)
17644 (if (> n 0) (- rem) (- dm rem))))))
17645 (setq time
17646 (apply #'encode-time
17647 (or (car time0) 0)
17648 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17649 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17650 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17651 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17652 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17653 (nthcdr 6 time0)))
17654 (when (and (memq timestamp? '(hour minute))
17655 extra
17656 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17657 (setq extra (org-modify-ts-extra
17658 extra
17659 (if (eq timestamp? 'hour) 2 5)
17660 n dm)))
17661 (when (integerp timestamp?)
17662 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17663 (when (eq what 'calendar)
17664 (let ((cal-date (org-get-date-from-calendar)))
17665 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17666 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17667 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17668 (setcar time0 (or (car time0) 0))
17669 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17670 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17671 (setq time (apply 'encode-time time0))))
17672 ;; Insert the new time-stamp, and ensure point stays in the same
17673 ;; category as before (i.e. not after the last position in that
17674 ;; category).
17675 (let ((pos (point)))
17676 ;; Stay before inserted string. `save-excursion' is of no use.
17677 (setq org-last-changed-timestamp
17678 (org-insert-time-stamp time with-hm inactive nil nil extra))
17679 (goto-char pos))
17680 (save-match-data
17681 (looking-at org-ts-regexp3)
17682 (goto-char
17683 (pcase origin-cat
17684 ;; `day' category ends before `hour' if any, or at the end
17685 ;; of the day name.
17686 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17687 (`hour (min (match-end 7) origin))
17688 (`minute (min (1- (match-end 8)) origin))
17689 ((pred integerp) (min (1- (match-end 0)) origin))
17690 ;; Point was right after the time-stamp. However, the
17691 ;; time-stamp length might have changed, so refer to
17692 ;; (match-end 0) instead.
17693 (`after (match-end 0))
17694 ;; `year' and `month' have both fixed size: point couldn't
17695 ;; have moved into another part.
17696 (_ origin))))
17697 ;; Update clock if on a CLOCK line.
17698 (org-clock-update-time-maybe)
17699 ;; Maybe adjust the closest clock in `org-clock-history'
17700 (when org-clock-adjust-closest
17701 (if (not (and (org-at-clock-log-p)
17702 (< 1 (length (delq nil (mapcar 'marker-position
17703 org-clock-history))))))
17704 (message "No clock to adjust")
17705 (cond ((save-excursion ; fix previous clock?
17706 (re-search-backward org-ts-regexp0 nil t)
17707 (looking-back (concat org-clock-string " \\[")
17708 (line-beginning-position)))
17709 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17710 ((save-excursion ; fix next clock?
17711 (re-search-backward org-ts-regexp0 nil t)
17712 (looking-at (concat org-ts-regexp0 "\\] =>")))
17713 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17714 (save-window-excursion
17715 ;; Find closest clock to point, adjust the previous/next one in history
17716 (let* ((p (save-excursion (org-back-to-heading t)))
17717 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17718 (clfixnth
17719 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17720 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17721 (if (not clfixpos)
17722 (message "No clock to adjust")
17723 (save-excursion
17724 (org-goto-marker-or-bmk clfixpos)
17725 (org-show-subtree)
17726 (when (re-search-forward clrgx nil t)
17727 (goto-char (match-beginning 1))
17728 (let (org-clock-adjust-closest)
17729 (org-timestamp-change n timestamp? updown))
17730 (message "Clock adjusted in %s for heading: %s"
17731 (file-name-nondirectory (buffer-file-name))
17732 (org-get-heading t t)))))))))
17733 ;; Try to recenter the calendar window, if any.
17734 (when (and org-calendar-follow-timestamp-change
17735 (get-buffer-window "*Calendar*" t)
17736 (memq timestamp? '(day month year)))
17737 (org-recenter-calendar (time-to-days time))))))
17739 (defun org-modify-ts-extra (s pos n dm)
17740 "Change the different parts of the lead-time and repeat fields in timestamp."
17741 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17742 ng h m new rem)
17743 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17744 (cond
17745 ((or (org-pos-in-match-range pos 2)
17746 (org-pos-in-match-range pos 3))
17747 (setq m (string-to-number (match-string 3 s))
17748 h (string-to-number (match-string 2 s)))
17749 (if (org-pos-in-match-range pos 2)
17750 (setq h (+ h n))
17751 (setq n (* dm (with-no-warnings (signum n))))
17752 (unless (= 0 (setq rem (% m dm)))
17753 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17754 (setq m (+ m n)))
17755 (when (< m 0) (setq m (+ m 60) h (1- h)))
17756 (when (> m 59) (setq m (- m 60) h (1+ h)))
17757 (setq h (mod h 24))
17758 (setq ng 1 new (format "-%02d:%02d" h m)))
17759 ((org-pos-in-match-range pos 6)
17760 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17761 ((org-pos-in-match-range pos 5)
17762 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17764 ((org-pos-in-match-range pos 9)
17765 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17766 ((org-pos-in-match-range pos 8)
17767 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17769 (when ng
17770 (setq s (concat
17771 (substring s 0 (match-beginning ng))
17773 (substring s (match-end ng))))))
17776 (defun org-recenter-calendar (d)
17777 "If the calendar is visible, recenter it to date D."
17778 (let ((cwin (get-buffer-window "*Calendar*" t)))
17779 (when cwin
17780 (let ((calendar-move-hook nil))
17781 (with-selected-window cwin
17782 (calendar-goto-date
17783 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17785 (defun org-goto-calendar (&optional arg)
17786 "Go to the Emacs calendar at the current date.
17787 If there is a time stamp in the current line, go to that date.
17788 A prefix ARG can be used to force the current date."
17789 (interactive "P")
17790 (let ((calendar-move-hook nil)
17791 (calendar-view-holidays-initially-flag nil)
17792 (calendar-view-diary-initially-flag nil)
17793 diff)
17794 (when (or (org-at-timestamp-p 'lax)
17795 (org-match-line (concat ".*" org-ts-regexp)))
17796 (let ((d1 (time-to-days (current-time)))
17797 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17798 (setq diff (- d2 d1))))
17799 (calendar)
17800 (calendar-goto-today)
17801 (when (and diff (not arg)) (calendar-forward-day diff))))
17803 (defun org-get-date-from-calendar ()
17804 "Return a list (month day year) of date at point in calendar."
17805 (with-current-buffer "*Calendar*"
17806 (save-match-data
17807 (calendar-cursor-to-date))))
17809 (defun org-date-from-calendar ()
17810 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17811 If there is already a time stamp at the cursor position, update it."
17812 (interactive)
17813 (if (org-at-timestamp-p 'lax)
17814 (org-timestamp-change 0 'calendar)
17815 (let ((cal-date (org-get-date-from-calendar)))
17816 (org-insert-time-stamp
17817 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17819 (defcustom org-effort-durations
17820 `(("min" . 1)
17821 ("h" . 60)
17822 ("d" . ,(* 60 8))
17823 ("w" . ,(* 60 8 5))
17824 ("m" . ,(* 60 8 5 4))
17825 ("y" . ,(* 60 8 5 40)))
17826 "Conversion factor to minutes for an effort modifier.
17828 Each entry has the form (MODIFIER . MINUTES).
17830 In an effort string, a number followed by MODIFIER is multiplied
17831 by the specified number of MINUTES to obtain an effort in
17832 minutes.
17834 For example, if the value of this variable is ((\"hours\" . 60)), then an
17835 effort string \"2hours\" is equivalent to 120 minutes."
17836 :group 'org-agenda
17837 :version "26.1"
17838 :package-version '(Org . "8.3")
17839 :type '(alist :key-type (string :tag "Modifier")
17840 :value-type (number :tag "Minutes")))
17842 (defcustom org-image-actual-width t
17843 "Should we use the actual width of images when inlining them?
17845 When set to t, always use the image width.
17847 When set to a number, use imagemagick (when available) to set
17848 the image's width to this value.
17850 When set to a number in a list, try to get the width from any
17851 #+ATTR.* keyword if it matches a width specification like
17853 #+ATTR_HTML: :width 300px
17855 and fall back on that number if none is found.
17857 When set to nil, try to get the width from an #+ATTR.* keyword
17858 and fall back on the original width if none is found.
17860 This requires Emacs >= 24.1, build with imagemagick support."
17861 :group 'org-appearance
17862 :version "24.4"
17863 :package-version '(Org . "8.0")
17864 :type '(choice
17865 (const :tag "Use the image width" t)
17866 (integer :tag "Use a number of pixels")
17867 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17868 (const :tag "Use #+ATTR* or don't resize" nil)))
17870 (defcustom org-agenda-inhibit-startup nil
17871 "Inhibit startup when preparing agenda buffers.
17872 When this variable is t, the initialization of the Org agenda
17873 buffers is inhibited: e.g. the visibility state is not set, the
17874 tables are not re-aligned, etc."
17875 :type 'boolean
17876 :version "24.3"
17877 :group 'org-agenda)
17879 (defcustom org-agenda-ignore-properties nil
17880 "Avoid updating text properties when building the agenda.
17881 Properties are used to prepare buffers for effort estimates,
17882 appointments, statistics and subtree-local categories.
17883 If you don't use these in the agenda, you can add them to this
17884 list and agenda building will be a bit faster.
17885 The value is a list, with zero or more of the symbols `effort', `appt',
17886 `stats' or `category'."
17887 :type '(set :greedy t
17888 (const effort)
17889 (const appt)
17890 (const stats)
17891 (const category))
17892 :version "26.1"
17893 :package-version '(Org . "8.3")
17894 :group 'org-agenda)
17896 ;;;; Files
17898 (defun org-save-all-org-buffers ()
17899 "Save all Org buffers without user confirmation."
17900 (interactive)
17901 (message "Saving all Org buffers...")
17902 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17903 (when (featurep 'org-id) (org-id-locations-save))
17904 (message "Saving all Org buffers... done"))
17906 (defun org-revert-all-org-buffers ()
17907 "Revert all Org buffers.
17908 Prompt for confirmation when there are unsaved changes.
17909 Be sure you know what you are doing before letting this function
17910 overwrite your changes.
17912 This function is useful in a setup where one tracks org files
17913 with a version control system, to revert on one machine after pulling
17914 changes from another. I believe the procedure must be like this:
17916 1. M-x org-save-all-org-buffers
17917 2. Pull changes from the other machine, resolve conflicts
17918 3. M-x org-revert-all-org-buffers"
17919 (interactive)
17920 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17921 (user-error "Abort"))
17922 (save-excursion
17923 (save-window-excursion
17924 (dolist (b (buffer-list))
17925 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17926 (with-current-buffer b buffer-file-name))
17927 (pop-to-buffer-same-window b)
17928 (revert-buffer t 'no-confirm)))
17929 (when (and (featurep 'org-id) org-id-track-globally)
17930 (org-id-locations-load)))))
17932 ;;;; Agenda files
17934 ;;;###autoload
17935 (defun org-switchb (&optional arg)
17936 "Switch between Org buffers.
17938 With `\\[universal-argument]' prefix, restrict available buffers to files.
17940 With `\\[universal-argument] \\[universal-argument]' \
17941 prefix, restrict available buffers to agenda files."
17942 (interactive "P")
17943 (let ((blist (org-buffer-list
17944 (cond ((equal arg '(4)) 'files)
17945 ((equal arg '(16)) 'agenda)))))
17946 (pop-to-buffer-same-window
17947 (completing-read "Org buffer: "
17948 (mapcar #'list (mapcar #'buffer-name blist))
17949 nil t))))
17951 (defun org-buffer-list (&optional predicate exclude-tmp)
17952 "Return a list of Org buffers.
17953 PREDICATE can be `export', `files' or `agenda'.
17955 export restrict the list to Export buffers.
17956 files restrict the list to buffers visiting Org files.
17957 agenda restrict the list to buffers visiting agenda files.
17959 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17960 (let* ((bfn nil)
17961 (agenda-files (and (eq predicate 'agenda)
17962 (mapcar 'file-truename (org-agenda-files t))))
17963 (filter
17964 (cond
17965 ((eq predicate 'files)
17966 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17967 ((eq predicate 'export)
17968 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17969 ((eq predicate 'agenda)
17970 (lambda (b)
17971 (with-current-buffer b
17972 (and (derived-mode-p 'org-mode)
17973 (setq bfn (buffer-file-name b))
17974 (member (file-truename bfn) agenda-files)))))
17975 (t (lambda (b) (with-current-buffer b
17976 (or (derived-mode-p 'org-mode)
17977 (string-match "\\*Org .*Export"
17978 (buffer-name b)))))))))
17979 (delq nil
17980 (mapcar
17981 (lambda(b)
17982 (if (and (funcall filter b)
17983 (or (not exclude-tmp)
17984 (not (string-match "tmp" (buffer-name b)))))
17986 nil))
17987 (buffer-list)))))
17989 (defun org-agenda-files (&optional unrestricted archives)
17990 "Get the list of agenda files.
17991 Optional UNRESTRICTED means return the full list even if a restriction
17992 is currently in place.
17993 When ARCHIVES is t, include all archive files that are really being
17994 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17995 `org-agenda-archives-mode' is t."
17996 (let ((files
17997 (cond
17998 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17999 ((stringp org-agenda-files) (org-read-agenda-file-list))
18000 ((listp org-agenda-files) org-agenda-files)
18001 (t (error "Invalid value of `org-agenda-files'")))))
18002 (setq files (apply 'append
18003 (mapcar (lambda (f)
18004 (if (file-directory-p f)
18005 (directory-files
18006 f t org-agenda-file-regexp)
18007 (list f)))
18008 files)))
18009 (when org-agenda-skip-unavailable-files
18010 (setq files (delq nil
18011 (mapcar (function
18012 (lambda (file)
18013 (and (file-readable-p file) file)))
18014 files))))
18015 (when (or (eq archives t)
18016 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18017 (setq files (org-add-archive-files files)))
18018 files))
18020 (defun org-agenda-file-p (&optional file)
18021 "Return non-nil, if FILE is an agenda file.
18022 If FILE is omitted, use the file associated with the current
18023 buffer."
18024 (let ((fname (or file (buffer-file-name))))
18025 (and fname
18026 (member (file-truename fname)
18027 (mapcar #'file-truename (org-agenda-files t))))))
18029 (defun org-edit-agenda-file-list ()
18030 "Edit the list of agenda files.
18031 Depending on setup, this either uses customize to edit the variable
18032 `org-agenda-files', or it visits the file that is holding the list. In the
18033 latter case, the buffer is set up in a way that saving it automatically kills
18034 the buffer and restores the previous window configuration."
18035 (interactive)
18036 (if (stringp org-agenda-files)
18037 (let ((cw (current-window-configuration)))
18038 (find-file org-agenda-files)
18039 (setq-local org-window-configuration cw)
18040 (add-hook 'after-save-hook
18041 (lambda ()
18042 (set-window-configuration
18043 (prog1 org-window-configuration
18044 (kill-buffer (current-buffer))))
18045 (org-install-agenda-files-menu)
18046 (message "New agenda file list installed"))
18047 nil 'local)
18048 (message "%s" (substitute-command-keys
18049 "Edit list and finish with \\[save-buffer]")))
18050 (customize-variable 'org-agenda-files)))
18052 (defun org-store-new-agenda-file-list (list)
18053 "Set new value for the agenda file list and save it correctly."
18054 (if (stringp org-agenda-files)
18055 (let ((fe (org-read-agenda-file-list t)) b u)
18056 (while (setq b (find-buffer-visiting org-agenda-files))
18057 (kill-buffer b))
18058 (with-temp-file org-agenda-files
18059 (insert
18060 (mapconcat
18061 (lambda (f) ;; Keep un-expanded entries.
18062 (if (setq u (assoc f fe))
18063 (cdr u)
18065 list "\n")
18066 "\n")))
18067 (let ((org-mode-hook nil) (org-inhibit-startup t)
18068 (org-insert-mode-line-in-empty-file nil))
18069 (setq org-agenda-files list)
18070 (customize-save-variable 'org-agenda-files org-agenda-files))))
18072 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18073 "Read the list of agenda files from a file.
18074 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18075 filenames, used by `org-store-new-agenda-file-list' to write back
18076 un-expanded file names."
18077 (when (file-directory-p org-agenda-files)
18078 (error "`org-agenda-files' cannot be a single directory"))
18079 (when (stringp org-agenda-files)
18080 (with-temp-buffer
18081 (insert-file-contents org-agenda-files)
18082 (mapcar
18083 (lambda (f)
18084 (let ((e (expand-file-name (substitute-in-file-name f)
18085 org-directory)))
18086 (if pair-with-expansion
18087 (cons e f)
18088 e)))
18089 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18091 ;;;###autoload
18092 (defun org-cycle-agenda-files ()
18093 "Cycle through the files in `org-agenda-files'.
18094 If the current buffer visits an agenda file, find the next one in the list.
18095 If the current buffer does not, find the first agenda file."
18096 (interactive)
18097 (let* ((fs (or (org-agenda-files t)
18098 (user-error "No agenda files")))
18099 (files (copy-sequence fs))
18100 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18101 file)
18102 (when tcf
18103 (while (and (setq file (pop files))
18104 (not (equal (file-truename file) tcf)))))
18105 (find-file (car (or files fs)))
18106 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18108 (defun org-agenda-file-to-front (&optional to-end)
18109 "Move/add the current file to the top of the agenda file list.
18110 If the file is not present in the list, it is added to the front. If it is
18111 present, it is moved there. With optional argument TO-END, add/move to the
18112 end of the list."
18113 (interactive "P")
18114 (let ((org-agenda-skip-unavailable-files nil)
18115 (file-alist (mapcar (lambda (x)
18116 (cons (file-truename x) x))
18117 (org-agenda-files t)))
18118 (ctf (file-truename
18119 (or buffer-file-name
18120 (user-error "Please save the current buffer to a file"))))
18121 x had)
18122 (setq x (assoc ctf file-alist) had x)
18124 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18125 (if to-end
18126 (setq file-alist (append (delq x file-alist) (list x)))
18127 (setq file-alist (cons x (delq x file-alist))))
18128 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18129 (org-install-agenda-files-menu)
18130 (message "File %s to %s of agenda file list"
18131 (if had "moved" "added") (if to-end "end" "front"))))
18133 (defun org-remove-file (&optional file)
18134 "Remove current file from the list of files in variable `org-agenda-files'.
18135 These are the files which are being checked for agenda entries.
18136 Optional argument FILE means use this file instead of the current."
18137 (interactive)
18138 (let* ((org-agenda-skip-unavailable-files nil)
18139 (file (or file buffer-file-name
18140 (user-error "Current buffer does not visit a file")))
18141 (true-file (file-truename file))
18142 (afile (abbreviate-file-name file))
18143 (files (delq nil (mapcar
18144 (lambda (x)
18145 (unless (equal true-file
18146 (file-truename x))
18148 (org-agenda-files t)))))
18149 (if (not (= (length files) (length (org-agenda-files t))))
18150 (progn
18151 (org-store-new-agenda-file-list files)
18152 (org-install-agenda-files-menu)
18153 (message "Removed from Org Agenda list: %s" afile))
18154 (message "File was not in list: %s (not removed)" afile))))
18156 (defun org-file-menu-entry (file)
18157 (vector file (list 'find-file file) t))
18159 (defun org-check-agenda-file (file)
18160 "Make sure FILE exists. If not, ask user what to do."
18161 (unless (file-exists-p file)
18162 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18163 (abbreviate-file-name file))
18164 (let ((r (downcase (read-char-exclusive))))
18165 (cond
18166 ((equal r ?r)
18167 (org-remove-file file)
18168 (throw 'nextfile t))
18169 (t (user-error "Abort"))))))
18171 (defun org-get-agenda-file-buffer (file)
18172 "Get an agenda buffer visiting FILE.
18173 If the buffer needs to be created, add it to the list of buffers
18174 which might be released later."
18175 (let ((buf (org-find-base-buffer-visiting file)))
18176 (if buf
18177 buf ; just return it
18178 ;; Make a new buffer and remember it
18179 (setq buf (find-file-noselect file))
18180 (when buf (push buf org-agenda-new-buffers))
18181 buf)))
18183 (defun org-release-buffers (blist)
18184 "Release all buffers in list, asking the user for confirmation when needed.
18185 When a buffer is unmodified, it is just killed. When modified, it is saved
18186 \(if the user agrees) and then killed."
18187 (let (file)
18188 (dolist (buf blist)
18189 (setq file (buffer-file-name buf))
18190 (when (and (buffer-modified-p buf)
18191 file
18192 (y-or-n-p (format "Save file %s? " file)))
18193 (with-current-buffer buf (save-buffer)))
18194 (kill-buffer buf))))
18196 (defun org-agenda-prepare-buffers (files)
18197 "Create buffers for all agenda files, protect archived trees and comments."
18198 (interactive)
18199 (let ((pa '(:org-archived t))
18200 (pc '(:org-comment t))
18201 (pall '(:org-archived t :org-comment t))
18202 (inhibit-read-only t)
18203 (org-inhibit-startup org-agenda-inhibit-startup)
18204 (rea (concat ":" org-archive-tag ":"))
18205 re pos)
18206 (setq org-tag-alist-for-agenda nil
18207 org-tag-groups-alist-for-agenda nil)
18208 (save-excursion
18209 (save-restriction
18210 (dolist (file files)
18211 (catch 'nextfile
18212 (if (bufferp file)
18213 (set-buffer file)
18214 (org-check-agenda-file file)
18215 (set-buffer (org-get-agenda-file-buffer file)))
18216 (widen)
18217 (org-set-regexps-and-options 'tags-only)
18218 (setq pos (point))
18219 (or (memq 'category org-agenda-ignore-properties)
18220 (org-refresh-category-properties))
18221 (or (memq 'stats org-agenda-ignore-properties)
18222 (org-refresh-stats-properties))
18223 (or (memq 'effort org-agenda-ignore-properties)
18224 (org-refresh-effort-properties))
18225 (or (memq 'appt org-agenda-ignore-properties)
18226 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18227 (setq org-todo-keywords-for-agenda
18228 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18229 (setq org-done-keywords-for-agenda
18230 (append org-done-keywords-for-agenda org-done-keywords))
18231 (setq org-todo-keyword-alist-for-agenda
18232 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18233 (setq org-tag-alist-for-agenda
18234 (org-uniquify
18235 (append org-tag-alist-for-agenda
18236 org-current-tag-alist)))
18237 ;; Merge current file's tag groups into global
18238 ;; `org-tag-groups-alist-for-agenda'.
18239 (when org-group-tags
18240 (dolist (alist org-tag-groups-alist)
18241 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18242 (if old
18243 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18244 (push alist org-tag-groups-alist-for-agenda)))))
18245 (org-with-silent-modifications
18246 (save-excursion
18247 (remove-text-properties (point-min) (point-max) pall)
18248 (when org-agenda-skip-archived-trees
18249 (goto-char (point-min))
18250 (while (re-search-forward rea nil t)
18251 (when (org-at-heading-p t)
18252 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18253 (goto-char (point-min))
18254 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18255 (while (re-search-forward re nil t)
18256 (when (save-match-data (org-in-commented-heading-p t))
18257 (add-text-properties
18258 (match-beginning 0) (org-end-of-subtree t) pc)))))
18259 (goto-char pos)))))
18260 (setq org-todo-keywords-for-agenda
18261 (org-uniquify org-todo-keywords-for-agenda))
18262 (setq org-todo-keyword-alist-for-agenda
18263 (org-uniquify org-todo-keyword-alist-for-agenda))))
18266 ;;;; CDLaTeX minor mode
18268 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18269 "Keymap for the minor `org-cdlatex-mode'.")
18271 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18272 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18273 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18274 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18275 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18277 (defvar org-cdlatex-texmathp-advice-is-done nil
18278 "Flag remembering if we have applied the advice to texmathp already.")
18280 (define-minor-mode org-cdlatex-mode
18281 "Toggle the minor `org-cdlatex-mode'.
18282 This mode supports entering LaTeX environment and math in LaTeX fragments
18283 in Org mode.
18284 \\{org-cdlatex-mode-map}"
18285 nil " OCDL" nil
18286 (when org-cdlatex-mode
18287 (require 'cdlatex)
18288 (run-hooks 'cdlatex-mode-hook)
18289 (cdlatex-compute-tables))
18290 (unless org-cdlatex-texmathp-advice-is-done
18291 (setq org-cdlatex-texmathp-advice-is-done t)
18292 (defadvice texmathp (around org-math-always-on activate)
18293 "Always return t in Org buffers.
18294 This is because we want to insert math symbols without dollars even outside
18295 the LaTeX math segments. If Org mode thinks that point is actually inside
18296 an embedded LaTeX fragment, let `texmathp' do its job.
18297 `\\[org-cdlatex-mode-map]'"
18298 (interactive)
18299 (let (p)
18300 (cond
18301 ((not (derived-mode-p 'org-mode)) ad-do-it)
18302 ((eq this-command 'cdlatex-math-symbol)
18303 (setq ad-return-value t
18304 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18306 (let ((p (org-inside-LaTeX-fragment-p)))
18307 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18308 (setq ad-return-value t
18309 texmathp-why '("Org mode embedded math" . 0))
18310 (when p ad-do-it)))))))))
18312 (defun turn-on-org-cdlatex ()
18313 "Unconditionally turn on `org-cdlatex-mode'."
18314 (org-cdlatex-mode 1))
18316 (defun org-try-cdlatex-tab ()
18317 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18318 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18319 - inside a LaTeX fragment, or
18320 - after the first word in a line, where an abbreviation expansion could
18321 insert a LaTeX environment."
18322 (when org-cdlatex-mode
18323 (cond
18324 ;; Before any word on the line: No expansion possible.
18325 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18326 ;; Just after first word on the line: Expand it. Make sure it
18327 ;; cannot happen on headlines, though.
18328 ((save-excursion
18329 (skip-chars-backward "a-zA-Z0-9*")
18330 (skip-chars-backward " \t")
18331 (and (bolp) (not (org-at-heading-p))))
18332 (cdlatex-tab) t)
18333 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18335 (defun org-cdlatex-underscore-caret (&optional _arg)
18336 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18337 Revert to the normal definition outside of these fragments."
18338 (interactive "P")
18339 (if (org-inside-LaTeX-fragment-p)
18340 (call-interactively 'cdlatex-sub-superscript)
18341 (let (org-cdlatex-mode)
18342 (call-interactively (key-binding (vector last-input-event))))))
18344 (defun org-cdlatex-math-modify (&optional _arg)
18345 "Execute `cdlatex-math-modify' in LaTeX fragments.
18346 Revert to the normal definition outside of these fragments."
18347 (interactive "P")
18348 (if (org-inside-LaTeX-fragment-p)
18349 (call-interactively 'cdlatex-math-modify)
18350 (let (org-cdlatex-mode)
18351 (call-interactively (key-binding (vector last-input-event))))))
18353 (defun org-cdlatex-environment-indent (&optional environment item)
18354 "Execute `cdlatex-environment' and indent the inserted environment.
18356 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18358 The inserted environment is indented to current indentation
18359 unless point is at the beginning of the line, in which the
18360 environment remains unintended."
18361 (interactive)
18362 ;; cdlatex-environment always return nil. Therefore, capture output
18363 ;; first and determine if an environment was selected.
18364 (let* ((beg (point-marker))
18365 (end (copy-marker (point) t))
18366 (inserted (progn
18367 (ignore-errors (cdlatex-environment environment item))
18368 (< beg end)))
18369 ;; Figure out how many lines to move forward after the
18370 ;; environment has been inserted.
18371 (lines (when inserted
18372 (save-excursion
18373 (- (cl-loop while (< beg (point))
18374 with x = 0
18375 do (forward-line -1)
18376 (cl-incf x)
18377 finally return x)
18378 (if (progn (goto-char beg)
18379 (and (progn (skip-chars-forward " \t") (eolp))
18380 (progn (skip-chars-backward " \t") (bolp))))
18381 1 0)))))
18382 (env (org-trim (delete-and-extract-region beg end))))
18383 (when inserted
18384 ;; Get indentation of next line unless at column 0.
18385 (let ((ind (if (bolp) 0
18386 (save-excursion
18387 (org-return-indent)
18388 (prog1 (org-get-indentation)
18389 (when (progn (skip-chars-forward " \t") (eolp))
18390 (delete-region beg (point)))))))
18391 (bol (progn (skip-chars-backward " \t") (bolp))))
18392 ;; Insert a newline before environment unless at column zero
18393 ;; to "escape" the current line. Insert a newline if
18394 ;; something is one the same line as \end{ENVIRONMENT}.
18395 (insert
18396 (concat (unless bol "\n") env
18397 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18398 (unless (zerop ind)
18399 (save-excursion
18400 (goto-char beg)
18401 (while (< (point) end)
18402 (unless (eolp) (indent-line-to ind))
18403 (forward-line))))
18404 (goto-char beg)
18405 (forward-line lines)
18406 (indent-line-to ind)))
18407 (set-marker beg nil)
18408 (set-marker end nil)))
18411 ;;;; LaTeX fragments
18413 (defun org-inside-LaTeX-fragment-p ()
18414 "Test if point is inside a LaTeX fragment.
18415 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18416 sequence appearing also before point.
18417 Even though the matchers for math are configurable, this function assumes
18418 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18419 delimiters are skipped when they have been removed by customization.
18420 The return value is nil, or a cons cell with the delimiter and the
18421 position of this delimiter.
18423 This function does a reasonably good job, but can locally be fooled by
18424 for example currency specifications. For example it will assume being in
18425 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18426 fragments that are properly closed, but during editing, we have to live
18427 with the uncertainty caused by missing closing delimiters. This function
18428 looks only before point, not after."
18429 (catch 'exit
18430 (let ((pos (point))
18431 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18432 (lim (save-excursion (org-backward-paragraph) (point)))
18433 dd-on str (start 0) m re)
18434 (goto-char pos)
18435 (when dodollar
18436 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18437 re (nth 1 (assoc "$" org-latex-regexps)))
18438 (while (string-match re str start)
18439 (cond
18440 ((= (match-end 0) (length str))
18441 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18442 ((= (match-end 0) (- (length str) 5))
18443 (throw 'exit nil))
18444 (t (setq start (match-end 0))))))
18445 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18446 (goto-char pos)
18447 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18448 (and (match-beginning 2) (throw 'exit nil))
18449 ;; count $$
18450 (while (re-search-backward "\\$\\$" lim t)
18451 (setq dd-on (not dd-on)))
18452 (goto-char pos)
18453 (when dd-on (cons "$$" m))))))
18455 (defun org-inside-latex-macro-p ()
18456 "Is point inside a LaTeX macro or its arguments?"
18457 (save-match-data
18458 (org-in-regexp
18459 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18461 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18462 "Build an overlay between BEG and END using IMAGE file.
18463 Argument IMAGETYPE is the extension of the displayed image,
18464 as a string. It defaults to \"png\"."
18465 (let ((ov (make-overlay beg end))
18466 (imagetype (or (intern imagetype) 'png)))
18467 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18468 (overlay-put ov 'evaporate t)
18469 (overlay-put ov
18470 'modification-hooks
18471 (list (lambda (o _flag _beg _end &optional _l)
18472 (delete-overlay o))))
18473 (overlay-put ov
18474 'display
18475 (list 'image :type imagetype :file image :ascent 'center))))
18477 (defun org--list-latex-overlays (&optional beg end)
18478 "List all Org LaTeX overlays in current buffer.
18479 Limit to overlays between BEG and END when those are provided."
18480 (cl-remove-if-not
18481 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18482 (overlays-in (or beg (point-min)) (or end (point-max)))))
18484 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18485 "Remove all overlays with LaTeX fragment images in current buffer.
18486 When optional arguments BEG and END are non-nil, remove all
18487 overlays between them instead. Return a non-nil value when some
18488 overlays were removed, nil otherwise."
18489 (let ((overlays (org--list-latex-overlays beg end)))
18490 (mapc #'delete-overlay overlays)
18491 overlays))
18493 (defun org-toggle-latex-fragment (&optional arg)
18494 "Preview the LaTeX fragment at point, or all locally or globally.
18496 If the cursor is on a LaTeX fragment, create the image and overlay
18497 it over the source code, if there is none. Remove it otherwise.
18498 If there is no fragment at point, display all fragments in the
18499 current section.
18501 With prefix ARG, preview or clear image for all fragments in the
18502 current subtree or in the whole buffer when used before the first
18503 headline. With a prefix ARG `\\[universal-argument] \
18504 \\[universal-argument]' preview or clear images
18505 for all fragments in the buffer."
18506 (interactive "P")
18507 (when (display-graphic-p)
18508 (catch 'exit
18509 (save-excursion
18510 (let (beg end msg)
18511 (cond
18512 ((or (equal arg '(16))
18513 (and (equal arg '(4))
18514 (org-with-limited-levels (org-before-first-heading-p))))
18515 (if (org-remove-latex-fragment-image-overlays)
18516 (progn (message "LaTeX fragments images removed from buffer")
18517 (throw 'exit nil))
18518 (setq msg "Creating images for buffer...")))
18519 ((equal arg '(4))
18520 (org-with-limited-levels (org-back-to-heading t))
18521 (setq beg (point))
18522 (setq end (progn (org-end-of-subtree t) (point)))
18523 (if (org-remove-latex-fragment-image-overlays beg end)
18524 (progn
18525 (message "LaTeX fragment images removed from subtree")
18526 (throw 'exit nil))
18527 (setq msg "Creating images for subtree...")))
18528 ((let ((datum (org-element-context)))
18529 (when (memq (org-element-type datum)
18530 '(latex-environment latex-fragment))
18531 (setq beg (org-element-property :begin datum))
18532 (setq end (org-element-property :end datum))
18533 (if (org-remove-latex-fragment-image-overlays beg end)
18534 (progn (message "LaTeX fragment image removed")
18535 (throw 'exit nil))
18536 (setq msg "Creating image...")))))
18538 (org-with-limited-levels
18539 (setq beg (if (org-at-heading-p) (line-beginning-position)
18540 (outline-previous-heading)
18541 (point)))
18542 (setq end (progn (outline-next-heading) (point)))
18543 (if (org-remove-latex-fragment-image-overlays beg end)
18544 (progn
18545 (message "LaTeX fragment images removed from section")
18546 (throw 'exit nil))
18547 (setq msg "Creating images for section...")))))
18548 (let ((file (buffer-file-name (buffer-base-buffer))))
18549 (org-format-latex
18550 (concat org-preview-latex-image-directory "org-ltximg")
18551 beg end
18552 ;; Emacs cannot overlay images from remote hosts. Create
18553 ;; it in `temporary-file-directory' instead.
18554 (if (or (not file) (file-remote-p file))
18555 temporary-file-directory
18556 default-directory)
18557 'overlays msg 'forbuffer org-preview-latex-default-process))
18558 (message (concat msg "done")))))))
18560 (defun org-format-latex
18561 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18562 "Replace LaTeX fragments with links to an image.
18564 The function takes care of creating the replacement image.
18566 Only consider fragments between BEG and END when those are
18567 provided.
18569 When optional argument OVERLAYS is non-nil, display the image on
18570 top of the fragment instead of replacing it.
18572 PROCESSING-TYPE is the conversion method to use, as a symbol.
18574 Some of the options can be changed using the variable
18575 `org-format-latex-options', which see."
18576 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18577 (unless (eq processing-type 'verbatim)
18578 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18579 (cnt 0)
18580 checkdir-flag)
18581 (goto-char (or beg (point-min)))
18582 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18583 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18584 (overlay-recenter (or end (point-max))))
18585 (while (re-search-forward math-regexp end t)
18586 (unless (and overlays
18587 (eq (get-char-property (point) 'org-overlay-type)
18588 'org-latex-overlay))
18589 (let* ((context (org-element-context))
18590 (type (org-element-type context)))
18591 (when (memq type '(latex-environment latex-fragment))
18592 (let ((block-type (eq type 'latex-environment))
18593 (value (org-element-property :value context))
18594 (beg (org-element-property :begin context))
18595 (end (save-excursion
18596 (goto-char (org-element-property :end context))
18597 (skip-chars-backward " \r\t\n")
18598 (point))))
18599 (cond
18600 ((eq processing-type 'mathjax)
18601 ;; Prepare for MathJax processing.
18602 (if (not (string-match "\\`\\$\\$?" value))
18603 (goto-char end)
18604 (delete-region beg end)
18605 (if (string= (match-string 0 value) "$$")
18606 (insert "\\[" (substring value 2 -2) "\\]")
18607 (insert "\\(" (substring value 1 -1) "\\)"))))
18608 ((assq processing-type org-preview-latex-process-alist)
18609 ;; Process to an image.
18610 (cl-incf cnt)
18611 (goto-char beg)
18612 (let* ((processing-info
18613 (cdr (assq processing-type org-preview-latex-process-alist)))
18614 (face (face-at-point))
18615 ;; Get the colors from the face at point.
18617 (let ((color (plist-get org-format-latex-options
18618 :foreground)))
18619 (if (and forbuffer (eq color 'auto))
18620 (face-attribute face :foreground nil 'default)
18621 color)))
18623 (let ((color (plist-get org-format-latex-options
18624 :background)))
18625 (if (and forbuffer (eq color 'auto))
18626 (face-attribute face :background nil 'default)
18627 color)))
18628 (hash (sha1 (prin1-to-string
18629 (list org-format-latex-header
18630 org-latex-default-packages-alist
18631 org-latex-packages-alist
18632 org-format-latex-options
18633 forbuffer value fg bg))))
18634 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18635 (absprefix (expand-file-name prefix dir))
18636 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18637 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18638 (sep (and block-type "\n\n"))
18639 (link (concat sep "[[file:" linkfile "]]" sep))
18640 (options
18641 (org-combine-plists
18642 org-format-latex-options
18643 `(:foreground ,fg :background ,bg))))
18644 (when msg (message msg cnt))
18645 (unless checkdir-flag ; Ensure the directory exists.
18646 (setq checkdir-flag t)
18647 (let ((todir (file-name-directory absprefix)))
18648 (unless (file-directory-p todir)
18649 (make-directory todir t))))
18650 (unless (file-exists-p movefile)
18651 (org-create-formula-image
18652 value movefile options forbuffer processing-type))
18653 (if overlays
18654 (progn
18655 (dolist (o (overlays-in beg end))
18656 (when (eq (overlay-get o 'org-overlay-type)
18657 'org-latex-overlay)
18658 (delete-overlay o)))
18659 (org--format-latex-make-overlay beg end movefile imagetype)
18660 (goto-char end))
18661 (delete-region beg end)
18662 (insert
18663 (org-add-props link
18664 (list 'org-latex-src
18665 (replace-regexp-in-string "\"" "" value)
18666 'org-latex-src-embed-type
18667 (if block-type 'paragraph 'character)))))))
18668 ((eq processing-type 'mathml)
18669 ;; Process to MathML.
18670 (unless (org-format-latex-mathml-available-p)
18671 (user-error "LaTeX to MathML converter not configured"))
18672 (cl-incf cnt)
18673 (when msg (message msg cnt))
18674 (goto-char beg)
18675 (delete-region beg end)
18676 (insert (org-format-latex-as-mathml
18677 value block-type prefix dir)))
18679 (error "Unknown conversion process %s for LaTeX fragments"
18680 processing-type)))))))))))
18682 (defun org-create-math-formula (latex-frag &optional mathml-file)
18683 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18684 Use `org-latex-to-mathml-convert-command'. If the conversion is
18685 sucessful, return the portion between \"<math...> </math>\"
18686 elements otherwise return nil. When MATHML-FILE is specified,
18687 write the results in to that file. When invoked as an
18688 interactive command, prompt for LATEX-FRAG, with initial value
18689 set to the current active region and echo the results for user
18690 inspection."
18691 (interactive (list (let ((frag (when (org-region-active-p)
18692 (buffer-substring-no-properties
18693 (region-beginning) (region-end)))))
18694 (read-string "LaTeX Fragment: " frag nil frag))))
18695 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18696 (let* ((tmp-in-file
18697 (let ((file (file-relative-name
18698 (make-temp-name (expand-file-name "ltxmathml-in")))))
18699 (write-region latex-frag nil file)
18700 file))
18701 (tmp-out-file (file-relative-name
18702 (make-temp-name (expand-file-name "ltxmathml-out"))))
18703 (cmd (format-spec
18704 org-latex-to-mathml-convert-command
18705 `((?j . ,(and org-latex-to-mathml-jar-file
18706 (shell-quote-argument
18707 (expand-file-name
18708 org-latex-to-mathml-jar-file))))
18709 (?I . ,(shell-quote-argument tmp-in-file))
18710 (?i . ,latex-frag)
18711 (?o . ,(shell-quote-argument tmp-out-file)))))
18712 mathml shell-command-output)
18713 (when (called-interactively-p 'any)
18714 (unless (org-format-latex-mathml-available-p)
18715 (user-error "LaTeX to MathML converter not configured")))
18716 (message "Running %s" cmd)
18717 (setq shell-command-output (shell-command-to-string cmd))
18718 (setq mathml
18719 (when (file-readable-p tmp-out-file)
18720 (with-current-buffer (find-file-noselect tmp-out-file t)
18721 (goto-char (point-min))
18722 (when (re-search-forward
18723 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18724 (regexp-quote
18725 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18726 nil t)
18727 (prog1 (match-string 0) (kill-buffer))))))
18728 (cond
18729 (mathml
18730 (setq mathml
18731 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18732 (when mathml-file
18733 (write-region mathml nil mathml-file))
18734 (when (called-interactively-p 'any)
18735 (message mathml)))
18736 ((message "LaTeX to MathML conversion failed")
18737 (message shell-command-output)))
18738 (delete-file tmp-in-file)
18739 (when (file-exists-p tmp-out-file)
18740 (delete-file tmp-out-file))
18741 mathml))
18743 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18744 prefix &optional dir)
18745 "Use `org-create-math-formula' but check local cache first."
18746 (let* ((absprefix (expand-file-name prefix dir))
18747 (print-length nil) (print-level nil)
18748 (formula-id (concat
18749 "formula-"
18750 (sha1
18751 (prin1-to-string
18752 (list latex-frag
18753 org-latex-to-mathml-convert-command)))))
18754 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18755 (formula-cache-dir (file-name-directory formula-cache)))
18757 (unless (file-directory-p formula-cache-dir)
18758 (make-directory formula-cache-dir t))
18760 (unless (file-exists-p formula-cache)
18761 (org-create-math-formula latex-frag formula-cache))
18763 (if (file-exists-p formula-cache)
18764 ;; Successful conversion. Return the link to MathML file.
18765 (org-add-props
18766 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18767 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18768 'org-latex-src-embed-type (if latex-frag-type
18769 'paragraph 'character)))
18770 ;; Failed conversion. Return the LaTeX fragment verbatim
18771 latex-frag)))
18773 (defun org--get-display-dpi ()
18774 "Get the DPI of the display.
18775 The function assumes that the display has the same pixel width in
18776 the horizontal and vertical directions."
18777 (if (display-graphic-p)
18778 (round (/ (display-pixel-height)
18779 (/ (display-mm-height) 25.4)))
18780 (error "Attempt to calculate the dpi of a non-graphic display")))
18782 (defun org-create-formula-image
18783 (string tofile options buffer &optional processing-type)
18784 "Create an image from LaTeX source using external processes.
18786 The LaTeX STRING is saved to a temporary LaTeX file, then
18787 converted to an image file by process PROCESSING-TYPE defined in
18788 `org-preview-latex-process-alist'. A nil value defaults to
18789 `org-preview-latex-default-process'.
18791 The generated image file is eventually moved to TOFILE.
18793 The OPTIONS argument controls the size, foreground color and
18794 background color of the generated image.
18796 When BUFFER non-nil, this function is used for LaTeX previewing.
18797 Otherwise, it is used to deal with LaTeX snippets showed in
18798 a HTML file."
18799 (let* ((processing-type (or processing-type
18800 org-preview-latex-default-process))
18801 (processing-info
18802 (cdr (assq processing-type org-preview-latex-process-alist)))
18803 (programs (plist-get processing-info :programs))
18804 (error-message (or (plist-get processing-info :message) ""))
18805 (use-xcolor (plist-get processing-info :use-xcolor))
18806 (image-input-type (plist-get processing-info :image-input-type))
18807 (image-output-type (plist-get processing-info :image-output-type))
18808 (post-clean (or (plist-get processing-info :post-clean)
18809 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18810 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18811 (latex-header
18812 (or (plist-get processing-info :latex-header)
18813 (org-latex-make-preamble
18814 (org-export-get-environment (org-export-get-backend 'latex))
18815 org-format-latex-header
18816 'snippet)))
18817 (latex-compiler (plist-get processing-info :latex-compiler))
18818 (image-converter (plist-get processing-info :image-converter))
18819 (tmpdir temporary-file-directory)
18820 (texfilebase (make-temp-name
18821 (expand-file-name "orgtex" tmpdir)))
18822 (texfile (concat texfilebase ".tex"))
18823 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18824 '(1.0 . 1.0)))
18825 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18826 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18827 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18828 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18829 "Black"))
18830 (bg (or (plist-get options (if buffer :background :html-background))
18831 "Transparent"))
18832 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18833 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18834 (dolist (program programs)
18835 (org-check-external-command program error-message))
18836 (if use-xcolor
18837 (progn (if (eq fg 'default)
18838 (setq fg (org-latex-color :foreground))
18839 (setq fg (org-latex-color-format fg)))
18840 (if (eq bg 'default)
18841 (setq bg (org-latex-color :background))
18842 (setq bg (org-latex-color-format
18843 (if (string= bg "Transparent") "white" bg))))
18844 (with-temp-file texfile
18845 (insert latex-header)
18846 (insert "\n\\begin{document}\n"
18847 "\\definecolor{fg}{rgb}{" fg "}\n"
18848 "\\definecolor{bg}{rgb}{" bg "}\n"
18849 "\n\\pagecolor{bg}\n"
18850 "\n{\\color{fg}\n"
18851 string
18852 "\n}\n"
18853 "\n\\end{document}\n")))
18854 (if (eq fg 'default)
18855 (setq fg (org-dvipng-color :foreground))
18856 (unless (string= fg "Transparent")
18857 (setq fg (org-dvipng-color-format fg))))
18858 (if (eq bg 'default)
18859 (setq bg (org-dvipng-color :background))
18860 (unless (string= bg "Transparent")
18861 (setq bg (org-dvipng-color-format bg))))
18862 (with-temp-file texfile
18863 (insert latex-header)
18864 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18866 (let* ((err-msg (format "Please adjust `%s' part of \
18867 `org-preview-latex-process-alist'."
18868 processing-type))
18869 (image-input-file
18870 (org-compile-file
18871 texfile latex-compiler image-input-type err-msg log-buf))
18872 (image-output-file
18873 (org-compile-file
18874 image-input-file image-converter image-output-type err-msg log-buf
18875 `((?F . ,(shell-quote-argument fg))
18876 (?B . ,(shell-quote-argument bg))
18877 (?D . ,(shell-quote-argument (format "%s" dpi)))
18878 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18879 (copy-file image-output-file tofile 'replace)
18880 (dolist (e post-clean)
18881 (when (file-exists-p (concat texfilebase e))
18882 (delete-file (concat texfilebase e))))
18883 image-output-file)))
18885 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18886 "Fill a LaTeX header template TPL.
18887 In the template, the following place holders will be recognized:
18889 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18890 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18891 [PACKAGES] \\usepackage statements for PKG
18892 [NO-PACKAGES] do not include PKG
18893 [EXTRA] the string EXTRA
18894 [NO-EXTRA] do not include EXTRA
18896 For backward compatibility, if both the positive and the negative place
18897 holder is missing, the positive one (without the \"NO-\") will be
18898 assumed to be present at the end of the template.
18899 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18900 EXTRA is a string.
18901 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18902 (let (rpl (end ""))
18903 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18904 (setq rpl (if (or (match-end 1) (not def-pkg))
18905 "" (org-latex-packages-to-string def-pkg snippets-p t))
18906 tpl (replace-match rpl t t tpl))
18907 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18909 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18910 (setq rpl (if (or (match-end 1) (not pkg))
18911 "" (org-latex-packages-to-string pkg snippets-p t))
18912 tpl (replace-match rpl t t tpl))
18913 (when pkg (setq end
18914 (concat end "\n"
18915 (org-latex-packages-to-string pkg snippets-p)))))
18917 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18918 (setq rpl (if (or (match-end 1) (not extra))
18919 "" (concat extra "\n"))
18920 tpl (replace-match rpl t t tpl))
18921 (when (and extra (string-match "\\S-" extra))
18922 (setq end (concat end "\n" extra))))
18924 (if (string-match "\\S-" end)
18925 (concat tpl "\n" end)
18926 tpl)))
18928 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18929 "Turn an alist of packages into a string with the \\usepackage macros."
18930 (setq pkg (mapconcat (lambda(p)
18931 (cond
18932 ((stringp p) p)
18933 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18934 (format "%% Package %s omitted" (cadr p)))
18935 ((equal "" (car p))
18936 (format "\\usepackage{%s}" (cadr p)))
18938 (format "\\usepackage[%s]{%s}"
18939 (car p) (cadr p)))))
18941 "\n"))
18942 (if newline (concat pkg "\n") pkg))
18944 (defun org-dvipng-color (attr)
18945 "Return a RGB color specification for dvipng."
18946 (org-dvipng-color-format (face-attribute 'default attr nil)))
18948 (defun org-dvipng-color-format (color-name)
18949 "Convert COLOR-NAME to a RGB color value for dvipng."
18950 (apply #'format "rgb %s %s %s"
18951 (mapcar 'org-normalize-color
18952 (color-values color-name))))
18954 (defun org-latex-color (attr)
18955 "Return a RGB color for the LaTeX color package."
18956 (org-latex-color-format (face-attribute 'default attr nil)))
18958 (defun org-latex-color-format (color-name)
18959 "Convert COLOR-NAME to a RGB color value."
18960 (apply #'format "%s,%s,%s"
18961 (mapcar 'org-normalize-color
18962 (color-values color-name))))
18964 (defun org-normalize-color (value)
18965 "Return string to be used as color value for an RGB component."
18966 (format "%g" (/ value 65535.0)))
18970 ;; Image display
18972 (defvar-local org-inline-image-overlays nil)
18974 (defun org-toggle-inline-images (&optional include-linked)
18975 "Toggle the display of inline images.
18976 INCLUDE-LINKED is passed to `org-display-inline-images'."
18977 (interactive "P")
18978 (if org-inline-image-overlays
18979 (progn
18980 (org-remove-inline-images)
18981 (when (called-interactively-p 'interactive)
18982 (message "Inline image display turned off")))
18983 (org-display-inline-images include-linked)
18984 (when (called-interactively-p 'interactive)
18985 (message (if org-inline-image-overlays
18986 (format "%d images displayed inline"
18987 (length org-inline-image-overlays))
18988 "No images to display inline")))))
18990 (defun org-redisplay-inline-images ()
18991 "Refresh the display of inline images."
18992 (interactive)
18993 (if (not org-inline-image-overlays)
18994 (org-toggle-inline-images)
18995 (org-toggle-inline-images)
18996 (org-toggle-inline-images)))
18998 (defun org-display-inline-images (&optional include-linked refresh beg end)
18999 "Display inline images.
19001 An inline image is a link which follows either of these
19002 conventions:
19004 1. Its path is a file with an extension matching return value
19005 from `image-file-name-regexp' and it has no contents.
19007 2. Its description consists in a single link of the previous
19008 type.
19010 When optional argument INCLUDE-LINKED is non-nil, also links with
19011 a text description part will be inlined. This can be nice for
19012 a quick look at those images, but it does not reflect what
19013 exported files will look like.
19015 When optional argument REFRESH is non-nil, refresh existing
19016 images between BEG and END. This will create new image displays
19017 only if necessary. BEG and END default to the buffer
19018 boundaries."
19019 (interactive "P")
19020 (when (display-graphic-p)
19021 (unless refresh
19022 (org-remove-inline-images)
19023 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19024 (org-with-wide-buffer
19025 (goto-char (or beg (point-min)))
19026 (let* ((case-fold-search t)
19027 (file-extension-re (image-file-name-regexp))
19028 (link-abbrevs (mapcar #'car
19029 (append org-link-abbrev-alist-local
19030 org-link-abbrev-alist)))
19031 ;; Check absolute, relative file names and explicit
19032 ;; "file:" links. Also check link abbreviations since
19033 ;; some might expand to "file" links.
19034 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19035 (if (not link-abbrevs) ""
19036 (format "\\|\\(?:%s:\\)"
19037 (regexp-opt link-abbrevs))))))
19038 (while (re-search-forward file-types-re end t)
19039 (let ((link (save-match-data (org-element-context))))
19040 ;; Check if we're at an inline image, i.e., an image file
19041 ;; link without a description (unless INCLUDE-LINKED is
19042 ;; non-nil).
19043 (when (and (equal "file" (org-element-property :type link))
19044 (or include-linked
19045 (null (org-element-contents link)))
19046 (string-match-p file-extension-re
19047 (org-element-property :path link)))
19048 (let ((file (expand-file-name
19049 (org-link-unescape
19050 (org-element-property :path link)))))
19051 (when (file-exists-p file)
19052 (let ((width
19053 ;; Apply `org-image-actual-width' specifications.
19054 (cond
19055 ((not (image-type-available-p 'imagemagick)) nil)
19056 ((eq org-image-actual-width t) nil)
19057 ((listp org-image-actual-width)
19059 ;; First try to find a width among
19060 ;; attributes associated to the paragraph
19061 ;; containing link.
19062 (let ((paragraph
19063 (let ((e link))
19064 (while (and (setq e (org-element-property
19065 :parent e))
19066 (not (eq (org-element-type e)
19067 'paragraph))))
19068 e)))
19069 (when paragraph
19070 (save-excursion
19071 (goto-char (org-element-property :begin paragraph))
19072 (when
19073 (re-search-forward
19074 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19075 (org-element-property
19076 :post-affiliated paragraph)
19078 (string-to-number (match-string 1))))))
19079 ;; Otherwise, fall-back to provided number.
19080 (car org-image-actual-width)))
19081 ((numberp org-image-actual-width)
19082 org-image-actual-width)))
19083 (old (get-char-property-and-overlay
19084 (org-element-property :begin link)
19085 'org-image-overlay)))
19086 (if (and (car-safe old) refresh)
19087 (image-refresh (overlay-get (cdr old) 'display))
19088 (let ((image (create-image file
19089 (and width 'imagemagick)
19091 :width width)))
19092 (when image
19093 (let ((ov (make-overlay
19094 (org-element-property :begin link)
19095 (progn
19096 (goto-char
19097 (org-element-property :end link))
19098 (skip-chars-backward " \t")
19099 (point)))))
19100 (overlay-put ov 'display image)
19101 (overlay-put ov 'face 'default)
19102 (overlay-put ov 'org-image-overlay t)
19103 (overlay-put
19104 ov 'modification-hooks
19105 (list 'org-display-inline-remove-overlay))
19106 (push ov org-inline-image-overlays)))))))))))))))
19108 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19109 "Remove inline-display overlay if a corresponding region is modified."
19110 (let ((inhibit-modification-hooks t))
19111 (when (and ov after)
19112 (delete ov org-inline-image-overlays)
19113 (delete-overlay ov))))
19115 (defun org-remove-inline-images ()
19116 "Remove inline display of images."
19117 (interactive)
19118 (mapc #'delete-overlay org-inline-image-overlays)
19119 (setq org-inline-image-overlays nil))
19121 ;;;; Key bindings
19123 (defun org-remap (map &rest commands)
19124 "In MAP, remap the functions given in COMMANDS.
19125 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19126 (let (new old)
19127 (while commands
19128 (setq old (pop commands) new (pop commands))
19129 (org-defkey map (vector 'remap old) new))))
19131 ;; Outline functions from `outline-mode-prefix-map'
19132 ;; that can be remapped in Org:
19133 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19134 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19135 (define-key org-mode-map [remap outline-forward-same-level]
19136 'org-forward-heading-same-level)
19137 (define-key org-mode-map [remap outline-backward-same-level]
19138 'org-backward-heading-same-level)
19139 (define-key org-mode-map [remap outline-show-branches]
19140 'org-kill-note-or-show-branches)
19141 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19142 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19143 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19144 (define-key org-mode-map [remap outline-next-visible-heading]
19145 'org-next-visible-heading)
19146 (define-key org-mode-map [remap outline-previous-visible-heading]
19147 'org-previous-visible-heading)
19148 (define-key org-mode-map [remap show-children] 'org-show-children)
19150 ;; Outline functions from `outline-mode-prefix-map' that can not
19151 ;; be remapped in Org:
19153 ;; - the column "key binding" shows whether the Outline function is still
19154 ;; available in Org mode on the same key that it has been bound to in
19155 ;; Outline mode:
19156 ;; - "overridden": key used for a different functionality in Org mode
19157 ;; - else: key still bound to the same Outline function in Org mode
19159 ;; | Outline function | key binding | Org replacement |
19160 ;; |------------------------------------+-------------+--------------------------|
19161 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19162 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19163 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19164 ;; | `show-entry' | overridden | no replacement |
19165 ;; | `show-branches' | `C-c C-k' | still same function |
19166 ;; | `show-subtree' | overridden | visibility cycling |
19167 ;; | `show-all' | overridden | no replacement |
19168 ;; | `hide-subtree' | overridden | visibility cycling |
19169 ;; | `hide-body' | overridden | no replacement |
19170 ;; | `hide-entry' | overridden | visibility cycling |
19171 ;; | `hide-leaves' | overridden | no replacement |
19172 ;; | `hide-sublevels' | overridden | no replacement |
19173 ;; | `hide-other' | overridden | no replacement |
19175 ;; Make `C-c C-x' a prefix key
19176 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19178 ;; TAB key with modifiers
19179 (org-defkey org-mode-map "\C-i" 'org-cycle)
19180 (org-defkey org-mode-map [(tab)] 'org-cycle)
19181 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19182 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19184 ;; The following line is necessary under Suse GNU/Linux
19185 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19186 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19187 (define-key org-mode-map [backtab] 'org-shifttab)
19189 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19190 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19191 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19193 ;; Cursor keys with modifiers
19194 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19195 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19196 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19197 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19199 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19200 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19201 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19202 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19203 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19204 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19206 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19207 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19208 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19209 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19211 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19212 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19213 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19214 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19216 ;; Babel keys
19217 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19218 (dolist (pair org-babel-key-bindings)
19219 (define-key org-babel-map (car pair) (cdr pair)))
19221 ;;; Extra keys for tty access.
19222 ;; We only set them when really needed because otherwise the
19223 ;; menus don't show the simple keys
19225 (when (or org-use-extra-keys (not window-system))
19226 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19227 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19228 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19229 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19230 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19231 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19232 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19233 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19234 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19235 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19236 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19237 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19238 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19239 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19240 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19241 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19242 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19243 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19244 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19245 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19246 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19247 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19248 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19249 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19250 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19251 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19252 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19253 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19255 ;; All the other keys
19256 (org-remap org-mode-map
19257 'self-insert-command 'org-self-insert-command
19258 'delete-char 'org-delete-char
19259 'delete-backward-char 'org-delete-backward-char)
19260 (org-defkey org-mode-map "|" 'org-force-self-insert)
19262 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19263 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19264 (if (boundp 'narrow-map)
19265 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19266 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19267 (if (boundp 'narrow-map)
19268 (org-defkey narrow-map "b" 'org-narrow-to-block)
19269 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19270 (if (boundp 'narrow-map)
19271 (org-defkey narrow-map "e" 'org-narrow-to-element)
19272 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19273 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19274 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19275 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19276 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19277 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19278 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19279 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19280 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19281 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19282 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19283 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19284 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19285 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19286 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19287 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19288 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19289 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19290 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19291 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19292 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19293 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19294 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19295 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19296 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19297 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19298 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19299 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19300 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19301 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19302 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19303 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19304 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19305 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19306 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19307 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19308 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19309 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19310 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19311 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19312 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19313 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19314 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19315 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19316 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19317 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19318 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19319 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19320 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19321 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19322 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19323 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19324 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19325 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19326 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19327 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19328 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19329 (org-defkey org-mode-map "\C-c^" 'org-sort)
19330 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19331 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19332 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19333 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19334 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19335 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19336 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19337 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19338 (org-defkey org-mode-map "\C-m" 'org-return)
19339 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19340 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19341 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19342 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19343 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19344 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19345 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19346 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19347 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19348 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19349 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19350 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19351 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19352 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19353 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19354 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19355 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19356 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19357 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19358 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19359 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19360 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19361 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19362 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19363 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19365 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19366 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19367 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19369 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19370 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19371 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19372 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19373 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19374 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19375 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19376 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19377 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19378 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19379 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19380 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19381 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19382 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19383 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19384 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19385 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19386 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19387 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19388 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19389 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19390 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19391 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19393 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19394 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19395 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19396 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19397 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19399 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19401 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19403 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19404 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19406 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19409 (defconst org-speed-commands-default
19411 ("Outline Navigation")
19412 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19413 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19414 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19415 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19416 ("F" . org-next-block)
19417 ("B" . org-previous-block)
19418 ("u" . (org-speed-move-safe 'outline-up-heading))
19419 ("j" . org-goto)
19420 ("g" . (org-refile t))
19421 ("Outline Visibility")
19422 ("c" . org-cycle)
19423 ("C" . org-shifttab)
19424 (" " . org-display-outline-path)
19425 ("s" . org-narrow-to-subtree)
19426 ("=" . org-columns)
19427 ("Outline Structure Editing")
19428 ("U" . org-metaup)
19429 ("D" . org-metadown)
19430 ("r" . org-metaright)
19431 ("l" . org-metaleft)
19432 ("R" . org-shiftmetaright)
19433 ("L" . org-shiftmetaleft)
19434 ("i" . (progn (forward-char 1) (call-interactively
19435 'org-insert-heading-respect-content)))
19436 ("^" . org-sort)
19437 ("w" . org-refile)
19438 ("a" . org-archive-subtree-default-with-confirmation)
19439 ("@" . org-mark-subtree)
19440 ("#" . org-toggle-comment)
19441 ("Clock Commands")
19442 ("I" . org-clock-in)
19443 ("O" . org-clock-out)
19444 ("Meta Data Editing")
19445 ("t" . org-todo)
19446 ("," . (org-priority))
19447 ("0" . (org-priority ?\ ))
19448 ("1" . (org-priority ?A))
19449 ("2" . (org-priority ?B))
19450 ("3" . (org-priority ?C))
19451 (":" . org-set-tags-command)
19452 ("e" . org-set-effort)
19453 ("E" . org-inc-effort)
19454 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19455 (org-entry-put (point) "APPT_WARNTIME" m)))
19456 ("Agenda Views etc")
19457 ("v" . org-agenda)
19458 ("/" . org-sparse-tree)
19459 ("Misc")
19460 ("o" . org-open-at-point)
19461 ("?" . org-speed-command-help)
19462 ("<" . (org-agenda-set-restriction-lock 'subtree))
19463 (">" . (org-agenda-remove-restriction-lock))
19465 "The default speed commands.")
19467 (defun org-print-speed-command (e)
19468 (if (> (length (car e)) 1)
19469 (progn
19470 (princ "\n")
19471 (princ (car e))
19472 (princ "\n")
19473 (princ (make-string (length (car e)) ?-))
19474 (princ "\n"))
19475 (princ (car e))
19476 (princ " ")
19477 (if (symbolp (cdr e))
19478 (princ (symbol-name (cdr e)))
19479 (prin1 (cdr e)))
19480 (princ "\n")))
19482 (defun org-speed-command-help ()
19483 "Show the available speed commands."
19484 (interactive)
19485 (if (not org-use-speed-commands)
19486 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19487 (with-output-to-temp-buffer "*Help*"
19488 (princ "User-defined Speed commands\n===========================\n")
19489 (mapc #'org-print-speed-command org-speed-commands-user)
19490 (princ "\n")
19491 (princ "Built-in Speed commands\n=======================\n")
19492 (mapc #'org-print-speed-command org-speed-commands-default))
19493 (with-current-buffer "*Help*"
19494 (setq truncate-lines t))))
19496 (defun org-speed-move-safe (cmd)
19497 "Execute CMD, but make sure that the cursor always ends up in a headline.
19498 If not, return to the original position and throw an error."
19499 (interactive)
19500 (let ((pos (point)))
19501 (call-interactively cmd)
19502 (unless (and (bolp) (org-at-heading-p))
19503 (goto-char pos)
19504 (error "Boundary reached while executing %s" cmd))))
19506 (defvar org-self-insert-command-undo-counter 0)
19508 (defvar org-table-auto-blank-field) ; defined in org-table.el
19509 (defvar org-speed-command nil)
19511 (defun org-speed-command-activate (keys)
19512 "Hook for activating single-letter speed commands.
19513 `org-speed-commands-default' specifies a minimal command set.
19514 Use `org-speed-commands-user' for further customization."
19515 (when (or (and (bolp) (looking-at org-outline-regexp))
19516 (and (functionp org-use-speed-commands)
19517 (funcall org-use-speed-commands)))
19518 (cdr (assoc keys (append org-speed-commands-user
19519 org-speed-commands-default)))))
19521 (defun org-babel-speed-command-activate (keys)
19522 "Hook for activating single-letter code block commands."
19523 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19524 (cdr (assoc keys org-babel-key-bindings))))
19526 (defcustom org-speed-command-hook
19527 '(org-speed-command-activate org-babel-speed-command-activate)
19528 "Hook for activating speed commands at strategic locations.
19529 Hook functions are called in sequence until a valid handler is
19530 found.
19532 Each hook takes a single argument, a user-pressed command key
19533 which is also a `self-insert-command' from the global map.
19535 Within the hook, examine the cursor position and the command key
19536 and return nil or a valid handler as appropriate. Handler could
19537 be one of an interactive command, a function, or a form.
19539 Set `org-use-speed-commands' to non-nil value to enable this
19540 hook. The default setting is `org-speed-command-activate'."
19541 :group 'org-structure
19542 :version "24.1"
19543 :type 'hook)
19545 (defun org-self-insert-command (N)
19546 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19547 If the cursor is in a table looking at whitespace, the whitespace is
19548 overwritten, and the table is not marked as requiring realignment."
19549 (interactive "p")
19550 (org-check-before-invisible-edit 'insert)
19551 (cond
19552 ((and org-use-speed-commands
19553 (let ((kv (this-command-keys-vector)))
19554 (setq org-speed-command
19555 (run-hook-with-args-until-success
19556 'org-speed-command-hook
19557 (make-string 1 (aref kv (1- (length kv))))))))
19558 (cond
19559 ((commandp org-speed-command)
19560 (setq this-command org-speed-command)
19561 (call-interactively org-speed-command))
19562 ((functionp org-speed-command)
19563 (funcall org-speed-command))
19564 ((and org-speed-command (listp org-speed-command))
19565 (eval org-speed-command))
19566 (t (let (org-use-speed-commands)
19567 (call-interactively 'org-self-insert-command)))))
19568 ((and
19569 (org-at-table-p)
19570 (eq N 1)
19571 (not (org-region-active-p))
19572 (progn
19573 ;; Check if we blank the field, and if that triggers align.
19574 (and (featurep 'org-table) org-table-auto-blank-field
19575 (memq last-command
19576 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19577 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19578 ;; Got extra space, this field does not determine
19579 ;; column width.
19580 (let (org-table-may-need-update) (org-table-blank-field))
19581 ;; No extra space, this field may determine column
19582 ;; width.
19583 (org-table-blank-field)))
19585 (looking-at "[^|\n]* \\( \\)|"))
19586 ;; There is room for insertion without re-aligning the table.
19587 (delete-region (match-beginning 1) (match-end 1))
19588 (self-insert-command N))
19590 (setq org-table-may-need-update t)
19591 (self-insert-command N)
19592 (org-fix-tags-on-the-fly)
19593 (when org-self-insert-cluster-for-undo
19594 (if (not (eq last-command 'org-self-insert-command))
19595 (setq org-self-insert-command-undo-counter 1)
19596 (if (>= org-self-insert-command-undo-counter 20)
19597 (setq org-self-insert-command-undo-counter 1)
19598 (and (> org-self-insert-command-undo-counter 0)
19599 buffer-undo-list (listp buffer-undo-list)
19600 (not (cadr buffer-undo-list)) ; remove nil entry
19601 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19602 (setq org-self-insert-command-undo-counter
19603 (1+ org-self-insert-command-undo-counter))))))))
19605 (defun org-check-before-invisible-edit (kind)
19606 "Check is editing if kind KIND would be dangerous with invisible text around.
19607 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19608 ;; First, try to get out of here as quickly as possible, to reduce overhead
19609 (when (and org-catch-invisible-edits
19610 (or (not (boundp 'visible-mode)) (not visible-mode))
19611 (or (get-char-property (point) 'invisible)
19612 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19613 ;; OK, we need to take a closer look. Do not consider
19614 ;; invisibility obtained through text properties (e.g., link
19615 ;; fontification), as it cannot be toggled.
19616 (let* ((invisible-at-point
19617 (pcase (get-char-property-and-overlay (point) 'invisible)
19618 (`(,_ . ,(and (pred overlayp) o)) o)))
19619 ;; Assume that point cannot land in the middle of an
19620 ;; overlay, or between two overlays.
19621 (invisible-before-point
19622 (and (not invisible-at-point)
19623 (not (bobp))
19624 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19625 (`(,_ . ,(and (pred overlayp) o)) o))))
19626 (border-and-ok-direction
19628 ;; Check if we are acting predictably before invisible
19629 ;; text.
19630 (and invisible-at-point
19631 (memq kind '(insert delete-backward)))
19632 ;; Check if we are acting predictably after invisible text
19633 ;; This works not well, and I have turned it off. It seems
19634 ;; better to always show and stop after invisible text.
19635 ;; (and (not invisible-at-point) invisible-before-point
19636 ;; (memq kind '(insert delete)))
19638 (when (or invisible-at-point invisible-before-point)
19639 (when (eq org-catch-invisible-edits 'error)
19640 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19641 (if (and org-custom-properties-overlays
19642 (y-or-n-p "Display invisible properties in this buffer? "))
19643 (org-toggle-custom-properties-visibility)
19644 ;; Make the area visible
19645 (save-excursion
19646 (when invisible-before-point
19647 (goto-char
19648 (previous-single-char-property-change (point) 'invisible)))
19649 ;; Remove whatever overlay is currently making yet-to-be
19650 ;; edited text invisible. Also remove nested invisibility
19651 ;; related overlays.
19652 (delete-overlay (or invisible-at-point invisible-before-point))
19653 (let ((origin (if invisible-at-point (point) (1- (point)))))
19654 (while (pcase (get-char-property-and-overlay origin 'invisible)
19655 (`(,_ . ,(and (pred overlayp) o))
19656 (delete-overlay o)
19657 t)))))
19658 (cond
19659 ((eq org-catch-invisible-edits 'show)
19660 ;; That's it, we do the edit after showing
19661 (message
19662 "Unfolding invisible region around point before editing")
19663 (sit-for 1))
19664 ((and (eq org-catch-invisible-edits 'smart)
19665 border-and-ok-direction)
19666 (message "Unfolding invisible region around point before editing"))
19668 ;; Don't do the edit, make the user repeat it in full visibility
19669 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19671 (defun org-fix-tags-on-the-fly ()
19672 "Align tags in headline at point.
19673 Unlike to `org-set-tags', it ignores region and sorting."
19674 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19675 (org-at-heading-p))
19676 (let ((org-ignore-region t)
19677 (org-tags-sort-function nil))
19678 (org-set-tags nil t))))
19680 (defun org-delete-backward-char (N)
19681 "Like `delete-backward-char', insert whitespace at field end in tables.
19682 When deleting backwards, in tables this function will insert whitespace in
19683 front of the next \"|\" separator, to keep the table aligned. The table will
19684 still be marked for re-alignment if the field did fill the entire column,
19685 because, in this case the deletion might narrow the column."
19686 (interactive "p")
19687 (save-match-data
19688 (org-check-before-invisible-edit 'delete-backward)
19689 (if (and (org-at-table-p)
19690 (eq N 1)
19691 (not (org-region-active-p))
19692 (string-match "|" (buffer-substring (point-at-bol) (point)))
19693 (looking-at ".*?|"))
19694 (let ((pos (point))
19695 (noalign (looking-at "[^|\n\r]* |"))
19696 (c org-table-may-need-update))
19697 (backward-delete-char N)
19698 (unless overwrite-mode
19699 (skip-chars-forward "^|")
19700 (insert " ")
19701 (goto-char (1- pos)))
19702 ;; noalign: if there were two spaces at the end, this field
19703 ;; does not determine the width of the column.
19704 (when noalign (setq org-table-may-need-update c)))
19705 (backward-delete-char N)
19706 (org-fix-tags-on-the-fly))))
19708 (defun org-delete-char (N)
19709 "Like `delete-char', but insert whitespace at field end in tables.
19710 When deleting characters, in tables this function will insert whitespace in
19711 front of the next \"|\" separator, to keep the table aligned. The table will
19712 still be marked for re-alignment if the field did fill the entire column,
19713 because, in this case the deletion might narrow the column."
19714 (interactive "p")
19715 (save-match-data
19716 (org-check-before-invisible-edit 'delete)
19717 (if (and (org-at-table-p)
19718 (not (bolp))
19719 (not (= (char-after) ?|))
19720 (eq N 1))
19721 (if (looking-at ".*?|")
19722 (let ((pos (point))
19723 (noalign (looking-at "[^|\n\r]* |"))
19724 (c org-table-may-need-update))
19725 (replace-match
19726 (concat (substring (match-string 0) 1 -1) " |") nil t)
19727 (goto-char pos)
19728 ;; noalign: if there were two spaces at the end, this field
19729 ;; does not determine the width of the column.
19730 (when noalign (setq org-table-may-need-update c)))
19731 (delete-char N))
19732 (delete-char N)
19733 (org-fix-tags-on-the-fly))))
19735 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19736 (put 'org-self-insert-command 'delete-selection
19737 (lambda ()
19738 (not (run-hook-with-args-until-success
19739 'self-insert-uses-region-functions))))
19740 (put 'orgtbl-self-insert-command 'delete-selection
19741 (lambda ()
19742 (not (run-hook-with-args-until-success
19743 'self-insert-uses-region-functions))))
19744 (put 'org-delete-char 'delete-selection 'supersede)
19745 (put 'org-delete-backward-char 'delete-selection 'supersede)
19746 (put 'org-yank 'delete-selection 'yank)
19748 ;; Make `flyspell-mode' delay after some commands
19749 (put 'org-self-insert-command 'flyspell-delayed t)
19750 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19751 (put 'org-delete-char 'flyspell-delayed t)
19752 (put 'org-delete-backward-char 'flyspell-delayed t)
19754 ;; Make pabbrev-mode expand after Org mode commands
19755 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19756 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19758 (defun org-transpose-words ()
19759 "Transpose words for Org.
19760 This uses the `org-mode-transpose-word-syntax-table' syntax
19761 table, which interprets characters in `org-emphasis-alist' as
19762 word constituents."
19763 (interactive)
19764 (with-syntax-table org-mode-transpose-word-syntax-table
19765 (call-interactively 'transpose-words)))
19766 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19768 (defvar org-ctrl-c-ctrl-c-hook nil
19769 "Hook for functions attaching themselves to `C-c C-c'.
19771 This can be used to add additional functionality to the C-c C-c
19772 key which executes context-dependent commands. This hook is run
19773 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19774 run after the last test.
19776 Each function will be called with no arguments. The function
19777 must check if the context is appropriate for it to act. If yes,
19778 it should do its thing and then return a non-nil value. If the
19779 context is wrong, just do nothing and return nil.")
19781 (defvar org-ctrl-c-ctrl-c-final-hook nil
19782 "Hook for functions attaching themselves to `C-c C-c'.
19784 This can be used to add additional functionality to the C-c C-c
19785 key which executes context-dependent commands. This hook is run
19786 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19787 before the first test.
19789 Each function will be called with no arguments. The function
19790 must check if the context is appropriate for it to act. If yes,
19791 it should do its thing and then return a non-nil value. If the
19792 context is wrong, just do nothing and return nil.")
19794 (defvar org-tab-first-hook nil
19795 "Hook for functions to attach themselves to TAB.
19796 See `org-ctrl-c-ctrl-c-hook' for more information.
19797 This hook runs as the first action when TAB is pressed, even before
19798 `org-cycle' messes around with the `outline-regexp' to cater for
19799 inline tasks and plain list item folding.
19800 If any function in this hook returns t, any other actions that
19801 would have been caused by TAB (such as table field motion or visibility
19802 cycling) will not occur.")
19804 (defvar org-tab-after-check-for-table-hook nil
19805 "Hook for functions to attach themselves to TAB.
19806 See `org-ctrl-c-ctrl-c-hook' for more information.
19807 This hook runs after it has been established that the cursor is not in a
19808 table, but before checking if the cursor is in a headline or if global cycling
19809 should be done.
19810 If any function in this hook returns t, not other actions like visibility
19811 cycling will be done.")
19813 (defvar org-tab-after-check-for-cycling-hook nil
19814 "Hook for functions to attach themselves to TAB.
19815 See `org-ctrl-c-ctrl-c-hook' for more information.
19816 This hook runs after it has been established that not table field motion and
19817 not visibility should be done because of current context. This is probably
19818 the place where a package like yasnippets can hook in.")
19820 (defvar org-tab-before-tab-emulation-hook nil
19821 "Hook for functions to attach themselves to TAB.
19822 See `org-ctrl-c-ctrl-c-hook' for more information.
19823 This hook runs after every other options for TAB have been exhausted, but
19824 before indentation and \t insertion takes place.")
19826 (defvar org-metaleft-hook nil
19827 "Hook for functions attaching themselves to `M-left'.
19828 See `org-ctrl-c-ctrl-c-hook' for more information.")
19829 (defvar org-metaright-hook nil
19830 "Hook for functions attaching themselves to `M-right'.
19831 See `org-ctrl-c-ctrl-c-hook' for more information.")
19832 (defvar org-metaup-hook nil
19833 "Hook for functions attaching themselves to `M-up'.
19834 See `org-ctrl-c-ctrl-c-hook' for more information.")
19835 (defvar org-metadown-hook nil
19836 "Hook for functions attaching themselves to `M-down'.
19837 See `org-ctrl-c-ctrl-c-hook' for more information.")
19838 (defvar org-shiftmetaleft-hook nil
19839 "Hook for functions attaching themselves to `M-S-left'.
19840 See `org-ctrl-c-ctrl-c-hook' for more information.")
19841 (defvar org-shiftmetaright-hook nil
19842 "Hook for functions attaching themselves to `M-S-right'.
19843 See `org-ctrl-c-ctrl-c-hook' for more information.")
19844 (defvar org-shiftmetaup-hook nil
19845 "Hook for functions attaching themselves to `M-S-up'.
19846 See `org-ctrl-c-ctrl-c-hook' for more information.")
19847 (defvar org-shiftmetadown-hook nil
19848 "Hook for functions attaching themselves to `M-S-down'.
19849 See `org-ctrl-c-ctrl-c-hook' for more information.")
19850 (defvar org-metareturn-hook nil
19851 "Hook for functions attaching themselves to `M-RET'.
19852 See `org-ctrl-c-ctrl-c-hook' for more information.")
19853 (defvar org-shiftup-hook nil
19854 "Hook for functions attaching themselves to `S-up'.
19855 See `org-ctrl-c-ctrl-c-hook' for more information.")
19856 (defvar org-shiftup-final-hook nil
19857 "Hook for functions attaching themselves to `S-up'.
19858 This one runs after all other options except shift-select have been excluded.
19859 See `org-ctrl-c-ctrl-c-hook' for more information.")
19860 (defvar org-shiftdown-hook nil
19861 "Hook for functions attaching themselves to `S-down'.
19862 See `org-ctrl-c-ctrl-c-hook' for more information.")
19863 (defvar org-shiftdown-final-hook nil
19864 "Hook for functions attaching themselves to `S-down'.
19865 This one runs after all other options except shift-select have been excluded.
19866 See `org-ctrl-c-ctrl-c-hook' for more information.")
19867 (defvar org-shiftleft-hook nil
19868 "Hook for functions attaching themselves to `S-left'.
19869 See `org-ctrl-c-ctrl-c-hook' for more information.")
19870 (defvar org-shiftleft-final-hook nil
19871 "Hook for functions attaching themselves to `S-left'.
19872 This one runs after all other options except shift-select have been excluded.
19873 See `org-ctrl-c-ctrl-c-hook' for more information.")
19874 (defvar org-shiftright-hook nil
19875 "Hook for functions attaching themselves to `S-right'.
19876 See `org-ctrl-c-ctrl-c-hook' for more information.")
19877 (defvar org-shiftright-final-hook nil
19878 "Hook for functions attaching themselves to `S-right'.
19879 This one runs after all other options except shift-select have been excluded.
19880 See `org-ctrl-c-ctrl-c-hook' for more information.")
19882 (defun org-modifier-cursor-error ()
19883 "Throw an error, a modified cursor command was applied in wrong context."
19884 (user-error "This command is active in special context like tables, headlines or items"))
19886 (defun org-shiftselect-error ()
19887 "Throw an error because Shift-Cursor command was applied in wrong context."
19888 (if (and (boundp 'shift-select-mode) shift-select-mode)
19889 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19890 (user-error "This command works only in special context like headlines or timestamps")))
19892 (defun org-call-for-shift-select (cmd)
19893 (let ((this-command-keys-shift-translated t))
19894 (call-interactively cmd)))
19896 (defun org-shifttab (&optional arg)
19897 "Global visibility cycling or move to previous table field.
19898 Call `org-table-previous-field' within a table.
19899 When ARG is nil, cycle globally through visibility states.
19900 When ARG is a numeric prefix, show contents of this level."
19901 (interactive "P")
19902 (cond
19903 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19904 ((integerp arg)
19905 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19906 (message "Content view to level: %d" arg)
19907 (org-content (prefix-numeric-value arg2))
19908 (org-cycle-show-empty-lines t)
19909 (setq org-cycle-global-status 'overview)))
19910 (t (call-interactively 'org-global-cycle))))
19912 (defun org-shiftmetaleft ()
19913 "Promote subtree or delete table column.
19914 Calls `org-promote-subtree', `org-outdent-item-tree', or
19915 `org-table-delete-column', depending on context. See the
19916 individual commands for more information."
19917 (interactive)
19918 (cond
19919 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19920 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19921 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19922 ((if (not (org-region-active-p)) (org-at-item-p)
19923 (save-excursion (goto-char (region-beginning))
19924 (org-at-item-p)))
19925 (call-interactively 'org-outdent-item-tree))
19926 (t (org-modifier-cursor-error))))
19928 (defun org-shiftmetaright ()
19929 "Demote subtree or insert table column.
19930 Calls `org-demote-subtree', `org-indent-item-tree', or
19931 `org-table-insert-column', depending on context. See the
19932 individual commands for more information."
19933 (interactive)
19934 (cond
19935 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19936 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19937 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19938 ((if (not (org-region-active-p)) (org-at-item-p)
19939 (save-excursion (goto-char (region-beginning))
19940 (org-at-item-p)))
19941 (call-interactively 'org-indent-item-tree))
19942 (t (org-modifier-cursor-error))))
19944 (defun org-shiftmetaup (&optional _arg)
19945 "Drag the line at point up.
19946 In a table, kill the current row.
19947 On a clock timestamp, update the value of the timestamp like `S-<up>'
19948 but also adjust the previous clocked item in the clock history.
19949 Everywhere else, drag the line at point up."
19950 (interactive "P")
19951 (cond
19952 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19953 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19954 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19955 (call-interactively 'org-timestamp-up)))
19956 (t (call-interactively 'org-drag-line-backward))))
19958 (defun org-shiftmetadown (&optional _arg)
19959 "Drag the line at point down.
19960 In a table, insert an empty row at the current line.
19961 On a clock timestamp, update the value of the timestamp like `S-<down>'
19962 but also adjust the previous clocked item in the clock history.
19963 Everywhere else, drag the line at point down."
19964 (interactive "P")
19965 (cond
19966 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19967 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19968 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19969 (call-interactively 'org-timestamp-down)))
19970 (t (call-interactively 'org-drag-line-forward))))
19972 (defsubst org-hidden-tree-error ()
19973 (user-error
19974 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19976 (defun org-metaleft (&optional _arg)
19977 "Promote heading, list item at point or move table column left.
19979 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19980 depending on context. With no specific context, calls the Emacs
19981 default `backward-word'. See the individual commands for more
19982 information.
19984 This function runs the hook `org-metaleft-hook' as a first step,
19985 and returns at first non-nil value."
19986 (interactive "P")
19987 (cond
19988 ((run-hook-with-args-until-success 'org-metaleft-hook))
19989 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19990 ((org-with-limited-levels
19991 (or (org-at-heading-p)
19992 (and (org-region-active-p)
19993 (save-excursion
19994 (goto-char (region-beginning))
19995 (org-at-heading-p)))))
19996 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19997 (call-interactively 'org-do-promote))
19998 ;; At an inline task.
19999 ((org-at-heading-p)
20000 (call-interactively 'org-inlinetask-promote))
20001 ((or (org-at-item-p)
20002 (and (org-region-active-p)
20003 (save-excursion
20004 (goto-char (region-beginning))
20005 (org-at-item-p))))
20006 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20007 (call-interactively 'org-outdent-item))
20008 (t (call-interactively 'backward-word))))
20010 (defun org-metaright (&optional _arg)
20011 "Demote heading, list item at point or move table column right.
20013 In front of a drawer or a block keyword, indent it correctly.
20015 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20016 `org-indent-drawer' or `org-indent-block' depending on context.
20017 With no specific context, calls the Emacs default `forward-word'.
20018 See the individual commands for more information.
20020 This function runs the hook `org-metaright-hook' as a first step,
20021 and returns at first non-nil value."
20022 (interactive "P")
20023 (cond
20024 ((run-hook-with-args-until-success 'org-metaright-hook))
20025 ((org-at-table-p) (call-interactively 'org-table-move-column))
20026 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20027 ((org-at-block-p) (call-interactively 'org-indent-block))
20028 ((org-with-limited-levels
20029 (or (org-at-heading-p)
20030 (and (org-region-active-p)
20031 (save-excursion
20032 (goto-char (region-beginning))
20033 (org-at-heading-p)))))
20034 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20035 (call-interactively 'org-do-demote))
20036 ;; At an inline task.
20037 ((org-at-heading-p)
20038 (call-interactively 'org-inlinetask-demote))
20039 ((or (org-at-item-p)
20040 (and (org-region-active-p)
20041 (save-excursion
20042 (goto-char (region-beginning))
20043 (org-at-item-p))))
20044 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20045 (call-interactively 'org-indent-item))
20046 (t (call-interactively 'forward-word))))
20048 (defun org-check-for-hidden (what)
20049 "Check if there are hidden headlines/items in the current visual line.
20050 WHAT can be either `headlines' or `items'. If the current line is
20051 an outline or item heading and it has a folded subtree below it,
20052 this function returns t, nil otherwise."
20053 (let ((re (cond
20054 ((eq what 'headlines) org-outline-regexp-bol)
20055 ((eq what 'items) (org-item-beginning-re))
20056 (t (error "This should not happen"))))
20057 beg end)
20058 (save-excursion
20059 (catch 'exit
20060 (unless (org-region-active-p)
20061 (setq beg (point-at-bol))
20062 (beginning-of-line 2)
20063 (while (and (not (eobp)) ;; this is like `next-line'
20064 (get-char-property (1- (point)) 'invisible))
20065 (beginning-of-line 2))
20066 (setq end (point))
20067 (goto-char beg)
20068 (goto-char (point-at-eol))
20069 (setq end (max end (point)))
20070 (while (re-search-forward re end t)
20071 (when (get-char-property (match-beginning 0) 'invisible)
20072 (throw 'exit t))))
20073 nil))))
20075 (defun org-metaup (&optional _arg)
20076 "Move subtree up or move table row up.
20077 Calls `org-move-subtree-up' or `org-table-move-row' or
20078 `org-move-item-up', depending on context. See the individual commands
20079 for more information."
20080 (interactive "P")
20081 (cond
20082 ((run-hook-with-args-until-success 'org-metaup-hook))
20083 ((org-region-active-p)
20084 (let* ((a (min (region-beginning) (region-end)))
20085 (b (1- (max (region-beginning) (region-end))))
20086 (c (save-excursion (goto-char a)
20087 (move-beginning-of-line 0)))
20088 (d (save-excursion (goto-char a)
20089 (move-end-of-line 0) (point))))
20090 (transpose-regions a b c d)
20091 (goto-char c)))
20092 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20093 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20094 ((org-at-item-p) (call-interactively 'org-move-item-up))
20095 (t (org-drag-element-backward))))
20097 (defun org-metadown (&optional _arg)
20098 "Move subtree down or move table row down.
20099 Calls `org-move-subtree-down' or `org-table-move-row' or
20100 `org-move-item-down', depending on context. See the individual
20101 commands for more information."
20102 (interactive "P")
20103 (cond
20104 ((run-hook-with-args-until-success 'org-metadown-hook))
20105 ((org-region-active-p)
20106 (let* ((a (min (region-beginning) (region-end)))
20107 (b (max (region-beginning) (region-end)))
20108 (c (save-excursion (goto-char b)
20109 (move-beginning-of-line 1)))
20110 (d (save-excursion (goto-char b)
20111 (move-end-of-line 1) (1+ (point)))))
20112 (transpose-regions a b c d)
20113 (goto-char d)))
20114 ((org-at-table-p) (call-interactively 'org-table-move-row))
20115 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20116 ((org-at-item-p) (call-interactively 'org-move-item-down))
20117 (t (org-drag-element-forward))))
20119 (defun org-shiftup (&optional arg)
20120 "Increase item in timestamp or increase priority of current headline.
20121 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20122 depending on context. See the individual commands for more information."
20123 (interactive "P")
20124 (cond
20125 ((run-hook-with-args-until-success 'org-shiftup-hook))
20126 ((and org-support-shift-select (org-region-active-p))
20127 (org-call-for-shift-select 'previous-line))
20128 ((org-at-timestamp-p 'lax)
20129 (call-interactively (if org-edit-timestamp-down-means-later
20130 'org-timestamp-down 'org-timestamp-up)))
20131 ((and (not (eq org-support-shift-select 'always))
20132 org-enable-priority-commands
20133 (org-at-heading-p))
20134 (call-interactively 'org-priority-up))
20135 ((and (not org-support-shift-select) (org-at-item-p))
20136 (call-interactively 'org-previous-item))
20137 ((org-clocktable-try-shift 'up arg))
20138 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20139 (org-support-shift-select
20140 (org-call-for-shift-select 'previous-line))
20141 (t (org-shiftselect-error))))
20143 (defun org-shiftdown (&optional arg)
20144 "Decrease item in timestamp or decrease priority of current headline.
20145 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20146 depending on context. See the individual commands for more information."
20147 (interactive "P")
20148 (cond
20149 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20150 ((and org-support-shift-select (org-region-active-p))
20151 (org-call-for-shift-select 'next-line))
20152 ((org-at-timestamp-p 'lax)
20153 (call-interactively (if org-edit-timestamp-down-means-later
20154 'org-timestamp-up 'org-timestamp-down)))
20155 ((and (not (eq org-support-shift-select 'always))
20156 org-enable-priority-commands
20157 (org-at-heading-p))
20158 (call-interactively 'org-priority-down))
20159 ((and (not org-support-shift-select) (org-at-item-p))
20160 (call-interactively 'org-next-item))
20161 ((org-clocktable-try-shift 'down arg))
20162 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20163 (org-support-shift-select
20164 (org-call-for-shift-select 'next-line))
20165 (t (org-shiftselect-error))))
20167 (defun org-shiftright (&optional arg)
20168 "Cycle the thing at point or in the current line, depending on context.
20169 Depending on context, this does one of the following:
20171 - switch a timestamp at point one day into the future
20172 - on a headline, switch to the next TODO keyword.
20173 - on an item, switch entire list to the next bullet type
20174 - on a property line, switch to the next allowed value
20175 - on a clocktable definition line, move time block into the future"
20176 (interactive "P")
20177 (cond
20178 ((run-hook-with-args-until-success 'org-shiftright-hook))
20179 ((and org-support-shift-select (org-region-active-p))
20180 (org-call-for-shift-select 'forward-char))
20181 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20182 ((and (not (eq org-support-shift-select 'always))
20183 (org-at-heading-p))
20184 (let ((org-inhibit-logging
20185 (not org-treat-S-cursor-todo-selection-as-state-change))
20186 (org-inhibit-blocking
20187 (not org-treat-S-cursor-todo-selection-as-state-change)))
20188 (org-call-with-arg 'org-todo 'right)))
20189 ((or (and org-support-shift-select
20190 (not (eq org-support-shift-select 'always))
20191 (org-at-item-bullet-p))
20192 (and (not org-support-shift-select) (org-at-item-p)))
20193 (org-call-with-arg 'org-cycle-list-bullet nil))
20194 ((and (not (eq org-support-shift-select 'always))
20195 (org-at-property-p))
20196 (call-interactively 'org-property-next-allowed-value))
20197 ((org-clocktable-try-shift 'right arg))
20198 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20199 (org-support-shift-select
20200 (org-call-for-shift-select 'forward-char))
20201 (t (org-shiftselect-error))))
20203 (defun org-shiftleft (&optional arg)
20204 "Cycle the thing at point or in the current line, depending on context.
20205 Depending on context, this does one of the following:
20207 - switch a timestamp at point one day into the past
20208 - on a headline, switch to the previous TODO keyword.
20209 - on an item, switch entire list to the previous bullet type
20210 - on a property line, switch to the previous allowed value
20211 - on a clocktable definition line, move time block into the past"
20212 (interactive "P")
20213 (cond
20214 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20215 ((and org-support-shift-select (org-region-active-p))
20216 (org-call-for-shift-select 'backward-char))
20217 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20218 ((and (not (eq org-support-shift-select 'always))
20219 (org-at-heading-p))
20220 (let ((org-inhibit-logging
20221 (not org-treat-S-cursor-todo-selection-as-state-change))
20222 (org-inhibit-blocking
20223 (not org-treat-S-cursor-todo-selection-as-state-change)))
20224 (org-call-with-arg 'org-todo 'left)))
20225 ((or (and org-support-shift-select
20226 (not (eq org-support-shift-select 'always))
20227 (org-at-item-bullet-p))
20228 (and (not org-support-shift-select) (org-at-item-p)))
20229 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20230 ((and (not (eq org-support-shift-select 'always))
20231 (org-at-property-p))
20232 (call-interactively 'org-property-previous-allowed-value))
20233 ((org-clocktable-try-shift 'left arg))
20234 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20235 (org-support-shift-select
20236 (org-call-for-shift-select 'backward-char))
20237 (t (org-shiftselect-error))))
20239 (defun org-shiftcontrolright ()
20240 "Switch to next TODO set."
20241 (interactive)
20242 (cond
20243 ((and org-support-shift-select (org-region-active-p))
20244 (org-call-for-shift-select 'forward-word))
20245 ((and (not (eq org-support-shift-select 'always))
20246 (org-at-heading-p))
20247 (org-call-with-arg 'org-todo 'nextset))
20248 (org-support-shift-select
20249 (org-call-for-shift-select 'forward-word))
20250 (t (org-shiftselect-error))))
20252 (defun org-shiftcontrolleft ()
20253 "Switch to previous TODO set."
20254 (interactive)
20255 (cond
20256 ((and org-support-shift-select (org-region-active-p))
20257 (org-call-for-shift-select 'backward-word))
20258 ((and (not (eq org-support-shift-select 'always))
20259 (org-at-heading-p))
20260 (org-call-with-arg 'org-todo 'previousset))
20261 (org-support-shift-select
20262 (org-call-for-shift-select 'backward-word))
20263 (t (org-shiftselect-error))))
20265 (defun org-shiftcontrolup (&optional n)
20266 "Change timestamps synchronously up in CLOCK log lines.
20267 Optional argument N tells to change by that many units."
20268 (interactive "P")
20269 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20270 (let (org-support-shift-select)
20271 (org-clock-timestamps-up n))
20272 (user-error "Not at a clock log")))
20274 (defun org-shiftcontroldown (&optional n)
20275 "Change timestamps synchronously down in CLOCK log lines.
20276 Optional argument N tells to change by that many units."
20277 (interactive "P")
20278 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20279 (let (org-support-shift-select)
20280 (org-clock-timestamps-down n))
20281 (user-error "Not at a clock log")))
20283 (defun org-increase-number-at-point (&optional inc)
20284 "Increment the number at point.
20285 With an optional prefix numeric argument INC, increment using
20286 this numeric value."
20287 (interactive "p")
20288 (if (not (number-at-point))
20289 (user-error "Not on a number")
20290 (unless inc (setq inc 1))
20291 (let ((pos (point))
20292 (beg (skip-chars-backward "-+^/*0-9eE."))
20293 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20294 (setq nap (buffer-substring-no-properties
20295 (+ pos beg) (+ pos beg end)))
20296 (delete-region (+ pos beg) (+ pos beg end))
20297 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20298 (when (org-at-table-p)
20299 (org-table-align)
20300 (org-table-end-of-field 1))))
20302 (defun org-decrease-number-at-point (&optional inc)
20303 "Decrement the number at point.
20304 With an optional prefix numeric argument INC, decrement using
20305 this numeric value."
20306 (interactive "p")
20307 (org-increase-number-at-point (- (or inc 1))))
20309 (defun org-ctrl-c-ret ()
20310 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20311 (interactive)
20312 (cond
20313 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20314 (t (call-interactively 'org-insert-heading))))
20316 (defun org-find-visible ()
20317 (let ((s (point)))
20318 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20319 (get-char-property s 'invisible)))
20321 (defun org-find-invisible ()
20322 (let ((s (point)))
20323 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20324 (not (get-char-property s 'invisible))))
20327 (defun org-copy-visible (beg end)
20328 "Copy the visible parts of the region."
20329 (interactive "r")
20330 (let ((result ""))
20331 (while (/= beg end)
20332 (when (get-char-property beg 'invisible)
20333 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20334 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20335 (setq result (concat result (buffer-substring beg next)))
20336 (setq beg next)))
20337 (kill-new result)))
20339 (defun org-copy-special ()
20340 "Copy region in table or copy current subtree.
20341 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20342 context. See the individual commands for more information."
20343 (interactive)
20344 (call-interactively
20345 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20347 (defun org-cut-special ()
20348 "Cut region in table or cut current subtree.
20349 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20350 context. See the individual commands for more information."
20351 (interactive)
20352 (call-interactively
20353 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20355 (defun org-paste-special (arg)
20356 "Paste rectangular region into table, or past subtree relative to level.
20357 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20358 See the individual commands for more information."
20359 (interactive "P")
20360 (if (org-at-table-p)
20361 (org-table-paste-rectangle)
20362 (org-paste-subtree arg)))
20364 (defun org-edit-special (&optional arg)
20365 "Call a special editor for the element at point.
20366 When at a table, call the formula editor with `org-table-edit-formulas'.
20367 When in a source code block, call `org-edit-src-code'.
20368 When in a fixed-width region, call `org-edit-fixed-width-region'.
20369 When in an export block, call `org-edit-export-block'.
20370 When in a LaTeX environment, call `org-edit-latex-environment'.
20371 When at an #+INCLUDE keyword, visit the included file.
20372 When at a footnote reference, call `org-edit-footnote-reference'
20373 On a link, call `ffap' to visit the link at point.
20374 Otherwise, return a user error."
20375 (interactive "P")
20376 (let ((element (org-element-at-point)))
20377 (barf-if-buffer-read-only)
20378 (pcase (org-element-type element)
20379 (`src-block
20380 (if (not arg) (org-edit-src-code)
20381 (let* ((info (org-babel-get-src-block-info))
20382 (lang (nth 0 info))
20383 (params (nth 2 info))
20384 (session (cdr (assq :session params))))
20385 (if (not session) (org-edit-src-code)
20386 ;; At a src-block with a session and function called with
20387 ;; an ARG: switch to the buffer related to the inferior
20388 ;; process.
20389 (switch-to-buffer
20390 (funcall (intern (concat "org-babel-prep-session:" lang))
20391 session params))))))
20392 (`keyword
20393 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20394 (org-open-link-from-string
20395 (format "[[%s]]"
20396 (expand-file-name
20397 (let ((value (org-element-property :value element)))
20398 (cond ((org-file-url-p value)
20399 (user-error "The file is specified as a URL, cannot be edited"))
20400 ((not (org-string-nw-p value))
20401 (user-error "No file to edit"))
20402 ((string-match "\\`\"\\(.*?\\)\"" value)
20403 (match-string 1 value))
20404 ((string-match "\\`[^ \t\"]\\S-*" value)
20405 (match-string 0 value))
20406 (t (user-error "No valid file specified")))))))
20407 (user-error "No special environment to edit here")))
20408 (`table
20409 (if (eq (org-element-property :type element) 'table.el)
20410 (org-edit-table.el)
20411 (call-interactively 'org-table-edit-formulas)))
20412 ;; Only Org tables contain `table-row' type elements.
20413 (`table-row (call-interactively 'org-table-edit-formulas))
20414 (`example-block (org-edit-src-code))
20415 (`export-block (org-edit-export-block))
20416 (`fixed-width (org-edit-fixed-width-region))
20417 (`latex-environment (org-edit-latex-environment))
20419 ;; No notable element at point. Though, we may be at a link or
20420 ;; a footnote reference, which are objects. Thus, scan deeper.
20421 (let ((context (org-element-context element)))
20422 (pcase (org-element-type context)
20423 (`footnote-reference (org-edit-footnote-reference))
20424 (`inline-src-block (org-edit-inline-src-code))
20425 (`link (call-interactively #'ffap))
20426 (_ (user-error "No special environment to edit here"))))))))
20428 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20429 (defun org-ctrl-c-ctrl-c (&optional arg)
20430 "Set tags in headline, or update according to changed information at point.
20432 This command does many different things, depending on context:
20434 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20435 this is what we do.
20437 - If the cursor is on a statistics cookie, update it.
20439 - If the cursor is in a headline, prompt for tags and insert them
20440 into the current line, aligned to `org-tags-column'. When called
20441 with prefix arg, realign all tags in the current buffer.
20443 - If the cursor is in one of the special #+KEYWORD lines, this
20444 triggers scanning the buffer for these lines and updating the
20445 information.
20447 - If the cursor is inside a table, realign the table. This command
20448 works even if the automatic table editor has been turned off.
20450 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20451 the entire table.
20453 - If the cursor is at a footnote reference or definition, jump to
20454 the corresponding definition or references, respectively.
20456 - If the cursor is a the beginning of a dynamic block, update it.
20458 - If the current buffer is a capture buffer, close note and file it.
20460 - If the cursor is on a <<<target>>>, update radio targets and
20461 corresponding links in this buffer.
20463 - If the cursor is on a numbered item in a plain list, renumber the
20464 ordered list.
20466 - If the cursor is on a checkbox, toggle it.
20468 - If the cursor is on a code block, evaluate it. The variable
20469 `org-confirm-babel-evaluate' can be used to control prompting
20470 before code block evaluation, by default every code block
20471 evaluation requires confirmation. Code block evaluation can be
20472 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20473 (interactive "P")
20474 (cond
20475 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20476 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20477 (org-remove-occur-highlights)
20478 (message "Temporary highlights/overlays removed from current buffer"))
20479 ((and (local-variable-p 'org-finish-function)
20480 (fboundp org-finish-function))
20481 (funcall org-finish-function))
20482 ((org-babel-hash-at-point))
20483 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20485 (let* ((context
20486 (org-element-lineage
20487 (org-element-context)
20488 ;; Limit to supported contexts.
20489 '(babel-call clock dynamic-block footnote-definition
20490 footnote-reference inline-babel-call inline-src-block
20491 inlinetask item keyword node-property paragraph
20492 plain-list planning property-drawer radio-target
20493 src-block statistics-cookie table table-cell table-row
20494 timestamp)
20496 (type (org-element-type context)))
20497 ;; For convenience: at the first line of a paragraph on the same
20498 ;; line as an item, apply function on that item instead.
20499 (when (eq type 'paragraph)
20500 (let ((parent (org-element-property :parent context)))
20501 (when (and (eq (org-element-type parent) 'item)
20502 (= (line-beginning-position)
20503 (org-element-property :begin parent)))
20504 (setq context parent)
20505 (setq type 'item))))
20506 ;; Act according to type of element or object at point.
20508 ;; Do nothing on a blank line, except if it is contained in
20509 ;; a src block. Hence, we first check if point is in such
20510 ;; a block and then if it is at a blank line.
20511 (pcase type
20512 ((or `inline-src-block `src-block)
20513 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20514 (org-babel-eval-wipe-error-buffer)
20515 (org-babel-execute-src-block
20516 current-prefix-arg (org-babel-get-src-block-info nil context))))
20517 ((guard (org-match-line "[ \t]*$"))
20518 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20519 (user-error
20520 (substitute-command-keys
20521 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20522 ((or `babel-call `inline-babel-call)
20523 (let ((info (org-babel-lob-get-info context)))
20524 (when info (org-babel-execute-src-block nil info))))
20525 (`clock (org-clock-update-time-maybe))
20526 (`dynamic-block
20527 (save-excursion
20528 (goto-char (org-element-property :post-affiliated context))
20529 (org-update-dblock)))
20530 (`footnote-definition
20531 (goto-char (org-element-property :post-affiliated context))
20532 (call-interactively 'org-footnote-action))
20533 (`footnote-reference (call-interactively #'org-footnote-action))
20534 ((or `headline `inlinetask)
20535 (save-excursion (goto-char (org-element-property :begin context))
20536 (call-interactively #'org-set-tags)))
20537 (`item
20538 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20539 ;; unconditionally, whereas `C-u' will toggle its presence.
20540 ;; Without a universal argument, if the item has a checkbox,
20541 ;; toggle it. Otherwise repair the list.
20542 (let* ((box (org-element-property :checkbox context))
20543 (struct (org-element-property :structure context))
20544 (old-struct (copy-tree struct))
20545 (parents (org-list-parents-alist struct))
20546 (prevs (org-list-prevs-alist struct))
20547 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20548 (org-list-set-checkbox
20549 (org-element-property :begin context) struct
20550 (cond ((equal arg '(16)) "[-]")
20551 ((and (not box) (equal arg '(4))) "[ ]")
20552 ((or (not box) (equal arg '(4))) nil)
20553 ((eq box 'on) "[ ]")
20554 (t "[X]")))
20555 ;; Mimic `org-list-write-struct' but with grabbing a return
20556 ;; value from `org-list-struct-fix-box'.
20557 (org-list-struct-fix-ind struct parents 2)
20558 (org-list-struct-fix-item-end struct)
20559 (org-list-struct-fix-bul struct prevs)
20560 (org-list-struct-fix-ind struct parents)
20561 (let ((block-item
20562 (org-list-struct-fix-box struct parents prevs orderedp)))
20563 (if (and box (equal struct old-struct))
20564 (if (equal arg '(16))
20565 (message "Checkboxes already reset")
20566 (user-error "Cannot toggle this checkbox: %s"
20567 (if (eq box 'on)
20568 "all subitems checked"
20569 "unchecked subitems")))
20570 (org-list-struct-apply-struct struct old-struct)
20571 (org-update-checkbox-count-maybe))
20572 (when block-item
20573 (message "Checkboxes were removed due to empty box at line %d"
20574 (org-current-line block-item))))))
20575 (`keyword
20576 (let ((org-inhibit-startup-visibility-stuff t)
20577 (org-startup-align-all-tables nil))
20578 (when (boundp 'org-table-coordinate-overlays)
20579 (mapc #'delete-overlay org-table-coordinate-overlays)
20580 (setq org-table-coordinate-overlays nil))
20581 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20582 (message "Local setup has been refreshed"))
20583 (`plain-list
20584 ;; At a plain list, with a double C-u argument, set
20585 ;; checkboxes of each item to "[-]", whereas a single one
20586 ;; will toggle their presence according to the state of the
20587 ;; first item in the list. Without an argument, repair the
20588 ;; list.
20589 (let* ((begin (org-element-property :contents-begin context))
20590 (beginm (move-marker (make-marker) begin))
20591 (struct (org-element-property :structure context))
20592 (old-struct (copy-tree struct))
20593 (first-box (save-excursion
20594 (goto-char begin)
20595 (looking-at org-list-full-item-re)
20596 (match-string-no-properties 3)))
20597 (new-box (cond ((equal arg '(16)) "[-]")
20598 ((equal arg '(4)) (unless first-box "[ ]"))
20599 ((equal first-box "[X]") "[ ]")
20600 (t "[X]"))))
20601 (cond
20602 (arg
20603 (dolist (pos
20604 (org-list-get-all-items
20605 begin struct (org-list-prevs-alist struct)))
20606 (org-list-set-checkbox pos struct new-box)))
20607 ((and first-box (eq (point) begin))
20608 ;; For convenience, when point is at bol on the first
20609 ;; item of the list and no argument is provided, simply
20610 ;; toggle checkbox of that item, if any.
20611 (org-list-set-checkbox begin struct new-box)))
20612 (org-list-write-struct
20613 struct (org-list-parents-alist struct) old-struct)
20614 (org-update-checkbox-count-maybe)
20615 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20616 ((or `property-drawer `node-property)
20617 (call-interactively #'org-property-action))
20618 (`radio-target
20619 (call-interactively #'org-update-radio-target-regexp))
20620 (`statistics-cookie
20621 (call-interactively #'org-update-statistics-cookies))
20622 ((or `table `table-cell `table-row)
20623 ;; At a table, recalculate every field and align it. Also
20624 ;; send the table if necessary. If the table has
20625 ;; a `table.el' type, just give up. At a table row or cell,
20626 ;; maybe recalculate line but always align table.
20627 (if (eq (org-element-property :type context) 'table.el)
20628 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20629 Use `\\[org-edit-special]' to edit table.el tables"))
20630 (if (or (eq type 'table)
20631 ;; Check if point is at a TBLFM line.
20632 (and (eq type 'table-row)
20633 (= (point) (org-element-property :end context))))
20634 (save-excursion
20635 (if (org-at-TBLFM-p)
20636 (progn (require 'org-table)
20637 (org-table-calc-current-TBLFM))
20638 (goto-char (org-element-property :contents-begin context))
20639 (org-call-with-arg 'org-table-recalculate (or arg t))
20640 (orgtbl-send-table 'maybe)))
20641 (org-table-maybe-eval-formula)
20642 (cond (arg (call-interactively #'org-table-recalculate))
20643 ((org-table-maybe-recalculate-line))
20644 (t (org-table-align))))))
20645 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20646 (org-timestamp-change 0 'day))
20647 ((and `nil (guard (org-at-heading-p)))
20648 ;; When point is on an unsupported object type, we can miss
20649 ;; the fact that it also is at a heading. Handle it here.
20650 (call-interactively #'org-set-tags))
20651 ((guard
20652 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20654 (user-error
20655 (substitute-command-keys
20656 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20658 (defun org-mode-restart ()
20659 (interactive)
20660 (let ((indent-status (bound-and-true-p org-indent-mode)))
20661 (funcall major-mode)
20662 (hack-local-variables)
20663 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20664 (org-indent-mode -1))
20665 (org-reset-file-cache))
20666 (message "%s restarted" major-mode))
20668 (defun org-kill-note-or-show-branches ()
20669 "Abort storing current note, or call `outline-show-branches'."
20670 (interactive)
20671 (if (not org-finish-function)
20672 (progn
20673 (outline-hide-subtree)
20674 (call-interactively 'outline-show-branches))
20675 (let ((org-note-abort t))
20676 (funcall org-finish-function))))
20678 (defun org-delete-indentation (&optional arg)
20679 "Join current line to previous and fix whitespace at join.
20681 If previous line is a headline add to headline title. Otherwise
20682 the function calls `delete-indentation'.
20684 With a non-nil optional argument, join it to the following one."
20685 (interactive "*P")
20686 (if (save-excursion
20687 (beginning-of-line (if arg 1 0))
20688 (let ((case-fold-search nil))
20689 (looking-at org-complex-heading-regexp)))
20690 ;; At headline.
20691 (let ((tags-column (when (match-beginning 5)
20692 (save-excursion (goto-char (match-beginning 5))
20693 (current-column))))
20694 (string (concat " " (progn (when arg (forward-line 1))
20695 (org-trim (delete-and-extract-region
20696 (line-beginning-position)
20697 (line-end-position)))))))
20698 (unless (bobp) (delete-region (point) (1- (point))))
20699 (goto-char (or (match-end 4)
20700 (match-beginning 5)
20701 (match-end 0)))
20702 (skip-chars-backward " \t")
20703 (save-excursion (insert string))
20704 ;; Adjust alignment of tags.
20705 (cond
20706 ((not tags-column)) ;no tags
20707 (org-auto-align-tags (org-set-tags nil t))
20708 (t (org--align-tags-here tags-column)))) ;preserve tags column
20709 (delete-indentation arg)))
20711 (defun org-open-line (n)
20712 "Insert a new row in tables, call `open-line' elsewhere.
20713 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20714 As a special case, when a document starts with a table, allow to
20715 call `open-line' on the very first character."
20716 (interactive "*p")
20717 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20718 (org-table-insert-row)
20719 (open-line n)))
20721 (defun org-return (&optional indent)
20722 "Goto next table row or insert a newline.
20724 Calls `org-table-next-row' or `newline', depending on context.
20726 When optional INDENT argument is non-nil, call
20727 `newline-and-indent' instead of `newline'.
20729 When `org-return-follows-link' is non-nil and point is on
20730 a timestamp or a link, call `org-open-at-point'. However, it
20731 will not happen if point is in a table or on a \"dead\"
20732 object (e.g., within a comment). In these case, you need to use
20733 `org-open-at-point' directly."
20734 (interactive)
20735 (let ((context (if org-return-follows-link (org-element-context)
20736 (org-element-at-point))))
20737 (cond
20738 ;; In a table, call `org-table-next-row'. However, before first
20739 ;; column or after last one, split the table.
20740 ((or (and (eq (org-element-type context) 'table)
20741 (>= (point) (org-element-property :contents-begin context))
20742 (< (point) (org-element-property :contents-end context)))
20743 (org-element-lineage context '(table-row table-cell) t))
20744 (if (or (looking-at-p "[ \t]*$")
20745 (save-excursion (skip-chars-backward " \t") (bolp)))
20746 (insert "\n")
20747 (org-table-justify-field-maybe)
20748 (call-interactively #'org-table-next-row)))
20749 ;; On a link or a timestamp, call `org-open-at-point' if
20750 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20751 ;; locations, e.g., in a comment, as `org-open-at-point'.
20752 ((and org-return-follows-link
20753 (or (org-in-regexp org-ts-regexp-both nil t)
20754 (org-in-regexp org-tsr-regexp-both nil t)
20755 (org-in-regexp org-any-link-re nil t)))
20756 (call-interactively #'org-open-at-point))
20757 ;; Insert newline in heading, but preserve tags.
20758 ((and (not (bolp))
20759 (save-excursion (beginning-of-line)
20760 (let ((case-fold-search nil))
20761 (looking-at org-complex-heading-regexp))))
20762 ;; At headline. Split line. However, if point is on keyword,
20763 ;; priority cookie or tags, do not break any of them: add
20764 ;; a newline after the headline instead.
20765 (let ((tags-column (and (match-beginning 5)
20766 (save-excursion (goto-char (match-beginning 5))
20767 (current-column))))
20768 (string
20769 (when (and (match-end 4) (org-point-in-group (point) 4))
20770 (delete-and-extract-region (point) (match-end 4)))))
20771 ;; Adjust tag alignment.
20772 (cond
20773 ((not (and tags-column string)))
20774 (org-auto-align-tags (org-set-tags nil t))
20775 (t (org--align-tags-here tags-column))) ;preserve tags column
20776 (end-of-line)
20777 (org-show-entry)
20778 (if indent (newline-and-indent) (newline))
20779 (when string (save-excursion (insert (org-trim string))))))
20780 ;; In a list, make sure indenting keeps trailing text within.
20781 ((and indent
20782 (not (eolp))
20783 (org-element-lineage context '(item)))
20784 (let ((trailing-data
20785 (delete-and-extract-region (point) (line-end-position))))
20786 (newline-and-indent)
20787 (save-excursion (insert trailing-data))))
20788 (t (if indent (newline-and-indent) (newline))))))
20790 (defun org-return-indent ()
20791 "Goto next table row or insert a newline and indent.
20792 Calls `org-table-next-row' or `newline-and-indent', depending on
20793 context. See the individual commands for more information."
20794 (interactive)
20795 (org-return t))
20797 (defun org-ctrl-c-tab (&optional _arg)
20798 "Toggle columns width in a table, or show children.
20799 Call `org-table-toggle-column-width' if point is in a table.
20800 Otherwise, call `org-show-children'."
20801 (interactive "p")
20802 (call-interactively
20803 (if (org-at-table-p) #'org-table-toggle-column-width
20804 #'org-show-children)))
20806 (defun org-ctrl-c-star ()
20807 "Compute table, or change heading status of lines.
20808 Calls `org-table-recalculate' or `org-toggle-heading',
20809 depending on context."
20810 (interactive)
20811 (cond
20812 ((org-at-table-p)
20813 (call-interactively 'org-table-recalculate))
20815 ;; Convert all lines in region to list items
20816 (call-interactively 'org-toggle-heading))))
20818 (defun org-ctrl-c-minus ()
20819 "Insert separator line in table or modify bullet status of line.
20820 Also turns a plain line or a region of lines into list items.
20821 Calls `org-table-insert-hline', `org-toggle-item', or
20822 `org-cycle-list-bullet', depending on context."
20823 (interactive)
20824 (cond
20825 ((org-at-table-p)
20826 (call-interactively 'org-table-insert-hline))
20827 ((org-region-active-p)
20828 (call-interactively 'org-toggle-item))
20829 ((org-in-item-p)
20830 (call-interactively 'org-cycle-list-bullet))
20832 (call-interactively 'org-toggle-item))))
20834 (defun org-toggle-heading (&optional nstars)
20835 "Convert headings to normal text, or items or text to headings.
20836 If there is no active region, only convert the current line.
20838 With a `\\[universal-argument]' prefix, convert the whole list at
20839 point into heading.
20841 In a region:
20843 - If the first non blank line is a headline, remove the stars
20844 from all headlines in the region.
20846 - If it is a normal line, turn each and every normal line (i.e.,
20847 not an heading or an item) in the region into headings. If you
20848 want to convert only the first line of this region, use one
20849 universal prefix argument.
20851 - If it is a plain list item, turn all plain list items into headings.
20853 When converting a line into a heading, the number of stars is chosen
20854 such that the lines become children of the current entry. However,
20855 when a numeric prefix argument is given, its value determines the
20856 number of stars to add."
20857 (interactive "P")
20858 (let ((skip-blanks
20859 (function
20860 ;; Return beginning of first non-blank line, starting from
20861 ;; line at POS.
20862 (lambda (pos)
20863 (save-excursion
20864 (goto-char pos)
20865 (while (org-at-comment-p) (forward-line))
20866 (skip-chars-forward " \r\t\n")
20867 (point-at-bol)))))
20868 beg end toggled)
20869 ;; Determine boundaries of changes. If a universal prefix has
20870 ;; been given, put the list in a region. If region ends at a bol,
20871 ;; do not consider the last line to be in the region.
20873 (when (and current-prefix-arg (org-at-item-p))
20874 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20875 (org-mark-element))
20877 (if (org-region-active-p)
20878 (setq beg (funcall skip-blanks (region-beginning))
20879 end (copy-marker (save-excursion
20880 (goto-char (region-end))
20881 (if (bolp) (point) (point-at-eol)))))
20882 (setq beg (funcall skip-blanks (point-at-bol))
20883 end (copy-marker (point-at-eol))))
20884 ;; Ensure inline tasks don't count as headings.
20885 (org-with-limited-levels
20886 (save-excursion
20887 (goto-char beg)
20888 (cond
20889 ;; Case 1. Started at an heading: de-star headings.
20890 ((org-at-heading-p)
20891 (while (< (point) end)
20892 (when (org-at-heading-p t)
20893 (looking-at org-outline-regexp) (replace-match "")
20894 (setq toggled t))
20895 (forward-line)))
20896 ;; Case 2. Started at an item: change items into headlines.
20897 ;; One star will be added by `org-list-to-subtree'.
20898 ((org-at-item-p)
20899 (while (< (point) end)
20900 (when (org-at-item-p)
20901 ;; Pay attention to cases when region ends before list.
20902 (let* ((struct (org-list-struct))
20903 (list-end
20904 (min (org-list-get-bottom-point struct) (1+ end))))
20905 (save-restriction
20906 (narrow-to-region (point) list-end)
20907 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20908 (setq toggled t))
20909 (forward-line)))
20910 ;; Case 3. Started at normal text: make every line an heading,
20911 ;; skipping headlines and items.
20912 (t (let* ((stars
20913 (make-string
20914 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20915 (add-stars
20916 (cond (nstars "") ; stars from prefix only
20917 ((equal stars "") "*") ; before first heading
20918 (org-odd-levels-only "**") ; inside heading, odd
20919 (t "*"))) ; inside heading, oddeven
20920 (rpl (concat stars add-stars " "))
20921 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20922 (while (< (point) (if (equal nstars '(4)) lend end))
20923 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20924 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20925 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20926 (forward-line)))))))
20927 (unless toggled (message "Cannot toggle heading from here"))))
20929 (defun org-meta-return (&optional arg)
20930 "Insert a new heading or wrap a region in a table.
20931 Calls `org-insert-heading', `org-insert-item' or
20932 `org-table-wrap-region', depending on context. When called with
20933 an argument, unconditionally call `org-insert-heading'."
20934 (interactive "P")
20935 (org-check-before-invisible-edit 'insert)
20936 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20937 (call-interactively (cond (arg #'org-insert-heading)
20938 ((org-at-table-p) #'org-table-wrap-region)
20939 ((org-in-item-p) #'org-insert-item)
20940 (t #'org-insert-heading)))))
20942 ;;; Menu entries
20944 (defsubst org-in-subtree-not-table-p ()
20945 "Are we in a subtree and not in a table?"
20946 (and (not (org-before-first-heading-p))
20947 (not (org-at-table-p))))
20949 ;; Define the Org mode menus
20950 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20951 '("Tbl"
20952 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20953 ["Next Field" org-cycle (org-at-table-p)]
20954 ["Previous Field" org-shifttab (org-at-table-p)]
20955 ["Next Row" org-return (org-at-table-p)]
20956 "--"
20957 ["Blank Field" org-table-blank-field (org-at-table-p)]
20958 ["Edit Field" org-table-edit-field (org-at-table-p)]
20959 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20960 "--"
20961 ("Column"
20962 ["Move Column Left" org-metaleft (org-at-table-p)]
20963 ["Move Column Right" org-metaright (org-at-table-p)]
20964 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20965 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20966 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20967 ("Row"
20968 ["Move Row Up" org-metaup (org-at-table-p)]
20969 ["Move Row Down" org-metadown (org-at-table-p)]
20970 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20971 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20972 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20973 "--"
20974 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20975 ("Rectangle"
20976 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20977 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20978 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20979 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20980 "--"
20981 ("Calculate"
20982 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20983 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20984 ["Edit Formulas" org-edit-special (org-at-table-p)]
20985 "--"
20986 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20987 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20988 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20989 "--"
20990 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20991 "--"
20992 ["Sum Column/Rectangle" org-table-sum
20993 (or (org-at-table-p) (org-region-active-p))]
20994 ["Which Column?" org-table-current-column (org-at-table-p)])
20995 ["Debug Formulas"
20996 org-table-toggle-formula-debugger
20997 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20998 ["Show Col/Row Numbers"
20999 org-table-toggle-coordinate-overlays
21000 :style toggle
21001 :selected (bound-and-true-p org-table-overlay-coordinates)]
21002 "--"
21003 ["Create" org-table-create (not (org-at-table-p))]
21004 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21005 ["Import from File" org-table-import (not (org-at-table-p))]
21006 ["Export to File" org-table-export (org-at-table-p)]
21007 "--"
21008 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21009 "--"
21010 ("Plot"
21011 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21012 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21014 (easy-menu-define org-org-menu org-mode-map "Org menu"
21015 '("Org"
21016 ("Show/Hide"
21017 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21018 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21019 ["Sparse Tree..." org-sparse-tree t]
21020 ["Reveal Context" org-reveal t]
21021 ["Show All" outline-show-all t]
21022 "--"
21023 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21024 "--"
21025 ["New Heading" org-insert-heading t]
21026 ("Navigate Headings"
21027 ["Up" outline-up-heading t]
21028 ["Next" outline-next-visible-heading t]
21029 ["Previous" outline-previous-visible-heading t]
21030 ["Next Same Level" outline-forward-same-level t]
21031 ["Previous Same Level" outline-backward-same-level t]
21032 "--"
21033 ["Jump" org-goto t])
21034 ("Edit Structure"
21035 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21036 "--"
21037 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21038 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21039 "--"
21040 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21041 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21042 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21043 "--"
21044 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21045 "--"
21046 ["Copy visible text" org-copy-visible t]
21047 "--"
21048 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21049 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21050 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21051 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21052 "--"
21053 ["Sort Region/Children" org-sort t]
21054 "--"
21055 ["Convert to odd levels" org-convert-to-odd-levels t]
21056 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21057 ("Editing"
21058 ["Emphasis..." org-emphasize t]
21059 ["Edit Source Example" org-edit-special t]
21060 "--"
21061 ["Footnote new/jump" org-footnote-action t]
21062 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21063 ("Archive"
21064 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21065 "--"
21066 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21067 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21068 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21070 "--"
21071 ("Hyperlinks"
21072 ["Store Link (Global)" org-store-link t]
21073 ["Find existing link to here" org-occur-link-in-agenda-files t]
21074 ["Insert Link" org-insert-link t]
21075 ["Follow Link" org-open-at-point t]
21076 "--"
21077 ["Next link" org-next-link t]
21078 ["Previous link" org-previous-link t]
21079 "--"
21080 ["Descriptive Links"
21081 org-toggle-link-display
21082 :style radio
21083 :selected org-descriptive-links
21085 ["Literal Links"
21086 org-toggle-link-display
21087 :style radio
21088 :selected (not org-descriptive-links)])
21089 "--"
21090 ("TODO Lists"
21091 ["TODO/DONE/-" org-todo t]
21092 ("Select keyword"
21093 ["Next keyword" org-shiftright (org-at-heading-p)]
21094 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21095 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21096 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21097 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21098 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21099 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21100 "--"
21101 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21102 :selected org-enforce-todo-dependencies :style toggle :active t]
21103 "Settings for tree at point"
21104 ["Do Children sequentially" org-toggle-ordered-property :style radio
21105 :selected (org-entry-get nil "ORDERED")
21106 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21107 ["Do Children parallel" org-toggle-ordered-property :style radio
21108 :selected (not (org-entry-get nil "ORDERED"))
21109 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21110 "--"
21111 ["Set Priority" org-priority t]
21112 ["Priority Up" org-shiftup t]
21113 ["Priority Down" org-shiftdown t]
21114 "--"
21115 ["Get news from all feeds" org-feed-update-all t]
21116 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21117 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21118 ("TAGS and Properties"
21119 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21120 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21121 "--"
21122 ["Set property" org-set-property (not (org-before-first-heading-p))]
21123 ["Column view of properties" org-columns t]
21124 ["Insert Column View DBlock" org-columns-insert-dblock t])
21125 ("Dates and Scheduling"
21126 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21127 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21128 ("Change Date"
21129 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21130 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21131 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21132 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21133 ["Compute Time Range" org-evaluate-time-range t]
21134 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21135 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21136 "--"
21137 ["Custom time format" org-toggle-time-stamp-overlays
21138 :style radio :selected org-display-custom-times]
21139 "--"
21140 ["Goto Calendar" org-goto-calendar t]
21141 ["Date from Calendar" org-date-from-calendar t]
21142 "--"
21143 ["Start/Restart Timer" org-timer-start t]
21144 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21145 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21146 ["Insert Timer String" org-timer t]
21147 ["Insert Timer Item" org-timer-item t])
21148 ("Logging work"
21149 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21150 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21151 ["Clock out" org-clock-out t]
21152 ["Clock cancel" org-clock-cancel t]
21153 "--"
21154 ["Mark as default task" org-clock-mark-default-task t]
21155 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21156 ["Goto running clock" org-clock-goto t]
21157 "--"
21158 ["Display times" org-clock-display t]
21159 ["Create clock table" org-clock-report t]
21160 "--"
21161 ["Record DONE time"
21162 (progn (setq org-log-done (not org-log-done))
21163 (message "Switching to %s will %s record a timestamp"
21164 (car org-done-keywords)
21165 (if org-log-done "automatically" "not")))
21166 :style toggle :selected org-log-done])
21167 "--"
21168 ["Agenda Command..." org-agenda t]
21169 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21170 ("File List for Agenda")
21171 ("Special views current file"
21172 ["TODO Tree" org-show-todo-tree t]
21173 ["Check Deadlines" org-check-deadlines t]
21174 ["Tags/Property tree" org-match-sparse-tree t])
21175 "--"
21176 ["Export/Publish..." org-export-dispatch t]
21177 ("LaTeX"
21178 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21179 :style toggle :selected org-cdlatex-mode]
21180 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21181 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21182 ["Modify math symbol" org-cdlatex-math-modify
21183 (org-inside-LaTeX-fragment-p)]
21184 ["Insert citation" org-reftex-citation t])
21185 "--"
21186 ("MobileOrg"
21187 ["Push Files and Views" org-mobile-push t]
21188 ["Get Captured and Flagged" org-mobile-pull t]
21189 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21190 "--"
21191 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21192 "--"
21193 ("Documentation"
21194 ["Show Version" org-version t]
21195 ["Info Documentation" org-info t])
21196 ("Customize"
21197 ["Browse Org Group" org-customize t]
21198 "--"
21199 ["Expand This Menu" org-create-customize-menu
21200 (fboundp 'customize-menu-create)])
21201 ["Send bug report" org-submit-bug-report t]
21202 "--"
21203 ("Refresh/Reload"
21204 ["Refresh setup current buffer" org-mode-restart t]
21205 ["Reload Org (after update)" org-reload t]
21206 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21209 (defun org-info (&optional node)
21210 "Read documentation for Org in the info system.
21211 With optional NODE, go directly to that node."
21212 (interactive)
21213 (info (format "(org)%s" (or node ""))))
21215 ;;;###autoload
21216 (defun org-submit-bug-report ()
21217 "Submit a bug report on Org via mail.
21219 Don't hesitate to report any problems or inaccurate documentation.
21221 If you don't have setup sending mail from (X)Emacs, please copy the
21222 output buffer into your mail program, as it gives us important
21223 information about your Org version and configuration."
21224 (interactive)
21225 (require 'reporter)
21226 (defvar reporter-prompt-for-summary-p)
21227 (org-load-modules-maybe)
21228 (org-require-autoloaded-modules)
21229 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21230 (reporter-submit-bug-report
21231 "emacs-orgmode@gnu.org"
21232 (org-version nil 'full)
21233 (let (list)
21234 (save-window-excursion
21235 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21236 (delete-other-windows)
21237 (erase-buffer)
21238 (insert "You are about to submit a bug report to the Org mailing list.
21240 We would like to add your full Org and Outline configuration to the
21241 bug report. This greatly simplifies the work of the maintainer and
21242 other experts on the mailing list.
21244 HOWEVER, some variables you have customized may contain private
21245 information. The names of customers, colleagues, or friends, might
21246 appear in the form of file names, tags, todo states, or search strings.
21247 If you answer yes to the prompt, you might want to check and remove
21248 such private information before sending the email.")
21249 (add-text-properties (point-min) (point-max) '(face org-warning))
21250 (when (yes-or-no-p "Include your Org configuration ")
21251 (mapatoms
21252 (lambda (v)
21253 (and (boundp v)
21254 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21255 (or (and (symbol-value v)
21256 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21257 (and
21258 (get v 'custom-type) (get v 'standard-value)
21259 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21260 (push v list)))))
21261 (kill-buffer (get-buffer "*Warn about privacy*"))
21262 list))
21263 nil nil
21264 "Remember to cover the basics, that is, what you expected to happen and
21265 what in fact did happen. You don't know how to make a good report? See
21267 http://orgmode.org/manual/Feedback.html#Feedback
21269 Your bug report will be posted to the Org mailing list.
21270 ------------------------------------------------------------------------")
21271 (save-excursion
21272 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21273 (replace-match "\\1Bug: \\3 [\\2]")))))
21276 (defun org-install-agenda-files-menu ()
21277 (let ((bl (buffer-list)))
21278 (save-excursion
21279 (while bl
21280 (set-buffer (pop bl))
21281 (when (derived-mode-p 'org-mode) (setq bl nil)))
21282 (when (derived-mode-p 'org-mode)
21283 (easy-menu-change
21284 '("Org") "File List for Agenda"
21285 (append
21286 (list
21287 ["Edit File List" (org-edit-agenda-file-list) t]
21288 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21289 ["Remove Current File from List" org-remove-file t]
21290 ["Cycle through agenda files" org-cycle-agenda-files t]
21291 ["Occur in all agenda files" org-occur-in-agenda-files t]
21292 "--")
21293 (mapcar 'org-file-menu-entry
21294 ;; Prevent initialization from failing.
21295 (ignore-errors (org-agenda-files t)))))))))
21297 ;;;; Documentation
21299 (defun org-require-autoloaded-modules ()
21300 (interactive)
21301 (mapc #'require
21302 '(org-agenda org-archive org-attach org-clock org-colview org-id
21303 org-table org-timer)))
21305 ;;;###autoload
21306 (defun org-reload (&optional uncompiled)
21307 "Reload all org lisp files.
21308 With prefix arg UNCOMPILED, load the uncompiled versions."
21309 (interactive "P")
21310 (require 'loadhist)
21311 (let* ((org-dir (org-find-library-dir "org"))
21312 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21313 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21314 (remove-re (format "\\`%s\\'"
21315 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21316 (feats (delete-dups
21317 (mapcar 'file-name-sans-extension
21318 (mapcar 'file-name-nondirectory
21319 (delq nil
21320 (mapcar 'feature-file
21321 features))))))
21322 (lfeat (append
21323 (sort
21324 (setq feats
21325 (delq nil (mapcar
21326 (lambda (f)
21327 (if (and (string-match feature-re f)
21328 (not (string-match remove-re f)))
21329 f nil))
21330 feats)))
21331 'string-lessp)
21332 (list "org-version" "org")))
21333 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21334 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21335 load-uncore load-misses)
21336 (setq load-misses
21337 (delq 't
21338 (mapcar (lambda (f)
21339 (or (org-load-noerror-mustsuffix (concat org-dir f))
21340 (and (string= org-dir contrib-dir)
21341 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21342 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21343 (add-to-list 'load-uncore f 'append)
21346 lfeat)))
21347 (when load-uncore
21348 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21349 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21350 (if load-misses
21351 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21352 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21353 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21355 ;;;###autoload
21356 (defun org-customize ()
21357 "Call the customize function with org as argument."
21358 (interactive)
21359 (org-load-modules-maybe)
21360 (org-require-autoloaded-modules)
21361 (customize-browse 'org))
21363 (defun org-create-customize-menu ()
21364 "Create a full customization menu for Org mode, insert it into the menu."
21365 (interactive)
21366 (org-load-modules-maybe)
21367 (org-require-autoloaded-modules)
21368 (if (fboundp 'customize-menu-create)
21369 (progn
21370 (easy-menu-change
21371 '("Org") "Customize"
21372 `(["Browse Org group" org-customize t]
21373 "--"
21374 ,(customize-menu-create 'org)
21375 ["Set" Custom-set t]
21376 ["Save" Custom-save t]
21377 ["Reset to Current" Custom-reset-current t]
21378 ["Reset to Saved" Custom-reset-saved t]
21379 ["Reset to Standard Settings" Custom-reset-standard t]))
21380 (message "\"Org\"-menu now contains full customization menu"))
21381 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21383 ;;;; Miscellaneous stuff
21385 ;;; Generally useful functions
21387 (defun org-link-display-format (s)
21388 "Replace links in string S with their description.
21389 If there is no description, use the link target."
21390 (save-match-data
21391 (replace-regexp-in-string
21392 org-bracket-link-analytic-regexp
21393 (lambda (m)
21394 (if (match-end 5) (match-string 5 m)
21395 (concat (match-string 1 m) (match-string 3 m))))
21396 s nil t)))
21398 (defun org-toggle-link-display ()
21399 "Toggle the literal or descriptive display of links."
21400 (interactive)
21401 (if org-descriptive-links
21402 (progn (org-remove-from-invisibility-spec '(org-link))
21403 (org-restart-font-lock)
21404 (setq org-descriptive-links nil))
21405 (progn (add-to-invisibility-spec '(org-link))
21406 (org-restart-font-lock)
21407 (setq org-descriptive-links t))))
21409 (defun org-in-clocktable-p ()
21410 "Check if the cursor is in a clocktable."
21411 (let ((pos (point)) start)
21412 (save-excursion
21413 (end-of-line 1)
21414 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21415 (setq start (match-beginning 0))
21416 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21417 (>= (match-end 0) pos)
21418 start))))
21420 (defun org-in-verbatim-emphasis ()
21421 (save-match-data
21422 (and (org-in-regexp org-verbatim-re 2)
21423 (>= (point) (match-beginning 3))
21424 (<= (point) (match-end 4)))))
21426 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21427 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21428 (if (and marker (marker-buffer marker)
21429 (buffer-live-p (marker-buffer marker)))
21430 (progn
21431 (pop-to-buffer-same-window (marker-buffer marker))
21432 (when (or (> marker (point-max)) (< marker (point-min)))
21433 (widen))
21434 (goto-char marker)
21435 (org-show-context 'org-goto))
21436 (if bookmark
21437 (bookmark-jump bookmark)
21438 (error "Cannot find location"))))
21440 (defun org-quote-csv-field (s)
21441 "Quote field for inclusion in CSV material."
21442 (if (string-match "[\",]" s)
21443 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21446 (defun org-force-self-insert (N)
21447 "Needed to enforce self-insert under remapping."
21448 (interactive "p")
21449 (self-insert-command N))
21451 (defun org-get-indentation (&optional line)
21452 "Get the indentation of the current line, interpreting tabs.
21453 When LINE is given, assume it represents a line and compute its indentation."
21454 (if line
21455 (when (string-match "^ *" (org-remove-tabs line))
21456 (match-end 0))
21457 (save-excursion
21458 (beginning-of-line 1)
21459 (skip-chars-forward " \t")
21460 (current-column))))
21462 (defun org-get-string-indentation (s)
21463 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21464 (let ((n -1) (i 0) (w tab-width) c)
21465 (catch 'exit
21466 (while (< (setq n (1+ n)) (length s))
21467 (setq c (aref s n))
21468 (cond ((= c ?\ ) (setq i (1+ i)))
21469 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21470 (t (throw 'exit t)))))
21473 (defun org-fix-indentation (line ind)
21474 "Fix indentation in LINE.
21475 IND is a cons cell with target and minimum indentation.
21476 If the current indentation in LINE is smaller than the minimum,
21477 leave it alone. If it is larger than ind, set it to the target."
21478 (let* ((l (org-remove-tabs line))
21479 (i (org-get-indentation l))
21480 (i1 (car ind)) (i2 (cdr ind)))
21481 (when (>= i i2) (setq l (substring line i2)))
21482 (if (> i1 0)
21483 (concat (make-string i1 ?\ ) l)
21484 l)))
21486 (defun org-fill-template (template alist)
21487 "Find each %key of ALIST in TEMPLATE and replace it."
21488 (let ((case-fold-search nil))
21489 (dolist (entry (sort (copy-sequence alist)
21490 (lambda (a b) (< (length (car a)) (length (car b))))))
21491 (setq template
21492 (replace-regexp-in-string
21493 (concat "%" (regexp-quote (car entry)))
21494 (or (cdr entry) "") template t t)))
21495 template))
21497 (defun org-quote-vert (s)
21498 "Replace \"|\" with \"\\vert\"."
21499 (while (string-match "|" s)
21500 (setq s (replace-match "\\vert" t t s)))
21503 (defun org-uuidgen-p (s)
21504 "Is S an ID created by UUIDGEN?"
21505 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21507 (defun org-in-src-block-p (&optional inside)
21508 "Whether point is in a code source block.
21509 When INSIDE is non-nil, don't consider we are within a src block
21510 when point is at #+BEGIN_SRC or #+END_SRC."
21511 (let ((case-fold-search t))
21512 (or (and (eq (get-char-property (point) 'src-block) t))
21513 (and (not inside)
21514 (save-match-data
21515 (save-excursion
21516 (beginning-of-line)
21517 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21519 (defun org-context ()
21520 "Return a list of contexts of the current cursor position.
21521 If several contexts apply, all are returned.
21522 Each context entry is a list with a symbol naming the context, and
21523 two positions indicating start and end of the context. Possible
21524 contexts are:
21526 :headline anywhere in a headline
21527 :headline-stars on the leading stars in a headline
21528 :todo-keyword on a TODO keyword (including DONE) in a headline
21529 :tags on the TAGS in a headline
21530 :priority on the priority cookie in a headline
21531 :item on the first line of a plain list item
21532 :item-bullet on the bullet/number of a plain list item
21533 :checkbox on the checkbox in a plain list item
21534 :table in an Org table
21535 :table-special on a special filed in a table
21536 :table-table in a table.el table
21537 :clocktable in a clocktable
21538 :src-block in a source block
21539 :link on a hyperlink
21540 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21541 :target on a <<target>>
21542 :radio-target on a <<<radio-target>>>
21543 :latex-fragment on a LaTeX fragment
21544 :latex-preview on a LaTeX fragment with overlaid preview image
21546 This function expects the position to be visible because it uses font-lock
21547 faces as a help to recognize the following contexts: :table-special, :link,
21548 and :keyword."
21549 (let* ((f (get-text-property (point) 'face))
21550 (faces (if (listp f) f (list f)))
21551 (case-fold-search t)
21552 (p (point)) clist o)
21553 ;; First the large context
21554 (cond
21555 ((org-at-heading-p t)
21556 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21557 (when (progn
21558 (beginning-of-line 1)
21559 (looking-at org-todo-line-tags-regexp))
21560 (push (org-point-in-group p 1 :headline-stars) clist)
21561 (push (org-point-in-group p 2 :todo-keyword) clist)
21562 (push (org-point-in-group p 4 :tags) clist))
21563 (goto-char p)
21564 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21565 (when (looking-at "\\[#[A-Z0-9]\\]")
21566 (push (org-point-in-group p 0 :priority) clist)))
21568 ((org-at-item-p)
21569 (push (org-point-in-group p 2 :item-bullet) clist)
21570 (push (list :item (point-at-bol)
21571 (save-excursion (org-end-of-item) (point)))
21572 clist)
21573 (and (org-at-item-checkbox-p)
21574 (push (org-point-in-group p 0 :checkbox) clist)))
21576 ((org-at-table-p)
21577 (push (list :table (org-table-begin) (org-table-end)) clist)
21578 (when (memq 'org-formula faces)
21579 (push (list :table-special
21580 (previous-single-property-change p 'face)
21581 (next-single-property-change p 'face)) clist)))
21582 ((org-at-table-p 'any)
21583 (push (list :table-table) clist)))
21584 (goto-char p)
21586 (let ((case-fold-search t))
21587 ;; New the "medium" contexts: clocktables, source blocks
21588 (cond ((org-in-clocktable-p)
21589 (push (list :clocktable
21590 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21591 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21592 (match-beginning 1))
21593 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21594 (match-end 0))) clist))
21595 ((org-in-src-block-p)
21596 (push (list :src-block
21597 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21598 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21599 (match-beginning 1))
21600 (and (search-forward "#+END_SRC" nil t)
21601 (match-beginning 0))) clist))))
21602 (goto-char p)
21604 ;; Now the small context
21605 (cond
21606 ((org-at-timestamp-p)
21607 (push (org-point-in-group p 0 :timestamp) clist))
21608 ((memq 'org-link faces)
21609 (push (list :link
21610 (previous-single-property-change p 'face)
21611 (next-single-property-change p 'face)) clist))
21612 ((memq 'org-special-keyword faces)
21613 (push (list :keyword
21614 (previous-single-property-change p 'face)
21615 (next-single-property-change p 'face)) clist))
21616 ((org-at-target-p)
21617 (push (org-point-in-group p 0 :target) clist)
21618 (goto-char (1- (match-beginning 0)))
21619 (when (looking-at org-radio-target-regexp)
21620 (push (org-point-in-group p 0 :radio-target) clist))
21621 (goto-char p))
21622 ((setq o (cl-some
21623 (lambda (o)
21624 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21626 (overlays-at (point))))
21627 (push (list :latex-fragment
21628 (overlay-start o) (overlay-end o)) clist)
21629 (push (list :latex-preview
21630 (overlay-start o) (overlay-end o)) clist))
21631 ((org-inside-LaTeX-fragment-p)
21632 ;; FIXME: positions wrong.
21633 (push (list :latex-fragment (point) (point)) clist)))
21635 (setq clist (nreverse (delq nil clist)))
21636 clist))
21638 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21639 "Non-nil when point is between matches of START-RE and END-RE.
21641 Also return a non-nil value when point is on one of the matches.
21643 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21644 buffer positions. Default values are the positions of headlines
21645 surrounding the point.
21647 The functions returns a cons cell whose car (resp. cdr) is the
21648 position before START-RE (resp. after END-RE)."
21649 (save-match-data
21650 (let ((pos (point))
21651 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21652 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21653 beg end)
21654 (save-excursion
21655 ;; Point is on a block when on START-RE or if START-RE can be
21656 ;; found before it...
21657 (and (or (org-in-regexp start-re)
21658 (re-search-backward start-re limit-up t))
21659 (setq beg (match-beginning 0))
21660 ;; ... and END-RE after it...
21661 (goto-char (match-end 0))
21662 (re-search-forward end-re limit-down t)
21663 (> (setq end (match-end 0)) pos)
21664 ;; ... without another START-RE in-between.
21665 (goto-char (match-beginning 0))
21666 (not (re-search-backward start-re (1+ beg) t))
21667 ;; Return value.
21668 (cons beg end))))))
21670 (defun org-in-block-p (names)
21671 "Non-nil when point belongs to a block whose name belongs to NAMES.
21673 NAMES is a list of strings containing names of blocks.
21675 Return first block name matched, or nil. Beware that in case of
21676 nested blocks, the returned name may not belong to the closest
21677 block from point."
21678 (save-match-data
21679 (catch 'exit
21680 (let ((case-fold-search t)
21681 (lim-up (save-excursion (outline-previous-heading)))
21682 (lim-down (save-excursion (outline-next-heading))))
21683 (dolist (name names)
21684 (let ((n (regexp-quote name)))
21685 (when (org-between-regexps-p
21686 (concat "^[ \t]*#\\+begin_" n)
21687 (concat "^[ \t]*#\\+end_" n)
21688 lim-up lim-down)
21689 (throw 'exit n)))))
21690 nil)))
21692 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21693 "Call `multi-occur' with buffers for all agenda files."
21694 (interactive "sOrg-files matching: ")
21695 (let* ((files (org-agenda-files))
21696 (tnames (mapcar #'file-truename files))
21697 (extra org-agenda-text-search-extra-files))
21698 (when (eq (car extra) 'agenda-archives)
21699 (setq extra (cdr extra))
21700 (setq files (org-add-archive-files files)))
21701 (dolist (f extra)
21702 (unless (member (file-truename f) tnames)
21703 (unless (member f files) (setq files (append files (list f))))
21704 (setq tnames (append tnames (list (file-truename f))))))
21705 (multi-occur
21706 (mapcar (lambda (x)
21707 (with-current-buffer
21708 ;; FIXME: Why not just (find-file-noselect x)?
21709 ;; Is it to avoid the "revert buffer" prompt?
21710 (or (get-file-buffer x) (find-file-noselect x))
21711 (widen)
21712 (current-buffer)))
21713 files)
21714 regexp)))
21716 (add-hook 'occur-mode-find-occurrence-hook
21717 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21719 (defun org-occur-link-in-agenda-files ()
21720 "Create a link and search for it in the agendas.
21721 The link is not stored in `org-stored-links', it is just created
21722 for the search purpose."
21723 (interactive)
21724 (let ((link (condition-case nil
21725 (org-store-link nil)
21726 (error "Unable to create a link to here"))))
21727 (org-occur-in-agenda-files (regexp-quote link))))
21729 (defun org-back-over-empty-lines ()
21730 "Move backwards over whitespace, to the beginning of the first empty line.
21731 Returns the number of empty lines passed."
21732 (let ((pos (point)))
21733 (if (cdr (assq 'heading org-blank-before-new-entry))
21734 (skip-chars-backward " \t\n\r")
21735 (unless (eobp)
21736 (forward-line -1)))
21737 (beginning-of-line 2)
21738 (goto-char (min (point) pos))
21739 (count-lines (point) pos)))
21741 (defun org-switch-to-buffer-other-window (&rest args)
21742 "Switch to buffer in a second window on the current frame.
21743 In particular, do not allow pop-up frames.
21744 Returns the newly created buffer."
21745 (org-no-popups
21746 (apply 'switch-to-buffer-other-window args)))
21748 (defun org-replace-escapes (string table)
21749 "Replace %-escapes in STRING with values in TABLE.
21750 TABLE is an association list with keys like \"%a\" and string values.
21751 The sequences in STRING may contain normal field width and padding information,
21752 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21753 so values can contain further %-escapes if they are define later in TABLE."
21754 (let ((tbl (copy-alist table))
21755 (case-fold-search nil)
21756 (pchg 0)
21757 re rpl)
21758 (dolist (e tbl)
21759 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21760 (when (and (cdr e) (string-match re (cdr e)))
21761 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21762 (safe "SREF"))
21763 (add-text-properties 0 3 (list 'sref sref) safe)
21764 (setcdr e (replace-match safe t t (cdr e)))))
21765 (while (string-match re string)
21766 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21767 (cdr e)))
21768 (setq string (replace-match rpl t t string))))
21769 (while (setq pchg (next-property-change pchg string))
21770 (let ((sref (get-text-property pchg 'sref string)))
21771 (when (and sref (string-match "SREF" string pchg))
21772 (setq string (replace-match sref t t string)))))
21773 string))
21775 ;;; TODO: Only called once, from ox-odt which should probably use
21776 ;;; org-export-inline-image-p or something.
21777 (defun org-file-image-p (file)
21778 "Return non-nil if FILE is an image."
21779 (save-match-data
21780 (string-match (image-file-name-regexp) file)))
21782 (defun org-get-cursor-date (&optional with-time)
21783 "Return the date at cursor in as a time.
21784 This works in the calendar and in the agenda, anywhere else it just
21785 returns the current time.
21786 If WITH-TIME is non-nil, returns the time of the event at point (in
21787 the agenda) or the current time of the day."
21788 (let (date day defd tp hod mod)
21789 (when with-time
21790 (setq tp (get-text-property (point) 'time))
21791 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21792 (setq hod (string-to-number (match-string 1 tp))
21793 mod (string-to-number (match-string 2 tp))))
21794 (or tp (let ((now (decode-time)))
21795 (setq hod (nth 2 now)
21796 mod (nth 1 now)))))
21797 (cond
21798 ((eq major-mode 'calendar-mode)
21799 (setq date (calendar-cursor-to-date)
21800 defd (encode-time 0 (or mod 0) (or hod 0)
21801 (nth 1 date) (nth 0 date) (nth 2 date))))
21802 ((eq major-mode 'org-agenda-mode)
21803 (setq day (get-text-property (point) 'day))
21804 (when day
21805 (setq date (calendar-gregorian-from-absolute day)
21806 defd (encode-time 0 (or mod 0) (or hod 0)
21807 (nth 1 date) (nth 0 date) (nth 2 date))))))
21808 (or defd (current-time))))
21810 (defun org-mark-subtree (&optional up)
21811 "Mark the current subtree.
21812 This puts point at the start of the current subtree, and mark at
21813 the end. If a numeric prefix UP is given, move up into the
21814 hierarchy of headlines by UP levels before marking the subtree."
21815 (interactive "P")
21816 (org-with-limited-levels
21817 (cond ((org-at-heading-p) (beginning-of-line))
21818 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21819 (t (outline-previous-visible-heading 1))))
21820 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21821 (if (called-interactively-p 'any)
21822 (call-interactively 'org-mark-element)
21823 (org-mark-element)))
21825 (defun org-file-newer-than-p (file time)
21826 "Non-nil if FILE is newer than TIME.
21827 FILE is a filename, as a string, TIME is a list of integers, as
21828 returned by, e.g., `current-time'."
21829 (and (file-exists-p file)
21830 ;; Only compare times up to whole seconds as some file-systems
21831 ;; (e.g. HFS+) do not retain any finer granularity. As
21832 ;; a consequence, make sure we return non-nil when the two
21833 ;; times are equal.
21834 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21835 (cl-subseq time 0 2)))))
21837 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21838 "Compile a SOURCE file using PROCESS.
21840 PROCESS is either a function or a list of shell commands, as
21841 strings. EXT is a file extension, without the leading dot, as
21842 a string. It is used to check if the process actually succeeded.
21844 PROCESS must create a file with the same base name and directory
21845 as SOURCE, but ending with EXT. The function then returns its
21846 filename. Otherwise, it raises an error. The error message can
21847 then be refined by providing string ERR-MSG, which is appended to
21848 the standard message.
21850 If PROCESS is a function, it is called with a single argument:
21851 the SOURCE file.
21853 If it is a list of commands, each of them is called using
21854 `shell-command'. By default, in each command, %b, %f, %F, %o and
21855 %O are replaced with, respectively, SOURCE base name, name, full
21856 name, directory and absolute output file name. It is possible,
21857 however, to use more place-holders by specifying them in optional
21858 argument SPEC, as an alist following the pattern
21860 (CHARACTER . REPLACEMENT-STRING).
21862 When PROCESS is a list of commands, optional argument LOG-BUF can
21863 be set to a buffer or a buffer name. `shell-command' then uses
21864 it for output."
21865 (let* ((base-name (file-name-base source))
21866 (full-name (file-truename source))
21867 (out-dir (or (file-name-directory source) "./"))
21868 (output (expand-file-name (concat base-name "." ext) out-dir))
21869 (time (current-time))
21870 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21871 (save-window-excursion
21872 (pcase process
21873 ((pred functionp) (funcall process (shell-quote-argument source)))
21874 ((pred consp)
21875 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21876 (spec (append spec
21877 `((?b . ,(shell-quote-argument base-name))
21878 (?f . ,(shell-quote-argument source))
21879 (?F . ,(shell-quote-argument full-name))
21880 (?o . ,(shell-quote-argument out-dir))
21881 (?O . ,(shell-quote-argument output))))))
21882 (dolist (command process)
21883 (shell-command (format-spec command spec) log-buf))
21884 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21885 (_ (error "No valid command to process %S%s" source err-msg))))
21886 ;; Check for process failure. Output file is expected to be
21887 ;; located in the same directory as SOURCE.
21888 (unless (org-file-newer-than-p output time)
21889 (error (format "File %S wasn't produced%s" output err-msg)))
21890 output))
21892 ;;; Indentation
21894 (defvar org-element-greater-elements)
21895 (defun org--get-expected-indentation (element contentsp)
21896 "Expected indentation column for current line, according to ELEMENT.
21897 ELEMENT is an element containing point. CONTENTSP is non-nil
21898 when indentation is to be computed according to contents of
21899 ELEMENT."
21900 (let ((type (org-element-type element))
21901 (start (org-element-property :begin element))
21902 (post-affiliated (org-element-property :post-affiliated element)))
21903 (org-with-wide-buffer
21904 (cond
21905 (contentsp
21906 (cl-case type
21907 ((diary-sexp footnote-definition) 0)
21908 ((headline inlinetask nil)
21909 (if (not org-adapt-indentation) 0
21910 (let ((level (org-current-level)))
21911 (if level (1+ level) 0))))
21912 ((item plain-list) (org-list-item-body-column post-affiliated))
21914 (goto-char start)
21915 (org-get-indentation))))
21916 ((memq type '(headline inlinetask nil))
21917 (if (org-match-line "[ \t]*$")
21918 (org--get-expected-indentation element t)
21920 ((memq type '(diary-sexp footnote-definition)) 0)
21921 ;; First paragraph of a footnote definition or an item.
21922 ;; Indent like parent.
21923 ((< (line-beginning-position) start)
21924 (org--get-expected-indentation
21925 (org-element-property :parent element) t))
21926 ;; At first line: indent according to previous sibling, if any,
21927 ;; ignoring footnote definitions and inline tasks, or parent's
21928 ;; contents.
21929 ((= (line-beginning-position) start)
21930 (catch 'exit
21931 (while t
21932 (if (= (point-min) start) (throw 'exit 0)
21933 (goto-char (1- start))
21934 (let* ((previous (org-element-at-point))
21935 (parent previous))
21936 (while (and parent (<= (org-element-property :end parent) start))
21937 (setq previous parent
21938 parent (org-element-property :parent parent)))
21939 (cond
21940 ((not previous) (throw 'exit 0))
21941 ((> (org-element-property :end previous) start)
21942 (throw 'exit (org--get-expected-indentation previous t)))
21943 ((memq (org-element-type previous)
21944 '(footnote-definition inlinetask))
21945 (setq start (org-element-property :begin previous)))
21946 (t (goto-char (org-element-property :begin previous))
21947 (throw 'exit
21948 (if (bolp) (org-get-indentation)
21949 ;; At first paragraph in an item or
21950 ;; a footnote definition.
21951 (org--get-expected-indentation
21952 (org-element-property :parent previous) t))))))))))
21953 ;; Otherwise, move to the first non-blank line above.
21955 (beginning-of-line)
21956 (let ((pos (point)))
21957 (skip-chars-backward " \r\t\n")
21958 (cond
21959 ;; Two blank lines end a footnote definition or a plain
21960 ;; list. When we indent an empty line after them, the
21961 ;; containing list or footnote definition is over, so it
21962 ;; qualifies as a previous sibling. Therefore, we indent
21963 ;; like its first line.
21964 ((and (memq type '(footnote-definition plain-list))
21965 (> (count-lines (point) pos) 2))
21966 (goto-char start)
21967 (org-get-indentation))
21968 ;; Line above is the first one of a paragraph at the
21969 ;; beginning of an item or a footnote definition. Indent
21970 ;; like parent.
21971 ((< (line-beginning-position) start)
21972 (org--get-expected-indentation
21973 (org-element-property :parent element) t))
21974 ;; Line above is the beginning of an element, i.e., point
21975 ;; was originally on the blank lines between element's start
21976 ;; and contents.
21977 ((= (line-beginning-position) post-affiliated)
21978 (org--get-expected-indentation element t))
21979 ;; POS is after contents in a greater element. Indent like
21980 ;; the beginning of the element.
21981 ((and (memq type org-element-greater-elements)
21982 (let ((cend (org-element-property :contents-end element)))
21983 (and cend (<= cend pos))))
21984 ;; As a special case, if point is at the end of a footnote
21985 ;; definition or an item, indent like the very last element
21986 ;; within. If that last element is an item, indent like
21987 ;; its contents.
21988 (if (memq type '(footnote-definition item plain-list))
21989 (let ((last (org-element-at-point)))
21990 (goto-char pos)
21991 (org--get-expected-indentation
21992 last (eq (org-element-type last) 'item)))
21993 (goto-char start)
21994 (org-get-indentation)))
21995 ;; In any other case, indent like the current line.
21996 (t (org-get-indentation)))))))))
21998 (defun org--align-node-property ()
21999 "Align node property at point.
22000 Alignment is done according to `org-property-format', which see."
22001 (when (save-excursion
22002 (beginning-of-line)
22003 (looking-at org-property-re))
22004 (replace-match
22005 (concat (match-string 4)
22006 (org-trim
22007 (format org-property-format (match-string 1) (match-string 3))))
22008 t t)))
22010 (defun org-indent-line ()
22011 "Indent line depending on context.
22013 Indentation is done according to the following rules:
22015 - Footnote definitions, diary sexps, headlines and inline tasks
22016 have to start at column 0.
22018 - On the very first line of an element, consider, in order, the
22019 next rules until one matches:
22021 1. If there's a sibling element before, ignoring footnote
22022 definitions and inline tasks, indent like its first line.
22024 2. If element has a parent, indent like its contents. More
22025 precisely, if parent is an item, indent after the
22026 description part, if any, or the bullet (see
22027 `org-list-description-max-indent'). Else, indent like
22028 parent's first line.
22030 3. Otherwise, indent relatively to current level, if
22031 `org-adapt-indentation' is non-nil, or to left margin.
22033 - On a blank line at the end of an element, indent according to
22034 the type of the element. More precisely
22036 1. If element is a plain list, an item, or a footnote
22037 definition, indent like the very last element within.
22039 2. If element is a paragraph, indent like its last non blank
22040 line.
22042 3. Otherwise, indent like its very first line.
22044 - In the code part of a source block, use language major mode
22045 to indent current line if `org-src-tab-acts-natively' is
22046 non-nil. If it is nil, do nothing.
22048 - Otherwise, indent like the first non-blank line above.
22050 The function doesn't indent an item as it could break the whole
22051 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22052 `\\[org-shiftmetaright]'.
22054 Also align node properties according to `org-property-format'."
22055 (interactive)
22056 (cond
22057 (orgstruct-is-++
22058 (let ((indent-line-function
22059 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22060 (indent-according-to-mode)))
22061 ((org-at-heading-p) 'noindent)
22063 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22064 (type (org-element-type element)))
22065 (cond ((and (memq type '(plain-list item))
22066 (= (line-beginning-position)
22067 (org-element-property :post-affiliated element)))
22068 'noindent)
22069 ((and (eq type 'latex-environment)
22070 (>= (point) (org-element-property :post-affiliated element))
22071 (< (point) (org-with-wide-buffer
22072 (goto-char (org-element-property :end element))
22073 (skip-chars-backward " \r\t\n")
22074 (line-beginning-position 2))))
22075 'noindent)
22076 ((and (eq type 'src-block)
22077 org-src-tab-acts-natively
22078 (> (line-beginning-position)
22079 (org-element-property :post-affiliated element))
22080 (< (line-beginning-position)
22081 (org-with-wide-buffer
22082 (goto-char (org-element-property :end element))
22083 (skip-chars-backward " \r\t\n")
22084 (line-beginning-position))))
22085 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22087 (let ((column (org--get-expected-indentation element nil)))
22088 ;; Preserve current column.
22089 (if (<= (current-column) (current-indentation))
22090 (indent-line-to column)
22091 (save-excursion (indent-line-to column))))
22092 ;; Align node property. Also preserve current column.
22093 (when (eq type 'node-property)
22094 (let ((column (current-column)))
22095 (org--align-node-property)
22096 (org-move-to-column column)))))))))
22098 (defun org-indent-region (start end)
22099 "Indent each non-blank line in the region.
22100 Called from a program, START and END specify the region to
22101 indent. The function will not indent contents of example blocks,
22102 verse blocks and export blocks as leading white spaces are
22103 assumed to be significant there."
22104 (interactive "r")
22105 (save-excursion
22106 (goto-char start)
22107 (skip-chars-forward " \r\t\n")
22108 (unless (eobp) (beginning-of-line))
22109 (let ((indent-to
22110 (lambda (ind pos)
22111 ;; Set IND as indentation for all lines between point and
22112 ;; POS. Blank lines are ignored. Leave point after POS
22113 ;; once done.
22114 (let ((limit (copy-marker pos)))
22115 (while (< (point) limit)
22116 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22117 (forward-line))
22118 (set-marker limit nil))))
22119 (end (copy-marker end)))
22120 (while (< (point) end)
22121 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22122 (let* ((element (org-element-at-point))
22123 (type (org-element-type element))
22124 (element-end (copy-marker (org-element-property :end element)))
22125 (ind (org--get-expected-indentation element nil)))
22126 (cond
22127 ;; Element indented as a single block. Example blocks
22128 ;; preserving indentation are a special case since the
22129 ;; "contents" must not be indented whereas the block
22130 ;; boundaries can.
22131 ((or (memq type '(export-block latex-environment))
22132 (and (eq type 'example-block)
22133 (not
22134 (or org-src-preserve-indentation
22135 (org-element-property :preserve-indent element)))))
22136 (let ((offset (- ind (org-get-indentation))))
22137 (unless (zerop offset)
22138 (indent-rigidly (org-element-property :begin element)
22139 (org-element-property :end element)
22140 offset)))
22141 (goto-char element-end))
22142 ;; Elements indented line wise. Be sure to exclude
22143 ;; example blocks (preserving indentation) and source
22144 ;; blocks from this category as they are treated
22145 ;; specially later.
22146 ((or (memq type '(paragraph table table-row))
22147 (not (or (org-element-property :contents-begin element)
22148 (memq type '(example-block src-block)))))
22149 (when (eq type 'node-property)
22150 (org--align-node-property)
22151 (beginning-of-line))
22152 (funcall indent-to ind (min element-end end)))
22153 ;; Elements consisting of three parts: before the
22154 ;; contents, the contents, and after the contents. The
22155 ;; contents are treated specially, according to the
22156 ;; element type, or not indented at all. Other parts are
22157 ;; indented as a single block.
22159 (let* ((post (copy-marker
22160 (org-element-property :post-affiliated element)))
22161 (cbeg
22162 (copy-marker
22163 (cond
22164 ((not (org-element-property :contents-begin element))
22165 ;; Fake contents for source blocks.
22166 (org-with-wide-buffer
22167 (goto-char post)
22168 (line-beginning-position 2)))
22169 ((memq type '(footnote-definition item plain-list))
22170 ;; Contents in these elements could start on
22171 ;; the same line as the beginning of the
22172 ;; element. Make sure we start indenting
22173 ;; from the second line.
22174 (org-with-wide-buffer
22175 (goto-char post)
22176 (end-of-line)
22177 (skip-chars-forward " \r\t\n")
22178 (if (eobp) (point) (line-beginning-position))))
22179 (t (org-element-property :contents-begin element)))))
22180 (cend (copy-marker
22181 (or (org-element-property :contents-end element)
22182 ;; Fake contents for source blocks.
22183 (org-with-wide-buffer
22184 (goto-char element-end)
22185 (skip-chars-backward " \r\t\n")
22186 (line-beginning-position)))
22187 t)))
22188 ;; Do not change items indentation individually as it
22189 ;; might break the list as a whole. On the other
22190 ;; hand, when at a plain list, indent it as a whole.
22191 (cond ((eq type 'plain-list)
22192 (let ((offset (- ind (org-get-indentation))))
22193 (unless (zerop offset)
22194 (indent-rigidly (org-element-property :begin element)
22195 (org-element-property :end element)
22196 offset))
22197 (goto-char cbeg)))
22198 ((eq type 'item) (goto-char cbeg))
22199 (t (funcall indent-to ind (min cbeg end))))
22200 (when (< (point) end)
22201 (cl-case type
22202 ((example-block verse-block))
22203 (src-block
22204 ;; In a source block, indent source code
22205 ;; according to language major mode, but only if
22206 ;; `org-src-tab-acts-natively' is non-nil.
22207 (when (and (< (point) end) org-src-tab-acts-natively)
22208 (ignore-errors
22209 (org-babel-do-in-edit-buffer
22210 (indent-region (point-min) (point-max))))))
22211 (t (org-indent-region (point) (min cend end))))
22212 (goto-char (min cend end))
22213 (when (< (point) end)
22214 (funcall indent-to ind (min element-end end))))
22215 (set-marker post nil)
22216 (set-marker cbeg nil)
22217 (set-marker cend nil))))
22218 (set-marker element-end nil))))
22219 (set-marker end nil))))
22221 (defun org-indent-drawer ()
22222 "Indent the drawer at point."
22223 (interactive)
22224 (unless (save-excursion
22225 (beginning-of-line)
22226 (looking-at-p org-drawer-regexp))
22227 (user-error "Not at a drawer"))
22228 (let ((element (org-element-at-point)))
22229 (unless (memq (org-element-type element) '(drawer property-drawer))
22230 (user-error "Not at a drawer"))
22231 (org-with-wide-buffer
22232 (org-indent-region (org-element-property :begin element)
22233 (org-element-property :end element))))
22234 (message "Drawer at point indented"))
22236 (defun org-indent-block ()
22237 "Indent the block at point."
22238 (interactive)
22239 (unless (save-excursion
22240 (beginning-of-line)
22241 (let ((case-fold-search t))
22242 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22243 (user-error "Not at a block"))
22244 (let ((element (org-element-at-point)))
22245 (unless (memq (org-element-type element)
22246 '(comment-block center-block dynamic-block example-block
22247 export-block quote-block special-block
22248 src-block verse-block))
22249 (user-error "Not at a block"))
22250 (org-with-wide-buffer
22251 (org-indent-region (org-element-property :begin element)
22252 (org-element-property :end element))))
22253 (message "Block at point indented"))
22256 ;;; Filling
22258 ;; We use our own fill-paragraph and auto-fill functions.
22260 ;; `org-fill-paragraph' relies on adaptive filling and context
22261 ;; checking. Appropriate `fill-prefix' is computed with
22262 ;; `org-adaptive-fill-function'.
22264 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22265 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22266 ;; `org-adaptive-fill-function' value. Internally,
22267 ;; `org-comment-line-break-function' breaks the line.
22269 ;; `org-setup-filling' installs filling and auto-filling related
22270 ;; variables during `org-mode' initialization.
22272 (defun org-setup-filling ()
22273 (require 'org-element)
22274 ;; Prevent auto-fill from inserting unwanted new items.
22275 (when (boundp 'fill-nobreak-predicate)
22276 (setq-local
22277 fill-nobreak-predicate
22278 (org-uniquify
22279 (append fill-nobreak-predicate
22280 '(org-fill-line-break-nobreak-p
22281 org-fill-n-macro-as-item-nobreak-p
22282 org-fill-paragraph-with-timestamp-nobreak-p)))))
22283 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22284 (setq-local paragraph-start paragraph-ending)
22285 (setq-local paragraph-separate paragraph-ending))
22286 (setq-local fill-paragraph-function 'org-fill-paragraph)
22287 (setq-local auto-fill-inhibit-regexp nil)
22288 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22289 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22290 (setq-local comment-line-break-function 'org-comment-line-break-function))
22292 (defun org-fill-line-break-nobreak-p ()
22293 "Non-nil when a new line at point would create an Org line break."
22294 (save-excursion
22295 (skip-chars-backward "[ \t]")
22296 (skip-chars-backward "\\\\")
22297 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22299 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22300 "Non-nil when a new line at point would split a timestamp."
22301 (and (org-at-timestamp-p 'lax)
22302 (not (looking-at org-ts-regexp-both))))
22304 (defun org-fill-n-macro-as-item-nobreak-p ()
22305 "Non-nil when a new line at point would create a new list."
22306 ;; During export, a "n" macro followed by a dot or a closing
22307 ;; parenthesis can end up being parsed as a new list item.
22308 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22310 (declare-function message-in-body-p "message" ())
22311 (defvar orgtbl-line-start-regexp) ; From org-table.el
22312 (defun org-adaptive-fill-function ()
22313 "Compute a fill prefix for the current line.
22314 Return fill prefix, as a string, or nil if current line isn't
22315 meant to be filled. For convenience, if `adaptive-fill-regexp'
22316 matches in paragraphs or comments, use it."
22317 (catch 'exit
22318 (when (derived-mode-p 'message-mode)
22319 (save-excursion
22320 (beginning-of-line)
22321 (cond ((not (message-in-body-p)) (throw 'exit nil))
22322 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22323 ((looking-at message-cite-prefix-regexp)
22324 (throw 'exit (match-string-no-properties 0)))
22325 ((looking-at org-outline-regexp)
22326 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22327 (org-with-wide-buffer
22328 (unless (org-at-heading-p)
22329 (let* ((p (line-beginning-position))
22330 (element (save-excursion
22331 (beginning-of-line)
22332 (org-element-at-point)))
22333 (type (org-element-type element))
22334 (post-affiliated (org-element-property :post-affiliated element)))
22335 (unless (< p post-affiliated)
22336 (cl-case type
22337 (comment
22338 (save-excursion
22339 (beginning-of-line)
22340 (looking-at "[ \t]*")
22341 (concat (match-string 0) "# ")))
22342 (footnote-definition "")
22343 ((item plain-list)
22344 (make-string (org-list-item-body-column post-affiliated) ?\s))
22345 (paragraph
22346 ;; Fill prefix is usually the same as the current line,
22347 ;; unless the paragraph is at the beginning of an item.
22348 (let ((parent (org-element-property :parent element)))
22349 (save-excursion
22350 (beginning-of-line)
22351 (cond ((eq (org-element-type parent) 'item)
22352 (make-string (org-list-item-body-column
22353 (org-element-property :begin parent))
22354 ?\s))
22355 ((and adaptive-fill-regexp
22356 ;; Locally disable
22357 ;; `adaptive-fill-function' to let
22358 ;; `fill-context-prefix' handle
22359 ;; `adaptive-fill-regexp' variable.
22360 (let (adaptive-fill-function)
22361 (fill-context-prefix
22362 post-affiliated
22363 (org-element-property :end element)))))
22364 ((looking-at "[ \t]+") (match-string 0))
22365 (t "")))))
22366 (comment-block
22367 ;; Only fill contents if P is within block boundaries.
22368 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22369 (forward-line)
22370 (point)))
22371 (cend (save-excursion
22372 (goto-char (org-element-property :end element))
22373 (skip-chars-backward " \r\t\n")
22374 (line-beginning-position))))
22375 (when (and (>= p cbeg) (< p cend))
22376 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22377 (match-string 0)
22378 "")))))))))))
22380 (declare-function message-goto-body "message" ())
22381 (defvar message-cite-prefix-regexp) ; From message.el
22383 (defun org-fill-element (&optional justify)
22384 "Fill element at point, when applicable.
22386 This function only applies to comment blocks, comments, example
22387 blocks and paragraphs. Also, as a special case, re-align table
22388 when point is at one.
22390 If JUSTIFY is non-nil (interactively, with prefix argument),
22391 justify as well. If `sentence-end-double-space' is non-nil, then
22392 period followed by one space does not end a sentence, so don't
22393 break a line there. The variable `fill-column' controls the
22394 width for filling.
22396 For convenience, when point is at a plain list, an item or
22397 a footnote definition, try to fill the first paragraph within."
22398 (with-syntax-table org-mode-transpose-word-syntax-table
22399 ;; Move to end of line in order to get the first paragraph within
22400 ;; a plain list or a footnote definition.
22401 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22402 ;; First check if point is in a blank line at the beginning of
22403 ;; the buffer. In that case, ignore filling.
22404 (cl-case (org-element-type element)
22405 ;; Use major mode filling function is src blocks.
22406 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22407 ;; Align Org tables, leave table.el tables as-is.
22408 (table-row (org-table-align) t)
22409 (table
22410 (when (eq (org-element-property :type element) 'org)
22411 (save-excursion
22412 (goto-char (org-element-property :post-affiliated element))
22413 (org-table-align)))
22415 (paragraph
22416 ;; Paragraphs may contain `line-break' type objects.
22417 (let ((beg (max (point-min)
22418 (org-element-property :contents-begin element)))
22419 (end (min (point-max)
22420 (org-element-property :contents-end element))))
22421 ;; Do nothing if point is at an affiliated keyword.
22422 (if (< (line-end-position) beg) t
22423 (when (derived-mode-p 'message-mode)
22424 ;; In `message-mode', do not fill following citation
22425 ;; in current paragraph nor text before message body.
22426 (let ((body-start (save-excursion (message-goto-body))))
22427 (when body-start (setq beg (max body-start beg))))
22428 (when (save-excursion
22429 (re-search-forward
22430 (concat "^" message-cite-prefix-regexp) end t))
22431 (setq end (match-beginning 0))))
22432 ;; Fill paragraph, taking line breaks into account.
22433 (save-excursion
22434 (goto-char beg)
22435 (let ((cuts (list beg)))
22436 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22437 (when (eq 'line-break
22438 (org-element-type
22439 (save-excursion (backward-char)
22440 (org-element-context))))
22441 (push (point) cuts)))
22442 (dolist (c (delq end cuts))
22443 (fill-region-as-paragraph c end justify)
22444 (setq end c))))
22445 t)))
22446 ;; Contents of `comment-block' type elements should be
22447 ;; filled as plain text, but only if point is within block
22448 ;; markers.
22449 (comment-block
22450 (let* ((case-fold-search t)
22451 (beg (save-excursion
22452 (goto-char (org-element-property :begin element))
22453 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22454 (forward-line)
22455 (point)))
22456 (end (save-excursion
22457 (goto-char (org-element-property :end element))
22458 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22459 (line-beginning-position))))
22460 (if (or (< (point) beg) (> (point) end)) t
22461 (fill-region-as-paragraph
22462 (save-excursion (end-of-line)
22463 (re-search-backward "^[ \t]*$" beg 'move)
22464 (line-beginning-position))
22465 (save-excursion (beginning-of-line)
22466 (re-search-forward "^[ \t]*$" end 'move)
22467 (line-beginning-position))
22468 justify))))
22469 ;; Fill comments.
22470 (comment
22471 (let ((begin (org-element-property :post-affiliated element))
22472 (end (org-element-property :end element)))
22473 (when (and (>= (point) begin) (<= (point) end))
22474 (let ((begin (save-excursion
22475 (end-of-line)
22476 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22477 (progn (forward-line) (point))
22478 begin)))
22479 (end (save-excursion
22480 (end-of-line)
22481 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22482 (1- (line-beginning-position))
22483 (skip-chars-backward " \r\t\n")
22484 (line-end-position)))))
22485 ;; Do not fill comments when at a blank line.
22486 (when (> end begin)
22487 (let ((fill-prefix
22488 (save-excursion
22489 (beginning-of-line)
22490 (looking-at "[ \t]*#")
22491 (let ((comment-prefix (match-string 0)))
22492 (goto-char (match-end 0))
22493 (if (looking-at adaptive-fill-regexp)
22494 (concat comment-prefix (match-string 0))
22495 (concat comment-prefix " "))))))
22496 (save-excursion
22497 (fill-region-as-paragraph begin end justify))))))
22499 ;; Ignore every other element.
22500 (otherwise t)))))
22502 (defun org-fill-paragraph (&optional justify region)
22503 "Fill element at point, when applicable.
22505 This function only applies to comment blocks, comments, example
22506 blocks and paragraphs. Also, as a special case, re-align table
22507 when point is at one.
22509 For convenience, when point is at a plain list, an item or
22510 a footnote definition, try to fill the first paragraph within.
22512 If JUSTIFY is non-nil (interactively, with prefix argument),
22513 justify as well. If `sentence-end-double-space' is non-nil, then
22514 period followed by one space does not end a sentence, so don't
22515 break a line there. The variable `fill-column' controls the
22516 width for filling.
22518 The REGION argument is non-nil if called interactively; in that
22519 case, if Transient Mark mode is enabled and the mark is active,
22520 fill each of the elements in the active region, instead of just
22521 filling the current element."
22522 (interactive (progn
22523 (barf-if-buffer-read-only)
22524 (list (if current-prefix-arg 'full) t)))
22525 (cond
22526 ((and (derived-mode-p 'message-mode)
22527 (or (not (message-in-body-p))
22528 (save-excursion (move-beginning-of-line 1)
22529 (looking-at message-cite-prefix-regexp))))
22530 ;; First ensure filling is correct in message-mode.
22531 (let ((fill-paragraph-function
22532 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22533 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22534 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22535 (paragraph-separate
22536 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22537 (fill-paragraph nil)))
22538 ((and region transient-mark-mode mark-active
22539 (not (eq (region-beginning) (region-end))))
22540 (let ((origin (point-marker))
22541 (start (region-beginning)))
22542 (unwind-protect
22543 (progn
22544 (goto-char (region-end))
22545 (while (> (point) start)
22546 (org-backward-paragraph)
22547 (org-fill-element justify)))
22548 (goto-char origin)
22549 (set-marker origin nil))))
22550 (t (org-fill-element justify))))
22551 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22553 (defun org-auto-fill-function ()
22554 "Auto-fill function."
22555 ;; Check if auto-filling is meaningful.
22556 (let ((fc (current-fill-column)))
22557 (when (and fc (> (current-column) fc))
22558 (let* ((fill-prefix (org-adaptive-fill-function))
22559 ;; Enforce empty fill prefix, if required. Otherwise, it
22560 ;; will be computed again.
22561 (adaptive-fill-mode (not (equal fill-prefix ""))))
22562 (when fill-prefix (do-auto-fill))))))
22564 (defun org-comment-line-break-function (&optional soft)
22565 "Break line at point and indent, continuing comment if within one.
22566 The inserted newline is marked hard if variable
22567 `use-hard-newlines' is true, unless optional argument SOFT is
22568 non-nil."
22569 (if soft (insert-and-inherit ?\n) (newline 1))
22570 (save-excursion (forward-char -1) (delete-horizontal-space))
22571 (delete-horizontal-space)
22572 (indent-to-left-margin)
22573 (insert-before-markers-and-inherit fill-prefix))
22576 ;;; Fixed Width Areas
22578 (defun org-toggle-fixed-width ()
22579 "Toggle fixed-width markup.
22581 Add or remove fixed-width markup on current line, whenever it
22582 makes sense. Return an error otherwise.
22584 If a region is active and if it contains only fixed-width areas
22585 or blank lines, remove all fixed-width markup in it. If the
22586 region contains anything else, convert all non-fixed-width lines
22587 to fixed-width ones.
22589 Blank lines at the end of the region are ignored unless the
22590 region only contains such lines."
22591 (interactive)
22592 (if (not (org-region-active-p))
22593 ;; No region:
22595 ;; Remove fixed width marker only in a fixed-with element.
22597 ;; Add fixed width maker in paragraphs, in blank lines after
22598 ;; elements or at the beginning of a headline or an inlinetask,
22599 ;; and before any one-line elements (e.g., a clock).
22600 (progn
22601 (beginning-of-line)
22602 (let* ((element (org-element-at-point))
22603 (type (org-element-type element)))
22604 (cond
22605 ((and (eq type 'fixed-width)
22606 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22607 (replace-match
22608 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22609 ((and (memq type '(babel-call clock comment diary-sexp headline
22610 horizontal-rule keyword paragraph
22611 planning))
22612 (<= (org-element-property :post-affiliated element) (point)))
22613 (skip-chars-forward " \t")
22614 (insert ": "))
22615 ((and (looking-at-p "[ \t]*$")
22616 (or (eq type 'inlinetask)
22617 (save-excursion
22618 (skip-chars-forward " \r\t\n")
22619 (<= (org-element-property :end element) (point)))))
22620 (delete-region (point) (line-end-position))
22621 (org-indent-line)
22622 (insert ": "))
22623 (t (user-error "Cannot insert a fixed-width line here")))))
22624 ;; Region active.
22625 (let* ((begin (save-excursion
22626 (goto-char (region-beginning))
22627 (line-beginning-position)))
22628 (end (copy-marker
22629 (save-excursion
22630 (goto-char (region-end))
22631 (unless (eolp) (beginning-of-line))
22632 (if (save-excursion (re-search-backward "\\S-" begin t))
22633 (progn (skip-chars-backward " \r\t\n") (point))
22634 (point)))))
22635 (all-fixed-width-p
22636 (catch 'not-all-p
22637 (save-excursion
22638 (goto-char begin)
22639 (skip-chars-forward " \r\t\n")
22640 (when (eobp) (throw 'not-all-p nil))
22641 (while (< (point) end)
22642 (let ((element (org-element-at-point)))
22643 (if (eq (org-element-type element) 'fixed-width)
22644 (goto-char (org-element-property :end element))
22645 (throw 'not-all-p nil))))
22646 t))))
22647 (if all-fixed-width-p
22648 (save-excursion
22649 (goto-char begin)
22650 (while (< (point) end)
22651 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22652 (replace-match
22653 "" nil nil nil
22654 (if (= (line-end-position) (match-end 0)) 0 1)))
22655 (forward-line)))
22656 (let ((min-ind (point-max)))
22657 ;; Find minimum indentation across all lines.
22658 (save-excursion
22659 (goto-char begin)
22660 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22661 (setq min-ind 0)
22662 (catch 'zerop
22663 (while (< (point) end)
22664 (unless (looking-at-p "[ \t]*$")
22665 (let ((ind (org-get-indentation)))
22666 (setq min-ind (min min-ind ind))
22667 (when (zerop ind) (throw 'zerop t))))
22668 (forward-line)))))
22669 ;; Loop over all lines and add fixed-width markup everywhere
22670 ;; but in fixed-width lines.
22671 (save-excursion
22672 (goto-char begin)
22673 (while (< (point) end)
22674 (cond
22675 ((org-at-heading-p)
22676 (insert ": ")
22677 (forward-line)
22678 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22679 (insert ":")
22680 (forward-line)))
22681 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22682 (let* ((element (org-element-at-point))
22683 (element-end (org-element-property :end element)))
22684 (if (eq (org-element-type element) 'fixed-width)
22685 (progn (goto-char element-end)
22686 (skip-chars-backward " \r\t\n")
22687 (forward-line))
22688 (let ((limit (min end element-end)))
22689 (while (< (point) limit)
22690 (org-move-to-column min-ind t)
22691 (insert ": ")
22692 (forward-line))))))
22694 (org-move-to-column min-ind t)
22695 (insert ": ")
22696 (forward-line)))))))
22697 (set-marker end nil))))
22700 ;;; Comments
22702 ;; Org comments syntax is quite complex. It requires the entire line
22703 ;; to be just a comment. Also, even with the right syntax at the
22704 ;; beginning of line, some elements (e.g., verse-block or
22705 ;; example-block) don't accept comments. Usual Emacs comment commands
22706 ;; cannot cope with those requirements. Therefore, Org replaces them.
22708 ;; Org still relies on `comment-dwim', but cannot trust
22709 ;; `comment-only-p'. So, `comment-region-function' and
22710 ;; `uncomment-region-function' both point
22711 ;; to`org-comment-or-uncomment-region'. Eventually,
22712 ;; `org-insert-comment' takes care of insertion of comments at the
22713 ;; beginning of line.
22715 ;; `org-setup-comments-handling' install comments related variables
22716 ;; during `org-mode' initialization.
22718 (defun org-setup-comments-handling ()
22719 (interactive)
22720 (setq-local comment-use-syntax nil)
22721 (setq-local comment-start "# ")
22722 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22723 (setq-local comment-insert-comment-function 'org-insert-comment)
22724 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22725 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22727 (defun org-insert-comment ()
22728 "Insert an empty comment above current line.
22729 If the line is empty, insert comment at its beginning. When
22730 point is within a source block, comment according to the related
22731 major mode."
22732 (if (let ((element (org-element-at-point)))
22733 (and (eq (org-element-type element) 'src-block)
22734 (< (save-excursion
22735 (goto-char (org-element-property :post-affiliated element))
22736 (line-end-position))
22737 (point))
22738 (> (save-excursion
22739 (goto-char (org-element-property :end element))
22740 (skip-chars-backward " \r\t\n")
22741 (line-beginning-position))
22742 (point))))
22743 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22744 (beginning-of-line)
22745 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22746 (open-line 1))
22747 (org-indent-line)
22748 (insert "# ")))
22750 (defvar comment-empty-lines) ; From newcomment.el.
22751 (defun org-comment-or-uncomment-region (beg end &rest _)
22752 "Comment or uncomment each non-blank line in the region.
22753 Uncomment each non-blank line between BEG and END if it only
22754 contains commented lines. Otherwise, comment them. If region is
22755 strictly within a source block, use appropriate comment syntax."
22756 (if (let ((element (org-element-at-point)))
22757 (and (eq (org-element-type element) 'src-block)
22758 (< (save-excursion
22759 (goto-char (org-element-property :post-affiliated element))
22760 (line-end-position))
22761 beg)
22762 (>= (save-excursion
22763 (goto-char (org-element-property :end element))
22764 (skip-chars-backward " \r\t\n")
22765 (line-beginning-position))
22766 end)))
22767 ;; Translate region boundaries for the Org buffer to the source
22768 ;; buffer.
22769 (let ((offset (- end beg)))
22770 (save-excursion
22771 (goto-char beg)
22772 (org-babel-do-in-edit-buffer
22773 (comment-or-uncomment-region (point) (+ offset (point))))))
22774 (save-restriction
22775 ;; Restrict region
22776 (narrow-to-region (save-excursion (goto-char beg)
22777 (skip-chars-forward " \r\t\n" end)
22778 (line-beginning-position))
22779 (save-excursion (goto-char end)
22780 (skip-chars-backward " \r\t\n" beg)
22781 (line-end-position)))
22782 (let ((uncommentp
22783 ;; UNCOMMENTP is non-nil when every non blank line between
22784 ;; BEG and END is a comment.
22785 (save-excursion
22786 (goto-char (point-min))
22787 (while (and (not (eobp))
22788 (let ((element (org-element-at-point)))
22789 (and (eq (org-element-type element) 'comment)
22790 (goto-char (min (point-max)
22791 (org-element-property
22792 :end element)))))))
22793 (eobp))))
22794 (if uncommentp
22795 ;; Only blank lines and comments in region: uncomment it.
22796 (save-excursion
22797 (goto-char (point-min))
22798 (while (not (eobp))
22799 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22800 (replace-match "" nil nil nil 1))
22801 (forward-line)))
22802 ;; Comment each line in region.
22803 (let ((min-indent (point-max)))
22804 ;; First find the minimum indentation across all lines.
22805 (save-excursion
22806 (goto-char (point-min))
22807 (while (and (not (eobp)) (not (zerop min-indent)))
22808 (unless (looking-at "[ \t]*$")
22809 (setq min-indent (min min-indent (current-indentation))))
22810 (forward-line)))
22811 ;; Then loop over all lines.
22812 (save-excursion
22813 (goto-char (point-min))
22814 (while (not (eobp))
22815 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22816 ;; Don't get fooled by invisible text (e.g. link path)
22817 ;; when moving to column MIN-INDENT.
22818 (let ((buffer-invisibility-spec nil))
22819 (org-move-to-column min-indent t))
22820 (insert comment-start))
22821 (forward-line)))))))))
22823 (defun org-comment-dwim (_arg)
22824 "Call the comment command you mean.
22825 Call `org-toggle-comment' if on a heading, otherwise call
22826 `comment-dwim', within a source edit buffer if needed."
22827 (interactive "*P")
22828 (cond ((org-at-heading-p)
22829 (call-interactively #'org-toggle-comment))
22830 ((org-in-src-block-p)
22831 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22832 (t (call-interactively #'comment-dwim))))
22835 ;;; Timestamps API
22837 ;; This section contains tools to operate on timestamp objects, as
22838 ;; returned by, e.g. `org-element-context'.
22840 (defun org-timestamp--to-internal-time (timestamp &optional end)
22841 "Encode TIMESTAMP object into Emacs internal time.
22842 Use end of date range or time range when END is non-nil."
22843 (apply #'encode-time
22844 (cons 0
22845 (mapcar
22846 (lambda (prop) (or (org-element-property prop timestamp) 0))
22847 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22848 '(:minute-start :hour-start :day-start :month-start
22849 :year-start))))))
22851 (defun org-timestamp-has-time-p (timestamp)
22852 "Non-nil when TIMESTAMP has a time specified."
22853 (org-element-property :hour-start timestamp))
22855 (defun org-timestamp-format (timestamp format &optional end utc)
22856 "Format a TIMESTAMP object into a string.
22858 FORMAT is a format specifier to be passed to
22859 `format-time-string'.
22861 When optional argument END is non-nil, use end of date-range or
22862 time-range, if possible.
22864 When optional argument UTC is non-nil, time will be expressed as
22865 Universal Time."
22866 (format-time-string
22867 format (org-timestamp--to-internal-time timestamp end)
22868 (and utc t)))
22870 (defun org-timestamp-split-range (timestamp &optional end)
22871 "Extract a TIMESTAMP object from a date or time range.
22873 END, when non-nil, means extract the end of the range.
22874 Otherwise, extract its start.
22876 Return a new timestamp object."
22877 (let ((type (org-element-property :type timestamp)))
22878 (if (memq type '(active inactive diary)) timestamp
22879 (let ((split-ts (org-element-copy timestamp)))
22880 ;; Set new type.
22881 (org-element-put-property
22882 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22883 ;; Copy start properties over end properties if END is
22884 ;; non-nil. Otherwise, copy end properties over `start' ones.
22885 (let ((p-alist '((:minute-start . :minute-end)
22886 (:hour-start . :hour-end)
22887 (:day-start . :day-end)
22888 (:month-start . :month-end)
22889 (:year-start . :year-end))))
22890 (dolist (p-cell p-alist)
22891 (org-element-put-property
22892 split-ts
22893 (funcall (if end #'car #'cdr) p-cell)
22894 (org-element-property
22895 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22896 ;; Eventually refresh `:raw-value'.
22897 (org-element-put-property split-ts :raw-value nil)
22898 (org-element-put-property
22899 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22901 (defun org-timestamp-translate (timestamp &optional boundary)
22902 "Translate TIMESTAMP object to custom format.
22904 Format string is defined in `org-time-stamp-custom-formats',
22905 which see.
22907 When optional argument BOUNDARY is non-nil, it is either the
22908 symbol `start' or `end'. In this case, only translate the
22909 starting or ending part of TIMESTAMP if it is a date or time
22910 range. Otherwise, translate both parts.
22912 Return timestamp as-is if `org-display-custom-times' is nil or if
22913 it has a `diary' type."
22914 (let ((type (org-element-property :type timestamp)))
22915 (if (or (not org-display-custom-times) (eq type 'diary))
22916 (org-element-interpret-data timestamp)
22917 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22918 org-time-stamp-custom-formats)))
22919 (if (and (not boundary) (memq type '(active-range inactive-range)))
22920 (concat (org-timestamp-format timestamp fmt)
22921 "--"
22922 (org-timestamp-format timestamp fmt t))
22923 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22927 ;;; Other stuff.
22929 (defvar reftex-docstruct-symbol)
22930 (defvar org--rds)
22932 (defun org-reftex-citation ()
22933 "Use reftex-citation to insert a citation into the buffer.
22934 This looks for a line like
22936 #+BIBLIOGRAPHY: foo plain option:-d
22938 and derives from it that foo.bib is the bibliography file relevant
22939 for this document. It then installs the necessary environment for RefTeX
22940 to work in this buffer and calls `reftex-citation' to insert a citation
22941 into the buffer.
22943 Export of such citations to both LaTeX and HTML is handled by the contributed
22944 package ox-bibtex by Taru Karttunen."
22945 (interactive)
22946 (let ((reftex-docstruct-symbol 'org--rds)
22947 org--rds bib)
22948 (org-with-wide-buffer
22949 (let ((case-fold-search t)
22950 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22951 (if (not (save-excursion
22952 (or (re-search-forward re nil t)
22953 (re-search-backward re nil t))))
22954 (user-error "No bibliography defined in file")
22955 (setq bib (concat (match-string 1) ".bib")
22956 org--rds (list (list 'bib bib))))))
22957 (call-interactively 'reftex-citation)))
22959 ;;;; Functions extending outline functionality
22961 (defun org-beginning-of-line (&optional n)
22962 "Go to the beginning of the current visible line.
22964 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22965 tags on the first attempt, and only move to after the tags when
22966 the cursor is already beyond the end of the headline.
22968 With argument N not nil or 1, move forward N - 1 lines first."
22969 (interactive "^p")
22970 (let ((origin (point))
22971 (special (pcase org-special-ctrl-a/e
22972 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22973 deactivate-mark)
22974 ;; First move to a visible line.
22975 (if (bound-and-true-p visual-line-mode)
22976 (beginning-of-visual-line n)
22977 (move-beginning-of-line n)
22978 ;; `move-beginning-of-line' may leave point after invisible
22979 ;; characters if line starts with such of these (e.g., with
22980 ;; a link at column 0). Really move to the beginning of the
22981 ;; current visible line.
22982 (beginning-of-line))
22983 (cond
22984 ;; No special behavior. Point is already at the beginning of
22985 ;; a line, logical or visual.
22986 ((not special))
22987 ;; `beginning-of-visual-line' left point before logical beginning
22988 ;; of line: point is at the beginning of a visual line. Bail
22989 ;; out.
22990 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22991 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22992 ;; At a headline, special position is before the title, but
22993 ;; after any TODO keyword or priority cookie.
22994 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22995 (line-end-position)))
22996 (bol (point)))
22997 (if (eq special 'reversed)
22998 (when (and (= origin bol) (eq last-command this-command))
22999 (goto-char refpos))
23000 (when (or (> origin refpos) (= origin bol))
23001 (goto-char refpos)))))
23002 ((and (looking-at org-list-full-item-re)
23003 (memq (org-element-type (save-match-data (org-element-at-point)))
23004 '(item plain-list)))
23005 ;; Set special position at first white space character after
23006 ;; bullet, and check-box, if any.
23007 (let ((after-bullet
23008 (let ((box (match-end 3)))
23009 (cond ((not box) (match-end 1))
23010 ((eq (char-after box) ?\s) (1+ box))
23011 (t box)))))
23012 (if (eq special 'reversed)
23013 (when (and (= (point) origin) (eq last-command this-command))
23014 (goto-char after-bullet))
23015 (when (or (> origin after-bullet) (= (point) origin))
23016 (goto-char after-bullet)))))
23017 ;; No special context. Point is already at beginning of line.
23018 (t nil))))
23020 (defun org-end-of-line (&optional n)
23021 "Go to the end of the line, but before ellipsis, if any.
23023 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23024 tags on the first attempt, and only move to after the tags when
23025 the cursor is already beyond the end of the headline.
23027 With argument N not nil or 1, move forward N - 1 lines first."
23028 (interactive "^p")
23029 (let ((origin (point))
23030 (special (pcase org-special-ctrl-a/e
23031 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23032 deactivate-mark)
23033 ;; First move to a visible line.
23034 (if (bound-and-true-p visual-line-mode)
23035 (beginning-of-visual-line n)
23036 (move-beginning-of-line n))
23037 (cond
23038 ;; At a headline, with tags.
23039 ((and special
23040 (save-excursion
23041 (beginning-of-line)
23042 (let ((case-fold-search nil))
23043 (looking-at org-complex-heading-regexp)))
23044 (match-end 5))
23045 (let ((tags (save-excursion
23046 (goto-char (match-beginning 5))
23047 (skip-chars-backward " \t")
23048 (point)))
23049 (visual-end (and (bound-and-true-p visual-line-mode)
23050 (save-excursion
23051 (end-of-visual-line)
23052 (point)))))
23053 ;; If `end-of-visual-line' brings us before end of line or
23054 ;; even tags, i.e., the headline spans over multiple visual
23055 ;; lines, move there.
23056 (cond ((and visual-end
23057 (< visual-end tags)
23058 (<= origin visual-end))
23059 (goto-char visual-end))
23060 ((eq special 'reversed)
23061 (if (and (= origin (line-end-position))
23062 (eq this-command last-command))
23063 (goto-char tags)
23064 (end-of-line)))
23066 (if (or (< origin tags) (= origin (line-end-position)))
23067 (goto-char tags)
23068 (end-of-line))))))
23069 ((bound-and-true-p visual-line-mode)
23070 (let ((bol (line-beginning-position)))
23071 (end-of-visual-line)
23072 ;; If `end-of-visual-line' gets us past the ellipsis at the
23073 ;; end of a line, backtrack and use `end-of-line' instead.
23074 (when (/= bol (line-beginning-position))
23075 (goto-char bol)
23076 (end-of-line))))
23077 (t (end-of-line)))))
23079 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23080 (define-key org-mode-map "\C-e" 'org-end-of-line)
23082 (defun org-backward-sentence (&optional _arg)
23083 "Go to beginning of sentence, or beginning of table field.
23084 This will call `backward-sentence' or `org-table-beginning-of-field',
23085 depending on context."
23086 (interactive)
23087 (let* ((element (org-element-at-point))
23088 (contents-begin (org-element-property :contents-begin element))
23089 (table (org-element-lineage element '(table) t)))
23090 (if (and table
23091 (> (point) contents-begin)
23092 (<= (point) (org-element-property :contents-end table)))
23093 (call-interactively #'org-table-beginning-of-field)
23094 (save-restriction
23095 (when (and contents-begin
23096 (< (point-min) contents-begin)
23097 (> (point) contents-begin))
23098 (narrow-to-region contents-begin
23099 (org-element-property :contents-end element)))
23100 (call-interactively #'backward-sentence)))))
23102 (defun org-forward-sentence (&optional _arg)
23103 "Go to end of sentence, or end of table field.
23104 This will call `forward-sentence' or `org-table-end-of-field',
23105 depending on context."
23106 (interactive)
23107 (if (and (org-at-heading-p)
23108 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23109 (save-restriction
23110 (narrow-to-region (line-beginning-position) (line-end-position))
23111 (call-interactively #'forward-sentence))
23112 (let* ((element (org-element-at-point))
23113 (contents-end (org-element-property :contents-end element))
23114 (table (org-element-lineage element '(table) t)))
23115 (if (and table
23116 (>= (point) (org-element-property :contents-begin table))
23117 (< (point) contents-end))
23118 (call-interactively #'org-table-end-of-field)
23119 (save-restriction
23120 (when (and contents-end
23121 (> (point-max) contents-end)
23122 ;; Skip blank lines between elements.
23123 (< (org-element-property :end element)
23124 (save-excursion (goto-char contents-end)
23125 (skip-chars-forward " \r\t\n"))))
23126 (narrow-to-region (org-element-property :contents-begin element)
23127 contents-end))
23128 ;; End of heading is considered as the end of a sentence.
23129 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23130 (call-interactively #'forward-sentence)))))))
23132 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23133 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23135 (defun org-kill-line (&optional _arg)
23136 "Kill line, to tags or end of line."
23137 (interactive)
23138 (cond
23139 ((or (not org-special-ctrl-k)
23140 (bolp)
23141 (not (org-at-heading-p)))
23142 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23143 org-ctrl-k-protect-subtree
23144 (or (eq org-ctrl-k-protect-subtree 'error)
23145 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23146 (user-error "C-k aborted as it would kill a hidden subtree"))
23147 (call-interactively
23148 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23149 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23150 (kill-region (point) (match-beginning 1))
23151 (org-set-tags nil t))
23152 (t (kill-region (point) (point-at-eol)))))
23154 (define-key org-mode-map "\C-k" 'org-kill-line)
23156 (defun org-yank (&optional arg)
23157 "Yank. If the kill is a subtree, treat it specially.
23158 This command will look at the current kill and check if is a single
23159 subtree, or a series of subtrees[1]. If it passes the test, and if the
23160 cursor is at the beginning of a line or after the stars of a currently
23161 empty headline, then the yank is handled specially. How exactly depends
23162 on the value of the following variables.
23164 `org-yank-folded-subtrees'
23165 By default, this variable is non-nil, which results in
23166 subtree(s) being folded after insertion, except if doing so
23167 would swallow text after the yanked text.
23169 `org-yank-adjusted-subtrees'
23170 When non-nil (the default value is nil), the subtree will be
23171 promoted or demoted in order to fit into the local outline tree
23172 structure, which means that the level will be adjusted so that it
23173 becomes the smaller one of the two *visible* surrounding headings.
23175 Any prefix to this command will cause `yank' to be called directly with
23176 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23177 will just
23178 plainly yank the text as it is.
23180 \[1] The test checks if the first non-white line is a heading
23181 and if there are no other headings with fewer stars."
23182 (interactive "P")
23183 (org-yank-generic 'yank arg))
23185 (defun org-yank-generic (command arg)
23186 "Perform some yank-like command.
23188 This function implements the behavior described in the `org-yank'
23189 documentation. However, it has been generalized to work for any
23190 interactive command with similar behavior."
23192 ;; pretend to be command COMMAND
23193 (setq this-command command)
23195 (if arg
23196 (call-interactively command)
23198 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23199 (and (org-kill-is-subtree-p)
23200 (or (bolp)
23201 (and (looking-at "[ \t]*$")
23202 (string-match
23203 "\\`\\*+\\'"
23204 (buffer-substring (point-at-bol) (point)))))))
23205 swallowp)
23206 (cond
23207 ((and subtreep org-yank-folded-subtrees)
23208 (let ((beg (point))
23209 end)
23210 (if (and subtreep org-yank-adjusted-subtrees)
23211 (org-paste-subtree nil nil 'for-yank)
23212 (call-interactively command))
23214 (setq end (point))
23215 (goto-char beg)
23216 (when (and (bolp) subtreep
23217 (not (setq swallowp
23218 (org-yank-folding-would-swallow-text beg end))))
23219 (org-with-limited-levels
23220 (or (looking-at org-outline-regexp)
23221 (re-search-forward org-outline-regexp-bol end t))
23222 (while (and (< (point) end) (looking-at org-outline-regexp))
23223 (outline-hide-subtree)
23224 (org-cycle-show-empty-lines 'folded)
23225 (condition-case nil
23226 (outline-forward-same-level 1)
23227 (error (goto-char end))))))
23228 (when swallowp
23229 (message
23230 "Inserted text not folded because that would swallow text"))
23232 (goto-char end)
23233 (skip-chars-forward " \t\n\r")
23234 (beginning-of-line 1)
23235 (push-mark beg 'nomsg)))
23236 ((and subtreep org-yank-adjusted-subtrees)
23237 (let ((beg (point-at-bol)))
23238 (org-paste-subtree nil nil 'for-yank)
23239 (push-mark beg 'nomsg)))
23241 (call-interactively command))))))
23243 (defun org-yank-folding-would-swallow-text (beg end)
23244 "Would hide-subtree at BEG swallow any text after END?"
23245 (let (level)
23246 (org-with-limited-levels
23247 (save-excursion
23248 (goto-char beg)
23249 (when (or (looking-at org-outline-regexp)
23250 (re-search-forward org-outline-regexp-bol end t))
23251 (setq level (org-outline-level)))
23252 (goto-char end)
23253 (skip-chars-forward " \t\r\n\v\f")
23254 (not (or (eobp)
23255 (and (bolp) (looking-at-p org-outline-regexp)
23256 (<= (org-outline-level) level))))))))
23258 (define-key org-mode-map "\C-y" 'org-yank)
23260 (defun org-back-to-heading (&optional invisible-ok)
23261 "Call `outline-back-to-heading', but provide a better error message."
23262 (condition-case nil
23263 (outline-back-to-heading invisible-ok)
23264 (error (error "Before first headline at position %d in buffer %s"
23265 (point) (current-buffer)))))
23267 (defun org-before-first-heading-p ()
23268 "Before first heading?"
23269 (save-excursion
23270 (end-of-line)
23271 (null (re-search-backward org-outline-regexp-bol nil t))))
23273 (defun org-at-heading-p (&optional ignored)
23274 (outline-on-heading-p t))
23276 (defun org-in-commented-heading-p (&optional no-inheritance)
23277 "Non-nil if point is under a commented heading.
23278 This function also checks ancestors of the current headline,
23279 unless optional argument NO-INHERITANCE is non-nil."
23280 (cond
23281 ((org-before-first-heading-p) nil)
23282 ((let ((headline (nth 4 (org-heading-components))))
23283 (and headline
23284 (let ((case-fold-search nil))
23285 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23286 headline)))))
23287 (no-inheritance nil)
23289 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23291 (defun org-at-comment-p nil
23292 "Is cursor in a commented line?"
23293 (save-excursion
23294 (save-match-data
23295 (beginning-of-line)
23296 (looking-at "^[ \t]*# "))))
23298 (defun org-at-drawer-p nil
23299 "Is cursor at a drawer keyword?"
23300 (save-excursion
23301 (move-beginning-of-line 1)
23302 (looking-at org-drawer-regexp)))
23304 (defun org-at-block-p nil
23305 "Is cursor at a block keyword?"
23306 (save-excursion
23307 (move-beginning-of-line 1)
23308 (looking-at org-block-regexp)))
23310 (defun org-point-at-end-of-empty-headline ()
23311 "If point is at the end of an empty headline, return t, else nil.
23312 If the heading only contains a TODO keyword, it is still still considered
23313 empty."
23314 (let ((case-fold-search nil))
23315 (and (looking-at "[ \t]*$")
23316 org-todo-line-regexp
23317 (save-excursion
23318 (beginning-of-line)
23319 (looking-at org-todo-line-regexp)
23320 (string= (match-string 3) "")))))
23322 (defun org-at-heading-or-item-p ()
23323 (or (org-at-heading-p) (org-at-item-p)))
23325 (defun org-at-target-p ()
23326 (or (org-in-regexp org-radio-target-regexp)
23327 (org-in-regexp org-target-regexp)))
23328 ;; Compatibility alias with Org versions < 7.8.03
23329 (defalias 'org-on-target-p 'org-at-target-p)
23331 (defun org-up-heading-all (arg)
23332 "Move to the heading line of which the present line is a subheading.
23333 This function considers both visible and invisible heading lines.
23334 With argument, move up ARG levels."
23335 (outline-up-heading arg t))
23337 (defun org-up-heading-safe ()
23338 "Move to the heading line of which the present line is a subheading.
23339 This version will not throw an error. It will return the level of the
23340 headline found, or nil if no higher level is found.
23342 Also, this function will be a lot faster than `outline-up-heading',
23343 because it relies on stars being the outline starters. This can really
23344 make a significant difference in outlines with very many siblings."
23345 (when (ignore-errors (org-back-to-heading t))
23346 (let ((level-up (1- (funcall outline-level))))
23347 (and (> level-up 0)
23348 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23349 (funcall outline-level)))))
23351 (defun org-first-sibling-p ()
23352 "Is this heading the first child of its parents?"
23353 (interactive)
23354 (let ((re org-outline-regexp-bol)
23355 level l)
23356 (unless (org-at-heading-p t)
23357 (user-error "Not at a heading"))
23358 (setq level (funcall outline-level))
23359 (save-excursion
23360 (if (not (re-search-backward re nil t))
23362 (setq l (funcall outline-level))
23363 (< l level)))))
23365 (defun org-goto-sibling (&optional previous)
23366 "Goto the next sibling, even if it is invisible.
23367 When PREVIOUS is set, go to the previous sibling instead. Returns t
23368 when a sibling was found. When none is found, return nil and don't
23369 move point."
23370 (let ((fun (if previous 're-search-backward 're-search-forward))
23371 (pos (point))
23372 (re org-outline-regexp-bol)
23373 level l)
23374 (when (ignore-errors (org-back-to-heading t))
23375 (setq level (funcall outline-level))
23376 (catch 'exit
23377 (or previous (forward-char 1))
23378 (while (funcall fun re nil t)
23379 (setq l (funcall outline-level))
23380 (when (< l level) (goto-char pos) (throw 'exit nil))
23381 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23382 (goto-char pos)
23383 nil))))
23385 (defun org-show-siblings ()
23386 "Show all siblings of the current headline."
23387 (save-excursion
23388 (while (org-goto-sibling) (org-flag-heading nil)))
23389 (save-excursion
23390 (while (org-goto-sibling 'previous)
23391 (org-flag-heading nil))))
23393 (defun org-goto-first-child ()
23394 "Goto the first child, even if it is invisible.
23395 Return t when a child was found. Otherwise don't move point and
23396 return nil."
23397 (let (level (pos (point)) (re org-outline-regexp-bol))
23398 (when (ignore-errors (org-back-to-heading t))
23399 (setq level (outline-level))
23400 (forward-char 1)
23401 (if (and (re-search-forward re nil t) (> (outline-level) level))
23402 (progn (goto-char (match-beginning 0)) t)
23403 (goto-char pos) nil))))
23405 (defun org-show-hidden-entry ()
23406 "Show an entry where even the heading is hidden."
23407 (save-excursion
23408 (org-show-entry)))
23410 (defun org-flag-heading (flag &optional entry)
23411 "Flag the current heading. FLAG non-nil means make invisible.
23412 When ENTRY is non-nil, show the entire entry."
23413 (save-excursion
23414 (org-back-to-heading t)
23415 ;; Check if we should show the entire entry
23416 (if entry
23417 (progn
23418 (org-show-entry)
23419 (save-excursion
23420 (and (outline-next-heading)
23421 (org-flag-heading nil))))
23422 (outline-flag-region (max (point-min) (1- (point)))
23423 (save-excursion (outline-end-of-heading) (point))
23424 flag))))
23426 (defun org-get-next-sibling ()
23427 "Move to next heading of the same level, and return point.
23428 If there is no such heading, return nil.
23429 This is like outline-next-sibling, but invisible headings are ok."
23430 (let ((level (funcall outline-level)))
23431 (outline-next-heading)
23432 (while (and (not (eobp)) (> (funcall outline-level) level))
23433 (outline-next-heading))
23434 (unless (or (eobp) (< (funcall outline-level) level))
23435 (point))))
23437 (defun org-get-last-sibling ()
23438 "Move to previous heading of the same level, and return point.
23439 If there is no such heading, return nil."
23440 (let ((opoint (point))
23441 (level (funcall outline-level)))
23442 (outline-previous-heading)
23443 (when (and (/= (point) opoint) (outline-on-heading-p t))
23444 (while (and (> (funcall outline-level) level)
23445 (not (bobp)))
23446 (outline-previous-heading))
23447 (unless (< (funcall outline-level) level)
23448 (point)))))
23450 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23451 "Goto to the end of a subtree."
23452 ;; This contains an exact copy of the original function, but it uses
23453 ;; `org-back-to-heading', to make it work also in invisible
23454 ;; trees. And is uses an invisible-ok argument.
23455 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23456 ;; Furthermore, when used inside Org, finding the end of a large subtree
23457 ;; with many children and grandchildren etc, this can be much faster
23458 ;; than the outline version.
23459 (org-back-to-heading invisible-ok)
23460 (let ((first t)
23461 (level (funcall outline-level)))
23462 (if (and (derived-mode-p 'org-mode) (< level 1000))
23463 ;; A true heading (not a plain list item), in Org
23464 ;; This means we can easily find the end by looking
23465 ;; only for the right number of stars. Using a regexp to do
23466 ;; this is so much faster than using a Lisp loop.
23467 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23468 (forward-char 1)
23469 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23470 ;; something else, do it the slow way
23471 (while (and (not (eobp))
23472 (or first (> (funcall outline-level) level)))
23473 (setq first nil)
23474 (outline-next-heading)))
23475 (unless to-heading
23476 (when (memq (preceding-char) '(?\n ?\^M))
23477 ;; Go to end of line before heading
23478 (forward-char -1)
23479 (when (memq (preceding-char) '(?\n ?\^M))
23480 ;; leave blank line before heading
23481 (forward-char -1)))))
23482 (point))
23484 (defun org-end-of-meta-data (&optional full)
23485 "Skip planning line and properties drawer in current entry.
23486 When optional argument FULL is non-nil, also skip empty lines,
23487 clocking lines and regular drawers at the beginning of the
23488 entry."
23489 (org-back-to-heading t)
23490 (forward-line)
23491 (when (looking-at-p org-planning-line-re) (forward-line))
23492 (when (looking-at org-property-drawer-re)
23493 (goto-char (match-end 0))
23494 (forward-line))
23495 (when (and full (not (org-at-heading-p)))
23496 (catch 'exit
23497 (let ((end (save-excursion (outline-next-heading) (point)))
23498 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23499 (while (not (eobp))
23500 (cond ((looking-at-p org-drawer-regexp)
23501 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23502 (forward-line)
23503 (throw 'exit t)))
23504 ((looking-at-p re) (forward-line))
23505 (t (throw 'exit t))))))))
23507 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23508 "Move forward to the ARG'th subheading at same level as this one.
23509 Stop at the first and last subheadings of a superior heading.
23510 Normally this only looks at visible headings, but when INVISIBLE-OK is
23511 non-nil it will also look at invisible ones."
23512 (interactive "p")
23513 (let ((backward? (and arg (< arg 0))))
23514 (if (org-before-first-heading-p)
23515 (if backward? (goto-char (point-min)) (outline-next-heading))
23516 (org-back-to-heading invisible-ok)
23517 (unless backward? (end-of-line)) ;do not match current headline
23518 (let ((level (- (match-end 0) (match-beginning 0) 1))
23519 (f (if backward? #'re-search-backward #'re-search-forward))
23520 (count (if arg (abs arg) 1))
23521 (result (point)))
23522 (while (and (> count 0)
23523 (funcall f org-outline-regexp-bol nil 'move))
23524 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23525 (cond ((< l level) (setq count 0))
23526 ((and (= l level)
23527 (or invisible-ok
23528 (not (org-invisible-p
23529 (line-beginning-position)))))
23530 (cl-decf count)
23531 (when (= l level) (setq result (point)))))))
23532 (goto-char result))
23533 (beginning-of-line))))
23535 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23536 "Move backward to the ARG'th subheading at same level as this one.
23537 Stop at the first and last subheadings of a superior heading."
23538 (interactive "p")
23539 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23541 (defun org-next-visible-heading (arg)
23542 "Move to the next visible heading.
23544 This function wraps `outline-next-visible-heading' with
23545 `org-with-limited-levels' in order to skip over inline tasks and
23546 respect customization of `org-odd-levels-only'."
23547 (interactive "p")
23548 (org-with-limited-levels
23549 (outline-next-visible-heading arg)))
23551 (defun org-previous-visible-heading (arg)
23552 "Move to the previous visible heading.
23554 This function wraps `outline-previous-visible-heading' with
23555 `org-with-limited-levels' in order to skip over inline tasks and
23556 respect customization of `org-odd-levels-only'."
23557 (interactive "p")
23558 (org-with-limited-levels
23559 (outline-previous-visible-heading arg)))
23561 (defun org-next-block (arg &optional backward block-regexp)
23562 "Jump to the next block.
23564 With a prefix argument ARG, jump forward ARG many blocks.
23566 When BACKWARD is non-nil, jump to the previous block.
23568 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23569 Match data is set according to this regexp when the function
23570 returns.
23572 Return point at beginning of the opening line of found block.
23573 Throw an error if no block is found."
23574 (interactive "p")
23575 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23576 (case-fold-search t)
23577 (search-fn (if backward #'re-search-backward #'re-search-forward))
23578 (count (or arg 1))
23579 (origin (point))
23580 last-element)
23581 (if backward (beginning-of-line) (end-of-line))
23582 (while (and (> count 0) (funcall search-fn re nil t))
23583 (let ((element (save-excursion
23584 (goto-char (match-beginning 0))
23585 (save-match-data (org-element-at-point)))))
23586 (when (and (memq (org-element-type element)
23587 '(center-block comment-block dynamic-block
23588 example-block export-block quote-block
23589 special-block src-block verse-block))
23590 (<= (match-beginning 0)
23591 (org-element-property :post-affiliated element)))
23592 (setq last-element element)
23593 (cl-decf count))))
23594 (if (= count 0)
23595 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23596 (save-match-data (org-show-context)))
23597 (goto-char origin)
23598 (user-error "No %s code blocks" (if backward "previous" "further")))))
23600 (defun org-previous-block (arg &optional block-regexp)
23601 "Jump to the previous block.
23602 With a prefix argument ARG, jump backward ARG many source blocks.
23603 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23604 (interactive "p")
23605 (org-next-block arg t block-regexp))
23607 (defun org-forward-paragraph ()
23608 "Move forward to beginning of next paragraph or equivalent.
23610 The function moves point to the beginning of the next visible
23611 structural element, which can be a paragraph, a table, a list
23612 item, etc. It also provides some special moves for convenience:
23614 - On an affiliated keyword, jump to the beginning of the
23615 relative element.
23616 - On an item or a footnote definition, move to the second
23617 element inside, if any.
23618 - On a table or a property drawer, jump after it.
23619 - On a verse or source block, stop after blank lines."
23620 (interactive)
23621 (unless (eobp)
23622 (let* ((deactivate-mark nil)
23623 (element (org-element-at-point))
23624 (type (org-element-type element))
23625 (post-affiliated (org-element-property :post-affiliated element))
23626 (contents-begin (org-element-property :contents-begin element))
23627 (contents-end (org-element-property :contents-end element))
23628 (end (let ((end (org-element-property :end element)) (parent element))
23629 (while (and (setq parent (org-element-property :parent parent))
23630 (= (org-element-property :contents-end parent) end))
23631 (setq end (org-element-property :end parent)))
23632 end)))
23633 (cond ((not element)
23634 (skip-chars-forward " \r\t\n")
23635 (or (eobp) (beginning-of-line)))
23636 ;; On affiliated keywords, move to element's beginning.
23637 ((< (point) post-affiliated)
23638 (goto-char post-affiliated))
23639 ;; At a table row, move to the end of the table. Similarly,
23640 ;; at a node property, move to the end of the property
23641 ;; drawer.
23642 ((memq type '(node-property table-row))
23643 (goto-char (org-element-property
23644 :end (org-element-property :parent element))))
23645 ((memq type '(property-drawer table)) (goto-char end))
23646 ;; Consider blank lines as separators in verse and source
23647 ;; blocks to ease editing.
23648 ((memq type '(src-block verse-block))
23649 (when (eq type 'src-block)
23650 (setq contents-end
23651 (save-excursion (goto-char end)
23652 (skip-chars-backward " \r\t\n")
23653 (line-beginning-position))))
23654 (beginning-of-line)
23655 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23656 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23657 (goto-char end)
23658 (skip-chars-forward " \r\t\n")
23659 (if (= (point) contents-end) (goto-char end)
23660 (beginning-of-line))))
23661 ;; With no contents, just skip element.
23662 ((not contents-begin) (goto-char end))
23663 ;; If contents are invisible, skip the element altogether.
23664 ((org-invisible-p (line-end-position))
23665 (cl-case type
23666 (headline
23667 (org-with-limited-levels (outline-next-visible-heading 1)))
23668 ;; At a plain list, make sure we move to the next item
23669 ;; instead of skipping the whole list.
23670 (plain-list (forward-char)
23671 (org-forward-paragraph))
23672 (otherwise (goto-char end))))
23673 ((>= (point) contents-end) (goto-char end))
23674 ((>= (point) contents-begin)
23675 ;; This can only happen on paragraphs and plain lists.
23676 (cl-case type
23677 (paragraph (goto-char end))
23678 ;; At a plain list, try to move to second element in
23679 ;; first item, if possible.
23680 (plain-list (end-of-line)
23681 (org-forward-paragraph))))
23682 ;; When contents start on the middle of a line (e.g. in
23683 ;; items and footnote definitions), try to reach first
23684 ;; element starting after current line.
23685 ((> (line-end-position) contents-begin)
23686 (end-of-line)
23687 (org-forward-paragraph))
23688 (t (goto-char contents-begin))))))
23690 (defun org-backward-paragraph ()
23691 "Move backward to start of previous paragraph or equivalent.
23693 The function moves point to the beginning of the current
23694 structural element, which can be a paragraph, a table, a list
23695 item, etc., or to the beginning of the previous visible one if
23696 point is already there. It also provides some special moves for
23697 convenience:
23699 - On an affiliated keyword, jump to the first one.
23700 - On a table or a property drawer, move to its beginning.
23701 - On comment, example, export, src and verse blocks, stop
23702 before blank lines."
23703 (interactive)
23704 (unless (bobp)
23705 (let* ((deactivate-mark nil)
23706 (element (org-element-at-point))
23707 (type (org-element-type element))
23708 (contents-end (org-element-property :contents-end element))
23709 (post-affiliated (org-element-property :post-affiliated element))
23710 (begin (org-element-property :begin element))
23711 (special? ;blocks handled specially
23712 (memq type '(comment-block example-block export-block src-block
23713 verse-block)))
23714 (contents-begin
23715 (if special?
23716 ;; These types have no proper contents. Fake line
23717 ;; below the block opening line as contents beginning.
23718 (save-excursion (goto-char begin) (line-beginning-position 2))
23719 (org-element-property :contents-begin element))))
23720 (cond
23721 ((not element) (goto-char (point-min)))
23722 ((= (point) begin)
23723 (backward-char)
23724 (org-backward-paragraph))
23725 ((<= (point) post-affiliated) (goto-char begin))
23726 ;; Special behavior: on a table or a property drawer, move to
23727 ;; its beginning.
23728 ((memq type '(node-property table-row))
23729 (goto-char (org-element-property
23730 :post-affiliated (org-element-property :parent element))))
23731 (special?
23732 (if (<= (point) contents-begin) (goto-char post-affiliated)
23733 ;; Inside a verse block, see blank lines as paragraph
23734 ;; separators.
23735 (let ((origin (point)))
23736 (skip-chars-backward " \r\t\n" contents-begin)
23737 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23738 (skip-chars-forward " \r\t\n" origin)
23739 (if (= (point) origin) (goto-char contents-begin)
23740 (beginning-of-line))))))
23741 ((eq type 'paragraph) (goto-char contents-begin)
23742 ;; When at first paragraph in an item or a footnote definition,
23743 ;; move directly to beginning of line.
23744 (let ((parent-contents
23745 (org-element-property
23746 :contents-begin (org-element-property :parent element))))
23747 (when (and parent-contents (= parent-contents contents-begin))
23748 (beginning-of-line))))
23749 ;; At the end of a greater element, move to the beginning of
23750 ;; the last element within.
23751 ((and contents-end (>= (point) contents-end))
23752 (goto-char (1- contents-end))
23753 (org-backward-paragraph))
23754 (t (goto-char (or post-affiliated begin))))
23755 ;; Ensure we never leave point invisible.
23756 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23758 (defun org-forward-element ()
23759 "Move forward by one element.
23760 Move to the next element at the same level, when possible."
23761 (interactive)
23762 (cond ((eobp) (user-error "Cannot move further down"))
23763 ((org-with-limited-levels (org-at-heading-p))
23764 (let ((origin (point)))
23765 (goto-char (org-end-of-subtree nil t))
23766 (unless (org-with-limited-levels (org-at-heading-p))
23767 (goto-char origin)
23768 (user-error "Cannot move further down"))))
23770 (let* ((elem (org-element-at-point))
23771 (end (org-element-property :end elem))
23772 (parent (org-element-property :parent elem)))
23773 (cond ((and parent (= (org-element-property :contents-end parent) end))
23774 (goto-char (org-element-property :end parent)))
23775 ((integer-or-marker-p end) (goto-char end))
23776 (t (message "No element at point")))))))
23778 (defun org-backward-element ()
23779 "Move backward by one element.
23780 Move to the previous element at the same level, when possible."
23781 (interactive)
23782 (cond ((bobp) (user-error "Cannot move further up"))
23783 ((org-with-limited-levels (org-at-heading-p))
23784 ;; At a headline, move to the previous one, if any, or stay
23785 ;; here.
23786 (let ((origin (point)))
23787 (org-with-limited-levels (org-backward-heading-same-level 1))
23788 ;; When current headline has no sibling above, move to its
23789 ;; parent.
23790 (when (= (point) origin)
23791 (or (org-with-limited-levels (org-up-heading-safe))
23792 (progn (goto-char origin)
23793 (user-error "Cannot move further up"))))))
23795 (let* ((elem (org-element-at-point))
23796 (beg (org-element-property :begin elem)))
23797 (cond
23798 ;; Move to beginning of current element if point isn't
23799 ;; there already.
23800 ((null beg) (message "No element at point"))
23801 ((/= (point) beg) (goto-char beg))
23802 (t (goto-char beg)
23803 (skip-chars-backward " \r\t\n")
23804 (unless (bobp)
23805 (let ((prev (org-element-at-point)))
23806 (goto-char (org-element-property :begin prev))
23807 (while (and (setq prev (org-element-property :parent prev))
23808 (<= (org-element-property :end prev) beg))
23809 (goto-char (org-element-property :begin prev)))))))))))
23811 (defun org-up-element ()
23812 "Move to upper element."
23813 (interactive)
23814 (if (org-with-limited-levels (org-at-heading-p))
23815 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23816 (let* ((elem (org-element-at-point))
23817 (parent (org-element-property :parent elem)))
23818 (if parent (goto-char (org-element-property :begin parent))
23819 (if (org-with-limited-levels (org-before-first-heading-p))
23820 (user-error "No surrounding element")
23821 (org-with-limited-levels (org-back-to-heading)))))))
23823 (defun org-down-element ()
23824 "Move to inner element."
23825 (interactive)
23826 (let ((element (org-element-at-point)))
23827 (cond
23828 ((memq (org-element-type element) '(plain-list table))
23829 (goto-char (org-element-property :contents-begin element))
23830 (forward-char))
23831 ((memq (org-element-type element) org-element-greater-elements)
23832 ;; If contents are hidden, first disclose them.
23833 (when (org-invisible-p (line-end-position)) (org-cycle))
23834 (goto-char (or (org-element-property :contents-begin element)
23835 (user-error "No content for this element"))))
23836 (t (user-error "No inner element")))))
23838 (defun org-drag-element-backward ()
23839 "Move backward element at point."
23840 (interactive)
23841 (let ((elem (or (org-element-at-point)
23842 (user-error "No element at point"))))
23843 (if (eq (org-element-type elem) 'headline)
23844 ;; Preserve point when moving a whole tree, even if point was
23845 ;; on blank lines below the headline.
23846 (let ((offset (skip-chars-backward " \t\n")))
23847 (unwind-protect (org-move-subtree-up)
23848 (forward-char (- offset))))
23849 (let ((prev-elem
23850 (save-excursion
23851 (goto-char (org-element-property :begin elem))
23852 (skip-chars-backward " \r\t\n")
23853 (unless (bobp)
23854 (let* ((beg (org-element-property :begin elem))
23855 (prev (org-element-at-point))
23856 (up prev))
23857 (while (and (setq up (org-element-property :parent up))
23858 (<= (org-element-property :end up) beg))
23859 (setq prev up))
23860 prev)))))
23861 ;; Error out if no previous element or previous element is
23862 ;; a parent of the current one.
23863 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23864 (user-error "Cannot drag element backward")
23865 (let ((pos (point)))
23866 (org-element-swap-A-B prev-elem elem)
23867 (goto-char (+ (org-element-property :begin prev-elem)
23868 (- pos (org-element-property :begin elem))))))))))
23870 (defun org-drag-element-forward ()
23871 "Move forward element at point."
23872 (interactive)
23873 (let* ((pos (point))
23874 (elem (or (org-element-at-point)
23875 (user-error "No element at point"))))
23876 (when (= (point-max) (org-element-property :end elem))
23877 (user-error "Cannot drag element forward"))
23878 (goto-char (org-element-property :end elem))
23879 (let ((next-elem (org-element-at-point)))
23880 (when (or (org-element-nested-p elem next-elem)
23881 (and (eq (org-element-type next-elem) 'headline)
23882 (not (eq (org-element-type elem) 'headline))))
23883 (goto-char pos)
23884 (user-error "Cannot drag element forward"))
23885 ;; Compute new position of point: it's shifted by NEXT-ELEM
23886 ;; body's length (without final blanks) and by the length of
23887 ;; blanks between ELEM and NEXT-ELEM.
23888 (let ((size-next (- (save-excursion
23889 (goto-char (org-element-property :end next-elem))
23890 (skip-chars-backward " \r\t\n")
23891 (forward-line)
23892 ;; Small correction if buffer doesn't end
23893 ;; with a newline character.
23894 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23895 (org-element-property :begin next-elem)))
23896 (size-blank (- (org-element-property :end elem)
23897 (save-excursion
23898 (goto-char (org-element-property :end elem))
23899 (skip-chars-backward " \r\t\n")
23900 (forward-line)
23901 (point)))))
23902 (org-element-swap-A-B elem next-elem)
23903 (goto-char (+ pos size-next size-blank))))))
23905 (defun org-drag-line-forward (arg)
23906 "Drag the line at point ARG lines forward."
23907 (interactive "p")
23908 (dotimes (_ (abs arg))
23909 (let ((c (current-column)))
23910 (if (< 0 arg)
23911 (progn
23912 (beginning-of-line 2)
23913 (transpose-lines 1)
23914 (beginning-of-line 0))
23915 (transpose-lines 1)
23916 (beginning-of-line -1))
23917 (org-move-to-column c))))
23919 (defun org-drag-line-backward (arg)
23920 "Drag the line at point ARG lines backward."
23921 (interactive "p")
23922 (org-drag-line-forward (- arg)))
23924 (defun org-mark-element ()
23925 "Put point at beginning of this element, mark at end.
23927 Interactively, if this command is repeated or (in Transient Mark
23928 mode) if the mark is active, it marks the next element after the
23929 ones already marked."
23930 (interactive)
23931 (let (deactivate-mark)
23932 (if (and (called-interactively-p 'any)
23933 (or (and (eq last-command this-command) (mark t))
23934 (and transient-mark-mode mark-active)))
23935 (set-mark
23936 (save-excursion
23937 (goto-char (mark))
23938 (goto-char (org-element-property :end (org-element-at-point)))))
23939 (let ((element (org-element-at-point)))
23940 (end-of-line)
23941 (push-mark (org-element-property :end element) t t)
23942 (goto-char (org-element-property :begin element))))))
23944 (defun org-narrow-to-element ()
23945 "Narrow buffer to current element."
23946 (interactive)
23947 (let ((elem (org-element-at-point)))
23948 (cond
23949 ((eq (car elem) 'headline)
23950 (narrow-to-region
23951 (org-element-property :begin elem)
23952 (org-element-property :end elem)))
23953 ((memq (car elem) org-element-greater-elements)
23954 (narrow-to-region
23955 (org-element-property :contents-begin elem)
23956 (org-element-property :contents-end elem)))
23958 (narrow-to-region
23959 (org-element-property :begin elem)
23960 (org-element-property :end elem))))))
23962 (defun org-transpose-element ()
23963 "Transpose current and previous elements, keeping blank lines between.
23964 Point is moved after both elements."
23965 (interactive)
23966 (org-skip-whitespace)
23967 (let ((end (org-element-property :end (org-element-at-point))))
23968 (org-drag-element-backward)
23969 (goto-char end)))
23971 (defun org-unindent-buffer ()
23972 "Un-indent the visible part of the buffer.
23973 Relative indentation (between items, inside blocks, etc.) isn't
23974 modified."
23975 (interactive)
23976 (unless (eq major-mode 'org-mode)
23977 (user-error "Cannot un-indent a buffer not in Org mode"))
23978 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23979 (unindent-tree
23980 (lambda (contents)
23981 (dolist (element (reverse contents))
23982 (if (memq (org-element-type element) '(headline section))
23983 (funcall unindent-tree (org-element-contents element))
23984 (save-excursion
23985 (save-restriction
23986 (narrow-to-region
23987 (org-element-property :begin element)
23988 (org-element-property :end element))
23989 (org-do-remove-indentation))))))))
23990 (funcall unindent-tree (org-element-contents parse-tree))))
23992 (defun org-show-children (&optional level)
23993 "Show all direct subheadings of this heading.
23994 Prefix arg LEVEL is how many levels below the current level
23995 should be shown. Default is enough to cause the following
23996 heading to appear."
23997 (interactive "p")
23998 ;; If `orgstruct-mode' is active, use the slower version.
23999 (if orgstruct-mode (call-interactively #'outline-show-children)
24000 (save-excursion
24001 (org-back-to-heading t)
24002 (let* ((current-level (funcall outline-level))
24003 (max-level (org-get-valid-level
24004 current-level
24005 (if level (prefix-numeric-value level) 1)))
24006 (end (save-excursion (org-end-of-subtree t t)))
24007 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24008 (past-first-child nil)
24009 ;; Make sure to skip inlinetasks.
24010 (re (format regexp-fmt
24011 current-level
24012 (cond
24013 ((not (featurep 'org-inlinetask)) "")
24014 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24016 (t (1- org-inlinetask-min-level))))))
24017 ;; Display parent heading.
24018 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24019 (forward-line)
24020 ;; Display children. First child may be deeper than expected
24021 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24022 ;; MAX-LEVEL accordingly.
24023 (while (re-search-forward re end t)
24024 (unless past-first-child
24025 (setq re (format regexp-fmt
24026 current-level
24027 (max (funcall outline-level) max-level)))
24028 (setq past-first-child t))
24029 (outline-flag-region
24030 (line-end-position 0) (line-end-position) nil))))))
24032 (defun org-show-subtree ()
24033 "Show everything after this heading at deeper levels."
24034 (interactive)
24035 (outline-flag-region
24036 (point)
24037 (save-excursion
24038 (org-end-of-subtree t t))
24039 nil))
24041 (defun org-show-entry ()
24042 "Show the body directly following this heading.
24043 Show the heading too, if it is currently invisible."
24044 (interactive)
24045 (save-excursion
24046 (ignore-errors
24047 (org-back-to-heading t)
24048 (outline-flag-region
24049 (max (point-min) (1- (point)))
24050 (save-excursion
24051 (if (re-search-forward
24052 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24053 (match-beginning 1)
24054 (point-max)))
24055 nil)
24056 (org-cycle-hide-drawers 'children))))
24058 (defun org-make-options-regexp (kwds &optional extra)
24059 "Make a regular expression for keyword lines.
24060 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24061 when non-nil, is a regexp matching keywords names."
24062 (concat "^[ \t]*#\\+\\("
24063 (regexp-opt kwds)
24064 (and extra (concat (and kwds "\\|") extra))
24065 "\\):[ \t]*\\(.*\\)"))
24067 ;;;; Finish up
24069 (provide 'org)
24071 (run-hooks 'org-load-hook)
24073 ;;; org.el ends here